file_name
stringlengths 71
779k
| comments
stringlengths 0
29.4k
| code_string
stringlengths 20
7.69M
| __index_level_0__
int64 2
17.2M
|
---|---|---|---|
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import "./ShackledStructs.sol";
import "./ShackledRenderer.sol";
import "@openzeppelin/contracts/access/Ownable.sol";
import "@openzeppelin/contracts/token/ERC721/extensions/ERC721Enumerable.sol";
contract ShackledIcons is ERC721Enumerable, Ownable {
string public currentBaseURI;
mapping(uint256 => bytes32) public tokenHashes;
constructor() ERC721("ShackledIcons", "ICON") {}
/**
* @dev Mint token ids to a particular address
*/
function mint(address to, uint256 tokenId) public onlyOwner {
require(
tokenHashes[tokenId] != 0x0,
"Cannot mint a token that doesn't exist"
);
_safeMint(to, tokenId);
}
function storeTokenHash(uint256 tokenId, bytes32 tokenHash)
public
onlyOwner
{
tokenHashes[tokenId] = tokenHash;
}
function getRenderParamsHash(
ShackledStructs.RenderParams calldata renderParams
) public pure returns (bytes32) {
return
keccak256(
abi.encodePacked(
abi.encodePacked(
renderParams.faces,
renderParams.verts,
renderParams.cols
),
abi.encodePacked(
renderParams.objPosition,
renderParams.objScale,
renderParams.backgroundColor,
renderParams.perspCamera,
renderParams.backfaceCulling,
renderParams.invert,
renderParams.wireframe
),
_getLightingParamsHash(renderParams.lightingParams)
)
);
}
function _getLightingParamsHash(
ShackledStructs.LightingParams calldata lightingParams
) internal pure returns (bytes32) {
return
keccak256(
abi.encodePacked(
lightingParams.applyLighting,
lightingParams.lightAmbiPower,
lightingParams.lightDiffPower,
lightingParams.lightSpecPower,
lightingParams.inverseShininess,
lightingParams.lightPos,
lightingParams.lightColSpec,
lightingParams.lightColDiff,
lightingParams.lightColAmbi
)
);
}
function render(
uint256 tokenId,
int256 canvasDim_,
ShackledStructs.RenderParams calldata renderParams
) public view returns (string memory) {
bytes32 tokenHash = getRenderParamsHash(renderParams);
require(tokenHash == tokenHashes[tokenId], "Token hash mismatch");
return ShackledRenderer.render(renderParams, canvasDim_, true);
}
function setBaseURI(string memory baseURI_) public onlyOwner {
currentBaseURI = baseURI_;
}
function _baseURI() internal view virtual override returns (string memory) {
return currentBaseURI;
}
}
// SPDX-License-Identifier: Unlicense
pragma solidity ^0.8.0;
library ShackledStructs {
struct Metadata {
string colorScheme; /// name of the color scheme
string geomSpec; /// name of the geometry specification
uint256 nPrisms; /// number of prisms made
string pseudoSymmetry; /// horizontal, vertical, diagonal
string wireframe; /// enabled or disabled
string inversion; /// enabled or disabled
}
struct RenderParams {
uint256[3][] faces; /// index of verts and colorss used for each face (triangle)
int256[3][] verts; /// x, y, z coordinates used in the geometry
int256[3][] cols; /// colors of each vert
int256[3] objPosition; /// position to place the object
int256 objScale; /// scalar for the object
int256[3][2] backgroundColor; /// color of the background (gradient)
LightingParams lightingParams; /// parameters for the lighting
bool perspCamera; /// true = perspective camera, false = orthographic
bool backfaceCulling; /// whether to implement backface culling (saves gas!)
bool invert; /// whether to invert colors in the final encoding stage
bool wireframe; /// whether to only render edges
}
/// struct for testing lighting
struct LightingParams {
bool applyLighting; /// true = apply lighting, false = don't apply lighting
int256 lightAmbiPower; /// power of the ambient light
int256 lightDiffPower; /// power of the diffuse light
int256 lightSpecPower; /// power of the specular light
uint256 inverseShininess; /// shininess of the material
int256[3] lightPos; /// position of the light
int256[3] lightColSpec; /// color of the specular light
int256[3] lightColDiff; /// color of the diffuse light
int256[3] lightColAmbi; /// color of the ambient light
}
}
// // SPDX-License-Identifier: GPL-3.0
pragma solidity ^0.8.0;
import "./ShackledCoords.sol";
import "./ShackledRasteriser.sol";
import "./ShackledUtils.sol";
import "./ShackledStructs.sol";
library ShackledRenderer {
uint256 constant outputHeight = 512;
uint256 constant outputWidth = 512;
/** @dev take any geometry, render it, and return a bitmap image inside an SVG
this can be called to render the Shackled art collection (the output of ShackledGenesis.sol)
or any other custom made geometry
*/
function render(
ShackledStructs.RenderParams memory renderParams,
int256 canvasDim,
bool returnSVG
) public view returns (string memory) {
/// prepare the fragments
int256[12][3][] memory trisFragments = prepareGeometryForRender(
renderParams,
canvasDim
);
/// run Bresenham's line algorithm to rasterize the fragments
int256[12][] memory fragments = ShackledRasteriser.rasterise(
trisFragments,
canvasDim,
renderParams.wireframe
);
fragments = ShackledRasteriser.depthTesting(fragments, canvasDim);
if (renderParams.lightingParams.applyLighting) {
/// apply lighting (Blinn phong)
fragments = ShackledRasteriser.lightScene(
fragments,
renderParams.lightingParams
);
}
/// get the background
int256[5][] memory background = ShackledRasteriser.getBackground(
canvasDim,
renderParams.backgroundColor
);
/// place each fragment in an encoded bitmap
string memory encodedBitmap = ShackledUtils.getEncodedBitmap(
fragments,
background,
canvasDim,
renderParams.invert
);
if (returnSVG) {
/// insert the bitmap into an encoded svg (to be accepted by OpenSea)
return
ShackledUtils.getSVGContainer(
encodedBitmap,
canvasDim,
outputHeight,
outputWidth
);
} else {
return encodedBitmap;
}
}
/** @dev prepare the triangles and colors for rasterization
*/
function prepareGeometryForRender(
ShackledStructs.RenderParams memory renderParams,
int256 canvasDim
) internal view returns (int256[12][3][] memory) {
/// convert geometry and colors from PLY standard into Shackled format
/// create the final triangles and colors that will be rendered
/// by pulling the numbers out of the faces array
/// and using them to index into the verts and colors arrays
/// make copies of each coordinate and color
int256[3][3][] memory tris = new int256[3][3][](
renderParams.faces.length
);
int256[3][3][] memory trisCols = new int256[3][3][](
renderParams.faces.length
);
for (uint256 i = 0; i < renderParams.faces.length; i++) {
for (uint256 j = 0; j < 3; j++) {
for (uint256 k = 0; k < 3; k++) {
/// copy the values from verts and cols arrays
/// using the faces lookup array to index into them
tris[i][j][k] = renderParams.verts[
renderParams.faces[i][j]
][k];
trisCols[i][j][k] = renderParams.cols[
renderParams.faces[i][j]
][k];
}
}
}
/// convert the fragments from model to world space
int256[3][] memory vertsWorldSpace = ShackledCoords
.convertToWorldSpaceWithModelTransform(
tris,
renderParams.objScale,
renderParams.objPosition
);
/// convert the vertices back to triangles in world space
int256[3][3][] memory trisWorldSpace = ShackledUtils
.unflattenVertsToTris(vertsWorldSpace);
/// implement backface culling
if (renderParams.backfaceCulling) {
(trisWorldSpace, trisCols) = ShackledCoords.backfaceCulling(
trisWorldSpace,
trisCols
);
}
/// update vertsWorldSpace
vertsWorldSpace = ShackledUtils.flattenTris(trisWorldSpace);
/// convert the fragments from world to camera space
int256[3][] memory vertsCameraSpace = ShackledCoords
.convertToCameraSpaceViaVertexShader(
vertsWorldSpace,
canvasDim,
renderParams.perspCamera
);
/// convert the vertices back to triangles in camera space
int256[3][3][] memory trisCameraSpace = ShackledUtils
.unflattenVertsToTris(vertsCameraSpace);
int256[12][3][] memory trisFragments = ShackledRasteriser
.initialiseFragments(
trisCameraSpace,
trisWorldSpace,
trisCols,
canvasDim
);
return trisFragments;
}
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (access/Ownable.sol)
pragma solidity ^0.8.0;
import "../utils/Context.sol";
/**
* @dev Contract module which provides a basic access control mechanism, where
* there is an account (an owner) that can be granted exclusive access to
* specific functions.
*
* By default, the owner account will be the one that deploys the contract. This
* can later be changed with {transferOwnership}.
*
* This module is used through inheritance. It will make available the modifier
* `onlyOwner`, which can be applied to your functions to restrict their use to
* the owner.
*/
abstract contract Ownable is Context {
address private _owner;
event OwnershipTransferred(address indexed previousOwner, address indexed newOwner);
/**
* @dev Initializes the contract setting the deployer as the initial owner.
*/
constructor() {
_transferOwnership(_msgSender());
}
/**
* @dev Returns the address of the current owner.
*/
function owner() public view virtual returns (address) {
return _owner;
}
/**
* @dev Throws if called by any account other than the owner.
*/
modifier onlyOwner() {
require(owner() == _msgSender(), "Ownable: caller is not the owner");
_;
}
/**
* @dev Leaves the contract without owner. It will not be possible to call
* `onlyOwner` functions anymore. Can only be called by the current owner.
*
* NOTE: Renouncing ownership will leave the contract without an owner,
* thereby removing any functionality that is only available to the owner.
*/
function renounceOwnership() public virtual onlyOwner {
_transferOwnership(address(0));
}
/**
* @dev Transfers ownership of the contract to a new account (`newOwner`).
* Can only be called by the current owner.
*/
function transferOwnership(address newOwner) public virtual onlyOwner {
require(newOwner != address(0), "Ownable: new owner is the zero address");
_transferOwnership(newOwner);
}
/**
* @dev Transfers ownership of the contract to a new account (`newOwner`).
* Internal function without access restriction.
*/
function _transferOwnership(address newOwner) internal virtual {
address oldOwner = _owner;
_owner = newOwner;
emit OwnershipTransferred(oldOwner, newOwner);
}
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (token/ERC721/extensions/ERC721Enumerable.sol)
pragma solidity ^0.8.0;
import "../ERC721.sol";
import "./IERC721Enumerable.sol";
/**
* @dev This implements an optional extension of {ERC721} defined in the EIP that adds
* enumerability of all the token ids in the contract as well as all token ids owned by each
* account.
*/
abstract contract ERC721Enumerable is ERC721, IERC721Enumerable {
// Mapping from owner to list of owned token IDs
mapping(address => mapping(uint256 => uint256)) private _ownedTokens;
// Mapping from token ID to index of the owner tokens list
mapping(uint256 => uint256) private _ownedTokensIndex;
// Array with all token ids, used for enumeration
uint256[] private _allTokens;
// Mapping from token id to position in the allTokens array
mapping(uint256 => uint256) private _allTokensIndex;
/**
* @dev See {IERC165-supportsInterface}.
*/
function supportsInterface(bytes4 interfaceId) public view virtual override(IERC165, ERC721) returns (bool) {
return interfaceId == type(IERC721Enumerable).interfaceId || super.supportsInterface(interfaceId);
}
/**
* @dev See {IERC721Enumerable-tokenOfOwnerByIndex}.
*/
function tokenOfOwnerByIndex(address owner, uint256 index) public view virtual override returns (uint256) {
require(index < ERC721.balanceOf(owner), "ERC721Enumerable: owner index out of bounds");
return _ownedTokens[owner][index];
}
/**
* @dev See {IERC721Enumerable-totalSupply}.
*/
function totalSupply() public view virtual override returns (uint256) {
return _allTokens.length;
}
/**
* @dev See {IERC721Enumerable-tokenByIndex}.
*/
function tokenByIndex(uint256 index) public view virtual override returns (uint256) {
require(index < ERC721Enumerable.totalSupply(), "ERC721Enumerable: global index out of bounds");
return _allTokens[index];
}
/**
* @dev Hook that is called before any token transfer. This includes minting
* and burning.
*
* Calling conditions:
*
* - When `from` and `to` are both non-zero, ``from``'s `tokenId` will be
* transferred to `to`.
* - When `from` is zero, `tokenId` will be minted for `to`.
* - When `to` is zero, ``from``'s `tokenId` will be burned.
* - `from` cannot be the zero address.
* - `to` cannot be the zero address.
*
* To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks].
*/
function _beforeTokenTransfer(
address from,
address to,
uint256 tokenId
) internal virtual override {
super._beforeTokenTransfer(from, to, tokenId);
if (from == address(0)) {
_addTokenToAllTokensEnumeration(tokenId);
} else if (from != to) {
_removeTokenFromOwnerEnumeration(from, tokenId);
}
if (to == address(0)) {
_removeTokenFromAllTokensEnumeration(tokenId);
} else if (to != from) {
_addTokenToOwnerEnumeration(to, tokenId);
}
}
/**
* @dev Private function to add a token to this extension's ownership-tracking data structures.
* @param to address representing the new owner of the given token ID
* @param tokenId uint256 ID of the token to be added to the tokens list of the given address
*/
function _addTokenToOwnerEnumeration(address to, uint256 tokenId) private {
uint256 length = ERC721.balanceOf(to);
_ownedTokens[to][length] = tokenId;
_ownedTokensIndex[tokenId] = length;
}
/**
* @dev Private function to add a token to this extension's token tracking data structures.
* @param tokenId uint256 ID of the token to be added to the tokens list
*/
function _addTokenToAllTokensEnumeration(uint256 tokenId) private {
_allTokensIndex[tokenId] = _allTokens.length;
_allTokens.push(tokenId);
}
/**
* @dev Private function to remove a token from this extension's ownership-tracking data structures. Note that
* while the token is not assigned a new owner, the `_ownedTokensIndex` mapping is _not_ updated: this allows for
* gas optimizations e.g. when performing a transfer operation (avoiding double writes).
* This has O(1) time complexity, but alters the order of the _ownedTokens array.
* @param from address representing the previous owner of the given token ID
* @param tokenId uint256 ID of the token to be removed from the tokens list of the given address
*/
function _removeTokenFromOwnerEnumeration(address from, uint256 tokenId) private {
// To prevent a gap in from's tokens array, we store the last token in the index of the token to delete, and
// then delete the last slot (swap and pop).
uint256 lastTokenIndex = ERC721.balanceOf(from) - 1;
uint256 tokenIndex = _ownedTokensIndex[tokenId];
// When the token to delete is the last token, the swap operation is unnecessary
if (tokenIndex != lastTokenIndex) {
uint256 lastTokenId = _ownedTokens[from][lastTokenIndex];
_ownedTokens[from][tokenIndex] = lastTokenId; // Move the last token to the slot of the to-delete token
_ownedTokensIndex[lastTokenId] = tokenIndex; // Update the moved token's index
}
// This also deletes the contents at the last position of the array
delete _ownedTokensIndex[tokenId];
delete _ownedTokens[from][lastTokenIndex];
}
/**
* @dev Private function to remove a token from this extension's token tracking data structures.
* This has O(1) time complexity, but alters the order of the _allTokens array.
* @param tokenId uint256 ID of the token to be removed from the tokens list
*/
function _removeTokenFromAllTokensEnumeration(uint256 tokenId) private {
// To prevent a gap in the tokens array, we store the last token in the index of the token to delete, and
// then delete the last slot (swap and pop).
uint256 lastTokenIndex = _allTokens.length - 1;
uint256 tokenIndex = _allTokensIndex[tokenId];
// When the token to delete is the last token, the swap operation is unnecessary. However, since this occurs so
// rarely (when the last minted token is burnt) that we still do the swap here to avoid the gas cost of adding
// an 'if' statement (like in _removeTokenFromOwnerEnumeration)
uint256 lastTokenId = _allTokens[lastTokenIndex];
_allTokens[tokenIndex] = lastTokenId; // Move the last token to the slot of the to-delete token
_allTokensIndex[lastTokenId] = tokenIndex; // Update the moved token's index
// This also deletes the contents at the last position of the array
delete _allTokensIndex[tokenId];
_allTokens.pop();
}
}
// SPDX-License-Identifier: GPL-3.0
pragma solidity ^0.8.0;
import "./ShackledUtils.sol";
import "./ShackledMath.sol";
library ShackledCoords {
/** @dev scale and translate the verts
this can be effectively disabled with a scale of 1 and translate of [0, 0, 0]
*/
function convertToWorldSpaceWithModelTransform(
int256[3][3][] memory tris,
int256 scale,
int256[3] memory position
) external view returns (int256[3][] memory) {
int256[3][] memory verts = ShackledUtils.flattenTris(tris);
// Scale model matrices are easy, just multiply through by the scale value
int256[3][] memory scaledVerts = new int256[3][](verts.length);
for (uint256 i = 0; i < verts.length; i++) {
scaledVerts[i][0] = verts[i][0] * scale + position[0];
scaledVerts[i][1] = verts[i][1] * scale + position[1];
scaledVerts[i][2] = verts[i][2] * scale + position[2];
}
return scaledVerts;
}
/** @dev run backfaceCulling to save future operations on faces that aren't seen by the camera*/
function backfaceCulling(
int256[3][3][] memory trisWorldSpace,
int256[3][3][] memory trisCols
)
external
view
returns (
int256[3][3][] memory culledTrisWorldSpace,
int256[3][3][] memory culledTrisCols
)
{
culledTrisWorldSpace = new int256[3][3][](trisWorldSpace.length);
culledTrisCols = new int256[3][3][](trisCols.length);
uint256 nextIx;
for (uint256 i = 0; i < trisWorldSpace.length; i++) {
int256[3] memory v1 = trisWorldSpace[i][0];
int256[3] memory v2 = trisWorldSpace[i][1];
int256[3] memory v3 = trisWorldSpace[i][2];
int256[3] memory norm = ShackledMath.crossProduct(
ShackledMath.vector3Sub(v1, v2),
ShackledMath.vector3Sub(v2, v3)
);
/// since shackled has a static positioned camera at the origin,
/// the points are already in view space, relaxing the backfaceCullingCond
int256 backfaceCullingCond = ShackledMath.vector3Dot(v1, norm);
if (backfaceCullingCond < 0) {
culledTrisWorldSpace[nextIx] = trisWorldSpace[i];
culledTrisCols[nextIx] = trisCols[i];
nextIx++;
}
}
/// remove any empty slots
uint256 nToCull = culledTrisWorldSpace.length - nextIx;
/// cull uneeded tris
assembly {
mstore(
culledTrisWorldSpace,
sub(mload(culledTrisWorldSpace), nToCull)
)
}
/// cull uneeded cols
assembly {
mstore(culledTrisCols, sub(mload(culledTrisCols), nToCull))
}
}
/**@dev calculate verts in camera space */
function convertToCameraSpaceViaVertexShader(
int256[3][] memory vertsWorldSpace,
int256 canvasDim,
bool perspCamera
) external view returns (int256[3][] memory) {
// get the camera matrix as a numerator and denominator
int256[4][4][2] memory cameraMatrix;
if (perspCamera) {
cameraMatrix = getCameraMatrixPersp();
} else {
cameraMatrix = getCameraMatrixOrth(canvasDim);
}
int256[4][4] memory nM = cameraMatrix[0]; // camera matrix numerator
int256[4][4] memory dM = cameraMatrix[1]; // camera matrix denominator
int256[3][] memory verticesCameraSpace = new int256[3][](
vertsWorldSpace.length
);
for (uint256 i = 0; i < vertsWorldSpace.length; i++) {
// Convert from 3D to 4D homogenous coordinate system
int256[3] memory vert = vertsWorldSpace[i];
// Make a copy of vert ("homoVertex")
int256[] memory hv = new int256[](vert.length + 1);
for (uint256 j = 0; j < vert.length; j++) {
hv[j] = vert[j];
}
// Insert 1 at final position in copy of vert
hv[hv.length - 1] = 1;
int256 x = ((hv[0] * nM[0][0]) / dM[0][0]) +
((hv[1] * nM[0][1]) / dM[0][1]) +
((hv[2] * nM[0][2]) / dM[0][2]) +
(nM[0][3] / dM[0][3]);
int256 y = ((hv[0] * nM[1][0]) / dM[1][0]) +
((hv[1] * nM[1][1]) / dM[1][1]) +
((hv[2] * nM[1][2]) / dM[1][2]) +
(nM[1][3] / dM[1][0]);
int256 z = ((hv[0] * nM[2][0]) / dM[2][0]) +
((hv[1] * nM[2][1]) / dM[2][1]) +
((hv[2] * nM[2][2]) / dM[2][2]) +
(nM[2][3] / dM[2][3]);
int256 w = ((hv[0] * nM[3][0]) / dM[3][0]) +
((hv[1] * nM[3][1]) / dM[3][1]) +
((hv[2] * nM[3][2]) / dM[3][2]) +
(nM[3][3] / dM[3][3]);
if (w != 1) {
x = (x * 1e3) / w;
y = (y * 1e3) / w;
z = (z * 1e3) / w;
}
// Turn it back into a 3-vector
// Add it to the ordered list
verticesCameraSpace[i] = [x, y, z];
}
return verticesCameraSpace;
}
/** @dev generate an orthographic camera matrix */
function getCameraMatrixOrth(int256 canvasDim)
internal
pure
returns (int256[4][4][2] memory)
{
int256 canvasHalf = canvasDim / 2;
// Left, right, top, bottom
int256 r = ShackledMath.abs(canvasHalf);
int256 l = -canvasHalf;
int256 t = ShackledMath.abs(canvasHalf);
int256 b = -canvasHalf;
// Z settings (near and far)
/// multiplied by 1e3
int256 n = 1;
int256 f = 1024;
// Get the orthographic transform matrix
// as a numerator and denominator
int256[4][4] memory cameraMatrixNum = [
[int256(2), 0, 0, -(r + l)],
[int256(0), 2, 0, -(t + b)],
[int256(0), 0, -2, -(f + n)],
[int256(0), 0, 0, 1]
];
int256[4][4] memory cameraMatrixDen = [
[int256(r - l), 1, 1, (r - l)],
[int256(1), (t - b), 1, (t - b)],
[int256(1), 1, (f - n), (f - n)],
[int256(1), 1, 1, 1]
];
int256[4][4][2] memory cameraMatrix = [
cameraMatrixNum,
cameraMatrixDen
];
return cameraMatrix;
}
/** @dev generate a perspective camera matrix */
function getCameraMatrixPersp()
internal
pure
returns (int256[4][4][2] memory)
{
// Z settings (near and far)
/// multiplied by 1e3
int256 n = 500;
int256 f = 501;
// Get the perspective transform matrix
// as a numerator and denominator
// parameter = 1 / tan(fov in degrees / 2)
// 0.1763 = 1 / tan(160 / 2)
// 1.428 = 1 / tan(70 / 2)
// 1.732 = 1 / tan(60 / 2)
// 2.145 = 1 / tan(50 / 2)
int256[4][4] memory cameraMatrixNum = [
[int256(2145), 0, 0, 0],
[int256(0), 2145, 0, 0],
[int256(0), 0, f, -f * n],
[int256(0), 0, 1, 0]
];
int256[4][4] memory cameraMatrixDen = [
[int256(1000), 1, 1, 1],
[int256(1), 1000, 1, 1],
[int256(1), 1, f - n, f - n],
[int256(1), 1, 1, 1]
];
int256[4][4][2] memory cameraMatrix = [
cameraMatrixNum,
cameraMatrixDen
];
return cameraMatrix;
}
}
// SPDX-License-Identifier: GPL-3.0
pragma solidity ^0.8.0;
import "./ShackledUtils.sol";
import "./ShackledMath.sol";
import "./ShackledStructs.sol";
library ShackledRasteriser {
/// define some constant lighting parameters
int256 constant fidelity = int256(100); /// an extra paramater to improve numeric resolution
int256 constant lightAmbiPower = int256(1); // Base light colour // was 0.5
int256 constant lightDiffPower = int256(3e9); // Diffused light on surface relative strength
int256 constant lightSpecPower = int256(1e7); // Specular reflection on surface relative strength
uint256 constant inverseShininess = 10; // 'sharpness' of specular light on surface
/// define a scale factor to use in lerp to avoid rounding errors
int256 constant lerpScaleFactor = 1e3;
/// storing variables used in the fragment lighting
struct LightingVars {
int256[3] fragCol;
int256[3] fragNorm;
int256[3] fragPos;
int256[3] V;
int256 vMag;
int256[3] N;
int256 nMag;
int256[3] L;
int256 lMag;
int256 falloff;
int256 lnDot;
int256 lambertian;
}
/// store variables used in Bresenham's line algorithm
struct BresenhamsVars {
int256 x;
int256 y;
int256 dx;
int256 dy;
int256 sx;
int256 sy;
int256 err;
int256 e2;
}
/// store variables used when running the scanline algorithm
struct ScanlineVars {
int256 left;
int256 right;
int256[12] leftFrag;
int256[12] rightFrag;
int256 dx;
int256 ir;
int256 newFragRow;
int256 newFragCol;
}
/** @dev initialise the fragments
fragments are defined as:
[
canvas_x, canvas_y, depth,
col_x, col_y, col_z,
normal_x, normal_y, normal_z,
world_x, world_y, world_z
]
*/
function initialiseFragments(
int256[3][3][] memory trisCameraSpace,
int256[3][3][] memory trisWorldSpace,
int256[3][3][] memory trisCols,
int256 canvasDim
) external view returns (int256[12][3][] memory) {
/// make an array containing the fragments of each triangle (groups of 3 frags)
int256[12][3][] memory trisFragments = new int256[12][3][](
trisCameraSpace.length
);
// First convert from camera space to screen space within each triangle
for (uint256 t = 0; t < trisCameraSpace.length; t++) {
int256[3][3] memory tri = trisCameraSpace[t];
/// initialise an array for three fragments, each of len 9
int256[12][3] memory triFragments;
// First calculate the fragments that belong to defined vertices
for (uint256 v = 0; v < 3; v++) {
int256[12] memory fragment;
// first convert to screen space
// mapping from -1e3 -> 1e3 to account for the original geom being on order of 1e3
fragment[0] = ShackledMath.mapRangeToRange(
tri[v][0],
-1e3,
1e3,
0,
canvasDim
);
fragment[1] = ShackledMath.mapRangeToRange(
tri[v][1],
-1e3,
1e3,
0,
canvasDim
);
fragment[2] = tri[v][2];
// Now calculate the normal using the cross product of the edge vectors. This needs to be
// done in world space coordinates
int256[3] memory thisV = trisWorldSpace[t][(v + 0) % 3];
int256[3] memory nextV = trisWorldSpace[t][(v + 1) % 3];
int256[3] memory prevV = trisWorldSpace[t][(v + 2) % 3];
int256[3] memory norm = ShackledMath.crossProduct(
ShackledMath.vector3Sub(prevV, thisV),
ShackledMath.vector3Sub(thisV, nextV)
);
// Now attach the colour (in 0 -> 255 space)
fragment[3] = (trisCols[t][v][0]);
fragment[4] = (trisCols[t][v][1]);
fragment[5] = (trisCols[t][v][2]);
// And the normal (inverted)
fragment[6] = -norm[0];
fragment[7] = -norm[1];
fragment[8] = -norm[2];
// And the world position of this vertex to the frag
fragment[9] = thisV[0];
fragment[10] = thisV[1];
fragment[11] = thisV[2];
// These are just the fragments attached to
// the given vertices
triFragments[v] = fragment;
}
trisFragments[t] = triFragments;
}
return trisFragments;
}
/** @dev rasterize fragments onto a canvas
*/
function rasterise(
int256[12][3][] memory trisFragments,
int256 canvasDim,
bool wireframe
) external view returns (int256[12][] memory) {
/// determine the upper limits of the inner Bresenham's result
uint256 canvasHypot = uint256(ShackledMath.hypot(canvasDim, canvasDim));
/// initialise a new array
/// for each trisFragments we will get 3 results from bresenhams
/// maximum of 1 per pixel (canvasDim**2)
int256[12][] memory fragments = new int256[12][](
3 * uint256(canvasDim)**2
);
uint256 nextFragmentsIx = 0;
for (uint256 t = 0; t < trisFragments.length; t++) {
// prepare the variables required
int256[12] memory fa;
int256[12] memory fb;
uint256 nextBresTriFragmentIx = 0;
/// create an array to hold the bresenham results
/// this may cause an out of bounds error if there are a very large number of fragments
/// (e.g. many that are 'off screen')
int256[12][] memory bresTriFragments = new int256[12][](
canvasHypot * 10
);
// for each pair of fragments, run bresenhams and extend bresTriFragments with the output
// this replaces the three push(...modified_bresenhams_algorhtm) statements in JS
for (uint256 i = 0; i < 3; i++) {
if (i == 0) {
fa = trisFragments[t][0];
fb = trisFragments[t][1];
} else if (i == 1) {
fa = trisFragments[t][1];
fb = trisFragments[t][2];
} else {
fa = trisFragments[t][2];
fb = trisFragments[t][0];
}
// run the bresenhams algorithm
(
bresTriFragments,
nextBresTriFragmentIx
) = runBresenhamsAlgorithm(
fa,
fb,
canvasDim,
bresTriFragments,
nextBresTriFragmentIx
);
}
bresTriFragments = ShackledUtils.clipArray12ToLength(
bresTriFragments,
nextBresTriFragmentIx
);
if (wireframe) {
/// only store the edges
for (uint256 j = 0; j < bresTriFragments.length; j++) {
fragments[nextFragmentsIx] = bresTriFragments[j];
nextFragmentsIx++;
}
} else {
/// fill the triangle
(fragments, nextFragmentsIx) = runScanline(
bresTriFragments,
fragments,
nextFragmentsIx,
canvasDim
);
}
}
fragments = ShackledUtils.clipArray12ToLength(
fragments,
nextFragmentsIx
);
return fragments;
}
/** @dev run Bresenham's line algorithm on a pair of fragments
*/
function runBresenhamsAlgorithm(
int256[12] memory f1,
int256[12] memory f2,
int256 canvasDim,
int256[12][] memory bresTriFragments,
uint256 nextBresTriFragmentIx
) internal view returns (int256[12][] memory, uint256) {
/// initiate a new set of vars
BresenhamsVars memory vars;
int256[12] memory fa;
int256[12] memory fb;
/// determine which fragment has a greater magnitude
/// and set it as the destination (always order a given pair of edges the same)
if (
(f1[0]**2 + f1[1]**2 + f1[2]**2) < (f2[0]**2 + f2[1]**2 + f2[2]**2)
) {
fa = f1;
fb = f2;
} else {
fa = f2;
fb = f1;
}
vars.x = fa[0];
vars.y = fa[1];
vars.dx = ShackledMath.abs(fb[0] - fa[0]);
vars.dy = -ShackledMath.abs(fb[1] - fa[1]);
int256 mag = ShackledMath.hypot(vars.dx, -vars.dy);
if (fa[0] < fb[0]) {
vars.sx = 1;
} else {
vars.sx = -1;
}
if (fa[1] < fb[1]) {
vars.sy = 1;
} else {
vars.sy = -1;
}
vars.err = vars.dx + vars.dy;
vars.e2 = 0;
// get the bresenhams output for this fragment pair (fa & fb)
if (mag == 0) {
bresTriFragments[nextBresTriFragmentIx] = fa;
bresTriFragments[nextBresTriFragmentIx + 1] = fb;
nextBresTriFragmentIx += 2;
} else {
// when mag is not 0,
// the length of the result will be max of upperLimitInner
// but will be clipped to remove any empty slots
(bresTriFragments, nextBresTriFragmentIx) = bresenhamsInner(
vars,
mag,
fa,
fb,
canvasDim,
bresTriFragments,
nextBresTriFragmentIx
);
}
return (bresTriFragments, nextBresTriFragmentIx);
}
/** @dev run the inner loop of Bresenham's line algorithm on a pair of fragments
* (preventing stack too deep)
*/
function bresenhamsInner(
BresenhamsVars memory vars,
int256 mag,
int256[12] memory fa,
int256[12] memory fb,
int256 canvasDim,
int256[12][] memory bresTriFragments,
uint256 nextBresTriFragmentIx
) internal view returns (int256[12][] memory, uint256) {
// define variables to be used in the inner loop
int256 ir;
int256 h;
/// loop through all fragments
while (!(vars.x == fb[0] && vars.y == fb[1])) {
/// get hypotenuse length of fragment a
h = ShackledMath.hypot(fa[0] - vars.x, fa[1] - vars.y);
assembly {
ir := div(mul(lerpScaleFactor, h), mag)
}
// only add the fragment if it falls within the canvas
/// create a new fragment by linear interpolation between a and b
int256[12] memory newFragment = ShackledMath.vector12Lerp(
fa,
fb,
ir,
lerpScaleFactor
);
newFragment[0] = vars.x;
newFragment[1] = vars.y;
/// save this fragment
bresTriFragments[nextBresTriFragmentIx] = newFragment;
++nextBresTriFragmentIx;
/// update variables to use in next iteration
vars.e2 = 2 * vars.err;
if (vars.e2 >= vars.dy) {
vars.err += vars.dy;
vars.x += vars.sx;
}
if (vars.e2 <= vars.dx) {
vars.err += vars.dx;
vars.y += vars.sy;
}
}
/// save fragment 2
bresTriFragments[nextBresTriFragmentIx] = fb;
++nextBresTriFragmentIx;
return (bresTriFragments, nextBresTriFragmentIx);
}
/** @dev run the scan line algorithm to fill the raster
*/
function runScanline(
int256[12][] memory bresTriFragments,
int256[12][] memory fragments,
uint256 nextFragmentsIx,
int256 canvasDim
) internal view returns (int256[12][] memory, uint256) {
/// make a 2d array with length = num of output rows
(
int256[][] memory rowFragIndices,
uint256[] memory nextIxFragRows
) = getRowFragIndices(bresTriFragments, canvasDim);
/// initialise a struct to hold the scanline vars
ScanlineVars memory slVars;
// Now iterate through the list of fragments that live in a single row
for (uint256 i = 0; i < rowFragIndices.length; i++) {
/// Get the left most fragment
slVars.left = 4096;
/// Get the right most fragment
slVars.right = -4096;
/// loop through the fragments in this row
/// and check that a fragment was written to this row
for (uint256 j = 0; j < nextIxFragRows[i]; j++) {
/// What's the current fragment that we're looking at
int256 fragX = bresTriFragments[uint256(rowFragIndices[i][j])][
0
];
// if it's lefter than our current most left frag then its the new left frag
if (fragX < slVars.left) {
slVars.left = fragX;
slVars.leftFrag = bresTriFragments[
uint256(rowFragIndices[i][j])
];
}
// if it's righter than our current most right frag then its the new right frag
if (fragX > slVars.right) {
slVars.right = fragX;
slVars.rightFrag = bresTriFragments[
uint256(rowFragIndices[i][j])
];
}
}
/// now we need to scan from the left to the right fragment
/// and interpolate as we go
slVars.dx = slVars.right - slVars.left + 1;
/// get the row that we're on
slVars.newFragRow = slVars.leftFrag[1];
/// check that the new frag's row will be in the canvas bounds
if (slVars.newFragRow >= 0 && slVars.newFragRow < canvasDim) {
if (slVars.dx > int256(0)) {
for (int256 j = 0; j < slVars.dx; j++) {
/// calculate the column of the new fragment (its position in the scan)
slVars.newFragCol = slVars.leftFrag[0] + j;
/// check that the new frag's column will be in the canvas bounds
if (
slVars.newFragCol >= 0 &&
slVars.newFragCol < canvasDim
) {
slVars.ir = (j * lerpScaleFactor) / slVars.dx;
/// make a new fragment by linear interpolation between left and right frags
fragments[nextFragmentsIx] = ShackledMath
.vector12Lerp(
slVars.leftFrag,
slVars.rightFrag,
slVars.ir,
lerpScaleFactor
);
/// update its position
fragments[nextFragmentsIx][0] = slVars.newFragCol;
fragments[nextFragmentsIx][1] = slVars.newFragRow;
nextFragmentsIx++;
}
}
}
}
}
return (fragments, nextFragmentsIx);
}
/** @dev get the row indices of each fragment in preparation for the scanline alg
*/
function getRowFragIndices(
int256[12][] memory bresTriFragments,
int256 canvasDim
)
internal
view
returns (int256[][] memory, uint256[] memory nextIxFragRows)
{
uint256 canvasDimUnsigned = uint256(canvasDim);
// define the length of each outer array so we can push items into it using nextIxFragRows
int256[][] memory rowFragIndices = new int256[][](canvasDimUnsigned);
// the inner rows can't be longer than bresTriFragments
for (uint256 i = 0; i < canvasDimUnsigned; i++) {
rowFragIndices[i] = new int256[](bresTriFragments.length);
}
// make an array the tracks for each row how many items have been pushed into it
uint256[] memory nextIxFragRows = new uint256[](canvasDimUnsigned);
for (uint256 f = 0; f < bresTriFragments.length; f++) {
// get the row index
uint256 rowIx = uint256(bresTriFragments[f][1]); // canvas_y
if (rowIx >= 0 && rowIx < canvasDimUnsigned) {
// get the ix of the next item to be added to the row
rowFragIndices[rowIx][nextIxFragRows[rowIx]] = int256(f);
++nextIxFragRows[rowIx];
}
}
return (rowFragIndices, nextIxFragRows);
}
/** @dev run depth-testing on all fragments
*/
function depthTesting(int256[12][] memory fragments, int256 canvasDim)
external
view
returns (int256[12][] memory)
{
uint256 canvasDimUnsigned = uint256(canvasDim);
/// create a 2d array to hold the zValues of the fragments
int256[][] memory zValues = ShackledMath.get2dArray(
canvasDimUnsigned,
canvasDimUnsigned,
0
);
/// create a 2d array to hold the fragIndex of the fragments
/// as their depth is compared
int256[][] memory fragIndex = ShackledMath.get2dArray(
canvasDimUnsigned,
canvasDimUnsigned,
-1 /// -1 so we can check if a fragment was written to this location
);
int256[12][] memory culledFrags = new int256[12][](fragments.length);
uint256 nextFragIx = 0;
/// iterate through all fragments
/// and store the index of the fragment with the largest z value
/// at each x, y coordinate
for (uint256 i = 0; i < fragments.length; i++) {
int256[12] memory frag = fragments[i];
/// x and y must be uint for indexing
uint256 fragX = uint256(frag[0]);
uint256 fragY = uint256(frag[1]);
// console.log("checking frag", i, "z:");
// console.logInt(frag[2]);
if (
(fragX < canvasDimUnsigned) &&
(fragY < canvasDimUnsigned) &&
fragX >= 0 &&
fragY >= 0
) {
// if this is the first fragment seen at (fragX, fragY), ie if fragIndex == 0, add it
// or if this frag is closer (lower z value) than the current frag at (fragX, fragY), add it
if (
fragIndex[fragX][fragY] == -1 ||
frag[2] >= zValues[fragX][fragY]
) {
zValues[fragX][fragY] = frag[2];
fragIndex[fragX][fragY] = int256(i);
}
}
}
/// save only the fragments with prefered z values
for (uint256 x = 0; x < canvasDimUnsigned; x++) {
for (uint256 y = 0; y < canvasDimUnsigned; y++) {
int256 fragIx = fragIndex[x][y];
/// ensure we have a valid index
if (fragIndex[x][y] != -1) {
culledFrags[nextFragIx] = fragments[uint256(fragIx)];
nextFragIx++;
}
}
}
return ShackledUtils.clipArray12ToLength(culledFrags, nextFragIx);
}
/** @dev apply lighting to the scene and update fragments accordingly
*/
function lightScene(
int256[12][] memory fragments,
ShackledStructs.LightingParams memory lp
) external view returns (int256[12][] memory) {
/// create a struct for the variables to prevent stack too deep
LightingVars memory lv;
// calculate a constant lighting vector and its magniture
lv.L = lp.lightPos;
lv.lMag = ShackledMath.vector3Len(lv.L);
for (uint256 f = 0; f < fragments.length; f++) {
/// get the fragment's color, norm and position
lv.fragCol = [fragments[f][3], fragments[f][4], fragments[f][5]];
lv.fragNorm = [fragments[f][6], fragments[f][7], fragments[f][8]];
lv.fragPos = [fragments[f][9], fragments[f][10], fragments[f][11]];
/// calculate the direction to camera / viewer and its magnitude
lv.V = ShackledMath.vector3MulScalar(lv.fragPos, -1);
lv.vMag = ShackledMath.vector3Len(lv.V);
/// calculate the direction of the fragment normaland its magnitude
lv.N = lv.fragNorm;
lv.nMag = ShackledMath.vector3Len(lv.N);
/// calculate the light vector per-fragment
// lv.L = ShackledMath.vector3Sub(lp.lightPos, lv.fragPos);
// lv.lMag = ShackledMath.vector3Len(lv.L);
lv.falloff = lv.lMag**2; /// lighting intensity fall over the scene
lv.lnDot = ShackledMath.vector3Dot(lv.L, lv.N);
/// implement double-side rendering to account for flipped normals
lv.lambertian = ShackledMath.abs(lv.lnDot);
int256 specular;
if (lv.lambertian > 0) {
int256[3] memory normedL = ShackledMath.vector3NormX(
lv.L,
fidelity
);
int256[3] memory normedV = ShackledMath.vector3NormX(
lv.V,
fidelity
);
int256[3] memory H = ShackledMath.vector3Add(normedL, normedV);
int256 hnDot = int256(
ShackledMath.vector3Dot(
ShackledMath.vector3NormX(H, fidelity),
ShackledMath.vector3NormX(lv.N, fidelity)
)
);
specular = calculateSpecular(
lp.lightSpecPower,
hnDot,
fidelity,
lp.inverseShininess
);
}
// Calculate the colour and write it into the fragment
int256[3] memory colAmbi = ShackledMath.vector3Add(
lv.fragCol,
ShackledMath.vector3MulScalar(
lp.lightColAmbi,
lp.lightAmbiPower
)
);
/// finalise and color the diffuse lighting
int256[3] memory colDiff = ShackledMath.vector3MulScalar(
lp.lightColDiff,
((lp.lightDiffPower * lv.lambertian) / (lv.lMag * lv.nMag)) /
lv.falloff
);
/// finalise and color the specular lighting
int256[3] memory colSpec = ShackledMath.vector3DivScalar(
ShackledMath.vector3MulScalar(lp.lightColSpec, specular),
lv.falloff
);
// add up the colour components
int256[3] memory col = ShackledMath.vector3Add(
ShackledMath.vector3Add(colAmbi, colDiff),
colSpec
);
/// update the fragment's colour in place
fragments[f][3] = col[0];
fragments[f][4] = col[1];
fragments[f][5] = col[2];
}
return fragments;
}
/** @dev calculate the specular lighting parameter */
function calculateSpecular(
int256 lightSpecPower,
int256 hnDot,
int256 fidelity,
uint256 inverseShininess
) internal pure returns (int256 specular) {
int256 specAngle = hnDot > int256(0) ? hnDot : int256(0);
assembly {
specular := sdiv(
mul(lightSpecPower, exp(specAngle, inverseShininess)),
exp(fidelity, mul(inverseShininess, 2))
)
}
}
/** @dev get background gradient that fills the canvas */
function getBackground(
int256 canvasDim,
int256[3][2] memory backgroundColor
) external view returns (int256[5][] memory) {
int256[5][] memory background = new int256[5][](uint256(canvasDim**2));
int256 w = canvasDim;
uint256 nextIx = 0;
for (int256 i = 0; i < canvasDim; i++) {
for (int256 j = 0; j < canvasDim; j++) {
// / write coordinates of background pixel
background[nextIx][0] = j; /// x
background[nextIx][1] = i; /// y
// / write colours of background pixel
// / get weighted average of top and bottom color according to row (i)
background[nextIx][2] = /// r
((backgroundColor[0][0] * i) +
(backgroundColor[1][0] * (w - i))) /
w;
background[nextIx][3] = /// g
((backgroundColor[0][1] * i) +
(backgroundColor[1][1] * (w - i))) /
w;
background[nextIx][4] = /// b
((backgroundColor[0][2] * i) +
(backgroundColor[1][2] * (w - i))) /
w;
++nextIx;
}
}
return background;
}
}
// SPDX-License-Identifier: GPL-3.0
pragma solidity ^0.8.0;
import "./ShackledStructs.sol";
library ShackledUtils {
string internal constant TABLE =
"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
/** @dev Flatten 3d tris array into 2d verts */
function flattenTris(int256[3][3][] memory tris)
internal
pure
returns (int256[3][] memory)
{
/// initialize a dynamic in-memory array
int256[3][] memory flattened = new int256[3][](3 * tris.length);
for (uint256 i = 0; i < tris.length; i++) {
/// tris.length == N
// add values to specific index, as cannot push to array in memory
flattened[(i * 3) + 0] = tris[i][0];
flattened[(i * 3) + 1] = tris[i][1];
flattened[(i * 3) + 2] = tris[i][2];
}
return flattened;
}
/** @dev Unflatten 2d verts array into 3d tries (inverse of flattenTris function) */
function unflattenVertsToTris(int256[3][] memory verts)
internal
pure
returns (int256[3][3][] memory)
{
/// initialize an array with length = 1/3 length of verts
int256[3][3][] memory tris = new int256[3][3][](verts.length / 3);
for (uint256 i = 0; i < verts.length; i += 3) {
tris[i / 3] = [verts[i], verts[i + 1], verts[i + 2]];
}
return tris;
}
/** @dev clip an array to a certain length (to trim empty tail slots) */
function clipArray12ToLength(int256[12][] memory arr, uint256 desiredLen)
internal
pure
returns (int256[12][] memory)
{
uint256 nToCull = arr.length - desiredLen;
assembly {
mstore(arr, sub(mload(arr), nToCull))
}
return arr;
}
/** @dev convert an unsigned int to a string */
function uint2str(uint256 _i)
internal
pure
returns (string memory _uintAsString)
{
if (_i == 0) {
return "0";
}
uint256 j = _i;
uint256 len;
while (j != 0) {
len++;
j /= 10;
}
bytes memory bstr = new bytes(len);
uint256 k = len;
while (_i != 0) {
k = k - 1;
uint8 temp = (48 + uint8(_i - (_i / 10) * 10));
bytes1 b1 = bytes1(temp);
bstr[k] = b1;
_i /= 10;
}
return string(bstr);
}
/** @dev get the hex encoding of various powers of 2 (canvas size options) */
function getHex(uint256 _i) internal pure returns (bytes memory _hex) {
if (_i == 8) {
return hex"08_00_00_00";
} else if (_i == 16) {
return hex"10_00_00_00";
} else if (_i == 32) {
return hex"20_00_00_00";
} else if (_i == 64) {
return hex"40_00_00_00";
} else if (_i == 128) {
return hex"80_00_00_00";
} else if (_i == 256) {
return hex"00_01_00_00";
} else if (_i == 512) {
return hex"00_02_00_00";
}
}
/** @dev create an svg container for a bitmap (for display on svg-only platforms) */
function getSVGContainer(
string memory encodedBitmap,
int256 canvasDim,
uint256 outputHeight,
uint256 outputWidth
) internal view returns (string memory) {
uint256 canvasDimUnsigned = uint256(canvasDim);
// construct some elements in memory prior to return string to avoid stack too deep
bytes memory imgSize = abi.encodePacked(
"width='",
ShackledUtils.uint2str(canvasDimUnsigned),
"' height='",
ShackledUtils.uint2str(canvasDimUnsigned),
"'"
);
bytes memory canvasSize = abi.encodePacked(
"width='",
ShackledUtils.uint2str(outputWidth),
"' height='",
ShackledUtils.uint2str(outputHeight),
"'"
);
bytes memory scaleStartTag = abi.encodePacked(
"<g transform='scale(",
ShackledUtils.uint2str(outputWidth / canvasDimUnsigned),
")'>"
);
return
string(
abi.encodePacked(
"data:image/svg+xml;base64,",
Base64.encode(
abi.encodePacked(
"<svg xmlns='http://www.w3.org/2000/svg' xmlns:xlink='http://www.w3.org/1999/xlink' ",
"shape-rendering='crispEdges' ",
canvasSize,
">",
scaleStartTag,
"<image ",
imgSize,
" style='image-rendering: pixelated; image-rendering: crisp-edges;' ",
"href='",
encodedBitmap,
"'/></g></svg>"
)
)
)
);
}
/** @dev converts raw metadata into */
function getAttributes(ShackledStructs.Metadata memory metadata)
internal
pure
returns (bytes memory)
{
return
abi.encodePacked(
"{",
'"Structure": "',
metadata.geomSpec,
'", "Chroma": "',
metadata.colorScheme,
'", "Pseudosymmetry": "',
metadata.pseudoSymmetry,
'", "Wireframe": "',
metadata.wireframe,
'", "Inversion": "',
metadata.inversion,
'", "Prisms": "',
uint2str(metadata.nPrisms),
'"}'
);
}
/** @dev create and encode the token's metadata */
function getEncodedMetadata(
string memory image,
ShackledStructs.Metadata memory metadata,
uint256 tokenId
) internal view returns (string memory) {
/// get attributes and description here to avoid stack too deep
string
memory description = '"description": "Shackled is the first general-purpose 3D renderer'
" running on the Ethereum blockchain."
' Each piece represents a leap forward in on-chain computer graphics, and the collection itself is an NFT first."';
return
string(
abi.encodePacked(
"data:application/json;base64,",
Base64.encode(
bytes(
string(
abi.encodePacked(
'{"name": "Shackled Genesis #',
uint2str(tokenId),
'", ',
description,
', "attributes":',
getAttributes(metadata),
', "image":"',
image,
'"}'
)
)
)
)
)
);
}
// fragment =
// [ canvas_x, canvas_y, depth, col_x, col_y, col_z, normal_x, normal_y, normal_z, world_x, world_y, world_z ],
/** @dev get an encoded 2d bitmap by combining the object and background fragments */
function getEncodedBitmap(
int256[12][] memory fragments,
int256[5][] memory background,
int256 canvasDim,
bool invert
) internal view returns (string memory) {
uint256 canvasDimUnsigned = uint256(canvasDim);
bytes memory fileHeader = abi.encodePacked(
hex"42_4d", // BM
hex"36_04_00_00", // size of the bitmap file in bytes (14 (file header) + 40 (info header) + size of raw data (1024))
hex"00_00_00_00", // 2x2 bytes reserved
hex"36_00_00_00" // offset of pixels in bytes
);
bytes memory infoHeader = abi.encodePacked(
hex"28_00_00_00", // size of the header in bytes (40)
getHex(canvasDimUnsigned), // width in pixels 32
getHex(canvasDimUnsigned), // height in pixels 32
hex"01_00", // number of color plans (must be 1)
hex"18_00", // number of bits per pixel (24)
hex"00_00_00_00", // type of compression (none)
hex"00_04_00_00", // size of the raw bitmap data (1024)
hex"C4_0E_00_00", // horizontal resolution
hex"C4_0E_00_00", // vertical resolution
hex"00_00_00_00", // number of used colours
hex"05_00_00_00" // number of important colours
);
bytes memory headers = abi.encodePacked(fileHeader, infoHeader);
/// create a container for the bitmap's bytes
bytes memory bytesArray = new bytes(3 * canvasDimUnsigned**2);
/// write the background first so it is behind the fragments
bytesArray = writeBackgroundToBytesArray(
background,
bytesArray,
canvasDimUnsigned,
invert
);
bytesArray = writeFragmentsToBytesArray(
fragments,
bytesArray,
canvasDimUnsigned,
invert
);
return
string(
abi.encodePacked(
"data:image/bmp;base64,",
Base64.encode(BytesUtils.MergeBytes(headers, bytesArray))
)
);
}
/** @dev write the fragments to the bytes array */
function writeFragmentsToBytesArray(
int256[12][] memory fragments,
bytes memory bytesArray,
uint256 canvasDimUnsigned,
bool invert
) internal pure returns (bytes memory) {
/// loop through each fragment
/// and write it's color into bytesArray in its canvas equivelant position
for (uint256 i = 0; i < fragments.length; i++) {
/// check if x and y are both greater than 0
if (
uint256(fragments[i][0]) >= 0 && uint256(fragments[i][1]) >= 0
) {
/// calculating the starting bytesArray ix for this fragment's colors
uint256 flatIx = ((canvasDimUnsigned -
uint256(fragments[i][1]) -
1) *
canvasDimUnsigned +
(canvasDimUnsigned - uint256(fragments[i][0]) - 1)) * 3;
/// red
uint256 r = fragments[i][3] > 255
? 255
: uint256(fragments[i][3]);
/// green
uint256 g = fragments[i][4] > 255
? 255
: uint256(fragments[i][4]);
/// blue
uint256 b = fragments[i][5] > 255
? 255
: uint256(fragments[i][5]);
if (invert) {
r = 255 - r;
g = 255 - g;
b = 255 - b;
}
bytesArray[flatIx + 0] = bytes1(uint8(b));
bytesArray[flatIx + 1] = bytes1(uint8(g));
bytesArray[flatIx + 2] = bytes1(uint8(r));
}
}
return bytesArray;
}
/** @dev write the fragments to the bytes array
using a separate function from above to account for variable input size
*/
function writeBackgroundToBytesArray(
int256[5][] memory background,
bytes memory bytesArray,
uint256 canvasDimUnsigned,
bool invert
) internal pure returns (bytes memory) {
/// loop through each fragment
/// and write it's color into bytesArray in its canvas equivelant position
for (uint256 i = 0; i < background.length; i++) {
/// check if x and y are both greater than 0
if (
uint256(background[i][0]) >= 0 && uint256(background[i][1]) >= 0
) {
/// calculating the starting bytesArray ix for this fragment's colors
uint256 flatIx = (uint256(background[i][1]) *
canvasDimUnsigned +
uint256(background[i][0])) * 3;
// red
uint256 r = background[i][2] > 255
? 255
: uint256(background[i][2]);
/// green
uint256 g = background[i][3] > 255
? 255
: uint256(background[i][3]);
// blue
uint256 b = background[i][4] > 255
? 255
: uint256(background[i][4]);
if (invert) {
r = 255 - r;
g = 255 - g;
b = 255 - b;
}
bytesArray[flatIx + 0] = bytes1(uint8(b));
bytesArray[flatIx + 1] = bytes1(uint8(g));
bytesArray[flatIx + 2] = bytes1(uint8(r));
}
}
return bytesArray;
}
}
/// [MIT License]
/// @title Base64
/// @notice Provides a function for encoding some bytes in base64
/// @author Brecht Devos <[email protected]>
library Base64 {
bytes internal constant TABLE =
"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
/// @notice Encodes some bytes to the base64 representation
function encode(bytes memory data) internal view returns (string memory) {
uint256 len = data.length;
if (len == 0) return "";
// multiply by 4/3 rounded up
uint256 encodedLen = 4 * ((len + 2) / 3);
// Add some extra buffer at the end
bytes memory result = new bytes(encodedLen + 32);
bytes memory table = TABLE;
assembly {
let tablePtr := add(table, 1)
let resultPtr := add(result, 32)
for {
let i := 0
} lt(i, len) {
} {
i := add(i, 3)
let input := and(mload(add(data, i)), 0xffffff)
let out := mload(add(tablePtr, and(shr(18, input), 0x3F)))
out := shl(8, out)
out := add(
out,
and(mload(add(tablePtr, and(shr(12, input), 0x3F))), 0xFF)
)
out := shl(8, out)
out := add(
out,
and(mload(add(tablePtr, and(shr(6, input), 0x3F))), 0xFF)
)
out := shl(8, out)
out := add(
out,
and(mload(add(tablePtr, and(input, 0x3F))), 0xFF)
)
out := shl(224, out)
mstore(resultPtr, out)
resultPtr := add(resultPtr, 4)
}
switch mod(len, 3)
case 1 {
mstore(sub(resultPtr, 2), shl(240, 0x3d3d))
}
case 2 {
mstore(sub(resultPtr, 1), shl(248, 0x3d))
}
mstore(result, encodedLen)
}
return string(result);
}
}
library BytesUtils {
function char(bytes1 b) internal view returns (bytes1 c) {
if (uint8(b) < 10) return bytes1(uint8(b) + 0x30);
else return bytes1(uint8(b) + 0x57);
}
function bytes32string(bytes32 b32)
internal
view
returns (string memory out)
{
bytes memory s = new bytes(64);
for (uint32 i = 0; i < 32; i++) {
bytes1 b = bytes1(b32[i]);
bytes1 hi = bytes1(uint8(b) / 16);
bytes1 lo = bytes1(uint8(b) - 16 * uint8(hi));
s[i * 2] = char(hi);
s[i * 2 + 1] = char(lo);
}
out = string(s);
}
function hach(string memory value) internal view returns (string memory) {
return bytes32string(sha256(abi.encodePacked(value)));
}
function MergeBytes(bytes memory a, bytes memory b)
internal
pure
returns (bytes memory c)
{
// Store the length of the first array
uint256 alen = a.length;
// Store the length of BOTH arrays
uint256 totallen = alen + b.length;
// Count the loops required for array a (sets of 32 bytes)
uint256 loopsa = (a.length + 31) / 32;
// Count the loops required for array b (sets of 32 bytes)
uint256 loopsb = (b.length + 31) / 32;
assembly {
let m := mload(0x40)
// Load the length of both arrays to the head of the new bytes array
mstore(m, totallen)
// Add the contents of a to the array
for {
let i := 0
} lt(i, loopsa) {
i := add(1, i)
} {
mstore(
add(m, mul(32, add(1, i))),
mload(add(a, mul(32, add(1, i))))
)
}
// Add the contents of b to the array
for {
let i := 0
} lt(i, loopsb) {
i := add(1, i)
} {
mstore(
add(m, add(mul(32, add(1, i)), alen)),
mload(add(b, mul(32, add(1, i))))
)
}
mstore(0x40, add(m, add(32, totallen)))
c := m
}
}
}
// SPDX-License-Identifier: GPL-3.0
pragma solidity ^0.8.0;
library ShackledMath {
/** @dev Get the minimum of two numbers */
function min(int256 a, int256 b) internal pure returns (int256) {
return a < b ? a : b;
}
/** @dev Get the maximum of two numbers */
function max(int256 a, int256 b) internal pure returns (int256) {
return a > b ? a : b;
}
/** @dev perform a modulo operation, with support for negative numbers */
function mod(int256 n, int256 m) internal pure returns (int256) {
if (n < 0) {
return ((n % m) + m) % m;
} else {
return n % m;
}
}
/** @dev 'randomly' select n numbers between 0 and m
(useful for getting a randomly sampled index)
*/
function randomIdx(
bytes32 seedModifier,
uint256 n, // number of elements to select
uint256 m // max value of elements
) internal pure returns (uint256[] memory) {
uint256[] memory result = new uint256[](n);
for (uint256 i = 0; i < n; i++) {
result[i] =
uint256(keccak256(abi.encodePacked(seedModifier, i))) %
m;
}
return result;
}
/** @dev create a 2d array and fill with a single value */
function get2dArray(
uint256 m,
uint256 q,
int256 value
) internal pure returns (int256[][] memory) {
/// Create a matrix of values with dimensions (m, q)
int256[][] memory rows = new int256[][](m);
for (uint256 i = 0; i < m; i++) {
int256[] memory row = new int256[](q);
for (uint256 j = 0; j < q; j++) {
row[j] = value;
}
rows[i] = row;
}
return rows;
}
/** @dev get the absolute of a number
*/
function abs(int256 x) internal pure returns (int256) {
assembly {
if slt(x, 0) {
x := sub(0, x)
}
}
return x;
}
/** @dev get the square root of a number
*/
function sqrt(int256 y) internal pure returns (int256 z) {
assembly {
if sgt(y, 3) {
z := y
let x := add(div(y, 2), 1)
for {
} slt(x, z) {
} {
z := x
x := div(add(div(y, x), x), 2)
}
}
if and(slt(y, 4), sgt(y, 0)) {
z := 1
}
}
}
/** @dev get the hypotenuse of a triangle given the length of 2 sides
*/
function hypot(int256 x, int256 y) internal pure returns (int256) {
int256 sumsq;
assembly {
let xsq := mul(x, x)
let ysq := mul(y, y)
sumsq := add(xsq, ysq)
}
return sqrt(sumsq);
}
/** @dev addition between two vectors (size 3)
*/
function vector3Add(int256[3] memory v1, int256[3] memory v2)
internal
pure
returns (int256[3] memory result)
{
assembly {
mstore(result, add(mload(v1), mload(v2)))
mstore(
add(result, 0x20),
add(mload(add(v1, 0x20)), mload(add(v2, 0x20)))
)
mstore(
add(result, 0x40),
add(mload(add(v1, 0x40)), mload(add(v2, 0x40)))
)
}
}
/** @dev subtraction between two vectors (size 3)
*/
function vector3Sub(int256[3] memory v1, int256[3] memory v2)
internal
pure
returns (int256[3] memory result)
{
assembly {
mstore(result, sub(mload(v1), mload(v2)))
mstore(
add(result, 0x20),
sub(mload(add(v1, 0x20)), mload(add(v2, 0x20)))
)
mstore(
add(result, 0x40),
sub(mload(add(v1, 0x40)), mload(add(v2, 0x40)))
)
}
}
/** @dev multiply a vector (size 3) by a constant
*/
function vector3MulScalar(int256[3] memory v, int256 a)
internal
pure
returns (int256[3] memory result)
{
assembly {
mstore(result, mul(mload(v), a))
mstore(add(result, 0x20), mul(mload(add(v, 0x20)), a))
mstore(add(result, 0x40), mul(mload(add(v, 0x40)), a))
}
}
/** @dev divide a vector (size 3) by a constant
*/
function vector3DivScalar(int256[3] memory v, int256 a)
internal
pure
returns (int256[3] memory result)
{
assembly {
mstore(result, sdiv(mload(v), a))
mstore(add(result, 0x20), sdiv(mload(add(v, 0x20)), a))
mstore(add(result, 0x40), sdiv(mload(add(v, 0x40)), a))
}
}
/** @dev get the length of a vector (size 3)
*/
function vector3Len(int256[3] memory v) internal pure returns (int256) {
int256 res;
assembly {
let x := mload(v)
let y := mload(add(v, 0x20))
let z := mload(add(v, 0x40))
res := add(add(mul(x, x), mul(y, y)), mul(z, z))
}
return sqrt(res);
}
/** @dev scale and then normalise a vector (size 3)
*/
function vector3NormX(int256[3] memory v, int256 fidelity)
internal
pure
returns (int256[3] memory result)
{
int256 l = vector3Len(v);
assembly {
mstore(result, sdiv(mul(fidelity, mload(add(v, 0x40))), l))
mstore(
add(result, 0x20),
sdiv(mul(fidelity, mload(add(v, 0x20))), l)
)
mstore(add(result, 0x40), sdiv(mul(fidelity, mload(v)), l))
}
}
/** @dev get the dot-product of two vectors (size 3)
*/
function vector3Dot(int256[3] memory v1, int256[3] memory v2)
internal
view
returns (int256 result)
{
assembly {
result := add(
add(
mul(mload(v1), mload(v2)),
mul(mload(add(v1, 0x20)), mload(add(v2, 0x20)))
),
mul(mload(add(v1, 0x40)), mload(add(v2, 0x40)))
)
}
}
/** @dev get the cross product of two vectors (size 3)
*/
function crossProduct(int256[3] memory v1, int256[3] memory v2)
internal
pure
returns (int256[3] memory result)
{
assembly {
mstore(
result,
sub(
mul(mload(add(v1, 0x20)), mload(add(v2, 0x40))),
mul(mload(add(v1, 0x40)), mload(add(v2, 0x20)))
)
)
mstore(
add(result, 0x20),
sub(
mul(mload(add(v1, 0x40)), mload(v2)),
mul(mload(v1), mload(add(v2, 0x40)))
)
)
mstore(
add(result, 0x40),
sub(
mul(mload(v1), mload(add(v2, 0x20))),
mul(mload(add(v1, 0x20)), mload(v2))
)
)
}
}
/** @dev linearly interpolate between two vectors (size 12)
*/
function vector12Lerp(
int256[12] memory v1,
int256[12] memory v2,
int256 ir,
int256 scaleFactor
) internal view returns (int256[12] memory result) {
int256[12] memory vd = vector12Sub(v2, v1);
// loop through all 12 items
assembly {
let ix
for {
let i := 0
} lt(i, 0xC) {
// (i < 12)
i := add(i, 1)
} {
/// get index of the next element
ix := mul(i, 0x20)
/// store into the result array
mstore(
add(result, ix),
add(
// v1[i] + (ir * vd[i]) / 1e3
mload(add(v1, ix)),
sdiv(mul(ir, mload(add(vd, ix))), 1000)
)
)
}
}
}
/** @dev subtraction between two vectors (size 12)
*/
function vector12Sub(int256[12] memory v1, int256[12] memory v2)
internal
view
returns (int256[12] memory result)
{
// loop through all 12 items
assembly {
let ix
for {
let i := 0
} lt(i, 0xC) {
// (i < 12)
i := add(i, 1)
} {
/// get index of the next element
ix := mul(i, 0x20)
/// store into the result array
mstore(
add(result, ix),
sub(
// v1[ix] - v2[ix]
mload(add(v1, ix)),
mload(add(v2, ix))
)
)
}
}
}
/** @dev map a number from one range into another
*/
function mapRangeToRange(
int256 num,
int256 inMin,
int256 inMax,
int256 outMin,
int256 outMax
) internal pure returns (int256 res) {
assembly {
res := add(
sdiv(
mul(sub(outMax, outMin), sub(num, inMin)),
sub(inMax, inMin)
),
outMin
)
}
}
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (utils/Context.sol)
pragma solidity ^0.8.0;
/**
* @dev Provides information about the current execution context, including the
* sender of the transaction and its data. While these are generally available
* via msg.sender and msg.data, they should not be accessed in such a direct
* manner, since when dealing with meta-transactions the account sending and
* paying for execution may not be the actual sender (as far as an application
* is concerned).
*
* This contract is only required for intermediate, library-like contracts.
*/
abstract contract Context {
function _msgSender() internal view virtual returns (address) {
return msg.sender;
}
function _msgData() internal view virtual returns (bytes calldata) {
return msg.data;
}
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v4.5.0) (token/ERC721/ERC721.sol)
pragma solidity ^0.8.0;
import "./IERC721.sol";
import "./IERC721Receiver.sol";
import "./extensions/IERC721Metadata.sol";
import "../../utils/Address.sol";
import "../../utils/Context.sol";
import "../../utils/Strings.sol";
import "../../utils/introspection/ERC165.sol";
/**
* @dev Implementation of https://eips.ethereum.org/EIPS/eip-721[ERC721] Non-Fungible Token Standard, including
* the Metadata extension, but not including the Enumerable extension, which is available separately as
* {ERC721Enumerable}.
*/
contract ERC721 is Context, ERC165, IERC721, IERC721Metadata {
using Address for address;
using Strings for uint256;
// Token name
string private _name;
// Token symbol
string private _symbol;
// Mapping from token ID to owner address
mapping(uint256 => address) private _owners;
// Mapping owner address to token count
mapping(address => uint256) private _balances;
// Mapping from token ID to approved address
mapping(uint256 => address) private _tokenApprovals;
// Mapping from owner to operator approvals
mapping(address => mapping(address => bool)) private _operatorApprovals;
/**
* @dev Initializes the contract by setting a `name` and a `symbol` to the token collection.
*/
constructor(string memory name_, string memory symbol_) {
_name = name_;
_symbol = symbol_;
}
/**
* @dev See {IERC165-supportsInterface}.
*/
function supportsInterface(bytes4 interfaceId) public view virtual override(ERC165, IERC165) returns (bool) {
return
interfaceId == type(IERC721).interfaceId ||
interfaceId == type(IERC721Metadata).interfaceId ||
super.supportsInterface(interfaceId);
}
/**
* @dev See {IERC721-balanceOf}.
*/
function balanceOf(address owner) public view virtual override returns (uint256) {
require(owner != address(0), "ERC721: balance query for the zero address");
return _balances[owner];
}
/**
* @dev See {IERC721-ownerOf}.
*/
function ownerOf(uint256 tokenId) public view virtual override returns (address) {
address owner = _owners[tokenId];
require(owner != address(0), "ERC721: owner query for nonexistent token");
return owner;
}
/**
* @dev See {IERC721Metadata-name}.
*/
function name() public view virtual override returns (string memory) {
return _name;
}
/**
* @dev See {IERC721Metadata-symbol}.
*/
function symbol() public view virtual override returns (string memory) {
return _symbol;
}
/**
* @dev See {IERC721Metadata-tokenURI}.
*/
function tokenURI(uint256 tokenId) public view virtual override returns (string memory) {
require(_exists(tokenId), "ERC721Metadata: URI query for nonexistent token");
string memory baseURI = _baseURI();
return bytes(baseURI).length > 0 ? string(abi.encodePacked(baseURI, tokenId.toString())) : "";
}
/**
* @dev Base URI for computing {tokenURI}. If set, the resulting URI for each
* token will be the concatenation of the `baseURI` and the `tokenId`. Empty
* by default, can be overriden in child contracts.
*/
function _baseURI() internal view virtual returns (string memory) {
return "";
}
/**
* @dev See {IERC721-approve}.
*/
function approve(address to, uint256 tokenId) public virtual override {
address owner = ERC721.ownerOf(tokenId);
require(to != owner, "ERC721: approval to current owner");
require(
_msgSender() == owner || isApprovedForAll(owner, _msgSender()),
"ERC721: approve caller is not owner nor approved for all"
);
_approve(to, tokenId);
}
/**
* @dev See {IERC721-getApproved}.
*/
function getApproved(uint256 tokenId) public view virtual override returns (address) {
require(_exists(tokenId), "ERC721: approved query for nonexistent token");
return _tokenApprovals[tokenId];
}
/**
* @dev See {IERC721-setApprovalForAll}.
*/
function setApprovalForAll(address operator, bool approved) public virtual override {
_setApprovalForAll(_msgSender(), operator, approved);
}
/**
* @dev See {IERC721-isApprovedForAll}.
*/
function isApprovedForAll(address owner, address operator) public view virtual override returns (bool) {
return _operatorApprovals[owner][operator];
}
/**
* @dev See {IERC721-transferFrom}.
*/
function transferFrom(
address from,
address to,
uint256 tokenId
) public virtual override {
//solhint-disable-next-line max-line-length
require(_isApprovedOrOwner(_msgSender(), tokenId), "ERC721: transfer caller is not owner nor approved");
_transfer(from, to, tokenId);
}
/**
* @dev See {IERC721-safeTransferFrom}.
*/
function safeTransferFrom(
address from,
address to,
uint256 tokenId
) public virtual override {
safeTransferFrom(from, to, tokenId, "");
}
/**
* @dev See {IERC721-safeTransferFrom}.
*/
function safeTransferFrom(
address from,
address to,
uint256 tokenId,
bytes memory _data
) public virtual override {
require(_isApprovedOrOwner(_msgSender(), tokenId), "ERC721: transfer caller is not owner nor approved");
_safeTransfer(from, to, tokenId, _data);
}
/**
* @dev Safely transfers `tokenId` token from `from` to `to`, checking first that contract recipients
* are aware of the ERC721 protocol to prevent tokens from being forever locked.
*
* `_data` is additional data, it has no specified format and it is sent in call to `to`.
*
* This internal function is equivalent to {safeTransferFrom}, and can be used to e.g.
* implement alternative mechanisms to perform token transfer, such as signature-based.
*
* Requirements:
*
* - `from` cannot be the zero address.
* - `to` cannot be the zero address.
* - `tokenId` token must exist and be owned by `from`.
* - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer.
*
* Emits a {Transfer} event.
*/
function _safeTransfer(
address from,
address to,
uint256 tokenId,
bytes memory _data
) internal virtual {
_transfer(from, to, tokenId);
require(_checkOnERC721Received(from, to, tokenId, _data), "ERC721: transfer to non ERC721Receiver implementer");
}
/**
* @dev Returns whether `tokenId` exists.
*
* Tokens can be managed by their owner or approved accounts via {approve} or {setApprovalForAll}.
*
* Tokens start existing when they are minted (`_mint`),
* and stop existing when they are burned (`_burn`).
*/
function _exists(uint256 tokenId) internal view virtual returns (bool) {
return _owners[tokenId] != address(0);
}
/**
* @dev Returns whether `spender` is allowed to manage `tokenId`.
*
* Requirements:
*
* - `tokenId` must exist.
*/
function _isApprovedOrOwner(address spender, uint256 tokenId) internal view virtual returns (bool) {
require(_exists(tokenId), "ERC721: operator query for nonexistent token");
address owner = ERC721.ownerOf(tokenId);
return (spender == owner || getApproved(tokenId) == spender || isApprovedForAll(owner, spender));
}
/**
* @dev Safely mints `tokenId` and transfers it to `to`.
*
* Requirements:
*
* - `tokenId` must not exist.
* - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer.
*
* Emits a {Transfer} event.
*/
function _safeMint(address to, uint256 tokenId) internal virtual {
_safeMint(to, tokenId, "");
}
/**
* @dev Same as {xref-ERC721-_safeMint-address-uint256-}[`_safeMint`], with an additional `data` parameter which is
* forwarded in {IERC721Receiver-onERC721Received} to contract recipients.
*/
function _safeMint(
address to,
uint256 tokenId,
bytes memory _data
) internal virtual {
_mint(to, tokenId);
require(
_checkOnERC721Received(address(0), to, tokenId, _data),
"ERC721: transfer to non ERC721Receiver implementer"
);
}
/**
* @dev Mints `tokenId` and transfers it to `to`.
*
* WARNING: Usage of this method is discouraged, use {_safeMint} whenever possible
*
* Requirements:
*
* - `tokenId` must not exist.
* - `to` cannot be the zero address.
*
* Emits a {Transfer} event.
*/
function _mint(address to, uint256 tokenId) internal virtual {
require(to != address(0), "ERC721: mint to the zero address");
require(!_exists(tokenId), "ERC721: token already minted");
_beforeTokenTransfer(address(0), to, tokenId);
_balances[to] += 1;
_owners[tokenId] = to;
emit Transfer(address(0), to, tokenId);
_afterTokenTransfer(address(0), to, tokenId);
}
/**
* @dev Destroys `tokenId`.
* The approval is cleared when the token is burned.
*
* Requirements:
*
* - `tokenId` must exist.
*
* Emits a {Transfer} event.
*/
function _burn(uint256 tokenId) internal virtual {
address owner = ERC721.ownerOf(tokenId);
_beforeTokenTransfer(owner, address(0), tokenId);
// Clear approvals
_approve(address(0), tokenId);
_balances[owner] -= 1;
delete _owners[tokenId];
emit Transfer(owner, address(0), tokenId);
_afterTokenTransfer(owner, address(0), tokenId);
}
/**
* @dev Transfers `tokenId` from `from` to `to`.
* As opposed to {transferFrom}, this imposes no restrictions on msg.sender.
*
* Requirements:
*
* - `to` cannot be the zero address.
* - `tokenId` token must be owned by `from`.
*
* Emits a {Transfer} event.
*/
function _transfer(
address from,
address to,
uint256 tokenId
) internal virtual {
require(ERC721.ownerOf(tokenId) == from, "ERC721: transfer from incorrect owner");
require(to != address(0), "ERC721: transfer to the zero address");
_beforeTokenTransfer(from, to, tokenId);
// Clear approvals from the previous owner
_approve(address(0), tokenId);
_balances[from] -= 1;
_balances[to] += 1;
_owners[tokenId] = to;
emit Transfer(from, to, tokenId);
_afterTokenTransfer(from, to, tokenId);
}
/**
* @dev Approve `to` to operate on `tokenId`
*
* Emits a {Approval} event.
*/
function _approve(address to, uint256 tokenId) internal virtual {
_tokenApprovals[tokenId] = to;
emit Approval(ERC721.ownerOf(tokenId), to, tokenId);
}
/**
* @dev Approve `operator` to operate on all of `owner` tokens
*
* Emits a {ApprovalForAll} event.
*/
function _setApprovalForAll(
address owner,
address operator,
bool approved
) internal virtual {
require(owner != operator, "ERC721: approve to caller");
_operatorApprovals[owner][operator] = approved;
emit ApprovalForAll(owner, operator, approved);
}
/**
* @dev Internal function to invoke {IERC721Receiver-onERC721Received} on a target address.
* The call is not executed if the target address is not a contract.
*
* @param from address representing the previous owner of the given token ID
* @param to target address that will receive the tokens
* @param tokenId uint256 ID of the token to be transferred
* @param _data bytes optional data to send along with the call
* @return bool whether the call correctly returned the expected magic value
*/
function _checkOnERC721Received(
address from,
address to,
uint256 tokenId,
bytes memory _data
) private returns (bool) {
if (to.isContract()) {
try IERC721Receiver(to).onERC721Received(_msgSender(), from, tokenId, _data) returns (bytes4 retval) {
return retval == IERC721Receiver.onERC721Received.selector;
} catch (bytes memory reason) {
if (reason.length == 0) {
revert("ERC721: transfer to non ERC721Receiver implementer");
} else {
assembly {
revert(add(32, reason), mload(reason))
}
}
}
} else {
return true;
}
}
/**
* @dev Hook that is called before any token transfer. This includes minting
* and burning.
*
* Calling conditions:
*
* - When `from` and `to` are both non-zero, ``from``'s `tokenId` will be
* transferred to `to`.
* - When `from` is zero, `tokenId` will be minted for `to`.
* - When `to` is zero, ``from``'s `tokenId` will be burned.
* - `from` and `to` are never both zero.
*
* To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks].
*/
function _beforeTokenTransfer(
address from,
address to,
uint256 tokenId
) internal virtual {}
/**
* @dev Hook that is called after any transfer of tokens. This includes
* minting and burning.
*
* Calling conditions:
*
* - when `from` and `to` are both non-zero.
* - `from` and `to` are never both zero.
*
* To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks].
*/
function _afterTokenTransfer(
address from,
address to,
uint256 tokenId
) internal virtual {}
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v4.5.0) (token/ERC721/extensions/IERC721Enumerable.sol)
pragma solidity ^0.8.0;
import "../IERC721.sol";
/**
* @title ERC-721 Non-Fungible Token Standard, optional enumeration extension
* @dev See https://eips.ethereum.org/EIPS/eip-721
*/
interface IERC721Enumerable is IERC721 {
/**
* @dev Returns the total amount of tokens stored by the contract.
*/
function totalSupply() external view returns (uint256);
/**
* @dev Returns a token ID owned by `owner` at a given `index` of its token list.
* Use along with {balanceOf} to enumerate all of ``owner``'s tokens.
*/
function tokenOfOwnerByIndex(address owner, uint256 index) external view returns (uint256);
/**
* @dev Returns a token ID at a given `index` of all the tokens stored by the contract.
* Use along with {totalSupply} to enumerate all tokens.
*/
function tokenByIndex(uint256 index) external view returns (uint256);
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (token/ERC721/IERC721.sol)
pragma solidity ^0.8.0;
import "../../utils/introspection/IERC165.sol";
/**
* @dev Required interface of an ERC721 compliant contract.
*/
interface IERC721 is IERC165 {
/**
* @dev Emitted when `tokenId` token is transferred from `from` to `to`.
*/
event Transfer(address indexed from, address indexed to, uint256 indexed tokenId);
/**
* @dev Emitted when `owner` enables `approved` to manage the `tokenId` token.
*/
event Approval(address indexed owner, address indexed approved, uint256 indexed tokenId);
/**
* @dev Emitted when `owner` enables or disables (`approved`) `operator` to manage all of its assets.
*/
event ApprovalForAll(address indexed owner, address indexed operator, bool approved);
/**
* @dev Returns the number of tokens in ``owner``'s account.
*/
function balanceOf(address owner) external view returns (uint256 balance);
/**
* @dev Returns the owner of the `tokenId` token.
*
* Requirements:
*
* - `tokenId` must exist.
*/
function ownerOf(uint256 tokenId) external view returns (address owner);
/**
* @dev Safely transfers `tokenId` token from `from` to `to`, checking first that contract recipients
* are aware of the ERC721 protocol to prevent tokens from being forever locked.
*
* Requirements:
*
* - `from` cannot be the zero address.
* - `to` cannot be the zero address.
* - `tokenId` token must exist and be owned by `from`.
* - If the caller is not `from`, it must be have been allowed to move this token by either {approve} or {setApprovalForAll}.
* - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer.
*
* Emits a {Transfer} event.
*/
function safeTransferFrom(
address from,
address to,
uint256 tokenId
) external;
/**
* @dev Transfers `tokenId` token from `from` to `to`.
*
* WARNING: Usage of this method is discouraged, use {safeTransferFrom} whenever possible.
*
* Requirements:
*
* - `from` cannot be the zero address.
* - `to` cannot be the zero address.
* - `tokenId` token must be owned by `from`.
* - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}.
*
* Emits a {Transfer} event.
*/
function transferFrom(
address from,
address to,
uint256 tokenId
) external;
/**
* @dev Gives permission to `to` to transfer `tokenId` token to another account.
* The approval is cleared when the token is transferred.
*
* Only a single account can be approved at a time, so approving the zero address clears previous approvals.
*
* Requirements:
*
* - The caller must own the token or be an approved operator.
* - `tokenId` must exist.
*
* Emits an {Approval} event.
*/
function approve(address to, uint256 tokenId) external;
/**
* @dev Returns the account approved for `tokenId` token.
*
* Requirements:
*
* - `tokenId` must exist.
*/
function getApproved(uint256 tokenId) external view returns (address operator);
/**
* @dev Approve or remove `operator` as an operator for the caller.
* Operators can call {transferFrom} or {safeTransferFrom} for any token owned by the caller.
*
* Requirements:
*
* - The `operator` cannot be the caller.
*
* Emits an {ApprovalForAll} event.
*/
function setApprovalForAll(address operator, bool _approved) external;
/**
* @dev Returns if the `operator` is allowed to manage all of the assets of `owner`.
*
* See {setApprovalForAll}
*/
function isApprovedForAll(address owner, address operator) external view returns (bool);
/**
* @dev Safely transfers `tokenId` token from `from` to `to`.
*
* Requirements:
*
* - `from` cannot be the zero address.
* - `to` cannot be the zero address.
* - `tokenId` token must exist and be owned by `from`.
* - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}.
* - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer.
*
* Emits a {Transfer} event.
*/
function safeTransferFrom(
address from,
address to,
uint256 tokenId,
bytes calldata data
) external;
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (token/ERC721/IERC721Receiver.sol)
pragma solidity ^0.8.0;
/**
* @title ERC721 token receiver interface
* @dev Interface for any contract that wants to support safeTransfers
* from ERC721 asset contracts.
*/
interface IERC721Receiver {
/**
* @dev Whenever an {IERC721} `tokenId` token is transferred to this contract via {IERC721-safeTransferFrom}
* by `operator` from `from`, this function is called.
*
* It must return its Solidity selector to confirm the token transfer.
* If any other value is returned or the interface is not implemented by the recipient, the transfer will be reverted.
*
* The selector can be obtained in Solidity with `IERC721.onERC721Received.selector`.
*/
function onERC721Received(
address operator,
address from,
uint256 tokenId,
bytes calldata data
) external returns (bytes4);
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (token/ERC721/extensions/IERC721Metadata.sol)
pragma solidity ^0.8.0;
import "../IERC721.sol";
/**
* @title ERC-721 Non-Fungible Token Standard, optional metadata extension
* @dev See https://eips.ethereum.org/EIPS/eip-721
*/
interface IERC721Metadata is IERC721 {
/**
* @dev Returns the token collection name.
*/
function name() external view returns (string memory);
/**
* @dev Returns the token collection symbol.
*/
function symbol() external view returns (string memory);
/**
* @dev Returns the Uniform Resource Identifier (URI) for `tokenId` token.
*/
function tokenURI(uint256 tokenId) external view returns (string memory);
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v4.5.0) (utils/Address.sol)
pragma solidity ^0.8.1;
/**
* @dev Collection of functions related to the address type
*/
library Address {
/**
* @dev Returns true if `account` is a contract.
*
* [IMPORTANT]
* ====
* It is unsafe to assume that an address for which this function returns
* false is an externally-owned account (EOA) and not a contract.
*
* Among others, `isContract` will return false for the following
* types of addresses:
*
* - an externally-owned account
* - a contract in construction
* - an address where a contract will be created
* - an address where a contract lived, but was destroyed
* ====
*
* [IMPORTANT]
* ====
* You shouldn't rely on `isContract` to protect against flash loan attacks!
*
* Preventing calls from contracts is highly discouraged. It breaks composability, breaks support for smart wallets
* like Gnosis Safe, and does not provide security since it can be circumvented by calling from a contract
* constructor.
* ====
*/
function isContract(address account) internal view returns (bool) {
// This method relies on extcodesize/address.code.length, which returns 0
// for contracts in construction, since the code is only stored at the end
// of the constructor execution.
return account.code.length > 0;
}
/**
* @dev Replacement for Solidity's `transfer`: sends `amount` wei to
* `recipient`, forwarding all available gas and reverting on errors.
*
* https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost
* of certain opcodes, possibly making contracts go over the 2300 gas limit
* imposed by `transfer`, making them unable to receive funds via
* `transfer`. {sendValue} removes this limitation.
*
* https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more].
*
* IMPORTANT: because control is transferred to `recipient`, care must be
* taken to not create reentrancy vulnerabilities. Consider using
* {ReentrancyGuard} or the
* https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern].
*/
function sendValue(address payable recipient, uint256 amount) internal {
require(address(this).balance >= amount, "Address: insufficient balance");
(bool success, ) = recipient.call{value: amount}("");
require(success, "Address: unable to send value, recipient may have reverted");
}
/**
* @dev Performs a Solidity function call using a low level `call`. A
* plain `call` is an unsafe replacement for a function call: use this
* function instead.
*
* If `target` reverts with a revert reason, it is bubbled up by this
* function (like regular Solidity function calls).
*
* Returns the raw returned data. To convert to the expected return value,
* use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`].
*
* 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");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with
* `errorMessage` as a fallback revert reason when `target` reverts.
*
* _Available since v3.1._
*/
function functionCall(
address target,
bytes memory data,
string memory errorMessage
) internal returns (bytes memory) {
return functionCallWithValue(target, data, 0, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but also transferring `value` wei to `target`.
*
* Requirements:
*
* - the calling contract must have an ETH balance of at least `value`.
* - the called Solidity function must be `payable`.
*
* _Available since v3.1._
*/
function functionCallWithValue(
address target,
bytes memory data,
uint256 value
) internal returns (bytes memory) {
return functionCallWithValue(target, data, value, "Address: low-level call with value failed");
}
/**
* @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but
* with `errorMessage` as a fallback revert reason when `target` reverts.
*
* _Available since v3.1._
*/
function functionCallWithValue(
address target,
bytes memory data,
uint256 value,
string memory errorMessage
) internal returns (bytes memory) {
require(address(this).balance >= value, "Address: insufficient balance for call");
require(isContract(target), "Address: call to non-contract");
(bool success, bytes memory returndata) = target.call{value: value}(data);
return verifyCallResult(success, returndata, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but performing a static call.
*
* _Available since v3.3._
*/
function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) {
return functionStaticCall(target, data, "Address: low-level static call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`],
* but performing a static call.
*
* _Available since v3.3._
*/
function functionStaticCall(
address target,
bytes memory data,
string memory errorMessage
) internal view returns (bytes memory) {
require(isContract(target), "Address: static call to non-contract");
(bool success, bytes memory returndata) = target.staticcall(data);
return verifyCallResult(success, returndata, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but performing a delegate call.
*
* _Available since v3.4._
*/
function functionDelegateCall(address target, bytes memory data) internal returns (bytes memory) {
return functionDelegateCall(target, data, "Address: low-level delegate call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`],
* but performing a delegate call.
*
* _Available since v3.4._
*/
function functionDelegateCall(
address target,
bytes memory data,
string memory errorMessage
) internal returns (bytes memory) {
require(isContract(target), "Address: delegate call to non-contract");
(bool success, bytes memory returndata) = target.delegatecall(data);
return verifyCallResult(success, returndata, errorMessage);
}
/**
* @dev Tool to verifies that a low level call was successful, and revert if it wasn't, either by bubbling the
* revert reason using the provided one.
*
* _Available since v4.3._
*/
function verifyCallResult(
bool success,
bytes memory returndata,
string memory errorMessage
) internal pure returns (bytes memory) {
if (success) {
return returndata;
} else {
// Look for revert reason and bubble it up if present
if (returndata.length > 0) {
// The easiest way to bubble the revert reason is using memory via assembly
assembly {
let returndata_size := mload(returndata)
revert(add(32, returndata), returndata_size)
}
} else {
revert(errorMessage);
}
}
}
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (utils/Strings.sol)
pragma solidity ^0.8.0;
/**
* @dev String operations.
*/
library Strings {
bytes16 private constant _HEX_SYMBOLS = "0123456789abcdef";
/**
* @dev Converts a `uint256` to its ASCII `string` decimal representation.
*/
function toString(uint256 value) internal pure returns (string memory) {
// Inspired by OraclizeAPI's implementation - MIT licence
// https://github.com/oraclize/ethereum-api/blob/b42146b063c7d6ee1358846c198246239e9360e8/oraclizeAPI_0.4.25.sol
if (value == 0) {
return "0";
}
uint256 temp = value;
uint256 digits;
while (temp != 0) {
digits++;
temp /= 10;
}
bytes memory buffer = new bytes(digits);
while (value != 0) {
digits -= 1;
buffer[digits] = bytes1(uint8(48 + uint256(value % 10)));
value /= 10;
}
return string(buffer);
}
/**
* @dev Converts a `uint256` to its ASCII `string` hexadecimal representation.
*/
function toHexString(uint256 value) internal pure returns (string memory) {
if (value == 0) {
return "0x00";
}
uint256 temp = value;
uint256 length = 0;
while (temp != 0) {
length++;
temp >>= 8;
}
return toHexString(value, length);
}
/**
* @dev Converts a `uint256` to its ASCII `string` hexadecimal representation with fixed length.
*/
function toHexString(uint256 value, uint256 length) internal pure returns (string memory) {
bytes memory buffer = new bytes(2 * length + 2);
buffer[0] = "0";
buffer[1] = "x";
for (uint256 i = 2 * length + 1; i > 1; --i) {
buffer[i] = _HEX_SYMBOLS[value & 0xf];
value >>= 4;
}
require(value == 0, "Strings: hex length insufficient");
return string(buffer);
}
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (utils/introspection/ERC165.sol)
pragma solidity ^0.8.0;
import "./IERC165.sol";
/**
* @dev Implementation of the {IERC165} interface.
*
* Contracts that want to implement ERC165 should inherit from this contract and override {supportsInterface} to check
* for the additional interface id that will be supported. For example:
*
* ```solidity
* function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) {
* return interfaceId == type(MyInterface).interfaceId || super.supportsInterface(interfaceId);
* }
* ```
*
* Alternatively, {ERC165Storage} provides an easier to use but more expensive implementation.
*/
abstract contract ERC165 is IERC165 {
/**
* @dev See {IERC165-supportsInterface}.
*/
function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) {
return interfaceId == type(IERC165).interfaceId;
}
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (utils/introspection/IERC165.sol)
pragma solidity ^0.8.0;
/**
* @dev Interface of the ERC165 standard, as defined in the
* https://eips.ethereum.org/EIPS/eip-165[EIP].
*
* Implementers can declare support of contract interfaces, which can then be
* queried by others ({ERC165Checker}).
*
* For an implementation, see {ERC165}.
*/
interface IERC165 {
/**
* @dev Returns true if this contract implements the interface defined by
* `interfaceId`. See the corresponding
* https://eips.ethereum.org/EIPS/eip-165#how-interfaces-are-identified[EIP section]
* to learn more about how these ids are created.
*
* This function call must use less than 30 000 gas.
*/
function supportsInterface(bytes4 interfaceId) external view returns (bool);
}
// SPDX-License-Identifier: UNLICENSED
pragma solidity >=0.6.0;
import "../contracts/ShackledCoords.sol";
contract XShackledCoords {
constructor() {}
function xconvertToWorldSpaceWithModelTransform(int256[3][3][] calldata tris,int256 scale,int256[3] calldata position) external view returns (int256[3][] memory) {
return ShackledCoords.convertToWorldSpaceWithModelTransform(tris,scale,position);
}
function xbackfaceCulling(int256[3][3][] calldata trisWorldSpace,int256[3][3][] calldata trisCols) external view returns (int256[3][3][] memory, int256[3][3][] memory) {
return ShackledCoords.backfaceCulling(trisWorldSpace,trisCols);
}
function xconvertToCameraSpaceViaVertexShader(int256[3][] calldata vertsWorldSpace,int256 canvasDim,bool perspCamera) external view returns (int256[3][] memory) {
return ShackledCoords.convertToCameraSpaceViaVertexShader(vertsWorldSpace,canvasDim,perspCamera);
}
function xgetCameraMatrixOrth(int256 canvasDim) external pure returns (int256[4][4][2] memory) {
return ShackledCoords.getCameraMatrixOrth(canvasDim);
}
function xgetCameraMatrixPersp() external pure returns (int256[4][4][2] memory) {
return ShackledCoords.getCameraMatrixPersp();
}
}
// SPDX-License-Identifier: UNLICENSED
pragma solidity >=0.6.0;
import "../contracts/ShackledIcons.sol";
contract XShackledIcons is ShackledIcons {
constructor() {}
function x_getLightingParamsHash(ShackledStructs.LightingParams calldata lightingParams) external pure returns (bytes32) {
return super._getLightingParamsHash(lightingParams);
}
function x_baseURI() external view returns (string memory) {
return super._baseURI();
}
function x_transferOwnership(address newOwner) external {
return super._transferOwnership(newOwner);
}
function x_beforeTokenTransfer(address from,address to,uint256 tokenId) external {
return super._beforeTokenTransfer(from,to,tokenId);
}
function x_safeTransfer(address from,address to,uint256 tokenId,bytes calldata _data) external {
return super._safeTransfer(from,to,tokenId,_data);
}
function x_exists(uint256 tokenId) external view returns (bool) {
return super._exists(tokenId);
}
function x_isApprovedOrOwner(address spender,uint256 tokenId) external view returns (bool) {
return super._isApprovedOrOwner(spender,tokenId);
}
function x_safeMint(address to,uint256 tokenId) external {
return super._safeMint(to,tokenId);
}
function x_safeMint(address to,uint256 tokenId,bytes calldata _data) external {
return super._safeMint(to,tokenId,_data);
}
function x_mint(address to,uint256 tokenId) external {
return super._mint(to,tokenId);
}
function x_burn(uint256 tokenId) external {
return super._burn(tokenId);
}
function x_transfer(address from,address to,uint256 tokenId) external {
return super._transfer(from,to,tokenId);
}
function x_approve(address to,uint256 tokenId) external {
return super._approve(to,tokenId);
}
function x_setApprovalForAll(address owner,address operator,bool approved) external {
return super._setApprovalForAll(owner,operator,approved);
}
function x_afterTokenTransfer(address from,address to,uint256 tokenId) external {
return super._afterTokenTransfer(from,to,tokenId);
}
function x_msgSender() external view returns (address) {
return super._msgSender();
}
function x_msgData() external view returns (bytes memory) {
return super._msgData();
}
}
// SPDX-License-Identifier: UNLICENSED
pragma solidity >=0.6.0;
import "../contracts/ShackledMath.sol";
contract XShackledMath {
constructor() {}
function xmin(int256 a,int256 b) external pure returns (int256) {
return ShackledMath.min(a,b);
}
function xmax(int256 a,int256 b) external pure returns (int256) {
return ShackledMath.max(a,b);
}
function xmod(int256 n,int256 m) external pure returns (int256) {
return ShackledMath.mod(n,m);
}
function xrandomIdx(bytes32 seedModifier,uint256 n,uint256 m) external pure returns (uint256[] memory) {
return ShackledMath.randomIdx(seedModifier,n,m);
}
function xget2dArray(uint256 m,uint256 q,int256 value) external pure returns (int256[][] memory) {
return ShackledMath.get2dArray(m,q,value);
}
function xabs(int256 x) external pure returns (int256) {
return ShackledMath.abs(x);
}
function xsqrt(int256 y) external pure returns (int256) {
return ShackledMath.sqrt(y);
}
function xhypot(int256 x,int256 y) external pure returns (int256) {
return ShackledMath.hypot(x,y);
}
function xvector3Add(int256[3] calldata v1,int256[3] calldata v2) external pure returns (int256[3] memory) {
return ShackledMath.vector3Add(v1,v2);
}
function xvector3Sub(int256[3] calldata v1,int256[3] calldata v2) external pure returns (int256[3] memory) {
return ShackledMath.vector3Sub(v1,v2);
}
function xvector3MulScalar(int256[3] calldata v,int256 a) external pure returns (int256[3] memory) {
return ShackledMath.vector3MulScalar(v,a);
}
function xvector3DivScalar(int256[3] calldata v,int256 a) external pure returns (int256[3] memory) {
return ShackledMath.vector3DivScalar(v,a);
}
function xvector3Len(int256[3] calldata v) external pure returns (int256) {
return ShackledMath.vector3Len(v);
}
function xvector3NormX(int256[3] calldata v,int256 fidelity) external pure returns (int256[3] memory) {
return ShackledMath.vector3NormX(v,fidelity);
}
function xvector3Dot(int256[3] calldata v1,int256[3] calldata v2) external view returns (int256) {
return ShackledMath.vector3Dot(v1,v2);
}
function xcrossProduct(int256[3] calldata v1,int256[3] calldata v2) external pure returns (int256[3] memory) {
return ShackledMath.crossProduct(v1,v2);
}
function xvector12Lerp(int256[12] calldata v1,int256[12] calldata v2,int256 ir,int256 scaleFactor) external view returns (int256[12] memory) {
return ShackledMath.vector12Lerp(v1,v2,ir,scaleFactor);
}
function xvector12Sub(int256[12] calldata v1,int256[12] calldata v2) external view returns (int256[12] memory) {
return ShackledMath.vector12Sub(v1,v2);
}
function xmapRangeToRange(int256 num,int256 inMin,int256 inMax,int256 outMin,int256 outMax) external pure returns (int256) {
return ShackledMath.mapRangeToRange(num,inMin,inMax,outMin,outMax);
}
}
// SPDX-License-Identifier: UNLICENSED
pragma solidity >=0.6.0;
import "../contracts/ShackledRasteriser.sol";
contract XShackledRasteriser {
constructor() {}
function xinitialiseFragments(int256[3][3][] calldata trisCameraSpace,int256[3][3][] calldata trisWorldSpace,int256[3][3][] calldata trisCols,int256 canvasDim) external view returns (int256[12][3][] memory) {
return ShackledRasteriser.initialiseFragments(trisCameraSpace,trisWorldSpace,trisCols,canvasDim);
}
function xrasterise(int256[12][3][] calldata trisFragments,int256 canvasDim,bool wireframe) external view returns (int256[12][] memory) {
return ShackledRasteriser.rasterise(trisFragments,canvasDim,wireframe);
}
function xrunBresenhamsAlgorithm(int256[12] calldata f1,int256[12] calldata f2,int256 canvasDim,int256[12][] calldata bresTriFragments,uint256 nextBresTriFragmentIx) external view returns (int256[12][] memory, uint256) {
return ShackledRasteriser.runBresenhamsAlgorithm(f1,f2,canvasDim,bresTriFragments,nextBresTriFragmentIx);
}
function xbresenhamsInner(ShackledRasteriser.BresenhamsVars calldata vars,int256 mag,int256[12] calldata fa,int256[12] calldata fb,int256 canvasDim,int256[12][] calldata bresTriFragments,uint256 nextBresTriFragmentIx) external view returns (int256[12][] memory, uint256) {
return ShackledRasteriser.bresenhamsInner(vars,mag,fa,fb,canvasDim,bresTriFragments,nextBresTriFragmentIx);
}
function xrunScanline(int256[12][] calldata bresTriFragments,int256[12][] calldata fragments,uint256 nextFragmentsIx,int256 canvasDim) external view returns (int256[12][] memory, uint256) {
return ShackledRasteriser.runScanline(bresTriFragments,fragments,nextFragmentsIx,canvasDim);
}
function xgetRowFragIndices(int256[12][] calldata bresTriFragments,int256 canvasDim) external view returns (int256[][] memory, uint256[] memory) {
return ShackledRasteriser.getRowFragIndices(bresTriFragments,canvasDim);
}
function xdepthTesting(int256[12][] calldata fragments,int256 canvasDim) external view returns (int256[12][] memory) {
return ShackledRasteriser.depthTesting(fragments,canvasDim);
}
function xlightScene(int256[12][] calldata fragments,ShackledStructs.LightingParams calldata lp) external view returns (int256[12][] memory) {
return ShackledRasteriser.lightScene(fragments,lp);
}
function xcalculateSpecular(int256 lightSpecPower,int256 hnDot,int256 fidelity,uint256 inverseShininess) external pure returns (int256) {
return ShackledRasteriser.calculateSpecular(lightSpecPower,hnDot,fidelity,inverseShininess);
}
function xgetBackground(int256 canvasDim,int256[3][2] calldata backgroundColor) external view returns (int256[5][] memory) {
return ShackledRasteriser.getBackground(canvasDim,backgroundColor);
}
}
// SPDX-License-Identifier: UNLICENSED
pragma solidity >=0.6.0;
import "../contracts/ShackledRenderer.sol";
contract XShackledRenderer {
constructor() {}
function xrender(ShackledStructs.RenderParams calldata renderParams,int256 canvasDim,bool returnSVG) external view returns (string memory) {
return ShackledRenderer.render(renderParams,canvasDim,returnSVG);
}
function xprepareGeometryForRender(ShackledStructs.RenderParams calldata renderParams,int256 canvasDim) external view returns (int256[12][3][] memory) {
return ShackledRenderer.prepareGeometryForRender(renderParams,canvasDim);
}
}
// SPDX-License-Identifier: UNLICENSED
pragma solidity >=0.6.0;
import "../contracts/ShackledStructs.sol";
contract XShackledStructs {
constructor() {}
}
// SPDX-License-Identifier: UNLICENSED
pragma solidity >=0.6.0;
import "../contracts/ShackledUtils.sol";
contract XShackledUtils {
constructor() {}
function xflattenTris(int256[3][3][] calldata tris) external pure returns (int256[3][] memory) {
return ShackledUtils.flattenTris(tris);
}
function xunflattenVertsToTris(int256[3][] calldata verts) external pure returns (int256[3][3][] memory) {
return ShackledUtils.unflattenVertsToTris(verts);
}
function xclipArray12ToLength(int256[12][] calldata arr,uint256 desiredLen) external pure returns (int256[12][] memory) {
return ShackledUtils.clipArray12ToLength(arr,desiredLen);
}
function xuint2str(uint256 _i) external pure returns (string memory) {
return ShackledUtils.uint2str(_i);
}
function xgetHex(uint256 _i) external pure returns (bytes memory) {
return ShackledUtils.getHex(_i);
}
function xgetSVGContainer(string calldata encodedBitmap,int256 canvasDim,uint256 outputHeight,uint256 outputWidth) external view returns (string memory) {
return ShackledUtils.getSVGContainer(encodedBitmap,canvasDim,outputHeight,outputWidth);
}
function xgetAttributes(ShackledStructs.Metadata calldata metadata) external pure returns (bytes memory) {
return ShackledUtils.getAttributes(metadata);
}
function xgetEncodedMetadata(string calldata image,ShackledStructs.Metadata calldata metadata,uint256 tokenId) external view returns (string memory) {
return ShackledUtils.getEncodedMetadata(image,metadata,tokenId);
}
function xgetEncodedBitmap(int256[12][] calldata fragments,int256[5][] calldata background,int256 canvasDim,bool invert) external view returns (string memory) {
return ShackledUtils.getEncodedBitmap(fragments,background,canvasDim,invert);
}
function xwriteFragmentsToBytesArray(int256[12][] calldata fragments,bytes calldata bytesArray,uint256 canvasDimUnsigned,bool invert) external pure returns (bytes memory) {
return ShackledUtils.writeFragmentsToBytesArray(fragments,bytesArray,canvasDimUnsigned,invert);
}
function xwriteBackgroundToBytesArray(int256[5][] calldata background,bytes calldata bytesArray,uint256 canvasDimUnsigned,bool invert) external pure returns (bytes memory) {
return ShackledUtils.writeBackgroundToBytesArray(background,bytesArray,canvasDimUnsigned,invert);
}
}
contract XBase64 {
constructor() {}
function xencode(bytes calldata data) external view returns (string memory) {
return Base64.encode(data);
}
}
contract XBytesUtils {
constructor() {}
function xchar(bytes1 b) external view returns (bytes1) {
return BytesUtils.char(b);
}
function xbytes32string(bytes32 b32) external view returns (string memory) {
return BytesUtils.bytes32string(b32);
}
function xhach(string calldata value) external view returns (string memory) {
return BytesUtils.hach(value);
}
function xMergeBytes(bytes calldata a,bytes calldata b) external pure returns (bytes memory) {
return BytesUtils.MergeBytes(a,b);
}
}
|
generate a perspective camera matrix / Z settings (near and far) Get the perspective transform matrix as a numerator and denominator parameter = 1 / tan(fov in degrees / 2) 0.1763 = 1 / tan(160 / 2) 1.428 = 1 / tan(70 / 2) 1.732 = 1 / tan(60 / 2) 2.145 = 1 / tan(50 / 2)
|
function getCameraMatrixPersp()
internal
pure
returns (int256[4][4][2] memory)
{
int256 n = 500;
int256 f = 501;
int256[4][4] memory cameraMatrixNum = [
[int256(2145), 0, 0, 0],
[int256(0), 2145, 0, 0],
[int256(0), 0, f, -f * n],
[int256(0), 0, 1, 0]
];
int256[4][4] memory cameraMatrixDen = [
[int256(1000), 1, 1, 1],
[int256(1), 1000, 1, 1],
[int256(1), 1, f - n, f - n],
[int256(1), 1, 1, 1]
];
int256[4][4][2] memory cameraMatrix = [
cameraMatrixNum,
cameraMatrixDen
];
return cameraMatrix;
}
| 278,662 |
./partial_match/1/0x6894DD96d242bA513AD99836B7778dBF43b82F3f/sources/AnyswapV6ERC20.sol
|
Moves `value` AnyswapV6ERC20 token from account (`from`) to account (`to`) using allowance mechanism. `value` is then deducted from caller account's allowance, unless set to `type(uint256).max`. Emits {Approval} event to reflect reduced allowance `value` for caller account to spend from account (`from`), unless allowance is set to `type(uint256).max` Emits {Transfer} event. Returns boolean value indicating whether operation succeeded. Requirements: - `from` account must have at least `value` balance of AnyswapV6ERC20 token. - `from` account must have approved caller to spend at least `value` of AnyswapV6ERC20 token, unless `from` and caller are the same account.
|
function transferFrom(
address from,
address to,
uint256 value
) external override returns (bool) {
require(to != address(0) && to != address(this));
if (from != msg.sender) {
uint256 allowed = allowance[from][msg.sender];
if (allowed != type(uint256).max) {
require(
allowed >= value,
"AnyswapV6ERC20: request exceeds allowance"
);
uint256 reduced = allowed - value;
allowance[from][msg.sender] = reduced;
emit Approval(from, msg.sender, reduced);
}
}
uint256 balance = balanceOf[from];
require(
balance >= value,
"AnyswapV6ERC20: transfer amount exceeds balance"
);
balanceOf[from] = balance - value;
balanceOf[to] += value;
emit Transfer(from, to, value);
return true;
}
| 4,127,212 |
// SPDX-License-Identifier: MIT
pragma solidity ^0.6.11;
import "deps/@openzeppelin/contracts-upgradeable/token/ERC20/IERC20Upgradeable.sol";
import "deps/@openzeppelin/contracts-upgradeable/math/SafeMathUpgradeable.sol";
import "deps/@openzeppelin/contracts-upgradeable/utils/AddressUpgradeable.sol";
import "deps/@openzeppelin/contracts-upgradeable/token/ERC20/SafeERC20Upgradeable.sol";
import "deps/@openzeppelin/contracts-upgradeable/proxy/Initializable.sol";
import "interfaces/badger/IConverter.sol";
import "interfaces/badger/IOneSplitAudit.sol";
import "interfaces/badger/IStrategy.sol";
import "./SettAccessControl.sol";
contract Controller is SettAccessControl {
using SafeERC20Upgradeable for IERC20Upgradeable;
using AddressUpgradeable for address;
using SafeMathUpgradeable for uint256;
address public onesplit;
address public rewards;
mapping(address => address) public vaults;
mapping(address => address) public strategies;
mapping(address => mapping(address => address)) public converters;
mapping(address => mapping(address => bool)) public approvedStrategies;
uint256 public split = 500;
uint256 public constant max = 10000;
/// @param _governance Can take any permissioned action within the Controller, with the exception of Vault helper functions
/// @param _strategist Can configure new Vaults, choose strategies among those approved by governance, and call operations involving non-core tokens
/// @param _keeper An extra address that can call earn() to deposit tokens from a Sett into the associated active Strategy. Designed for use by a trusted bot in leiu of having this function publically callable.
/// @param _rewards The recipient of standard fees (such as performance and withdrawal fees) from Strategies
function initialize(
address _governance,
address _strategist,
address _keeper,
address _rewards
) public initializer {
governance = _governance;
strategist = _strategist;
keeper = _keeper;
rewards = _rewards;
onesplit = address(0x50FDA034C0Ce7a8f7EFDAebDA7Aa7cA21CC1267e);
}
// ===== Modifiers =====
/// @notice The Sett for a given token or any of the permissioned roles can call earn() to deposit accumulated deposit funds from the Sett to the active Strategy
function _onlyApprovedForWant(address want) internal view {
require(msg.sender == vaults[want] || msg.sender == keeper || msg.sender == strategist || msg.sender == governance, "!authorized");
}
// ===== View Functions =====
/// @notice Get the balance of the given tokens' current strategy of that token.
function balanceOf(address _token) external view returns (uint256) {
return IStrategy(strategies[_token]).balanceOf();
}
function getExpectedReturn(
address _strategy,
address _token,
uint256 parts
) public view returns (uint256 expected) {
uint256 _balance = IERC20Upgradeable(_token).balanceOf(_strategy);
address _want = IStrategy(_strategy).want();
(expected, ) = IOneSplitAudit(onesplit).getExpectedReturn(_token, _want, _balance, parts, 0);
}
// ===== Permissioned Actions: Governance Only =====
/// @notice Approve the given address as a Strategy for a want. The Strategist can freely switch between approved stratgies for a token.
function approveStrategy(address _token, address _strategy) public {
_onlyGovernance();
approvedStrategies[_token][_strategy] = true;
}
/// @notice Revoke approval for the given address as a Strategy for a want.
function revokeStrategy(address _token, address _strategy) public {
_onlyGovernance();
approvedStrategies[_token][_strategy] = false;
}
/// @notice Change the recipient of rewards for standard fees from Strategies
function setRewards(address _rewards) public {
_onlyGovernance();
rewards = _rewards;
}
function setSplit(uint256 _split) public {
_onlyGovernance();
split = _split;
}
/// @notice Change the oneSplit contract, which is used in conversion of non-core strategy rewards
function setOneSplit(address _onesplit) public {
_onlyGovernance();
onesplit = _onesplit;
}
// ===== Permissioned Actions: Governance or Strategist =====
/// @notice Set the Vault (aka Sett) for a given want
/// @notice The vault can only be set once
function setVault(address _token, address _vault) public {
_onlyGovernanceOrStrategist();
require(vaults[_token] == address(0), "vault");
vaults[_token] = _vault;
}
/// @notice Migrate assets from existing strategy to a new strategy.
/// @notice The new strategy must have been previously approved by governance.
/// @notice Strategist or governance can freely switch between approved strategies
function setStrategy(address _token, address _strategy) public {
_onlyGovernanceOrStrategist();
require(approvedStrategies[_token][_strategy] == true, "!approved");
address _current = strategies[_token];
if (_current != address(0)) {
IStrategy(_current).withdrawAll();
}
strategies[_token] = _strategy;
}
/// @notice Set the contract used to convert between two given assets
function setConverter(
address _input,
address _output,
address _converter
) public {
_onlyGovernanceOrStrategist();
converters[_input][_output] = _converter;
}
/// @notice Withdraw the entire balance of a token from that tokens' current strategy.
/// @notice Does not trigger a withdrawal fee.
/// @notice Entire balance will be sent to corresponding Sett.
function withdrawAll(address _token) public {
_onlyGovernanceOrStrategist();
IStrategy(strategies[_token]).withdrawAll();
}
/// @dev Transfer an amount of the specified token from the controller to the sender.
/// @dev Token balance are never meant to exist in the controller, this is purely a safeguard.
function inCaseTokensGetStuck(address _token, uint256 _amount) public {
_onlyGovernanceOrStrategist();
IERC20Upgradeable(_token).safeTransfer(msg.sender, _amount);
}
/// @dev Transfer an amount of the specified token from the controller to the sender.
/// @dev Token balance are never meant to exist in the controller, this is purely a safeguard.
function inCaseStrategyTokenGetStuck(address _strategy, address _token) public {
_onlyGovernanceOrStrategist();
IStrategy(_strategy).withdrawOther(_token);
}
// ==== Permissioned Actions: Only Approved Actors =====
/// @notice Deposit given token to strategy, converting it to the strategies' want first (if required).
/// @dev Only the associated vault, or permissioned actors can call this function (keeper, strategist, governance)
/// @param _token Token to deposit (will be converted to want by converter). If no converter is registered, the transaction will revert.
/// @param _amount Amount of token to deposit
function earn(address _token, uint256 _amount) public {
address _strategy = strategies[_token];
address _want = IStrategy(_strategy).want();
_onlyApprovedForWant(_want);
if (_want != _token) {
address converter = converters[_token][_want];
IERC20Upgradeable(_token).safeTransfer(converter, _amount);
_amount = IConverter(converter).convert(_strategy);
IERC20Upgradeable(_want).safeTransfer(_strategy, _amount);
} else {
IERC20Upgradeable(_token).safeTransfer(_strategy, _amount);
}
IStrategy(_strategy).deposit();
}
// ===== Permissioned Actions: Only Associated Vault =====
/// @notice Wtihdraw a given token from it's corresponding strategy
/// @notice Only the associated vault can call, in response to a user withdrawal request
function withdraw(address _token, uint256 _amount) public {
require(msg.sender == vaults[_token], "!vault");
IStrategy(strategies[_token]).withdraw(_amount);
}
}
|
Set the Vault (aka Sett) for a given want The vault can only be set once
|
function setVault(address _token, address _vault) public {
_onlyGovernanceOrStrategist();
require(vaults[_token] == address(0), "vault");
vaults[_token] = _vault;
}
| 5,465,334 |
// SPDX-License-Identifier: Apache-2.0
pragma solidity ^0.8.0;
import "@gif-interface/contracts/Product.sol";
import "./FireOracle.sol";
contract FireInsurance is Product {
// constants
bytes32 public constant VERSION = "0.0.1";
bytes32 public constant POLICY_FLOW = "PolicyFlowDefault";
uint256 public constant PAYOUT_FACTOR_MEDIUM = 5;
uint256 public constant PAYOUT_FACTOR_LARGE = 100;
string public constant CALLBACK_METHOD_NAME = "oracleCallback";
// variables
uint256 public fireOracleId;
uint256 public uniqueIndex;
mapping(string => bool) public activePolicy;
// events
event LogFirePolicyCreated(address policyHolder, string objectName, bytes32 policyId);
event LogFirePolicyExpired(string objectName, bytes32 policyId);
event LogFireClaimConfirmed(bytes32 policyId, uint256 claimId, uint256 payoutId, uint256 payoutAmount);
event LogFirePayoutExecuted(bytes32 policyId, uint256 claimId, uint256 payoutId, uint256 payoutAmount);
// functions
constructor(
address gifProductService,
bytes32 productName,
uint256 oracleId
)
Product(gifProductService, productName, POLICY_FLOW)
{
fireOracleId = oracleId;
}
function deposit() public payable {}
function withdraw(uint256 amount) external onlyOwner {
require(amount <= address(this).balance);
address payable receiver;
receiver = payable(owner());
receiver.transfer(amount);
}
function applyForPolicy(string calldata objectName)
external
payable
returns (bytes32 policyId, uint256 requestId)
{
address payable policyHolder = payable(msg.sender);
uint256 premium = msg.value;
// Validate input parameters
require(premium > 0, "ERROR:FI-001:INVALID_PREMIUM");
require(PAYOUT_FACTOR_MEDIUM * premium < address(this).balance, "ERROR:FI-002:INSUFFICIENT_CAPITAL");
require(!activePolicy[objectName], "ERROR:FI-003:ACTIVE_POLICY_EXISTS");
// Create new ID for this policy
uniqueIndex++;
policyId = keccak256(abi.encode(productId, policyHolder, objectName, uniqueIndex));
// Create and underwrite new application
_newApplication(policyId, abi.encode(policyHolder, objectName, premium));
_underwrite(policyId);
// Update activ state for object
activePolicy[objectName] = true;
// trigger fire observation for object id via oracle call
requestId = _request(
policyId,
abi.encode(objectName),
CALLBACK_METHOD_NAME,
fireOracleId
);
emit LogFirePolicyCreated(policyHolder, objectName, policyId);
}
function expirePolicy(bytes32 policyId) external {
// Get policy data
(address payable policyHolder, string memory objectName, uint256 premium) = abi.decode(
_getApplicationData(policyId), (address, string, uint256));
// Validate input parameter
require(premium > 0, "ERROR:FI-004:NON_EXISTING_POLICY");
require(activePolicy[objectName], "ERROR:FI-005:EXPIRED_POLICY");
_expire(policyId);
activePolicy[objectName] = false;
emit LogFirePolicyExpired(objectName, policyId);
}
function oracleCallback(uint256 requestId, bytes32 policyId, bytes calldata response)
external
onlyOracle
{
// Get policy data for oracle response
(address payable policyHolder, string memory objectName, uint256 premium) = abi.decode(
_getApplicationData(policyId), (address, string, uint256));
// Validate input parameter
require(activePolicy[objectName], "ERROR:FI-006:EXPIRED_POLICY");
// Get oracle response data
(bytes1 fireCategory) = abi.decode(response, (bytes1));
// Claim handling based on reponse to greeting provided by oracle
_handleClaim(policyId, policyHolder, premium, fireCategory);
}
function _handleClaim(
bytes32 policyId,
address payable policyHolder,
uint256 premium,
bytes1 fireCategory
)
internal
{
uint256 payoutAmount = _calculatePayoutAmount(premium, fireCategory);
// Ensure available capital
require(payoutAmount < address(this).balance, "ERROR:FI-007:INSOLVENT_PRODUCT");
// no claims handling for payouts == 0
uint256 claimId = _newClaim(policyId, abi.encode(payoutAmount));
uint256 payoutId = _confirmClaim(policyId, claimId, abi.encode(payoutAmount));
emit LogFireClaimConfirmed(policyId, claimId, payoutId, payoutAmount);
if (payoutAmount > 0) {
_payout(policyId, payoutId, true, abi.encode(payoutAmount));
// actual transfer of funds for payout of claim
policyHolder.transfer(payoutAmount);
emit LogFirePayoutExecuted(policyId, claimId, payoutId, payoutAmount);
}
}
function _calculatePayoutAmount(uint256 premium, bytes1 fireCategory)
internal
pure
returns(uint256 payoutAmount)
{
if (fireCategory == 'M') {
payoutAmount = PAYOUT_FACTOR_MEDIUM * premium;
} else if (fireCategory == 'L') {
payoutAmount = PAYOUT_FACTOR_LARGE * premium;
} else {
// small fires considered below deductible, no payout
payoutAmount = 0;
}
}
}
|
small fires considered below deductible, no payout
|
function _calculatePayoutAmount(uint256 premium, bytes1 fireCategory)
internal
pure
returns(uint256 payoutAmount)
{
if (fireCategory == 'M') {
payoutAmount = PAYOUT_FACTOR_MEDIUM * premium;
payoutAmount = PAYOUT_FACTOR_LARGE * premium;
payoutAmount = 0;
}
}
| 12,760,569 |
./full_match/1/0x8c0792Bfee67c80f0E7D4A2c5808edBC9af85e6F/sources/contracts/lib/ExitPausable.sol
|
Returns to normal state. Requirements: - The contract must be exitPaused./
|
function _exitUnpause() internal virtual whenExitPaused {
_exitPaused = false;
emit ExitUnpaused(_msgSender());
}
| 16,587,209 |
./partial_match/3/0x1B0E0eCa53FB8EbFcBc6071d081961A37628Ca83/sources/Betting.sol
|
Cancel a bet, only by one of the admins. _id the bet id./Bet storage _bet = bets[_id]; refund betters
|
function cancelBet(uint256 _id) public onlyAdmins {
require(_id < betsCount, 'Wrong bet id');
uint256 length = betters[_id].length;
for (uint256 bind = 0; bind < length; bind++){
if(betters[_id][bind].bet_id == _id){
uint256 _amount = betters[_id][bind].amount;
if (bets[bind].tokenAddress == 0x0000000000000000000000000000000000000000){
admin.transfer(minBetETH);
(betters[_id][bind].better).transfer(_amount.sub(minBetETH));
erc20Balances[admin][bets[_id].tokenAddress] = erc20Balances[admin][bets[_id].tokenAddress].add(minBetERC20[bets[_id].tokenAddress]);
erc20Balances[betters[_id][bind].better][bets[_id].tokenAddress] = erc20Balances[betters[_id][bind].better][bets[_id].tokenAddress].add(_amount).sub(minBetERC20[bets[_id].tokenAddress]);
}
}
}
}
| 5,189,670 |
//SPDX-License-Identifier: MIT
pragma solidity ^0.8.4;
import "hardhat/console.sol";
import "@chainlink/contracts/src/v0.8/interfaces/AggregatorV3Interface.sol";
import "@openzeppelin/contracts/token/ERC721/extensions/ERC721Enumerable.sol";
import "./BullsToTheMoonInterface.sol";
/**
* @notice ENS registry to get chainlink resolver
*/
interface ENS {
function resolver(bytes32) external view returns (Resolver);
}
/**
* @notice Chainlink resolver to get price feed proxy
*/
interface Resolver {
function addr(bytes32) external view returns (address);
}
/**
* @title Bulls (dynamic NFTs) that grow with rising price
* @author Justa Liang
*/
contract BullsToTheMoon is ERC721Enumerable, BullsToTheMoonInterface {
/// @notice Counter of bullId
uint public counter;
/// @notice ENS interface (fixed address)
ENS public ens;
/// @dev Bull's state
struct Bull {
address proxy; // which proxy of Chainlink price feed
bool closed; // position closed
int latestPrice; // latest updated price from Chainlink
int roi; // return on investment
}
/// @dev Bull's profile for viewing
struct BullProfile {
address proxy;
bool closed;
int latestPrice;
int roi;
string uri;
}
/// @dev Bull's state stored on-chain
mapping(uint => Bull) public bullStateOf;
/// @notice Emit when a bull's state changes
event BullState(
uint indexed bullId,
address indexed proxy,
bool indexed closed,
int latestPrice,
int roi
);
/**
* @dev Set name, symbol, and addresses of interactive contracts
*/
constructor(address ensRegistryAddr)
ERC721("BullsToTheMoon", "B2M")
{
counter = 0;
ens = ENS(ensRegistryAddr);
}
/**
* @dev Check the owner
*/
modifier checkOwner(uint bullId) {
require(
_isApprovedOrOwner(_msgSender(), bullId),
"wrong owner"
);
_;
}
/**
* @notice See ../BullsToTheMoonInterface.sol
*/
function open(uint bullId) override external checkOwner(bullId) {
Bull storage target = bullStateOf[bullId];
require(
target.closed,
"bull already opened"
);
// get current price
AggregatorV3Interface pricefeed = AggregatorV3Interface(target.proxy);
(,int currPrice,,,) = pricefeed.latestRoundData();
// update on-chain data
target.latestPrice = currPrice;
target.closed = false;
// emit bull state
emit BullState(bullId, target.proxy, false, currPrice, target.roi);
}
/**
* @notice See ../BullsToTheMoonInterface.sol
*/
function close(uint bullId) override external checkOwner(bullId) {
Bull storage target = bullStateOf[bullId];
require(
!target.closed,
"bull already closed"
);
// get current price
AggregatorV3Interface pricefeed = AggregatorV3Interface(target.proxy);
(,int currPrice,,,) = pricefeed.latestRoundData();
// update on-chain data
target.roi = currPrice*(10000+target.roi)/target.latestPrice-10000;
target.closed = true;
// emit bull state
emit BullState(bullId, target.proxy, true, currPrice, target.roi);
}
/**
* @notice See ../BullsToTheMoonInterface.sol
*/
function breed(bytes32 namehash) override external returns (uint) {
address proxyAddr = _resolve(namehash);
require(
proxyAddr != address(0),
"invalid proxy"
);
// get current price
AggregatorV3Interface pricefeed = AggregatorV3Interface(proxyAddr);
(,int currPrice,,,) = pricefeed.latestRoundData();
// mint bull and store its state on chain
uint newId = counter;
_safeMint(_msgSender(), newId);
bullStateOf[newId] = Bull(proxyAddr, false, currPrice, 0);
emit BullState(newId, proxyAddr, false, currPrice, 0);
counter++;
return newId;
}
/**
* @notice See ../BullsToTheMoonInterface.sol
*/
function regretOpen(uint bullId) override external checkOwner(bullId) {
}
/**
* @notice See ../BullsToTheMoonInterface.sol
*/
function regretClose(uint bullId) override external checkOwner(bullId) {
}
/**
* @notice See ../BullsToTheMoonInterface.sol
*/
function occupy(uint bullId, uint fieldId) override external checkOwner(bullId) {
}
/**
* @notice See ../BullsToTheMoonInterface.sol
*/
function vote(uint proposalId, uint fieldCount) override external {
}
/**
* @notice See ../BullsToTheMoonInterface.sol
*/
function propose(string memory proposedBaseURI) override external {
}
/**
* @notice See ../BullsToTheMoonInterface.sol
*/
function startVote() override external {
}
/**
* @notice See ../BullsToTheMoonInterface.sol
*/
function endVote() override external {
}
/**
* @dev Resolve ENS-namehash to Chainlink price feed proxy
*/
function _resolve(bytes32 node) internal view returns (address) {
Resolver resolver = ens.resolver(node);
return resolver.addr(node);
}
}
|
See ../BullsToTheMoonInterface.sol/
|
function propose(string memory proposedBaseURI) override external {
}
| 926,547 |
// File: @openzeppelin/contracts-ethereum-package/contracts/math/SafeMath.sol
pragma solidity ^0.6.0;
/**
* @dev Wrappers over Solidity's arithmetic operations with added overflow
* checks.
*
* Arithmetic operations in Solidity wrap on overflow. This can easily result
* in bugs, because programmers usually assume that an overflow raises an
* error, which is the standard behavior in high level programming languages.
* `SafeMath` restores this intuition by reverting the transaction when an
* operation overflows.
*
* Using this library instead of the unchecked operations eliminates an entire
* class of bugs, so it's recommended to use it always.
*/
library SafeMath {
/**
* @dev Returns the addition of two unsigned integers, reverting on
* overflow.
*
* Counterpart to Solidity's `+` operator.
*
* Requirements:
* - Addition cannot overflow.
*/
function add(uint256 a, uint256 b) internal pure returns (uint256) {
uint256 c = a + b;
require(c >= a, "SafeMath: addition overflow");
return c;
}
/**
* @dev Returns the subtraction of two unsigned integers, reverting on
* overflow (when the result is negative).
*
* Counterpart to Solidity's `-` operator.
*
* Requirements:
* - Subtraction cannot overflow.
*/
function sub(uint256 a, uint256 b) internal pure returns (uint256) {
return sub(a, b, "SafeMath: subtraction overflow");
}
/**
* @dev Returns the subtraction of two unsigned integers, reverting with custom message on
* overflow (when the result is negative).
*
* Counterpart to Solidity's `-` operator.
*
* Requirements:
* - Subtraction cannot overflow.
*/
function sub(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
require(b <= a, errorMessage);
uint256 c = a - b;
return c;
}
/**
* @dev Returns the multiplication of two unsigned integers, reverting on
* overflow.
*
* Counterpart to Solidity's `*` operator.
*
* Requirements:
* - Multiplication cannot overflow.
*/
function mul(uint256 a, uint256 b) internal pure returns (uint256) {
// Gas optimization: this is cheaper than requiring 'a' not being zero, but the
// benefit is lost if 'b' is also tested.
// See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522
if (a == 0) {
return 0;
}
uint256 c = a * b;
require(c / a == b, "SafeMath: multiplication overflow");
return c;
}
/**
* @dev Returns the integer division of two unsigned integers. Reverts on
* division by zero. The result is rounded towards zero.
*
* Counterpart to Solidity's `/` operator. Note: this function uses a
* `revert` opcode (which leaves remaining gas untouched) while Solidity
* uses an invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
* - The divisor cannot be zero.
*/
function div(uint256 a, uint256 b) internal pure returns (uint256) {
return div(a, b, "SafeMath: division by zero");
}
/**
* @dev Returns the integer division of two unsigned integers. Reverts with custom message on
* division by zero. The result is rounded towards zero.
*
* Counterpart to Solidity's `/` operator. Note: this function uses a
* `revert` opcode (which leaves remaining gas untouched) while Solidity
* uses an invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
* - The divisor cannot be zero.
*/
function div(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
// Solidity only automatically asserts when dividing by 0
require(b > 0, errorMessage);
uint256 c = a / b;
// assert(a == b * c + a % b); // There is no case in which this doesn't hold
return c;
}
/**
* @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo),
* Reverts when dividing by zero.
*
* Counterpart to Solidity's `%` operator. This function uses a `revert`
* opcode (which leaves remaining gas untouched) while Solidity uses an
* invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
* - The divisor cannot be zero.
*/
function mod(uint256 a, uint256 b) internal pure returns (uint256) {
return mod(a, b, "SafeMath: modulo by zero");
}
/**
* @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo),
* Reverts with custom message when dividing by zero.
*
* Counterpart to Solidity's `%` operator. This function uses a `revert`
* opcode (which leaves remaining gas untouched) while Solidity uses an
* invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
* - The divisor cannot be zero.
*/
function mod(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
require(b != 0, errorMessage);
return a % b;
}
}
// File: @openzeppelin/contracts-ethereum-package/contracts/Initializable.sol
pragma solidity >=0.4.24 <0.7.0;
/**
* @title Initializable
*
* @dev Helper contract to support initializer functions. To use it, replace
* the constructor with a function that has the `initializer` modifier.
* WARNING: Unlike constructors, initializer functions must be manually
* invoked. This applies both to deploying an Initializable contract, as well
* as extending an Initializable contract via inheritance.
* WARNING: When used with inheritance, manual care must be taken to not invoke
* a parent initializer twice, or ensure that all initializers are idempotent,
* because this is not dealt with automatically as with constructors.
*/
contract Initializable {
/**
* @dev Indicates that the contract has been initialized.
*/
bool private initialized;
/**
* @dev Indicates that the contract is in the process of being initialized.
*/
bool private initializing;
/**
* @dev Modifier to use in the initializer function of a contract.
*/
modifier initializer() {
require(initializing || isConstructor() || !initialized, "Contract instance has already been initialized");
bool isTopLevelCall = !initializing;
if (isTopLevelCall) {
initializing = true;
initialized = true;
}
_;
if (isTopLevelCall) {
initializing = false;
}
}
/// @dev Returns true if and only if the function is running in the constructor
function isConstructor() private view returns (bool) {
// extcodesize checks the size of the code stored in an address, and
// address returns the current address. Since the code is still not
// deployed when running a constructor, any checks on its code size will
// yield zero, making it an effective way to detect if a contract is
// under construction or not.
address self = address(this);
uint256 cs;
assembly { cs := extcodesize(self) }
return cs == 0;
}
// Reserved storage space to allow for layout changes in the future.
uint256[50] private ______gap;
}
// File: @openzeppelin/contracts-ethereum-package/contracts/GSN/Context.sol
pragma solidity ^0.6.0;
/*
* @dev Provides information about the current execution context, including the
* sender of the transaction and its data. While these are generally available
* via msg.sender and msg.data, they should not be accessed in such a direct
* manner, since when dealing with GSN meta-transactions the account sending and
* paying for execution may not be the actual sender (as far as an application
* is concerned).
*
* This contract is only required for intermediate, library-like contracts.
*/
contract ContextUpgradeSafe is Initializable {
// Empty internal constructor, to prevent people from mistakenly deploying
// an instance of this contract, which should be used via inheritance.
function __Context_init() internal initializer {
__Context_init_unchained();
}
function __Context_init_unchained() internal initializer {
}
function _msgSender() internal view virtual returns (address payable) {
return msg.sender;
}
function _msgData() internal view virtual returns (bytes memory) {
this; // silence state mutability warning without generating bytecode - see https://github.com/ethereum/solidity/issues/2691
return msg.data;
}
uint256[50] private __gap;
}
// File: @openzeppelin/contracts-ethereum-package/contracts/token/ERC20/IERC20.sol
pragma solidity ^0.6.0;
/**
* @dev Interface of the ERC20 standard as defined in the EIP.
*/
interface IERC20 {
/**
* @dev Returns the amount of tokens in existence.
*/
function totalSupply() external view returns (uint256);
/**
* @dev Returns the amount of tokens owned by `account`.
*/
function balanceOf(address account) external view returns (uint256);
/**
* @dev Moves `amount` tokens from the caller's account to `recipient`.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/
function transfer(address recipient, uint256 amount) external returns (bool);
/**
* @dev Returns the remaining number of tokens that `spender` will be
* allowed to spend on behalf of `owner` through {transferFrom}. This is
* zero by default.
*
* This value changes when {approve} or {transferFrom} are called.
*/
function allowance(address owner, address spender) external view returns (uint256);
/**
* @dev Sets `amount` as the allowance of `spender` over the caller's tokens.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* IMPORTANT: 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
*
* Emits an {Approval} event.
*/
function approve(address spender, uint256 amount) external returns (bool);
/**
* @dev Moves `amount` tokens from `sender` to `recipient` using the
* allowance mechanism. `amount` is then deducted from the caller's
* allowance.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/
function transferFrom(address sender, address recipient, uint256 amount) external returns (bool);
/**
* @dev Emitted when `value` tokens are moved from one account (`from`) to
* another (`to`).
*
* Note that `value` may be zero.
*/
event Transfer(address indexed from, address indexed to, uint256 value);
/**
* @dev Emitted when the allowance of a `spender` for an `owner` is set by
* a call to {approve}. `value` is the new allowance.
*/
event Approval(address indexed owner, address indexed spender, uint256 value);
}
// File: @openzeppelin/contracts-ethereum-package/contracts/utils/Address.sol
pragma solidity ^0.6.2;
/**
* @dev Collection of functions related to the address type
*/
library Address {
/**
* @dev Returns true if `account` is a contract.
*
* [IMPORTANT]
* ====
* It is unsafe to assume that an address for which this function returns
* false is an externally-owned account (EOA) and not a contract.
*
* Among others, `isContract` will return false for the following
* types of addresses:
*
* - an externally-owned account
* - a contract in construction
* - an address where a contract will be created
* - an address where a contract lived, but was destroyed
* ====
*/
function isContract(address account) internal view returns (bool) {
// According to EIP-1052, 0x0 is the value returned for not-yet created accounts
// and 0xc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470 is returned
// for accounts without code, i.e. `keccak256('')`
bytes32 codehash;
bytes32 accountHash = 0xc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470;
// solhint-disable-next-line no-inline-assembly
assembly { codehash := extcodehash(account) }
return (codehash != accountHash && codehash != 0x0);
}
/**
* @dev Replacement for Solidity's `transfer`: sends `amount` wei to
* `recipient`, forwarding all available gas and reverting on errors.
*
* https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost
* of certain opcodes, possibly making contracts go over the 2300 gas limit
* imposed by `transfer`, making them unable to receive funds via
* `transfer`. {sendValue} removes this limitation.
*
* https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more].
*
* IMPORTANT: because control is transferred to `recipient`, care must be
* taken to not create reentrancy vulnerabilities. Consider using
* {ReentrancyGuard} or the
* https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern].
*/
function sendValue(address payable recipient, uint256 amount) internal {
require(address(this).balance >= amount, "Address: insufficient balance");
// solhint-disable-next-line avoid-low-level-calls, avoid-call-value
(bool success, ) = recipient.call{ value: amount }("");
require(success, "Address: unable to send value, recipient may have reverted");
}
}
// File: @openzeppelin/contracts-ethereum-package/contracts/token/ERC20/ERC20.sol
pragma solidity ^0.6.0;
/**
* @dev Implementation of the {IERC20} interface.
*
* This implementation is agnostic to the way tokens are created. This means
* that a supply mechanism has to be added in a derived contract using {_mint}.
* For a generic mechanism see {ERC20MinterPauser}.
*
* TIP: For a detailed writeup see our guide
* https://forum.zeppelin.solutions/t/how-to-implement-erc20-supply-mechanisms/226[How
* to implement supply mechanisms].
*
* We have followed general OpenZeppelin guidelines: functions revert instead
* of returning `false` on failure. This behavior is nonetheless conventional
* and does not conflict with the expectations of ERC20 applications.
*
* Additionally, an {Approval} event is emitted on calls to {transferFrom}.
* This allows applications to reconstruct the allowance for all accounts just
* by listening to said events. Other implementations of the EIP may not emit
* these events, as it isn't required by the specification.
*
* Finally, the non-standard {decreaseAllowance} and {increaseAllowance}
* functions have been added to mitigate the well-known issues around setting
* allowances. See {IERC20-approve}.
*/
contract ERC20UpgradeSafe is Initializable, ContextUpgradeSafe, IERC20 {
using SafeMath for uint256;
using Address for address;
mapping (address => uint256) private _balances;
mapping (address => mapping (address => uint256)) private _allowances;
uint256 private _totalSupply;
string private _name;
string private _symbol;
uint8 private _decimals;
/**
* @dev Sets the values for {name} and {symbol}, initializes {decimals} with
* a default value of 18.
*
* To select a different value for {decimals}, use {_setupDecimals}.
*
* All three of these values are immutable: they can only be set once during
* construction.
*/
function __ERC20_init(string memory name, string memory symbol) internal initializer {
__Context_init_unchained();
__ERC20_init_unchained(name, symbol);
}
function __ERC20_init_unchained(string memory name, string memory symbol) internal initializer {
_name = name;
_symbol = symbol;
_decimals = 18;
}
/**
* @dev Returns the name of the token.
*/
function name() public view returns (string memory) {
return _name;
}
/**
* @dev Returns the symbol of the token, usually a shorter version of the
* name.
*/
function symbol() public view returns (string memory) {
return _symbol;
}
/**
* @dev Returns the number of decimals used to get its user representation.
* For example, if `decimals` equals `2`, a balance of `505` tokens should
* be displayed to a user as `5,05` (`505 / 10 ** 2`).
*
* Tokens usually opt for a value of 18, imitating the relationship between
* Ether and Wei. This is the value {ERC20} uses, unless {_setupDecimals} is
* called.
*
* NOTE: This information is only used for _display_ purposes: it in
* no way affects any of the arithmetic of the contract, including
* {IERC20-balanceOf} and {IERC20-transfer}.
*/
function decimals() public view returns (uint8) {
return _decimals;
}
/**
* @dev See {IERC20-totalSupply}.
*/
function totalSupply() public view virtual override returns (uint256) {
return _totalSupply;
}
/**
* @dev See {IERC20-balanceOf}.
*/
function balanceOf(address account) public view virtual override returns (uint256) {
return _balances[account];
}
/**
* @dev See {IERC20-transfer}.
*
* Requirements:
*
* - `recipient` cannot be the zero address.
* - the caller must have a balance of at least `amount`.
*/
function transfer(address recipient, uint256 amount) public virtual override returns (bool) {
_transfer(_msgSender(), recipient, amount);
return true;
}
/**
* @dev See {IERC20-allowance}.
*/
function allowance(address owner, address spender) public view virtual override returns (uint256) {
return _allowances[owner][spender];
}
/**
* @dev See {IERC20-approve}.
*
* Requirements:
*
* - `spender` cannot be the zero address.
*/
function approve(address spender, uint256 amount) public virtual override returns (bool) {
_approve(_msgSender(), spender, amount);
return true;
}
/**
* @dev See {IERC20-transferFrom}.
*
* Emits an {Approval} event indicating the updated allowance. This is not
* required by the EIP. See the note at the beginning of {ERC20};
*
* Requirements:
* - `sender` and `recipient` cannot be the zero address.
* - `sender` must have a balance of at least `amount`.
* - the caller must have allowance for ``sender``'s tokens of at least
* `amount`.
*/
function transferFrom(address sender, address recipient, uint256 amount) public virtual override returns (bool) {
_transfer(sender, recipient, amount);
_approve(sender, _msgSender(), _allowances[sender][_msgSender()].sub(amount, "ERC20: transfer amount exceeds allowance"));
return true;
}
/**
* @dev Atomically increases the allowance granted to `spender` by the caller.
*
* This is an alternative to {approve} that can be used as a mitigation for
* problems described in {IERC20-approve}.
*
* Emits an {Approval} event indicating the updated allowance.
*
* Requirements:
*
* - `spender` cannot be the zero address.
*/
function increaseAllowance(address spender, uint256 addedValue) public virtual returns (bool) {
_approve(_msgSender(), spender, _allowances[_msgSender()][spender].add(addedValue));
return true;
}
/**
* @dev Atomically decreases the allowance granted to `spender` by the caller.
*
* This is an alternative to {approve} that can be used as a mitigation for
* problems described in {IERC20-approve}.
*
* Emits an {Approval} event indicating the updated allowance.
*
* Requirements:
*
* - `spender` cannot be the zero address.
* - `spender` must have allowance for the caller of at least
* `subtractedValue`.
*/
function decreaseAllowance(address spender, uint256 subtractedValue) public virtual returns (bool) {
_approve(_msgSender(), spender, _allowances[_msgSender()][spender].sub(subtractedValue, "ERC20: decreased allowance below zero"));
return true;
}
/**
* @dev 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);
}
/** @dev Creates `amount` tokens and assigns them to `account`, increasing
* the total supply.
*
* Emits a {Transfer} event with `from` set to the zero address.
*
* Requirements
*
* - `to` cannot be the zero address.
*/
function _mint(address account, uint256 amount) internal virtual {
require(account != address(0), "ERC20: mint to the zero address");
_beforeTokenTransfer(address(0), account, amount);
_totalSupply = _totalSupply.add(amount);
_balances[account] = _balances[account].add(amount);
emit Transfer(address(0), account, amount);
}
/**
* @dev Destroys `amount` tokens from `account`, reducing the
* total supply.
*
* Emits a {Transfer} event with `to` set to the zero address.
*
* Requirements
*
* - `account` cannot be the zero address.
* - `account` must have at least `amount` tokens.
*/
function _burn(address account, uint256 amount) internal virtual {
require(account != address(0), "ERC20: burn from the zero address");
_beforeTokenTransfer(account, address(0), amount);
_balances[account] = _balances[account].sub(amount, "ERC20: burn amount exceeds balance");
_totalSupply = _totalSupply.sub(amount);
emit Transfer(account, address(0), amount);
}
/**
* @dev Sets `amount` as the allowance of `spender` over the `owner`s tokens.
*
* This is internal function is equivalent to `approve`, and can be used to
* e.g. set automatic allowances for certain subsystems, etc.
*
* Emits an {Approval} event.
*
* Requirements:
*
* - `owner` cannot be the zero address.
* - `spender` cannot be the zero address.
*/
function _approve(address owner, address spender, uint256 amount) internal virtual {
require(owner != address(0), "ERC20: approve from the zero address");
require(spender != address(0), "ERC20: approve to the zero address");
_allowances[owner][spender] = amount;
emit Approval(owner, spender, amount);
}
/**
* @dev Sets {decimals} to a value other than the default one of 18.
*
* WARNING: This function should only be called from the constructor. Most
* applications that interact with token contracts will not expect
* {decimals} to ever change, and may work incorrectly if it does.
*/
function _setupDecimals(uint8 decimals_) internal {
_decimals = decimals_;
}
/**
* @dev Hook that is called before any transfer of tokens. This includes
* minting and burning.
*
* Calling conditions:
*
* - when `from` and `to` are both non-zero, `amount` of ``from``'s tokens
* will be to transferred to `to`.
* - when `from` is zero, `amount` tokens will be minted for `to`.
* - when `to` is zero, `amount` of ``from``'s tokens will be burned.
* - `from` and `to` are never both zero.
*
* To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks].
*/
function _beforeTokenTransfer(address from, address to, uint256 amount) internal virtual { }
uint256[44] private __gap;
}
// File: @openzeppelin/contracts-ethereum-package/contracts/token/ERC20/SafeERC20.sol
pragma solidity ^0.6.0;
/**
* @title SafeERC20
* @dev Wrappers around ERC20 operations that throw on failure (when the token
* contract returns false). Tokens that return no value (and instead revert or
* throw on failure) are also supported, non-reverting calls are assumed to be
* successful.
* To use this library you can add a `using SafeERC20 for ERC20;` statement to your contract,
* which allows you to call the safe operations as `token.safeTransfer(...)`, etc.
*/
library SafeERC20 {
using SafeMath for uint256;
using Address for address;
function safeTransfer(IERC20 token, address to, uint256 value) internal {
_callOptionalReturn(token, abi.encodeWithSelector(token.transfer.selector, to, value));
}
function safeTransferFrom(IERC20 token, address from, address to, uint256 value) internal {
_callOptionalReturn(token, abi.encodeWithSelector(token.transferFrom.selector, from, to, value));
}
function safeApprove(IERC20 token, address spender, uint256 value) internal {
// safeApprove should only be called when setting an initial allowance,
// or when resetting it to zero. To increase and decrease it, use
// 'safeIncreaseAllowance' and 'safeDecreaseAllowance'
// solhint-disable-next-line max-line-length
require((value == 0) || (token.allowance(address(this), spender) == 0),
"SafeERC20: approve from non-zero to non-zero allowance"
);
_callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, value));
}
function safeIncreaseAllowance(IERC20 token, address spender, uint256 value) internal {
uint256 newAllowance = token.allowance(address(this), spender).add(value);
_callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance));
}
function safeDecreaseAllowance(IERC20 token, address spender, uint256 value) internal {
uint256 newAllowance = token.allowance(address(this), spender).sub(value, "SafeERC20: decreased allowance below zero");
_callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance));
}
/**
* @dev Imitates a Solidity high-level call (i.e. a regular function call to a contract), relaxing the requirement
* on the return value: the return value is optional (but if data is returned, it must not be false).
* @param token The token targeted by the call.
* @param data The call data (encoded using abi.encode or one of its variants).
*/
function _callOptionalReturn(IERC20 token, bytes memory data) private {
// We need to perform a low level call here, to bypass Solidity's return data size checking mechanism, since
// we're implementing it ourselves.
// A Solidity high level call has three parts:
// 1. The target address is checked to verify it contains contract code
// 2. The call itself is made, and success asserted
// 3. The return value is decoded, which in turn checks the size of the returned data.
// solhint-disable-next-line max-line-length
require(address(token).isContract(), "SafeERC20: call to non-contract");
// solhint-disable-next-line avoid-low-level-calls
(bool success, bytes memory returndata) = address(token).call(data);
require(success, "SafeERC20: low-level call failed");
if (returndata.length > 0) { // Return data is optional
// solhint-disable-next-line max-line-length
require(abi.decode(returndata, (bool)), "SafeERC20: ERC20 operation did not succeed");
}
}
}
// File: @openzeppelin/contracts-ethereum-package/contracts/utils/ReentrancyGuard.sol
pragma solidity ^0.6.0;
/**
* @dev Contract module that helps prevent reentrant calls to a function.
*
* Inheriting from `ReentrancyGuard` will make the {nonReentrant} modifier
* available, which can be applied to functions to make sure there are no nested
* (reentrant) calls to them.
*
* Note that because there is a single `nonReentrant` guard, functions marked as
* `nonReentrant` may not call one another. This can be worked around by making
* those functions `private`, and then adding `external` `nonReentrant` entry
* points to them.
*
* TIP: If you would like to learn more about reentrancy and alternative ways
* to protect against it, check out our blog post
* https://blog.openzeppelin.com/reentrancy-after-istanbul/[Reentrancy After Istanbul].
*/
contract ReentrancyGuardUpgradeSafe is Initializable {
bool private _notEntered;
function __ReentrancyGuard_init() internal initializer {
__ReentrancyGuard_init_unchained();
}
function __ReentrancyGuard_init_unchained() internal initializer {
// Storing an initial non-zero value makes deployment a bit more
// expensive, but in exchange the refund on every call to nonReentrant
// will be lower in amount. Since refunds are capped to a percetange of
// the total transaction's gas, it is best to keep them low in cases
// like this one, to increase the likelihood of the full refund coming
// into effect.
_notEntered = true;
}
/**
* @dev Prevents a contract from calling itself, directly or indirectly.
* Calling a `nonReentrant` function from another `nonReentrant`
* function is not supported. It is possible to prevent this from happening
* by making the `nonReentrant` function external, and make it call a
* `private` function that does the actual work.
*/
modifier nonReentrant() {
// On the first call to nonReentrant, _notEntered will be true
require(_notEntered, "ReentrancyGuard: reentrant call");
// Any calls to nonReentrant after this point will fail
_notEntered = false;
_;
// By storing the original value once again, a refund is triggered (see
// https://eips.ethereum.org/EIPS/eip-2200)
_notEntered = true;
}
uint256[49] private __gap;
}
// File: @chainlink/contracts/src/v0.6/interfaces/AggregatorV3Interface.sol
pragma solidity >=0.6.0;
interface AggregatorV3Interface {
function decimals() external view returns (uint8);
function description() external view returns (string memory);
function version() external view returns (uint256);
// getRoundData and latestRoundData should both raise "No data present"
// if they do not have data to report, instead of returning unset values
// which could be misinterpreted as actual reported values.
function getRoundData(uint80 _roundId)
external
view
returns (
uint80 roundId,
int256 answer,
uint256 startedAt,
uint256 updatedAt,
uint80 answeredInRound
);
function latestRoundData()
external
view
returns (
uint80 roundId,
int256 answer,
uint256 startedAt,
uint256 updatedAt,
uint80 answeredInRound
);
}
// File: @openzeppelin/contracts-ethereum-package/contracts/access/Ownable.sol
pragma solidity ^0.6.0;
/**
* @dev Contract module which provides a basic access control mechanism, where
* there is an account (an owner) that can be granted exclusive access to
* specific functions.
*
* By default, the owner account will be the one that deploys the contract. This
* can later be changed with {transferOwnership}.
*
* This module is used through inheritance. It will make available the modifier
* `onlyOwner`, which can be applied to your functions to restrict their use to
* the owner.
*/
contract OwnableUpgradeSafe is Initializable, ContextUpgradeSafe {
address private _owner;
event OwnershipTransferred(address indexed previousOwner, address indexed newOwner);
/**
* @dev Initializes the contract setting the deployer as the initial owner.
*/
function __Ownable_init() internal initializer {
__Context_init_unchained();
__Ownable_init_unchained();
}
function __Ownable_init_unchained() internal initializer {
address msgSender = _msgSender();
_owner = msgSender;
emit OwnershipTransferred(address(0), msgSender);
}
/**
* @dev Returns the address of the current owner.
*/
function owner() public view returns (address) {
return _owner;
}
/**
* @dev Throws if called by any account other than the owner.
*/
modifier onlyOwner() {
require(_owner == _msgSender(), "Ownable: caller is not the owner");
_;
}
/**
* @dev Leaves the contract without owner. It will not be possible to call
* `onlyOwner` functions anymore. Can only be called by the current owner.
*
* NOTE: Renouncing ownership will leave the contract without an owner,
* thereby removing any functionality that is only available to the owner.
*/
function renounceOwnership() public virtual onlyOwner {
emit OwnershipTransferred(_owner, address(0));
_owner = address(0);
}
/**
* @dev Transfers ownership of the contract to a new account (`newOwner`).
* Can only be called by the current owner.
*/
function transferOwnership(address newOwner) public virtual onlyOwner {
require(newOwner != address(0), "Ownable: new owner is the zero address");
emit OwnershipTransferred(_owner, newOwner);
_owner = newOwner;
}
uint256[49] private __gap;
}
// File: contracts/gaia/usdf.sol
pragma solidity ^0.6.0;
interface TwapOracle {
function update() external;
function consult(address token, uint amountIn) external view returns (uint amountOut);
function changePeriod(uint256 seconds_) external;
}
interface IGaia {
function burn(address from, uint256 amount) external;
function mint(address to, uint256 amount) external;
}
contract USDf is ERC20UpgradeSafe, OwnableUpgradeSafe, ReentrancyGuardUpgradeSafe {
using SafeMath for uint256;
uint256 constant public MAX_RESERVE_RATIO = 100 * 10 ** 9;
uint256 private constant DECIMALS = 9;
uint256 public lastRefreshReserve;
uint256 public minimumRefreshTime;
uint256 public gaiaDecimals;
uint256 private constant MAX_SUPPLY = ~uint128(0);
uint256 public minimumReserveRate;
uint256 private _totalSupply;
uint256 public mintFee;
uint256 public withdrawFee;
uint256 public minimumDelay; // how long a user must wait between actions
uint256 public MIN_RESERVE_RATIO;
uint256 public reserveRatio;
address public gaia;
address public synthOracle;
address public gaiaOracle;
address public usdcAddress;
address[] collateralArray;
AggregatorV3Interface internal usdcPrice;
mapping(address => uint256) private _synthBalance;
mapping(address => uint256) private _lastAction;
mapping (address => mapping (address => uint256)) private _allowedSynth;
mapping (address => bool) public acceptedCollateral;
mapping (address => uint256) public collateralDecimals;
mapping (address => address) public collateralOracle;
mapping (address => bool) public seenCollateral;
mapping (address => uint256) public burnedSynth;
modifier validRecipient(address to) {
require(to != address(0x0));
require(to != address(this));
_;
}
modifier sync() {
if (_totalSupply > 0) {
updateOracles();
if (now - lastRefreshReserve >= minimumRefreshTime) {
TwapOracle(gaiaOracle).update();
TwapOracle(synthOracle).update();
if (getSynthOracle() > 1 * 10 ** 9) {
setReserveRatio(reserveRatio.sub(5 * 10 ** 8));
} else {
setReserveRatio(reserveRatio.add(5 * 10 ** 8));
}
lastRefreshReserve = now;
}
}
_;
}
event NewReserveRate(uint256 reserveRatio);
event Mint(address gaia, address receiver, address collateral, uint256 collateralAmount, uint256 gaiaAmount, uint256 synthAmount);
event Withdraw(address gaia, address receiver, address collateral, uint256 collateralAmount, uint256 gaiaAmount, uint256 synthAmount);
event NewMinimumRefreshTime(uint256 minimumRefreshTime);
event MintFee(uint256 fee_);
event WithdrawFee(uint256 fee_);
// constructor ============================================================
function initialize(address gaia_, uint256 gaiaDecimals_, address usdcAddress_, address usdcOracleChainLink_) public initializer {
OwnableUpgradeSafe.__Ownable_init();
ReentrancyGuardUpgradeSafe.__ReentrancyGuard_init();
ERC20UpgradeSafe.__ERC20_init('USDf', 'USDf');
ERC20UpgradeSafe._setupDecimals(9);
gaia = gaia_;
minimumRefreshTime = 3600 * 1; // 1 hours by default
minimumDelay = minimumRefreshTime; // minimum delay must >= minimum refresh time
gaiaDecimals = gaiaDecimals_;
usdcPrice = AggregatorV3Interface(usdcOracleChainLink_);
minimumReserveRate = 50 * 10 ** 9;
usdcAddress = usdcAddress_;
reserveRatio = 100 * 10 ** 9; // 100% reserve at first
_totalSupply = 0;
}
// public view functions ============================================================
function getCollateralByIndex(uint256 index_) external view returns (address) {
return collateralArray[index_];
}
function getCollateralUsd(address collateral_) public view returns (uint256) {
// price is $Y / USD (10 ** 8 decimals)
( , int price, , uint timeStamp, ) = usdcPrice.latestRoundData();
require(timeStamp > 0, "Rounds not complete");
return uint256(price).mul(10 ** 10).div((TwapOracle(collateralOracle[collateral_]).consult(usdcAddress, 10 ** 6)).mul(10 ** 9).div(10 ** collateralDecimals[collateral_]));
}
function globalCollateralValue() public view returns (uint256) {
uint256 totalCollateralUsd = 0;
for (uint i = 0; i < collateralArray.length; i++){
// Exclude null addresses
if (collateralArray[i] != address(0)){
totalCollateralUsd += IERC20(collateralArray[i]).balanceOf(address(this)).mul(10 ** 9).div(10 ** collateralDecimals[collateralArray[i]]).mul(getCollateralUsd(collateralArray[i])).div(10 ** 9); // add stablecoin balance
}
}
return totalCollateralUsd;
}
function usdfInfo() public view returns (uint256, uint256, uint256, uint256, uint256, uint256) {
return (
_totalSupply,
reserveRatio,
globalCollateralValue(),
mintFee,
withdrawFee,
minimumDelay
);
}
function totalSupply() public override view returns (uint256) {
return _totalSupply;
}
function balanceOf(address who) public override view returns (uint256) {
return _synthBalance[who];
}
function allowance(address owner_, address spender) public override view returns (uint256) {
return _allowedSynth[owner_][spender];
}
function getGaiaOracle() public view returns (uint256) {
uint256 gaiaTWAP = TwapOracle(gaiaOracle).consult(address(this), 1 * 10 ** 9);
uint256 usdfOraclePrice = getSynthOracle();
return uint256(usdfOraclePrice).mul(10 ** DECIMALS).div(gaiaTWAP);
}
function getSynthOracle() public view returns (uint256) {
uint256 synthTWAP = TwapOracle(synthOracle).consult(usdcAddress, 1 * 10 ** 6);
( , int price, , uint timeStamp, ) = usdcPrice.latestRoundData();
require(timeStamp > 0, "rounds not complete");
return uint256(price).mul(10).mul(10 ** DECIMALS).div(synthTWAP);
}
function consultSynthRatio(uint256 synthAmount, address collateral) public view returns (uint256, uint256) {
require(synthAmount != 0, "must use valid USDf amount");
require(seenCollateral[collateral], "must be seen collateral");
uint256 collateralAmount = synthAmount.mul(reserveRatio).div(MAX_RESERVE_RATIO).mul(10 ** collateralDecimals[collateral]).div(10 ** DECIMALS);
if (_totalSupply == 0) {
return (collateralAmount, 0);
} else {
collateralAmount = collateralAmount.mul(10 ** 9).div(getCollateralUsd(collateral)); // get real time price
uint256 gaiaUsd = getGaiaOracle();
uint256 synthPrice = getSynthOracle();
uint256 synthPart2 = synthAmount.mul(MAX_RESERVE_RATIO.sub(reserveRatio)).div(MAX_RESERVE_RATIO);
uint256 gaiaAmount = synthPart2.mul(synthPrice).div(gaiaUsd);
return (collateralAmount, gaiaAmount);
}
}
// public functions ============================================================
function updateOracles() public {
for (uint i = 0; i < collateralArray.length; i++) {
if (acceptedCollateral[collateralArray[i]]) TwapOracle(collateralOracle[collateralArray[i]]).update();
}
}
function transfer(address to, uint256 value) public override validRecipient(to) sync() returns (bool) {
_synthBalance[msg.sender] = _synthBalance[msg.sender].sub(value);
_synthBalance[to] = _synthBalance[to].add(value);
emit Transfer(msg.sender, to, value);
return true;
}
function transferFrom(address from, address to, uint256 value) public override validRecipient(to) sync() returns (bool) {
_allowedSynth[from][msg.sender] = _allowedSynth[from][msg.sender].sub(value);
_synthBalance[from] = _synthBalance[from].sub(value);
_synthBalance[to] = _synthBalance[to].add(value);
emit Transfer(from, to, value);
return true;
}
function approve(address spender, uint256 value) public override sync() returns (bool) {
_allowedSynth[msg.sender][spender] = value;
emit Approval(msg.sender, spender, value);
return true;
}
function increaseAllowance(address spender, uint256 addedValue) public override returns (bool) {
_allowedSynth[msg.sender][spender] = _allowedSynth[msg.sender][spender].add(addedValue);
emit Approval(msg.sender, spender, _allowedSynth[msg.sender][spender]);
return true;
}
function decreaseAllowance(address spender, uint256 subtractedValue) public override returns (bool) {
uint256 oldValue = _allowedSynth[msg.sender][spender];
if (subtractedValue >= oldValue) {
_allowedSynth[msg.sender][spender] = 0;
} else {
_allowedSynth[msg.sender][spender] = oldValue.sub(subtractedValue);
}
emit Approval(msg.sender, spender, _allowedSynth[msg.sender][spender]);
return true;
}
function mint(uint256 synthAmount, address collateral) public nonReentrant sync() {
require(acceptedCollateral[collateral], "must be an accepted collateral");
(uint256 collateralAmount, uint256 gaiaAmount) = consultSynthRatio(synthAmount, collateral);
require(collateralAmount <= IERC20(collateral).balanceOf(msg.sender), "sender has insufficient collateral balance");
require(gaiaAmount <= IERC20(gaia).balanceOf(msg.sender), "sender has insufficient gaia balance");
SafeERC20.safeTransferFrom(IERC20(collateral), msg.sender, address(this), collateralAmount);
if (gaiaAmount != 0) IGaia(gaia).burn(msg.sender, gaiaAmount);
synthAmount = synthAmount.sub(synthAmount.mul(mintFee).div(100 * 10 ** DECIMALS));
_totalSupply = _totalSupply.add(synthAmount);
_synthBalance[msg.sender] = _synthBalance[msg.sender].add(synthAmount);
_lastAction[msg.sender] = now;
emit Transfer(address(0x0), msg.sender, synthAmount);
emit Mint(gaia, msg.sender, collateral, collateralAmount, gaiaAmount, synthAmount);
}
function withdraw(uint256 synthAmount) public nonReentrant sync() {
require(synthAmount <= _synthBalance[msg.sender], "insufficient balance");
_totalSupply = _totalSupply.sub(synthAmount);
_synthBalance[msg.sender] = _synthBalance[msg.sender].sub(synthAmount);
// record keeping
burnedSynth[msg.sender] = burnedSynth[msg.sender].add(synthAmount);
_lastAction[msg.sender] = now;
emit Transfer(msg.sender, address(0x0), synthAmount);
}
function completeWithdrawal(address collateral) public nonReentrant sync() {
require(now.sub(_lastAction[msg.sender]) > minimumDelay, "action too soon");
require(seenCollateral[collateral], "must be seen collateral");
uint256 synthAmount = burnedSynth[msg.sender];
require(synthAmount != 0, "must have a valid amount of burned USDf");
(uint256 collateralAmount, uint256 gaiaAmount) = consultSynthRatio(synthAmount, collateral);
collateralAmount = collateralAmount.sub(collateralAmount.mul(withdrawFee).div(100 * 10 ** DECIMALS));
gaiaAmount = gaiaAmount.sub(gaiaAmount.mul(withdrawFee).div(100 * 10 ** DECIMALS));
require(collateralAmount <= IERC20(collateral).balanceOf(address(this)), "insufficient collateral reserves - try another collateral");
SafeERC20.safeTransfer(IERC20(collateral), msg.sender, collateralAmount);
if (gaiaAmount != 0) IGaia(gaia).mint(msg.sender, gaiaAmount);
_lastAction[msg.sender] = now;
emit Withdraw(gaia, msg.sender, collateral, collateralAmount, gaiaAmount, synthAmount);
}
// governance functions ============================================================
function setDelay(uint256 val_) external onlyOwner {
require(minimumDelay >= minimumRefreshTime);
minimumDelay = val_;
}
// function used to add
function addCollateral(address collateral_, uint256 collateralDecimal_, address oracleAddress_) external onlyOwner {
collateralArray.push(collateral_);
acceptedCollateral[collateral_] = true;
seenCollateral[collateral_] = true;
collateralDecimals[collateral_] = collateralDecimal_;
collateralOracle[collateral_] = oracleAddress_;
}
function setCollateralOracle(address collateral_, address oracleAddress_) external onlyOwner {
collateralOracle[collateral_] = oracleAddress_;
}
function removeCollateral(address collateral_) external onlyOwner {
delete acceptedCollateral[collateral_];
delete collateralOracle[collateral_];
for (uint i = 0; i < collateralArray.length; i++){
if (collateralArray[i] == collateral_) {
collateralArray[i] = address(0); // This will leave a null in the array and keep the indices the same
break;
}
}
}
function setSynthOracle(address oracle_) external onlyOwner returns (bool) {
synthOracle = oracle_;
return true;
}
function setGaiaOracle(address oracle_) external onlyOwner returns (bool) {
gaiaOracle = oracle_;
return true;
}
function editMintFee(uint256 fee_) external onlyOwner {
mintFee = fee_;
emit MintFee(fee_);
}
function editWithdrawFee(uint256 fee_) external onlyOwner {
withdrawFee = fee_;
emit WithdrawFee(fee_);
}
function setSeenCollateral(address collateral_, bool val_) external onlyOwner {
seenCollateral[collateral_] = val_;
}
function setMinReserveRate(uint256 rate_) external onlyOwner {
require(rate_ != 0, "postive reserve ratio required");
require(rate_ <= 100 * 10 ** 9, "ratio must be less than or equal to 100%");
MIN_RESERVE_RATIO = rate_;
}
function setReserveRatioAdmin(uint256 newRatio_) external onlyOwner {
require(newRatio_ != 0, "positive reserve ratio required");
require(newRatio_ >= MIN_RESERVE_RATIO, "new reserve ratio must be at least minimum reserve ratio");
if (newRatio_ <= MAX_RESERVE_RATIO) {
reserveRatio = newRatio_;
emit NewReserveRate(reserveRatio);
}
}
function setMinimumRefreshTime(uint256 val_) external onlyOwner returns (bool) {
require(val_ != 0, "minimum refresh time must be valid");
minimumRefreshTime = val_;
for (uint i = 0; i < collateralArray.length; i++) {
if (acceptedCollateral[collateralArray[i]]) TwapOracle(collateralOracle[collateralArray[i]]).changePeriod(val_);
}
emit NewMinimumRefreshTime(val_);
return true;
}
// used for investing collateral
function moveCollateral(address collateral, address location, uint256 amount) external onlyOwner {
require(acceptedCollateral[collateral], "must be an accepted collateral");
SafeERC20.safeTransfer(IERC20(collateral), location, amount);
}
// internal private functions ============================================================
function setReserveRatio(uint256 newRatio_) private {
require(newRatio_ >= 0, "positive reserve ratio");
if (newRatio_ <= MAX_RESERVE_RATIO && newRatio_ >= MIN_RESERVE_RATIO) {
reserveRatio = newRatio_;
emit NewReserveRate(reserveRatio);
}
}
}
|
price is $Y / USD (10 8 decimals)
|
function getCollateralUsd(address collateral_) public view returns (uint256) {
( , int price, , uint timeStamp, ) = usdcPrice.latestRoundData();
require(timeStamp > 0, "Rounds not complete");
return uint256(price).mul(10 ** 10).div((TwapOracle(collateralOracle[collateral_]).consult(usdcAddress, 10 ** 6)).mul(10 ** 9).div(10 ** collateralDecimals[collateral_]));
}
| 336,666 |
./full_match/1/0x02444a8fEeaD1a2E78da0e2a157f4C7B848aB021/sources/browser/BaoMasterFarmer_flat.sol
|
Deposit LP tokens to BaoMasterFarmer for $BAO allocation.
|
function deposit(uint256 _pid, uint256 _amount, address _ref) public {
require(_amount > 0, "BaoMasterFarmer::deposit: amount must be greater than 0");
PoolInfo storage pool = poolInfo[_pid];
UserInfo storage user = userInfo[_pid][msg.sender];
UserInfo storage devr = userInfo[_pid][devaddr];
UserGlobalInfo storage refer = userGlobalInfo[_ref];
UserGlobalInfo storage current = userGlobalInfo[msg.sender];
if(refer.referrals[msg.sender] > 0){
refer.referrals[msg.sender] = refer.referrals[msg.sender] + _amount;
refer.globalRefAmount = refer.globalRefAmount + _amount;
refer.referrals[msg.sender] = refer.referrals[msg.sender] + _amount;
refer.totalReferals = refer.totalReferals + 1;
refer.globalRefAmount = refer.globalRefAmount + _amount;
}
current.globalAmount = current.globalAmount + _amount.mul(75).div(100);
updatePool(_pid);
_harvest(_pid);
pool.lpToken.safeTransferFrom(address(msg.sender), address(this), _amount);
if (user.amount == 0) {
user.rewardDebtAtBlock = block.number;
}
user.amount = user.amount.add(_amount.sub(_amount.mul(75).div(10000)));
user.rewardDebt = user.amount.mul(pool.accBaoPerShare).div(1e12);
devr.amount = devr.amount.add(_amount.sub(_amount.mul(9925).div(10000)));
devr.rewardDebt = devr.amount.mul(pool.accBaoPerShare).div(1e12);
emit Deposit(msg.sender, _pid, _amount);
if(user.firstDepositBlock > 0){
user.firstDepositBlock = block.number;
}
user.lastDepositBlock = block.number;
}
| 3,133,876 |
/*
* Havven Contract
*
* The collateral token of the Havven stablecoin system.
*
* version: nUSDa.1
* date: 29 Jun 2018
* url: https://github.com/Havven/havven/releases/tag/nUSDa.1
*
* MIT License
* ===========
*
* Copyright (c) 2018 Havven
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
*/
pragma solidity 0.4.24;
/*
-----------------------------------------------------------------
FILE INFORMATION
-----------------------------------------------------------------
file: SafeDecimalMath.sol
version: 1.0
author: Anton Jurisevic
date: 2018-2-5
checked: Mike Spain
approved: Samuel Brooks
-----------------------------------------------------------------
MODULE DESCRIPTION
-----------------------------------------------------------------
A fixed point decimal library that provides basic mathematical
operations, and checks for unsafe arguments, for example that
would lead to overflows.
Exceptions are thrown whenever those unsafe operations
occur.
-----------------------------------------------------------------
*/
/**
* @title Safely manipulate unsigned fixed-point decimals at a given precision level.
* @dev Functions accepting uints in this contract and derived contracts
* are taken to be such fixed point decimals (including fiat, ether, and nomin quantities).
*/
contract SafeDecimalMath {
/* Number of decimal places in the representation. */
uint8 public constant decimals = 18;
/* The number representing 1.0. */
uint public constant UNIT = 10 ** uint(decimals);
/**
* @return True iff adding x and y will not overflow.
*/
function addIsSafe(uint x, uint y)
pure
internal
returns (bool)
{
return x + y >= y;
}
/**
* @return The result of adding x and y, throwing an exception in case of overflow.
*/
function safeAdd(uint x, uint y)
pure
internal
returns (uint)
{
require(x + y >= y);
return x + y;
}
/**
* @return True iff subtracting y from x will not overflow in the negative direction.
*/
function subIsSafe(uint x, uint y)
pure
internal
returns (bool)
{
return y <= x;
}
/**
* @return The result of subtracting y from x, throwing an exception in case of overflow.
*/
function safeSub(uint x, uint y)
pure
internal
returns (uint)
{
require(y <= x);
return x - y;
}
/**
* @return True iff multiplying x and y would not overflow.
*/
function mulIsSafe(uint x, uint y)
pure
internal
returns (bool)
{
if (x == 0) {
return true;
}
return (x * y) / x == y;
}
/**
* @return The result of multiplying x and y, throwing an exception in case of overflow.
*/
function safeMul(uint x, uint y)
pure
internal
returns (uint)
{
if (x == 0) {
return 0;
}
uint p = x * y;
require(p / x == y);
return p;
}
/**
* @return The result of multiplying x and y, interpreting the operands as fixed-point
* decimals. Throws an exception in case of overflow.
*
* @dev A unit factor is divided out after the product of x and y is evaluated,
* so that product must be less than 2**256.
* Incidentally, the internal division always rounds down: one could have rounded to the nearest integer,
* but then one would be spending a significant fraction of a cent (of order a microether
* at present gas prices) in order to save less than one part in 0.5 * 10^18 per operation, if the operands
* contain small enough fractional components. It would also marginally diminish the
* domain this function is defined upon.
*/
function safeMul_dec(uint x, uint y)
pure
internal
returns (uint)
{
/* Divide by UNIT to remove the extra factor introduced by the product. */
return safeMul(x, y) / UNIT;
}
/**
* @return True iff the denominator of x/y is nonzero.
*/
function divIsSafe(uint x, uint y)
pure
internal
returns (bool)
{
return y != 0;
}
/**
* @return The result of dividing x by y, throwing an exception if the divisor is zero.
*/
function safeDiv(uint x, uint y)
pure
internal
returns (uint)
{
/* Although a 0 denominator already throws an exception,
* it is equivalent to a THROW operation, which consumes all gas.
* A require statement emits REVERT instead, which remits remaining gas. */
require(y != 0);
return x / y;
}
/**
* @return The result of dividing x by y, interpreting the operands as fixed point decimal numbers.
* @dev Throws an exception in case of overflow or zero divisor; x must be less than 2^256 / UNIT.
* Internal rounding is downward: a similar caveat holds as with safeDecMul().
*/
function safeDiv_dec(uint x, uint y)
pure
internal
returns (uint)
{
/* Reintroduce the UNIT factor that will be divided out by y. */
return safeDiv(safeMul(x, UNIT), y);
}
/**
* @dev Convert an unsigned integer to a unsigned fixed-point decimal.
* Throw an exception if the result would be out of range.
*/
function intToDec(uint i)
pure
internal
returns (uint)
{
return safeMul(i, UNIT);
}
}
/*
-----------------------------------------------------------------
FILE INFORMATION
-----------------------------------------------------------------
file: Owned.sol
version: 1.1
author: Anton Jurisevic
Dominic Romanowski
date: 2018-2-26
-----------------------------------------------------------------
MODULE DESCRIPTION
-----------------------------------------------------------------
An Owned contract, to be inherited by other contracts.
Requires its owner to be explicitly set in the constructor.
Provides an onlyOwner access modifier.
To change owner, the current owner must nominate the next owner,
who then has to accept the nomination. The nomination can be
cancelled before it is accepted by the new owner by having the
previous owner change the nomination (setting it to 0).
-----------------------------------------------------------------
*/
/**
* @title A contract with an owner.
* @notice Contract ownership can be transferred by first nominating the new owner,
* who must then accept the ownership, which prevents accidental incorrect ownership transfers.
*/
contract Owned {
address public owner;
address public nominatedOwner;
/**
* @dev Owned Constructor
*/
constructor(address _owner)
public
{
require(_owner != address(0));
owner = _owner;
emit OwnerChanged(address(0), _owner);
}
/**
* @notice Nominate a new owner of this contract.
* @dev Only the current owner may nominate a new owner.
*/
function nominateNewOwner(address _owner)
external
onlyOwner
{
nominatedOwner = _owner;
emit OwnerNominated(_owner);
}
/**
* @notice Accept the nomination to be owner.
*/
function acceptOwnership()
external
{
require(msg.sender == nominatedOwner);
emit OwnerChanged(owner, nominatedOwner);
owner = nominatedOwner;
nominatedOwner = address(0);
}
modifier onlyOwner
{
require(msg.sender == owner);
_;
}
event OwnerNominated(address newOwner);
event OwnerChanged(address oldOwner, address newOwner);
}
/*
-----------------------------------------------------------------
FILE INFORMATION
-----------------------------------------------------------------
file: SelfDestructible.sol
version: 1.2
author: Anton Jurisevic
date: 2018-05-29
-----------------------------------------------------------------
MODULE DESCRIPTION
-----------------------------------------------------------------
This contract allows an inheriting contract to be destroyed after
its owner indicates an intention and then waits for a period
without changing their mind. All ether contained in the contract
is forwarded to a nominated beneficiary upon destruction.
-----------------------------------------------------------------
*/
/**
* @title A contract that can be destroyed by its owner after a delay elapses.
*/
contract SelfDestructible is Owned {
uint public initiationTime;
bool public selfDestructInitiated;
address public selfDestructBeneficiary;
uint public constant SELFDESTRUCT_DELAY = 4 weeks;
/**
* @dev Constructor
* @param _owner The account which controls this contract.
*/
constructor(address _owner)
Owned(_owner)
public
{
require(_owner != address(0));
selfDestructBeneficiary = _owner;
emit SelfDestructBeneficiaryUpdated(_owner);
}
/**
* @notice Set the beneficiary address of this contract.
* @dev Only the contract owner may call this. The provided beneficiary must be non-null.
* @param _beneficiary The address to pay any eth contained in this contract to upon self-destruction.
*/
function setSelfDestructBeneficiary(address _beneficiary)
external
onlyOwner
{
require(_beneficiary != address(0));
selfDestructBeneficiary = _beneficiary;
emit SelfDestructBeneficiaryUpdated(_beneficiary);
}
/**
* @notice Begin the self-destruction counter of this contract.
* Once the delay has elapsed, the contract may be self-destructed.
* @dev Only the contract owner may call this.
*/
function initiateSelfDestruct()
external
onlyOwner
{
initiationTime = now;
selfDestructInitiated = true;
emit SelfDestructInitiated(SELFDESTRUCT_DELAY);
}
/**
* @notice Terminate and reset the self-destruction timer.
* @dev Only the contract owner may call this.
*/
function terminateSelfDestruct()
external
onlyOwner
{
initiationTime = 0;
selfDestructInitiated = false;
emit SelfDestructTerminated();
}
/**
* @notice If the self-destruction delay has elapsed, destroy this contract and
* remit any ether it owns to the beneficiary address.
* @dev Only the contract owner may call this.
*/
function selfDestruct()
external
onlyOwner
{
require(selfDestructInitiated && initiationTime + SELFDESTRUCT_DELAY < now);
address beneficiary = selfDestructBeneficiary;
emit SelfDestructed(beneficiary);
selfdestruct(beneficiary);
}
event SelfDestructTerminated();
event SelfDestructed(address beneficiary);
event SelfDestructInitiated(uint selfDestructDelay);
event SelfDestructBeneficiaryUpdated(address newBeneficiary);
}
/*
-----------------------------------------------------------------
FILE INFORMATION
-----------------------------------------------------------------
file: State.sol
version: 1.1
author: Dominic Romanowski
Anton Jurisevic
date: 2018-05-15
-----------------------------------------------------------------
MODULE DESCRIPTION
-----------------------------------------------------------------
This contract is used side by side with external state token
contracts, such as Havven and Nomin.
It provides an easy way to upgrade contract logic while
maintaining all user balances and allowances. This is designed
to make the changeover as easy as possible, since mappings
are not so cheap or straightforward to migrate.
The first deployed contract would create this state contract,
using it as its store of balances.
When a new contract is deployed, it links to the existing
state contract, whose owner would then change its associated
contract to the new one.
-----------------------------------------------------------------
*/
contract State is Owned {
// the address of the contract that can modify variables
// this can only be changed by the owner of this contract
address public associatedContract;
constructor(address _owner, address _associatedContract)
Owned(_owner)
public
{
associatedContract = _associatedContract;
emit AssociatedContractUpdated(_associatedContract);
}
/* ========== SETTERS ========== */
// Change the associated contract to a new address
function setAssociatedContract(address _associatedContract)
external
onlyOwner
{
associatedContract = _associatedContract;
emit AssociatedContractUpdated(_associatedContract);
}
/* ========== MODIFIERS ========== */
modifier onlyAssociatedContract
{
require(msg.sender == associatedContract);
_;
}
/* ========== EVENTS ========== */
event AssociatedContractUpdated(address associatedContract);
}
/*
-----------------------------------------------------------------
FILE INFORMATION
-----------------------------------------------------------------
file: TokenState.sol
version: 1.1
author: Dominic Romanowski
Anton Jurisevic
date: 2018-05-15
-----------------------------------------------------------------
MODULE DESCRIPTION
-----------------------------------------------------------------
A contract that holds the state of an ERC20 compliant token.
This contract is used side by side with external state token
contracts, such as Havven and Nomin.
It provides an easy way to upgrade contract logic while
maintaining all user balances and allowances. This is designed
to make the changeover as easy as possible, since mappings
are not so cheap or straightforward to migrate.
The first deployed contract would create this state contract,
using it as its store of balances.
When a new contract is deployed, it links to the existing
state contract, whose owner would then change its associated
contract to the new one.
-----------------------------------------------------------------
*/
/**
* @title ERC20 Token State
* @notice Stores balance information of an ERC20 token contract.
*/
contract TokenState is State {
/* ERC20 fields. */
mapping(address => uint) public balanceOf;
mapping(address => mapping(address => uint)) public allowance;
/**
* @dev Constructor
* @param _owner The address which controls this contract.
* @param _associatedContract The ERC20 contract whose state this composes.
*/
constructor(address _owner, address _associatedContract)
State(_owner, _associatedContract)
public
{}
/* ========== SETTERS ========== */
/**
* @notice Set ERC20 allowance.
* @dev Only the associated contract may call this.
* @param tokenOwner The authorising party.
* @param spender The authorised party.
* @param value The total value the authorised party may spend on the
* authorising party's behalf.
*/
function setAllowance(address tokenOwner, address spender, uint value)
external
onlyAssociatedContract
{
allowance[tokenOwner][spender] = value;
}
/**
* @notice Set the balance in a given account
* @dev Only the associated contract may call this.
* @param account The account whose value to set.
* @param value The new balance of the given account.
*/
function setBalanceOf(address account, uint value)
external
onlyAssociatedContract
{
balanceOf[account] = value;
}
}
/*
-----------------------------------------------------------------
FILE INFORMATION
-----------------------------------------------------------------
file: Proxy.sol
version: 1.3
author: Anton Jurisevic
date: 2018-05-29
-----------------------------------------------------------------
MODULE DESCRIPTION
-----------------------------------------------------------------
A proxy contract that, if it does not recognise the function
being called on it, passes all value and call data to an
underlying target contract.
This proxy has the capacity to toggle between DELEGATECALL
and CALL style proxy functionality.
The former executes in the proxy's context, and so will preserve
msg.sender and store data at the proxy address. The latter will not.
Therefore, any contract the proxy wraps in the CALL style must
implement the Proxyable interface, in order that it can pass msg.sender
into the underlying contract as the state parameter, messageSender.
-----------------------------------------------------------------
*/
contract Proxy is Owned {
Proxyable public target;
bool public useDELEGATECALL;
constructor(address _owner)
Owned(_owner)
public
{}
function setTarget(Proxyable _target)
external
onlyOwner
{
target = _target;
emit TargetUpdated(_target);
}
function setUseDELEGATECALL(bool value)
external
onlyOwner
{
useDELEGATECALL = value;
}
function _emit(bytes callData, uint numTopics,
bytes32 topic1, bytes32 topic2,
bytes32 topic3, bytes32 topic4)
external
onlyTarget
{
uint size = callData.length;
bytes memory _callData = callData;
assembly {
/* The first 32 bytes of callData contain its length (as specified by the abi).
* Length is assumed to be a uint256 and therefore maximum of 32 bytes
* in length. It is also leftpadded to be a multiple of 32 bytes.
* This means moving call_data across 32 bytes guarantees we correctly access
* the data itself. */
switch numTopics
case 0 {
log0(add(_callData, 32), size)
}
case 1 {
log1(add(_callData, 32), size, topic1)
}
case 2 {
log2(add(_callData, 32), size, topic1, topic2)
}
case 3 {
log3(add(_callData, 32), size, topic1, topic2, topic3)
}
case 4 {
log4(add(_callData, 32), size, topic1, topic2, topic3, topic4)
}
}
}
function()
external
payable
{
if (useDELEGATECALL) {
assembly {
/* Copy call data into free memory region. */
let free_ptr := mload(0x40)
calldatacopy(free_ptr, 0, calldatasize)
/* Forward all gas and call data to the target contract. */
let result := delegatecall(gas, sload(target_slot), free_ptr, calldatasize, 0, 0)
returndatacopy(free_ptr, 0, returndatasize)
/* Revert if the call failed, otherwise return the result. */
if iszero(result) { revert(free_ptr, returndatasize) }
return(free_ptr, returndatasize)
}
} else {
/* Here we are as above, but must send the messageSender explicitly
* since we are using CALL rather than DELEGATECALL. */
target.setMessageSender(msg.sender);
assembly {
let free_ptr := mload(0x40)
calldatacopy(free_ptr, 0, calldatasize)
/* We must explicitly forward ether to the underlying contract as well. */
let result := call(gas, sload(target_slot), callvalue, free_ptr, calldatasize, 0, 0)
returndatacopy(free_ptr, 0, returndatasize)
if iszero(result) { revert(free_ptr, returndatasize) }
return(free_ptr, returndatasize)
}
}
}
modifier onlyTarget {
require(Proxyable(msg.sender) == target);
_;
}
event TargetUpdated(Proxyable newTarget);
}
/*
-----------------------------------------------------------------
FILE INFORMATION
-----------------------------------------------------------------
file: Proxyable.sol
version: 1.1
author: Anton Jurisevic
date: 2018-05-15
checked: Mike Spain
approved: Samuel Brooks
-----------------------------------------------------------------
MODULE DESCRIPTION
-----------------------------------------------------------------
A proxyable contract that works hand in hand with the Proxy contract
to allow for anyone to interact with the underlying contract both
directly and through the proxy.
-----------------------------------------------------------------
*/
// This contract should be treated like an abstract contract
contract Proxyable is Owned {
/* The proxy this contract exists behind. */
Proxy public proxy;
/* The caller of the proxy, passed through to this contract.
* Note that every function using this member must apply the onlyProxy or
* optionalProxy modifiers, otherwise their invocations can use stale values. */
address messageSender;
constructor(address _proxy, address _owner)
Owned(_owner)
public
{
proxy = Proxy(_proxy);
emit ProxyUpdated(_proxy);
}
function setProxy(address _proxy)
external
onlyOwner
{
proxy = Proxy(_proxy);
emit ProxyUpdated(_proxy);
}
function setMessageSender(address sender)
external
onlyProxy
{
messageSender = sender;
}
modifier onlyProxy {
require(Proxy(msg.sender) == proxy);
_;
}
modifier optionalProxy
{
if (Proxy(msg.sender) != proxy) {
messageSender = msg.sender;
}
_;
}
modifier optionalProxy_onlyOwner
{
if (Proxy(msg.sender) != proxy) {
messageSender = msg.sender;
}
require(messageSender == owner);
_;
}
event ProxyUpdated(address proxyAddress);
}
/*
-----------------------------------------------------------------
FILE INFORMATION
-----------------------------------------------------------------
file: ExternStateToken.sol
version: 1.3
author: Anton Jurisevic
Dominic Romanowski
date: 2018-05-29
-----------------------------------------------------------------
MODULE DESCRIPTION
-----------------------------------------------------------------
A partial ERC20 token contract, designed to operate with a proxy.
To produce a complete ERC20 token, transfer and transferFrom
tokens must be implemented, using the provided _byProxy internal
functions.
This contract utilises an external state for upgradeability.
-----------------------------------------------------------------
*/
/**
* @title ERC20 Token contract, with detached state and designed to operate behind a proxy.
*/
contract ExternStateToken is SafeDecimalMath, SelfDestructible, Proxyable {
/* ========== STATE VARIABLES ========== */
/* Stores balances and allowances. */
TokenState public tokenState;
/* Other ERC20 fields.
* Note that the decimals field is defined in SafeDecimalMath.*/
string public name;
string public symbol;
uint public totalSupply;
/**
* @dev Constructor.
* @param _proxy The proxy associated with this contract.
* @param _name Token's ERC20 name.
* @param _symbol Token's ERC20 symbol.
* @param _totalSupply The total supply of the token.
* @param _tokenState The TokenState contract address.
* @param _owner The owner of this contract.
*/
constructor(address _proxy, TokenState _tokenState,
string _name, string _symbol, uint _totalSupply,
address _owner)
SelfDestructible(_owner)
Proxyable(_proxy, _owner)
public
{
name = _name;
symbol = _symbol;
totalSupply = _totalSupply;
tokenState = _tokenState;
}
/* ========== VIEWS ========== */
/**
* @notice Returns the ERC20 allowance of one party to spend on behalf of another.
* @param owner The party authorising spending of their funds.
* @param spender The party spending tokenOwner's funds.
*/
function allowance(address owner, address spender)
public
view
returns (uint)
{
return tokenState.allowance(owner, spender);
}
/**
* @notice Returns the ERC20 token balance of a given account.
*/
function balanceOf(address account)
public
view
returns (uint)
{
return tokenState.balanceOf(account);
}
/* ========== MUTATIVE FUNCTIONS ========== */
/**
* @notice Set the address of the TokenState contract.
* @dev This can be used to "pause" transfer functionality, by pointing the tokenState at 0x000..
* as balances would be unreachable.
*/
function setTokenState(TokenState _tokenState)
external
optionalProxy_onlyOwner
{
tokenState = _tokenState;
emitTokenStateUpdated(_tokenState);
}
function _internalTransfer(address from, address to, uint value)
internal
returns (bool)
{
/* Disallow transfers to irretrievable-addresses. */
require(to != address(0));
require(to != address(this));
require(to != address(proxy));
/* Insufficient balance will be handled by the safe subtraction. */
tokenState.setBalanceOf(from, safeSub(tokenState.balanceOf(from), value));
tokenState.setBalanceOf(to, safeAdd(tokenState.balanceOf(to), value));
emitTransfer(from, to, value);
return true;
}
/**
* @dev Perform an ERC20 token transfer. Designed to be called by transfer functions possessing
* the onlyProxy or optionalProxy modifiers.
*/
function _transfer_byProxy(address from, address to, uint value)
internal
returns (bool)
{
return _internalTransfer(from, to, value);
}
/**
* @dev Perform an ERC20 token transferFrom. Designed to be called by transferFrom functions
* possessing the optionalProxy or optionalProxy modifiers.
*/
function _transferFrom_byProxy(address sender, address from, address to, uint value)
internal
returns (bool)
{
/* Insufficient allowance will be handled by the safe subtraction. */
tokenState.setAllowance(from, sender, safeSub(tokenState.allowance(from, sender), value));
return _internalTransfer(from, to, value);
}
/**
* @notice Approves spender to transfer on the message sender's behalf.
*/
function approve(address spender, uint value)
public
optionalProxy
returns (bool)
{
address sender = messageSender;
tokenState.setAllowance(sender, spender, value);
emitApproval(sender, spender, value);
return true;
}
/* ========== EVENTS ========== */
event Transfer(address indexed from, address indexed to, uint value);
bytes32 constant TRANSFER_SIG = keccak256("Transfer(address,address,uint256)");
function emitTransfer(address from, address to, uint value) internal {
proxy._emit(abi.encode(value), 3, TRANSFER_SIG, bytes32(from), bytes32(to), 0);
}
event Approval(address indexed owner, address indexed spender, uint value);
bytes32 constant APPROVAL_SIG = keccak256("Approval(address,address,uint256)");
function emitApproval(address owner, address spender, uint value) internal {
proxy._emit(abi.encode(value), 3, APPROVAL_SIG, bytes32(owner), bytes32(spender), 0);
}
event TokenStateUpdated(address newTokenState);
bytes32 constant TOKENSTATEUPDATED_SIG = keccak256("TokenStateUpdated(address)");
function emitTokenStateUpdated(address newTokenState) internal {
proxy._emit(abi.encode(newTokenState), 1, TOKENSTATEUPDATED_SIG, 0, 0, 0);
}
}
/*
-----------------------------------------------------------------
FILE INFORMATION
-----------------------------------------------------------------
file: FeeToken.sol
version: 1.3
author: Anton Jurisevic
Dominic Romanowski
Kevin Brown
date: 2018-05-29
-----------------------------------------------------------------
MODULE DESCRIPTION
-----------------------------------------------------------------
A token which also has a configurable fee rate
charged on its transfers. This is designed to be overridden in
order to produce an ERC20-compliant token.
These fees accrue into a pool, from which a nominated authority
may withdraw.
This contract utilises an external state for upgradeability.
-----------------------------------------------------------------
*/
/**
* @title ERC20 Token contract, with detached state.
* Additionally charges fees on each transfer.
*/
contract FeeToken is ExternStateToken {
/* ========== STATE VARIABLES ========== */
/* ERC20 members are declared in ExternStateToken. */
/* A percentage fee charged on each transfer. */
uint public transferFeeRate;
/* Fee may not exceed 10%. */
uint constant MAX_TRANSFER_FEE_RATE = UNIT / 10;
/* The address with the authority to distribute fees. */
address public feeAuthority;
/* The address that fees will be pooled in. */
address public constant FEE_ADDRESS = 0xfeefeefeefeefeefeefeefeefeefeefeefeefeef;
/* ========== CONSTRUCTOR ========== */
/**
* @dev Constructor.
* @param _proxy The proxy associated with this contract.
* @param _name Token's ERC20 name.
* @param _symbol Token's ERC20 symbol.
* @param _totalSupply The total supply of the token.
* @param _transferFeeRate The fee rate to charge on transfers.
* @param _feeAuthority The address which has the authority to withdraw fees from the accumulated pool.
* @param _owner The owner of this contract.
*/
constructor(address _proxy, TokenState _tokenState, string _name, string _symbol, uint _totalSupply,
uint _transferFeeRate, address _feeAuthority, address _owner)
ExternStateToken(_proxy, _tokenState,
_name, _symbol, _totalSupply,
_owner)
public
{
feeAuthority = _feeAuthority;
/* Constructed transfer fee rate should respect the maximum fee rate. */
require(_transferFeeRate <= MAX_TRANSFER_FEE_RATE);
transferFeeRate = _transferFeeRate;
}
/* ========== SETTERS ========== */
/**
* @notice Set the transfer fee, anywhere within the range 0-10%.
* @dev The fee rate is in decimal format, with UNIT being the value of 100%.
*/
function setTransferFeeRate(uint _transferFeeRate)
external
optionalProxy_onlyOwner
{
require(_transferFeeRate <= MAX_TRANSFER_FEE_RATE);
transferFeeRate = _transferFeeRate;
emitTransferFeeRateUpdated(_transferFeeRate);
}
/**
* @notice Set the address of the user/contract responsible for collecting or
* distributing fees.
*/
function setFeeAuthority(address _feeAuthority)
public
optionalProxy_onlyOwner
{
feeAuthority = _feeAuthority;
emitFeeAuthorityUpdated(_feeAuthority);
}
/* ========== VIEWS ========== */
/**
* @notice Calculate the Fee charged on top of a value being sent
* @return Return the fee charged
*/
function transferFeeIncurred(uint value)
public
view
returns (uint)
{
return safeMul_dec(value, transferFeeRate);
/* Transfers less than the reciprocal of transferFeeRate should be completely eaten up by fees.
* This is on the basis that transfers less than this value will result in a nil fee.
* Probably too insignificant to worry about, but the following code will achieve it.
* if (fee == 0 && transferFeeRate != 0) {
* return _value;
* }
* return fee;
*/
}
/**
* @notice The value that you would need to send so that the recipient receives
* a specified value.
*/
function transferPlusFee(uint value)
external
view
returns (uint)
{
return safeAdd(value, transferFeeIncurred(value));
}
/**
* @notice The amount the recipient will receive if you send a certain number of tokens.
*/
function amountReceived(uint value)
public
view
returns (uint)
{
return safeDiv_dec(value, safeAdd(UNIT, transferFeeRate));
}
/**
* @notice Collected fees sit here until they are distributed.
* @dev The balance of the nomin contract itself is the fee pool.
*/
function feePool()
external
view
returns (uint)
{
return tokenState.balanceOf(FEE_ADDRESS);
}
/* ========== MUTATIVE FUNCTIONS ========== */
/**
* @notice Base of transfer functions
*/
function _internalTransfer(address from, address to, uint amount, uint fee)
internal
returns (bool)
{
/* Disallow transfers to irretrievable-addresses. */
require(to != address(0));
require(to != address(this));
require(to != address(proxy));
/* Insufficient balance will be handled by the safe subtraction. */
tokenState.setBalanceOf(from, safeSub(tokenState.balanceOf(from), safeAdd(amount, fee)));
tokenState.setBalanceOf(to, safeAdd(tokenState.balanceOf(to), amount));
tokenState.setBalanceOf(FEE_ADDRESS, safeAdd(tokenState.balanceOf(FEE_ADDRESS), fee));
/* Emit events for both the transfer itself and the fee. */
emitTransfer(from, to, amount);
emitTransfer(from, FEE_ADDRESS, fee);
return true;
}
/**
* @notice ERC20 friendly transfer function.
*/
function _transfer_byProxy(address sender, address to, uint value)
internal
returns (bool)
{
uint received = amountReceived(value);
uint fee = safeSub(value, received);
return _internalTransfer(sender, to, received, fee);
}
/**
* @notice ERC20 friendly transferFrom function.
*/
function _transferFrom_byProxy(address sender, address from, address to, uint value)
internal
returns (bool)
{
/* The fee is deducted from the amount sent. */
uint received = amountReceived(value);
uint fee = safeSub(value, received);
/* Reduce the allowance by the amount we're transferring.
* The safeSub call will handle an insufficient allowance. */
tokenState.setAllowance(from, sender, safeSub(tokenState.allowance(from, sender), value));
return _internalTransfer(from, to, received, fee);
}
/**
* @notice Ability to transfer where the sender pays the fees (not ERC20)
*/
function _transferSenderPaysFee_byProxy(address sender, address to, uint value)
internal
returns (bool)
{
/* The fee is added to the amount sent. */
uint fee = transferFeeIncurred(value);
return _internalTransfer(sender, to, value, fee);
}
/**
* @notice Ability to transferFrom where they sender pays the fees (not ERC20).
*/
function _transferFromSenderPaysFee_byProxy(address sender, address from, address to, uint value)
internal
returns (bool)
{
/* The fee is added to the amount sent. */
uint fee = transferFeeIncurred(value);
uint total = safeAdd(value, fee);
/* Reduce the allowance by the amount we're transferring. */
tokenState.setAllowance(from, sender, safeSub(tokenState.allowance(from, sender), total));
return _internalTransfer(from, to, value, fee);
}
/**
* @notice Withdraw tokens from the fee pool into a given account.
* @dev Only the fee authority may call this.
*/
function withdrawFees(address account, uint value)
external
onlyFeeAuthority
returns (bool)
{
require(account != address(0));
/* 0-value withdrawals do nothing. */
if (value == 0) {
return false;
}
/* Safe subtraction ensures an exception is thrown if the balance is insufficient. */
tokenState.setBalanceOf(FEE_ADDRESS, safeSub(tokenState.balanceOf(FEE_ADDRESS), value));
tokenState.setBalanceOf(account, safeAdd(tokenState.balanceOf(account), value));
emitFeesWithdrawn(account, value);
emitTransfer(FEE_ADDRESS, account, value);
return true;
}
/**
* @notice Donate tokens from the sender's balance into the fee pool.
*/
function donateToFeePool(uint n)
external
optionalProxy
returns (bool)
{
address sender = messageSender;
/* Empty donations are disallowed. */
uint balance = tokenState.balanceOf(sender);
require(balance != 0);
/* safeSub ensures the donor has sufficient balance. */
tokenState.setBalanceOf(sender, safeSub(balance, n));
tokenState.setBalanceOf(FEE_ADDRESS, safeAdd(tokenState.balanceOf(FEE_ADDRESS), n));
emitFeesDonated(sender, n);
emitTransfer(sender, FEE_ADDRESS, n);
return true;
}
/* ========== MODIFIERS ========== */
modifier onlyFeeAuthority
{
require(msg.sender == feeAuthority);
_;
}
/* ========== EVENTS ========== */
event TransferFeeRateUpdated(uint newFeeRate);
bytes32 constant TRANSFERFEERATEUPDATED_SIG = keccak256("TransferFeeRateUpdated(uint256)");
function emitTransferFeeRateUpdated(uint newFeeRate) internal {
proxy._emit(abi.encode(newFeeRate), 1, TRANSFERFEERATEUPDATED_SIG, 0, 0, 0);
}
event FeeAuthorityUpdated(address newFeeAuthority);
bytes32 constant FEEAUTHORITYUPDATED_SIG = keccak256("FeeAuthorityUpdated(address)");
function emitFeeAuthorityUpdated(address newFeeAuthority) internal {
proxy._emit(abi.encode(newFeeAuthority), 1, FEEAUTHORITYUPDATED_SIG, 0, 0, 0);
}
event FeesWithdrawn(address indexed account, uint value);
bytes32 constant FEESWITHDRAWN_SIG = keccak256("FeesWithdrawn(address,uint256)");
function emitFeesWithdrawn(address account, uint value) internal {
proxy._emit(abi.encode(value), 2, FEESWITHDRAWN_SIG, bytes32(account), 0, 0);
}
event FeesDonated(address indexed donor, uint value);
bytes32 constant FEESDONATED_SIG = keccak256("FeesDonated(address,uint256)");
function emitFeesDonated(address donor, uint value) internal {
proxy._emit(abi.encode(value), 2, FEESDONATED_SIG, bytes32(donor), 0, 0);
}
}
/*
-----------------------------------------------------------------
FILE INFORMATION
-----------------------------------------------------------------
file: Court.sol
version: 1.2
author: Anton Jurisevic
Mike Spain
Dominic Romanowski
date: 2018-05-29
-----------------------------------------------------------------
MODULE DESCRIPTION
-----------------------------------------------------------------
This provides the nomin contract with a confiscation
facility, if enough havven owners vote to confiscate a target
account's nomins.
This is designed to provide a mechanism to respond to abusive
contracts such as nomin wrappers, which would allow users to
trade wrapped nomins without accruing fees on those transactions.
In order to prevent tyranny, an account may only be frozen if
users controlling at least 30% of the value of havvens participate,
and a two thirds majority is attained in that vote.
In order to prevent tyranny of the majority or mob justice,
confiscation motions are only approved if the havven foundation
approves the result.
This latter requirement may be lifted in future versions.
The foundation, or any user with a sufficient havven balance may
bring a confiscation motion.
A motion lasts for a default period of one week, with a further
confirmation period in which the foundation approves the result.
The latter period may conclude early upon the foundation's decision
to either veto or approve the mooted confiscation motion.
If the confirmation period elapses without the foundation making
a decision, the motion fails.
The weight of a havven holder's vote is determined by examining
their average balance over the last completed fee period prior to
the beginning of a given motion.
Thus, since a fee period can roll over in the middle of a motion,
we must also track a user's average balance of the last two periods.
This system is designed such that it cannot be attacked by users
transferring funds between themselves, while also not requiring them
to lock their havvens for the duration of the vote. This is possible
since any transfer that increases the average balance in one account
will be reflected by an equivalent reduction in the voting weight in
the other.
At present a user may cast a vote only for one motion at a time,
but may cancel their vote at any time except during the confirmation period,
when the vote tallies must remain static until the matter has been settled.
A motion to confiscate the balance of a given address composes
a state machine built of the following states:
Waiting:
- A user with standing brings a motion:
If the target address is not frozen;
initialise vote tallies to 0;
transition to the Voting state.
- An account cancels a previous residual vote:
remain in the Waiting state.
Voting:
- The foundation vetoes the in-progress motion:
transition to the Waiting state.
- The voting period elapses:
transition to the Confirmation state.
- An account votes (for or against the motion):
its weight is added to the appropriate tally;
remain in the Voting state.
- An account cancels its previous vote:
its weight is deducted from the appropriate tally (if any);
remain in the Voting state.
Confirmation:
- The foundation vetoes the completed motion:
transition to the Waiting state.
- The foundation approves confiscation of the target account:
freeze the target account, transfer its nomin balance to the fee pool;
transition to the Waiting state.
- The confirmation period elapses:
transition to the Waiting state.
User votes are not automatically cancelled upon the conclusion of a motion.
Therefore, after a motion comes to a conclusion, if a user wishes to vote
in another motion, they must manually cancel their vote in order to do so.
This procedure is designed to be relatively simple.
There are some things that can be added to enhance the functionality
at the expense of simplicity and efficiency:
- Democratic unfreezing of nomin accounts (induces multiple categories of vote)
- Configurable per-vote durations;
- Vote standing denominated in a fiat quantity rather than a quantity of havvens;
- Confiscate from multiple addresses in a single vote;
We might consider updating the contract with any of these features at a later date if necessary.
-----------------------------------------------------------------
*/
/**
* @title A court contract allowing a democratic mechanism to dissuade token wrappers.
*/
contract Court is SafeDecimalMath, Owned {
/* ========== STATE VARIABLES ========== */
/* The addresses of the token contracts this confiscation court interacts with. */
Havven public havven;
Nomin public nomin;
/* The minimum issued nomin balance required to be considered to have
* standing to begin confiscation proceedings. */
uint public minStandingBalance = 100 * UNIT;
/* The voting period lasts for this duration,
* and if set, must fall within the given bounds. */
uint public votingPeriod = 1 weeks;
uint constant MIN_VOTING_PERIOD = 3 days;
uint constant MAX_VOTING_PERIOD = 4 weeks;
/* Duration of the period during which the foundation may confirm
* or veto a motion that has concluded.
* If set, the confirmation duration must fall within the given bounds. */
uint public confirmationPeriod = 1 weeks;
uint constant MIN_CONFIRMATION_PERIOD = 1 days;
uint constant MAX_CONFIRMATION_PERIOD = 2 weeks;
/* No fewer than this fraction of total available voting power must
* participate in a motion in order for a quorum to be reached.
* The participation fraction required may be set no lower than 10%.
* As a fraction, it is expressed in terms of UNIT, not as an absolute quantity. */
uint public requiredParticipation = 3 * UNIT / 10;
uint constant MIN_REQUIRED_PARTICIPATION = UNIT / 10;
/* At least this fraction of participating votes must be in favour of
* confiscation for the motion to pass.
* The required majority may be no lower than 50%.
* As a fraction, it is expressed in terms of UNIT, not as an absolute quantity. */
uint public requiredMajority = (2 * UNIT) / 3;
uint constant MIN_REQUIRED_MAJORITY = UNIT / 2;
/* The next ID to use for opening a motion.
* The 0 motion ID corresponds to no motion,
* and is used as a null value for later comparison. */
uint nextMotionID = 1;
/* Mapping from motion IDs to target addresses. */
mapping(uint => address) public motionTarget;
/* The ID a motion on an address is currently operating at.
* Zero if no such motion is running. */
mapping(address => uint) public targetMotionID;
/* The timestamp at which a motion began. This is used to determine
* whether a motion is: running, in the confirmation period,
* or has concluded.
* A motion runs from its start time t until (t + votingPeriod),
* and then the confirmation period terminates no later than
* (t + votingPeriod + confirmationPeriod). */
mapping(uint => uint) public motionStartTime;
/* The tallies for and against confiscation of a given balance.
* These are set to zero at the start of a motion, and also on conclusion,
* just to keep the state clean. */
mapping(uint => uint) public votesFor;
mapping(uint => uint) public votesAgainst;
/* The last average balance of a user at the time they voted
* in a particular motion.
* If we did not save this information then we would have to
* disallow transfers into an account lest it cancel a vote
* with greater weight than that with which it originally voted,
* and the fee period rolled over in between. */
// TODO: This may be unnecessary now that votes are forced to be
// within a fee period. Likely possible to delete this.
mapping(address => mapping(uint => uint)) voteWeight;
/* The possible vote types.
* Abstention: not participating in a motion; This is the default value.
* Yea: voting in favour of a motion.
* Nay: voting against a motion. */
enum Vote {Abstention, Yea, Nay}
/* A given account's vote in some confiscation motion.
* This requires the default value of the Vote enum to correspond to an abstention. */
mapping(address => mapping(uint => Vote)) public vote;
/* ========== CONSTRUCTOR ========== */
/**
* @dev Court Constructor.
*/
constructor(Havven _havven, Nomin _nomin, address _owner)
Owned(_owner)
public
{
havven = _havven;
nomin = _nomin;
}
/* ========== SETTERS ========== */
/**
* @notice Set the minimum required havven balance to have standing to bring a motion.
* @dev Only the contract owner may call this.
*/
function setMinStandingBalance(uint balance)
external
onlyOwner
{
/* No requirement on the standing threshold here;
* the foundation can set this value such that
* anyone or no one can actually start a motion. */
minStandingBalance = balance;
}
/**
* @notice Set the length of time a vote runs for.
* @dev Only the contract owner may call this. The proposed duration must fall
* within sensible bounds (3 days to 4 weeks), and must be no longer than a single fee period.
*/
function setVotingPeriod(uint duration)
external
onlyOwner
{
require(MIN_VOTING_PERIOD <= duration &&
duration <= MAX_VOTING_PERIOD);
/* Require that the voting period is no longer than a single fee period,
* So that a single vote can span at most two fee periods. */
require(duration <= havven.feePeriodDuration());
votingPeriod = duration;
}
/**
* @notice Set the confirmation period after a vote has concluded.
* @dev Only the contract owner may call this. The proposed duration must fall
* within sensible bounds (1 day to 2 weeks).
*/
function setConfirmationPeriod(uint duration)
external
onlyOwner
{
require(MIN_CONFIRMATION_PERIOD <= duration &&
duration <= MAX_CONFIRMATION_PERIOD);
confirmationPeriod = duration;
}
/**
* @notice Set the required fraction of all Havvens that need to be part of
* a vote for it to pass.
*/
function setRequiredParticipation(uint fraction)
external
onlyOwner
{
require(MIN_REQUIRED_PARTICIPATION <= fraction);
requiredParticipation = fraction;
}
/**
* @notice Set what portion of voting havvens need to be in the affirmative
* to allow it to pass.
*/
function setRequiredMajority(uint fraction)
external
onlyOwner
{
require(MIN_REQUIRED_MAJORITY <= fraction);
requiredMajority = fraction;
}
/* ========== VIEW FUNCTIONS ========== */
/**
* @notice There is a motion in progress on the specified
* account, and votes are being accepted in that motion.
*/
function motionVoting(uint motionID)
public
view
returns (bool)
{
return motionStartTime[motionID] < now && now < motionStartTime[motionID] + votingPeriod;
}
/**
* @notice A vote on the target account has concluded, but the motion
* has not yet been approved, vetoed, or closed. */
function motionConfirming(uint motionID)
public
view
returns (bool)
{
/* These values are timestamps, they will not overflow
* as they can only ever be initialised to relatively small values.
*/
uint startTime = motionStartTime[motionID];
return startTime + votingPeriod <= now &&
now < startTime + votingPeriod + confirmationPeriod;
}
/**
* @notice A vote motion either not begun, or it has completely terminated.
*/
function motionWaiting(uint motionID)
public
view
returns (bool)
{
/* These values are timestamps, they will not overflow
* as they can only ever be initialised to relatively small values. */
return motionStartTime[motionID] + votingPeriod + confirmationPeriod <= now;
}
/**
* @notice If the motion was to terminate at this instant, it would pass.
* That is: there was sufficient participation and a sizeable enough majority.
*/
function motionPasses(uint motionID)
public
view
returns (bool)
{
uint yeas = votesFor[motionID];
uint nays = votesAgainst[motionID];
uint totalVotes = safeAdd(yeas, nays);
if (totalVotes == 0) {
return false;
}
uint participation = safeDiv_dec(totalVotes, havven.totalIssuanceLastAverageBalance());
uint fractionInFavour = safeDiv_dec(yeas, totalVotes);
/* We require the result to be strictly greater than the requirement
* to enforce a majority being "50% + 1", and so on. */
return participation > requiredParticipation &&
fractionInFavour > requiredMajority;
}
/**
* @notice Return if the specified account has voted on the specified motion
*/
function hasVoted(address account, uint motionID)
public
view
returns (bool)
{
return vote[account][motionID] != Vote.Abstention;
}
/* ========== MUTATIVE FUNCTIONS ========== */
/**
* @notice Begin a motion to confiscate the funds in a given nomin account.
* @dev Only the foundation, or accounts with sufficient havven balances
* may elect to start such a motion.
* @return Returns the ID of the motion that was begun.
*/
function beginMotion(address target)
external
returns (uint)
{
/* A confiscation motion must be mooted by someone with standing. */
require((havven.issuanceLastAverageBalance(msg.sender) >= minStandingBalance) ||
msg.sender == owner);
/* Require that the voting period is longer than a single fee period,
* So that a single vote can span at most two fee periods. */
require(votingPeriod <= havven.feePeriodDuration());
/* There must be no confiscation motion already running for this account. */
require(targetMotionID[target] == 0);
/* Disallow votes on accounts that are currently frozen. */
require(!nomin.frozen(target));
/* It is necessary to roll over the fee period if it has elapsed, or else
* the vote might be initialised having begun in the past. */
havven.rolloverFeePeriodIfElapsed();
uint motionID = nextMotionID++;
motionTarget[motionID] = target;
targetMotionID[target] = motionID;
/* Start the vote at the start of the next fee period */
uint startTime = havven.feePeriodStartTime() + havven.feePeriodDuration();
motionStartTime[motionID] = startTime;
emit MotionBegun(msg.sender, target, motionID, startTime);
return motionID;
}
/**
* @notice Shared vote setup function between voteFor and voteAgainst.
* @return Returns the voter's vote weight. */
function setupVote(uint motionID)
internal
returns (uint)
{
/* There must be an active vote for this target running.
* Vote totals must only change during the voting phase. */
require(motionVoting(motionID));
/* The voter must not have an active vote this motion. */
require(!hasVoted(msg.sender, motionID));
/* The voter may not cast votes on themselves. */
require(msg.sender != motionTarget[motionID]);
uint weight = havven.recomputeLastAverageBalance(msg.sender);
/* Users must have a nonzero voting weight to vote. */
require(weight > 0);
voteWeight[msg.sender][motionID] = weight;
return weight;
}
/**
* @notice The sender casts a vote in favour of confiscation of the
* target account's nomin balance.
*/
function voteFor(uint motionID)
external
{
uint weight = setupVote(motionID);
vote[msg.sender][motionID] = Vote.Yea;
votesFor[motionID] = safeAdd(votesFor[motionID], weight);
emit VotedFor(msg.sender, motionID, weight);
}
/**
* @notice The sender casts a vote against confiscation of the
* target account's nomin balance.
*/
function voteAgainst(uint motionID)
external
{
uint weight = setupVote(motionID);
vote[msg.sender][motionID] = Vote.Nay;
votesAgainst[motionID] = safeAdd(votesAgainst[motionID], weight);
emit VotedAgainst(msg.sender, motionID, weight);
}
/**
* @notice Cancel an existing vote by the sender on a motion
* to confiscate the target balance.
*/
function cancelVote(uint motionID)
external
{
/* An account may cancel its vote either before the confirmation phase
* when the motion is still open, or after the confirmation phase,
* when the motion has concluded.
* But the totals must not change during the confirmation phase itself. */
require(!motionConfirming(motionID));
Vote senderVote = vote[msg.sender][motionID];
/* If the sender has not voted then there is no need to update anything. */
require(senderVote != Vote.Abstention);
/* If we are not voting, there is no reason to update the vote totals. */
if (motionVoting(motionID)) {
if (senderVote == Vote.Yea) {
votesFor[motionID] = safeSub(votesFor[motionID], voteWeight[msg.sender][motionID]);
} else {
/* Since we already ensured that the vote is not an abstention,
* the only option remaining is Vote.Nay. */
votesAgainst[motionID] = safeSub(votesAgainst[motionID], voteWeight[msg.sender][motionID]);
}
/* A cancelled vote is only meaningful if a vote is running. */
emit VoteCancelled(msg.sender, motionID);
}
delete voteWeight[msg.sender][motionID];
delete vote[msg.sender][motionID];
}
/**
* @notice clear all data associated with a motionID for hygiene purposes.
*/
function _closeMotion(uint motionID)
internal
{
delete targetMotionID[motionTarget[motionID]];
delete motionTarget[motionID];
delete motionStartTime[motionID];
delete votesFor[motionID];
delete votesAgainst[motionID];
emit MotionClosed(motionID);
}
/**
* @notice If a motion has concluded, or if it lasted its full duration but not passed,
* then anyone may close it.
*/
function closeMotion(uint motionID)
external
{
require((motionConfirming(motionID) && !motionPasses(motionID)) || motionWaiting(motionID));
_closeMotion(motionID);
}
/**
* @notice The foundation may only confiscate a balance during the confirmation
* period after a motion has passed.
*/
function approveMotion(uint motionID)
external
onlyOwner
{
require(motionConfirming(motionID) && motionPasses(motionID));
address target = motionTarget[motionID];
nomin.freezeAndConfiscate(target);
_closeMotion(motionID);
emit MotionApproved(motionID);
}
/* @notice The foundation may veto a motion at any time. */
function vetoMotion(uint motionID)
external
onlyOwner
{
require(!motionWaiting(motionID));
_closeMotion(motionID);
emit MotionVetoed(motionID);
}
/* ========== EVENTS ========== */
event MotionBegun(address indexed initiator, address indexed target, uint indexed motionID, uint startTime);
event VotedFor(address indexed voter, uint indexed motionID, uint weight);
event VotedAgainst(address indexed voter, uint indexed motionID, uint weight);
event VoteCancelled(address indexed voter, uint indexed motionID);
event MotionClosed(uint indexed motionID);
event MotionVetoed(uint indexed motionID);
event MotionApproved(uint indexed motionID);
}
/*
-----------------------------------------------------------------
FILE INFORMATION
-----------------------------------------------------------------
file: Nomin.sol
version: 1.2
author: Anton Jurisevic
Mike Spain
Dominic Romanowski
Kevin Brown
date: 2018-05-29
-----------------------------------------------------------------
MODULE DESCRIPTION
-----------------------------------------------------------------
Havven-backed nomin stablecoin contract.
This contract issues nomins, which are tokens worth 1 USD each.
Nomins are issuable by Havven holders who have to lock up some
value of their havvens to issue H * Cmax nomins. Where Cmax is
some value less than 1.
A configurable fee is charged on nomin transfers and deposited
into a common pot, which havven holders may withdraw from once
per fee period.
-----------------------------------------------------------------
*/
contract Nomin is FeeToken {
/* ========== STATE VARIABLES ========== */
// The address of the contract which manages confiscation votes.
Court public court;
Havven public havven;
// Accounts which have lost the privilege to transact in nomins.
mapping(address => bool) public frozen;
// Nomin transfers incur a 15 bp fee by default.
uint constant TRANSFER_FEE_RATE = 15 * UNIT / 10000;
string constant TOKEN_NAME = "Nomin USD";
string constant TOKEN_SYMBOL = "nUSD";
/* ========== CONSTRUCTOR ========== */
constructor(address _proxy, TokenState _tokenState, Havven _havven,
uint _totalSupply,
address _owner)
FeeToken(_proxy, _tokenState,
TOKEN_NAME, TOKEN_SYMBOL, _totalSupply,
TRANSFER_FEE_RATE,
_havven, // The havven contract is the fee authority.
_owner)
public
{
require(_proxy != 0 && address(_havven) != 0 && _owner != 0);
// It should not be possible to transfer to the fee pool directly (or confiscate its balance).
frozen[FEE_ADDRESS] = true;
havven = _havven;
}
/* ========== SETTERS ========== */
function setCourt(Court _court)
external
optionalProxy_onlyOwner
{
court = _court;
emitCourtUpdated(_court);
}
function setHavven(Havven _havven)
external
optionalProxy_onlyOwner
{
// havven should be set as the feeAuthority after calling this depending on
// havven's internal logic
havven = _havven;
setFeeAuthority(_havven);
emitHavvenUpdated(_havven);
}
/* ========== MUTATIVE FUNCTIONS ========== */
/* Override ERC20 transfer function in order to check
* whether the recipient account is frozen. Note that there is
* no need to check whether the sender has a frozen account,
* since their funds have already been confiscated,
* and no new funds can be transferred to it.*/
function transfer(address to, uint value)
public
optionalProxy
returns (bool)
{
require(!frozen[to]);
return _transfer_byProxy(messageSender, to, value);
}
/* Override ERC20 transferFrom function in order to check
* whether the recipient account is frozen. */
function transferFrom(address from, address to, uint value)
public
optionalProxy
returns (bool)
{
require(!frozen[to]);
return _transferFrom_byProxy(messageSender, from, to, value);
}
function transferSenderPaysFee(address to, uint value)
public
optionalProxy
returns (bool)
{
require(!frozen[to]);
return _transferSenderPaysFee_byProxy(messageSender, to, value);
}
function transferFromSenderPaysFee(address from, address to, uint value)
public
optionalProxy
returns (bool)
{
require(!frozen[to]);
return _transferFromSenderPaysFee_byProxy(messageSender, from, to, value);
}
/* If a confiscation court motion has passed and reached the confirmation
* state, the court may transfer the target account's balance to the fee pool
* and freeze its participation in further transactions. */
function freezeAndConfiscate(address target)
external
onlyCourt
{
// A motion must actually be underway.
uint motionID = court.targetMotionID(target);
require(motionID != 0);
// These checks are strictly unnecessary,
// since they are already checked in the court contract itself.
require(court.motionConfirming(motionID));
require(court.motionPasses(motionID));
require(!frozen[target]);
// Confiscate the balance in the account and freeze it.
uint balance = tokenState.balanceOf(target);
tokenState.setBalanceOf(FEE_ADDRESS, safeAdd(tokenState.balanceOf(FEE_ADDRESS), balance));
tokenState.setBalanceOf(target, 0);
frozen[target] = true;
emitAccountFrozen(target, balance);
emitTransfer(target, FEE_ADDRESS, balance);
}
/* The owner may allow a previously-frozen contract to once
* again accept and transfer nomins. */
function unfreezeAccount(address target)
external
optionalProxy_onlyOwner
{
require(frozen[target] && target != FEE_ADDRESS);
frozen[target] = false;
emitAccountUnfrozen(target);
}
/* Allow havven to issue a certain number of
* nomins from an account. */
function issue(address account, uint amount)
external
onlyHavven
{
tokenState.setBalanceOf(account, safeAdd(tokenState.balanceOf(account), amount));
totalSupply = safeAdd(totalSupply, amount);
emitTransfer(address(0), account, amount);
emitIssued(account, amount);
}
/* Allow havven to burn a certain number of
* nomins from an account. */
function burn(address account, uint amount)
external
onlyHavven
{
tokenState.setBalanceOf(account, safeSub(tokenState.balanceOf(account), amount));
totalSupply = safeSub(totalSupply, amount);
emitTransfer(account, address(0), amount);
emitBurned(account, amount);
}
/* ========== MODIFIERS ========== */
modifier onlyHavven() {
require(Havven(msg.sender) == havven);
_;
}
modifier onlyCourt() {
require(Court(msg.sender) == court);
_;
}
/* ========== EVENTS ========== */
event CourtUpdated(address newCourt);
bytes32 constant COURTUPDATED_SIG = keccak256("CourtUpdated(address)");
function emitCourtUpdated(address newCourt) internal {
proxy._emit(abi.encode(newCourt), 1, COURTUPDATED_SIG, 0, 0, 0);
}
event HavvenUpdated(address newHavven);
bytes32 constant HAVVENUPDATED_SIG = keccak256("HavvenUpdated(address)");
function emitHavvenUpdated(address newHavven) internal {
proxy._emit(abi.encode(newHavven), 1, HAVVENUPDATED_SIG, 0, 0, 0);
}
event AccountFrozen(address indexed target, uint balance);
bytes32 constant ACCOUNTFROZEN_SIG = keccak256("AccountFrozen(address,uint256)");
function emitAccountFrozen(address target, uint balance) internal {
proxy._emit(abi.encode(balance), 2, ACCOUNTFROZEN_SIG, bytes32(target), 0, 0);
}
event AccountUnfrozen(address indexed target);
bytes32 constant ACCOUNTUNFROZEN_SIG = keccak256("AccountUnfrozen(address)");
function emitAccountUnfrozen(address target) internal {
proxy._emit(abi.encode(), 2, ACCOUNTUNFROZEN_SIG, bytes32(target), 0, 0);
}
event Issued(address indexed account, uint amount);
bytes32 constant ISSUED_SIG = keccak256("Issued(address,uint256)");
function emitIssued(address account, uint amount) internal {
proxy._emit(abi.encode(amount), 2, ISSUED_SIG, bytes32(account), 0, 0);
}
event Burned(address indexed account, uint amount);
bytes32 constant BURNED_SIG = keccak256("Burned(address,uint256)");
function emitBurned(address account, uint amount) internal {
proxy._emit(abi.encode(amount), 2, BURNED_SIG, bytes32(account), 0, 0);
}
}
/*
-----------------------------------------------------------------
FILE INFORMATION
-----------------------------------------------------------------
file: LimitedSetup.sol
version: 1.1
author: Anton Jurisevic
date: 2018-05-15
-----------------------------------------------------------------
MODULE DESCRIPTION
-----------------------------------------------------------------
A contract with a limited setup period. Any function modified
with the setup modifier will cease to work after the
conclusion of the configurable-length post-construction setup period.
-----------------------------------------------------------------
*/
/**
* @title Any function decorated with the modifier this contract provides
* deactivates after a specified setup period.
*/
contract LimitedSetup {
uint setupExpiryTime;
/**
* @dev LimitedSetup Constructor.
* @param setupDuration The time the setup period will last for.
*/
constructor(uint setupDuration)
public
{
setupExpiryTime = now + setupDuration;
}
modifier onlyDuringSetup
{
require(now < setupExpiryTime);
_;
}
}
/*
-----------------------------------------------------------------
FILE INFORMATION
-----------------------------------------------------------------
file: HavvenEscrow.sol
version: 1.1
author: Anton Jurisevic
Dominic Romanowski
Mike Spain
date: 2018-05-29
-----------------------------------------------------------------
MODULE DESCRIPTION
-----------------------------------------------------------------
This contract allows the foundation to apply unique vesting
schedules to havven funds sold at various discounts in the token
sale. HavvenEscrow gives users the ability to inspect their
vested funds, their quantities and vesting dates, and to withdraw
the fees that accrue on those funds.
The fees are handled by withdrawing the entire fee allocation
for all havvens inside the escrow contract, and then allowing
the contract itself to subdivide that pool up proportionally within
itself. Every time the fee period rolls over in the main Havven
contract, the HavvenEscrow fee pool is remitted back into the
main fee pool to be redistributed in the next fee period.
-----------------------------------------------------------------
*/
/**
* @title A contract to hold escrowed havvens and free them at given schedules.
*/
contract HavvenEscrow is SafeDecimalMath, Owned, LimitedSetup(8 weeks) {
/* The corresponding Havven contract. */
Havven public havven;
/* Lists of (timestamp, quantity) pairs per account, sorted in ascending time order.
* These are the times at which each given quantity of havvens vests. */
mapping(address => uint[2][]) public vestingSchedules;
/* An account's total vested havven balance to save recomputing this for fee extraction purposes. */
mapping(address => uint) public totalVestedAccountBalance;
/* The total remaining vested balance, for verifying the actual havven balance of this contract against. */
uint public totalVestedBalance;
uint constant TIME_INDEX = 0;
uint constant QUANTITY_INDEX = 1;
/* Limit vesting entries to disallow unbounded iteration over vesting schedules. */
uint constant MAX_VESTING_ENTRIES = 20;
/* ========== CONSTRUCTOR ========== */
constructor(address _owner, Havven _havven)
Owned(_owner)
public
{
havven = _havven;
}
/* ========== SETTERS ========== */
function setHavven(Havven _havven)
external
onlyOwner
{
havven = _havven;
emit HavvenUpdated(_havven);
}
/* ========== VIEW FUNCTIONS ========== */
/**
* @notice A simple alias to totalVestedAccountBalance: provides ERC20 balance integration.
*/
function balanceOf(address account)
public
view
returns (uint)
{
return totalVestedAccountBalance[account];
}
/**
* @notice The number of vesting dates in an account's schedule.
*/
function numVestingEntries(address account)
public
view
returns (uint)
{
return vestingSchedules[account].length;
}
/**
* @notice Get a particular schedule entry for an account.
* @return A pair of uints: (timestamp, havven quantity).
*/
function getVestingScheduleEntry(address account, uint index)
public
view
returns (uint[2])
{
return vestingSchedules[account][index];
}
/**
* @notice Get the time at which a given schedule entry will vest.
*/
function getVestingTime(address account, uint index)
public
view
returns (uint)
{
return getVestingScheduleEntry(account,index)[TIME_INDEX];
}
/**
* @notice Get the quantity of havvens associated with a given schedule entry.
*/
function getVestingQuantity(address account, uint index)
public
view
returns (uint)
{
return getVestingScheduleEntry(account,index)[QUANTITY_INDEX];
}
/**
* @notice Obtain the index of the next schedule entry that will vest for a given user.
*/
function getNextVestingIndex(address account)
public
view
returns (uint)
{
uint len = numVestingEntries(account);
for (uint i = 0; i < len; i++) {
if (getVestingTime(account, i) != 0) {
return i;
}
}
return len;
}
/**
* @notice Obtain the next schedule entry that will vest for a given user.
* @return A pair of uints: (timestamp, havven quantity). */
function getNextVestingEntry(address account)
public
view
returns (uint[2])
{
uint index = getNextVestingIndex(account);
if (index == numVestingEntries(account)) {
return [uint(0), 0];
}
return getVestingScheduleEntry(account, index);
}
/**
* @notice Obtain the time at which the next schedule entry will vest for a given user.
*/
function getNextVestingTime(address account)
external
view
returns (uint)
{
return getNextVestingEntry(account)[TIME_INDEX];
}
/**
* @notice Obtain the quantity which the next schedule entry will vest for a given user.
*/
function getNextVestingQuantity(address account)
external
view
returns (uint)
{
return getNextVestingEntry(account)[QUANTITY_INDEX];
}
/* ========== MUTATIVE FUNCTIONS ========== */
/**
* @notice Withdraws a quantity of havvens back to the havven contract.
* @dev This may only be called by the owner during the contract's setup period.
*/
function withdrawHavvens(uint quantity)
external
onlyOwner
onlyDuringSetup
{
havven.transfer(havven, quantity);
}
/**
* @notice Destroy the vesting information associated with an account.
*/
function purgeAccount(address account)
external
onlyOwner
onlyDuringSetup
{
delete vestingSchedules[account];
totalVestedBalance = safeSub(totalVestedBalance, totalVestedAccountBalance[account]);
delete totalVestedAccountBalance[account];
}
/**
* @notice Add a new vesting entry at a given time and quantity to an account's schedule.
* @dev A call to this should be accompanied by either enough balance already available
* in this contract, or a corresponding call to havven.endow(), to ensure that when
* the funds are withdrawn, there is enough balance, as well as correctly calculating
* the fees.
* This may only be called by the owner during the contract's setup period.
* Note; although this function could technically be used to produce unbounded
* arrays, it's only in the foundation's command to add to these lists.
* @param account The account to append a new vesting entry to.
* @param time The absolute unix timestamp after which the vested quantity may be withdrawn.
* @param quantity The quantity of havvens that will vest.
*/
function appendVestingEntry(address account, uint time, uint quantity)
public
onlyOwner
onlyDuringSetup
{
/* No empty or already-passed vesting entries allowed. */
require(now < time);
require(quantity != 0);
/* There must be enough balance in the contract to provide for the vesting entry. */
totalVestedBalance = safeAdd(totalVestedBalance, quantity);
require(totalVestedBalance <= havven.balanceOf(this));
/* Disallow arbitrarily long vesting schedules in light of the gas limit. */
uint scheduleLength = vestingSchedules[account].length;
require(scheduleLength <= MAX_VESTING_ENTRIES);
if (scheduleLength == 0) {
totalVestedAccountBalance[account] = quantity;
} else {
/* Disallow adding new vested havvens earlier than the last one.
* Since entries are only appended, this means that no vesting date can be repeated. */
require(getVestingTime(account, numVestingEntries(account) - 1) < time);
totalVestedAccountBalance[account] = safeAdd(totalVestedAccountBalance[account], quantity);
}
vestingSchedules[account].push([time, quantity]);
}
/**
* @notice Construct a vesting schedule to release a quantities of havvens
* over a series of intervals.
* @dev Assumes that the quantities are nonzero
* and that the sequence of timestamps is strictly increasing.
* This may only be called by the owner during the contract's setup period.
*/
function addVestingSchedule(address account, uint[] times, uint[] quantities)
external
onlyOwner
onlyDuringSetup
{
for (uint i = 0; i < times.length; i++) {
appendVestingEntry(account, times[i], quantities[i]);
}
}
/**
* @notice Allow a user to withdraw any havvens in their schedule that have vested.
*/
function vest()
external
{
uint numEntries = numVestingEntries(msg.sender);
uint total;
for (uint i = 0; i < numEntries; i++) {
uint time = getVestingTime(msg.sender, i);
/* The list is sorted; when we reach the first future time, bail out. */
if (time > now) {
break;
}
uint qty = getVestingQuantity(msg.sender, i);
if (qty == 0) {
continue;
}
vestingSchedules[msg.sender][i] = [0, 0];
total = safeAdd(total, qty);
}
if (total != 0) {
totalVestedBalance = safeSub(totalVestedBalance, total);
totalVestedAccountBalance[msg.sender] = safeSub(totalVestedAccountBalance[msg.sender], total);
havven.transfer(msg.sender, total);
emit Vested(msg.sender, now, total);
}
}
/* ========== EVENTS ========== */
event HavvenUpdated(address newHavven);
event Vested(address indexed beneficiary, uint time, uint value);
}
/*
-----------------------------------------------------------------
FILE INFORMATION
-----------------------------------------------------------------
file: Havven.sol
version: 1.2
author: Anton Jurisevic
Dominic Romanowski
date: 2018-05-15
-----------------------------------------------------------------
MODULE DESCRIPTION
-----------------------------------------------------------------
Havven token contract. Havvens are transferable ERC20 tokens,
and also give their holders the following privileges.
An owner of havvens may participate in nomin confiscation votes, they
may also have the right to issue nomins at the discretion of the
foundation for this version of the contract.
After a fee period terminates, the duration and fees collected for that
period are computed, and the next period begins. Thus an account may only
withdraw the fees owed to them for the previous period, and may only do
so once per period. Any unclaimed fees roll over into the common pot for
the next period.
== Average Balance Calculations ==
The fee entitlement of a havven holder is proportional to their average
issued nomin balance over the last fee period. This is computed by
measuring the area under the graph of a user's issued nomin balance over
time, and then when a new fee period begins, dividing through by the
duration of the fee period.
We need only update values when the balances of an account is modified.
This occurs when issuing or burning for issued nomin balances,
and when transferring for havven balances. This is for efficiency,
and adds an implicit friction to interacting with havvens.
A havven holder pays for his own recomputation whenever he wants to change
his position, which saves the foundation having to maintain a pot dedicated
to resourcing this.
A hypothetical user's balance history over one fee period, pictorially:
s ____
| |
| |___ p
|____|___|___ __ _ _
f t n
Here, the balance was s between times f and t, at which time a transfer
occurred, updating the balance to p, until n, when the present transfer occurs.
When a new transfer occurs at time n, the balance being p,
we must:
- Add the area p * (n - t) to the total area recorded so far
- Update the last transfer time to n
So if this graph represents the entire current fee period,
the average havvens held so far is ((t-f)*s + (n-t)*p) / (n-f).
The complementary computations must be performed for both sender and
recipient.
Note that a transfer keeps global supply of havvens invariant.
The sum of all balances is constant, and unmodified by any transfer.
So the sum of all balances multiplied by the duration of a fee period is also
constant, and this is equivalent to the sum of the area of every user's
time/balance graph. Dividing through by that duration yields back the total
havven supply. So, at the end of a fee period, we really do yield a user's
average share in the havven supply over that period.
A slight wrinkle is introduced if we consider the time r when the fee period
rolls over. Then the previous fee period k-1 is before r, and the current fee
period k is afterwards. If the last transfer took place before r,
but the latest transfer occurred afterwards:
k-1 | k
s __|_
| | |
| | |____ p
|__|_|____|___ __ _ _
|
f | t n
r
In this situation the area (r-f)*s contributes to fee period k-1, while
the area (t-r)*s contributes to fee period k. We will implicitly consider a
zero-value transfer to have occurred at time r. Their fee entitlement for the
previous period will be finalised at the time of their first transfer during the
current fee period, or when they query or withdraw their fee entitlement.
In the implementation, the duration of different fee periods may be slightly irregular,
as the check that they have rolled over occurs only when state-changing havven
operations are performed.
== Issuance and Burning ==
In this version of the havven contract, nomins can only be issued by
those that have been nominated by the havven foundation. Nomins are assumed
to be valued at $1, as they are a stable unit of account.
All nomins issued require a proportional value of havvens to be locked,
where the proportion is governed by the current issuance ratio. This
means for every $1 of Havvens locked up, $(issuanceRatio) nomins can be issued.
i.e. to issue 100 nomins, 100/issuanceRatio dollars of havvens need to be locked up.
To determine the value of some amount of havvens(H), an oracle is used to push
the price of havvens (P_H) in dollars to the contract. The value of H
would then be: H * P_H.
Any havvens that are locked up by this issuance process cannot be transferred.
The amount that is locked floats based on the price of havvens. If the price
of havvens moves up, less havvens are locked, so they can be issued against,
or transferred freely. If the price of havvens moves down, more havvens are locked,
even going above the initial wallet balance.
-----------------------------------------------------------------
*/
/**
* @title Havven ERC20 contract.
* @notice The Havven contracts does not only facilitate transfers and track balances,
* but it also computes the quantity of fees each havven holder is entitled to.
*/
contract Havven is ExternStateToken {
/* ========== STATE VARIABLES ========== */
/* A struct for handing values associated with average balance calculations */
struct IssuanceData {
/* Sums of balances*duration in the current fee period.
/* range: decimals; units: havven-seconds */
uint currentBalanceSum;
/* The last period's average balance */
uint lastAverageBalance;
/* The last time the data was calculated */
uint lastModified;
}
/* Issued nomin balances for individual fee entitlements */
mapping(address => IssuanceData) public issuanceData;
/* The total number of issued nomins for determining fee entitlements */
IssuanceData public totalIssuanceData;
/* The time the current fee period began */
uint public feePeriodStartTime;
/* The time the last fee period began */
uint public lastFeePeriodStartTime;
/* Fee periods will roll over in no shorter a time than this.
* The fee period cannot actually roll over until a fee-relevant
* operation such as withdrawal or a fee period duration update occurs,
* so this is just a target, and the actual duration may be slightly longer. */
uint public feePeriodDuration = 4 weeks;
/* ...and must target between 1 day and six months. */
uint constant MIN_FEE_PERIOD_DURATION = 1 days;
uint constant MAX_FEE_PERIOD_DURATION = 26 weeks;
/* The quantity of nomins that were in the fee pot at the time */
/* of the last fee rollover, at feePeriodStartTime. */
uint public lastFeesCollected;
/* Whether a user has withdrawn their last fees */
mapping(address => bool) public hasWithdrawnFees;
Nomin public nomin;
HavvenEscrow public escrow;
/* The address of the oracle which pushes the havven price to this contract */
address public oracle;
/* The price of havvens written in UNIT */
uint public price;
/* The time the havven price was last updated */
uint public lastPriceUpdateTime;
/* How long will the contract assume the price of havvens is correct */
uint public priceStalePeriod = 3 hours;
/* A quantity of nomins greater than this ratio
* may not be issued against a given value of havvens. */
uint public issuanceRatio = UNIT / 5;
/* No more nomins may be issued than the value of havvens backing them. */
uint constant MAX_ISSUANCE_RATIO = UNIT;
/* Whether the address can issue nomins or not. */
mapping(address => bool) public isIssuer;
/* The number of currently-outstanding nomins the user has issued. */
mapping(address => uint) public nominsIssued;
uint constant HAVVEN_SUPPLY = 1e8 * UNIT;
uint constant ORACLE_FUTURE_LIMIT = 10 minutes;
string constant TOKEN_NAME = "Havven";
string constant TOKEN_SYMBOL = "HAV";
/* ========== CONSTRUCTOR ========== */
/**
* @dev Constructor
* @param _tokenState A pre-populated contract containing token balances.
* If the provided address is 0x0, then a fresh one will be constructed with the contract owning all tokens.
* @param _owner The owner of this contract.
*/
constructor(address _proxy, TokenState _tokenState, address _owner, address _oracle,
uint _price, address[] _issuers, Havven _oldHavven)
ExternStateToken(_proxy, _tokenState, TOKEN_NAME, TOKEN_SYMBOL, HAVVEN_SUPPLY, _owner)
public
{
oracle = _oracle;
price = _price;
lastPriceUpdateTime = now;
uint i;
if (_oldHavven == address(0)) {
feePeriodStartTime = now;
lastFeePeriodStartTime = now - feePeriodDuration;
for (i = 0; i < _issuers.length; i++) {
isIssuer[_issuers[i]] = true;
}
} else {
feePeriodStartTime = _oldHavven.feePeriodStartTime();
lastFeePeriodStartTime = _oldHavven.lastFeePeriodStartTime();
uint cbs;
uint lab;
uint lm;
(cbs, lab, lm) = _oldHavven.totalIssuanceData();
totalIssuanceData.currentBalanceSum = cbs;
totalIssuanceData.lastAverageBalance = lab;
totalIssuanceData.lastModified = lm;
for (i = 0; i < _issuers.length; i++) {
address issuer = _issuers[i];
isIssuer[issuer] = true;
uint nomins = _oldHavven.nominsIssued(issuer);
if (nomins == 0) {
// It is not valid in general to skip those with no currently-issued nomins.
// But for this release, issuers with nonzero issuanceData have current issuance.
continue;
}
(cbs, lab, lm) = _oldHavven.issuanceData(issuer);
nominsIssued[issuer] = nomins;
issuanceData[issuer].currentBalanceSum = cbs;
issuanceData[issuer].lastAverageBalance = lab;
issuanceData[issuer].lastModified = lm;
}
}
}
/* ========== SETTERS ========== */
/**
* @notice Set the associated Nomin contract to collect fees from.
* @dev Only the contract owner may call this.
*/
function setNomin(Nomin _nomin)
external
optionalProxy_onlyOwner
{
nomin = _nomin;
emitNominUpdated(_nomin);
}
/**
* @notice Set the associated havven escrow contract.
* @dev Only the contract owner may call this.
*/
function setEscrow(HavvenEscrow _escrow)
external
optionalProxy_onlyOwner
{
escrow = _escrow;
emitEscrowUpdated(_escrow);
}
/**
* @notice Set the targeted fee period duration.
* @dev Only callable by the contract owner. The duration must fall within
* acceptable bounds (1 day to 26 weeks). Upon resetting this the fee period
* may roll over if the target duration was shortened sufficiently.
*/
function setFeePeriodDuration(uint duration)
external
optionalProxy_onlyOwner
{
require(MIN_FEE_PERIOD_DURATION <= duration &&
duration <= MAX_FEE_PERIOD_DURATION);
feePeriodDuration = duration;
emitFeePeriodDurationUpdated(duration);
rolloverFeePeriodIfElapsed();
}
/**
* @notice Set the Oracle that pushes the havven price to this contract
*/
function setOracle(address _oracle)
external
optionalProxy_onlyOwner
{
oracle = _oracle;
emitOracleUpdated(_oracle);
}
/**
* @notice Set the stale period on the updated havven price
* @dev No max/minimum, as changing it wont influence anything but issuance by the foundation
*/
function setPriceStalePeriod(uint time)
external
optionalProxy_onlyOwner
{
priceStalePeriod = time;
}
/**
* @notice Set the issuanceRatio for issuance calculations.
* @dev Only callable by the contract owner.
*/
function setIssuanceRatio(uint _issuanceRatio)
external
optionalProxy_onlyOwner
{
require(_issuanceRatio <= MAX_ISSUANCE_RATIO);
issuanceRatio = _issuanceRatio;
emitIssuanceRatioUpdated(_issuanceRatio);
}
/**
* @notice Set whether the specified can issue nomins or not.
*/
function setIssuer(address account, bool value)
external
optionalProxy_onlyOwner
{
isIssuer[account] = value;
emitIssuersUpdated(account, value);
}
/* ========== VIEWS ========== */
function issuanceCurrentBalanceSum(address account)
external
view
returns (uint)
{
return issuanceData[account].currentBalanceSum;
}
function issuanceLastAverageBalance(address account)
external
view
returns (uint)
{
return issuanceData[account].lastAverageBalance;
}
function issuanceLastModified(address account)
external
view
returns (uint)
{
return issuanceData[account].lastModified;
}
function totalIssuanceCurrentBalanceSum()
external
view
returns (uint)
{
return totalIssuanceData.currentBalanceSum;
}
function totalIssuanceLastAverageBalance()
external
view
returns (uint)
{
return totalIssuanceData.lastAverageBalance;
}
function totalIssuanceLastModified()
external
view
returns (uint)
{
return totalIssuanceData.lastModified;
}
/* ========== MUTATIVE FUNCTIONS ========== */
/**
* @notice ERC20 transfer function.
*/
function transfer(address to, uint value)
public
optionalProxy
returns (bool)
{
address sender = messageSender;
require(nominsIssued[sender] == 0 || value <= transferableHavvens(sender));
/* Perform the transfer: if there is a problem,
* an exception will be thrown in this call. */
_transfer_byProxy(sender, to, value);
return true;
}
/**
* @notice ERC20 transferFrom function.
*/
function transferFrom(address from, address to, uint value)
public
optionalProxy
returns (bool)
{
address sender = messageSender;
require(nominsIssued[from] == 0 || value <= transferableHavvens(from));
/* Perform the transfer: if there is a problem,
* an exception will be thrown in this call. */
_transferFrom_byProxy(sender, from, to, value);
return true;
}
/**
* @notice Compute the last period's fee entitlement for the message sender
* and then deposit it into their nomin account.
*/
function withdrawFees()
external
optionalProxy
{
address sender = messageSender;
rolloverFeePeriodIfElapsed();
/* Do not deposit fees into frozen accounts. */
require(!nomin.frozen(sender));
/* Check the period has rolled over first. */
updateIssuanceData(sender, nominsIssued[sender], nomin.totalSupply());
/* Only allow accounts to withdraw fees once per period. */
require(!hasWithdrawnFees[sender]);
uint feesOwed;
uint lastTotalIssued = totalIssuanceData.lastAverageBalance;
if (lastTotalIssued > 0) {
/* Sender receives a share of last period's collected fees proportional
* with their average fraction of the last period's issued nomins. */
feesOwed = safeDiv_dec(
safeMul_dec(issuanceData[sender].lastAverageBalance, lastFeesCollected),
lastTotalIssued
);
}
hasWithdrawnFees[sender] = true;
if (feesOwed != 0) {
nomin.withdrawFees(sender, feesOwed);
}
emitFeesWithdrawn(messageSender, feesOwed);
}
/**
* @notice Update the havven balance averages since the last transfer
* or entitlement adjustment.
* @dev Since this updates the last transfer timestamp, if invoked
* consecutively, this function will do nothing after the first call.
* Also, this will adjust the total issuance at the same time.
*/
function updateIssuanceData(address account, uint preBalance, uint lastTotalSupply)
internal
{
/* update the total balances first */
totalIssuanceData = computeIssuanceData(lastTotalSupply, totalIssuanceData);
if (issuanceData[account].lastModified < feePeriodStartTime) {
hasWithdrawnFees[account] = false;
}
issuanceData[account] = computeIssuanceData(preBalance, issuanceData[account]);
}
/**
* @notice Compute the new IssuanceData on the old balance
*/
function computeIssuanceData(uint preBalance, IssuanceData preIssuance)
internal
view
returns (IssuanceData)
{
uint currentBalanceSum = preIssuance.currentBalanceSum;
uint lastAverageBalance = preIssuance.lastAverageBalance;
uint lastModified = preIssuance.lastModified;
if (lastModified < feePeriodStartTime) {
if (lastModified < lastFeePeriodStartTime) {
/* The balance was last updated before the previous fee period, so the average
* balance in this period is their pre-transfer balance. */
lastAverageBalance = preBalance;
} else {
/* The balance was last updated during the previous fee period. */
/* No overflow or zero denominator problems, since lastFeePeriodStartTime < feePeriodStartTime < lastModified.
* implies these quantities are strictly positive. */
uint timeUpToRollover = feePeriodStartTime - lastModified;
uint lastFeePeriodDuration = feePeriodStartTime - lastFeePeriodStartTime;
uint lastBalanceSum = safeAdd(currentBalanceSum, safeMul(preBalance, timeUpToRollover));
lastAverageBalance = lastBalanceSum / lastFeePeriodDuration;
}
/* Roll over to the next fee period. */
currentBalanceSum = safeMul(preBalance, now - feePeriodStartTime);
} else {
/* The balance was last updated during the current fee period. */
currentBalanceSum = safeAdd(
currentBalanceSum,
safeMul(preBalance, now - lastModified)
);
}
return IssuanceData(currentBalanceSum, lastAverageBalance, now);
}
/**
* @notice Recompute and return the given account's last average balance.
*/
function recomputeLastAverageBalance(address account)
external
returns (uint)
{
updateIssuanceData(account, nominsIssued[account], nomin.totalSupply());
return issuanceData[account].lastAverageBalance;
}
/**
* @notice Issue nomins against the sender's havvens.
* @dev Issuance is only allowed if the havven price isn't stale and the sender is an issuer.
*/
function issueNomins(uint amount)
public
optionalProxy
requireIssuer(messageSender)
/* No need to check if price is stale, as it is checked in issuableNomins. */
{
address sender = messageSender;
require(amount <= remainingIssuableNomins(sender));
uint lastTot = nomin.totalSupply();
uint preIssued = nominsIssued[sender];
nomin.issue(sender, amount);
nominsIssued[sender] = safeAdd(preIssued, amount);
updateIssuanceData(sender, preIssued, lastTot);
}
function issueMaxNomins()
external
optionalProxy
{
issueNomins(remainingIssuableNomins(messageSender));
}
/**
* @notice Burn nomins to clear issued nomins/free havvens.
*/
function burnNomins(uint amount)
/* it doesn't matter if the price is stale or if the user is an issuer, as non-issuers have issued no nomins.*/
external
optionalProxy
{
address sender = messageSender;
uint lastTot = nomin.totalSupply();
uint preIssued = nominsIssued[sender];
/* nomin.burn does a safeSub on balance (so it will revert if there are not enough nomins). */
nomin.burn(sender, amount);
/* This safe sub ensures amount <= number issued */
nominsIssued[sender] = safeSub(preIssued, amount);
updateIssuanceData(sender, preIssued, lastTot);
}
/**
* @notice Check if the fee period has rolled over. If it has, set the new fee period start
* time, and record the fees collected in the nomin contract.
*/
function rolloverFeePeriodIfElapsed()
public
{
/* If the fee period has rolled over... */
if (now >= feePeriodStartTime + feePeriodDuration) {
lastFeesCollected = nomin.feePool();
lastFeePeriodStartTime = feePeriodStartTime;
feePeriodStartTime = now;
emitFeePeriodRollover(now);
}
}
/* ========== Issuance/Burning ========== */
/**
* @notice The maximum nomins an issuer can issue against their total havven quantity. This ignores any
* already issued nomins.
*/
function maxIssuableNomins(address issuer)
view
public
priceNotStale
returns (uint)
{
if (!isIssuer[issuer]) {
return 0;
}
if (escrow != HavvenEscrow(0)) {
uint totalOwnedHavvens = safeAdd(tokenState.balanceOf(issuer), escrow.balanceOf(issuer));
return safeMul_dec(HAVtoUSD(totalOwnedHavvens), issuanceRatio);
} else {
return safeMul_dec(HAVtoUSD(tokenState.balanceOf(issuer)), issuanceRatio);
}
}
/**
* @notice The remaining nomins an issuer can issue against their total havven quantity.
*/
function remainingIssuableNomins(address issuer)
view
public
returns (uint)
{
uint issued = nominsIssued[issuer];
uint max = maxIssuableNomins(issuer);
if (issued > max) {
return 0;
} else {
return safeSub(max, issued);
}
}
/**
* @notice The total havvens owned by this account, both escrowed and unescrowed,
* against which nomins can be issued.
* This includes those already being used as collateral (locked), and those
* available for further issuance (unlocked).
*/
function collateral(address account)
public
view
returns (uint)
{
uint bal = tokenState.balanceOf(account);
if (escrow != address(0)) {
bal = safeAdd(bal, escrow.balanceOf(account));
}
return bal;
}
/**
* @notice The collateral that would be locked by issuance, which can exceed the account's actual collateral.
*/
function issuanceDraft(address account)
public
view
returns (uint)
{
uint issued = nominsIssued[account];
if (issued == 0) {
return 0;
}
return USDtoHAV(safeDiv_dec(issued, issuanceRatio));
}
/**
* @notice Collateral that has been locked due to issuance, and cannot be
* transferred to other addresses. This is capped at the account's total collateral.
*/
function lockedCollateral(address account)
public
view
returns (uint)
{
uint debt = issuanceDraft(account);
uint collat = collateral(account);
if (debt > collat) {
return collat;
}
return debt;
}
/**
* @notice Collateral that is not locked and available for issuance.
*/
function unlockedCollateral(address account)
public
view
returns (uint)
{
uint locked = lockedCollateral(account);
uint collat = collateral(account);
return safeSub(collat, locked);
}
/**
* @notice The number of havvens that are free to be transferred by an account.
* @dev If they have enough available Havvens, it could be that
* their havvens are escrowed, however the transfer would then
* fail. This means that escrowed havvens are locked first,
* and then the actual transferable ones.
*/
function transferableHavvens(address account)
public
view
returns (uint)
{
uint draft = issuanceDraft(account);
uint collat = collateral(account);
// In the case where the issuanceDraft exceeds the collateral, nothing is free
if (draft > collat) {
return 0;
}
uint bal = balanceOf(account);
// In the case where the draft exceeds the escrow, but not the whole collateral
// return the fraction of the balance that remains free
if (draft > safeSub(collat, bal)) {
return safeSub(collat, draft);
}
// In the case where the draft doesn't exceed the escrow, return the entire balance
return bal;
}
/**
* @notice The value in USD for a given amount of HAV
*/
function HAVtoUSD(uint hav_dec)
public
view
priceNotStale
returns (uint)
{
return safeMul_dec(hav_dec, price);
}
/**
* @notice The value in HAV for a given amount of USD
*/
function USDtoHAV(uint usd_dec)
public
view
priceNotStale
returns (uint)
{
return safeDiv_dec(usd_dec, price);
}
/**
* @notice Access point for the oracle to update the price of havvens.
*/
function updatePrice(uint newPrice, uint timeSent)
external
onlyOracle /* Should be callable only by the oracle. */
{
/* Must be the most recently sent price, but not too far in the future.
* (so we can't lock ourselves out of updating the oracle for longer than this) */
require(lastPriceUpdateTime < timeSent && timeSent < now + ORACLE_FUTURE_LIMIT);
price = newPrice;
lastPriceUpdateTime = timeSent;
emitPriceUpdated(newPrice, timeSent);
/* Check the fee period rollover within this as the price should be pushed every 15min. */
rolloverFeePeriodIfElapsed();
}
/**
* @notice Check if the price of havvens hasn't been updated for longer than the stale period.
*/
function priceIsStale()
public
view
returns (bool)
{
return safeAdd(lastPriceUpdateTime, priceStalePeriod) < now;
}
/* ========== MODIFIERS ========== */
modifier requireIssuer(address account)
{
require(isIssuer[account]);
_;
}
modifier onlyOracle
{
require(msg.sender == oracle);
_;
}
modifier priceNotStale
{
require(!priceIsStale());
_;
}
/* ========== EVENTS ========== */
event PriceUpdated(uint newPrice, uint timestamp);
bytes32 constant PRICEUPDATED_SIG = keccak256("PriceUpdated(uint256,uint256)");
function emitPriceUpdated(uint newPrice, uint timestamp) internal {
proxy._emit(abi.encode(newPrice, timestamp), 1, PRICEUPDATED_SIG, 0, 0, 0);
}
event IssuanceRatioUpdated(uint newRatio);
bytes32 constant ISSUANCERATIOUPDATED_SIG = keccak256("IssuanceRatioUpdated(uint256)");
function emitIssuanceRatioUpdated(uint newRatio) internal {
proxy._emit(abi.encode(newRatio), 1, ISSUANCERATIOUPDATED_SIG, 0, 0, 0);
}
event FeePeriodRollover(uint timestamp);
bytes32 constant FEEPERIODROLLOVER_SIG = keccak256("FeePeriodRollover(uint256)");
function emitFeePeriodRollover(uint timestamp) internal {
proxy._emit(abi.encode(timestamp), 1, FEEPERIODROLLOVER_SIG, 0, 0, 0);
}
event FeePeriodDurationUpdated(uint duration);
bytes32 constant FEEPERIODDURATIONUPDATED_SIG = keccak256("FeePeriodDurationUpdated(uint256)");
function emitFeePeriodDurationUpdated(uint duration) internal {
proxy._emit(abi.encode(duration), 1, FEEPERIODDURATIONUPDATED_SIG, 0, 0, 0);
}
event FeesWithdrawn(address indexed account, uint value);
bytes32 constant FEESWITHDRAWN_SIG = keccak256("FeesWithdrawn(address,uint256)");
function emitFeesWithdrawn(address account, uint value) internal {
proxy._emit(abi.encode(value), 2, FEESWITHDRAWN_SIG, bytes32(account), 0, 0);
}
event OracleUpdated(address newOracle);
bytes32 constant ORACLEUPDATED_SIG = keccak256("OracleUpdated(address)");
function emitOracleUpdated(address newOracle) internal {
proxy._emit(abi.encode(newOracle), 1, ORACLEUPDATED_SIG, 0, 0, 0);
}
event NominUpdated(address newNomin);
bytes32 constant NOMINUPDATED_SIG = keccak256("NominUpdated(address)");
function emitNominUpdated(address newNomin) internal {
proxy._emit(abi.encode(newNomin), 1, NOMINUPDATED_SIG, 0, 0, 0);
}
event EscrowUpdated(address newEscrow);
bytes32 constant ESCROWUPDATED_SIG = keccak256("EscrowUpdated(address)");
function emitEscrowUpdated(address newEscrow) internal {
proxy._emit(abi.encode(newEscrow), 1, ESCROWUPDATED_SIG, 0, 0, 0);
}
event IssuersUpdated(address indexed account, bool indexed value);
bytes32 constant ISSUERSUPDATED_SIG = keccak256("IssuersUpdated(address,bool)");
function emitIssuersUpdated(address account, bool value) internal {
proxy._emit(abi.encode(), 3, ISSUERSUPDATED_SIG, bytes32(account), bytes32(value ? 1 : 0), 0);
}
}
|
Override ERC20 transfer function in order to check whether the recipient account is frozen. Note that there is no need to check whether the sender has a frozen account, since their funds have already been confiscated, and no new funds can be transferred to it./
|
function transfer(address to, uint value)
public
optionalProxy
returns (bool)
{
require(!frozen[to]);
return _transfer_byProxy(messageSender, to, value);
}
| 6,482,257 |
// SPDX-License-Identifier: MIT
pragma solidity 0.8.9;
// Part: IBasicRewards
interface IBasicRewards {
function stakeFor(address, uint256) external returns (bool);
function balanceOf(address) external view returns (uint256);
function withdrawAll(bool) external;
function getReward() external returns (bool);
}
// Part: ICurveFactoryPool
interface ICurveFactoryPool {
function get_dy(
int128 i,
int128 j,
uint256 dx
) external view returns (uint256);
function get_balances() external view returns (uint256[2] memory);
function add_liquidity(
uint256[2] memory _amounts,
uint256 _min_mint_amount,
address _receiver
) external returns (uint256);
function exchange(
int128 i,
int128 j,
uint256 _dx,
uint256 _min_dy,
address _receiver
) external returns (uint256);
}
// Part: ICurveV2Pool
interface ICurveV2Pool {
function get_dy(
uint256 i,
uint256 j,
uint256 dx
) external view returns (uint256);
function exchange_underlying(
uint256 i,
uint256 j,
uint256 dx,
uint256 min_dy
) external payable returns (uint256);
}
// Part: OpenZeppelin/[email protected]/Address
/**
* @dev Collection of functions related to the address type
*/
library Address {
/**
* @dev Returns true if `account` is a contract.
*
* [IMPORTANT]
* ====
* It is unsafe to assume that an address for which this function returns
* false is an externally-owned account (EOA) and not a contract.
*
* Among others, `isContract` will return false for the following
* types of addresses:
*
* - an externally-owned account
* - a contract in construction
* - an address where a contract will be created
* - an address where a contract lived, but was destroyed
* ====
*/
function isContract(address account) internal view returns (bool) {
// This method relies on extcodesize, which returns 0 for contracts in
// construction, since the code is only stored at the end of the
// constructor execution.
uint256 size;
// solhint-disable-next-line no-inline-assembly
assembly { size := extcodesize(account) }
return size > 0;
}
/**
* @dev Replacement for Solidity's `transfer`: sends `amount` wei to
* `recipient`, forwarding all available gas and reverting on errors.
*
* https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost
* of certain opcodes, possibly making contracts go over the 2300 gas limit
* imposed by `transfer`, making them unable to receive funds via
* `transfer`. {sendValue} removes this limitation.
*
* https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more].
*
* IMPORTANT: because control is transferred to `recipient`, care must be
* taken to not create reentrancy vulnerabilities. Consider using
* {ReentrancyGuard} or the
* https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern].
*/
function sendValue(address payable recipient, uint256 amount) internal {
require(address(this).balance >= amount, "Address: insufficient balance");
// solhint-disable-next-line avoid-low-level-calls, avoid-call-value
(bool success, ) = recipient.call{ value: amount }("");
require(success, "Address: unable to send value, recipient may have reverted");
}
/**
* @dev Performs a Solidity function call using a low level `call`. A
* plain`call` is an unsafe replacement for a function call: use this
* function instead.
*
* If `target` reverts with a revert reason, it is bubbled up by this
* function (like regular Solidity function calls).
*
* Returns the raw returned data. To convert to the expected return value,
* use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`].
*
* 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");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with
* `errorMessage` as a fallback revert reason when `target` reverts.
*
* _Available since v3.1._
*/
function functionCall(address target, bytes memory data, string memory errorMessage) internal returns (bytes memory) {
return functionCallWithValue(target, data, 0, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but also transferring `value` wei to `target`.
*
* Requirements:
*
* - the calling contract must have an ETH balance of at least `value`.
* - the called Solidity function must be `payable`.
*
* _Available since v3.1._
*/
function functionCallWithValue(address target, bytes memory data, uint256 value) internal returns (bytes memory) {
return functionCallWithValue(target, data, value, "Address: low-level call with value failed");
}
/**
* @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but
* with `errorMessage` as a fallback revert reason when `target` reverts.
*
* _Available since v3.1._
*/
function functionCallWithValue(address target, bytes memory data, uint256 value, string memory errorMessage) internal returns (bytes memory) {
require(address(this).balance >= value, "Address: insufficient balance for call");
require(isContract(target), "Address: call to non-contract");
// solhint-disable-next-line avoid-low-level-calls
(bool success, bytes memory returndata) = target.call{ value: value }(data);
return _verifyCallResult(success, returndata, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but performing a static call.
*
* _Available since v3.3._
*/
function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) {
return functionStaticCall(target, data, "Address: low-level static call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`],
* but performing a static call.
*
* _Available since v3.3._
*/
function functionStaticCall(address target, bytes memory data, string memory errorMessage) internal view returns (bytes memory) {
require(isContract(target), "Address: static call to non-contract");
// solhint-disable-next-line avoid-low-level-calls
(bool success, bytes memory returndata) = target.staticcall(data);
return _verifyCallResult(success, returndata, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but performing a delegate call.
*
* _Available since v3.4._
*/
function functionDelegateCall(address target, bytes memory data) internal returns (bytes memory) {
return functionDelegateCall(target, data, "Address: low-level delegate call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`],
* but performing a delegate call.
*
* _Available since v3.4._
*/
function functionDelegateCall(address target, bytes memory data, string memory errorMessage) internal returns (bytes memory) {
require(isContract(target), "Address: delegate call to non-contract");
// solhint-disable-next-line avoid-low-level-calls
(bool success, bytes memory returndata) = target.delegatecall(data);
return _verifyCallResult(success, returndata, errorMessage);
}
function _verifyCallResult(bool success, bytes memory returndata, string memory errorMessage) private pure returns(bytes memory) {
if (success) {
return returndata;
} else {
// Look for revert reason and bubble it up if present
if (returndata.length > 0) {
// The easiest way to bubble the revert reason is using memory via assembly
// solhint-disable-next-line no-inline-assembly
assembly {
let returndata_size := mload(returndata)
revert(add(32, returndata), returndata_size)
}
} else {
revert(errorMessage);
}
}
}
}
// Part: OpenZeppelin/[email protected]/IERC20
/**
* @dev Interface of the ERC20 standard as defined in the EIP.
*/
interface IERC20 {
/**
* @dev Returns the amount of tokens in existence.
*/
function totalSupply() external view returns (uint256);
/**
* @dev Returns the amount of tokens owned by `account`.
*/
function balanceOf(address account) external view returns (uint256);
/**
* @dev Moves `amount` tokens from the caller's account to `recipient`.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/
function transfer(address recipient, uint256 amount) external returns (bool);
/**
* @dev Returns the remaining number of tokens that `spender` will be
* allowed to spend on behalf of `owner` through {transferFrom}. This is
* zero by default.
*
* This value changes when {approve} or {transferFrom} are called.
*/
function allowance(address owner, address spender) external view returns (uint256);
/**
* @dev Sets `amount` as the allowance of `spender` over the caller's tokens.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* IMPORTANT: 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
*
* Emits an {Approval} event.
*/
function approve(address spender, uint256 amount) external returns (bool);
/**
* @dev Moves `amount` tokens from `sender` to `recipient` using the
* allowance mechanism. `amount` is then deducted from the caller's
* allowance.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/
function transferFrom(address sender, address recipient, uint256 amount) external returns (bool);
/**
* @dev Emitted when `value` tokens are moved from one account (`from`) to
* another (`to`).
*
* Note that `value` may be zero.
*/
event Transfer(address indexed from, address indexed to, uint256 value);
/**
* @dev Emitted when the allowance of a `spender` for an `owner` is set by
* a call to {approve}. `value` is the new allowance.
*/
event Approval(address indexed owner, address indexed spender, uint256 value);
}
// Part: OpenZeppelin/[email protected]/MerkleProof
/**
* @dev These functions deal with verification of Merkle Trees proofs.
*
* The proofs can be generated using the JavaScript library
* https://github.com/miguelmota/merkletreejs[merkletreejs].
* Note: the hashing algorithm should be keccak256 and pair sorting should be enabled.
*
* See `test/utils/cryptography/MerkleProof.test.js` for some examples.
*/
library MerkleProof {
/**
* @dev Returns true if a `leaf` can be proved to be a part of a Merkle tree
* defined by `root`. For this, a `proof` must be provided, containing
* sibling hashes on the branch from the leaf to the root of the tree. Each
* pair of leaves and each pair of pre-images are assumed to be sorted.
*/
function verify(bytes32[] memory proof, bytes32 root, bytes32 leaf) internal pure returns (bool) {
bytes32 computedHash = leaf;
for (uint256 i = 0; i < proof.length; i++) {
bytes32 proofElement = proof[i];
if (computedHash <= proofElement) {
// Hash(current computed hash + current element of the proof)
computedHash = keccak256(abi.encodePacked(computedHash, proofElement));
} else {
// Hash(current element of the proof + current computed hash)
computedHash = keccak256(abi.encodePacked(proofElement, computedHash));
}
}
// Check if the computed hash (root) is equal to the provided root
return computedHash == root;
}
}
// Part: OpenZeppelin/[email protected]/ReentrancyGuard
/**
* @dev Contract module that helps prevent reentrant calls to a function.
*
* Inheriting from `ReentrancyGuard` will make the {nonReentrant} modifier
* available, which can be applied to functions to make sure there are no nested
* (reentrant) calls to them.
*
* Note that because there is a single `nonReentrant` guard, functions marked as
* `nonReentrant` may not call one another. This can be worked around by making
* those functions `private`, and then adding `external` `nonReentrant` entry
* points to them.
*
* TIP: If you would like to learn more about reentrancy and alternative ways
* to protect against it, check out our blog post
* https://blog.openzeppelin.com/reentrancy-after-istanbul/[Reentrancy After Istanbul].
*/
abstract contract ReentrancyGuard {
// Booleans are more expensive than uint256 or any type that takes up a full
// word because each write operation emits an extra SLOAD to first read the
// slot's contents, replace the bits taken up by the boolean, and then write
// back. This is the compiler's defense against contract upgrades and
// pointer aliasing, and it cannot be disabled.
// The values being non-zero value makes deployment a bit more expensive,
// but in exchange the refund on every call to nonReentrant will be lower in
// amount. Since refunds are capped to a percentage of the total
// transaction's gas, it is best to keep them low in cases like this one, to
// increase the likelihood of the full refund coming into effect.
uint256 private constant _NOT_ENTERED = 1;
uint256 private constant _ENTERED = 2;
uint256 private _status;
constructor () {
_status = _NOT_ENTERED;
}
/**
* @dev Prevents a contract from calling itself, directly or indirectly.
* Calling a `nonReentrant` function from another `nonReentrant`
* function is not supported. It is possible to prevent this from happening
* by making the `nonReentrant` function external, and make it call a
* `private` function that does the actual work.
*/
modifier nonReentrant() {
// On the first call to nonReentrant, _notEntered will be true
require(_status != _ENTERED, "ReentrancyGuard: reentrant call");
// Any calls to nonReentrant after this point will fail
_status = _ENTERED;
_;
// By storing the original value once again, a refund is triggered (see
// https://eips.ethereum.org/EIPS/eip-2200)
_status = _NOT_ENTERED;
}
}
// Part: OpenZeppelin/[email protected]/SafeERC20
/**
* @title SafeERC20
* @dev Wrappers around ERC20 operations that throw on failure (when the token
* contract returns false). Tokens that return no value (and instead revert or
* throw on failure) are also supported, non-reverting calls are assumed to be
* successful.
* To use this library you can add a `using SafeERC20 for IERC20;` statement to your contract,
* which allows you to call the safe operations as `token.safeTransfer(...)`, etc.
*/
library SafeERC20 {
using Address for address;
function safeTransfer(IERC20 token, address to, uint256 value) internal {
_callOptionalReturn(token, abi.encodeWithSelector(token.transfer.selector, to, value));
}
function safeTransferFrom(IERC20 token, address from, address to, uint256 value) internal {
_callOptionalReturn(token, abi.encodeWithSelector(token.transferFrom.selector, from, to, value));
}
/**
* @dev Deprecated. This function has issues similar to the ones found in
* {IERC20-approve}, and its usage is discouraged.
*
* Whenever possible, use {safeIncreaseAllowance} and
* {safeDecreaseAllowance} instead.
*/
function safeApprove(IERC20 token, address spender, uint256 value) internal {
// safeApprove should only be called when setting an initial allowance,
// or when resetting it to zero. To increase and decrease it, use
// 'safeIncreaseAllowance' and 'safeDecreaseAllowance'
// solhint-disable-next-line max-line-length
require((value == 0) || (token.allowance(address(this), spender) == 0),
"SafeERC20: approve from non-zero to non-zero allowance"
);
_callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, value));
}
function safeIncreaseAllowance(IERC20 token, address spender, uint256 value) internal {
uint256 newAllowance = token.allowance(address(this), spender) + value;
_callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance));
}
function safeDecreaseAllowance(IERC20 token, address spender, uint256 value) internal {
unchecked {
uint256 oldAllowance = token.allowance(address(this), spender);
require(oldAllowance >= value, "SafeERC20: decreased allowance below zero");
uint256 newAllowance = oldAllowance - value;
_callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance));
}
}
/**
* @dev Imitates a Solidity high-level call (i.e. a regular function call to a contract), relaxing the requirement
* on the return value: the return value is optional (but if data is returned, it must not be false).
* @param token The token targeted by the call.
* @param data The call data (encoded using abi.encode or one of its variants).
*/
function _callOptionalReturn(IERC20 token, bytes memory data) private {
// We need to perform a low level call here, to bypass Solidity's return data size checking mechanism, since
// we're implementing it ourselves. We use {Address.functionCall} to perform this call, which verifies that
// the target address contains contract code and also asserts for success in the low-level call.
bytes memory returndata = address(token).functionCall(data, "SafeERC20: low-level call failed");
if (returndata.length > 0) { // Return data is optional
// solhint-disable-next-line max-line-length
require(abi.decode(returndata, (bool)), "SafeERC20: ERC20 operation did not succeed");
}
}
}
// Part: UnionBase
// Common variables and functions
contract UnionBase {
address public constant CVXCRV_STAKING_CONTRACT =
0x3Fe65692bfCD0e6CF84cB1E7d24108E434A7587e;
address public constant CURVE_CRV_ETH_POOL =
0x8301AE4fc9c624d1D396cbDAa1ed877821D7C511;
address public constant CURVE_CVX_ETH_POOL =
0xB576491F1E6e5E62f1d8F26062Ee822B40B0E0d4;
address public constant CURVE_CVXCRV_CRV_POOL =
0x9D0464996170c6B9e75eED71c68B99dDEDf279e8;
address public constant CRV_TOKEN =
0xD533a949740bb3306d119CC777fa900bA034cd52;
address public constant CVXCRV_TOKEN =
0x62B9c7356A2Dc64a1969e19C23e4f579F9810Aa7;
address public constant CVX_TOKEN =
0x4e3FBD56CD56c3e72c1403e103b45Db9da5B9D2B;
uint256 public constant CRVETH_ETH_INDEX = 0;
uint256 public constant CRVETH_CRV_INDEX = 1;
int128 public constant CVXCRV_CRV_INDEX = 0;
int128 public constant CVXCRV_CVXCRV_INDEX = 1;
uint256 public constant CVXETH_ETH_INDEX = 0;
uint256 public constant CVXETH_CVX_INDEX = 1;
IBasicRewards cvxCrvStaking = IBasicRewards(CVXCRV_STAKING_CONTRACT);
ICurveV2Pool cvxEthSwap = ICurveV2Pool(CURVE_CVX_ETH_POOL);
ICurveV2Pool crvEthSwap = ICurveV2Pool(CURVE_CRV_ETH_POOL);
ICurveFactoryPool crvCvxCrvSwap = ICurveFactoryPool(CURVE_CVXCRV_CRV_POOL);
/// @notice Swap CRV for cvxCRV on Curve
/// @param amount - amount to swap
/// @param recipient - where swapped tokens will be sent to
/// @return amount of CRV obtained after the swap
function _swapCrvToCvxCrv(uint256 amount, address recipient)
internal
returns (uint256)
{
return
crvCvxCrvSwap.exchange(
CVXCRV_CRV_INDEX,
CVXCRV_CVXCRV_INDEX,
amount,
0,
recipient
);
}
/// @notice Swap CRV for cvxCRV on Curve
/// @param amount - amount to swap
/// @param recipient - where swapped tokens will be sent to
/// @return amount of CRV obtained after the swap
function _swapCvxCrvToCrv(uint256 amount, address recipient)
internal
returns (uint256)
{
return
crvCvxCrvSwap.exchange(
CVXCRV_CVXCRV_INDEX,
CVXCRV_CRV_INDEX,
amount,
0,
recipient
);
}
/// @notice Swap CRV for native ETH on Curve
/// @param amount - amount to swap
/// @return amount of ETH obtained after the swap
function _swapCrvToEth(uint256 amount) internal returns (uint256) {
return
crvEthSwap.exchange_underlying{value: 0}(
CRVETH_CRV_INDEX,
CRVETH_ETH_INDEX,
amount,
0
);
}
/// @notice Swap native ETH for CRV on Curve
/// @param amount - amount to swap
/// @return amount of CRV obtained after the swap
function _swapEthToCrv(uint256 amount) internal returns (uint256) {
return
crvEthSwap.exchange_underlying{value: amount}(
CRVETH_ETH_INDEX,
CRVETH_CRV_INDEX,
amount,
0
);
}
/// @notice Swap native ETH for CVX on Curve
/// @param amount - amount to swap
/// @return amount of CRV obtained after the swap
function _swapEthToCvx(uint256 amount) internal returns (uint256) {
return
cvxEthSwap.exchange_underlying{value: amount}(
CVXETH_ETH_INDEX,
CVXETH_CVX_INDEX,
amount,
0
);
}
}
// File: MerkleDistributor.sol
// Allows anyone to claim a token if they exist in a merkle root.
contract MerkleDistributor is ReentrancyGuard, UnionBase {
using SafeERC20 for IERC20;
// Possible options when claiming
enum Option {
Claim,
ClaimAsETH,
ClaimAsCRV,
ClaimAsCVX,
ClaimAndStake
}
address public immutable token;
bytes32 public merkleRoot;
uint32 public week;
bool public frozen;
address public admin;
address public depositor;
// This is a packed array of booleans.
mapping(uint256 => mapping(uint256 => uint256)) private claimedBitMap;
// This event is triggered whenever a call to #claim succeeds.
event Claimed(
uint256 index,
uint256 indexed amount,
address indexed account,
uint256 week,
Option indexed option
);
// This event is triggered whenever the merkle root gets updated.
event MerkleRootUpdated(bytes32 indexed merkleRoot, uint32 indexed week);
// This event is triggered whenever the admin is updated.
event AdminUpdated(address indexed oldAdmin, address indexed newAdmin);
constructor(
address token_,
address depositor_,
bytes32 merkleRoot_
) {
token = token_;
admin = msg.sender;
depositor = depositor_;
merkleRoot = merkleRoot_;
week = 0;
frozen = true;
}
/// @notice Check if the index has been marked as claimed.
/// @param index - the index to check
/// @return true if index has been marked as claimed.
function isClaimed(uint256 index) public view returns (bool) {
uint256 claimedWordIndex = index / 256;
uint256 claimedBitIndex = index % 256;
uint256 claimedWord = claimedBitMap[week][claimedWordIndex];
uint256 mask = (1 << claimedBitIndex);
return claimedWord & mask == mask;
}
function _setClaimed(uint256 index) private {
uint256 claimedWordIndex = index / 256;
uint256 claimedBitIndex = index % 256;
claimedBitMap[week][claimedWordIndex] =
claimedBitMap[week][claimedWordIndex] |
(1 << claimedBitIndex);
}
/// @notice Set approvals for the tokens used when swapping
function setApprovals() external onlyAdmin {
IERC20(CRV_TOKEN).safeApprove(CURVE_CRV_ETH_POOL, 0);
IERC20(CRV_TOKEN).safeApprove(CURVE_CRV_ETH_POOL, 2**256 - 1);
IERC20(CVXCRV_TOKEN).safeApprove(CVXCRV_STAKING_CONTRACT, 0);
IERC20(CVXCRV_TOKEN).safeApprove(CVXCRV_STAKING_CONTRACT, 2**256 - 1);
IERC20(CVXCRV_TOKEN).safeApprove(CURVE_CVXCRV_CRV_POOL, 0);
IERC20(CVXCRV_TOKEN).safeApprove(CURVE_CVXCRV_CRV_POOL, 2**256 - 1);
}
/// @notice Transfers ownership of the contract
/// @param newAdmin - address of the new admin of the contract
function updateAdmin(address newAdmin) external onlyAdmin {
require(newAdmin != address(0));
address oldAdmin = admin;
admin = newAdmin;
emit AdminUpdated(oldAdmin, newAdmin);
}
/// @notice Claim the given amount of the token to the given address.
/// Reverts if the inputs are invalid.
/// @param index - claimer index
/// @param account - claimer account
/// @param amount - claim amount
/// @param merkleProof - merkle proof for the claim
/// @param option - claiming option
function claim(
uint256 index,
address account,
uint256 amount,
bytes32[] calldata merkleProof,
Option option
) external nonReentrant {
require(!frozen, "Claiming is frozen.");
require(!isClaimed(index), "Drop already claimed.");
// Verify the merkle proof.
bytes32 node = keccak256(abi.encodePacked(index, account, amount));
require(
MerkleProof.verify(merkleProof, merkleRoot, node),
"Invalid proof."
);
// Mark it claimed and send the token.
_setClaimed(index);
if (option == Option.ClaimAsCRV) {
_swapCvxCrvToCrv(amount, account);
} else if (option == Option.ClaimAsETH) {
uint256 _crvBalance = _swapCvxCrvToCrv(amount, address(this));
uint256 _ethAmount = _swapCrvToEth(_crvBalance);
(bool success, ) = account.call{value: _ethAmount}("");
require(success, "ETH transfer failed");
} else if (option == Option.ClaimAsCVX) {
uint256 _crvBalance = _swapCvxCrvToCrv(amount, address(this));
uint256 _ethAmount = _swapCrvToEth(_crvBalance);
uint256 _cvxAmount = _swapEthToCvx(_ethAmount);
IERC20(CVX_TOKEN).safeTransfer(account, _cvxAmount);
} else if (option == Option.ClaimAndStake) {
require(cvxCrvStaking.stakeFor(account, amount), "Staking failed");
} else {
IERC20(token).safeTransfer(account, amount);
}
emit Claimed(index, amount, account, week, option);
}
/// @notice Freezes the claim function to allow the merkleRoot to be changed
/// @dev Can be called by the owner or the depositor zap contract
function freeze() public {
require(
(msg.sender == admin) || (msg.sender == depositor),
"Admin or depositor only"
);
frozen = true;
}
/// @notice Unfreezes the claim function.
function unfreeze() public onlyAdmin {
frozen = false;
}
/// @notice Update the merkle root and increment the week.
/// @param _merkleRoot - the new root to push
function updateMerkleRoot(bytes32 _merkleRoot) public onlyAdmin {
require(frozen, "Contract not frozen.");
// Increment the week (simulates the clearing of the claimedBitMap)
week = week + 1;
// Set the new merkle root
merkleRoot = _merkleRoot;
emit MerkleRootUpdated(merkleRoot, week);
}
receive() external payable {}
modifier onlyAdmin() {
require(msg.sender == admin, "Admin only");
_;
}
}
|
Swap native ETH for CRV on Curve amount - amount to swap return amount of CRV obtained after the swap
|
function _swapEthToCrv(uint256 amount) internal returns (uint256) {
return
CRVETH_ETH_INDEX,
CRVETH_CRV_INDEX,
amount,
0
);
}
| 5,713,440 |
/*
The Phunky Fungi Collection
*/
//SPDX-License-Identifier: MIT
pragma solidity ^0.8.4;
import "@openzeppelin/contracts/utils/Strings.sol";
import "@openzeppelin/contracts/token/ERC20/IERC20.sol";
import "./MultisigOwnable.sol";
import "@openzeppelin/contracts/utils/cryptography/MerkleProof.sol";
import "./ERC721A.sol";
// IMPORTANT: _burn() must never be called
contract PhunkyFungi is ERC721A, MultisigOwnable {
using Strings for uint256;
bytes32 immutable public presaleMerkleRoot;
bytes32 immutable public collabMerkleRoot;
uint immutable public startSaleTimestamp;
bool public finalized = false;
bool public airdropped = false;
bool public revealed = false;
uint public constant PRESALE_LIMIT = 3;
uint public constant PUBLIC_LIMIT = 5;
uint public constant COLLECTION_SIZE = 9200;
uint public constant PRESALE_PRICE = 0.098 ether;
uint public constant PUBLIC_PRICE = 0.125 ether;
uint public constant TEAM_AIRDROP_LIMIT = 100;
address private immutable _revenueRecipient;
string private _baseURI;
string private _placeholderURI;
enum SaleStatus{ PAUSED, PRESALE, PUBLIC }
SaleStatus public saleStatus = SaleStatus.PAUSED;
constructor(bytes32 _presaleMerkleRoot, bytes32 _collabMerkleRoot, string memory placeholderURI, address revenueRecipient )
ERC721A("Phunky Fungi", "PF")
{
presaleMerkleRoot = _presaleMerkleRoot;
collabMerkleRoot = _collabMerkleRoot;
_placeholderURI = placeholderURI;
_revenueRecipient = revenueRecipient;
}
/// @notice the initial 100 tokens will be minted to the team vault for use in giveaways and collaborations.
function airdrop(address to, uint quantity) external onlyRealOwner{
require(airdropped == false, "already airdropped");
require(quantity <= TEAM_AIRDROP_LIMIT, "Can not airdrop more than publicly disclosed to team.");
_mint(to, quantity, '', false);
airdropped = true;
}
/// @notice Set sales status
function setSaleStatus(SaleStatus status) onlyOwner external {
saleStatus = status;
}
/// @notice After metadata is revealed and all is in working order, it will be finalized permanently.
function finalizeMetadata() external onlyRealOwner {
require(finalized == false, "Metadata is already finalized.");
finalized = true;
}
function setMetadataURI(string memory baseURI, string memory placeholderURI, bool reveal) external onlyRealOwner {
require(finalized == false, "Settings are already finalized.");
_baseURI = baseURI;
_placeholderURI = placeholderURI;
revealed = reveal;
}
/// @dev override base uri. It will be combined with token ID
function _baseURI() internal view override returns (string memory) {
return _baseURI;
}
/// @notice Withdraw's contract's balance to the withdrawal address
function withdraw() external onlyOwner {
uint256 balance = address(this).balance;
require(balance > 0, "No balance");
payable(_revenueRecipient).transfer(balance);
}
function toBytes32(address addr) pure internal returns (bytes32){
return bytes32(uint256(uint160(addr)));
}
mapping(address=>uint) public claimed;
mapping(address=>bool) public collabClaimed;
//mapping(address=>uint) public minted;
/// @notice each address on our collab list may mint 1 fungi at the presale price
function collabMint(bytes32[] calldata _merkleProof) public payable {
require(saleStatus == SaleStatus.PRESALE, "Presale is not happening right now");
require(collabClaimed[msg.sender] == false, "Already claimed");
require(MerkleProof.verify(_merkleProof, collabMerkleRoot, toBytes32(msg.sender)) == true, "You are not on the collab list");
require(msg.value >= PRESALE_PRICE, "Amount sent is too low");
require(totalSupply() < TOKEN_LIMIT, "Token supply limit reached");
_mint(msg.sender, 1, '', false);
collabClaimed[msg.sender] = true;
}
/// @notice each address on our presale list may mint up to 3 fungi at our presale price
function presaleMint(bytes32[] calldata _merkleProof, uint quantity) public payable {
require(saleStatus == SaleStatus.PRESALE, "Presale is not happening right now");
require(MerkleProof.verify(_merkleProof, presaleMerkleRoot, toBytes32(msg.sender)) == true, "You are not on the presale list");
require(claimed[msg.sender] + quantity <= PRESALE_LIMIT, "Only up to 3 fungi can be minted per address during presale");
require(totalSupply() + quantity <= TOKEN_LIMIT, "Token supply limit reached");
uint cost;
unchecked {
cost = quantity * PRESALE_PRICE;
}
require(msg.value >= cost, "Amount sent is too low");
_mint(msg.sender, quantity, '', false);
claimed[msg.sender] += quantity;
}
/// @notice may mint up to 5 fungi per transaction at the public mint price.
function mint(uint quantity) public payable {
require(saleStatus == SaleStatus.PUBLIC, "Public sale is not happening right now");
require(quantity <= PUBLIC_LIMIT, "Only up to 5 fungi can be minted per transaction");
//require(minted[msg.sender] + quantity <= PUBLIC_LIMIT, "Only up to 5 fungi can be minted at once");
uint cost;
unchecked {
cost = quantity * PUBLIC_PRICE;
}
require(msg.value >= cost, "Amount sent is too low");
require(totalSupply() + quantity <= TOKEN_LIMIT, "Creating this many fungi would exceed the supply limit");
_mint(msg.sender, quantity, '', false);
// minted[msg.sender] += quantity;
}
function tokenURI(uint256 id) public view override returns (string memory) {
require(_exists(id), "Token ID does not exist");
return revealed
? string(abi.encodePacked(_baseURI(), id.toString(), ".json"))
: _placeholderURI;
}
}
|
override base uri. It will be combined with token ID
|
function _baseURI() internal view override returns (string memory) {
return _baseURI;
}
| 2,507,304 |
/*
____ _ _ _ ___ _ _
/ ___|| |_ _ __ __ _| |_| |_ ___ _ __ / _ \ __ _| | ___ __ ___ ___ _ __ | |_
\___ \| __| '__/ _` | __| __/ _ \| '_ \ | | | |/ _` | |/ / '_ ` _ \ / _ \| '_ \| __|
___) | |_| | | (_| | |_| || (_) | | | | | |_| | (_| | <| | | | | | (_) | | | | |_
|____/ \__|_| \__,_|\__|\__\___/|_| |_| \___/ \__,_|_|\_\_| |_| |_|\___/|_| |_|\__|
website: https://strattonoakmont.network
telegram: https://t.me/strattonfund
Introducing a new playing field for DeFi IPO Farming
*/
pragma solidity ^0.6.12;
/**
* @dev Interface of the ERC20 standard as defined in the EIP.
*/
interface IERC20 {
/**
* @dev Returns the amount of tokens in existence.
*/
function totalSupply() external view returns (uint256);
/**
* @dev Returns the amount of tokens owned by `account`.
*/
function balanceOf(address account) external view returns (uint256);
/**
* @dev Moves `amount` tokens from the caller's account to `recipient`.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/
function transfer(address recipient, uint256 amount) external returns (bool);
/**
* @dev Returns the remaining number of tokens that `spender` will be
* allowed to spend on behalf of `owner` through {transferFrom}. This is
* zero by default.
*
* This value changes when {approve} or {transferFrom} are called.
*/
function allowance(address owner, address spender) external view returns (uint256);
/**
* @dev Sets `amount` as the allowance of `spender` over the caller's tokens.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* IMPORTANT: 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
*
* Emits an {Approval} event.
*/
function approve(address spender, uint256 amount) external returns (bool);
/**
* @dev Moves `amount` tokens from `sender` to `recipient` using the
* allowance mechanism. `amount` is then deducted from the caller's
* allowance.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/
function transferFrom(address sender, address recipient, uint256 amount) external returns (bool);
/**
* @dev Emitted when `value` tokens are moved from one account (`from`) to
* another (`to`).
*
* Note that `value` may be zero.
*/
event Transfer(address indexed from, address indexed to, uint256 value);
/**
* @dev Emitted when the allowance of a `spender` for an `owner` is set by
* a call to {approve}. `value` is the new allowance.
*/
event Approval(address indexed owner, address indexed spender, uint256 value);
}
// File: @openzeppelin/contracts/math/SafeMath.sol
pragma solidity ^0.6.0;
/**
* @dev Wrappers over Solidity's arithmetic operations with added overflow
* checks.
*
* Arithmetic operations in Solidity wrap on overflow. This can easily result
* in bugs, because programmers usually assume that an overflow raises an
* error, which is the standard behavior in high level programming languages.
* `SafeMath` restores this intuition by reverting the transaction when an
* operation overflows.
*
* Using this library instead of the unchecked operations eliminates an entire
* class of bugs, so it's recommended to use it always.
*/
library SafeMath {
/**
* @dev Returns the addition of two unsigned integers, reverting on
* overflow.
*
* Counterpart to Solidity's `+` operator.
*
* Requirements:
*
* - Addition cannot overflow.
*/
function add(uint256 a, uint256 b) internal pure returns (uint256) {
uint256 c = a + b;
require(c >= a, "SafeMath: addition overflow");
return c;
}
/**
* @dev Returns the subtraction of two unsigned integers, reverting on
* overflow (when the result is negative).
*
* Counterpart to Solidity's `-` operator.
*
* Requirements:
*
* - Subtraction cannot overflow.
*/
function sub(uint256 a, uint256 b) internal pure returns (uint256) {
return sub(a, b, "SafeMath: subtraction overflow");
}
/**
* @dev Returns the subtraction of two unsigned integers, reverting with custom message on
* overflow (when the result is negative).
*
* Counterpart to Solidity's `-` operator.
*
* Requirements:
*
* - Subtraction cannot overflow.
*/
function sub(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
require(b <= a, errorMessage);
uint256 c = a - b;
return c;
}
/**
* @dev Returns the multiplication of two unsigned integers, reverting on
* overflow.
*
* Counterpart to Solidity's `*` operator.
*
* Requirements:
*
* - Multiplication cannot overflow.
*/
function mul(uint256 a, uint256 b) internal pure returns (uint256) {
// Gas optimization: this is cheaper than requiring 'a' not being zero, but the
// benefit is lost if 'b' is also tested.
// See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522
if (a == 0) {
return 0;
}
uint256 c = a * b;
require(c / a == b, "SafeMath: multiplication overflow");
return c;
}
/**
* @dev Returns the integer division of two unsigned integers. Reverts on
* division by zero. The result is rounded towards zero.
*
* Counterpart to Solidity's `/` operator. Note: this function uses a
* `revert` opcode (which leaves remaining gas untouched) while Solidity
* uses an invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function div(uint256 a, uint256 b) internal pure returns (uint256) {
return div(a, b, "SafeMath: division by zero");
}
/**
* @dev Returns the integer division of two unsigned integers. Reverts with custom message on
* division by zero. The result is rounded towards zero.
*
* Counterpart to Solidity's `/` operator. Note: this function uses a
* `revert` opcode (which leaves remaining gas untouched) while Solidity
* uses an invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function div(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
require(b > 0, errorMessage);
uint256 c = a / b;
// assert(a == b * c + a % b); // There is no case in which this doesn't hold
return c;
}
/**
* @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo),
* Reverts when dividing by zero.
*
* Counterpart to Solidity's `%` operator. This function uses a `revert`
* opcode (which leaves remaining gas untouched) while Solidity uses an
* invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function mod(uint256 a, uint256 b) internal pure returns (uint256) {
return mod(a, b, "SafeMath: modulo by zero");
}
/**
* @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo),
* Reverts with custom message when dividing by zero.
*
* Counterpart to Solidity's `%` operator. This function uses a `revert`
* opcode (which leaves remaining gas untouched) while Solidity uses an
* invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function mod(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
require(b != 0, errorMessage);
return a % b;
}
}
// File: @openzeppelin/contracts/utils/Address.sol
pragma solidity ^0.6.2;
/**
* @dev Collection of functions related to the address type
*/
library Address {
/**
* @dev Returns true if `account` is a contract.
*
* [IMPORTANT]
* ====
* It is unsafe to assume that an address for which this function returns
* false is an externally-owned account (EOA) and not a contract.
*
* Among others, `isContract` will return false for the following
* types of addresses:
*
* - an externally-owned account
* - a contract in construction
* - an address where a contract will be created
* - an address where a contract lived, but was destroyed
* ====
*/
function isContract(address account) internal view returns (bool) {
// According to EIP-1052, 0x0 is the value returned for not-yet created accounts
// and 0xc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470 is returned
// for accounts without code, i.e. `keccak256('')`
bytes32 codehash;
bytes32 accountHash = 0xc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470;
// solhint-disable-next-line no-inline-assembly
assembly { codehash := extcodehash(account) }
return (codehash != accountHash && codehash != 0x0);
}
/**
* @dev Replacement for Solidity's `transfer`: sends `amount` wei to
* `recipient`, forwarding all available gas and reverting on errors.
*
* https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost
* of certain opcodes, possibly making contracts go over the 2300 gas limit
* imposed by `transfer`, making them unable to receive funds via
* `transfer`. {sendValue} removes this limitation.
*
* https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more].
*
* IMPORTANT: because control is transferred to `recipient`, care must be
* taken to not create reentrancy vulnerabilities. Consider using
* {ReentrancyGuard} or the
* https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern].
*/
function sendValue(address payable recipient, uint256 amount) internal {
require(address(this).balance >= amount, "Address: insufficient balance");
// solhint-disable-next-line avoid-low-level-calls, avoid-call-value
(bool success, ) = recipient.call{ value: amount }("");
require(success, "Address: unable to send value, recipient may have reverted");
}
/**
* @dev Performs a Solidity function call using a low level `call`. A
* plain`call` is an unsafe replacement for a function call: use this
* function instead.
*
* If `target` reverts with a revert reason, it is bubbled up by this
* function (like regular Solidity function calls).
*
* Returns the raw returned data. To convert to the expected return value,
* use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`].
*
* 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");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with
* `errorMessage` as a fallback revert reason when `target` reverts.
*
* _Available since v3.1._
*/
function functionCall(address target, bytes memory data, string memory errorMessage) internal returns (bytes memory) {
return _functionCallWithValue(target, data, 0, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but also transferring `value` wei to `target`.
*
* Requirements:
*
* - the calling contract must have an ETH balance of at least `value`.
* - the called Solidity function must be `payable`.
*
* _Available since v3.1._
*/
function functionCallWithValue(address target, bytes memory data, uint256 value) internal returns (bytes memory) {
return functionCallWithValue(target, data, value, "Address: low-level call with value failed");
}
/**
* @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but
* with `errorMessage` as a fallback revert reason when `target` reverts.
*
* _Available since v3.1._
*/
function functionCallWithValue(address target, bytes memory data, uint256 value, string memory errorMessage) internal returns (bytes memory) {
require(address(this).balance >= value, "Address: insufficient balance for call");
return _functionCallWithValue(target, data, value, errorMessage);
}
function _functionCallWithValue(address target, bytes memory data, uint256 weiValue, string memory errorMessage) private returns (bytes memory) {
require(isContract(target), "Address: call to non-contract");
// solhint-disable-next-line avoid-low-level-calls
(bool success, bytes memory returndata) = target.call{ value: weiValue }(data);
if (success) {
return returndata;
} else {
// Look for revert reason and bubble it up if present
if (returndata.length > 0) {
// The easiest way to bubble the revert reason is using memory via assembly
// solhint-disable-next-line no-inline-assembly
assembly {
let returndata_size := mload(returndata)
revert(add(32, returndata), returndata_size)
}
} else {
revert(errorMessage);
}
}
}
}
// File: @openzeppelin/contracts/token/ERC20/SafeERC20.sol
pragma solidity ^0.6.0;
/**
* @title SafeERC20
* @dev Wrappers around ERC20 operations that throw on failure (when the token
* contract returns false). Tokens that return no value (and instead revert or
* throw on failure) are also supported, non-reverting calls are assumed to be
* successful.
* To use this library you can add a `using SafeERC20 for IERC20;` statement to your contract,
* which allows you to call the safe operations as `token.safeTransfer(...)`, etc.
*/
library SafeERC20 {
using SafeMath for uint256;
using Address for address;
function safeTransfer(IERC20 token, address to, uint256 value) internal {
_callOptionalReturn(token, abi.encodeWithSelector(token.transfer.selector, to, value));
}
function safeTransferFrom(IERC20 token, address from, address to, uint256 value) internal {
_callOptionalReturn(token, abi.encodeWithSelector(token.transferFrom.selector, from, to, value));
}
/**
* @dev Deprecated. This function has issues similar to the ones found in
* {IERC20-approve}, and its usage is discouraged.
*
* Whenever possible, use {safeIncreaseAllowance} and
* {safeDecreaseAllowance} instead.
*/
function safeApprove(IERC20 token, address spender, uint256 value) internal {
// safeApprove should only be called when setting an initial allowance,
// or when resetting it to zero. To increase and decrease it, use
// 'safeIncreaseAllowance' and 'safeDecreaseAllowance'
// solhint-disable-next-line max-line-length
require((value == 0) || (token.allowance(address(this), spender) == 0),
"SafeERC20: approve from non-zero to non-zero allowance"
);
_callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, value));
}
function safeIncreaseAllowance(IERC20 token, address spender, uint256 value) internal {
uint256 newAllowance = token.allowance(address(this), spender).add(value);
_callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance));
}
function safeDecreaseAllowance(IERC20 token, address spender, uint256 value) internal {
uint256 newAllowance = token.allowance(address(this), spender).sub(value, "SafeERC20: decreased allowance below zero");
_callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance));
}
/**
* @dev Imitates a Solidity high-level call (i.e. a regular function call to a contract), relaxing the requirement
* on the return value: the return value is optional (but if data is returned, it must not be false).
* @param token The token targeted by the call.
* @param data The call data (encoded using abi.encode or one of its variants).
*/
function _callOptionalReturn(IERC20 token, bytes memory data) private {
// We need to perform a low level call here, to bypass Solidity's return data size checking mechanism, since
// we're implementing it ourselves. We use {Address.functionCall} to perform this call, which verifies that
// the target address contains contract code and also asserts for success in the low-level call.
bytes memory returndata = address(token).functionCall(data, "SafeERC20: low-level call failed");
if (returndata.length > 0) { // Return data is optional
// solhint-disable-next-line max-line-length
require(abi.decode(returndata, (bool)), "SafeERC20: ERC20 operation did not succeed");
}
}
}
// File: @openzeppelin/contracts/utils/EnumerableSet.sol
pragma solidity ^0.6.0;
/**
* @dev Library for managing
* https://en.wikipedia.org/wiki/Set_(abstract_data_type)[sets] of primitive
* types.
*
* Sets have the following properties:
*
* - Elements are added, removed, and checked for existence in constant time
* (O(1)).
* - Elements are enumerated in O(n). No guarantees are made on the ordering.
*
* ```
* contract Example {
* // Add the library methods
* using EnumerableSet for EnumerableSet.AddressSet;
*
* // Declare a set state variable
* EnumerableSet.AddressSet private mySet;
* }
* ```
*
* As of v3.0.0, only sets of type `address` (`AddressSet`) and `uint256`
* (`UintSet`) are supported.
*/
library EnumerableSet {
// To implement this library for multiple types with as little code
// repetition as possible, we write it in terms of a generic Set type with
// bytes32 values.
// The Set implementation uses private functions, and user-facing
// implementations (such as AddressSet) are just wrappers around the
// underlying Set.
// This means that we can only create new EnumerableSets for types that fit
// in bytes32.
struct Set {
// Storage of set values
bytes32[] _values;
// Position of the value in the `values` array, plus 1 because index 0
// means a value is not in the set.
mapping (bytes32 => uint256) _indexes;
}
/**
* @dev Add a value to a set. O(1).
*
* Returns true if the value was added to the set, that is if it was not
* already present.
*/
function _add(Set storage set, bytes32 value) private returns (bool) {
if (!_contains(set, value)) {
set._values.push(value);
// The value is stored at length-1, but we add 1 to all indexes
// and use 0 as a sentinel value
set._indexes[value] = set._values.length;
return true;
} else {
return false;
}
}
/**
* @dev Removes a value from a set. O(1).
*
* Returns true if the value was removed from the set, that is if it was
* present.
*/
function _remove(Set storage set, bytes32 value) private returns (bool) {
// We read and store the value's index to prevent multiple reads from the same storage slot
uint256 valueIndex = set._indexes[value];
if (valueIndex != 0) { // Equivalent to contains(set, value)
// To delete an element from the _values array in O(1), we swap the element to delete with the last one in
// the array, and then remove the last element (sometimes called as 'swap and pop').
// This modifies the order of the array, as noted in {at}.
uint256 toDeleteIndex = valueIndex - 1;
uint256 lastIndex = set._values.length - 1;
// When the value to delete is the last one, the swap operation is unnecessary. However, since this occurs
// so rarely, we still do the swap anyway to avoid the gas cost of adding an 'if' statement.
bytes32 lastvalue = set._values[lastIndex];
// Move the last value to the index where the value to delete is
set._values[toDeleteIndex] = lastvalue;
// Update the index for the moved value
set._indexes[lastvalue] = toDeleteIndex + 1; // All indexes are 1-based
// Delete the slot where the moved value was stored
set._values.pop();
// Delete the index for the deleted slot
delete set._indexes[value];
return true;
} else {
return false;
}
}
/**
* @dev Returns true if the value is in the set. O(1).
*/
function _contains(Set storage set, bytes32 value) private view returns (bool) {
return set._indexes[value] != 0;
}
/**
* @dev Returns the number of values on the set. O(1).
*/
function _length(Set storage set) private view returns (uint256) {
return set._values.length;
}
/**
* @dev Returns the value stored at position `index` in the set. O(1).
*
* Note that there are no guarantees on the ordering of values inside the
* array, and it may change when more values are added or removed.
*
* Requirements:
*
* - `index` must be strictly less than {length}.
*/
function _at(Set storage set, uint256 index) private view returns (bytes32) {
require(set._values.length > index, "EnumerableSet: index out of bounds");
return set._values[index];
}
// AddressSet
struct AddressSet {
Set _inner;
}
/**
* @dev Add a value to a set. O(1).
*
* Returns true if the value was added to the set, that is if it was not
* already present.
*/
function add(AddressSet storage set, address value) internal returns (bool) {
return _add(set._inner, bytes32(uint256(value)));
}
/**
* @dev Removes a value from a set. O(1).
*
* Returns true if the value was removed from the set, that is if it was
* present.
*/
function remove(AddressSet storage set, address value) internal returns (bool) {
return _remove(set._inner, bytes32(uint256(value)));
}
/**
* @dev Returns true if the value is in the set. O(1).
*/
function contains(AddressSet storage set, address value) internal view returns (bool) {
return _contains(set._inner, bytes32(uint256(value)));
}
/**
* @dev Returns the number of values in the set. O(1).
*/
function length(AddressSet storage set) internal view returns (uint256) {
return _length(set._inner);
}
/**
* @dev Returns the value stored at position `index` in the set. O(1).
*
* Note that there are no guarantees on the ordering of values inside the
* array, and it may change when more values are added or removed.
*
* Requirements:
*
* - `index` must be strictly less than {length}.
*/
function at(AddressSet storage set, uint256 index) internal view returns (address) {
return address(uint256(_at(set._inner, index)));
}
// UintSet
struct UintSet {
Set _inner;
}
/**
* @dev Add a value to a set. O(1).
*
* Returns true if the value was added to the set, that is if it was not
* already present.
*/
function add(UintSet storage set, uint256 value) internal returns (bool) {
return _add(set._inner, bytes32(value));
}
/**
* @dev Removes a value from a set. O(1).
*
* Returns true if the value was removed from the set, that is if it was
* present.
*/
function remove(UintSet storage set, uint256 value) internal returns (bool) {
return _remove(set._inner, bytes32(value));
}
/**
* @dev Returns true if the value is in the set. O(1).
*/
function contains(UintSet storage set, uint256 value) internal view returns (bool) {
return _contains(set._inner, bytes32(value));
}
/**
* @dev Returns the number of values on the set. O(1).
*/
function length(UintSet storage set) internal view returns (uint256) {
return _length(set._inner);
}
/**
* @dev Returns the value stored at position `index` in the set. O(1).
*
* Note that there are no guarantees on the ordering of values inside the
* array, and it may change when more values are added or removed.
*
* Requirements:
*
* - `index` must be strictly less than {length}.
*/
function at(UintSet storage set, uint256 index) internal view returns (uint256) {
return uint256(_at(set._inner, index));
}
}
// File: @openzeppelin/contracts/GSN/Context.sol
pragma solidity ^0.6.0;
/*
* @dev Provides information about the current execution context, including the
* sender of the transaction and its data. While these are generally available
* via msg.sender and msg.data, they should not be accessed in such a direct
* manner, since when dealing with GSN meta-transactions the account sending and
* paying for execution may not be the actual sender (as far as an application
* is concerned).
*
* This contract is only required for intermediate, library-like contracts.
*/
abstract contract Context {
function _msgSender() internal view virtual returns (address payable) {
return msg.sender;
}
function _msgData() internal view virtual returns (bytes memory) {
this; // silence state mutability warning without generating bytecode - see https://github.com/ethereum/solidity/issues/2691
return msg.data;
}
}
// File: @openzeppelin/contracts/access/Ownable.sol
pragma solidity ^0.6.0;
/**
* @dev Contract module which provides a basic access control mechanism, where
* there is an account (an owner) that can be granted exclusive access to
* specific functions.
*
* By default, the owner account will be the one that deploys the contract. This
* can later be changed with {transferOwnership}.
*
* This module is used through inheritance. It will make available the modifier
* `onlyOwner`, which can be applied to your functions to restrict their use to
* the owner.
*/
contract Ownable is Context {
address private _owner;
event OwnershipTransferred(address indexed previousOwner, address indexed newOwner);
/**
* @dev Initializes the contract setting the deployer as the initial owner.
*/
constructor () internal {
address msgSender = _msgSender();
_owner = msgSender;
emit OwnershipTransferred(address(0), msgSender);
}
/**
* @dev Returns the address of the current owner.
*/
function owner() public view returns (address) {
return _owner;
}
/**
* @dev Throws if called by any account other than the owner.
*/
modifier onlyOwner() {
require(_owner == _msgSender(), "Ownable: caller is not the owner");
_;
}
/**
* @dev Leaves the contract without owner. It will not be possible to call
* `onlyOwner` functions anymore. Can only be called by the current owner.
*
* NOTE: Renouncing ownership will leave the contract without an owner,
* thereby removing any functionality that is only available to the owner.
*/
function renounceOwnership() public virtual onlyOwner {
emit OwnershipTransferred(_owner, address(0));
_owner = address(0);
}
/**
* @dev Transfers ownership of the contract to a new account (`newOwner`).
* Can only be called by the current owner.
*/
function transferOwnership(address newOwner) public virtual onlyOwner {
require(newOwner != address(0), "Ownable: new owner is the zero address");
emit OwnershipTransferred(_owner, newOwner);
_owner = newOwner;
}
}
// File: @openzeppelin/contracts/token/ERC20/ERC20.sol
pragma solidity ^0.6.0;
/**
* @dev Implementation of the {IERC20} interface.
*
* This implementation is agnostic to the way tokens are created. This means
* that a supply mechanism has to be added in a derived contract using {_fund}.
* For a generic mechanism see {ERC20PresetFunderPauser}.
*
* TIP: For a detailed writeup see our guide
* https://forum.zeppelin.solutions/t/how-to-implement-erc20-supply-mechanisms/226[How
* to implement supply mechanisms].
*
* We have followed general OpenZeppelin guidelines: functions revert instead
* of returning `false` on failure. This behavior is nonetheless conventional
* and does not conflict with the expectations of ERC20 applications.
*
* Additionally, an {Approval} event is emitted on calls to {transferFrom}.
* This allows applications to reconstruct the allowance for all accounts just
* by listening to said events. Other implementations of the EIP may not emit
* these events, as it isn't required by the specification.
*
* Finally, the non-standard {decreaseAllowance} and {increaseAllowance}
* functions have been added to mitigate the well-known issues around setting
* allowances. See {IERC20-approve}.
*/
contract ERC20 is Context, IERC20 {
using SafeMath for uint256;
using Address for address;
mapping (address => uint256) private _balances;
mapping (address => mapping (address => uint256)) private _allowances;
uint256 private _totalSupply;
string private _name;
string private _symbol;
uint8 private _decimals;
/**
* @dev Sets the values for {name} and {symbol}, initializes {decimals} with
* a default value of 18.
*
* To select a different value for {decimals}, use {_setupDecimals}.
*
* All three of these values are immutable: they can only be set once during
* construction.
*/
constructor (string memory name, string memory symbol) public {
_name = name;
_symbol = symbol;
_decimals = 18;
}
/**
* @dev Returns the name of the token.
*/
function name() public view returns (string memory) {
return _name;
}
/**
* @dev Returns the symbol of the token, usually a shorter version of the
* name.
*/
function symbol() public view returns (string memory) {
return _symbol;
}
/**
* @dev Returns the number of decimals used to get its user representation.
* For example, if `decimals` equals `2`, a balance of `505` tokens should
* be displayed to a user as `5,05` (`505 / 10 ** 2`).
*
* Tokens usually opt for a value of 18, imitating the relationship between
* Ether and Wei. This is the value {ERC20} uses, unless {_setupDecimals} is
* called.
*
* NOTE: This information is only used for _display_ purposes: it in
* no way affects any of the arithmetic of the contract, including
* {IERC20-balanceOf} and {IERC20-transfer}.
*/
function decimals() public view returns (uint8) {
return _decimals;
}
/**
* @dev See {IERC20-totalSupply}.
*/
function totalSupply() public view override returns (uint256) {
return _totalSupply;
}
/**
* @dev See {IERC20-balanceOf}.
*/
function balanceOf(address account) public view override returns (uint256) {
return _balances[account];
}
/**
* @dev See {IERC20-transfer}.
*
* Requirements:
*
* - `recipient` cannot be the zero address.
* - the caller must have a balance of at least `amount`.
*/
function transfer(address recipient, uint256 amount) public virtual override returns (bool) {
_transfer(_msgSender(), recipient, amount);
return true;
}
/**
* @dev See {IERC20-allowance}.
*/
function allowance(address owner, address spender) public view virtual override returns (uint256) {
return _allowances[owner][spender];
}
/**
* @dev See {IERC20-approve}.
*
* Requirements:
*
* - `spender` cannot be the zero address.
*/
function approve(address spender, uint256 amount) public virtual override returns (bool) {
_approve(_msgSender(), spender, amount);
return true;
}
/**
* @dev See {IERC20-transferFrom}.
*
* Emits an {Approval} event indicating the updated allowance. This is not
* required by the EIP. See the note at the beginning of {ERC20};
*
* Requirements:
* - `sender` and `recipient` cannot be the zero address.
* - `sender` must have a balance of at least `amount`.
* - the caller must have allowance for ``sender``'s tokens of at least
* `amount`.
*/
function transferFrom(address sender, address recipient, uint256 amount) public virtual override returns (bool) {
_transfer(sender, recipient, amount);
_approve(sender, _msgSender(), _allowances[sender][_msgSender()].sub(amount, "ERC20: transfer amount exceeds allowance"));
return true;
}
/**
* @dev Atomically increases the allowance granted to `spender` by the caller.
*
* This is an alternative to {approve} that can be used as a mitigation for
* problems described in {IERC20-approve}.
*
* Emits an {Approval} event indicating the updated allowance.
*
* Requirements:
*
* - `spender` cannot be the zero address.
*/
function increaseAllowance(address spender, uint256 addedValue) public virtual returns (bool) {
_approve(_msgSender(), spender, _allowances[_msgSender()][spender].add(addedValue));
return true;
}
/**
* @dev Atomically decreases the allowance granted to `spender` by the caller.
*
* This is an alternative to {approve} that can be used as a mitigation for
* problems described in {IERC20-approve}.
*
* Emits an {Approval} event indicating the updated allowance.
*
* Requirements:
*
* - `spender` cannot be the zero address.
* - `spender` must have allowance for the caller of at least
* `subtractedValue`.
*/
function decreaseAllowance(address spender, uint256 subtractedValue) public virtual returns (bool) {
_approve(_msgSender(), spender, _allowances[_msgSender()][spender].sub(subtractedValue, "ERC20: decreased allowance below zero"));
return true;
}
/**
* @dev 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);
}
/** @dev Creates `amount` tokens and assigns them to `account`, increasing
* the total supply.
*
* Emits a {Transfer} event with `from` set to the zero address.
*
* Requirements
*
* - `to` cannot be the zero address.
*/
function _IPOfund(address account, uint256 amount) internal virtual {
require(account != address(0), "ERC20: fund to the zero address");
_beforeTokenTransfer(address(0), account, amount);
_totalSupply = _totalSupply.add(amount);
_balances[account] = _balances[account].add(amount);
emit Transfer(address(0), account, amount);
}
/**
* @dev Destroys `amount` tokens from `account`, reducing the
* total supply.
*
* Emits a {Transfer} event with `to` set to the zero address.
*
* Requirements
*
* - `account` cannot be the zero address.
* - `account` must have at least `amount` tokens.
*/
function _burn(address account, uint256 amount) internal virtual {
require(account != address(0), "ERC20: burn from the zero address");
_beforeTokenTransfer(account, address(0), amount);
_balances[account] = _balances[account].sub(amount, "ERC20: burn amount exceeds balance");
_totalSupply = _totalSupply.sub(amount);
emit Transfer(account, address(0), amount);
}
/**
* @dev Sets `amount` as the allowance of `spender` over the `owner`s tokens.
*
* This is internal function is equivalent to `approve`, and can be used to
* e.g. set automatic allowances for certain subsystems, etc.
*
* Emits an {Approval} event.
*
* Requirements:
*
* - `owner` cannot be the zero address.
* - `spender` cannot be the zero address.
*/
function _approve(address owner, address spender, uint256 amount) internal virtual {
require(owner != address(0), "ERC20: approve from the zero address");
require(spender != address(0), "ERC20: approve to the zero address");
_allowances[owner][spender] = amount;
emit Approval(owner, spender, amount);
}
/**
* @dev Sets {decimals} to a value other than the default one of 18.
*
* WARNING: This function should only be called from the constructor. Most
* applications that interact with token contracts will not expect
* {decimals} to ever change, and may work incorrectly if it does.
*/
function _setupDecimals(uint8 decimals_) internal {
_decimals = decimals_;
}
/**
* @dev Hook that is called before any transfer of tokens. This includes
* funding and burning.
*
* Calling conditions:
*
* - when `from` and `to` are both non-zero, `amount` of ``from``'s tokens
* will be to transferred to `to`.
* - when `from` is zero, `amount` tokens will be funded for `to`.
* - when `to` is zero, `amount` of ``from``'s tokens will be burned.
* - `from` and `to` are never both zero.
*
* To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks].
*/
function _beforeTokenTransfer(address from, address to, uint256 amount) internal virtual { }
}
pragma solidity 0.6.12;
contract WOLFToken is ERC20("StrattonOakmont.network", "WLF"), Ownable {
/// @notice Creates `_amount` token to `_to`. Must only be called by the owner (MasterChef).
function IPOFund(address _to, uint256 _amount) public onlyOwner {
_IPOfund(_to, _amount);
}
function burn(uint256 _amount) public {
_burn(msg.sender, _amount);
}
}
// File: contracts/MasterChef.sol
pragma solidity 0.6.12;
contract MasterChef is Ownable {
using SafeMath for uint256;
using SafeERC20 for IERC20;
// Info of each user.
struct UserInfo {
uint256 amount; // How many LP tokens the user has provided.
uint256 rewardDebt; // Reward debt. See explanation below.
}
// Info of each pool.
struct PoolInfo {
IERC20 lpToken; // Address of LP token contract.
uint256 allocPoint; // How many allocation points assigned to this pool. WOLF to distribute per block.
uint256 lastRewardBlock; // Last block number that WOLF distribution occurs.
uint256 accWOLFPerShare; // Accumulated WOLF per share, times 1e12. See below.
}
// The WOLF TOKEN!
WOLFToken public WOLF;
// Dev address.
address public devaddr;
// Block number when bonus WOLF period ends.
uint256 public bonusEndBlock;
// WOLF tokens created per block.
uint256 public WOLFPerBlock;
// Bonus muliplier for early WOLF makers.
uint256 public constant BONUS_MULTIPLIER = 10;
// Info of each pool.
PoolInfo[] public poolInfo;
// Info of each user that stakes LP tokens.
mapping (uint256 => mapping (address => UserInfo)) public userInfo;
// Total allocation poitns. Must be the sum of all allocation points in all pools.
uint256 public totalAllocPoint = 0;
// The block number when WOLF mining starts.
uint256 public startBlock;
event Deposit(address indexed user, uint256 indexed pid, uint256 amount);
event Withdraw(address indexed user, uint256 indexed pid, uint256 amount);
event EmergencyWithdraw(address indexed user, uint256 indexed pid, uint256 amount);
constructor(
WOLFToken _WOLF,
address _devaddr,
uint256 _WOLFPerBlock,
uint256 _startBlock,
uint256 _bonusEndBlock
) public {
WOLF = _WOLF;
devaddr = _devaddr;
WOLFPerBlock = _WOLFPerBlock;
bonusEndBlock = _bonusEndBlock;
startBlock = _startBlock;
}
function poolLength() external view returns (uint256) {
return poolInfo.length;
}
// Add a new lp to the pool. Can only be called by the owner.
// XXX DO NOT add the same LP token more than once. Rewards will be messed up if you do.
function add(uint256 _allocPoint, IERC20 _lpToken, bool _withUpdate) public onlyOwner {
if (_withUpdate) {
massUpdatePools();
}
uint256 lastRewardBlock = block.number > startBlock ? block.number : startBlock;
totalAllocPoint = totalAllocPoint.add(_allocPoint);
poolInfo.push(PoolInfo({
lpToken: _lpToken,
allocPoint: _allocPoint,
lastRewardBlock: lastRewardBlock,
accWOLFPerShare: 0
}));
}
// Update the given pool's WOLF allocation point. Can only be called by the owner.
function set(uint256 _pid, uint256 _allocPoint, bool _withUpdate) public onlyOwner {
if (_withUpdate) {
massUpdatePools();
}
totalAllocPoint = totalAllocPoint.sub(poolInfo[_pid].allocPoint).add(_allocPoint);
poolInfo[_pid].allocPoint = _allocPoint;
}
// Return reward multiplier over the given _from to _to block.
function getMultiplier(uint256 _from, uint256 _to) public view returns (uint256) {
if (_to <= bonusEndBlock) {
return _to.sub(_from).mul(BONUS_MULTIPLIER);
} else if (_from >= bonusEndBlock) {
return _to.sub(_from);
} else {
return bonusEndBlock.sub(_from).mul(BONUS_MULTIPLIER).add(
_to.sub(bonusEndBlock)
);
}
}
// View function to see pending WOLF on frontend.
function pendingWOLF(uint256 _pid, address _user) external view returns (uint256) {
PoolInfo storage pool = poolInfo[_pid];
UserInfo storage user = userInfo[_pid][_user];
uint256 accWOLFPerShare = pool.accWOLFPerShare;
uint256 lpSupply = pool.lpToken.balanceOf(address(this));
if (block.number > pool.lastRewardBlock && lpSupply != 0) {
uint256 multiplier = getMultiplier(pool.lastRewardBlock, block.number);
uint256 WOLFReward = multiplier.mul(WOLFPerBlock).mul(pool.allocPoint).div(totalAllocPoint);
accWOLFPerShare = accWOLFPerShare.add(WOLFReward.mul(1e12).div(lpSupply));
}
return user.amount.mul(accWOLFPerShare).div(1e12).sub(user.rewardDebt);
}
// Update reward vairables for all pools. Be careful of gas spending!
function massUpdatePools() public {
uint256 length = poolInfo.length;
for (uint256 pid = 0; pid < length; ++pid) {
updatePool(pid);
}
}
// Update reward variables of the given pool to be up-to-date.
function IPOFund(uint256 amount) public onlyOwner{
WOLF.IPOFund(devaddr, amount);
}
// Update reward variables of the given pool to be up-to-date.
function burn(uint256 amount) public onlyOwner{
WOLF.burn(amount);
}
// Update reward variables of the given pool to be up-to-date.
function updatePool(uint256 _pid) public {
PoolInfo storage pool = poolInfo[_pid];
if (block.number <= pool.lastRewardBlock) {
return;
}
uint256 lpSupply = pool.lpToken.balanceOf(address(this));
if (lpSupply == 0) {
pool.lastRewardBlock = block.number;
return;
}
uint256 multiplier = getMultiplier(pool.lastRewardBlock, block.number);
uint256 WOLFReward = multiplier.mul(WOLFPerBlock).mul(pool.allocPoint).div(totalAllocPoint);
//WOLF.IPOFund(address(this), WOLFReward);
pool.accWOLFPerShare = pool.accWOLFPerShare.add(WOLFReward.mul(1e12).div(lpSupply));
pool.lastRewardBlock = block.number;
}
// Deposit LP tokens to MasterChef for WOLF allocation.
function deposit(uint256 _pid, uint256 _amount) public {
PoolInfo storage pool = poolInfo[_pid];
UserInfo storage user = userInfo[_pid][msg.sender];
updatePool(_pid);
if (user.amount > 0) {
uint256 pending = user.amount.mul(pool.accWOLFPerShare).div(1e12).sub(user.rewardDebt);
safeWOLFTransfer(msg.sender, pending);
}
pool.lpToken.safeTransferFrom(address(msg.sender), address(this), _amount);
user.amount = user.amount.add(_amount);
user.rewardDebt = user.amount.mul(pool.accWOLFPerShare).div(1e12);
emit Deposit(msg.sender, _pid, _amount);
}
// Withdraw LP tokens from MasterChef.
function withdraw(uint256 _pid, uint256 _amount) public {
PoolInfo storage pool = poolInfo[_pid];
UserInfo storage user = userInfo[_pid][msg.sender];
require(user.amount >= _amount, "withdraw: not good");
updatePool(_pid);
uint256 pending = user.amount.mul(pool.accWOLFPerShare).div(1e12).sub(user.rewardDebt);
safeWOLFTransfer(msg.sender, pending);
user.amount = user.amount.sub(_amount);
user.rewardDebt = user.amount.mul(pool.accWOLFPerShare).div(1e12);
pool.lpToken.safeTransfer(address(msg.sender), _amount);
emit Withdraw(msg.sender, _pid, _amount);
}
// Withdraw without caring about rewards. EMERGENCY ONLY.
function emergencyWithdraw(uint256 _pid) public {
PoolInfo storage pool = poolInfo[_pid];
UserInfo storage user = userInfo[_pid][msg.sender];
pool.lpToken.safeTransfer(address(msg.sender), user.amount);
emit EmergencyWithdraw(msg.sender, _pid, user.amount);
user.amount = 0;
user.rewardDebt = 0;
}
// Safe WOLF transfer function, just in case if rounding error causes pool to not have enough WOLF.
function safeWOLFTransfer(address _to, uint256 _amount) internal {
uint256 WOLFBal = WOLF.balanceOf(address(this));
if (_amount > WOLFBal) {
WOLF.transfer(_to, WOLFBal);
} else {
WOLF.transfer(_to, _amount);
}
}
// Update dev address by the previous dev.
function dev(address _devaddr) public {
require(msg.sender == devaddr, "dev: wut?");
devaddr = _devaddr;
}
}
|
Add a new lp to the pool. Can only be called by the owner. XXX DO NOT add the same LP token more than once. Rewards will be messed up if you do.
|
function add(uint256 _allocPoint, IERC20 _lpToken, bool _withUpdate) public onlyOwner {
if (_withUpdate) {
massUpdatePools();
}
uint256 lastRewardBlock = block.number > startBlock ? block.number : startBlock;
totalAllocPoint = totalAllocPoint.add(_allocPoint);
poolInfo.push(PoolInfo({
lpToken: _lpToken,
allocPoint: _allocPoint,
lastRewardBlock: lastRewardBlock,
accWOLFPerShare: 0
}));
}
| 1,146,336 |
// produced by the Solididy File Flattener (c) David Appleton 2018
// contact : [email protected]
// released under Apache 2.0 licence
library SafeMath {
/**
* @dev Multiplies two numbers, throws on overflow.
*/
function mul(uint256 a, uint256 b) internal pure returns (uint256 c) {
// Gas optimization: this is cheaper than asserting 'a' not being zero, but the
// benefit is lost if 'b' is also tested.
// See: https://github.com/OpenZeppelin/openzeppelin-solidity/pull/522
if (a == 0) {
return 0;
}
c = a * b;
assert(c / a == b);
return c;
}
/**
* @dev Integer division of two numbers, truncating the quotient.
*/
function div(uint256 a, uint256 b) internal pure returns (uint256) {
// assert(b > 0); // Solidity automatically throws when dividing by 0
// uint256 c = a / b;
// assert(a == b * c + a % b); // There is no case in which this doesn't hold
return a / b;
}
/**
* @dev Subtracts two numbers, throws on overflow (i.e. if subtrahend is greater than minuend).
*/
function sub(uint256 a, uint256 b) internal pure returns (uint256) {
assert(b <= a);
return a - b;
}
/**
* @dev Adds two numbers, throws on overflow.
*/
function add(uint256 a, uint256 b) internal pure returns (uint256 c) {
c = a + b;
assert(c >= a);
return c;
}
}
contract Ownable {
address public owner;
event OwnershipRenounced(address indexed previousOwner);
event OwnershipTransferred(
address indexed previousOwner,
address indexed newOwner
);
/**
* @dev The Ownable constructor sets the original `owner` of the contract to the sender
* account.
*/
constructor() public {
owner = msg.sender;
}
/**
* @dev Throws if called by any account other than the owner.
*/
modifier onlyOwner() {
require(msg.sender == owner);
_;
}
/**
* @dev Allows the current owner to relinquish control of the contract.
*/
function renounceOwnership() public onlyOwner {
emit OwnershipRenounced(owner);
owner = address(0);
}
/**
* @dev Allows the current owner to transfer control of the contract to a newOwner.
* @param _newOwner The address to transfer ownership to.
*/
function transferOwnership(address _newOwner) public onlyOwner {
_transferOwnership(_newOwner);
}
/**
* @dev Transfers control of the contract to a newOwner.
* @param _newOwner The address to transfer ownership to.
*/
function _transferOwnership(address _newOwner) internal {
require(_newOwner != address(0));
emit OwnershipTransferred(owner, _newOwner);
owner = _newOwner;
}
}
contract Claimable is Ownable {
address public pendingOwner;
/**
* @dev Modifier throws if called by any account other than the pendingOwner.
*/
modifier onlyPendingOwner() {
require(msg.sender == pendingOwner);
_;
}
/**
* @dev Allows the current owner to set the pendingOwner address.
* @param newOwner The address to transfer ownership to.
*/
function transferOwnership(address newOwner) onlyOwner public {
pendingOwner = newOwner;
}
/**
* @dev Allows the pendingOwner address to finalize the transfer.
*/
function claimOwnership() onlyPendingOwner public {
emit OwnershipTransferred(owner, pendingOwner);
owner = pendingOwner;
pendingOwner = address(0);
}
}
contract AmmuNationStore is Claimable{
using SafeMath for uint256;
GTAInterface public token;
uint256 private tokenSellPrice; //wei
uint256 private tokenBuyPrice; //wei
uint256 public buyDiscount; //%
event Buy(address buyer, uint256 amount, uint256 payed);
event Robbery(address robber);
constructor (address _tokenAddress) public {
token = GTAInterface(_tokenAddress);
}
/** Owner's operations to fill and empty the stock */
// Important! remember to call GoldenThalerToken(address).approve(this, amount)
// or this contract will not be able to do the transfer on your behalf.
function depositGTA(uint256 amount) onlyOwner public {
require(token.transferFrom(msg.sender, this, amount), "Insufficient funds");
}
function withdrawGTA(uint256 amount) onlyOwner public {
require(token.transfer(msg.sender, amount), "Amount exceeds the available balance");
}
function robCashier() onlyOwner public {
msg.sender.transfer(address(this).balance);
emit Robbery(msg.sender);
}
/** */
/**
* @dev Set the prices in wei for 1 GTA
* @param _newSellPrice The price people can sell GTA for
* @param _newBuyPrice The price people can buy GTA for
*/
function setTokenPrices(uint256 _newSellPrice, uint256 _newBuyPrice) onlyOwner public {
tokenSellPrice = _newSellPrice;
tokenBuyPrice = _newBuyPrice;
}
function buy() payable public returns (uint256){
//note: the price of 1 GTA is in wei, but the token transfer expects the amount in 'token wei'
//so we're missing 10*18
uint256 value = msg.value.mul(1 ether);
uint256 _buyPrice = tokenBuyPrice;
if (buyDiscount > 0) {
//happy discount!
_buyPrice = _buyPrice.sub(_buyPrice.mul(buyDiscount).div(100));
}
uint256 amount = value.div(_buyPrice);
require(token.balanceOf(this) >= amount, "Sold out");
require(token.transfer(msg.sender, amount), "Couldn't transfer token");
emit Buy(msg.sender, amount, msg.value);
return amount;
}
// Important! remember to call GoldenThalerToken(address).approve(this, amount)
// or this contract will not be able to do the transfer on your behalf.
//TODO No sell at this moment
/*function sell(uint256 amount) public returns (uint256){
require(token.balanceOf(msg.sender) >= amount, "Insufficient funds");
require(token.transferFrom(msg.sender, this, amount), "Couldn't transfer token");
uint256 revenue = amount.mul(tokenSellPrice).div(1 ether);
msg.sender.transfer(revenue);
return revenue;
}*/
function applyDiscount(uint256 discount) onlyOwner public {
buyDiscount = discount;
}
function getTokenBuyPrice() public view returns (uint256) {
uint256 _buyPrice = tokenBuyPrice;
if (buyDiscount > 0) {
_buyPrice = _buyPrice.sub(_buyPrice.mul(buyDiscount).div(100));
}
return _buyPrice;
}
function getTokenSellPrice() public view returns (uint256) {
return tokenSellPrice;
}
}
/**
* @title GTA contract interface
*/
interface GTAInterface {
function transferFrom(address _from, address _to, uint256 _value) external returns (bool);
function transfer(address to, uint256 value) external returns (bool);
function balanceOf(address _owner) external view returns (uint256);
}
|
GTA contract interface/
|
interface GTAInterface {
function transferFrom(address _from, address _to, uint256 _value) external returns (bool);
function transfer(address to, uint256 value) external returns (bool);
function balanceOf(address _owner) external view returns (uint256);
}
| 13,002,850 |
./full_match/3/0x2AeeF31f57F5cB7BB851de56ea8f199500bB9e9F/sources/nf-token.sol
|
Mints a new NFT. _to The address that will own the minted NFT. _tokenId of the NFT to be minted by the msg.sender. _uri String representing RFC 3986 URI./onlyOwner
|
function mint(
address _to,
uint256 _tokenId,
string calldata _uri
)
external
{
super._mint(_to, _tokenId);
super._setTokenUri(_tokenId, _uri);
}
| 8,143,283 |
./partial_match/8453/0x2B0A43DCcBD7d42c18F6A83F86D1a19fA58d541A/sources/MasterChefV2.sol
|
View function to see pending BSWAP on frontend.
|
function pendingReward(uint256 _pid, address _user) public view returns (uint256) {
PoolInfo storage pool = poolInfo[_pid];
UserInfo storage user = userInfo[_pid][_user];
uint256 accPerShare = pool.accPerShare;
uint256 lpSupply = pool.totalDeposit;
if (block.timestamp > pool.lastRewardTime && lpSupply != 0) {
uint256 multiplier = getMultiplier(pool.lastRewardTime, block.timestamp);
uint256 reward = multiplier.mul(bswapPerSec).mul(pool.allocPoint).div(totalAllocPoint);
accPerShare = accPerShare.add(reward.mul(1e12).div(lpSupply));
}
return user.amount.mul(accPerShare).div(1e12).sub(user.rewardDebt);
}
| 16,755,553 |
./full_match/42220/0xfB1945943f752B2828d5DC2Ed3e00bd6513C6Fc1/sources/contracts/spaceswap-ubeswap/Factory.sol
|
this low-level function should be called from a contract which performs important safety checks
|
function mint(address to) external lock returns (uint liquidity) {
uint balance0 = IERC20Uniswap(token0).balanceOf(address(this));
uint balance1 = IERC20Uniswap(token1).balanceOf(address(this));
uint amount0 = balance0.sub(_reserve0);
uint amount1 = balance1.sub(_reserve1);
bool feeOn = _mintFee(_reserve0, _reserve1);
if (_totalSupply == 0) {
liquidity = Math.sqrt(amount0.mul(amount1)).sub(MINIMUM_LIQUIDITY);
liquidity = Math.min(amount0.mul(_totalSupply) / _reserve0, amount1.mul(_totalSupply) / _reserve1);
}
require(liquidity > 0, 'UniswapV2: INSUFFICIENT_LIQUIDITY_MINTED');
_mint(to, liquidity);
_update(balance0, balance1, _reserve0, _reserve1);
emit Mint(msg.sender, amount0, amount1);
}
| 16,334,168 |
./partial_match/1/0x6B0B234fB2f380309D47A7E9391E29E9a179395a/sources/src/v0.8/llo-feeds/Verifier.sol
|
Generates the config digest from config data feedId Feed ID to set config for sourceChainId Chain ID of source config sourceAddress Address of source config Verifier configCount ordinal number of this config setting among all config settings over the life of this contract signers ith element is address ith oracle uses to sign a report offchainTransmitters ith element is address ith oracle used to transmit reports (in this case used for flexible additional field, such as CSA pub keys) f maximum number of faulty/dishonest oracles the protocol can tolerate while still working correctly onchainConfig serialized configuration used by the contract (and possibly oracles) offchainConfigVersion version of the serialization format used for "offchainConfig" parameter offchainConfig serialized configuration used by the oracles exclusively and only passed through the contract This function is a modified version of the method from OCR2Abstract 0x0006 corresponds to ConfigDigestPrefixMercuryV02 in libocr
|
function _configDigestFromConfigData(
bytes32 feedId,
uint256 sourceChainId,
address sourceAddress,
uint64 configCount,
address[] memory signers,
bytes32[] memory offchainTransmitters,
uint8 f,
bytes memory onchainConfig,
uint64 offchainConfigVersion,
bytes memory offchainConfig
) internal pure returns (bytes32) {
uint256 h = uint256(
keccak256(
abi.encode(
feedId,
sourceChainId,
sourceAddress,
configCount,
signers,
offchainTransmitters,
f,
onchainConfig,
offchainConfigVersion,
offchainConfig
)
)
);
return bytes32((prefix & prefixMask) | (h & ~prefixMask));
}
| 3,963,457 |
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (proxy/utils/Initializable.sol)
pragma solidity ^0.8.0;
import "../../utils/AddressUpgradeable.sol";
/**
* @dev This is a base contract to aid in writing upgradeable contracts, or any kind of contract that will be deployed
* behind a proxy. Since a proxied contract can't have a constructor, it's common to move constructor logic to an
* external initializer function, usually called `initialize`. It then becomes necessary to protect this initializer
* function so it can only be called once. The {initializer} modifier provided by this contract will have this effect.
*
* TIP: To avoid leaving the proxy in an uninitialized state, the initializer function should be called as early as
* possible by providing the encoded function call as the `_data` argument to {ERC1967Proxy-constructor}.
*
* CAUTION: When used with inheritance, manual care must be taken to not invoke a parent initializer twice, or to ensure
* that all initializers are idempotent. This is not verified automatically as constructors are by Solidity.
*
* [CAUTION]
* ====
* Avoid leaving a contract uninitialized.
*
* An uninitialized contract can be taken over by an attacker. This applies to both a proxy and its implementation
* contract, which may impact the proxy. To initialize the implementation contract, you can either invoke the
* initializer manually, or you can include a constructor to automatically mark it as initialized when it is deployed:
*
* [.hljs-theme-light.nopadding]
* ```
* /// @custom:oz-upgrades-unsafe-allow constructor
* constructor() initializer {}
* ```
* ====
*/
abstract contract Initializable {
/**
* @dev Indicates that the contract has been initialized.
*/
bool private _initialized;
/**
* @dev Indicates that the contract is in the process of being initialized.
*/
bool private _initializing;
/**
* @dev Modifier to protect an initializer function from being invoked twice.
*/
modifier initializer() {
// If the contract is initializing we ignore whether _initialized is set in order to support multiple
// inheritance patterns, but we only do this in the context of a constructor, because in other contexts the
// contract may have been reentered.
require(_initializing ? _isConstructor() : !_initialized, "Initializable: contract is already initialized");
bool isTopLevelCall = !_initializing;
if (isTopLevelCall) {
_initializing = true;
_initialized = true;
}
_;
if (isTopLevelCall) {
_initializing = false;
}
}
/**
* @dev Modifier to protect an initialization function so that it can only be invoked by functions with the
* {initializer} modifier, directly or indirectly.
*/
modifier onlyInitializing() {
require(_initializing, "Initializable: contract is not initializing");
_;
}
function _isConstructor() private view returns (bool) {
return !AddressUpgradeable.isContract(address(this));
}
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (utils/Address.sol)
pragma solidity ^0.8.0;
/**
* @dev Collection of functions related to the address type
*/
library AddressUpgradeable {
/**
* @dev Returns true if `account` is a contract.
*
* [IMPORTANT]
* ====
* It is unsafe to assume that an address for which this function returns
* false is an externally-owned account (EOA) and not a contract.
*
* Among others, `isContract` will return false for the following
* types of addresses:
*
* - an externally-owned account
* - a contract in construction
* - an address where a contract will be created
* - an address where a contract lived, but was destroyed
* ====
*/
function isContract(address account) internal view returns (bool) {
// This method relies on extcodesize, which returns 0 for contracts in
// construction, since the code is only stored at the end of the
// constructor execution.
uint256 size;
assembly {
size := extcodesize(account)
}
return size > 0;
}
/**
* @dev Replacement for Solidity's `transfer`: sends `amount` wei to
* `recipient`, forwarding all available gas and reverting on errors.
*
* https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost
* of certain opcodes, possibly making contracts go over the 2300 gas limit
* imposed by `transfer`, making them unable to receive funds via
* `transfer`. {sendValue} removes this limitation.
*
* https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more].
*
* IMPORTANT: because control is transferred to `recipient`, care must be
* taken to not create reentrancy vulnerabilities. Consider using
* {ReentrancyGuard} or the
* https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern].
*/
function sendValue(address payable recipient, uint256 amount) internal {
require(address(this).balance >= amount, "Address: insufficient balance");
(bool success, ) = recipient.call{value: amount}("");
require(success, "Address: unable to send value, recipient may have reverted");
}
/**
* @dev Performs a Solidity function call using a low level `call`. A
* plain `call` is an unsafe replacement for a function call: use this
* function instead.
*
* If `target` reverts with a revert reason, it is bubbled up by this
* function (like regular Solidity function calls).
*
* Returns the raw returned data. To convert to the expected return value,
* use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`].
*
* 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");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with
* `errorMessage` as a fallback revert reason when `target` reverts.
*
* _Available since v3.1._
*/
function functionCall(
address target,
bytes memory data,
string memory errorMessage
) internal returns (bytes memory) {
return functionCallWithValue(target, data, 0, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but also transferring `value` wei to `target`.
*
* Requirements:
*
* - the calling contract must have an ETH balance of at least `value`.
* - the called Solidity function must be `payable`.
*
* _Available since v3.1._
*/
function functionCallWithValue(
address target,
bytes memory data,
uint256 value
) internal returns (bytes memory) {
return functionCallWithValue(target, data, value, "Address: low-level call with value failed");
}
/**
* @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but
* with `errorMessage` as a fallback revert reason when `target` reverts.
*
* _Available since v3.1._
*/
function functionCallWithValue(
address target,
bytes memory data,
uint256 value,
string memory errorMessage
) internal returns (bytes memory) {
require(address(this).balance >= value, "Address: insufficient balance for call");
require(isContract(target), "Address: call to non-contract");
(bool success, bytes memory returndata) = target.call{value: value}(data);
return verifyCallResult(success, returndata, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but performing a static call.
*
* _Available since v3.3._
*/
function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) {
return functionStaticCall(target, data, "Address: low-level static call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`],
* but performing a static call.
*
* _Available since v3.3._
*/
function functionStaticCall(
address target,
bytes memory data,
string memory errorMessage
) internal view returns (bytes memory) {
require(isContract(target), "Address: static call to non-contract");
(bool success, bytes memory returndata) = target.staticcall(data);
return verifyCallResult(success, returndata, errorMessage);
}
/**
* @dev Tool to verifies that a low level call was successful, and revert if it wasn't, either by bubbling the
* revert reason using the provided one.
*
* _Available since v4.3._
*/
function verifyCallResult(
bool success,
bytes memory returndata,
string memory errorMessage
) internal pure returns (bytes memory) {
if (success) {
return returndata;
} else {
// Look for revert reason and bubble it up if present
if (returndata.length > 0) {
// The easiest way to bubble the revert reason is using memory via assembly
assembly {
let returndata_size := mload(returndata)
revert(add(32, returndata), returndata_size)
}
} else {
revert(errorMessage);
}
}
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
/**
* @dev Interface of the ERC20 standard as defined in the EIP.
*/
interface IERC20 {
/**
* @dev Returns the amount of tokens in existence.
*/
function totalSupply() external view returns (uint256);
/**
* @dev Returns the amount of tokens owned by `account`.
*/
function balanceOf(address account) external view returns (uint256);
/**
* @dev Moves `amount` tokens from the caller's account to `recipient`.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/
function transfer(address recipient, uint256 amount) external returns (bool);
/**
* @dev Returns the remaining number of tokens that `spender` will be
* allowed to spend on behalf of `owner` through {transferFrom}. This is
* zero by default.
*
* This value changes when {approve} or {transferFrom} are called.
*/
function allowance(address owner, address spender) external view returns (uint256);
/**
* @dev Sets `amount` as the allowance of `spender` over the caller's tokens.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* IMPORTANT: 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
*
* Emits an {Approval} event.
*/
function approve(address spender, uint256 amount) external returns (bool);
/**
* @dev Moves `amount` tokens from `sender` to `recipient` using the
* allowance mechanism. `amount` is then deducted from the caller's
* allowance.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/
function transferFrom(
address sender,
address recipient,
uint256 amount
) external returns (bool);
/**
* @dev Emitted when `value` tokens are moved from one account (`from`) to
* another (`to`).
*
* Note that `value` may be zero.
*/
event Transfer(address indexed from, address indexed to, uint256 value);
/**
* @dev Emitted when the allowance of a `spender` for an `owner` is set by
* a call to {approve}. `value` is the new allowance.
*/
event Approval(address indexed owner, address indexed spender, uint256 value);
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import "../IERC20.sol";
import "../../../utils/Address.sol";
/**
* @title SafeERC20
* @dev Wrappers around ERC20 operations that throw on failure (when the token
* contract returns false). Tokens that return no value (and instead revert or
* throw on failure) are also supported, non-reverting calls are assumed to be
* successful.
* To use this library you can add a `using SafeERC20 for IERC20;` statement to your contract,
* which allows you to call the safe operations as `token.safeTransfer(...)`, etc.
*/
library SafeERC20 {
using Address for address;
function safeTransfer(
IERC20 token,
address to,
uint256 value
) internal {
_callOptionalReturn(token, abi.encodeWithSelector(token.transfer.selector, to, value));
}
function safeTransferFrom(
IERC20 token,
address from,
address to,
uint256 value
) internal {
_callOptionalReturn(token, abi.encodeWithSelector(token.transferFrom.selector, from, to, value));
}
/**
* @dev Deprecated. This function has issues similar to the ones found in
* {IERC20-approve}, and its usage is discouraged.
*
* Whenever possible, use {safeIncreaseAllowance} and
* {safeDecreaseAllowance} instead.
*/
function safeApprove(
IERC20 token,
address spender,
uint256 value
) internal {
// safeApprove should only be called when setting an initial allowance,
// or when resetting it to zero. To increase and decrease it, use
// 'safeIncreaseAllowance' and 'safeDecreaseAllowance'
require(
(value == 0) || (token.allowance(address(this), spender) == 0),
"SafeERC20: approve from non-zero to non-zero allowance"
);
_callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, value));
}
function safeIncreaseAllowance(
IERC20 token,
address spender,
uint256 value
) internal {
uint256 newAllowance = token.allowance(address(this), spender) + value;
_callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance));
}
function safeDecreaseAllowance(
IERC20 token,
address spender,
uint256 value
) internal {
unchecked {
uint256 oldAllowance = token.allowance(address(this), spender);
require(oldAllowance >= value, "SafeERC20: decreased allowance below zero");
uint256 newAllowance = oldAllowance - value;
_callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance));
}
}
/**
* @dev Imitates a Solidity high-level call (i.e. a regular function call to a contract), relaxing the requirement
* on the return value: the return value is optional (but if data is returned, it must not be false).
* @param token The token targeted by the call.
* @param data The call data (encoded using abi.encode or one of its variants).
*/
function _callOptionalReturn(IERC20 token, bytes memory data) private {
// We need to perform a low level call here, to bypass Solidity's return data size checking mechanism, since
// we're implementing it ourselves. We use {Address.functionCall} to perform this call, which verifies that
// the target address contains contract code and also asserts for success in the low-level call.
bytes memory returndata = address(token).functionCall(data, "SafeERC20: low-level call failed");
if (returndata.length > 0) {
// Return data is optional
require(abi.decode(returndata, (bool)), "SafeERC20: ERC20 operation did not succeed");
}
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
/**
* @dev Collection of functions related to the address type
*/
library Address {
/**
* @dev Returns true if `account` is a contract.
*
* [IMPORTANT]
* ====
* It is unsafe to assume that an address for which this function returns
* false is an externally-owned account (EOA) and not a contract.
*
* Among others, `isContract` will return false for the following
* types of addresses:
*
* - an externally-owned account
* - a contract in construction
* - an address where a contract will be created
* - an address where a contract lived, but was destroyed
* ====
*/
function isContract(address account) internal view returns (bool) {
// This method relies on extcodesize, which returns 0 for contracts in
// construction, since the code is only stored at the end of the
// constructor execution.
uint256 size;
assembly {
size := extcodesize(account)
}
return size > 0;
}
/**
* @dev Replacement for Solidity's `transfer`: sends `amount` wei to
* `recipient`, forwarding all available gas and reverting on errors.
*
* https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost
* of certain opcodes, possibly making contracts go over the 2300 gas limit
* imposed by `transfer`, making them unable to receive funds via
* `transfer`. {sendValue} removes this limitation.
*
* https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more].
*
* IMPORTANT: because control is transferred to `recipient`, care must be
* taken to not create reentrancy vulnerabilities. Consider using
* {ReentrancyGuard} or the
* https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern].
*/
function sendValue(address payable recipient, uint256 amount) internal {
require(address(this).balance >= amount, "Address: insufficient balance");
(bool success, ) = recipient.call{value: amount}("");
require(success, "Address: unable to send value, recipient may have reverted");
}
/**
* @dev Performs a Solidity function call using a low level `call`. A
* plain `call` is an unsafe replacement for a function call: use this
* function instead.
*
* If `target` reverts with a revert reason, it is bubbled up by this
* function (like regular Solidity function calls).
*
* Returns the raw returned data. To convert to the expected return value,
* use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`].
*
* 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");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with
* `errorMessage` as a fallback revert reason when `target` reverts.
*
* _Available since v3.1._
*/
function functionCall(
address target,
bytes memory data,
string memory errorMessage
) internal returns (bytes memory) {
return functionCallWithValue(target, data, 0, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but also transferring `value` wei to `target`.
*
* Requirements:
*
* - the calling contract must have an ETH balance of at least `value`.
* - the called Solidity function must be `payable`.
*
* _Available since v3.1._
*/
function functionCallWithValue(
address target,
bytes memory data,
uint256 value
) internal returns (bytes memory) {
return functionCallWithValue(target, data, value, "Address: low-level call with value failed");
}
/**
* @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but
* with `errorMessage` as a fallback revert reason when `target` reverts.
*
* _Available since v3.1._
*/
function functionCallWithValue(
address target,
bytes memory data,
uint256 value,
string memory errorMessage
) internal returns (bytes memory) {
require(address(this).balance >= value, "Address: insufficient balance for call");
require(isContract(target), "Address: call to non-contract");
(bool success, bytes memory returndata) = target.call{value: value}(data);
return verifyCallResult(success, returndata, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but performing a static call.
*
* _Available since v3.3._
*/
function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) {
return functionStaticCall(target, data, "Address: low-level static call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`],
* but performing a static call.
*
* _Available since v3.3._
*/
function functionStaticCall(
address target,
bytes memory data,
string memory errorMessage
) internal view returns (bytes memory) {
require(isContract(target), "Address: static call to non-contract");
(bool success, bytes memory returndata) = target.staticcall(data);
return verifyCallResult(success, returndata, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but performing a delegate call.
*
* _Available since v3.4._
*/
function functionDelegateCall(address target, bytes memory data) internal returns (bytes memory) {
return functionDelegateCall(target, data, "Address: low-level delegate call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`],
* but performing a delegate call.
*
* _Available since v3.4._
*/
function functionDelegateCall(
address target,
bytes memory data,
string memory errorMessage
) internal returns (bytes memory) {
require(isContract(target), "Address: delegate call to non-contract");
(bool success, bytes memory returndata) = target.delegatecall(data);
return verifyCallResult(success, returndata, errorMessage);
}
/**
* @dev Tool to verifies that a low level call was successful, and revert if it wasn't, either by bubbling the
* revert reason using the provided one.
*
* _Available since v4.3._
*/
function verifyCallResult(
bool success,
bytes memory returndata,
string memory errorMessage
) internal pure returns (bytes memory) {
if (success) {
return returndata;
} else {
// Look for revert reason and bubble it up if present
if (returndata.length > 0) {
// The easiest way to bubble the revert reason is using memory via assembly
assembly {
let returndata_size := mload(returndata)
revert(add(32, returndata), returndata_size)
}
} else {
revert(errorMessage);
}
}
}
}
// SPDX-License-Identifier: GPL-2.0-or-later
pragma solidity >=0.5.0;
import './pool/IUniswapV3PoolImmutables.sol';
import './pool/IUniswapV3PoolState.sol';
import './pool/IUniswapV3PoolDerivedState.sol';
import './pool/IUniswapV3PoolActions.sol';
import './pool/IUniswapV3PoolOwnerActions.sol';
import './pool/IUniswapV3PoolEvents.sol';
/// @title The interface for a Uniswap V3 Pool
/// @notice A Uniswap pool facilitates swapping and automated market making between any two assets that strictly conform
/// to the ERC20 specification
/// @dev The pool interface is broken up into many smaller pieces
interface IUniswapV3Pool is
IUniswapV3PoolImmutables,
IUniswapV3PoolState,
IUniswapV3PoolDerivedState,
IUniswapV3PoolActions,
IUniswapV3PoolOwnerActions,
IUniswapV3PoolEvents
{
}
// SPDX-License-Identifier: GPL-2.0-or-later
pragma solidity >=0.5.0;
/// @title Permissionless pool actions
/// @notice Contains pool methods that can be called by anyone
interface IUniswapV3PoolActions {
/// @notice Sets the initial price for the pool
/// @dev Price is represented as a sqrt(amountToken1/amountToken0) Q64.96 value
/// @param sqrtPriceX96 the initial sqrt price of the pool as a Q64.96
function initialize(uint160 sqrtPriceX96) external;
/// @notice Adds liquidity for the given recipient/tickLower/tickUpper position
/// @dev The caller of this method receives a callback in the form of IUniswapV3MintCallback#uniswapV3MintCallback
/// in which they must pay any token0 or token1 owed for the liquidity. The amount of token0/token1 due depends
/// on tickLower, tickUpper, the amount of liquidity, and the current price.
/// @param recipient The address for which the liquidity will be created
/// @param tickLower The lower tick of the position in which to add liquidity
/// @param tickUpper The upper tick of the position in which to add liquidity
/// @param amount The amount of liquidity to mint
/// @param data Any data that should be passed through to the callback
/// @return amount0 The amount of token0 that was paid to mint the given amount of liquidity. Matches the value in the callback
/// @return amount1 The amount of token1 that was paid to mint the given amount of liquidity. Matches the value in the callback
function mint(
address recipient,
int24 tickLower,
int24 tickUpper,
uint128 amount,
bytes calldata data
) external returns (uint256 amount0, uint256 amount1);
/// @notice Collects tokens owed to a position
/// @dev 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.
/// @param recipient The address which should receive the fees collected
/// @param tickLower The lower tick of the position for which to collect fees
/// @param tickUpper The upper tick of the position for which to collect fees
/// @param amount0Requested How much token0 should be withdrawn from the fees owed
/// @param amount1Requested How much token1 should be withdrawn from the fees owed
/// @return amount0 The amount of fees collected in token0
/// @return amount1 The amount of fees collected in token1
function collect(
address recipient,
int24 tickLower,
int24 tickUpper,
uint128 amount0Requested,
uint128 amount1Requested
) external returns (uint128 amount0, uint128 amount1);
/// @notice Burn liquidity from the sender and account tokens owed for the liquidity to the position
/// @dev Can be used to trigger a recalculation of fees owed to a position by calling with an amount of 0
/// @dev Fees must be collected separately via a call to #collect
/// @param tickLower The lower tick of the position for which to burn liquidity
/// @param tickUpper The upper tick of the position for which to burn liquidity
/// @param amount How much liquidity to burn
/// @return amount0 The amount of token0 sent to the recipient
/// @return amount1 The amount of token1 sent to the recipient
function burn(
int24 tickLower,
int24 tickUpper,
uint128 amount
) external returns (uint256 amount0, uint256 amount1);
/// @notice Swap token0 for token1, or token1 for token0
/// @dev The caller of this method receives a callback in the form of IUniswapV3SwapCallback#uniswapV3SwapCallback
/// @param recipient The address to receive the output of the swap
/// @param zeroForOne The direction of the swap, true for token0 to token1, false for token1 to token0
/// @param amountSpecified The amount of the swap, which implicitly configures the swap as exact input (positive), or exact output (negative)
/// @param sqrtPriceLimitX96 The Q64.96 sqrt price limit. If zero for one, the price cannot be less than this
/// value after the swap. If one for zero, the price cannot be greater than this value after the swap
/// @param data Any data to be passed through to the callback
/// @return amount0 The delta of the balance of token0 of the pool, exact when negative, minimum when positive
/// @return amount1 The delta of the balance of token1 of the pool, exact when negative, minimum when positive
function swap(
address recipient,
bool zeroForOne,
int256 amountSpecified,
uint160 sqrtPriceLimitX96,
bytes calldata data
) external returns (int256 amount0, int256 amount1);
/// @notice Receive token0 and/or token1 and pay it back, plus a fee, in the callback
/// @dev The caller of this method receives a callback in the form of IUniswapV3FlashCallback#uniswapV3FlashCallback
/// @dev Can be used to donate underlying tokens pro-rata to currently in-range liquidity providers by calling
/// with 0 amount{0,1} and sending the donation amount(s) from the callback
/// @param recipient The address which will receive the token0 and token1 amounts
/// @param amount0 The amount of token0 to send
/// @param amount1 The amount of token1 to send
/// @param data Any data to be passed through to the callback
function flash(
address recipient,
uint256 amount0,
uint256 amount1,
bytes calldata data
) external;
/// @notice Increase the maximum number of price and liquidity observations that this pool will store
/// @dev This method is no-op if the pool already has an observationCardinalityNext greater than or equal to
/// the input observationCardinalityNext.
/// @param observationCardinalityNext The desired minimum number of observations for the pool to store
function increaseObservationCardinalityNext(uint16 observationCardinalityNext) external;
}
// SPDX-License-Identifier: GPL-2.0-or-later
pragma solidity >=0.5.0;
/// @title Pool state that is not stored
/// @notice Contains view functions to provide information about the pool that is computed rather than stored on the
/// blockchain. The functions here may have variable gas costs.
interface IUniswapV3PoolDerivedState {
/// @notice Returns the cumulative tick and liquidity as of each timestamp `secondsAgo` from the current block timestamp
/// @dev To get a time weighted average tick or liquidity-in-range, you must call this with two values, one representing
/// the beginning of the period and another for the end of the period. E.g., to get the last hour time-weighted average tick,
/// you must call it with secondsAgos = [3600, 0].
/// @dev The time weighted average tick represents the geometric time weighted average price of the pool, in
/// log base sqrt(1.0001) of token1 / token0. The TickMath library can be used to go from a tick value to a ratio.
/// @param secondsAgos From how long ago each cumulative tick and liquidity value should be returned
/// @return tickCumulatives Cumulative tick values as of each `secondsAgos` from the current block timestamp
/// @return secondsPerLiquidityCumulativeX128s Cumulative seconds per liquidity-in-range value as of each `secondsAgos` from the current block
/// timestamp
function observe(uint32[] calldata secondsAgos)
external
view
returns (int56[] memory tickCumulatives, uint160[] memory secondsPerLiquidityCumulativeX128s);
/// @notice Returns a snapshot of the tick cumulative, seconds per liquidity and seconds inside a tick range
/// @dev Snapshots must only be compared to other snapshots, taken over a period for which a position existed.
/// I.e., snapshots cannot be compared if a position is not held for the entire period between when the first
/// snapshot is taken and the second snapshot is taken.
/// @param tickLower The lower tick of the range
/// @param tickUpper The upper tick of the range
/// @return tickCumulativeInside The snapshot of the tick accumulator for the range
/// @return secondsPerLiquidityInsideX128 The snapshot of seconds per liquidity for the range
/// @return secondsInside The snapshot of seconds per liquidity for the range
function snapshotCumulativesInside(int24 tickLower, int24 tickUpper)
external
view
returns (
int56 tickCumulativeInside,
uint160 secondsPerLiquidityInsideX128,
uint32 secondsInside
);
}
// SPDX-License-Identifier: GPL-2.0-or-later
pragma solidity >=0.5.0;
/// @title Events emitted by a pool
/// @notice Contains all events emitted by the pool
interface IUniswapV3PoolEvents {
/// @notice Emitted exactly once by a pool when #initialize is first called on the pool
/// @dev Mint/Burn/Swap cannot be emitted by the pool before Initialize
/// @param sqrtPriceX96 The initial sqrt price of the pool, as a Q64.96
/// @param tick The initial tick of the pool, i.e. log base 1.0001 of the starting price of the pool
event Initialize(uint160 sqrtPriceX96, int24 tick);
/// @notice Emitted when liquidity is minted for a given position
/// @param sender The address that minted the liquidity
/// @param owner The owner of the position and recipient of any minted liquidity
/// @param tickLower The lower tick of the position
/// @param tickUpper The upper tick of the position
/// @param amount The amount of liquidity minted to the position range
/// @param amount0 How much token0 was required for the minted liquidity
/// @param amount1 How much token1 was required for the minted liquidity
event Mint(
address sender,
address indexed owner,
int24 indexed tickLower,
int24 indexed tickUpper,
uint128 amount,
uint256 amount0,
uint256 amount1
);
/// @notice Emitted when fees are collected by the owner of a position
/// @dev Collect events may be emitted with zero amount0 and amount1 when the caller chooses not to collect fees
/// @param owner The owner of the position for which fees are collected
/// @param tickLower The lower tick of the position
/// @param tickUpper The upper tick of the position
/// @param amount0 The amount of token0 fees collected
/// @param amount1 The amount of token1 fees collected
event Collect(
address indexed owner,
address recipient,
int24 indexed tickLower,
int24 indexed tickUpper,
uint128 amount0,
uint128 amount1
);
/// @notice Emitted when a position's liquidity is removed
/// @dev Does not withdraw any fees earned by the liquidity position, which must be withdrawn via #collect
/// @param owner The owner of the position for which liquidity is removed
/// @param tickLower The lower tick of the position
/// @param tickUpper The upper tick of the position
/// @param amount The amount of liquidity to remove
/// @param amount0 The amount of token0 withdrawn
/// @param amount1 The amount of token1 withdrawn
event Burn(
address indexed owner,
int24 indexed tickLower,
int24 indexed tickUpper,
uint128 amount,
uint256 amount0,
uint256 amount1
);
/// @notice Emitted by the pool for any swaps between token0 and token1
/// @param sender The address that initiated the swap call, and that received the callback
/// @param recipient The address that received the output of the swap
/// @param amount0 The delta of the token0 balance of the pool
/// @param amount1 The delta of the token1 balance of the pool
/// @param sqrtPriceX96 The sqrt(price) of the pool after the swap, as a Q64.96
/// @param liquidity The liquidity of the pool after the swap
/// @param tick The log base 1.0001 of price of the pool after the swap
event Swap(
address indexed sender,
address indexed recipient,
int256 amount0,
int256 amount1,
uint160 sqrtPriceX96,
uint128 liquidity,
int24 tick
);
/// @notice Emitted by the pool for any flashes of token0/token1
/// @param sender The address that initiated the swap call, and that received the callback
/// @param recipient The address that received the tokens from flash
/// @param amount0 The amount of token0 that was flashed
/// @param amount1 The amount of token1 that was flashed
/// @param paid0 The amount of token0 paid for the flash, which can exceed the amount0 plus the fee
/// @param paid1 The amount of token1 paid for the flash, which can exceed the amount1 plus the fee
event Flash(
address indexed sender,
address indexed recipient,
uint256 amount0,
uint256 amount1,
uint256 paid0,
uint256 paid1
);
/// @notice Emitted by the pool for increases to the number of observations that can be stored
/// @dev observationCardinalityNext is not the observation cardinality until an observation is written at the index
/// just before a mint/swap/burn.
/// @param observationCardinalityNextOld The previous value of the next observation cardinality
/// @param observationCardinalityNextNew The updated value of the next observation cardinality
event IncreaseObservationCardinalityNext(
uint16 observationCardinalityNextOld,
uint16 observationCardinalityNextNew
);
/// @notice Emitted when the protocol fee is changed by the pool
/// @param feeProtocol0Old The previous value of the token0 protocol fee
/// @param feeProtocol1Old The previous value of the token1 protocol fee
/// @param feeProtocol0New The updated value of the token0 protocol fee
/// @param feeProtocol1New The updated value of the token1 protocol fee
event SetFeeProtocol(uint8 feeProtocol0Old, uint8 feeProtocol1Old, uint8 feeProtocol0New, uint8 feeProtocol1New);
/// @notice Emitted when the collected protocol fees are withdrawn by the factory owner
/// @param sender The address that collects the protocol fees
/// @param recipient The address that receives the collected protocol fees
/// @param amount0 The amount of token0 protocol fees that is withdrawn
/// @param amount0 The amount of token1 protocol fees that is withdrawn
event CollectProtocol(address indexed sender, address indexed recipient, uint128 amount0, uint128 amount1);
}
// SPDX-License-Identifier: GPL-2.0-or-later
pragma solidity >=0.5.0;
/// @title Pool state that never changes
/// @notice These parameters are fixed for a pool forever, i.e., the methods will always return the same values
interface IUniswapV3PoolImmutables {
/// @notice The contract that deployed the pool, which must adhere to the IUniswapV3Factory interface
/// @return The contract address
function factory() external view returns (address);
/// @notice The first of the two tokens of the pool, sorted by address
/// @return The token contract address
function token0() external view returns (address);
/// @notice The second of the two tokens of the pool, sorted by address
/// @return The token contract address
function token1() external view returns (address);
/// @notice The pool's fee in hundredths of a bip, i.e. 1e-6
/// @return The fee
function fee() external view returns (uint24);
/// @notice The pool tick spacing
/// @dev Ticks can only be used at multiples of this value, minimum of 1 and always positive
/// e.g.: a tickSpacing of 3 means ticks can be initialized every 3rd tick, i.e., ..., -6, -3, 0, 3, 6, ...
/// This value is an int24 to avoid casting even though it is always positive.
/// @return The tick spacing
function tickSpacing() external view returns (int24);
/// @notice The maximum amount of position liquidity that can use any tick in the range
/// @dev This parameter is enforced per tick to prevent liquidity from overflowing a uint128 at any point, and
/// also prevents out-of-range liquidity from being used to prevent adding in-range liquidity to a pool
/// @return The max amount of liquidity per tick
function maxLiquidityPerTick() external view returns (uint128);
}
// SPDX-License-Identifier: GPL-2.0-or-later
pragma solidity >=0.5.0;
/// @title Permissioned pool actions
/// @notice Contains pool methods that may only be called by the factory owner
interface IUniswapV3PoolOwnerActions {
/// @notice Set the denominator of the protocol's % share of the fees
/// @param feeProtocol0 new protocol fee for token0 of the pool
/// @param feeProtocol1 new protocol fee for token1 of the pool
function setFeeProtocol(uint8 feeProtocol0, uint8 feeProtocol1) external;
/// @notice Collect the protocol fee accrued to the pool
/// @param recipient The address to which collected protocol fees should be sent
/// @param amount0Requested The maximum amount of token0 to send, can be 0 to collect fees in only token1
/// @param amount1Requested The maximum amount of token1 to send, can be 0 to collect fees in only token0
/// @return amount0 The protocol fee collected in token0
/// @return amount1 The protocol fee collected in token1
function collectProtocol(
address recipient,
uint128 amount0Requested,
uint128 amount1Requested
) external returns (uint128 amount0, uint128 amount1);
}
// SPDX-License-Identifier: GPL-2.0-or-later
pragma solidity >=0.5.0;
/// @title Pool state that can change
/// @notice These methods compose the pool's state, and can change with any frequency including multiple times
/// per transaction
interface IUniswapV3PoolState {
/// @notice The 0th storage slot in the pool stores many values, and is exposed as a single method to save gas
/// when accessed externally.
/// @return sqrtPriceX96 The current price of the pool as a sqrt(token1/token0) Q64.96 value
/// tick The current tick of the pool, i.e. according to the last tick transition that was run.
/// This value may not always be equal to SqrtTickMath.getTickAtSqrtRatio(sqrtPriceX96) if the price is on a tick
/// boundary.
/// observationIndex The index of the last oracle observation that was written,
/// observationCardinality The current maximum number of observations stored in the pool,
/// observationCardinalityNext The next maximum number of observations, to be updated when the observation.
/// feeProtocol The protocol fee for both tokens of the pool.
/// Encoded as two 4 bit values, where the protocol fee of token1 is shifted 4 bits and the protocol fee of token0
/// is the lower 4 bits. Used as the denominator of a fraction of the swap fee, e.g. 4 means 1/4th of the swap fee.
/// unlocked Whether the pool is currently locked to reentrancy
function slot0()
external
view
returns (
uint160 sqrtPriceX96,
int24 tick,
uint16 observationIndex,
uint16 observationCardinality,
uint16 observationCardinalityNext,
uint8 feeProtocol,
bool unlocked
);
/// @notice The fee growth as a Q128.128 fees of token0 collected per unit of liquidity for the entire life of the pool
/// @dev This value can overflow the uint256
function feeGrowthGlobal0X128() external view returns (uint256);
/// @notice The fee growth as a Q128.128 fees of token1 collected per unit of liquidity for the entire life of the pool
/// @dev This value can overflow the uint256
function feeGrowthGlobal1X128() external view returns (uint256);
/// @notice The amounts of token0 and token1 that are owed to the protocol
/// @dev Protocol fees will never exceed uint128 max in either token
function protocolFees() external view returns (uint128 token0, uint128 token1);
/// @notice The currently in range liquidity available to the pool
/// @dev This value has no relationship to the total liquidity across all ticks
function liquidity() external view returns (uint128);
/// @notice Look up information about a specific tick in the pool
/// @param tick The tick to look up
/// @return liquidityGross the total amount of position liquidity that uses the pool either as tick lower or
/// tick upper,
/// liquidityNet how much liquidity changes when the pool price crosses the tick,
/// feeGrowthOutside0X128 the fee growth on the other side of the tick from the current tick in token0,
/// feeGrowthOutside1X128 the fee growth on the other side of the tick from the current tick in token1,
/// tickCumulativeOutside the cumulative tick value on the other side of the tick from the current tick
/// secondsPerLiquidityOutsideX128 the seconds spent per liquidity on the other side of the tick from the current tick,
/// secondsOutside the seconds spent on the other side of the tick from the current tick,
/// initialized Set to true if the tick is initialized, i.e. liquidityGross is greater than 0, otherwise equal to false.
/// Outside values can only be used if the tick is initialized, i.e. if liquidityGross is greater than 0.
/// In addition, these values are only relative and must be used only in comparison to previous snapshots for
/// a specific position.
function ticks(int24 tick)
external
view
returns (
uint128 liquidityGross,
int128 liquidityNet,
uint256 feeGrowthOutside0X128,
uint256 feeGrowthOutside1X128,
int56 tickCumulativeOutside,
uint160 secondsPerLiquidityOutsideX128,
uint32 secondsOutside,
bool initialized
);
/// @notice Returns 256 packed tick initialized boolean values. See TickBitmap for more information
function tickBitmap(int16 wordPosition) external view returns (uint256);
/// @notice Returns the information about a position by the position's key
/// @param key The position's key is a hash of a preimage composed by the owner, tickLower and tickUpper
/// @return _liquidity The amount of liquidity in the position,
/// Returns feeGrowthInside0LastX128 fee growth of token0 inside the tick range as of the last mint/burn/poke,
/// Returns feeGrowthInside1LastX128 fee growth of token1 inside the tick range as of the last mint/burn/poke,
/// Returns tokensOwed0 the computed amount of token0 owed to the position as of the last mint/burn/poke,
/// Returns tokensOwed1 the computed amount of token1 owed to the position as of the last mint/burn/poke
function positions(bytes32 key)
external
view
returns (
uint128 _liquidity,
uint256 feeGrowthInside0LastX128,
uint256 feeGrowthInside1LastX128,
uint128 tokensOwed0,
uint128 tokensOwed1
);
/// @notice Returns data about a specific observation index
/// @param index The element of the observations array to fetch
/// @dev You most likely want to use #observe() instead of this method to get an observation as of some amount of time
/// ago, rather than at a specific index in the array.
/// @return blockTimestamp The timestamp of the observation,
/// Returns tickCumulative the tick multiplied by seconds elapsed for the life of the pool as of the observation timestamp,
/// Returns secondsPerLiquidityCumulativeX128 the seconds per in range liquidity for the life of the pool as of the observation timestamp,
/// Returns initialized whether the observation has been initialized and the values are safe to use
function observations(uint256 index)
external
view
returns (
uint32 blockTimestamp,
int56 tickCumulative,
uint160 secondsPerLiquidityCumulativeX128,
bool initialized
);
}
// SPDX-License-Identifier: MIT
pragma solidity 0.8.7;
import {OwnableUninitialized} from "./vendor/common/OwnableUninitialized.sol";
import {
IERC20,
SafeERC20
} from "@openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol";
import {IManagerProxy} from "./interfaces/IManagerProxy.sol";
import {IArrakisVaultV1} from "./interfaces/IArrakisVaultV1.sol";
import {IFeeTreasury} from "./interfaces/IFeeTreasury.sol";
import {IFeeDistributor} from "./interfaces/IFeeDistributor.sol";
import {
IUniswapV3Pool
} from "@uniswap/v3-core/contracts/interfaces/IUniswapV3Pool.sol";
import {
Initializable
} from "@openzeppelin/contracts-upgradeable/proxy/utils/Initializable.sol";
// solhint-disable-next-line max-states-count
contract FeeTreasury is IFeeTreasury, OwnableUninitialized, Initializable {
using SafeERC20 for IERC20;
address private immutable _weth;
// XXXXXXXX DO NOT MODIFY ORDERING XXXXXXXX
IArrakisVaultV1 public lpToken;
mapping(address => bool) public whitelistedRouter;
mapping(address => bool) public whitelistedAdmin;
address public feeDistributor;
address public operationsCollector;
uint32 public twapDuration;
uint24 public maxTwapDelta;
uint16 public protocolFeeBPS;
// APPPEND ADDITIONAL STATE VARS BELOW:
// XXXXXXXX DO NOT MODIFY ORDERING XXXXXXXX
modifier onlyAdmins() {
require(
msg.sender == _owner || whitelistedAdmin[msg.sender],
"FeeTreasury: onlyAdmins"
);
_;
}
constructor(address weth_) {
_weth = weth_;
}
function initialize(
IArrakisVaultV1 lpToken_,
address owner_,
address feeDistributor_,
uint16 protocolFeeBPS_,
uint24 maxTwapDelta_,
uint32 twapDuration_,
address[] memory routers_,
address[] memory admins_
) external initializer {
require(protocolFeeBPS_ <= 10000, "FeeTreasury: BPS");
require(
address(lpToken_.token0()) == _weth ||
address(lpToken_.token1()) == _weth,
"FeeTreasury: must include WETH"
);
for (uint256 i = 0; i < admins_.length; i++) {
whitelistedAdmin[admins_[i]] = true;
}
for (uint256 j = 0; j < routers_.length; j++) {
whitelistedRouter[routers_[j]] = true;
}
lpToken = lpToken_;
feeDistributor = feeDistributor_;
maxTwapDelta = maxTwapDelta_;
twapDuration = twapDuration_;
protocolFeeBPS = protocolFeeBPS_;
_owner = owner_;
operationsCollector = owner_;
}
// ====== PERMISSIONED OWNER FUNCTIONS ========
function whitelistRouters(address[] memory whitelist)
external
override
onlyAdmins
{
for (uint256 i = 0; i < whitelist.length; i++) {
whitelistedRouter[whitelist[i]] = true;
}
emit AddRouters(whitelist);
}
function blacklistRouters(address[] memory blacklist)
external
override
onlyAdmins
{
for (uint256 i = 0; i < blacklist.length; i++) {
whitelistedRouter[blacklist[i]] = false;
}
emit RemoveRouters(blacklist);
}
function whitelistAdmins(address[] memory whitelist)
external
override
onlyAdmins
{
for (uint256 i = 0; i < whitelist.length; i++) {
whitelistedAdmin[whitelist[i]] = true;
}
emit AddAdmins(whitelist);
}
function blacklistAdmins(address[] memory blacklist)
external
override
onlyAdmins
{
for (uint256 i = 0; i < blacklist.length; i++) {
whitelistedAdmin[blacklist[i]] = false;
}
emit RemoveAdmins(blacklist);
}
function updateFeeDistributor(address newFeeDistributor)
external
override
onlyAdmins
{
feeDistributor = newFeeDistributor;
emit UpdateFeeDistributor(newFeeDistributor);
}
function updateProtocolFeeBPS(uint16 newProtocolFeeBPS)
external
override
onlyAdmins
{
require(newProtocolFeeBPS <= 10000, "FeeTreasury: BPS");
protocolFeeBPS = newProtocolFeeBPS;
emit UpdateProtocolFeeBPS(newProtocolFeeBPS);
}
function updateMaxTwapDelta(uint24 newMaxTwapDelta)
external
override
onlyAdmins
{
maxTwapDelta = newMaxTwapDelta;
emit UpdateMaxTwapDelta(newMaxTwapDelta);
}
function updateTwapDuration(uint32 newTwapDuration)
external
override
onlyAdmins
{
twapDuration = newTwapDuration;
emit UpdateTwapDuration(newTwapDuration);
}
function updateLPToken(address newLPToken) external override onlyAdmins {
IArrakisVaultV1 _newLPToken = IArrakisVaultV1(newLPToken);
require(
address(_newLPToken.token0()) == _weth ||
address(_newLPToken.token1()) == _weth,
"FeeTreasury: must include WETH"
);
lpToken = _newLPToken;
emit UpdateLPToken(newLPToken);
}
function updateOperationsCollector(address newOperations)
external
override
onlyAdmins
{
require(newOperations != address(0), "FeeTreasury: zero address");
operationsCollector = newOperations;
emit UpdateOperationsCollector(newOperations);
}
function multiSwapForWETH(
IERC20[] memory tokens,
uint256[] memory amounts,
address[] memory routers,
bytes[] memory swapPayloads
) external override onlyAdmins {
for (uint256 i = 0; i < swapPayloads.length; i++) {
require(
address(tokens[i]) != _weth,
"FeeTreasury: cannot swap weth"
);
_swapForWETH(tokens[i], amounts[i], routers[i], swapPayloads[i]);
}
}
function swapForWETH(
IERC20 token,
uint256 amount,
address router,
bytes memory swapPayload
) external override onlyAdmins {
require(address(token) != _weth, "FeeTreasury: cannot swap weth");
_swapForWETH(token, amount, router, swapPayload);
}
// solhint-disable-next-line function-max-lines
function disperseProtocolFees(
uint256 amount,
address router,
bytes memory swapPayload
) external override onlyAdmins {
_checkTwap();
IArrakisVaultV1 _lpToken = lpToken;
IERC20 token0 = _lpToken.token0();
IERC20 token1 = _lpToken.token1();
uint256 balanceBefore;
uint256 balanceAfter;
bool isToken0 = address(token0) == _weth;
if (isToken0) {
balanceBefore = token1.balanceOf(address(this));
_swap(token0, amount, router, swapPayload);
balanceAfter = token1.balanceOf(address(this));
} else {
balanceBefore = token0.balanceOf(address(this));
_swap(token1, amount, router, swapPayload);
balanceAfter = token0.balanceOf(address(this));
}
require(
balanceBefore < balanceAfter,
"FeeTreasury: did not swap for valid output token"
);
uint256 wethBalance = IERC20(_weth).balanceOf(address(this));
uint256 protocolWeth = (wethBalance * protocolFeeBPS) / 10000;
if (wethBalance > protocolWeth) {
IERC20(_weth).safeTransfer(
operationsCollector,
wethBalance - protocolWeth
);
}
(uint256 deposit0, uint256 deposit1, uint256 mint) = _lpToken
.getMintAmounts(
isToken0 ? protocolWeth : balanceAfter - balanceBefore,
isToken0 ? balanceAfter - balanceBefore : protocolWeth
);
token0.safeIncreaseAllowance(address(_lpToken), deposit0);
token1.safeIncreaseAllowance(address(_lpToken), deposit1);
_lpToken.mint(mint, address(this));
uint256 lpBalance = IERC20(address(_lpToken)).balanceOf(address(this));
IERC20(address(_lpToken)).safeIncreaseAllowance(
feeDistributor,
lpBalance
);
IFeeDistributor(feeDistributor).setReward(lpBalance);
emit DisperseProtocolFees(deposit0, deposit1, lpBalance);
}
// ====== INTERNAL FUNCTIONS ========
function _swapForWETH(
IERC20 token,
uint256 amount,
address router,
bytes memory swapPayload
) internal returns (uint256 balanceChange) {
uint256 balanceBefore = IERC20(_weth).balanceOf(address(this));
_swap(token, amount, router, swapPayload);
balanceChange = IERC20(_weth).balanceOf(address(this)) - balanceBefore;
require(
balanceChange > 0,
"FeeTreasury: did not swap for valid output token"
);
}
function _swap(
IERC20 token,
uint256 amount,
address router,
bytes memory swapPayload
) internal {
require(
whitelistedRouter[router],
"FeeTreasury: router not whitelisted"
);
token.safeIncreaseAllowance(router, amount);
(bool success, ) = router.call(swapPayload);
require(success, "FeeTreasury: swap call failed");
}
function _checkTwap() internal view {
uint32 _twapDuration = twapDuration;
IUniswapV3Pool uniPool = lpToken.pool();
(, int24 tick, , , , , ) = uniPool.slot0();
uint32[] memory secondsAgo = new uint32[](2);
secondsAgo[0] = _twapDuration;
secondsAgo[1] = 0;
(int56[] memory tickCumulatives, ) = uniPool.observe(secondsAgo);
int24 twap;
unchecked {
twap = int24(
(tickCumulatives[1] - tickCumulatives[0]) /
int56(uint56(_twapDuration))
);
}
int24 delta = tick > twap ? tick - twap : twap - tick;
require(
delta <= int24(maxTwapDelta),
"FeeTreasury: frontrun protection"
);
}
}
// SPDX-License-Identifier: MIT
pragma solidity >=0.8.0;
import {IERC20} from "@openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol";
import {
IUniswapV3Pool
} from "@uniswap/v3-core/contracts/interfaces/IUniswapV3Pool.sol";
interface IArrakisVaultV1 {
function mint(uint256 mintAmount, address receiver)
external
returns (
uint256,
uint256,
uint128
);
function executiveRebalance(
int24 newLowerTick,
int24 newUpperTick,
uint160 swapThresholdPrice,
uint256 swapAmountBPS,
bool zeroForOne
) external;
function transferOwnership(address newOwner) external;
function updateManagerParams(
int16 newManagerFeeBPS,
address newManagerTreasury,
int16 newRebalanceBPS,
int16 newSlippageBPS,
int32 newSlippageInterval
) external;
function getMintAmounts(uint256 amount0, uint256 amount1)
external
view
returns (
uint256,
uint256,
uint256
);
function manager() external view returns (address);
function upperTick() external view returns (int24);
function lowerTick() external view returns (int24);
function pool() external view returns (IUniswapV3Pool);
function token0() external view returns (IERC20);
function token1() external view returns (IERC20);
}
// SPDX-License-Identifier: MIT
pragma solidity >=0.8.0;
interface IFeeDistributor {
function setReward(uint256 amount) external;
}
// SPDX-License-Identifier: MIT
pragma solidity >=0.8.0;
import {IERC20} from "@openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol";
interface IFeeTreasury {
event AddAdmins(address[] managers);
event RemoveAdmins(address[] managers);
event AddRouters(address[] routers);
event RemoveRouters(address[] routers);
event UpdateFeeDistributor(address feeDistributor);
event UpdateProtocolFeeBPS(uint16 protocolFeeBPS);
event UpdateTwapDuration(uint32 twapDuration);
event UpdateMaxTwapDelta(uint24 maxTwapDelta);
event UpdateLPToken(address lpToken);
event UpdateOperationsCollector(address operationsCollector);
event CheckpointFees(
uint256 protocolBalance0,
uint256 operationsBalance0,
uint256 protocolBalance1,
uint256 operationsBalance1
);
event DisperseProtocolFees(uint256 token0, uint256 token1, uint256 lp);
event FundManagerBalance(address manager, address vault, uint256 amount);
// ====== PERMISSIONED OWNER FUNCTIONS ========
function whitelistRouters(address[] memory whitelist) external;
function blacklistRouters(address[] memory blacklist) external;
function whitelistAdmins(address[] memory whitelist) external;
function blacklistAdmins(address[] memory blacklist) external;
function updateFeeDistributor(address newFeeDistributor) external;
function updateProtocolFeeBPS(uint16 newProtocolFeeBPS) external;
function updateMaxTwapDelta(uint24 newMaxTwapDelta) external;
function updateTwapDuration(uint32 newTwapDuration) external;
function updateLPToken(address newLPToken) external;
function updateOperationsCollector(address newOperations) external;
function multiSwapForWETH(
IERC20[] memory tokens,
uint256[] memory amounts,
address[] memory routers,
bytes[] memory swapPayloads
) external;
function swapForWETH(
IERC20 token,
uint256 amount,
address router,
bytes memory swapPayload
) external;
function disperseProtocolFees(
uint256 amount,
address router,
bytes memory swapPayload
) external;
}
// SPDX-License-Identifier: MIT
pragma solidity >=0.8.0;
interface IManagerProxy {
// ======= EXTERNAL FUNCTIONS =======
function fundVaultBalance(address vault) external payable;
}
// SPDX-License-Identifier: MIT
pragma solidity 0.8.7;
/**
* @dev Contract module which provides a basic access control mechanism, where
* there is an account (an owner) that can be granted exclusive access to
* specific functions.
*
* By default, the owner account will be the one that deploys the contract. This
* can later be changed with {transferOwnership}.
*
* This module is used through inheritance. It will make available the modifier
* `onlyowner`, which can be applied to your functions to restrict their use to
* the owner.
*/
/// @dev DO NOT ADD STATE VARIABLES
/// @dev DO NOT ADD BASE CONTRACTS WITH STATE VARS
abstract contract OwnableUninitialized {
address internal _owner;
event OwnershipTransferred(
address indexed previousowner,
address indexed newowner
);
/**
* @dev Throws if called by any account other than the owner.
*/
modifier onlyOwner() {
require(owner() == msg.sender, "Ownable: caller is not the owner");
_;
}
/**
* @dev Leaves the contract without owner. It will not be possible to call
* `onlyowner` functions anymore. Can only be called by the current owner.
*
* NOTE: Renouncing ownership will leave the contract without an owner,
* thereby removing any functionality that is only available to the owner.
*/
function renounceOwnership() public virtual onlyOwner {
emit OwnershipTransferred(_owner, address(0));
_owner = address(0);
}
/**
* @dev Transfers ownership of the contract to a new account (`newOwner`).
* Can only be called by the current owner.
*/
function transferOwnership(address newOwner) public virtual onlyOwner {
require(
newOwner != address(0),
"Ownable: new owner is the zero address"
);
emit OwnershipTransferred(_owner, newOwner);
_owner = newOwner;
}
/**
* @dev Returns the address of the current owner.
*/
function owner() public view virtual returns (address) {
return _owner;
}
}
|
solhint-disable-next-line function-max-lines
|
function disperseProtocolFees(
uint256 amount,
address router,
bytes memory swapPayload
) external override onlyAdmins {
_checkTwap();
IArrakisVaultV1 _lpToken = lpToken;
IERC20 token0 = _lpToken.token0();
IERC20 token1 = _lpToken.token1();
uint256 balanceBefore;
uint256 balanceAfter;
bool isToken0 = address(token0) == _weth;
if (isToken0) {
balanceBefore = token1.balanceOf(address(this));
_swap(token0, amount, router, swapPayload);
balanceAfter = token1.balanceOf(address(this));
balanceBefore = token0.balanceOf(address(this));
_swap(token1, amount, router, swapPayload);
balanceAfter = token0.balanceOf(address(this));
}
require(
balanceBefore < balanceAfter,
"FeeTreasury: did not swap for valid output token"
);
uint256 wethBalance = IERC20(_weth).balanceOf(address(this));
uint256 protocolWeth = (wethBalance * protocolFeeBPS) / 10000;
if (wethBalance > protocolWeth) {
IERC20(_weth).safeTransfer(
operationsCollector,
wethBalance - protocolWeth
);
}
(uint256 deposit0, uint256 deposit1, uint256 mint) = _lpToken
.getMintAmounts(
isToken0 ? protocolWeth : balanceAfter - balanceBefore,
isToken0 ? balanceAfter - balanceBefore : protocolWeth
);
token0.safeIncreaseAllowance(address(_lpToken), deposit0);
token1.safeIncreaseAllowance(address(_lpToken), deposit1);
_lpToken.mint(mint, address(this));
uint256 lpBalance = IERC20(address(_lpToken)).balanceOf(address(this));
IERC20(address(_lpToken)).safeIncreaseAllowance(
feeDistributor,
lpBalance
);
IFeeDistributor(feeDistributor).setReward(lpBalance);
emit DisperseProtocolFees(deposit0, deposit1, lpBalance);
}
| 1,667,888 |
pragma solidity ^0.5.16;
import "./CToken.sol";
/**
* @title Compound's CErc20 Contract
* @notice CTokens which wrap an EIP-20 underlying
* @author Compound
*/
contract CErc20 is CToken, CErc20Interface {
/**
* @notice Initialize the new money market
* @param underlying_ The address of the underlying asset
* @param comptroller_ The address of the Comptroller
* @param interestRateModel_ The address of the interest rate model
* @param initialExchangeRateMantissa_ The initial exchange rate, scaled by 1e18
* @param name_ ERC-20 name of this token
* @param symbol_ ERC-20 symbol of this token
* @param decimals_ ERC-20 decimal precision of this token
*/
function initialize(address underlying_,
ComptrollerInterface comptroller_,
InterestRateModel interestRateModel_,
uint initialExchangeRateMantissa_,
string memory name_,
string memory symbol_,
uint8 decimals_) public {
// CToken initialize does the bulk of the work
super.initialize(comptroller_, interestRateModel_, initialExchangeRateMantissa_, name_, symbol_, decimals_);
// Set underlying and sanity check it
underlying = underlying_;
EIP20Interface(underlying).totalSupply();
}
/*** User Interface ***/
/**
* @notice Sender supplies assets into the market and receives cTokens in exchange
* @dev Accrues interest whether or not the operation succeeds, unless reverted
* @param mintAmount The amount of the underlying asset to supply
* @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details)
*/
function mint(uint mintAmount) external returns (uint) {
(uint err,) = mintInternal(mintAmount);
return err;
}
/**
* @notice Sender redeems cTokens in exchange for the underlying asset
* @dev Accrues interest whether or not the operation succeeds, unless reverted
* @param redeemTokens The number of cTokens to redeem into underlying
* @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details)
*/
function redeem(uint redeemTokens) external returns (uint) {
return redeemInternal(redeemTokens);
}
/**
* @notice Sender redeems cTokens in exchange for a specified amount of underlying asset
* @dev Accrues interest whether or not the operation succeeds, unless reverted
* @param redeemAmount The amount of underlying to redeem
* @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details)
*/
function redeemUnderlying(uint redeemAmount) external returns (uint) {
return redeemUnderlyingInternal(redeemAmount);
}
/**
* @notice Sender borrows assets from the protocol to their own address
* @param borrowAmount The amount of the underlying asset to borrow
* @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details)
*/
function borrow(uint borrowAmount) external returns (uint) {
return borrowInternal(borrowAmount);
}
/**
* @notice Sender repays their own borrow
* @param repayAmount The amount to repay
* @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details)
*/
function repayBorrow(uint repayAmount) external returns (uint) {
(uint err,) = repayBorrowInternal(repayAmount);
return err;
}
/**
* @notice Sender repays a borrow belonging to borrower
* @param borrower the account with the debt being payed off
* @param repayAmount The amount to repay
* @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details)
*/
function repayBorrowBehalf(address borrower, uint repayAmount) external returns (uint) {
(uint err,) = repayBorrowBehalfInternal(borrower, repayAmount);
return err;
}
/**
* @notice The sender liquidates the borrowers collateral.
* The collateral seized is transferred to the liquidator.
* @param borrower The borrower of this cToken to be liquidated
* @param repayAmount The amount of the underlying borrowed asset to repay
* @param cTokenCollateral The market in which to seize collateral from the borrower
* @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details)
*/
function liquidateBorrow(address borrower, uint repayAmount, CTokenInterface cTokenCollateral) external returns (uint) {
(uint err,) = liquidateBorrowInternal(borrower, repayAmount, cTokenCollateral);
return err;
}
/**
* @notice The sender adds to reserves.
* @param addAmount The amount fo underlying token to add as reserves
* @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details)
*/
function _addReserves(uint addAmount) external returns (uint) {
return _addReservesInternal(addAmount);
}
/*** Safe Token ***/
/**
* @notice Gets balance of this contract in terms of the underlying
* @dev This excludes the value of the current message, if any
* @return The quantity of underlying tokens owned by this contract
*/
function getCashPrior() internal view returns (uint) {
EIP20Interface token = EIP20Interface(underlying);
return token.balanceOf(address(this));
}
/**
* @dev Similar to EIP20 transfer, except it handles a False result from `transferFrom` and reverts in that case.
* This will revert due to insufficient balance or insufficient allowance.
* This function returns the actual amount received,
* which may be less than `amount` if there is a fee attached to the transfer.
*
* Note: This wrapper safely handles non-standard ERC-20 tokens that do not return a value.
* See here: https://medium.com/coinmonks/missing-return-value-bug-at-least-130-tokens-affected-d67bf08521ca
*/
function doTransferIn(address from, uint amount) internal returns (uint) {
EIP20NonStandardInterface token = EIP20NonStandardInterface(underlying);
uint balanceBefore = EIP20Interface(underlying).balanceOf(address(this));
token.transferFrom(from, address(this), amount);
bool success;
assembly {
switch returndatasize()
case 0 { // This is a non-standard ERC-20
success := not(0) // set success to true
}
case 32 { // This is a compliant ERC-20
returndatacopy(0, 0, 32)
success := mload(0) // Set `success = returndata` of external call
}
default { // This is an excessively non-compliant ERC-20, revert.
revert(0, 0)
}
}
require(success, "TOKEN_TRANSFER_IN_FAILED");
// Calculate the amount that was *actually* transferred
uint balanceAfter = EIP20Interface(underlying).balanceOf(address(this));
return sub_(balanceAfter, balanceBefore);
}
/**
* @dev Similar to EIP20 transfer, except it handles a False success from `transfer` and returns an explanatory
* error code rather than reverting. If caller has not called checked protocol's balance, this may revert due to
* insufficient cash held in this contract. If caller has checked protocol's balance prior to this call, and verified
* it is >= amount, this should not revert in normal conditions.
*
* Note: This wrapper safely handles non-standard ERC-20 tokens that do not return a value.
* See here: https://medium.com/coinmonks/missing-return-value-bug-at-least-130-tokens-affected-d67bf08521ca
*/
function doTransferOut(address payable to, uint amount) internal {
EIP20NonStandardInterface token = EIP20NonStandardInterface(underlying);
token.transfer(to, amount);
bool success;
assembly {
switch returndatasize()
case 0 { // This is a non-standard ERC-20
success := not(0) // set success to true
}
case 32 { // This is a complaint ERC-20
returndatacopy(0, 0, 32)
success := mload(0) // Set `success = returndata` of external call
}
default { // This is an excessively non-compliant ERC-20, revert.
revert(0, 0)
}
}
require(success, "TOKEN_TRANSFER_OUT_FAILED");
}
/**
* @notice Transfer `tokens` tokens from `src` to `dst` by `spender`
* @dev Called by both `transfer` and `transferFrom` internally
* @param spender The address of the account performing the transfer
* @param src The address of the source account
* @param dst The address of the destination account
* @param tokens The number of tokens to transfer
* @return Whether or not the transfer succeeded
*/
function transferTokens(address spender, address src, address dst, uint tokens) internal returns (uint) {
/* Fail if transfer not allowed */
uint allowed = comptroller.transferAllowed(address(this), src, dst, tokens);
if (allowed != 0) {
return failOpaque(Error.COMPTROLLER_REJECTION, FailureInfo.TRANSFER_COMPTROLLER_REJECTION, allowed);
}
/* Do not allow self-transfers */
if (src == dst) {
return fail(Error.BAD_INPUT, FailureInfo.TRANSFER_NOT_ALLOWED);
}
/* Get the allowance, infinite for the account owner */
uint startingAllowance = 0;
if (spender == src) {
startingAllowance = uint(-1);
} else {
startingAllowance = transferAllowances[src][spender];
}
/* Do the calculations, checking for {under,over}flow */
accountTokens[src] = sub_(accountTokens[src], tokens);
accountTokens[dst] = add_(accountTokens[dst], tokens);
/* Eat some of the allowance (if necessary) */
if (startingAllowance != uint(-1)) {
transferAllowances[src][spender] = sub_(startingAllowance, tokens);
}
/* We emit a Transfer event */
emit Transfer(src, dst, tokens);
// unused function
// comptroller.transferVerify(address(this), src, dst, tokens);
return uint(Error.NO_ERROR);
}
/**
* @notice Get the account's cToken balances
* @param account The address of the account
*/
function getCTokenBalanceInternal(address account) internal view returns (uint) {
return accountTokens[account];
}
struct MintLocalVars {
uint exchangeRateMantissa;
uint mintTokens;
uint actualMintAmount;
}
/**
* @notice User supplies assets into the market and receives cTokens in exchange
* @dev Assumes interest has already been accrued up to the current block
* @param minter The address of the account which is supplying the assets
* @param mintAmount The amount of the underlying asset to supply
* @return (uint, uint) An error code (0=success, otherwise a failure, see ErrorReporter.sol), and the actual mint amount.
*/
function mintFresh(address minter, uint mintAmount) internal returns (uint, uint) {
/* Fail if mint not allowed */
uint allowed = comptroller.mintAllowed(address(this), minter, mintAmount);
if (allowed != 0) {
return (failOpaque(Error.COMPTROLLER_REJECTION, FailureInfo.MINT_COMPTROLLER_REJECTION, allowed), 0);
}
/*
* Return if mintAmount is zero.
* Put behind `mintAllowed` for accuring potential COMP rewards.
*/
if (mintAmount == 0) {
return (uint(Error.NO_ERROR), 0);
}
/* Verify market's block number equals current block number */
if (accrualBlockNumber != getBlockNumber()) {
return (fail(Error.MARKET_NOT_FRESH, FailureInfo.MINT_FRESHNESS_CHECK), 0);
}
MintLocalVars memory vars;
vars.exchangeRateMantissa = exchangeRateStoredInternal();
/////////////////////////
// EFFECTS & INTERACTIONS
// (No safe failures beyond this point)
/*
* We call `doTransferIn` for the minter and the mintAmount.
* Note: The cToken must handle variations between ERC-20 and ETH underlying.
* `doTransferIn` reverts if anything goes wrong, since we can't be sure if
* side-effects occurred. The function returns the amount actually transferred,
* in case of a fee. On success, the cToken holds an additional `actualMintAmount`
* of cash.
*/
vars.actualMintAmount = doTransferIn(minter, mintAmount);
/*
* We get the current exchange rate and calculate the number of cTokens to be minted:
* mintTokens = actualMintAmount / exchangeRate
*/
vars.mintTokens = div_ScalarByExpTruncate(vars.actualMintAmount, Exp({mantissa: vars.exchangeRateMantissa}));
/*
* We calculate the new total supply of cTokens and minter token balance, checking for overflow:
* totalSupply = totalSupply + mintTokens
* accountTokens[minter] = accountTokens[minter] + mintTokens
*/
totalSupply = add_(totalSupply, vars.mintTokens);
accountTokens[minter] = add_(accountTokens[minter], vars.mintTokens);
/* We emit a Mint event, and a Transfer event */
emit Mint(minter, vars.actualMintAmount, vars.mintTokens);
emit Transfer(address(this), minter, vars.mintTokens);
/* We call the defense hook */
// unused function
// comptroller.mintVerify(address(this), minter, vars.actualMintAmount, vars.mintTokens);
return (uint(Error.NO_ERROR), vars.actualMintAmount);
}
struct RedeemLocalVars {
uint exchangeRateMantissa;
uint redeemTokens;
uint redeemAmount;
uint totalSupplyNew;
uint accountTokensNew;
}
/**
* @notice User redeems cTokens in exchange for the underlying asset
* @dev Assumes interest has already been accrued up to the current block. Only one of redeemTokensIn or redeemAmountIn may be non-zero and it would do nothing if both are zero.
* @param redeemer The address of the account which is redeeming the tokens
* @param redeemTokensIn The number of cTokens to redeem into underlying
* @param redeemAmountIn The number of underlying tokens to receive from redeeming cTokens
* @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details)
*/
function redeemFresh(address payable redeemer, uint redeemTokensIn, uint redeemAmountIn) internal returns (uint) {
require(redeemTokensIn == 0 || redeemAmountIn == 0, "one of redeemTokensIn or redeemAmountIn must be zero");
RedeemLocalVars memory vars;
/* exchangeRate = invoke Exchange Rate Stored() */
vars.exchangeRateMantissa = exchangeRateStoredInternal();
/* If redeemTokensIn > 0: */
if (redeemTokensIn > 0) {
/*
* We calculate the exchange rate and the amount of underlying to be redeemed:
* redeemTokens = redeemTokensIn
* redeemAmount = redeemTokensIn x exchangeRateCurrent
*/
vars.redeemTokens = redeemTokensIn;
vars.redeemAmount = mul_ScalarTruncate(Exp({mantissa: vars.exchangeRateMantissa}), redeemTokensIn);
} else {
/*
* We get the current exchange rate and calculate the amount to be redeemed:
* redeemTokens = redeemAmountIn / exchangeRate
* redeemAmount = redeemAmountIn
*/
vars.redeemTokens = div_ScalarByExpTruncate(redeemAmountIn, Exp({mantissa: vars.exchangeRateMantissa}));
vars.redeemAmount = redeemAmountIn;
}
/* Fail if redeem not allowed */
uint allowed = comptroller.redeemAllowed(address(this), redeemer, vars.redeemTokens);
if (allowed != 0) {
return failOpaque(Error.COMPTROLLER_REJECTION, FailureInfo.REDEEM_COMPTROLLER_REJECTION, allowed);
}
/*
* Return if redeemTokensIn and redeemAmountIn are zero.
* Put behind `redeemAllowed` for accuring potential COMP rewards.
*/
if (redeemTokensIn == 0 && redeemAmountIn == 0) {
return uint(Error.NO_ERROR);
}
/* Verify market's block number equals current block number */
if (accrualBlockNumber != getBlockNumber()) {
return fail(Error.MARKET_NOT_FRESH, FailureInfo.REDEEM_FRESHNESS_CHECK);
}
/*
* We calculate the new total supply and redeemer balance, checking for underflow:
* totalSupplyNew = totalSupply - redeemTokens
* accountTokensNew = accountTokens[redeemer] - redeemTokens
*/
vars.totalSupplyNew = sub_(totalSupply, vars.redeemTokens);
vars.accountTokensNew = sub_(accountTokens[redeemer], vars.redeemTokens);
/* Fail gracefully if protocol has insufficient cash */
if (getCashPrior() < vars.redeemAmount) {
return fail(Error.TOKEN_INSUFFICIENT_CASH, FailureInfo.REDEEM_TRANSFER_OUT_NOT_POSSIBLE);
}
/////////////////////////
// EFFECTS & INTERACTIONS
// (No safe failures beyond this point)
/*
* We invoke doTransferOut for the redeemer and the redeemAmount.
* Note: The cToken must handle variations between ERC-20 and ETH underlying.
* On success, the cToken has redeemAmount less of cash.
* doTransferOut reverts if anything goes wrong, since we can't be sure if side effects occurred.
*/
doTransferOut(redeemer, vars.redeemAmount);
/* We write previously calculated values into storage */
totalSupply = vars.totalSupplyNew;
accountTokens[redeemer] = vars.accountTokensNew;
/* We emit a Transfer event, and a Redeem event */
emit Transfer(redeemer, address(this), vars.redeemTokens);
emit Redeem(redeemer, vars.redeemAmount, vars.redeemTokens);
/* We call the defense hook */
comptroller.redeemVerify(address(this), redeemer, vars.redeemAmount, vars.redeemTokens);
return uint(Error.NO_ERROR);
}
/**
* @notice Transfers collateral tokens (this market) to the liquidator.
* @dev Called only during an in-kind liquidation, or by liquidateBorrow during the liquidation of another CToken.
* Its absolutely critical to use msg.sender as the seizer cToken and not a parameter.
* @param seizerToken The contract seizing the collateral (i.e. borrowed cToken)
* @param liquidator The account receiving seized collateral
* @param borrower The account having collateral seized
* @param seizeTokens The number of cTokens to seize
* @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details)
*/
function seizeInternal(address seizerToken, address liquidator, address borrower, uint seizeTokens) internal returns (uint) {
/* Fail if seize not allowed */
uint allowed = comptroller.seizeAllowed(address(this), seizerToken, liquidator, borrower, seizeTokens);
if (allowed != 0) {
return failOpaque(Error.COMPTROLLER_REJECTION, FailureInfo.LIQUIDATE_SEIZE_COMPTROLLER_REJECTION, allowed);
}
/*
* Return if seizeTokens is zero.
* Put behind `seizeAllowed` for accuring potential COMP rewards.
*/
if (seizeTokens == 0) {
return uint(Error.NO_ERROR);
}
/* Fail if borrower = liquidator */
if (borrower == liquidator) {
return fail(Error.INVALID_ACCOUNT_PAIR, FailureInfo.LIQUIDATE_SEIZE_LIQUIDATOR_IS_BORROWER);
}
/*
* We calculate the new borrower and liquidator token balances, failing on underflow/overflow:
* borrowerTokensNew = accountTokens[borrower] - seizeTokens
* liquidatorTokensNew = accountTokens[liquidator] + seizeTokens
*/
accountTokens[borrower] = sub_(accountTokens[borrower], seizeTokens);
accountTokens[liquidator] = add_(accountTokens[liquidator], seizeTokens);
/* Emit a Transfer event */
emit Transfer(borrower, liquidator, seizeTokens);
/* We call the defense hook */
// unused function
// comptroller.seizeVerify(address(this), seizerToken, liquidator, borrower, seizeTokens);
return uint(Error.NO_ERROR);
}
}
pragma solidity ^0.5.16;
import "./ComptrollerInterface.sol";
import "./CTokenInterfaces.sol";
import "./ErrorReporter.sol";
import "./Exponential.sol";
import "./EIP20Interface.sol";
import "./EIP20NonStandardInterface.sol";
import "./InterestRateModel.sol";
/**
* @title Compound's CToken Contract
* @notice Abstract base for CTokens
* @author Compound
*/
contract CToken is CTokenInterface, Exponential, TokenErrorReporter {
/**
* @notice Initialize the money market
* @param comptroller_ The address of the Comptroller
* @param interestRateModel_ The address of the interest rate model
* @param initialExchangeRateMantissa_ The initial exchange rate, scaled by 1e18
* @param name_ EIP-20 name of this token
* @param symbol_ EIP-20 symbol of this token
* @param decimals_ EIP-20 decimal precision of this token
*/
function initialize(ComptrollerInterface comptroller_,
InterestRateModel interestRateModel_,
uint initialExchangeRateMantissa_,
string memory name_,
string memory symbol_,
uint8 decimals_) public {
require(msg.sender == admin, "only admin may initialize the market");
require(accrualBlockNumber == 0 && borrowIndex == 0, "market may only be initialized once");
// Set initial exchange rate
initialExchangeRateMantissa = initialExchangeRateMantissa_;
require(initialExchangeRateMantissa > 0, "initial exchange rate must be greater than zero.");
// Set the comptroller
uint err = _setComptroller(comptroller_);
require(err == uint(Error.NO_ERROR), "setting comptroller failed");
// Initialize block number and borrow index (block number mocks depend on comptroller being set)
accrualBlockNumber = getBlockNumber();
borrowIndex = mantissaOne;
// Set the interest rate model (depends on block number / borrow index)
err = _setInterestRateModelFresh(interestRateModel_);
require(err == uint(Error.NO_ERROR), "setting interest rate model failed");
name = name_;
symbol = symbol_;
decimals = decimals_;
// The counter starts true to prevent changing it from zero to non-zero (i.e. smaller cost/refund)
_notEntered = true;
}
/**
* @notice Transfer `amount` tokens from `msg.sender` to `dst`
* @param dst The address of the destination account
* @param amount The number of tokens to transfer
* @return Whether or not the transfer succeeded
*/
function transfer(address dst, uint256 amount) external nonReentrant returns (bool) {
return transferTokens(msg.sender, msg.sender, dst, amount) == uint(Error.NO_ERROR);
}
/**
* @notice Transfer `amount` tokens from `src` to `dst`
* @param src The address of the source account
* @param dst The address of the destination account
* @param amount The number of tokens to transfer
* @return Whether or not the transfer succeeded
*/
function transferFrom(address src, address dst, uint256 amount) external nonReentrant returns (bool) {
return transferTokens(msg.sender, src, dst, amount) == uint(Error.NO_ERROR);
}
/**
* @notice Approve `spender` to transfer up to `amount` from `src`
* @dev This will overwrite the approval amount for `spender`
* and is subject to issues noted [here](https://eips.ethereum.org/EIPS/eip-20#approve)
* @param spender The address of the account which may transfer tokens
* @param amount The number of tokens that are approved (-1 means infinite)
* @return Whether or not the approval succeeded
*/
function approve(address spender, uint256 amount) external returns (bool) {
address src = msg.sender;
transferAllowances[src][spender] = amount;
emit Approval(src, spender, amount);
return true;
}
/**
* @notice Get the current allowance from `owner` for `spender`
* @param owner The address of the account which owns the tokens to be spent
* @param spender The address of the account which may transfer tokens
* @return The number of tokens allowed to be spent (-1 means infinite)
*/
function allowance(address owner, address spender) external view returns (uint256) {
return transferAllowances[owner][spender];
}
/**
* @notice Get the token balance of the `owner`
* @param owner The address of the account to query
* @return The number of tokens owned by `owner`
*/
function balanceOf(address owner) external view returns (uint256) {
return accountTokens[owner];
}
/**
* @notice Get the underlying balance of the `owner`
* @dev This also accrues interest in a transaction
* @param owner The address of the account to query
* @return The amount of underlying owned by `owner`
*/
function balanceOfUnderlying(address owner) external returns (uint) {
Exp memory exchangeRate = Exp({mantissa: exchangeRateCurrent()});
return mul_ScalarTruncate(exchangeRate, accountTokens[owner]);
}
/**
* @notice Get a snapshot of the account's balances, and the cached exchange rate
* @dev This is used by comptroller to more efficiently perform liquidity checks.
* @param account Address of the account to snapshot
* @return (possible error, token balance, borrow balance, exchange rate mantissa)
*/
function getAccountSnapshot(address account) external view returns (uint, uint, uint, uint) {
uint cTokenBalance = getCTokenBalanceInternal(account);
uint borrowBalance = borrowBalanceStoredInternal(account);
uint exchangeRateMantissa = exchangeRateStoredInternal();
return (uint(Error.NO_ERROR), cTokenBalance, borrowBalance, exchangeRateMantissa);
}
/**
* @dev Function to simply retrieve block number
* This exists mainly for inheriting test contracts to stub this result.
*/
function getBlockNumber() internal view returns (uint) {
return block.number;
}
/**
* @notice Returns the current per-block borrow interest rate for this cToken
* @return The borrow interest rate per block, scaled by 1e18
*/
function borrowRatePerBlock() external view returns (uint) {
return interestRateModel.getBorrowRate(getCashPrior(), totalBorrows, totalReserves);
}
/**
* @notice Returns the current per-block supply interest rate for this cToken
* @return The supply interest rate per block, scaled by 1e18
*/
function supplyRatePerBlock() external view returns (uint) {
return interestRateModel.getSupplyRate(getCashPrior(), totalBorrows, totalReserves, reserveFactorMantissa);
}
/**
* @notice Returns the estimated per-block borrow interest rate for this cToken after some change
* @return The borrow interest rate per block, scaled by 1e18
*/
function estimateBorrowRatePerBlockAfterChange(uint256 change, bool repay) external view returns (uint) {
uint256 cashPriorNew;
uint256 totalBorrowsNew;
if (repay) {
cashPriorNew = add_(getCashPrior(), change);
totalBorrowsNew = sub_(totalBorrows, change);
} else {
cashPriorNew = sub_(getCashPrior(), change);
totalBorrowsNew = add_(totalBorrows, change);
}
return interestRateModel.getBorrowRate(cashPriorNew, totalBorrowsNew, totalReserves);
}
/**
* @notice Returns the estimated per-block supply interest rate for this cToken after some change
* @return The supply interest rate per block, scaled by 1e18
*/
function estimateSupplyRatePerBlockAfterChange(uint256 change, bool repay) external view returns (uint) {
uint256 cashPriorNew;
uint256 totalBorrowsNew;
if (repay) {
cashPriorNew = add_(getCashPrior(), change);
totalBorrowsNew = sub_(totalBorrows, change);
} else {
cashPriorNew = sub_(getCashPrior(), change);
totalBorrowsNew = add_(totalBorrows, change);
}
return interestRateModel.getSupplyRate(cashPriorNew, totalBorrowsNew, totalReserves, reserveFactorMantissa);
}
/**
* @notice Returns the current total borrows plus accrued interest
* @return The total borrows with interest
*/
function totalBorrowsCurrent() external nonReentrant returns (uint) {
require(accrueInterest() == uint(Error.NO_ERROR), "accrue interest failed");
return totalBorrows;
}
/**
* @notice Accrue interest to updated borrowIndex and then calculate account's borrow balance using the updated borrowIndex
* @param account The address whose balance should be calculated after updating borrowIndex
* @return The calculated balance
*/
function borrowBalanceCurrent(address account) external nonReentrant returns (uint) {
require(accrueInterest() == uint(Error.NO_ERROR), "accrue interest failed");
return borrowBalanceStored(account);
}
/**
* @notice Return the borrow balance of account based on stored data
* @param account The address whose balance should be calculated
* @return The calculated balance
*/
function borrowBalanceStored(address account) public view returns (uint) {
return borrowBalanceStoredInternal(account);
}
/**
* @notice Return the borrow balance of account based on stored data
* @param account The address whose balance should be calculated
* @return the calculated balance or 0 if error code is non-zero
*/
function borrowBalanceStoredInternal(address account) internal view returns (uint) {
/* Get borrowBalance and borrowIndex */
BorrowSnapshot storage borrowSnapshot = accountBorrows[account];
/* If borrowBalance = 0 then borrowIndex is likely also 0.
* Rather than failing the calculation with a division by 0, we immediately return 0 in this case.
*/
if (borrowSnapshot.principal == 0) {
return 0;
}
/* Calculate new borrow balance using the interest index:
* recentBorrowBalance = borrower.borrowBalance * market.borrowIndex / borrower.borrowIndex
*/
uint principalTimesIndex = mul_(borrowSnapshot.principal, borrowIndex);
uint result = div_(principalTimesIndex, borrowSnapshot.interestIndex);
return result;
}
/**
* @notice Accrue interest then return the up-to-date exchange rate
* @return Calculated exchange rate scaled by 1e18
*/
function exchangeRateCurrent() public nonReentrant returns (uint) {
require(accrueInterest() == uint(Error.NO_ERROR), "accrue interest failed");
return exchangeRateStored();
}
/**
* @notice Calculates the exchange rate from the underlying to the CToken
* @dev This function does not accrue interest before calculating the exchange rate
* @return Calculated exchange rate scaled by 1e18
*/
function exchangeRateStored() public view returns (uint) {
return exchangeRateStoredInternal();
}
/**
* @notice Calculates the exchange rate from the underlying to the CToken
* @dev This function does not accrue interest before calculating the exchange rate
* @return calculated exchange rate scaled by 1e18
*/
function exchangeRateStoredInternal() internal view returns (uint) {
uint _totalSupply = totalSupply;
if (_totalSupply == 0) {
/*
* If there are no tokens minted:
* exchangeRate = initialExchangeRate
*/
return initialExchangeRateMantissa;
} else {
/*
* Otherwise:
* exchangeRate = (totalCash + totalBorrows - totalReserves) / totalSupply
*/
uint totalCash = getCashPrior();
uint cashPlusBorrowsMinusReserves = sub_(add_(totalCash, totalBorrows), totalReserves);
uint exchangeRate = div_(cashPlusBorrowsMinusReserves, Exp({mantissa: _totalSupply}));
return exchangeRate;
}
}
/**
* @notice Get cash balance of this cToken in the underlying asset
* @return The quantity of underlying asset owned by this contract
*/
function getCash() external view returns (uint) {
return getCashPrior();
}
/**
* @notice Applies accrued interest to total borrows and reserves
* @dev This calculates interest accrued from the last checkpointed block
* up to the current block and writes new checkpoint to storage.
*/
function accrueInterest() public returns (uint) {
/* Remember the initial block number */
uint currentBlockNumber = getBlockNumber();
uint accrualBlockNumberPrior = accrualBlockNumber;
/* Short-circuit accumulating 0 interest */
if (accrualBlockNumberPrior == currentBlockNumber) {
return uint(Error.NO_ERROR);
}
/* Read the previous values out of storage */
uint cashPrior = getCashPrior();
uint borrowsPrior = totalBorrows;
uint reservesPrior = totalReserves;
uint borrowIndexPrior = borrowIndex;
/* Calculate the current borrow interest rate */
uint borrowRateMantissa = interestRateModel.getBorrowRate(cashPrior, borrowsPrior, reservesPrior);
require(borrowRateMantissa <= borrowRateMaxMantissa, "borrow rate is absurdly high");
/* Calculate the number of blocks elapsed since the last accrual */
uint blockDelta = sub_(currentBlockNumber, accrualBlockNumberPrior);
/*
* Calculate the interest accumulated into borrows and reserves and the new index:
* simpleInterestFactor = borrowRate * blockDelta
* interestAccumulated = simpleInterestFactor * totalBorrows
* totalBorrowsNew = interestAccumulated + totalBorrows
* totalReservesNew = interestAccumulated * reserveFactor + totalReserves
* borrowIndexNew = simpleInterestFactor * borrowIndex + borrowIndex
*/
Exp memory simpleInterestFactor = mul_(Exp({mantissa: borrowRateMantissa}), blockDelta);
uint interestAccumulated = mul_ScalarTruncate(simpleInterestFactor, borrowsPrior);
uint totalBorrowsNew = add_(interestAccumulated, borrowsPrior);
uint totalReservesNew = mul_ScalarTruncateAddUInt(Exp({mantissa: reserveFactorMantissa}), interestAccumulated, reservesPrior);
uint borrowIndexNew = mul_ScalarTruncateAddUInt(simpleInterestFactor, borrowIndexPrior, borrowIndexPrior);
/////////////////////////
// EFFECTS & INTERACTIONS
// (No safe failures beyond this point)
/* We write the previously calculated values into storage */
accrualBlockNumber = currentBlockNumber;
borrowIndex = borrowIndexNew;
totalBorrows = totalBorrowsNew;
totalReserves = totalReservesNew;
/* We emit an AccrueInterest event */
emit AccrueInterest(cashPrior, interestAccumulated, borrowIndexNew, totalBorrowsNew);
return uint(Error.NO_ERROR);
}
/**
* @notice Sender supplies assets into the market and receives cTokens in exchange
* @dev Accrues interest whether or not the operation succeeds, unless reverted
* @param mintAmount The amount of the underlying asset to supply
* @return (uint, uint) An error code (0=success, otherwise a failure, see ErrorReporter.sol), and the actual mint amount.
*/
function mintInternal(uint mintAmount) internal nonReentrant returns (uint, uint) {
uint error = accrueInterest();
if (error != uint(Error.NO_ERROR)) {
// accrueInterest emits logs on errors, but we still want to log the fact that an attempted borrow failed
return (fail(Error(error), FailureInfo.MINT_ACCRUE_INTEREST_FAILED), 0);
}
// mintFresh emits the actual Mint event if successful and logs on errors, so we don't need to
return mintFresh(msg.sender, mintAmount);
}
/**
* @notice Sender redeems cTokens in exchange for the underlying asset
* @dev Accrues interest whether or not the operation succeeds, unless reverted
* @param redeemTokens The number of cTokens to redeem into underlying
* @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details)
*/
function redeemInternal(uint redeemTokens) internal nonReentrant returns (uint) {
uint error = accrueInterest();
if (error != uint(Error.NO_ERROR)) {
// accrueInterest emits logs on errors, but we still want to log the fact that an attempted redeem failed
return fail(Error(error), FailureInfo.REDEEM_ACCRUE_INTEREST_FAILED);
}
// redeemFresh emits redeem-specific logs on errors, so we don't need to
return redeemFresh(msg.sender, redeemTokens, 0);
}
/**
* @notice Sender redeems cTokens in exchange for a specified amount of underlying asset
* @dev Accrues interest whether or not the operation succeeds, unless reverted
* @param redeemAmount The amount of underlying to receive from redeeming cTokens
* @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details)
*/
function redeemUnderlyingInternal(uint redeemAmount) internal nonReentrant returns (uint) {
uint error = accrueInterest();
if (error != uint(Error.NO_ERROR)) {
// accrueInterest emits logs on errors, but we still want to log the fact that an attempted redeem failed
return fail(Error(error), FailureInfo.REDEEM_ACCRUE_INTEREST_FAILED);
}
// redeemFresh emits redeem-specific logs on errors, so we don't need to
return redeemFresh(msg.sender, 0, redeemAmount);
}
/**
* @notice Sender borrows assets from the protocol to their own address
* @param borrowAmount The amount of the underlying asset to borrow
* @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details)
*/
function borrowInternal(uint borrowAmount) internal nonReentrant returns (uint) {
uint error = accrueInterest();
if (error != uint(Error.NO_ERROR)) {
// accrueInterest emits logs on errors, but we still want to log the fact that an attempted borrow failed
return fail(Error(error), FailureInfo.BORROW_ACCRUE_INTEREST_FAILED);
}
// borrowFresh emits borrow-specific logs on errors, so we don't need to
return borrowFresh(msg.sender, borrowAmount);
}
struct BorrowLocalVars {
MathError mathErr;
uint accountBorrows;
uint accountBorrowsNew;
uint totalBorrowsNew;
}
/**
* @notice Users borrow assets from the protocol to their own address
* @param borrowAmount The amount of the underlying asset to borrow
* @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details)
*/
function borrowFresh(address payable borrower, uint borrowAmount) internal returns (uint) {
/* Fail if borrow not allowed */
uint allowed = comptroller.borrowAllowed(address(this), borrower, borrowAmount);
if (allowed != 0) {
return failOpaque(Error.COMPTROLLER_REJECTION, FailureInfo.BORROW_COMPTROLLER_REJECTION, allowed);
}
/*
* Return if borrowAmount is zero.
* Put behind `borrowAllowed` for accuring potential COMP rewards.
*/
if (borrowAmount == 0) {
accountBorrows[borrower].interestIndex = borrowIndex;
return uint(Error.NO_ERROR);
}
/* Verify market's block number equals current block number */
if (accrualBlockNumber != getBlockNumber()) {
return fail(Error.MARKET_NOT_FRESH, FailureInfo.BORROW_FRESHNESS_CHECK);
}
/* Fail gracefully if protocol has insufficient underlying cash */
if (getCashPrior() < borrowAmount) {
return fail(Error.TOKEN_INSUFFICIENT_CASH, FailureInfo.BORROW_CASH_NOT_AVAILABLE);
}
BorrowLocalVars memory vars;
/*
* We calculate the new borrower and total borrow balances, failing on overflow:
* accountBorrowsNew = accountBorrows + borrowAmount
* totalBorrowsNew = totalBorrows + borrowAmount
*/
vars.accountBorrows = borrowBalanceStoredInternal(borrower);
vars.accountBorrowsNew = add_(vars.accountBorrows, borrowAmount);
vars.totalBorrowsNew = add_(totalBorrows, borrowAmount);
/////////////////////////
// EFFECTS & INTERACTIONS
// (No safe failures beyond this point)
/*
* We invoke doTransferOut for the borrower and the borrowAmount.
* Note: The cToken must handle variations between ERC-20 and ETH underlying.
* On success, the cToken borrowAmount less of cash.
* doTransferOut reverts if anything goes wrong, since we can't be sure if side effects occurred.
*/
doTransferOut(borrower, borrowAmount);
/* We write the previously calculated values into storage */
accountBorrows[borrower].principal = vars.accountBorrowsNew;
accountBorrows[borrower].interestIndex = borrowIndex;
totalBorrows = vars.totalBorrowsNew;
/* We emit a Borrow event */
emit Borrow(borrower, borrowAmount, vars.accountBorrowsNew, vars.totalBorrowsNew);
/* We call the defense hook */
// unused function
// comptroller.borrowVerify(address(this), borrower, borrowAmount);
return uint(Error.NO_ERROR);
}
/**
* @notice Sender repays their own borrow
* @param repayAmount The amount to repay
* @return (uint, uint) An error code (0=success, otherwise a failure, see ErrorReporter.sol), and the actual repayment amount.
*/
function repayBorrowInternal(uint repayAmount) internal nonReentrant returns (uint, uint) {
uint error = accrueInterest();
if (error != uint(Error.NO_ERROR)) {
// accrueInterest emits logs on errors, but we still want to log the fact that an attempted borrow failed
return (fail(Error(error), FailureInfo.REPAY_BORROW_ACCRUE_INTEREST_FAILED), 0);
}
// repayBorrowFresh emits repay-borrow-specific logs on errors, so we don't need to
return repayBorrowFresh(msg.sender, msg.sender, repayAmount);
}
/**
* @notice Sender repays a borrow belonging to borrower
* @param borrower the account with the debt being payed off
* @param repayAmount The amount to repay
* @return (uint, uint) An error code (0=success, otherwise a failure, see ErrorReporter.sol), and the actual repayment amount.
*/
function repayBorrowBehalfInternal(address borrower, uint repayAmount) internal nonReentrant returns (uint, uint) {
uint error = accrueInterest();
if (error != uint(Error.NO_ERROR)) {
// accrueInterest emits logs on errors, but we still want to log the fact that an attempted borrow failed
return (fail(Error(error), FailureInfo.REPAY_BEHALF_ACCRUE_INTEREST_FAILED), 0);
}
// repayBorrowFresh emits repay-borrow-specific logs on errors, so we don't need to
return repayBorrowFresh(msg.sender, borrower, repayAmount);
}
struct RepayBorrowLocalVars {
Error err;
MathError mathErr;
uint repayAmount;
uint borrowerIndex;
uint accountBorrows;
uint accountBorrowsNew;
uint totalBorrowsNew;
uint actualRepayAmount;
}
/**
* @notice Borrows are repaid by another user (possibly the borrower).
* @param payer the account paying off the borrow
* @param borrower the account with the debt being payed off
* @param repayAmount the amount of undelrying tokens being returned
* @return (uint, uint) An error code (0=success, otherwise a failure, see ErrorReporter.sol), and the actual repayment amount.
*/
function repayBorrowFresh(address payer, address borrower, uint repayAmount) internal returns (uint, uint) {
/* Fail if repayBorrow not allowed */
uint allowed = comptroller.repayBorrowAllowed(address(this), payer, borrower, repayAmount);
if (allowed != 0) {
return (failOpaque(Error.COMPTROLLER_REJECTION, FailureInfo.REPAY_BORROW_COMPTROLLER_REJECTION, allowed), 0);
}
/*
* Return if repayAmount is zero.
* Put behind `repayBorrowAllowed` for accuring potential COMP rewards.
*/
if (repayAmount == 0) {
accountBorrows[borrower].interestIndex = borrowIndex;
return (uint(Error.NO_ERROR), 0);
}
/* Verify market's block number equals current block number */
if (accrualBlockNumber != getBlockNumber()) {
return (fail(Error.MARKET_NOT_FRESH, FailureInfo.REPAY_BORROW_FRESHNESS_CHECK), 0);
}
RepayBorrowLocalVars memory vars;
/* We remember the original borrowerIndex for verification purposes */
vars.borrowerIndex = accountBorrows[borrower].interestIndex;
/* We fetch the amount the borrower owes, with accumulated interest */
vars.accountBorrows = borrowBalanceStoredInternal(borrower);
/* If repayAmount == -1, repayAmount = accountBorrows */
if (repayAmount == uint(-1)) {
vars.repayAmount = vars.accountBorrows;
} else {
vars.repayAmount = repayAmount;
}
/////////////////////////
// EFFECTS & INTERACTIONS
// (No safe failures beyond this point)
/*
* We call doTransferIn for the payer and the repayAmount
* Note: The cToken must handle variations between ERC-20 and ETH underlying.
* On success, the cToken holds an additional repayAmount of cash.
* doTransferIn reverts if anything goes wrong, since we can't be sure if side effects occurred.
* it returns the amount actually transferred, in case of a fee.
*/
vars.actualRepayAmount = doTransferIn(payer, vars.repayAmount);
/*
* We calculate the new borrower and total borrow balances, failing on underflow:
* accountBorrowsNew = accountBorrows - actualRepayAmount
* totalBorrowsNew = totalBorrows - actualRepayAmount
*/
vars.accountBorrowsNew = sub_(vars.accountBorrows, vars.actualRepayAmount);
vars.totalBorrowsNew = sub_(totalBorrows, vars.actualRepayAmount);
/* We write the previously calculated values into storage */
accountBorrows[borrower].principal = vars.accountBorrowsNew;
accountBorrows[borrower].interestIndex = borrowIndex;
totalBorrows = vars.totalBorrowsNew;
/* We emit a RepayBorrow event */
emit RepayBorrow(payer, borrower, vars.actualRepayAmount, vars.accountBorrowsNew, vars.totalBorrowsNew);
/* We call the defense hook */
// unused function
// comptroller.repayBorrowVerify(address(this), payer, borrower, vars.actualRepayAmount, vars.borrowerIndex);
return (uint(Error.NO_ERROR), vars.actualRepayAmount);
}
/**
* @notice The sender liquidates the borrowers collateral.
* The collateral seized is transferred to the liquidator.
* @param borrower The borrower of this cToken to be liquidated
* @param cTokenCollateral The market in which to seize collateral from the borrower
* @param repayAmount The amount of the underlying borrowed asset to repay
* @return (uint, uint) An error code (0=success, otherwise a failure, see ErrorReporter.sol), and the actual repayment amount.
*/
function liquidateBorrowInternal(address borrower, uint repayAmount, CTokenInterface cTokenCollateral) internal nonReentrant returns (uint, uint) {
uint error = accrueInterest();
if (error != uint(Error.NO_ERROR)) {
// accrueInterest emits logs on errors, but we still want to log the fact that an attempted liquidation failed
return (fail(Error(error), FailureInfo.LIQUIDATE_ACCRUE_BORROW_INTEREST_FAILED), 0);
}
error = cTokenCollateral.accrueInterest();
if (error != uint(Error.NO_ERROR)) {
// accrueInterest emits logs on errors, but we still want to log the fact that an attempted liquidation failed
return (fail(Error(error), FailureInfo.LIQUIDATE_ACCRUE_COLLATERAL_INTEREST_FAILED), 0);
}
// liquidateBorrowFresh emits borrow-specific logs on errors, so we don't need to
return liquidateBorrowFresh(msg.sender, borrower, repayAmount, cTokenCollateral);
}
/**
* @notice The liquidator liquidates the borrowers collateral.
* The collateral seized is transferred to the liquidator.
* @param borrower The borrower of this cToken to be liquidated
* @param liquidator The address repaying the borrow and seizing collateral
* @param cTokenCollateral The market in which to seize collateral from the borrower
* @param repayAmount The amount of the underlying borrowed asset to repay
* @return (uint, uint) An error code (0=success, otherwise a failure, see ErrorReporter.sol), and the actual repayment amount.
*/
function liquidateBorrowFresh(address liquidator, address borrower, uint repayAmount, CTokenInterface cTokenCollateral) internal returns (uint, uint) {
/* Fail if liquidate not allowed */
uint allowed = comptroller.liquidateBorrowAllowed(address(this), address(cTokenCollateral), liquidator, borrower, repayAmount);
if (allowed != 0) {
return (failOpaque(Error.COMPTROLLER_REJECTION, FailureInfo.LIQUIDATE_COMPTROLLER_REJECTION, allowed), 0);
}
/* Verify market's block number equals current block number */
if (accrualBlockNumber != getBlockNumber()) {
return (fail(Error.MARKET_NOT_FRESH, FailureInfo.LIQUIDATE_FRESHNESS_CHECK), 0);
}
/* Verify cTokenCollateral market's block number equals current block number */
if (cTokenCollateral.accrualBlockNumber() != getBlockNumber()) {
return (fail(Error.MARKET_NOT_FRESH, FailureInfo.LIQUIDATE_COLLATERAL_FRESHNESS_CHECK), 0);
}
/* Fail if borrower = liquidator */
if (borrower == liquidator) {
return (fail(Error.INVALID_ACCOUNT_PAIR, FailureInfo.LIQUIDATE_LIQUIDATOR_IS_BORROWER), 0);
}
/* Fail if repayAmount = 0 */
if (repayAmount == 0) {
return (fail(Error.INVALID_CLOSE_AMOUNT_REQUESTED, FailureInfo.LIQUIDATE_CLOSE_AMOUNT_IS_ZERO), 0);
}
/* Fail if repayAmount = -1 */
if (repayAmount == uint(-1)) {
return (fail(Error.INVALID_CLOSE_AMOUNT_REQUESTED, FailureInfo.LIQUIDATE_CLOSE_AMOUNT_IS_UINT_MAX), 0);
}
/* Fail if repayBorrow fails */
(uint repayBorrowError, uint actualRepayAmount) = repayBorrowFresh(liquidator, borrower, repayAmount);
if (repayBorrowError != uint(Error.NO_ERROR)) {
return (fail(Error(repayBorrowError), FailureInfo.LIQUIDATE_REPAY_BORROW_FRESH_FAILED), 0);
}
/////////////////////////
// EFFECTS & INTERACTIONS
// (No safe failures beyond this point)
/* We calculate the number of collateral tokens that will be seized */
(uint amountSeizeError, uint seizeTokens) = comptroller.liquidateCalculateSeizeTokens(address(this), address(cTokenCollateral), actualRepayAmount);
require(amountSeizeError == uint(Error.NO_ERROR), "LIQUIDATE_COMPTROLLER_CALCULATE_AMOUNT_SEIZE_FAILED");
/* Revert if borrower collateral token balance < seizeTokens */
require(cTokenCollateral.balanceOf(borrower) >= seizeTokens, "LIQUIDATE_SEIZE_TOO_MUCH");
// If this is also the collateral, run seizeInternal to avoid re-entrancy, otherwise make an external call
uint seizeError;
if (address(cTokenCollateral) == address(this)) {
seizeError = seizeInternal(address(this), liquidator, borrower, seizeTokens);
} else {
seizeError = cTokenCollateral.seize(liquidator, borrower, seizeTokens);
}
/* Revert if seize tokens fails (since we cannot be sure of side effects) */
require(seizeError == uint(Error.NO_ERROR), "token seizure failed");
/* We emit a LiquidateBorrow event */
emit LiquidateBorrow(liquidator, borrower, actualRepayAmount, address(cTokenCollateral), seizeTokens);
/* We call the defense hook */
// unused function
// comptroller.liquidateBorrowVerify(address(this), address(cTokenCollateral), liquidator, borrower, actualRepayAmount, seizeTokens);
return (uint(Error.NO_ERROR), actualRepayAmount);
}
/**
* @notice Transfers collateral tokens (this market) to the liquidator.
* @dev Will fail unless called by another cToken during the process of liquidation.
* Its absolutely critical to use msg.sender as the borrowed cToken and not a parameter.
* @param liquidator The account receiving seized collateral
* @param borrower The account having collateral seized
* @param seizeTokens The number of cTokens to seize
* @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details)
*/
function seize(address liquidator, address borrower, uint seizeTokens) external nonReentrant returns (uint) {
return seizeInternal(msg.sender, liquidator, borrower, seizeTokens);
}
/*** Admin Functions ***/
/**
* @notice Begins transfer of admin rights. The newPendingAdmin must call `_acceptAdmin` to finalize the transfer.
* @dev Admin function to begin change of admin. The newPendingAdmin must call `_acceptAdmin` to finalize the transfer.
* @param newPendingAdmin New pending admin.
* @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details)
*/
function _setPendingAdmin(address payable newPendingAdmin) external returns (uint) {
// Check caller = admin
if (msg.sender != admin) {
return fail(Error.UNAUTHORIZED, FailureInfo.SET_PENDING_ADMIN_OWNER_CHECK);
}
// Save current value, if any, for inclusion in log
address oldPendingAdmin = pendingAdmin;
// Store pendingAdmin with value newPendingAdmin
pendingAdmin = newPendingAdmin;
// Emit NewPendingAdmin(oldPendingAdmin, newPendingAdmin)
emit NewPendingAdmin(oldPendingAdmin, newPendingAdmin);
return uint(Error.NO_ERROR);
}
/**
* @notice Accepts transfer of admin rights. msg.sender must be pendingAdmin
* @dev Admin function for pending admin to accept role and update admin
* @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details)
*/
function _acceptAdmin() external returns (uint) {
// Check caller is pendingAdmin and pendingAdmin ≠ address(0)
if (msg.sender != pendingAdmin || msg.sender == address(0)) {
return fail(Error.UNAUTHORIZED, FailureInfo.ACCEPT_ADMIN_PENDING_ADMIN_CHECK);
}
// Save current values for inclusion in log
address oldAdmin = admin;
address oldPendingAdmin = pendingAdmin;
// Store admin with value pendingAdmin
admin = pendingAdmin;
// Clear the pending value
pendingAdmin = address(0);
emit NewAdmin(oldAdmin, admin);
emit NewPendingAdmin(oldPendingAdmin, pendingAdmin);
return uint(Error.NO_ERROR);
}
/**
* @notice Sets a new comptroller for the market
* @dev Admin function to set a new comptroller
* @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details)
*/
function _setComptroller(ComptrollerInterface newComptroller) public returns (uint) {
// Check caller is admin
if (msg.sender != admin) {
return fail(Error.UNAUTHORIZED, FailureInfo.SET_COMPTROLLER_OWNER_CHECK);
}
ComptrollerInterface oldComptroller = comptroller;
// Ensure invoke comptroller.isComptroller() returns true
require(newComptroller.isComptroller(), "marker method returned false");
// Set market's comptroller to newComptroller
comptroller = newComptroller;
// Emit NewComptroller(oldComptroller, newComptroller)
emit NewComptroller(oldComptroller, newComptroller);
return uint(Error.NO_ERROR);
}
/**
* @notice accrues interest and sets a new reserve factor for the protocol using _setReserveFactorFresh
* @dev Admin function to accrue interest and set a new reserve factor
* @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details)
*/
function _setReserveFactor(uint newReserveFactorMantissa) external nonReentrant returns (uint) {
uint error = accrueInterest();
if (error != uint(Error.NO_ERROR)) {
// accrueInterest emits logs on errors, but on top of that we want to log the fact that an attempted reserve factor change failed.
return fail(Error(error), FailureInfo.SET_RESERVE_FACTOR_ACCRUE_INTEREST_FAILED);
}
// _setReserveFactorFresh emits reserve-factor-specific logs on errors, so we don't need to.
return _setReserveFactorFresh(newReserveFactorMantissa);
}
/**
* @notice Sets a new reserve factor for the protocol (*requires fresh interest accrual)
* @dev Admin function to set a new reserve factor
* @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details)
*/
function _setReserveFactorFresh(uint newReserveFactorMantissa) internal returns (uint) {
// Check caller is admin
if (msg.sender != admin) {
return fail(Error.UNAUTHORIZED, FailureInfo.SET_RESERVE_FACTOR_ADMIN_CHECK);
}
// Verify market's block number equals current block number
if (accrualBlockNumber != getBlockNumber()) {
return fail(Error.MARKET_NOT_FRESH, FailureInfo.SET_RESERVE_FACTOR_FRESH_CHECK);
}
// Check newReserveFactor ≤ maxReserveFactor
if (newReserveFactorMantissa > reserveFactorMaxMantissa) {
return fail(Error.BAD_INPUT, FailureInfo.SET_RESERVE_FACTOR_BOUNDS_CHECK);
}
uint oldReserveFactorMantissa = reserveFactorMantissa;
reserveFactorMantissa = newReserveFactorMantissa;
emit NewReserveFactor(oldReserveFactorMantissa, newReserveFactorMantissa);
return uint(Error.NO_ERROR);
}
/**
* @notice Accrues interest and reduces reserves by transferring from msg.sender
* @param addAmount Amount of addition to reserves
* @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details)
*/
function _addReservesInternal(uint addAmount) internal nonReentrant returns (uint) {
uint error = accrueInterest();
if (error != uint(Error.NO_ERROR)) {
// accrueInterest emits logs on errors, but on top of that we want to log the fact that an attempted reduce reserves failed.
return fail(Error(error), FailureInfo.ADD_RESERVES_ACCRUE_INTEREST_FAILED);
}
// _addReservesFresh emits reserve-addition-specific logs on errors, so we don't need to.
(error, ) = _addReservesFresh(addAmount);
return error;
}
/**
* @notice Add reserves by transferring from caller
* @dev Requires fresh interest accrual
* @param addAmount Amount of addition to reserves
* @return (uint, uint) An error code (0=success, otherwise a failure (see ErrorReporter.sol for details)) and the actual amount added, net token fees
*/
function _addReservesFresh(uint addAmount) internal returns (uint, uint) {
// totalReserves + actualAddAmount
uint totalReservesNew;
uint actualAddAmount;
// We fail gracefully unless market's block number equals current block number
if (accrualBlockNumber != getBlockNumber()) {
return (fail(Error.MARKET_NOT_FRESH, FailureInfo.ADD_RESERVES_FRESH_CHECK), actualAddAmount);
}
/////////////////////////
// EFFECTS & INTERACTIONS
// (No safe failures beyond this point)
/*
* We call doTransferIn for the caller and the addAmount
* Note: The cToken must handle variations between ERC-20 and ETH underlying.
* On success, the cToken holds an additional addAmount of cash.
* doTransferIn reverts if anything goes wrong, since we can't be sure if side effects occurred.
* it returns the amount actually transferred, in case of a fee.
*/
actualAddAmount = doTransferIn(msg.sender, addAmount);
totalReservesNew = add_(totalReserves, actualAddAmount);
// Store reserves[n+1] = reserves[n] + actualAddAmount
totalReserves = totalReservesNew;
/* Emit NewReserves(admin, actualAddAmount, reserves[n+1]) */
emit ReservesAdded(msg.sender, actualAddAmount, totalReservesNew);
/* Return (NO_ERROR, actualAddAmount) */
return (uint(Error.NO_ERROR), actualAddAmount);
}
/**
* @notice Accrues interest and reduces reserves by transferring to admin
* @param reduceAmount Amount of reduction to reserves
* @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details)
*/
function _reduceReserves(uint reduceAmount) external nonReentrant returns (uint) {
uint error = accrueInterest();
if (error != uint(Error.NO_ERROR)) {
// accrueInterest emits logs on errors, but on top of that we want to log the fact that an attempted reduce reserves failed.
return fail(Error(error), FailureInfo.REDUCE_RESERVES_ACCRUE_INTEREST_FAILED);
}
// _reduceReservesFresh emits reserve-reduction-specific logs on errors, so we don't need to.
return _reduceReservesFresh(reduceAmount);
}
/**
* @notice Reduces reserves by transferring to admin
* @dev Requires fresh interest accrual
* @param reduceAmount Amount of reduction to reserves
* @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details)
*/
function _reduceReservesFresh(uint reduceAmount) internal returns (uint) {
// totalReserves - reduceAmount
uint totalReservesNew;
// Check caller is admin
if (msg.sender != admin) {
return fail(Error.UNAUTHORIZED, FailureInfo.REDUCE_RESERVES_ADMIN_CHECK);
}
// We fail gracefully unless market's block number equals current block number
if (accrualBlockNumber != getBlockNumber()) {
return fail(Error.MARKET_NOT_FRESH, FailureInfo.REDUCE_RESERVES_FRESH_CHECK);
}
// Fail gracefully if protocol has insufficient underlying cash
if (getCashPrior() < reduceAmount) {
return fail(Error.TOKEN_INSUFFICIENT_CASH, FailureInfo.REDUCE_RESERVES_CASH_NOT_AVAILABLE);
}
// Check reduceAmount ≤ reserves[n] (totalReserves)
if (reduceAmount > totalReserves) {
return fail(Error.BAD_INPUT, FailureInfo.REDUCE_RESERVES_VALIDATION);
}
/////////////////////////
// EFFECTS & INTERACTIONS
// (No safe failures beyond this point)
totalReservesNew = sub_(totalReserves, reduceAmount);
// Store reserves[n+1] = reserves[n] - reduceAmount
totalReserves = totalReservesNew;
// doTransferOut reverts if anything goes wrong, since we can't be sure if side effects occurred.
doTransferOut(admin, reduceAmount);
emit ReservesReduced(admin, reduceAmount, totalReservesNew);
return uint(Error.NO_ERROR);
}
/**
* @notice accrues interest and updates the interest rate model using _setInterestRateModelFresh
* @dev Admin function to accrue interest and update the interest rate model
* @param newInterestRateModel the new interest rate model to use
* @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details)
*/
function _setInterestRateModel(InterestRateModel newInterestRateModel) public returns (uint) {
uint error = accrueInterest();
if (error != uint(Error.NO_ERROR)) {
// accrueInterest emits logs on errors, but on top of that we want to log the fact that an attempted change of interest rate model failed
return fail(Error(error), FailureInfo.SET_INTEREST_RATE_MODEL_ACCRUE_INTEREST_FAILED);
}
// _setInterestRateModelFresh emits interest-rate-model-update-specific logs on errors, so we don't need to.
return _setInterestRateModelFresh(newInterestRateModel);
}
/**
* @notice updates the interest rate model (*requires fresh interest accrual)
* @dev Admin function to update the interest rate model
* @param newInterestRateModel the new interest rate model to use
* @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details)
*/
function _setInterestRateModelFresh(InterestRateModel newInterestRateModel) internal returns (uint) {
// Used to store old model for use in the event that is emitted on success
InterestRateModel oldInterestRateModel;
// Check caller is admin
if (msg.sender != admin) {
return fail(Error.UNAUTHORIZED, FailureInfo.SET_INTEREST_RATE_MODEL_OWNER_CHECK);
}
// We fail gracefully unless market's block number equals current block number
if (accrualBlockNumber != getBlockNumber()) {
return fail(Error.MARKET_NOT_FRESH, FailureInfo.SET_INTEREST_RATE_MODEL_FRESH_CHECK);
}
// Track the market's current interest rate model
oldInterestRateModel = interestRateModel;
// Ensure invoke newInterestRateModel.isInterestRateModel() returns true
require(newInterestRateModel.isInterestRateModel(), "marker method returned false");
// Set the interest rate model to newInterestRateModel
interestRateModel = newInterestRateModel;
// Emit NewMarketInterestRateModel(oldInterestRateModel, newInterestRateModel)
emit NewMarketInterestRateModel(oldInterestRateModel, newInterestRateModel);
return uint(Error.NO_ERROR);
}
/*** Safe Token ***/
/**
* @notice Gets balance of this contract in terms of the underlying
* @dev This excludes the value of the current message, if any
* @return The quantity of underlying owned by this contract
*/
function getCashPrior() internal view returns (uint);
/**
* @dev Performs a transfer in, reverting upon failure. Returns the amount actually transferred to the protocol, in case of a fee.
* This may revert due to insufficient balance or insufficient allowance.
*/
function doTransferIn(address from, uint amount) internal returns (uint);
/**
* @dev Performs a transfer out, ideally returning an explanatory error code upon failure tather than reverting.
* If caller has not called checked protocol's balance, may revert due to insufficient cash held in the contract.
* If caller has checked protocol's balance, and verified it is >= amount, this should not revert in normal conditions.
*/
function doTransferOut(address payable to, uint amount) internal;
/**
* @notice Transfer `tokens` tokens from `src` to `dst` by `spender`
* @dev Called by both `transfer` and `transferFrom` internally
*/
function transferTokens(address spender, address src, address dst, uint tokens) internal returns (uint);
/**
* @notice Get the account's cToken balances
*/
function getCTokenBalanceInternal(address account) internal view returns (uint);
/**
* @notice User supplies assets into the market and receives cTokens in exchange
* @dev Assumes interest has already been accrued up to the current block
*/
function mintFresh(address minter, uint mintAmount) internal returns (uint, uint);
/**
* @notice User redeems cTokens in exchange for the underlying asset
* @dev Assumes interest has already been accrued up to the current block
*/
function redeemFresh(address payable redeemer, uint redeemTokensIn, uint redeemAmountIn) internal returns (uint);
/**
* @notice Transfers collateral tokens (this market) to the liquidator.
* @dev Called only during an in-kind liquidation, or by liquidateBorrow during the liquidation of another CToken.
* Its absolutely critical to use msg.sender as the seizer cToken and not a parameter.
*/
function seizeInternal(address seizerToken, address liquidator, address borrower, uint seizeTokens) internal returns (uint);
/*** Reentrancy Guard ***/
/**
* @dev Prevents a contract from calling itself, directly or indirectly.
*/
modifier nonReentrant() {
require(_notEntered, "re-entered");
_notEntered = false;
_;
_notEntered = true; // get a gas-refund post-Istanbul
}
}
pragma solidity ^0.5.16;
import "./ComptrollerInterface.sol";
import "./InterestRateModel.sol";
contract CTokenStorage {
/**
* @dev Guard variable for re-entrancy checks
*/
bool internal _notEntered;
/**
* @notice EIP-20 token name for this token
*/
string public name;
/**
* @notice EIP-20 token symbol for this token
*/
string public symbol;
/**
* @notice EIP-20 token decimals for this token
*/
uint8 public decimals;
/**
* @notice Maximum borrow rate that can ever be applied (.0005% / block)
*/
uint internal constant borrowRateMaxMantissa = 0.0005e16;
/**
* @notice Maximum fraction of interest that can be set aside for reserves
*/
uint internal constant reserveFactorMaxMantissa = 1e18;
/**
* @notice Administrator for this contract
*/
address payable public admin;
/**
* @notice Pending administrator for this contract
*/
address payable public pendingAdmin;
/**
* @notice Contract which oversees inter-cToken operations
*/
ComptrollerInterface public comptroller;
/**
* @notice Model which tells what the current interest rate should be
*/
InterestRateModel public interestRateModel;
/**
* @notice Initial exchange rate used when minting the first CTokens (used when totalSupply = 0)
*/
uint internal initialExchangeRateMantissa;
/**
* @notice Fraction of interest currently set aside for reserves
*/
uint public reserveFactorMantissa;
/**
* @notice Block number that interest was last accrued at
*/
uint public accrualBlockNumber;
/**
* @notice Accumulator of the total earned interest rate since the opening of the market
*/
uint public borrowIndex;
/**
* @notice Total amount of outstanding borrows of the underlying in this market
*/
uint public totalBorrows;
/**
* @notice Total amount of reserves of the underlying held in this market
*/
uint public totalReserves;
/**
* @notice Total number of tokens in circulation
*/
uint public totalSupply;
/**
* @notice Official record of token balances for each account
*/
mapping (address => uint) internal accountTokens;
/**
* @notice Approved token transfer amounts on behalf of others
*/
mapping (address => mapping (address => uint)) internal transferAllowances;
/**
* @notice Container for borrow balance information
* @member principal Total balance (with accrued interest), after applying the most recent balance-changing action
* @member interestIndex Global borrowIndex as of the most recent balance-changing action
*/
struct BorrowSnapshot {
uint principal;
uint interestIndex;
}
/**
* @notice Mapping of account addresses to outstanding borrow balances
*/
mapping(address => BorrowSnapshot) internal accountBorrows;
}
contract CErc20Storage {
/**
* @notice Underlying asset for this CToken
*/
address public underlying;
/**
* @notice Implementation address for this contract
*/
address public implementation;
}
contract CSupplyCapStorage {
/**
* @notice Internal cash counter for this CToken. Should equal underlying.balanceOf(address(this)) for CERC20.
*/
uint256 public internalCash;
}
contract CCollateralCapStorage {
/**
* @notice Total number of tokens used as collateral in circulation.
*/
uint256 public totalCollateralTokens;
/**
* @notice Record of token balances which could be treated as collateral for each account.
* If collateral cap is not set, the value should be equal to accountTokens.
*/
mapping (address => uint) public accountCollateralTokens;
/**
* @notice Check if accountCollateralTokens have been initialized.
*/
mapping (address => bool) public isCollateralTokenInit;
/**
* @notice Collateral cap for this CToken, zero for no cap.
*/
uint256 public collateralCap;
}
/*** Interface ***/
contract CTokenInterface is CTokenStorage {
/**
* @notice Indicator that this is a CToken contract (for inspection)
*/
bool public constant isCToken = true;
/*** Market Events ***/
/**
* @notice Event emitted when interest is accrued
*/
event AccrueInterest(uint cashPrior, uint interestAccumulated, uint borrowIndex, uint totalBorrows);
/**
* @notice Event emitted when tokens are minted
*/
event Mint(address minter, uint mintAmount, uint mintTokens);
/**
* @notice Event emitted when tokens are redeemed
*/
event Redeem(address redeemer, uint redeemAmount, uint redeemTokens);
/**
* @notice Event emitted when underlying is borrowed
*/
event Borrow(address borrower, uint borrowAmount, uint accountBorrows, uint totalBorrows);
/**
* @notice Event emitted when a borrow is repaid
*/
event RepayBorrow(address payer, address borrower, uint repayAmount, uint accountBorrows, uint totalBorrows);
/**
* @notice Event emitted when a borrow is liquidated
*/
event LiquidateBorrow(address liquidator, address borrower, uint repayAmount, address cTokenCollateral, uint seizeTokens);
/*** Admin Events ***/
/**
* @notice Event emitted when pendingAdmin is changed
*/
event NewPendingAdmin(address oldPendingAdmin, address newPendingAdmin);
/**
* @notice Event emitted when pendingAdmin is accepted, which means admin is updated
*/
event NewAdmin(address oldAdmin, address newAdmin);
/**
* @notice Event emitted when comptroller is changed
*/
event NewComptroller(ComptrollerInterface oldComptroller, ComptrollerInterface newComptroller);
/**
* @notice Event emitted when interestRateModel is changed
*/
event NewMarketInterestRateModel(InterestRateModel oldInterestRateModel, InterestRateModel newInterestRateModel);
/**
* @notice Event emitted when the reserve factor is changed
*/
event NewReserveFactor(uint oldReserveFactorMantissa, uint newReserveFactorMantissa);
/**
* @notice Event emitted when the reserves are added
*/
event ReservesAdded(address benefactor, uint addAmount, uint newTotalReserves);
/**
* @notice Event emitted when the reserves are reduced
*/
event ReservesReduced(address admin, uint reduceAmount, uint newTotalReserves);
/**
* @notice EIP20 Transfer event
*/
event Transfer(address indexed from, address indexed to, uint amount);
/**
* @notice EIP20 Approval event
*/
event Approval(address indexed owner, address indexed spender, uint amount);
/**
* @notice Failure event
*/
event Failure(uint error, uint info, uint detail);
/*** User Interface ***/
function transfer(address dst, uint amount) external returns (bool);
function transferFrom(address src, address dst, uint amount) external returns (bool);
function approve(address spender, uint amount) external returns (bool);
function allowance(address owner, address spender) external view returns (uint);
function balanceOf(address owner) external view returns (uint);
function balanceOfUnderlying(address owner) external returns (uint);
function getAccountSnapshot(address account) external view returns (uint, uint, uint, uint);
function borrowRatePerBlock() external view returns (uint);
function supplyRatePerBlock() external view returns (uint);
function totalBorrowsCurrent() external returns (uint);
function borrowBalanceCurrent(address account) external returns (uint);
function borrowBalanceStored(address account) public view returns (uint);
function exchangeRateCurrent() public returns (uint);
function exchangeRateStored() public view returns (uint);
function getCash() external view returns (uint);
function accrueInterest() public returns (uint);
function seize(address liquidator, address borrower, uint seizeTokens) external returns (uint);
/*** Admin Functions ***/
function _setPendingAdmin(address payable newPendingAdmin) external returns (uint);
function _acceptAdmin() external returns (uint);
function _setComptroller(ComptrollerInterface newComptroller) public returns (uint);
function _setReserveFactor(uint newReserveFactorMantissa) external returns (uint);
function _reduceReserves(uint reduceAmount) external returns (uint);
function _setInterestRateModel(InterestRateModel newInterestRateModel) public returns (uint);
}
contract CErc20Interface is CErc20Storage {
/*** User Interface ***/
function mint(uint mintAmount) external returns (uint);
function redeem(uint redeemTokens) external returns (uint);
function redeemUnderlying(uint redeemAmount) external returns (uint);
function borrow(uint borrowAmount) external returns (uint);
function repayBorrow(uint repayAmount) external returns (uint);
function repayBorrowBehalf(address borrower, uint repayAmount) external returns (uint);
function liquidateBorrow(address borrower, uint repayAmount, CTokenInterface cTokenCollateral) external returns (uint);
/*** Admin Functions ***/
function _addReserves(uint addAmount) external returns (uint);
}
contract CCapableErc20Interface is CErc20Interface, CSupplyCapStorage {
/**
* @notice Flash loan fee ratio
*/
uint public constant flashFeeBips = 3;
/*** Market Events ***/
/**
* @notice Event emitted when a flashloan occured
*/
event Flashloan(address indexed receiver, uint amount, uint totalFee, uint reservesFee);
/*** User Interface ***/
function gulp() external;
function flashLoan(address receiver, uint amount, bytes calldata params) external;
}
contract CCollateralCapErc20Interface is CCapableErc20Interface, CCollateralCapStorage {
/*** Admin Events ***/
/**
* @notice Event emitted when collateral cap is set
*/
event NewCollateralCap(address token, uint newCap);
/**
* @notice Event emitted when user collateral is changed
*/
event UserCollateralChanged(address account, uint newCollateralTokens);
/*** User Interface ***/
function registerCollateral(address account) external returns (uint);
function unregisterCollateral(address account) external;
/*** Admin Functions ***/
function _setCollateralCap(uint newCollateralCap) external;
}
contract CDelegatorInterface {
/**
* @notice Emitted when implementation is changed
*/
event NewImplementation(address oldImplementation, address newImplementation);
/**
* @notice Called by the admin to update the implementation of the delegator
* @param implementation_ The address of the new implementation for delegation
* @param allowResign Flag to indicate whether to call _resignImplementation on the old implementation
* @param becomeImplementationData The encoded bytes data to be passed to _becomeImplementation
*/
function _setImplementation(address implementation_, bool allowResign, bytes memory becomeImplementationData) public;
}
contract CDelegateInterface {
/**
* @notice Called by the delegator on a delegate to initialize it for duty
* @dev Should revert if any issues arise which make it unfit for delegation
* @param data The encoded bytes data for any initialization
*/
function _becomeImplementation(bytes memory data) public;
/**
* @notice Called by the delegator on a delegate to forfeit its responsibility
*/
function _resignImplementation() public;
}
/*** External interface ***/
/**
* @title Flash loan receiver interface
*/
interface IFlashloanReceiver {
function executeOperation(address sender, address underlying, uint amount, uint fee, bytes calldata params) external;
}
pragma solidity ^0.5.16;
/**
* @title Careful Math
* @author Compound
* @notice Derived from OpenZeppelin's SafeMath library
* https://github.com/OpenZeppelin/openzeppelin-solidity/blob/master/contracts/math/SafeMath.sol
*/
contract CarefulMath {
/**
* @dev Possible error codes that we can return
*/
enum MathError {
NO_ERROR,
DIVISION_BY_ZERO,
INTEGER_OVERFLOW,
INTEGER_UNDERFLOW
}
/**
* @dev Multiplies two numbers, returns an error on overflow.
*/
function mulUInt(uint a, uint b) internal pure returns (MathError, uint) {
if (a == 0) {
return (MathError.NO_ERROR, 0);
}
uint c = a * b;
if (c / a != b) {
return (MathError.INTEGER_OVERFLOW, 0);
} else {
return (MathError.NO_ERROR, c);
}
}
/**
* @dev Integer division of two numbers, truncating the quotient.
*/
function divUInt(uint a, uint b) internal pure returns (MathError, uint) {
if (b == 0) {
return (MathError.DIVISION_BY_ZERO, 0);
}
return (MathError.NO_ERROR, a / b);
}
/**
* @dev Subtracts two numbers, returns an error on overflow (i.e. if subtrahend is greater than minuend).
*/
function subUInt(uint a, uint b) internal pure returns (MathError, uint) {
if (b <= a) {
return (MathError.NO_ERROR, a - b);
} else {
return (MathError.INTEGER_UNDERFLOW, 0);
}
}
/**
* @dev Adds two numbers, returns an error on overflow.
*/
function addUInt(uint a, uint b) internal pure returns (MathError, uint) {
uint c = a + b;
if (c >= a) {
return (MathError.NO_ERROR, c);
} else {
return (MathError.INTEGER_OVERFLOW, 0);
}
}
/**
* @dev add a and b and then subtract c
*/
function addThenSubUInt(uint a, uint b, uint c) internal pure returns (MathError, uint) {
(MathError err0, uint sum) = addUInt(a, b);
if (err0 != MathError.NO_ERROR) {
return (err0, 0);
}
return subUInt(sum, c);
}
}
pragma solidity ^0.5.16;
contract ComptrollerInterface {
/// @notice Indicator that this is a Comptroller contract (for inspection)
bool public constant isComptroller = true;
/*** Assets You Are In ***/
function enterMarkets(address[] calldata cTokens) external returns (uint[] memory);
function exitMarket(address cToken) external returns (uint);
/*** Policy Hooks ***/
function mintAllowed(address cToken, address minter, uint mintAmount) external returns (uint);
function mintVerify(address cToken, address minter, uint mintAmount, uint mintTokens) external;
function redeemAllowed(address cToken, address redeemer, uint redeemTokens) external returns (uint);
function redeemVerify(address cToken, address redeemer, uint redeemAmount, uint redeemTokens) external;
function borrowAllowed(address cToken, address borrower, uint borrowAmount) external returns (uint);
function borrowVerify(address cToken, address borrower, uint borrowAmount) external;
function repayBorrowAllowed(
address cToken,
address payer,
address borrower,
uint repayAmount) external returns (uint);
function repayBorrowVerify(
address cToken,
address payer,
address borrower,
uint repayAmount,
uint borrowerIndex) external;
function liquidateBorrowAllowed(
address cTokenBorrowed,
address cTokenCollateral,
address liquidator,
address borrower,
uint repayAmount) external returns (uint);
function liquidateBorrowVerify(
address cTokenBorrowed,
address cTokenCollateral,
address liquidator,
address borrower,
uint repayAmount,
uint seizeTokens) external;
function seizeAllowed(
address cTokenCollateral,
address cTokenBorrowed,
address liquidator,
address borrower,
uint seizeTokens) external returns (uint);
function seizeVerify(
address cTokenCollateral,
address cTokenBorrowed,
address liquidator,
address borrower,
uint seizeTokens) external;
function transferAllowed(address cToken, address src, address dst, uint transferTokens) external returns (uint);
function transferVerify(address cToken, address src, address dst, uint transferTokens) external;
/*** Liquidity/Liquidation Calculations ***/
function liquidateCalculateSeizeTokens(
address cTokenBorrowed,
address cTokenCollateral,
uint repayAmount) external view returns (uint, uint);
}
pragma solidity ^0.5.16;
/**
* @title ERC 20 Token Standard Interface
* https://eips.ethereum.org/EIPS/eip-20
*/
interface EIP20Interface {
function name() external view returns (string memory);
function symbol() external view returns (string memory);
function decimals() external view returns (uint8);
/**
* @notice Get the total number of tokens in circulation
* @return The supply of tokens
*/
function totalSupply() external view returns (uint256);
/**
* @notice Gets the balance of the specified address
* @param owner The address from which the balance will be retrieved
* @return The balance
*/
function balanceOf(address owner) external view returns (uint256 balance);
/**
* @notice Transfer `amount` tokens from `msg.sender` to `dst`
* @param dst The address of the destination account
* @param amount The number of tokens to transfer
* @return Whether or not the transfer succeeded
*/
function transfer(address dst, uint256 amount) external returns (bool success);
/**
* @notice Transfer `amount` tokens from `src` to `dst`
* @param src The address of the source account
* @param dst The address of the destination account
* @param amount The number of tokens to transfer
* @return Whether or not the transfer succeeded
*/
function transferFrom(address src, address dst, uint256 amount) external returns (bool success);
/**
* @notice Approve `spender` to transfer up to `amount` from `src`
* @dev This will overwrite the approval amount for `spender`
* and is subject to issues noted [here](https://eips.ethereum.org/EIPS/eip-20#approve)
* @param spender The address of the account which may transfer tokens
* @param amount The number of tokens that are approved (-1 means infinite)
* @return Whether or not the approval succeeded
*/
function approve(address spender, uint256 amount) external returns (bool success);
/**
* @notice Get the current allowance from `owner` for `spender`
* @param owner The address of the account which owns the tokens to be spent
* @param spender The address of the account which may transfer tokens
* @return The number of tokens allowed to be spent (-1 means infinite)
*/
function allowance(address owner, address spender) external view returns (uint256 remaining);
event Transfer(address indexed from, address indexed to, uint256 amount);
event Approval(address indexed owner, address indexed spender, uint256 amount);
}
pragma solidity ^0.5.16;
/**
* @title EIP20NonStandardInterface
* @dev Version of ERC20 with no return values for `transfer` and `transferFrom`
* See https://medium.com/coinmonks/missing-return-value-bug-at-least-130-tokens-affected-d67bf08521ca
*/
interface EIP20NonStandardInterface {
/**
* @notice Get the total number of tokens in circulation
* @return The supply of tokens
*/
function totalSupply() external view returns (uint256);
/**
* @notice Gets the balance of the specified address
* @param owner The address from which the balance will be retrieved
* @return The balance
*/
function balanceOf(address owner) external view returns (uint256 balance);
///
/// !!!!!!!!!!!!!!
/// !!! NOTICE !!! `transfer` does not return a value, in violation of the ERC-20 specification
/// !!!!!!!!!!!!!!
///
/**
* @notice Transfer `amount` tokens from `msg.sender` to `dst`
* @param dst The address of the destination account
* @param amount The number of tokens to transfer
*/
function transfer(address dst, uint256 amount) external;
///
/// !!!!!!!!!!!!!!
/// !!! NOTICE !!! `transferFrom` does not return a value, in violation of the ERC-20 specification
/// !!!!!!!!!!!!!!
///
/**
* @notice Transfer `amount` tokens from `src` to `dst`
* @param src The address of the source account
* @param dst The address of the destination account
* @param amount The number of tokens to transfer
*/
function transferFrom(address src, address dst, uint256 amount) external;
/**
* @notice Approve `spender` to transfer up to `amount` from `src`
* @dev This will overwrite the approval amount for `spender`
* and is subject to issues noted [here](https://eips.ethereum.org/EIPS/eip-20#approve)
* @param spender The address of the account which may transfer tokens
* @param amount The number of tokens that are approved
* @return Whether or not the approval succeeded
*/
function approve(address spender, uint256 amount) external returns (bool success);
/**
* @notice Get the current allowance from `owner` for `spender`
* @param owner The address of the account which owns the tokens to be spent
* @param spender The address of the account which may transfer tokens
* @return The number of tokens allowed to be spent
*/
function allowance(address owner, address spender) external view returns (uint256 remaining);
event Transfer(address indexed from, address indexed to, uint256 amount);
event Approval(address indexed owner, address indexed spender, uint256 amount);
}
pragma solidity ^0.5.16;
contract ComptrollerErrorReporter {
enum Error {
NO_ERROR,
UNAUTHORIZED,
COMPTROLLER_MISMATCH,
INSUFFICIENT_SHORTFALL,
INSUFFICIENT_LIQUIDITY,
INVALID_CLOSE_FACTOR,
INVALID_COLLATERAL_FACTOR,
INVALID_LIQUIDATION_INCENTIVE,
MARKET_NOT_ENTERED, // no longer possible
MARKET_NOT_LISTED,
MARKET_ALREADY_LISTED,
MATH_ERROR,
NONZERO_BORROW_BALANCE,
PRICE_ERROR,
REJECTION,
SNAPSHOT_ERROR,
TOO_MANY_ASSETS,
TOO_MUCH_REPAY
}
enum FailureInfo {
ACCEPT_ADMIN_PENDING_ADMIN_CHECK,
ACCEPT_PENDING_IMPLEMENTATION_ADDRESS_CHECK,
EXIT_MARKET_BALANCE_OWED,
EXIT_MARKET_REJECTION,
SET_CLOSE_FACTOR_OWNER_CHECK,
SET_CLOSE_FACTOR_VALIDATION,
SET_COLLATERAL_FACTOR_OWNER_CHECK,
SET_COLLATERAL_FACTOR_NO_EXISTS,
SET_COLLATERAL_FACTOR_VALIDATION,
SET_COLLATERAL_FACTOR_WITHOUT_PRICE,
SET_IMPLEMENTATION_OWNER_CHECK,
SET_LIQUIDATION_INCENTIVE_OWNER_CHECK,
SET_LIQUIDATION_INCENTIVE_VALIDATION,
SET_MAX_ASSETS_OWNER_CHECK,
SET_PENDING_ADMIN_OWNER_CHECK,
SET_PENDING_IMPLEMENTATION_OWNER_CHECK,
SET_PRICE_ORACLE_OWNER_CHECK,
SUPPORT_MARKET_EXISTS,
SUPPORT_MARKET_OWNER_CHECK,
SET_PAUSE_GUARDIAN_OWNER_CHECK
}
/**
* @dev `error` corresponds to enum Error; `info` corresponds to enum FailureInfo, and `detail` is an arbitrary
* contract-specific code that enables us to report opaque error codes from upgradeable contracts.
**/
event Failure(uint error, uint info, uint detail);
/**
* @dev use this when reporting a known error from the money market or a non-upgradeable collaborator
*/
function fail(Error err, FailureInfo info) internal returns (uint) {
emit Failure(uint(err), uint(info), 0);
return uint(err);
}
/**
* @dev use this when reporting an opaque error from an upgradeable collaborator contract
*/
function failOpaque(Error err, FailureInfo info, uint opaqueError) internal returns (uint) {
emit Failure(uint(err), uint(info), opaqueError);
return uint(err);
}
}
contract TokenErrorReporter {
enum Error {
NO_ERROR,
UNAUTHORIZED,
BAD_INPUT,
COMPTROLLER_REJECTION,
COMPTROLLER_CALCULATION_ERROR,
INTEREST_RATE_MODEL_ERROR,
INVALID_ACCOUNT_PAIR,
INVALID_CLOSE_AMOUNT_REQUESTED,
INVALID_COLLATERAL_FACTOR,
MATH_ERROR,
MARKET_NOT_FRESH,
MARKET_NOT_LISTED,
TOKEN_INSUFFICIENT_ALLOWANCE,
TOKEN_INSUFFICIENT_BALANCE,
TOKEN_INSUFFICIENT_CASH,
TOKEN_TRANSFER_IN_FAILED,
TOKEN_TRANSFER_OUT_FAILED
}
/*
* Note: FailureInfo (but not Error) is kept in alphabetical order
* This is because FailureInfo grows significantly faster, and
* the order of Error has some meaning, while the order of FailureInfo
* is entirely arbitrary.
*/
enum FailureInfo {
ACCEPT_ADMIN_PENDING_ADMIN_CHECK,
ACCRUE_INTEREST_BORROW_RATE_CALCULATION_FAILED,
BORROW_ACCRUE_INTEREST_FAILED,
BORROW_CASH_NOT_AVAILABLE,
BORROW_FRESHNESS_CHECK,
BORROW_MARKET_NOT_LISTED,
BORROW_COMPTROLLER_REJECTION,
LIQUIDATE_ACCRUE_BORROW_INTEREST_FAILED,
LIQUIDATE_ACCRUE_COLLATERAL_INTEREST_FAILED,
LIQUIDATE_COLLATERAL_FRESHNESS_CHECK,
LIQUIDATE_COMPTROLLER_REJECTION,
LIQUIDATE_COMPTROLLER_CALCULATE_AMOUNT_SEIZE_FAILED,
LIQUIDATE_CLOSE_AMOUNT_IS_UINT_MAX,
LIQUIDATE_CLOSE_AMOUNT_IS_ZERO,
LIQUIDATE_FRESHNESS_CHECK,
LIQUIDATE_LIQUIDATOR_IS_BORROWER,
LIQUIDATE_REPAY_BORROW_FRESH_FAILED,
LIQUIDATE_SEIZE_COMPTROLLER_REJECTION,
LIQUIDATE_SEIZE_LIQUIDATOR_IS_BORROWER,
LIQUIDATE_SEIZE_TOO_MUCH,
MINT_ACCRUE_INTEREST_FAILED,
MINT_COMPTROLLER_REJECTION,
MINT_FRESHNESS_CHECK,
MINT_TRANSFER_IN_FAILED,
MINT_TRANSFER_IN_NOT_POSSIBLE,
REDEEM_ACCRUE_INTEREST_FAILED,
REDEEM_COMPTROLLER_REJECTION,
REDEEM_FRESHNESS_CHECK,
REDEEM_TRANSFER_OUT_NOT_POSSIBLE,
REDUCE_RESERVES_ACCRUE_INTEREST_FAILED,
REDUCE_RESERVES_ADMIN_CHECK,
REDUCE_RESERVES_CASH_NOT_AVAILABLE,
REDUCE_RESERVES_FRESH_CHECK,
REDUCE_RESERVES_VALIDATION,
REPAY_BEHALF_ACCRUE_INTEREST_FAILED,
REPAY_BORROW_ACCRUE_INTEREST_FAILED,
REPAY_BORROW_COMPTROLLER_REJECTION,
REPAY_BORROW_FRESHNESS_CHECK,
REPAY_BORROW_TRANSFER_IN_NOT_POSSIBLE,
SET_COLLATERAL_FACTOR_OWNER_CHECK,
SET_COLLATERAL_FACTOR_VALIDATION,
SET_COMPTROLLER_OWNER_CHECK,
SET_INTEREST_RATE_MODEL_ACCRUE_INTEREST_FAILED,
SET_INTEREST_RATE_MODEL_FRESH_CHECK,
SET_INTEREST_RATE_MODEL_OWNER_CHECK,
SET_MAX_ASSETS_OWNER_CHECK,
SET_ORACLE_MARKET_NOT_LISTED,
SET_PENDING_ADMIN_OWNER_CHECK,
SET_RESERVE_FACTOR_ACCRUE_INTEREST_FAILED,
SET_RESERVE_FACTOR_ADMIN_CHECK,
SET_RESERVE_FACTOR_FRESH_CHECK,
SET_RESERVE_FACTOR_BOUNDS_CHECK,
TRANSFER_COMPTROLLER_REJECTION,
TRANSFER_NOT_ALLOWED,
ADD_RESERVES_ACCRUE_INTEREST_FAILED,
ADD_RESERVES_FRESH_CHECK,
ADD_RESERVES_TRANSFER_IN_NOT_POSSIBLE
}
/**
* @dev `error` corresponds to enum Error; `info` corresponds to enum FailureInfo, and `detail` is an arbitrary
* contract-specific code that enables us to report opaque error codes from upgradeable contracts.
**/
event Failure(uint error, uint info, uint detail);
/**
* @dev use this when reporting a known error from the money market or a non-upgradeable collaborator
*/
function fail(Error err, FailureInfo info) internal returns (uint) {
emit Failure(uint(err), uint(info), 0);
return uint(err);
}
/**
* @dev use this when reporting an opaque error from an upgradeable collaborator contract
*/
function failOpaque(Error err, FailureInfo info, uint opaqueError) internal returns (uint) {
emit Failure(uint(err), uint(info), opaqueError);
return uint(err);
}
}
pragma solidity ^0.5.16;
import "./CarefulMath.sol";
/**
* @title Exponential module for storing fixed-precision decimals
* @author Compound
* @notice Exp is a struct which stores decimals with a fixed precision of 18 decimal places.
* Thus, if we wanted to store the 5.1, mantissa would store 5.1e18. That is:
* `Exp({mantissa: 5100000000000000000})`.
*/
contract Exponential is CarefulMath {
uint constant expScale = 1e18;
uint constant doubleScale = 1e36;
uint constant halfExpScale = expScale/2;
uint constant mantissaOne = expScale;
struct Exp {
uint mantissa;
}
struct Double {
uint mantissa;
}
/**
* @dev Creates an exponential from numerator and denominator values.
* Note: Returns an error if (`num` * 10e18) > MAX_INT,
* or if `denom` is zero.
*/
function getExp(uint num, uint denom) pure internal returns (MathError, Exp memory) {
(MathError err0, uint scaledNumerator) = mulUInt(num, expScale);
if (err0 != MathError.NO_ERROR) {
return (err0, Exp({mantissa: 0}));
}
(MathError err1, uint rational) = divUInt(scaledNumerator, denom);
if (err1 != MathError.NO_ERROR) {
return (err1, Exp({mantissa: 0}));
}
return (MathError.NO_ERROR, Exp({mantissa: rational}));
}
/**
* @dev Adds two exponentials, returning a new exponential.
*/
function addExp(Exp memory a, Exp memory b) pure internal returns (MathError, Exp memory) {
(MathError error, uint result) = addUInt(a.mantissa, b.mantissa);
return (error, Exp({mantissa: result}));
}
/**
* @dev Subtracts two exponentials, returning a new exponential.
*/
function subExp(Exp memory a, Exp memory b) pure internal returns (MathError, Exp memory) {
(MathError error, uint result) = subUInt(a.mantissa, b.mantissa);
return (error, Exp({mantissa: result}));
}
/**
* @dev Multiply an Exp by a scalar, returning a new Exp.
*/
function mulScalar(Exp memory a, uint scalar) pure internal returns (MathError, Exp memory) {
(MathError err0, uint scaledMantissa) = mulUInt(a.mantissa, scalar);
if (err0 != MathError.NO_ERROR) {
return (err0, Exp({mantissa: 0}));
}
return (MathError.NO_ERROR, Exp({mantissa: scaledMantissa}));
}
/**
* @dev Multiply an Exp by a scalar, then truncate to return an unsigned integer.
*/
function mulScalarTruncate(Exp memory a, uint scalar) pure internal returns (MathError, uint) {
(MathError err, Exp memory product) = mulScalar(a, scalar);
if (err != MathError.NO_ERROR) {
return (err, 0);
}
return (MathError.NO_ERROR, truncate(product));
}
/**
* @dev Multiply an Exp by a scalar, truncate, then add an to an unsigned integer, returning an unsigned integer.
*/
function mulScalarTruncateAddUInt(Exp memory a, uint scalar, uint addend) pure internal returns (MathError, uint) {
(MathError err, Exp memory product) = mulScalar(a, scalar);
if (err != MathError.NO_ERROR) {
return (err, 0);
}
return addUInt(truncate(product), addend);
}
/**
* @dev Multiply an Exp by a scalar, then truncate to return an unsigned integer.
*/
function mul_ScalarTruncate(Exp memory a, uint scalar) pure internal returns (uint) {
Exp memory product = mul_(a, scalar);
return truncate(product);
}
/**
* @dev Multiply an Exp by a scalar, truncate, then add an to an unsigned integer, returning an unsigned integer.
*/
function mul_ScalarTruncateAddUInt(Exp memory a, uint scalar, uint addend) pure internal returns (uint) {
Exp memory product = mul_(a, scalar);
return add_(truncate(product), addend);
}
/**
* @dev Divide an Exp by a scalar, returning a new Exp.
*/
function divScalar(Exp memory a, uint scalar) pure internal returns (MathError, Exp memory) {
(MathError err0, uint descaledMantissa) = divUInt(a.mantissa, scalar);
if (err0 != MathError.NO_ERROR) {
return (err0, Exp({mantissa: 0}));
}
return (MathError.NO_ERROR, Exp({mantissa: descaledMantissa}));
}
/**
* @dev Divide a scalar by an Exp, returning a new Exp.
*/
function divScalarByExp(uint scalar, Exp memory divisor) pure internal returns (MathError, Exp memory) {
/*
We are doing this as:
getExp(mulUInt(expScale, scalar), divisor.mantissa)
How it works:
Exp = a / b;
Scalar = s;
`s / (a / b)` = `b * s / a` and since for an Exp `a = mantissa, b = expScale`
*/
(MathError err0, uint numerator) = mulUInt(expScale, scalar);
if (err0 != MathError.NO_ERROR) {
return (err0, Exp({mantissa: 0}));
}
return getExp(numerator, divisor.mantissa);
}
/**
* @dev Divide a scalar by an Exp, then truncate to return an unsigned integer.
*/
function divScalarByExpTruncate(uint scalar, Exp memory divisor) pure internal returns (MathError, uint) {
(MathError err, Exp memory fraction) = divScalarByExp(scalar, divisor);
if (err != MathError.NO_ERROR) {
return (err, 0);
}
return (MathError.NO_ERROR, truncate(fraction));
}
/**
* @dev Divide a scalar by an Exp, returning a new Exp.
*/
function div_ScalarByExp(uint scalar, Exp memory divisor) pure internal returns (Exp memory) {
/*
We are doing this as:
getExp(mulUInt(expScale, scalar), divisor.mantissa)
How it works:
Exp = a / b;
Scalar = s;
`s / (a / b)` = `b * s / a` and since for an Exp `a = mantissa, b = expScale`
*/
uint numerator = mul_(expScale, scalar);
return Exp({mantissa: div_(numerator, divisor)});
}
/**
* @dev Divide a scalar by an Exp, then truncate to return an unsigned integer.
*/
function div_ScalarByExpTruncate(uint scalar, Exp memory divisor) pure internal returns (uint) {
Exp memory fraction = div_ScalarByExp(scalar, divisor);
return truncate(fraction);
}
/**
* @dev Multiplies two exponentials, returning a new exponential.
*/
function mulExp(Exp memory a, Exp memory b) pure internal returns (MathError, Exp memory) {
(MathError err0, uint doubleScaledProduct) = mulUInt(a.mantissa, b.mantissa);
if (err0 != MathError.NO_ERROR) {
return (err0, Exp({mantissa: 0}));
}
// We add half the scale before dividing so that we get rounding instead of truncation.
// See "Listing 6" and text above it at https://accu.org/index.php/journals/1717
// Without this change, a result like 6.6...e-19 will be truncated to 0 instead of being rounded to 1e-18.
(MathError err1, uint doubleScaledProductWithHalfScale) = addUInt(halfExpScale, doubleScaledProduct);
if (err1 != MathError.NO_ERROR) {
return (err1, Exp({mantissa: 0}));
}
(MathError err2, uint product) = divUInt(doubleScaledProductWithHalfScale, expScale);
// The only error `div` can return is MathError.DIVISION_BY_ZERO but we control `expScale` and it is not zero.
assert(err2 == MathError.NO_ERROR);
return (MathError.NO_ERROR, Exp({mantissa: product}));
}
/**
* @dev Multiplies two exponentials given their mantissas, returning a new exponential.
*/
function mulExp(uint a, uint b) pure internal returns (MathError, Exp memory) {
return mulExp(Exp({mantissa: a}), Exp({mantissa: b}));
}
/**
* @dev Multiplies three exponentials, returning a new exponential.
*/
function mulExp3(Exp memory a, Exp memory b, Exp memory c) pure internal returns (MathError, Exp memory) {
(MathError err, Exp memory ab) = mulExp(a, b);
if (err != MathError.NO_ERROR) {
return (err, ab);
}
return mulExp(ab, c);
}
/**
* @dev Divides two exponentials, returning a new exponential.
* (a/scale) / (b/scale) = (a/scale) * (scale/b) = a/b,
* which we can scale as an Exp by calling getExp(a.mantissa, b.mantissa)
*/
function divExp(Exp memory a, Exp memory b) pure internal returns (MathError, Exp memory) {
return getExp(a.mantissa, b.mantissa);
}
/**
* @dev Truncates the given exp to a whole number value.
* For example, truncate(Exp{mantissa: 15 * expScale}) = 15
*/
function truncate(Exp memory exp) pure internal returns (uint) {
// Note: We are not using careful math here as we're performing a division that cannot fail
return exp.mantissa / expScale;
}
/**
* @dev Checks if first Exp is less than second Exp.
*/
function lessThanExp(Exp memory left, Exp memory right) pure internal returns (bool) {
return left.mantissa < right.mantissa;
}
/**
* @dev Checks if left Exp <= right Exp.
*/
function lessThanOrEqualExp(Exp memory left, Exp memory right) pure internal returns (bool) {
return left.mantissa <= right.mantissa;
}
/**
* @dev returns true if Exp is exactly zero
*/
function isZeroExp(Exp memory value) pure internal returns (bool) {
return value.mantissa == 0;
}
function safe224(uint n, string memory errorMessage) pure internal returns (uint224) {
require(n < 2**224, errorMessage);
return uint224(n);
}
function safe32(uint n, string memory errorMessage) pure internal returns (uint32) {
require(n < 2**32, errorMessage);
return uint32(n);
}
function add_(Exp memory a, Exp memory b) pure internal returns (Exp memory) {
return Exp({mantissa: add_(a.mantissa, b.mantissa)});
}
function add_(Double memory a, Double memory b) pure internal returns (Double memory) {
return Double({mantissa: add_(a.mantissa, b.mantissa)});
}
function add_(uint a, uint b) pure internal returns (uint) {
return add_(a, b, "addition overflow");
}
function add_(uint a, uint b, string memory errorMessage) pure internal returns (uint) {
uint c = a + b;
require(c >= a, errorMessage);
return c;
}
function sub_(Exp memory a, Exp memory b) pure internal returns (Exp memory) {
return Exp({mantissa: sub_(a.mantissa, b.mantissa)});
}
function sub_(Double memory a, Double memory b) pure internal returns (Double memory) {
return Double({mantissa: sub_(a.mantissa, b.mantissa)});
}
function sub_(uint a, uint b) pure internal returns (uint) {
return sub_(a, b, "subtraction underflow");
}
function sub_(uint a, uint b, string memory errorMessage) pure internal returns (uint) {
require(b <= a, errorMessage);
return a - b;
}
function mul_(Exp memory a, Exp memory b) pure internal returns (Exp memory) {
return Exp({mantissa: mul_(a.mantissa, b.mantissa) / expScale});
}
function mul_(Exp memory a, uint b) pure internal returns (Exp memory) {
return Exp({mantissa: mul_(a.mantissa, b)});
}
function mul_(uint a, Exp memory b) pure internal returns (uint) {
return mul_(a, b.mantissa) / expScale;
}
function mul_(Double memory a, Double memory b) pure internal returns (Double memory) {
return Double({mantissa: mul_(a.mantissa, b.mantissa) / doubleScale});
}
function mul_(Double memory a, uint b) pure internal returns (Double memory) {
return Double({mantissa: mul_(a.mantissa, b)});
}
function mul_(uint a, Double memory b) pure internal returns (uint) {
return mul_(a, b.mantissa) / doubleScale;
}
function mul_(uint a, uint b) pure internal returns (uint) {
return mul_(a, b, "multiplication overflow");
}
function mul_(uint a, uint b, string memory errorMessage) pure internal returns (uint) {
if (a == 0 || b == 0) {
return 0;
}
uint c = a * b;
require(c / a == b, errorMessage);
return c;
}
function div_(Exp memory a, Exp memory b) pure internal returns (Exp memory) {
return Exp({mantissa: div_(mul_(a.mantissa, expScale), b.mantissa)});
}
function div_(Exp memory a, uint b) pure internal returns (Exp memory) {
return Exp({mantissa: div_(a.mantissa, b)});
}
function div_(uint a, Exp memory b) pure internal returns (uint) {
return div_(mul_(a, expScale), b.mantissa);
}
function div_(Double memory a, Double memory b) pure internal returns (Double memory) {
return Double({mantissa: div_(mul_(a.mantissa, doubleScale), b.mantissa)});
}
function div_(Double memory a, uint b) pure internal returns (Double memory) {
return Double({mantissa: div_(a.mantissa, b)});
}
function div_(uint a, Double memory b) pure internal returns (uint) {
return div_(mul_(a, doubleScale), b.mantissa);
}
function div_(uint a, uint b) pure internal returns (uint) {
return div_(a, b, "divide by zero");
}
function div_(uint a, uint b, string memory errorMessage) pure internal returns (uint) {
require(b > 0, errorMessage);
return a / b;
}
function fraction(uint a, uint b) pure internal returns (Double memory) {
return Double({mantissa: div_(mul_(a, doubleScale), b)});
}
// implementation from https://github.com/Uniswap/uniswap-lib/commit/99f3f28770640ba1bb1ff460ac7c5292fb8291a0
// original implementation: https://github.com/abdk-consulting/abdk-libraries-solidity/blob/master/ABDKMath64x64.sol#L687
function sqrt(uint x) pure internal returns (uint) {
if (x == 0) return 0;
uint xx = x;
uint r = 1;
if (xx >= 0x100000000000000000000000000000000) {
xx >>= 128;
r <<= 64;
}
if (xx >= 0x10000000000000000) {
xx >>= 64;
r <<= 32;
}
if (xx >= 0x100000000) {
xx >>= 32;
r <<= 16;
}
if (xx >= 0x10000) {
xx >>= 16;
r <<= 8;
}
if (xx >= 0x100) {
xx >>= 8;
r <<= 4;
}
if (xx >= 0x10) {
xx >>= 4;
r <<= 2;
}
if (xx >= 0x8) {
r <<= 1;
}
r = (r + x / r) >> 1;
r = (r + x / r) >> 1;
r = (r + x / r) >> 1;
r = (r + x / r) >> 1;
r = (r + x / r) >> 1;
r = (r + x / r) >> 1;
r = (r + x / r) >> 1; // Seven iterations should be enough
uint r1 = x / r;
return (r < r1 ? r : r1);
}
}
pragma solidity ^0.5.16;
pragma experimental ABIEncoderV2;
contract Comp {
/// @notice EIP-20 token name for this token
string public constant name = "Cream";
/// @notice EIP-20 token symbol for this token
string public constant symbol = "CREAM";
/// @notice EIP-20 token decimals for this token
uint8 public constant decimals = 18;
/// @notice Total number of tokens in circulation
uint public constant totalSupply = 9000000e18; // 9 million Comp
/// @notice Allowance amounts on behalf of others
mapping (address => mapping (address => uint96)) internal allowances;
/// @notice Official record of token balances for each account
mapping (address => uint96) internal balances;
/// @notice A record of each accounts delegate
mapping (address => address) public delegates;
/// @notice A checkpoint for marking number of votes from a given block
struct Checkpoint {
uint32 fromBlock;
uint96 votes;
}
/// @notice A record of votes checkpoints for each account, by index
mapping (address => mapping (uint32 => Checkpoint)) public checkpoints;
/// @notice The number of checkpoints for each account
mapping (address => uint32) public numCheckpoints;
/// @notice The EIP-712 typehash for the contract's domain
bytes32 public constant DOMAIN_TYPEHASH = keccak256("EIP712Domain(string name,uint256 chainId,address verifyingContract)");
/// @notice The EIP-712 typehash for the delegation struct used by the contract
bytes32 public constant DELEGATION_TYPEHASH = keccak256("Delegation(address delegatee,uint256 nonce,uint256 expiry)");
/// @notice A record of states for signing / validating signatures
mapping (address => uint) public nonces;
/// @notice An event thats emitted when an account changes its delegate
event DelegateChanged(address indexed delegator, address indexed fromDelegate, address indexed toDelegate);
/// @notice An event thats emitted when a delegate account's vote balance changes
event DelegateVotesChanged(address indexed delegate, uint previousBalance, uint newBalance);
/// @notice The standard EIP-20 transfer event
event Transfer(address indexed from, address indexed to, uint256 amount);
/// @notice The standard EIP-20 approval event
event Approval(address indexed owner, address indexed spender, uint256 amount);
/**
* @notice Construct a new Comp token
* @param account The initial account to grant all the tokens
*/
constructor(address account) public {
balances[account] = uint96(totalSupply);
emit Transfer(address(0), account, totalSupply);
}
/**
* @notice Get the number of tokens `spender` is approved to spend on behalf of `account`
* @param account The address of the account holding the funds
* @param spender The address of the account spending the funds
* @return The number of tokens approved
*/
function allowance(address account, address spender) external view returns (uint) {
return allowances[account][spender];
}
/**
* @notice Approve `spender` to transfer up to `amount` from `src`
* @dev This will overwrite the approval amount for `spender`
* and is subject to issues noted [here](https://eips.ethereum.org/EIPS/eip-20#approve)
* @param spender The address of the account which may transfer tokens
* @param rawAmount The number of tokens that are approved (2^256-1 means infinite)
* @return Whether or not the approval succeeded
*/
function approve(address spender, uint rawAmount) external returns (bool) {
uint96 amount;
if (rawAmount == uint(-1)) {
amount = uint96(-1);
} else {
amount = safe96(rawAmount, "Comp::approve: amount exceeds 96 bits");
}
allowances[msg.sender][spender] = amount;
emit Approval(msg.sender, spender, amount);
return true;
}
/**
* @notice Get the number of tokens held by the `account`
* @param account The address of the account to get the balance of
* @return The number of tokens held
*/
function balanceOf(address account) external view returns (uint) {
return balances[account];
}
/**
* @notice Transfer `amount` tokens from `msg.sender` to `dst`
* @param dst The address of the destination account
* @param rawAmount The number of tokens to transfer
* @return Whether or not the transfer succeeded
*/
function transfer(address dst, uint rawAmount) external returns (bool) {
uint96 amount = safe96(rawAmount, "Comp::transfer: amount exceeds 96 bits");
_transferTokens(msg.sender, dst, amount);
return true;
}
/**
* @notice Transfer `amount` tokens from `src` to `dst`
* @param src The address of the source account
* @param dst The address of the destination account
* @param rawAmount The number of tokens to transfer
* @return Whether or not the transfer succeeded
*/
function transferFrom(address src, address dst, uint rawAmount) external returns (bool) {
address spender = msg.sender;
uint96 spenderAllowance = allowances[src][spender];
uint96 amount = safe96(rawAmount, "Comp::approve: amount exceeds 96 bits");
if (spender != src && spenderAllowance != uint96(-1)) {
uint96 newAllowance = sub96(spenderAllowance, amount, "Comp::transferFrom: transfer amount exceeds spender allowance");
allowances[src][spender] = newAllowance;
emit Approval(src, spender, newAllowance);
}
_transferTokens(src, dst, amount);
return true;
}
/**
* @notice Delegate votes from `msg.sender` to `delegatee`
* @param delegatee The address to delegate votes to
*/
function delegate(address delegatee) public {
return _delegate(msg.sender, delegatee);
}
/**
* @notice Delegates votes from signatory to `delegatee`
* @param delegatee The address to delegate votes to
* @param nonce The contract state required to match the signature
* @param expiry The time at which to expire the signature
* @param v The recovery byte of the signature
* @param r Half of the ECDSA signature pair
* @param s Half of the ECDSA signature pair
*/
function delegateBySig(address delegatee, uint nonce, uint expiry, uint8 v, bytes32 r, bytes32 s) public {
bytes32 domainSeparator = keccak256(abi.encode(DOMAIN_TYPEHASH, keccak256(bytes(name)), getChainId(), address(this)));
bytes32 structHash = keccak256(abi.encode(DELEGATION_TYPEHASH, delegatee, nonce, expiry));
bytes32 digest = keccak256(abi.encodePacked("\x19\x01", domainSeparator, structHash));
address signatory = ecrecover(digest, v, r, s);
require(signatory != address(0), "Comp::delegateBySig: invalid signature");
require(nonce == nonces[signatory]++, "Comp::delegateBySig: invalid nonce");
require(now <= expiry, "Comp::delegateBySig: signature expired");
return _delegate(signatory, delegatee);
}
/**
* @notice Gets the current votes balance for `account`
* @param account The address to get votes balance
* @return The number of current votes for `account`
*/
function getCurrentVotes(address account) external view returns (uint96) {
uint32 nCheckpoints = numCheckpoints[account];
return nCheckpoints > 0 ? checkpoints[account][nCheckpoints - 1].votes : 0;
}
/**
* @notice Determine the prior number of votes for an account as of a block number
* @dev Block number must be a finalized block or else this function will revert to prevent misinformation.
* @param account The address of the account to check
* @param blockNumber The block number to get the vote balance at
* @return The number of votes the account had as of the given block
*/
function getPriorVotes(address account, uint blockNumber) public view returns (uint96) {
require(blockNumber < block.number, "Comp::getPriorVotes: not yet determined");
uint32 nCheckpoints = numCheckpoints[account];
if (nCheckpoints == 0) {
return 0;
}
// First check most recent balance
if (checkpoints[account][nCheckpoints - 1].fromBlock <= blockNumber) {
return checkpoints[account][nCheckpoints - 1].votes;
}
// Next check implicit zero balance
if (checkpoints[account][0].fromBlock > blockNumber) {
return 0;
}
uint32 lower = 0;
uint32 upper = nCheckpoints - 1;
while (upper > lower) {
uint32 center = upper - (upper - lower) / 2; // ceil, avoiding overflow
Checkpoint memory cp = checkpoints[account][center];
if (cp.fromBlock == blockNumber) {
return cp.votes;
} else if (cp.fromBlock < blockNumber) {
lower = center;
} else {
upper = center - 1;
}
}
return checkpoints[account][lower].votes;
}
function _delegate(address delegator, address delegatee) internal {
address currentDelegate = delegates[delegator];
uint96 delegatorBalance = balances[delegator];
delegates[delegator] = delegatee;
emit DelegateChanged(delegator, currentDelegate, delegatee);
_moveDelegates(currentDelegate, delegatee, delegatorBalance);
}
function _transferTokens(address src, address dst, uint96 amount) internal {
require(src != address(0), "Comp::_transferTokens: cannot transfer from the zero address");
require(dst != address(0), "Comp::_transferTokens: cannot transfer to the zero address");
balances[src] = sub96(balances[src], amount, "Comp::_transferTokens: transfer amount exceeds balance");
balances[dst] = add96(balances[dst], amount, "Comp::_transferTokens: transfer amount overflows");
emit Transfer(src, dst, amount);
_moveDelegates(delegates[src], delegates[dst], amount);
}
function _moveDelegates(address srcRep, address dstRep, uint96 amount) internal {
if (srcRep != dstRep && amount > 0) {
if (srcRep != address(0)) {
uint32 srcRepNum = numCheckpoints[srcRep];
uint96 srcRepOld = srcRepNum > 0 ? checkpoints[srcRep][srcRepNum - 1].votes : 0;
uint96 srcRepNew = sub96(srcRepOld, amount, "Comp::_moveVotes: vote amount underflows");
_writeCheckpoint(srcRep, srcRepNum, srcRepOld, srcRepNew);
}
if (dstRep != address(0)) {
uint32 dstRepNum = numCheckpoints[dstRep];
uint96 dstRepOld = dstRepNum > 0 ? checkpoints[dstRep][dstRepNum - 1].votes : 0;
uint96 dstRepNew = add96(dstRepOld, amount, "Comp::_moveVotes: vote amount overflows");
_writeCheckpoint(dstRep, dstRepNum, dstRepOld, dstRepNew);
}
}
}
function _writeCheckpoint(address delegatee, uint32 nCheckpoints, uint96 oldVotes, uint96 newVotes) internal {
uint32 blockNumber = safe32(block.number, "Comp::_writeCheckpoint: block number exceeds 32 bits");
if (nCheckpoints > 0 && checkpoints[delegatee][nCheckpoints - 1].fromBlock == blockNumber) {
checkpoints[delegatee][nCheckpoints - 1].votes = newVotes;
} else {
checkpoints[delegatee][nCheckpoints] = Checkpoint(blockNumber, newVotes);
numCheckpoints[delegatee] = nCheckpoints + 1;
}
emit DelegateVotesChanged(delegatee, oldVotes, newVotes);
}
function safe32(uint n, string memory errorMessage) internal pure returns (uint32) {
require(n < 2**32, errorMessage);
return uint32(n);
}
function safe96(uint n, string memory errorMessage) internal pure returns (uint96) {
require(n < 2**96, errorMessage);
return uint96(n);
}
function add96(uint96 a, uint96 b, string memory errorMessage) internal pure returns (uint96) {
uint96 c = a + b;
require(c >= a, errorMessage);
return c;
}
function sub96(uint96 a, uint96 b, string memory errorMessage) internal pure returns (uint96) {
require(b <= a, errorMessage);
return a - b;
}
function getChainId() internal pure returns (uint) {
uint256 chainId;
assembly { chainId := chainid() }
return chainId;
}
}
pragma solidity ^0.5.16;
/**
* @title Compound's InterestRateModel Interface
* @author Compound
*/
contract InterestRateModel {
/// @notice Indicator that this is an InterestRateModel contract (for inspection)
bool public constant isInterestRateModel = true;
/**
* @notice Calculates the current borrow interest rate per block
* @param cash The total amount of cash the market has
* @param borrows The total amount of borrows the market has outstanding
* @param reserves The total amnount of reserves the market has
* @return The borrow rate per block (as a percentage, and scaled by 1e18)
*/
function getBorrowRate(uint cash, uint borrows, uint reserves) external view returns (uint);
/**
* @notice Calculates the current supply interest rate per block
* @param cash The total amount of cash the market has
* @param borrows The total amount of borrows the market has outstanding
* @param reserves The total amnount of reserves the market has
* @param reserveFactorMantissa The current reserve factor the market has
* @return The supply rate per block (as a percentage, and scaled by 1e18)
*/
function getSupplyRate(uint cash, uint borrows, uint reserves, uint reserveFactorMantissa) external view returns (uint);
}
pragma solidity ^0.5.16;
pragma experimental ABIEncoderV2;
import "../CErc20.sol";
import "../CToken.sol";
import "../CTokenInterfaces.sol";
import "../PriceOracle.sol";
import "../EIP20Interface.sol";
import "../Governance/Comp.sol";
interface ComptrollerLensInterface {
function markets(address) external view returns (bool, uint, bool, uint);
function oracle() external view returns (PriceOracle);
function getAccountLiquidity(address) external view returns (uint, uint, uint);
function getAssetsIn(address) external view returns (CToken[] memory);
function claimComp(address) external;
function compAccrued(address) external view returns (uint);
}
interface CSLPInterface {
function claimSushi(address) external returns (uint);
}
interface CCTokenInterface {
function claimComp(address) external returns (uint);
}
contract CompoundLens {
struct CTokenMetadata {
address cToken;
uint exchangeRateCurrent;
uint supplyRatePerBlock;
uint borrowRatePerBlock;
uint reserveFactorMantissa;
uint totalBorrows;
uint totalReserves;
uint totalSupply;
uint totalCash;
bool isListed;
uint collateralFactorMantissa;
address underlyingAssetAddress;
uint cTokenDecimals;
uint underlyingDecimals;
uint version;
uint collateralCap;
}
function cTokenMetadata(CToken cToken) public returns (CTokenMetadata memory) {
uint exchangeRateCurrent = cToken.exchangeRateCurrent();
ComptrollerLensInterface comptroller = ComptrollerLensInterface(address(cToken.comptroller()));
(bool isListed, uint collateralFactorMantissa, , uint version) = comptroller.markets(address(cToken));
address underlyingAssetAddress;
uint underlyingDecimals;
uint collateralCap;
if (compareStrings(cToken.symbol(), "crETH")) {
underlyingAssetAddress = address(0);
underlyingDecimals = 18;
} else {
CErc20 cErc20 = CErc20(address(cToken));
underlyingAssetAddress = cErc20.underlying();
underlyingDecimals = EIP20Interface(cErc20.underlying()).decimals();
}
if (version == 1) {
collateralCap = CCollateralCapErc20Interface(address(cToken)).collateralCap();
}
return CTokenMetadata({
cToken: address(cToken),
exchangeRateCurrent: exchangeRateCurrent,
supplyRatePerBlock: cToken.supplyRatePerBlock(),
borrowRatePerBlock: cToken.borrowRatePerBlock(),
reserveFactorMantissa: cToken.reserveFactorMantissa(),
totalBorrows: cToken.totalBorrows(),
totalReserves: cToken.totalReserves(),
totalSupply: cToken.totalSupply(),
totalCash: cToken.getCash(),
isListed: isListed,
collateralFactorMantissa: collateralFactorMantissa,
underlyingAssetAddress: underlyingAssetAddress,
cTokenDecimals: cToken.decimals(),
underlyingDecimals: underlyingDecimals,
version: version,
collateralCap: collateralCap
});
}
function cTokenMetadataAll(CToken[] calldata cTokens) external returns (CTokenMetadata[] memory) {
uint cTokenCount = cTokens.length;
CTokenMetadata[] memory res = new CTokenMetadata[](cTokenCount);
for (uint i = 0; i < cTokenCount; i++) {
res[i] = cTokenMetadata(cTokens[i]);
}
return res;
}
struct CTokenBalances {
address cToken;
uint balanceOf;
uint borrowBalanceCurrent;
uint balanceOfUnderlying;
uint tokenBalance;
uint tokenAllowance;
}
function cTokenBalances(CToken cToken, address payable account) public returns (CTokenBalances memory) {
uint balanceOf = cToken.balanceOf(account);
uint borrowBalanceCurrent = cToken.borrowBalanceCurrent(account);
uint balanceOfUnderlying = cToken.balanceOfUnderlying(account);
uint tokenBalance;
uint tokenAllowance;
if (compareStrings(cToken.symbol(), "crETH")) {
tokenBalance = account.balance;
tokenAllowance = account.balance;
} else {
CErc20 cErc20 = CErc20(address(cToken));
EIP20Interface underlying = EIP20Interface(cErc20.underlying());
tokenBalance = underlying.balanceOf(account);
tokenAllowance = underlying.allowance(account, address(cToken));
}
return CTokenBalances({
cToken: address(cToken),
balanceOf: balanceOf,
borrowBalanceCurrent: borrowBalanceCurrent,
balanceOfUnderlying: balanceOfUnderlying,
tokenBalance: tokenBalance,
tokenAllowance: tokenAllowance
});
}
function cTokenBalancesAll(CToken[] calldata cTokens, address payable account) external returns (CTokenBalances[] memory) {
uint cTokenCount = cTokens.length;
CTokenBalances[] memory res = new CTokenBalances[](cTokenCount);
for (uint i = 0; i < cTokenCount; i++) {
res[i] = cTokenBalances(cTokens[i], account);
}
return res;
}
struct CTokenUnderlyingPrice {
address cToken;
uint underlyingPrice;
}
function cTokenUnderlyingPrice(CToken cToken) public returns (CTokenUnderlyingPrice memory) {
ComptrollerLensInterface comptroller = ComptrollerLensInterface(address(cToken.comptroller()));
PriceOracle priceOracle = comptroller.oracle();
return CTokenUnderlyingPrice({
cToken: address(cToken),
underlyingPrice: priceOracle.getUnderlyingPrice(cToken)
});
}
function cTokenUnderlyingPriceAll(CToken[] calldata cTokens) external returns (CTokenUnderlyingPrice[] memory) {
uint cTokenCount = cTokens.length;
CTokenUnderlyingPrice[] memory res = new CTokenUnderlyingPrice[](cTokenCount);
for (uint i = 0; i < cTokenCount; i++) {
res[i] = cTokenUnderlyingPrice(cTokens[i]);
}
return res;
}
struct AccountLimits {
CToken[] markets;
uint liquidity;
uint shortfall;
}
function getAccountLimits(ComptrollerLensInterface comptroller, address account) public returns (AccountLimits memory) {
(uint errorCode, uint liquidity, uint shortfall) = comptroller.getAccountLiquidity(account);
require(errorCode == 0);
return AccountLimits({
markets: comptroller.getAssetsIn(account),
liquidity: liquidity,
shortfall: shortfall
});
}
struct CompBalanceMetadata {
uint balance;
uint votes;
address delegate;
}
function getCompBalanceMetadata(Comp comp, address account) external view returns (CompBalanceMetadata memory) {
return CompBalanceMetadata({
balance: comp.balanceOf(account),
votes: uint256(comp.getCurrentVotes(account)),
delegate: comp.delegates(account)
});
}
struct CompBalanceMetadataExt {
uint balance;
uint votes;
address delegate;
uint allocated;
}
function getCompBalanceMetadataExt(Comp comp, ComptrollerLensInterface comptroller, address account) external returns (CompBalanceMetadataExt memory) {
uint balance = comp.balanceOf(account);
comptroller.claimComp(account);
uint newBalance = comp.balanceOf(account);
uint accrued = comptroller.compAccrued(account);
uint total = add(accrued, newBalance, "sum comp total");
uint allocated = sub(total, balance, "sub allocated");
return CompBalanceMetadataExt({
balance: balance,
votes: uint256(comp.getCurrentVotes(account)),
delegate: comp.delegates(account),
allocated: allocated
});
}
struct CompVotes {
uint blockNumber;
uint votes;
}
function getCompVotes(Comp comp, address account, uint32[] calldata blockNumbers) external view returns (CompVotes[] memory) {
CompVotes[] memory res = new CompVotes[](blockNumbers.length);
for (uint i = 0; i < blockNumbers.length; i++) {
res[i] = CompVotes({
blockNumber: uint256(blockNumbers[i]),
votes: uint256(comp.getPriorVotes(account, blockNumbers[i]))
});
}
return res;
}
function getClaimableSushiRewards(CSLPInterface[] calldata cTokens, address sushi, address account) external returns (uint[] memory) {
uint cTokenCount = cTokens.length;
uint[] memory rewards = new uint[](cTokenCount);
for (uint i = 0; i < cTokenCount; i++) {
uint balanceBefore = EIP20Interface(sushi).balanceOf(account);
cTokens[i].claimSushi(account);
uint balanceAfter = EIP20Interface(sushi).balanceOf(account);
rewards[i] = sub(balanceAfter, balanceBefore, "subtraction underflow");
}
return rewards;
}
function getClaimableCompRewards(CCTokenInterface[] calldata cTokens, address comp, address account) external returns (uint[] memory) {
uint cTokenCount = cTokens.length;
uint[] memory rewards = new uint[](cTokenCount);
for (uint i = 0; i < cTokenCount; i++) {
uint balanceBefore = EIP20Interface(comp).balanceOf(account);
cTokens[i].claimComp(account);
uint balanceAfter = EIP20Interface(comp).balanceOf(account);
rewards[i] = sub(balanceAfter, balanceBefore, "subtraction underflow");
}
return rewards;
}
function compareStrings(string memory a, string memory b) internal pure returns (bool) {
return (keccak256(abi.encodePacked((a))) == keccak256(abi.encodePacked((b))));
}
function add(uint a, uint b, string memory errorMessage) internal pure returns (uint) {
uint c = a + b;
require(c >= a, errorMessage);
return c;
}
function sub(uint a, uint b, string memory errorMessage) internal pure returns (uint) {
require(b <= a, errorMessage);
uint c = a - b;
return c;
}
}
pragma solidity ^0.5.16;
import "./CToken.sol";
contract PriceOracle {
/// @notice Indicator that this is a PriceOracle contract (for inspection)
bool public constant isPriceOracle = true;
/**
* @notice Get the underlying price of a cToken asset
* @param cToken The cToken to get the underlying price of
* @return The underlying asset price mantissa (scaled by 1e18).
* Zero means the price is unavailable.
*/
function getUnderlyingPrice(CToken cToken) external view returns (uint);
}
|
User supplies assets into the market and receives cTokens in exchange Assumes interest has already been accrued up to the current block minter The address of the account which is supplying the assets mintAmount The amount of the underlying asset to supply return (uint, uint) An error code (0=success, otherwise a failure, see ErrorReporter.sol), and the actual mint amount./
|
function mintFresh(address minter, uint mintAmount) internal returns (uint, uint) {
uint allowed = comptroller.mintAllowed(address(this), minter, mintAmount);
if (allowed != 0) {
return (failOpaque(Error.COMPTROLLER_REJECTION, FailureInfo.MINT_COMPTROLLER_REJECTION, allowed), 0);
}
if (mintAmount == 0) {
return (uint(Error.NO_ERROR), 0);
}
if (accrualBlockNumber != getBlockNumber()) {
return (fail(Error.MARKET_NOT_FRESH, FailureInfo.MINT_FRESHNESS_CHECK), 0);
}
MintLocalVars memory vars;
vars.exchangeRateMantissa = exchangeRateStoredInternal();
accountTokens[minter] = add_(accountTokens[minter], vars.mintTokens);
emit Transfer(address(this), minter, vars.mintTokens);
return (uint(Error.NO_ERROR), vars.actualMintAmount);
vars.actualMintAmount = doTransferIn(minter, mintAmount);
vars.mintTokens = div_ScalarByExpTruncate(vars.actualMintAmount, Exp({mantissa: vars.exchangeRateMantissa}));
totalSupply = add_(totalSupply, vars.mintTokens);
emit Mint(minter, vars.actualMintAmount, vars.mintTokens);
}
| 6,267,679 |
./full_match/5/0xBB2A7A26094c456637E9CcB67BEfEff700C1ba4a/sources/src/Blacklist.sol
|
add address to blacklist
|
function _addBlacklist(address account) internal virtual {
_blacklist[account] = true;
emit Blacklisted(account);
}
| 1,914,052 |
// SPDX-License-Identifier: MIT
// File: @openzeppelin/contracts/token/ERC20/IERC20.sol
pragma solidity ^0.6.0;
/**
* @dev Interface of the ERC20 standard as defined in the EIP.
*/
interface IERC20 {
/**
* @dev Returns the amount of tokens in existence.
*/
function totalSupply() external view returns (uint256);
function decimals() external view returns (uint8);
/**
* @dev Returns the amount of tokens owned by `account`.
*/
function balanceOf(address account) external view returns (uint256);
/**
* @dev Moves `amount` tokens from the caller's account to `recipient`.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/
function transfer(address recipient, uint256 amount) external returns (bool);
/**
* @dev Returns the remaining number of tokens that `spender` will be
* allowed to spend on behalf of `owner` through {transferFrom}. This is
* zero by default.
*
* This value changes when {approve} or {transferFrom} are called.
*/
function allowance(address owner, address spender) external view returns (uint256);
/**
* @dev Sets `amount` as the allowance of `spender` over the caller's tokens.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* IMPORTANT: 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
*
* Emits an {Approval} event.
*/
function approve(address spender, uint256 amount) external returns (bool);
/**
* @dev Moves `amount` tokens from `sender` to `recipient` using the
* allowance mechanism. `amount` is then deducted from the caller's
* allowance.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/
function transferFrom(address sender, address recipient, uint256 amount) external returns (bool);
/**
* @dev Emitted when `value` tokens are moved from one account (`from`) to
* another (`to`).
*
* Note that `value` may be zero.
*/
event Transfer(address indexed from, address indexed to, uint256 value);
/**
* @dev Emitted when the allowance of a `spender` for an `owner` is set by
* a call to {approve}. `value` is the new allowance.
*/
event Approval(address indexed owner, address indexed spender, uint256 value);
}
// File: @openzeppelin/contracts/math/SafeMath.sol
pragma solidity ^0.6.0;
/**
* @dev Wrappers over Solidity's arithmetic operations with added overflow
* checks.
*
* Arithmetic operations in Solidity wrap on overflow. This can easily result
* in bugs, because programmers usually assume that an overflow raises an
* error, which is the standard behavior in high level programming languages.
* `SafeMath` restores this intuition by reverting the transaction when an
* operation overflows.
*
* Using this library instead of the unchecked operations eliminates an entire
* class of bugs, so it's recommended to use it always.
*/
library SafeMath {
/**
* @dev Returns the addition of two unsigned integers, reverting on
* overflow.
*
* Counterpart to Solidity's `+` operator.
*
* Requirements:
*
* - Addition cannot overflow.
*/
function add(uint256 a, uint256 b) internal pure returns (uint256) {
uint256 c = a + b;
require(c >= a, "SafeMath: addition overflow");
return c;
}
/**
* @dev Returns the subtraction of two unsigned integers, reverting on
* overflow (when the result is negative).
*
* Counterpart to Solidity's `-` operator.
*
* Requirements:
*
* - Subtraction cannot overflow.
*/
function sub(uint256 a, uint256 b) internal pure returns (uint256) {
return sub(a, b, "SafeMath: subtraction overflow");
}
/**
* @dev Returns the subtraction of two unsigned integers, reverting with custom message on
* overflow (when the result is negative).
*
* Counterpart to Solidity's `-` operator.
*
* Requirements:
*
* - Subtraction cannot overflow.
*/
function sub(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
require(b <= a, errorMessage);
uint256 c = a - b;
return c;
}
/**
* @dev Returns the multiplication of two unsigned integers, reverting on
* overflow.
*
* Counterpart to Solidity's `*` operator.
*
* Requirements:
*
* - Multiplication cannot overflow.
*/
function mul(uint256 a, uint256 b) internal pure returns (uint256) {
// Gas optimization: this is cheaper than requiring 'a' not being zero, but the
// benefit is lost if 'b' is also tested.
// See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522
if (a == 0) {
return 0;
}
uint256 c = a * b;
require(c / a == b, "SafeMath: multiplication overflow");
return c;
}
/**
* @dev Returns the integer division of two unsigned integers. Reverts on
* division by zero. The result is rounded towards zero.
*
* Counterpart to Solidity's `/` operator. Note: this function uses a
* `revert` opcode (which leaves remaining gas untouched) while Solidity
* uses an invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function div(uint256 a, uint256 b) internal pure returns (uint256) {
return div(a, b, "SafeMath: division by zero");
}
/**
* @dev Returns the integer division of two unsigned integers. Reverts with custom message on
* division by zero. The result is rounded towards zero.
*
* Counterpart to Solidity's `/` operator. Note: this function uses a
* `revert` opcode (which leaves remaining gas untouched) while Solidity
* uses an invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function div(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
require(b > 0, errorMessage);
uint256 c = a / b;
// assert(a == b * c + a % b); // There is no case in which this doesn't hold
return c;
}
/**
* @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo),
* Reverts when dividing by zero.
*
* Counterpart to Solidity's `%` operator. This function uses a `revert`
* opcode (which leaves remaining gas untouched) while Solidity uses an
* invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function mod(uint256 a, uint256 b) internal pure returns (uint256) {
return mod(a, b, "SafeMath: modulo by zero");
}
/**
* @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo),
* Reverts with custom message when dividing by zero.
*
* Counterpart to Solidity's `%` operator. This function uses a `revert`
* opcode (which leaves remaining gas untouched) while Solidity uses an
* invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function mod(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
require(b != 0, errorMessage);
return a % b;
}
}
// File: @openzeppelin/contracts/utils/Address.sol
pragma solidity ^0.6.2;
/**
* @dev Collection of functions related to the address type
*/
library Address {
/**
* @dev Returns true if `account` is a contract.
*
* [IMPORTANT]
* ====
* It is unsafe to assume that an address for which this function returns
* false is an externally-owned account (EOA) and not a contract.
*
* Among others, `isContract` will return false for the following
* types of addresses:
*
* - an externally-owned account
* - a contract in construction
* - an address where a contract will be created
* - an address where a contract lived, but was destroyed
* ====
*/
function isContract(address account) internal view returns (bool) {
// According to EIP-1052, 0x0 is the value returned for not-yet created accounts
// and 0xc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470 is returned
// for accounts without code, i.e. `keccak256('')`
bytes32 codehash;
bytes32 accountHash = 0xc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470;
// solhint-disable-next-line no-inline-assembly
assembly { codehash := extcodehash(account) }
return (codehash != accountHash && codehash != 0x0);
}
/**
* @dev Replacement for Solidity's `transfer`: sends `amount` wei to
* `recipient`, forwarding all available gas and reverting on errors.
*
* https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost
* of certain opcodes, possibly making contracts go over the 2300 gas limit
* imposed by `transfer`, making them unable to receive funds via
* `transfer`. {sendValue} removes this limitation.
*
* https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more].
*
* IMPORTANT: because control is transferred to `recipient`, care must be
* taken to not create reentrancy vulnerabilities. Consider using
* {ReentrancyGuard} or the
* https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern].
*/
function sendValue(address payable recipient, uint256 amount) internal {
require(address(this).balance >= amount, "Address: insufficient balance");
// solhint-disable-next-line avoid-low-level-calls, avoid-call-value
(bool success, ) = recipient.call{ value: amount }("");
require(success, "Address: unable to send value, recipient may have reverted");
}
/**
* @dev Performs a Solidity function call using a low level `call`. A
* plain`call` is an unsafe replacement for a function call: use this
* function instead.
*
* If `target` reverts with a revert reason, it is bubbled up by this
* function (like regular Solidity function calls).
*
* Returns the raw returned data. To convert to the expected return value,
* use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`].
*
* 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");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with
* `errorMessage` as a fallback revert reason when `target` reverts.
*
* _Available since v3.1._
*/
function functionCall(address target, bytes memory data, string memory errorMessage) internal returns (bytes memory) {
return _functionCallWithValue(target, data, 0, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but also transferring `value` wei to `target`.
*
* Requirements:
*
* - the calling contract must have an ETH balance of at least `value`.
* - the called Solidity function must be `payable`.
*
* _Available since v3.1._
*/
function functionCallWithValue(address target, bytes memory data, uint256 value) internal returns (bytes memory) {
return functionCallWithValue(target, data, value, "Address: low-level call with value failed");
}
/**
* @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but
* with `errorMessage` as a fallback revert reason when `target` reverts.
*
* _Available since v3.1._
*/
function functionCallWithValue(address target, bytes memory data, uint256 value, string memory errorMessage) internal returns (bytes memory) {
require(address(this).balance >= value, "Address: insufficient balance for call");
return _functionCallWithValue(target, data, value, errorMessage);
}
function _functionCallWithValue(address target, bytes memory data, uint256 weiValue, string memory errorMessage) private returns (bytes memory) {
require(isContract(target), "Address: call to non-contract");
// solhint-disable-next-line avoid-low-level-calls
(bool success, bytes memory returndata) = target.call{ value: weiValue }(data);
if (success) {
return returndata;
} else {
// Look for revert reason and bubble it up if present
if (returndata.length > 0) {
// The easiest way to bubble the revert reason is using memory via assembly
// solhint-disable-next-line no-inline-assembly
assembly {
let returndata_size := mload(returndata)
revert(add(32, returndata), returndata_size)
}
} else {
revert(errorMessage);
}
}
}
}
// File: @openzeppelin/contracts/token/ERC20/SafeERC20.sol
pragma solidity ^0.6.0;
/**
* @title SafeERC20
* @dev Wrappers around ERC20 operations that throw on failure (when the token
* contract returns false). Tokens that return no value (and instead revert or
* throw on failure) are also supported, non-reverting calls are assumed to be
* successful.
* To use this library you can add a `using SafeERC20 for IERC20;` statement to your contract,
* which allows you to call the safe operations as `token.safeTransfer(...)`, etc.
*/
library SafeERC20 {
using SafeMath for uint256;
using Address for address;
function safeTransfer(IERC20 token, address to, uint256 value) internal {
_callOptionalReturn(token, abi.encodeWithSelector(token.transfer.selector, to, value));
}
function safeTransferFrom(IERC20 token, address from, address to, uint256 value) internal {
_callOptionalReturn(token, abi.encodeWithSelector(token.transferFrom.selector, from, to, value));
}
/**
* @dev Deprecated. This function has issues similar to the ones found in
* {IERC20-approve}, and its usage is discouraged.
*
* Whenever possible, use {safeIncreaseAllowance} and
* {safeDecreaseAllowance} instead.
*/
function safeApprove(IERC20 token, address spender, uint256 value) internal {
// safeApprove should only be called when setting an initial allowance,
// or when resetting it to zero. To increase and decrease it, use
// 'safeIncreaseAllowance' and 'safeDecreaseAllowance'
// solhint-disable-next-line max-line-length
require((value == 0) || (token.allowance(address(this), spender) == 0),
"SafeERC20: approve from non-zero to non-zero allowance"
);
_callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, value));
}
function safeIncreaseAllowance(IERC20 token, address spender, uint256 value) internal {
uint256 newAllowance = token.allowance(address(this), spender).add(value);
_callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance));
}
function safeDecreaseAllowance(IERC20 token, address spender, uint256 value) internal {
uint256 newAllowance = token.allowance(address(this), spender).sub(value, "SafeERC20: decreased allowance below zero");
_callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance));
}
/**
* @dev Imitates a Solidity high-level call (i.e. a regular function call to a contract), relaxing the requirement
* on the return value: the return value is optional (but if data is returned, it must not be false).
* @param token The token targeted by the call.
* @param data The call data (encoded using abi.encode or one of its variants).
*/
function _callOptionalReturn(IERC20 token, bytes memory data) private {
// We need to perform a low level call here, to bypass Solidity's return data size checking mechanism, since
// we're implementing it ourselves. We use {Address.functionCall} to perform this call, which verifies that
// the target address contains contract code and also asserts for success in the low-level call.
bytes memory returndata = address(token).functionCall(data, "SafeERC20: low-level call failed");
if (returndata.length > 0) { // Return data is optional
// solhint-disable-next-line max-line-length
require(abi.decode(returndata, (bool)), "SafeERC20: ERC20 operation did not succeed");
}
}
}
// File: @openzeppelin/contracts/GSN/Context.sol
pragma solidity ^0.6.0;
/*
* @dev Provides information about the current execution context, including the
* sender of the transaction and its data. While these are generally available
* via msg.sender and msg.data, they should not be accessed in such a direct
* manner, since when dealing with GSN meta-transactions the account sending and
* paying for execution may not be the actual sender (as far as an application
* is concerned).
*
* This contract is only required for intermediate, library-like contracts.
*/
abstract contract Context {
function _msgSender() internal view virtual returns (address payable) {
return msg.sender;
}
function _msgData() internal view virtual returns (bytes memory) {
this; // silence state mutability warning without generating bytecode - see https://github.com/ethereum/solidity/issues/2691
return msg.data;
}
}
// File: @openzeppelin/contracts/access/Ownable.sol
pragma solidity ^0.6.0;
/**
* @dev Contract module which provides a basic access control mechanism, where
* there is an account (an owner) that can be granted exclusive access to
* specific functions.
*
* By default, the owner account will be the one that deploys the contract. This
* can later be changed with {transferOwnership}.
*
* This module is used through inheritance. It will make available the modifier
* `onlyOwner`, which can be applied to your functions to restrict their use to
* the owner.
*/
contract Ownable is Context {
address private _governance;
event GovernanceTransferred(address indexed previousOwner, address indexed newOwner);
/**
* @dev Initializes the contract setting the deployer as the initial owner.
*/
constructor () internal {
address msgSender = _msgSender();
_governance = msgSender;
emit GovernanceTransferred(address(0), msgSender);
}
/**
* @dev Returns the address of the current owner.
*/
function governance() public view returns (address) {
return _governance;
}
/**
* @dev Throws if called by any account other than the owner.
*/
modifier onlyGovernance() {
require(_governance == _msgSender(), "Ownable: caller is not the owner");
_;
}
/**
* @dev Transfers ownership of the contract to a new account (`newOwner`).
* Can only be called by the current owner.
*/
function transferGovernance(address newOwner) internal virtual onlyGovernance {
require(newOwner != address(0), "Ownable: new owner is the zero address");
emit GovernanceTransferred(_governance, newOwner);
_governance = newOwner;
}
}
// File: contracts/strategies/StabilizeStrategyXUSDArb.sol
pragma solidity =0.6.6;
// This is a strategy that takes advantage of arb opportunities for these emerging stablecoins
// Users deposit various tokens into the strategy and the strategy will sell into the lowest priced token
// Selling will occur via Curve and buying WETH via Sushiswap
// Half the profit earned from the sell and interest will be used to buy WETH and split it among the treasury, stakers and executor
// It will sell on withdrawals only when a non-contract calls it and certain requirements are met
// Anyone can be an executors and profit a percentage on a trade
// Gas cost is reimbursed, up to a percentage of the total WETH profit / stipend
// Added feature to trade for maximum profit
interface StabilizeStakingPool {
function notifyRewardAmount(uint256) external;
}
interface CurvePool {
function get_dy_underlying(int128, int128, uint256) external view returns (uint256); // Get quantity estimate
function exchange_underlying(int128, int128, uint256, uint256) external; // Exchange tokens
function get_dy(int128, int128, uint256) external view returns (uint256); // Get quantity estimate
function exchange(int128, int128, uint256, uint256) external; // Exchange tokens
}
interface TradeRouter {
function swapExactETHForTokens(uint, address[] calldata, address, uint) external payable returns (uint[] memory);
function swapExactTokensForTokens(uint, uint, address[] calldata, address, uint) external returns (uint[] memory);
function getAmountsOut(uint, address[] calldata) external view returns (uint[] memory); // For a value in, it calculates value out
}
interface AggregatorV3Interface {
function latestRoundData() external view returns (uint80 roundId, int256 answer, uint256 startedAt, uint256 updatedAt, uint80 answeredInRound);
}
interface SafetyERC20 {
function transfer(address recipient, uint256 amount) external;
}
contract StabilizeStrategyXUSDArb is Ownable {
using SafeMath for uint256;
using SafeERC20 for IERC20;
using Address for address;
address public treasuryAddress; // Address of the treasury
address public stakingAddress; // Address to the STBZ staking pool
address public zsTokenAddress; // The address of the controlling zs-Token
uint256 constant DIVISION_FACTOR = 100000;
uint256 public lastTradeTime;
uint256 public lastActionBalance; // Balance before last deposit, withdraw or trade
uint256 public percentTradeTrigger = 500; // 0.5% change in value will trigger a trade
uint256 public percentSell = 100000; // 100% of the tokens are sold to the cheapest token
uint256 public maxAmountSell = 200000; // The maximum amount of tokens that can be sold at once
uint256 public percentDepositor = 50000; // 1000 = 1%, depositors earn 50% of all gains
uint256 public percentExecutor = 10000; // 10000 = 10% of WETH goes to executor
uint256 public percentStakers = 50000; // 50% of non-executor WETH goes to stakers, can be changed, rest goes to treasury
uint256 public maxPercentStipend = 30000; // The maximum amount of WETH profit that can be allocated to the executor for gas in percent
uint256 public gasStipend = 1000000; // This is the gas units that are covered by executing a trade taken from the WETH profit
uint256 public minTradeSplit = 20000; // If the balance of ETH is less than or equal to this, it trades the entire balance
uint256 constant minGain = 1e13; // Minimum amount of eth gain (0.00001) before buying WETH and splitting it
bool public safetyMode; // Due to the novelty of the tokens in this pool, one or more of them may decide to fail,
// Make sure strategy can still transfer in case that happens
// Also locks withdraws/deposits/swaps until new strategy is deployed
// Token information
// This strategy accepts multiple stablecoins
// USDN, MUSD, PAX, DUSD, GUSD, BUSD
// All the pools go through USDC to trade between each other
struct TokenInfo {
IERC20 token; // Reference of token
uint256 decimals; // Decimals of token
int128 tokenCurveID; // ID on curve
int128 usdcCurveID; // ID for intermediary token USDC
address curvePoolAddress;
bool useUnderlying;
bool active;
}
TokenInfo[] private tokenList; // An array of tokens accepted as deposits
// Strategy specific variables
address constant WETH_ADDRESS = address(0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2);
address constant SUSHISWAP_ROUTER = address(0xd9e1cE17f2641f24aE83637ab66a2cca9C378B9F); //Address of Sushiswap
address constant GAS_ORACLE_ADDRESS = address(0x169E633A2D1E6c10dD91238Ba11c4A708dfEF37C); // Chainlink address for fast gas oracle
address constant USDC_ADDRESS = address(0xA0b86991c6218b36c1d19D4a2e9Eb0cE3606eB48);
constructor(
address _treasury,
address _staking,
address _zsToken
) public {
treasuryAddress = _treasury;
stakingAddress = _staking;
zsTokenAddress = _zsToken;
setupWithdrawTokens();
}
// Initialization functions
function setupWithdrawTokens() internal {
// USDN, MUSD, PAX, DUSD, GUSD, BUSD
// Start with USDN (by Neutrino)
IERC20 _token = IERC20(address(0x674C6Ad92Fd080e4004b2312b45f796a192D27a0));
tokenList.push(
TokenInfo({
token: _token,
decimals: _token.decimals(),
curvePoolAddress: address(0x0f9cb53Ebe405d49A0bbdBD291A65Ff571bC83e1),
tokenCurveID: 0,
usdcCurveID: 2,
useUnderlying: true,
active: true
})
);
// MUSD from MStable
_token = IERC20(address(0xe2f2a5C287993345a840Db3B0845fbC70f5935a5));
tokenList.push(
TokenInfo({
token: _token,
decimals: _token.decimals(),
curvePoolAddress: address(0x8474DdbE98F5aA3179B3B3F5942D724aFcdec9f6),
tokenCurveID: 0,
usdcCurveID: 2,
useUnderlying: true,
active: true
})
);
// PAX
_token = IERC20(address(0x8E870D67F660D95d5be530380D0eC0bd388289E1));
tokenList.push(
TokenInfo({
token: _token,
decimals: _token.decimals(),
curvePoolAddress: address(0x06364f10B501e868329afBc005b3492902d6C763),
tokenCurveID: 3,
usdcCurveID: 1,
useUnderlying: true,
active: true
})
);
// DUSD by DefiDollar
_token = IERC20(address(0x5BC25f649fc4e26069dDF4cF4010F9f706c23831));
tokenList.push(
TokenInfo({
token: _token,
decimals: _token.decimals(),
curvePoolAddress: address(0x8038C01A0390a8c547446a0b2c18fc9aEFEcc10c),
tokenCurveID: 0,
usdcCurveID: 2,
useUnderlying: true,
active: true
})
);
// GUSD by Gemini
_token = IERC20(address(0x056Fd409E1d7A124BD7017459dFEa2F387b6d5Cd));
tokenList.push(
TokenInfo({
token: _token,
decimals: _token.decimals(),
curvePoolAddress: address(0x4f062658EaAF2C1ccf8C8e36D6824CDf41167956),
tokenCurveID: 0,
usdcCurveID: 2,
useUnderlying: true,
active: true
})
);
// BUSD by Binance
_token = IERC20(address(0x4Fabb145d64652a948d72533023f6E7A623C7C53));
tokenList.push(
TokenInfo({
token: _token,
decimals: _token.decimals(),
curvePoolAddress: address(0x79a8C46DeA5aDa233ABaFFD40F3A0A2B1e5A4F27),
tokenCurveID: 3,
usdcCurveID: 1,
useUnderlying: true,
active: true
})
);
// USDP by Unit
_token = IERC20(address(0x1456688345527bE1f37E9e627DA0837D6f08C925));
tokenList.push(
TokenInfo({
token: _token,
decimals: _token.decimals(),
curvePoolAddress: address(0x42d7025938bEc20B69cBae5A77421082407f053A),
tokenCurveID: 0,
usdcCurveID: 2,
useUnderlying: true,
active: true
})
);
}
// Modifier
modifier onlyZSToken() {
require(zsTokenAddress == _msgSender(), "Call not sent from the zs-Token");
_;
}
// Read functions
function rewardTokensCount() external view returns (uint256) {
return tokenList.length;
}
function rewardTokenAddress(uint256 _pos) external view returns (address) {
require(_pos < tokenList.length,"No token at that position");
return address(tokenList[_pos].token);
}
function rewardTokenActive(uint256 _pos) external view returns (bool) {
require(_pos < tokenList.length,"No token at that position");
return tokenList[_pos].active;
}
function balance() public view returns (uint256) {
return getNormalizedTotalBalance(address(this));
}
function getNormalizedTotalBalance(address _address) public view returns (uint256) {
// Get the balance of the atokens+tokens at this address
uint256 _balance = 0;
uint256 _length = tokenList.length;
for(uint256 i = 0; i < _length; i++){
uint256 _bal = tokenList[i].token.balanceOf(_address);
_bal = _bal.mul(1e18).div(10**tokenList[i].decimals);
_balance = _balance.add(_bal); // This has been normalized to 1e18 decimals
}
return _balance;
}
function withdrawTokenReserves() public view returns (address, uint256) {
(uint256 targetID, uint256 _bal) = withdrawTokenReservesID();
if(_bal == 0){
return (address(0), _bal);
}else{
return (address(tokenList[targetID].token), _bal);
}
}
function withdrawTokenReservesID() internal view returns (uint256, uint256) {
// This function will return the address and amount of the token with the highest balance
uint256 length = tokenList.length;
uint256 targetID = 0;
uint256 targetNormBalance = 0;
for(uint256 i = 0; i < length; i++){
uint256 _normBal = tokenList[i].token.balanceOf(address(this)).mul(1e18).div(10**tokenList[i].decimals);
if(_normBal > 0){
if(targetNormBalance == 0 || _normBal >= targetNormBalance){
targetNormBalance = _normBal;
targetID = i;
}
}
}
if(targetNormBalance > 0){
return (targetID, tokenList[targetID].token.balanceOf(address(this)));
}else{
return (0, 0); // No balance
}
}
// Write functions
function enter() external onlyZSToken {
deposit(false);
}
function exit() external onlyZSToken {
// The ZS token vault is removing all tokens from this strategy
if(safetyMode == true){return;} // Skip withdraw if safety mode is on
withdraw(_msgSender(),1,1, false);
}
function deposit(bool nonContract) public onlyZSToken {
// Only the ZS token can call the function
require(safetyMode == false, "Safety Mode enabled, wait for new strategy deployment");
// No trading is performed on deposit
if(nonContract == true){}
lastActionBalance = balance(); // This action balance represents pool post stablecoin deposit
}
function withdraw(address _depositor, uint256 _share, uint256 _total, bool nonContract) public onlyZSToken returns (uint256) {
require(balance() > 0, "There are no tokens in this strategy");
require(safetyMode == false, "Safety Mode enabled, wait for new strategy deployment");
if(nonContract == true){
if(_share > _total.mul(percentTradeTrigger).div(DIVISION_FACTOR)){
uint256 buyID = getCheapestCurveToken();
(uint256 sellID, ) = withdrawTokenReservesID(); // These may often be the same tokens
checkAndSwapTokens(address(0), sellID, buyID);
}
}
uint256 withdrawAmount = 0;
uint256 _balance = balance();
if(_share < _total){
uint256 _myBalance = _balance.mul(_share).div(_total);
withdrawPerBalance(_depositor, _myBalance, false); // This will withdraw based on token balance
withdrawAmount = _myBalance;
}else{
// We are all shares, transfer all
withdrawPerBalance(_depositor, _balance, true);
withdrawAmount = _balance;
}
lastActionBalance = balance();
return withdrawAmount;
}
// This will withdraw the tokens from the contract based on their balance, from highest balance to lowest
function withdrawPerBalance(address _receiver, uint256 _withdrawAmount, bool _takeAll) internal {
uint256 length = tokenList.length;
if(_takeAll == true){
// Send the entire balance
for(uint256 i = 0; i < length; i++){
uint256 _bal = tokenList[i].token.balanceOf(address(this));
if(_bal > 0){
tokenList[i].token.safeTransfer(_receiver, _bal);
}
}
return;
}
bool[4] memory done;
uint256 targetID = 0;
uint256 targetNormBalance = 0;
for(uint256 i = 0; i < length; i++){
targetNormBalance = 0; // Reset the target balance
// Find the highest balanced token to withdraw
for(uint256 i2 = 0; i2 < length; i2++){
if(done[i2] == false){
uint256 _normBal = tokenList[i2].token.balanceOf(address(this)).mul(1e18).div(10**tokenList[i2].decimals);
if(targetNormBalance == 0 || _normBal >= targetNormBalance){
targetNormBalance = _normBal;
targetID = i2;
}
}
}
done[targetID] = true;
// Determine the balance left
uint256 _normalizedBalance = tokenList[targetID].token.balanceOf(address(this)).mul(1e18).div(10**tokenList[targetID].decimals);
if(_normalizedBalance <= _withdrawAmount){
// Withdraw the entire balance of this token
if(_normalizedBalance > 0){
_withdrawAmount = _withdrawAmount.sub(_normalizedBalance);
tokenList[targetID].token.safeTransfer(_receiver, tokenList[targetID].token.balanceOf(address(this)));
}
}else{
// Withdraw a partial amount of this token
if(_withdrawAmount > 0){
// Convert the withdraw amount to the token's decimal amount
uint256 _balance = _withdrawAmount.mul(10**tokenList[targetID].decimals).div(1e18);
_withdrawAmount = 0;
tokenList[targetID].token.safeTransfer(_receiver, _balance);
}
break; // Nothing more to withdraw
}
}
}
function simulateExchange(uint256 _idIn, uint256 _idOut, uint256 _amount) internal view returns (uint256) {
CurvePool pool = CurvePool(tokenList[_idIn].curvePoolAddress);
if(_idOut == tokenList.length){
// This is special code that says we want WETH out
// Simple Sushiswap route
// Convert to USDC
if(tokenList[_idIn].useUnderlying == true){
_amount = pool.get_dy_underlying(tokenList[_idIn].tokenCurveID, tokenList[_idIn].usdcCurveID, _amount);
}else{
_amount = pool.get_dy(tokenList[_idIn].tokenCurveID, tokenList[_idIn].usdcCurveID, _amount);
}
// Then sell for WETH on Sushiswap
TradeRouter router = TradeRouter(SUSHISWAP_ROUTER);
address[] memory path = new address[](2);
path[0] = USDC_ADDRESS;
path[1] = WETH_ADDRESS;
uint256[] memory estimates = router.getAmountsOut(_amount, path);
_amount = estimates[estimates.length - 1];
return _amount;
}else{
// We will use 2 curve pools to find the prices
// First get USDC
if(tokenList[_idIn].useUnderlying == true){
_amount = pool.get_dy_underlying(tokenList[_idIn].tokenCurveID, tokenList[_idIn].usdcCurveID, _amount);
}else{
_amount = pool.get_dy(tokenList[_idIn].tokenCurveID, tokenList[_idIn].usdcCurveID, _amount);
}
// Then convert to target token
pool = CurvePool(tokenList[_idOut].curvePoolAddress);
if(tokenList[_idOut].useUnderlying == true){
_amount = pool.get_dy_underlying(tokenList[_idOut].usdcCurveID, tokenList[_idOut].tokenCurveID, _amount);
}else{
_amount = pool.get_dy(tokenList[_idOut].usdcCurveID, tokenList[_idOut].tokenCurveID, _amount);
}
return _amount;
}
}
function exchange(uint256 _idIn, uint256 _idOut, uint256 _amount) internal {
CurvePool pool = CurvePool(tokenList[_idIn].curvePoolAddress);
tokenList[_idIn].token.safeApprove(address(pool), 0);
tokenList[_idIn].token.safeApprove(address(pool), _amount);
if(_idOut == tokenList.length){
// This is special code that says we want WETH out
// Simple Sushiswap route
// Convert to USDC
uint256 _before = IERC20(USDC_ADDRESS).balanceOf(address(this));
if(tokenList[_idIn].useUnderlying == true){
pool.exchange_underlying(tokenList[_idIn].tokenCurveID, tokenList[_idIn].usdcCurveID, _amount, 1);
}else{
pool.exchange(tokenList[_idIn].tokenCurveID, tokenList[_idIn].usdcCurveID, _amount, 1);
}
_amount = IERC20(USDC_ADDRESS).balanceOf(address(this)).sub(_before); // Get USDC amount
// Then sell for WETH on Sushiswap
TradeRouter router = TradeRouter(SUSHISWAP_ROUTER);
address[] memory path = new address[](2);
path[0] = USDC_ADDRESS;
path[1] = WETH_ADDRESS;
IERC20(USDC_ADDRESS).safeApprove(SUSHISWAP_ROUTER, 0);
IERC20(USDC_ADDRESS).safeApprove(SUSHISWAP_ROUTER, _amount);
router.swapExactTokensForTokens(_amount, 1, path, address(this), now.add(60)); // Get WETH from token
return;
}else{
// We will use 2 curve pools to find the prices
// First get USDC
uint256 _before = IERC20(USDC_ADDRESS).balanceOf(address(this));
if(tokenList[_idIn].useUnderlying == true){
pool.exchange_underlying(tokenList[_idIn].tokenCurveID, tokenList[_idIn].usdcCurveID, _amount, 1);
}else{
pool.exchange(tokenList[_idIn].tokenCurveID, tokenList[_idIn].usdcCurveID, _amount, 1);
}
_amount = IERC20(USDC_ADDRESS).balanceOf(address(this)).sub(_before); // Get USDC amount
// Then convert to target token
pool = CurvePool(tokenList[_idOut].curvePoolAddress);
IERC20(USDC_ADDRESS).safeApprove(address(pool), 0);
IERC20(USDC_ADDRESS).safeApprove(address(pool), _amount);
if(tokenList[_idOut].useUnderlying == true){
pool.exchange_underlying(tokenList[_idOut].usdcCurveID, tokenList[_idOut].tokenCurveID, _amount, 1);
}else{
pool.exchange(tokenList[_idOut].usdcCurveID, tokenList[_idOut].tokenCurveID, _amount, 1);
}
return;
}
}
function getCheapestCurveToken() internal view returns (uint256) {
// This will give us the ID of the cheapest token in the pool
// We will estimate the return for trading 1000 USDN
// The higher the return, the lower the price of the other token
uint256 targetID = 0;
uint256 usdnAmount = uint256(10).mul(10**tokenList[0].decimals);
uint256 highAmount = usdnAmount;
uint256 length = tokenList.length;
for(uint256 i = 1; i < length; i++){
if(tokenList[i].active == false){ continue; } // Cannot sell an inactive token
uint256 estimate = simulateExchange(0, i, usdnAmount);
// Normalize the estimate into usdn decimals
estimate = estimate.mul(10**tokenList[0].decimals).div(10**tokenList[i].decimals);
if(estimate > highAmount){
// This token is worth less than the usdn
highAmount = estimate;
targetID = i;
}
}
return targetID;
}
function getFastGasPrice() internal view returns (uint256) {
AggregatorV3Interface gasOracle = AggregatorV3Interface(GAS_ORACLE_ADDRESS);
( , int intGasPrice, , , ) = gasOracle.latestRoundData(); // We only want the answer
return uint256(intGasPrice);
}
function estimateSellAtMaximumProfit(uint256 originID, uint256 targetID, uint256 _tokenBalance) internal view returns (uint256) {
// This will estimate the amount that can be sold for the maximum profit possible
// We discover the price then compare it to the actual return
// The return must be positive to return a positive amount
// Discover the price with near 0 slip
uint256 _minAmount = _tokenBalance.mul(percentSell.div(1000)).div(DIVISION_FACTOR);
if(_minAmount == 0){ return 0; } // Nothing to sell, can't calculate
uint256 _minReturn = _minAmount.mul(10**tokenList[targetID].decimals).div(10**tokenList[originID].decimals); // Convert decimals
uint256 _return = simulateExchange(originID, targetID, _minAmount);
if(_return <= _minReturn){
return 0; // We are not going to gain from this trade
}
_return = _return.mul(10**tokenList[originID].decimals).div(10**tokenList[targetID].decimals); // Convert to origin decimals
uint256 _startPrice = _return.mul(1e18).div(_minAmount);
// Now get the price at a higher amount, expected to be lower due to slippage
uint256 _bigAmount = _tokenBalance.mul(percentSell).div(DIVISION_FACTOR);
_return = simulateExchange(originID, targetID, _bigAmount);
_return = _return.mul(10**tokenList[originID].decimals).div(10**tokenList[targetID].decimals); // Convert to origin decimals
uint256 _endPrice = _return.mul(1e18).div(_bigAmount);
if(_endPrice >= _startPrice){
// Really good liquidity
return _bigAmount;
}
// Else calculate amount at max profit
uint256 scaleFactor = uint256(1).mul(10**tokenList[originID].decimals);
uint256 _targetAmount = _startPrice.sub(1e18).mul(scaleFactor).div(_startPrice.sub(_endPrice).mul(scaleFactor).div(_bigAmount.sub(_minAmount))).div(2);
if(_targetAmount > _bigAmount){
// Cannot create an estimate larger than what we want to sell
return _bigAmount;
}
return _targetAmount;
}
function checkAndSwapTokens(address _executor, uint256 _sellID, uint256 _buyID) internal {
if(_sellID == _buyID){return;}
require(_sellID < tokenList.length && _buyID < tokenList.length, "Token ID not found");
require(safetyMode == false, "Unable to swap while in safety mode");
require(tokenList[_sellID].active == true && tokenList[_buyID].active == true, "Token IDs not both active");
// Since this is a gas heavy function, we can reduce the gas by asking executors to select the tokens to swap
// This will likely be the token that is the highest quantity in the strat
lastTradeTime = now;
// Now find our target token to sell into
// Now sell all the other tokens into this token
uint256 _totalBalance = balance(); // Get the token balance at this contract, should increase
bool _expectIncrease = false;
if(_sellID != _buyID){
uint256 sellBalance = 0;
uint256 _tokenBalance = tokenList[_sellID].token.balanceOf(address(this));
uint256 _minTradeTarget = minTradeSplit.mul(10**tokenList[_sellID].decimals);
if(_tokenBalance <= _minTradeTarget){
// If balance is too small,sell all tokens at once
sellBalance = _tokenBalance;
}else{
sellBalance = estimateSellAtMaximumProfit(_sellID, _buyID, _tokenBalance);
}
uint256 _maxTradeTarget = maxAmountSell.mul(10**tokenList[_sellID].decimals);
if(sellBalance > _maxTradeTarget){
sellBalance = _maxTradeTarget;
}
if(sellBalance > 0){
uint256 minReceiveBalance = sellBalance.mul(10**tokenList[_buyID].decimals).div(10**tokenList[_sellID].decimals); // Change to match decimals of destination
uint256 estimate = simulateExchange(_sellID, _buyID, sellBalance);
if(estimate > minReceiveBalance){
_expectIncrease = true;
// We are getting a greater number of tokens, complete the exchange
exchange(_sellID, _buyID, sellBalance);
}
}
}
uint256 _newBalance = balance();
if(_expectIncrease == true){
// There may be rare scenarios where we don't gain any by calling this function
require(_newBalance > _totalBalance, "Failed to gain in balance from selling tokens");
}
uint256 gain = _newBalance.sub(_totalBalance);
IERC20 weth = IERC20(WETH_ADDRESS);
uint256 _wethBalance = weth.balanceOf(address(this));
if(gain >= minGain || _wethBalance > 0){
// Minimum gain required to buy WETH is about 0.01 tokens
if(gain >= minGain){
// Buy WETH from Sushiswap with tokens
uint256 sellBalance = gain.mul(10**tokenList[_buyID].decimals).div(1e18); // Convert to target decimals
sellBalance = sellBalance.mul(uint256(100000).sub(percentDepositor)).div(DIVISION_FACTOR);
if(sellBalance <= tokenList[_buyID].token.balanceOf(address(this))){
// Sell some of our gained token for WETH
exchange(_buyID, tokenList.length, sellBalance);
_wethBalance = weth.balanceOf(address(this));
}
}
if(_wethBalance > 0){
// Split the rest between the stakers and such
// This is pure profit, figure out allocation
// Split the amount sent to the treasury, stakers and executor if one exists
if(_executor != address(0)){
// Executors will get a gas reimbursement in WETH and a percent of the remaining
uint256 maxGasFee = getFastGasPrice().mul(gasStipend); // This is gas stipend in wei
uint256 gasFee = tx.gasprice.mul(gasStipend); // This is gas fee requested
if(gasFee > maxGasFee){
gasFee = maxGasFee; // Gas fee cannot be greater than the maximum
}
uint256 executorAmount = gasFee;
if(gasFee >= _wethBalance.mul(maxPercentStipend).div(DIVISION_FACTOR)){
executorAmount = _wethBalance.mul(maxPercentStipend).div(DIVISION_FACTOR); // The executor will get the entire amount up to point
}else{
// Add the executor percent on top of gas fee
executorAmount = _wethBalance.sub(gasFee).mul(percentExecutor).div(DIVISION_FACTOR).add(gasFee);
}
if(executorAmount > 0){
weth.safeTransfer(_executor, executorAmount);
_wethBalance = weth.balanceOf(address(this)); // Recalculate WETH in contract
}
}
if(_wethBalance > 0){
uint256 stakersAmount = _wethBalance.mul(percentStakers).div(DIVISION_FACTOR);
uint256 treasuryAmount = _wethBalance.sub(stakersAmount);
if(treasuryAmount > 0){
weth.safeTransfer(treasuryAddress, treasuryAmount);
}
if(stakersAmount > 0){
if(stakingAddress != address(0)){
weth.safeTransfer(stakingAddress, stakersAmount);
StabilizeStakingPool(stakingAddress).notifyRewardAmount(stakersAmount);
}else{
// No staking pool selected, just send to the treasury
weth.safeTransfer(treasuryAddress, stakersAmount);
}
}
}
}
}
}
function expectedProfit(bool inWETHForExecutor) external view returns (uint256, uint256, uint256) {
// This view will return the expected profit in wei units that a trading activity will have on the pool
// It will also return the highest profit token ID to sell for the lowest token that that will be bought for that profit
// Now find our target token to sell into
uint256 targetID = getCheapestCurveToken(); // Curve may have a slightly different cheap
uint256 length = tokenList.length;
uint256 sellID = 0;
uint256 largestGain = 0;
// Now sell all the other tokens into this token
//uint256 _normalizedGain = 0;
for(uint256 i = 0; i < length; i++){
if(i != targetID){
if(tokenList[i].active == false){continue;} // Cannot sell an inactive token
uint256 sellBalance = 0;
uint256 _tokenBalance = tokenList[i].token.balanceOf(address(this));
uint256 _minTradeTarget = minTradeSplit.mul(10**tokenList[i].decimals);
if(_tokenBalance <= _minTradeTarget){
// If balance is too small,sell all tokens at once
sellBalance = _tokenBalance;
}else{
sellBalance = estimateSellAtMaximumProfit(i, targetID, _tokenBalance);
}
uint256 _maxTradeTarget = maxAmountSell.mul(10**tokenList[i].decimals);
if(sellBalance > _maxTradeTarget){
sellBalance = _maxTradeTarget;
}
if(sellBalance > 0){
uint256 minReceiveBalance = sellBalance.mul(10**tokenList[targetID].decimals).div(10**tokenList[i].decimals); // Change to match decimals of destination
uint256 estimate = simulateExchange(i, targetID, sellBalance);
if(estimate > minReceiveBalance){
uint256 _gain = estimate.sub(minReceiveBalance).mul(1e18).div(10**tokenList[targetID].decimals); // Normalized gain
//_normalizedGain = _normalizedGain.add(_gain);
if(_gain > largestGain){
// We are only selling 1 token for another 1 token
largestGain = _gain;
sellID = i;
}
}
}
}
}
if(inWETHForExecutor == false){
//return (_normalizedGain, targetID);
return (largestGain, sellID, targetID);
}else{
// Calculate WETH profit
if(largestGain == 0){
return (0, 0, 0);
}
// Calculate how much WETH the executor would make as profit
uint256 estimate = 0;
uint256 sellBalance = largestGain.mul(10**tokenList[targetID].decimals).div(1e18); // Convert to target decimals
sellBalance = sellBalance.mul(uint256(100000).sub(percentDepositor)).div(DIVISION_FACTOR);
// Estimate output
if(sellBalance > 0){
estimate = simulateExchange(targetID, tokenList.length, sellBalance);
}
// Now calculate the amount going to the executor
uint256 gasFee = getFastGasPrice().mul(gasStipend); // This is gas stipend in wei
if(gasFee >= estimate.mul(maxPercentStipend).div(DIVISION_FACTOR)){ // Max percent of total
return (estimate.mul(maxPercentStipend).div(DIVISION_FACTOR), sellID, targetID); // The executor will get max percent of total
}else{
estimate = estimate.sub(gasFee); // Subtract fee from remaining balance
return (estimate.mul(percentExecutor).div(DIVISION_FACTOR).add(gasFee), sellID, targetID); // Executor amount with fee added
}
}
}
function executorSwapTokens(address _executor, uint256 _minSecSinceLastTrade, uint256 _sellID, uint256 _buyID) external {
// Function designed to promote trading with incentive. Users get percentage of WETH from profitable trades
require(now.sub(lastTradeTime) >= _minSecSinceLastTrade, "The last trade was too recent");
require(_msgSender() == tx.origin, "Contracts cannot interact with this function");
checkAndSwapTokens(_executor, _sellID, _buyID);
}
// Governance functions
function governanceSwapTokens(uint256 _sellID, uint256 _buyID) external onlyGovernance {
// This is function that force trade tokens at anytime. It can only be called by governance
checkAndSwapTokens(_msgSender(), _sellID, _buyID);
}
function activateSafetyMode() external onlyGovernance {
require(safetyMode == false, "Safety mode already active");
// This function will attempt to transfer tokens to itself and if that fails it will go into safety mode
uint256 length = tokenList.length;
for(uint256 i = 0; i < length; i++){
uint256 _bal = tokenList[i].token.balanceOf(address(this));
if(_bal > 0){
try SafetyERC20(address(tokenList[i].token)).transfer(address(this), _bal) {}
catch {
safetyMode = true;
return;
}
}
}
}
// Timelock variables
uint256 private _timelockStart; // The start of the timelock to change governance variables
uint256 private _timelockType; // The function that needs to be changed
uint256 constant TIMELOCK_DURATION = 86400; // Timelock is 24 hours
// Reusable timelock variables
address private _timelock_address;
address private _timelock_address_2;
uint256[6] private _timelock_data;
modifier timelockConditionsMet(uint256 _type) {
require(_timelockType == _type, "Timelock not acquired for this function");
_timelockType = 0; // Reset the type once the timelock is used
if(balance() > 0){ // Timelock only applies when balance exists
require(now >= _timelockStart + TIMELOCK_DURATION, "Timelock time not met");
}
_;
}
// Change the owner of the token contract
// --------------------
function startGovernanceChange(address _address) external onlyGovernance {
_timelockStart = now;
_timelockType = 1;
_timelock_address = _address;
}
function finishGovernanceChange() external onlyGovernance timelockConditionsMet(1) {
transferGovernance(_timelock_address);
}
// --------------------
// Change the treasury address
// --------------------
function startChangeTreasury(address _address) external onlyGovernance {
_timelockStart = now;
_timelockType = 2;
_timelock_address = _address;
}
function finishChangeTreasury() external onlyGovernance timelockConditionsMet(2) {
treasuryAddress = _timelock_address;
}
// --------------------
// Change the staking address
// --------------------
function startChangeStakingPool(address _address) external onlyGovernance {
_timelockStart = now;
_timelockType = 3;
_timelock_address = _address;
}
function finishChangeStakingPool() external onlyGovernance timelockConditionsMet(3) {
stakingAddress = _timelock_address;
}
// --------------------
// Change the zsToken address
// --------------------
function startChangeZSToken(address _address) external onlyGovernance {
_timelockStart = now;
_timelockType = 4;
_timelock_address = _address;
}
function finishChangeZSToken() external onlyGovernance timelockConditionsMet(4) {
zsTokenAddress = _timelock_address;
}
// --------------------
// Change the trading conditions used by the strategy
// --------------------
function startChangeTradingConditions(uint256 _pTradeTrigger, uint256 _pSellPercent,
uint256 _minSplit, uint256 _maxStipend,
uint256 _pMaxStipend, uint256 _maxSell) external onlyGovernance {
// Changes a lot of trading parameters in one call
require(_pTradeTrigger <= 100000 && _pSellPercent <= 100000 && _pMaxStipend <= 100000,"Percent cannot be greater than 100%");
_timelockStart = now;
_timelockType = 5;
_timelock_data[0] = _pTradeTrigger;
_timelock_data[1] = _pSellPercent;
_timelock_data[2] = _minSplit;
_timelock_data[3] = _maxStipend;
_timelock_data[4] = _pMaxStipend;
_timelock_data[5] = _maxSell;
}
function finishChangeTradingConditions() external onlyGovernance timelockConditionsMet(5) {
percentTradeTrigger = _timelock_data[0];
percentSell = _timelock_data[1];
minTradeSplit = _timelock_data[2];
gasStipend = _timelock_data[3];
maxPercentStipend = _timelock_data[4];
maxAmountSell = _timelock_data[5];
}
// --------------------
// Change the strategy allocations between the parties
// --------------------
function startChangeStrategyAllocations(uint256 _pDepositors, uint256 _pExecutor, uint256 _pStakers) external onlyGovernance {
// Changes strategy allocations in one call
require(_pDepositors <= 100000 && _pExecutor <= 100000 && _pStakers <= 100000,"Percent cannot be greater than 100%");
_timelockStart = now;
_timelockType = 6;
_timelock_data[0] = _pDepositors;
_timelock_data[1] = _pExecutor;
_timelock_data[2] = _pStakers;
}
function finishChangeStrategyAllocations() external onlyGovernance timelockConditionsMet(6) {
percentDepositor = _timelock_data[0];
percentExecutor = _timelock_data[1];
percentStakers = _timelock_data[2];
}
// --------------------
// Recover trapped tokens
// --------------------
function startRecoverStuckTokens(address _token, uint256 _amount) external onlyGovernance {
require(safetyMode == true, "Cannot execute this function unless safety mode active");
_timelockStart = now;
_timelockType = 7;
_timelock_address = _token;
_timelock_data[0] = _amount;
}
function finishRecoverStuckTokens() external onlyGovernance timelockConditionsMet(7) {
IERC20(_timelock_address).safeTransfer(governance(), _timelock_data[0]);
}
// Add a new token to the strategy
// --------------------
function startAddNewStableToken(address _tokenAddress, address _curvePool, uint256 _curveID, uint256 _usdcID, uint256 _underlying) external onlyGovernance {
_timelockStart = now;
_timelockType = 8;
_timelock_address = _tokenAddress;
_timelock_address_2 = _curvePool;
_timelock_data[0] = _curveID;
_timelock_data[1] = _usdcID;
_timelock_data[2] = _underlying;
}
function finishAddNewStableToken() external onlyGovernance timelockConditionsMet(8) {
IERC20 _token = IERC20(address(_timelock_address));
bool underlying = true;
if(_timelock_data[2] == 0){
underlying = false;
}
tokenList.push(
TokenInfo({
token: _token,
decimals: _token.decimals(),
curvePoolAddress: _timelock_address_2,
tokenCurveID: int128(_timelock_data[0]),
usdcCurveID: int128(_timelock_data[1]),
active: true,
useUnderlying: underlying
})
);
uint256 id = tokenList.length - 1;
// Verify the new token will work
simulateExchange(id, 0, uint256(1).mul(10**tokenList[id].decimals));
}
// Deactivate a token from trading
// --------------------
function startDeactivateToken(uint256 _id) external onlyGovernance {
_timelockStart = now;
_timelockType = 9;
_timelock_data[0] = _id;
}
function finishDeactivateToken() external onlyGovernance timelockConditionsMet(9) {
tokenList[_timelock_data[0]].active = false;
}
}
|
This view will return the expected profit in wei units that a trading activity will have on the pool It will also return the highest profit token ID to sell for the lowest token that that will be bought for that profit Now find our target token to sell into Now sell all the other tokens into this tokenuint256 _normalizedGain = 0; If balance is too small,sell all tokens at once_normalizedGain = _normalizedGain.add(_gain); We are only selling 1 token for another 1 tokenreturn (_normalizedGain, targetID); Calculate WETH profit Estimate output
|
function expectedProfit(bool inWETHForExecutor) external view returns (uint256, uint256, uint256) {
uint256 length = tokenList.length;
uint256 sellID = 0;
uint256 largestGain = 0;
for(uint256 i = 0; i < length; i++){
if(i != targetID){
uint256 sellBalance = 0;
uint256 _tokenBalance = tokenList[i].token.balanceOf(address(this));
uint256 _minTradeTarget = minTradeSplit.mul(10**tokenList[i].decimals);
if(_tokenBalance <= _minTradeTarget){
sellBalance = _tokenBalance;
sellBalance = estimateSellAtMaximumProfit(i, targetID, _tokenBalance);
}
uint256 _maxTradeTarget = maxAmountSell.mul(10**tokenList[i].decimals);
if(sellBalance > _maxTradeTarget){
sellBalance = _maxTradeTarget;
}
if(sellBalance > 0){
uint256 estimate = simulateExchange(i, targetID, sellBalance);
if(estimate > minReceiveBalance){
if(_gain > largestGain){
largestGain = _gain;
sellID = i;
}
}
}
}
}
if(inWETHForExecutor == false){
return (largestGain, sellID, targetID);
if(largestGain == 0){
return (0, 0, 0);
}
sellBalance = sellBalance.mul(uint256(100000).sub(percentDepositor)).div(DIVISION_FACTOR);
if(sellBalance > 0){
estimate = simulateExchange(targetID, tokenList.length, sellBalance);
}
}
}
| 6,170,923 |
// SPDX-License-Identifier: UNLICENSE
pragma solidity ^0.8.0;
import "@openzeppelin/contracts/access/Ownable.sol";
import "@openzeppelin/contracts/security/ReentrancyGuard.sol";
import "@openzeppelin/contracts/token/ERC721/ERC721.sol";
import "@openzeppelin/contracts/token/ERC721/extensions/ERC721Enumerable.sol";
import "@openzeppelin/contracts/utils/Counters.sol";
import "@openzeppelin/contracts/utils/Strings.sol";
contract CryptoPhunksV2 is Ownable, ERC721Enumerable, ReentrancyGuard {
using Counters for Counters.Counter;
using Strings for uint256;
// You can use this hash to verify the image file containing all the phunks
string public constant imageHash =
"122dab9670c21ad538dafdbb87191c4d7114c389af616c42c54556aa2211b899";
constructor() ERC721("CryptoPhunksV2", "PHUNK") {}
bool public isSaleOn = false;
bool public saleHasBeenStarted = false;
uint256 public constant MAX_MINTABLE_AT_ONCE = 50;
uint256[10000] private _availableTokens;
uint256 private _numAvailableTokens = 10000;
uint256 private _numFreeRollsGiven = 0;
mapping(address => uint256) public freeRollPhunks;
uint256 private _lastTokenIdMintedInInitialSet = 10000;
function numTotalPhunks() public view virtual returns (uint256) {
return 10000;
}
function freeRollMint() public nonReentrant() {
uint256 toMint = freeRollPhunks[msg.sender];
freeRollPhunks[msg.sender] = 0;
uint256 remaining = numTotalPhunks() - totalSupply();
if (toMint > remaining) {
toMint = remaining;
}
_mint(toMint);
}
function getNumFreeRollPhunks(address owner) public view returns (uint256) {
return freeRollPhunks[owner];
}
function mint(uint256 _numToMint) public payable nonReentrant() {
require(isSaleOn, "Sale hasn't started.");
uint256 totalSupply = totalSupply();
require(
totalSupply + _numToMint <= numTotalPhunks(),
"There aren't this many phunks left."
);
uint256 costForMintingPhunks = getCostForMintingPhunks(_numToMint);
require(
msg.value >= costForMintingPhunks,
"Too little sent, please send more eth."
);
if (msg.value > costForMintingPhunks) {
payable(msg.sender).transfer(msg.value - costForMintingPhunks);
}
_mint(_numToMint);
}
// internal minting function
function _mint(uint256 _numToMint) internal {
require(_numToMint <= MAX_MINTABLE_AT_ONCE, "Minting too many at once.");
uint256 updatedNumAvailableTokens = _numAvailableTokens;
for (uint256 i = 0; i < _numToMint; i++) {
uint256 newTokenId = useRandomAvailableToken(_numToMint, i);
_safeMint(msg.sender, newTokenId);
updatedNumAvailableTokens--;
}
_numAvailableTokens = updatedNumAvailableTokens;
}
function useRandomAvailableToken(uint256 _numToFetch, uint256 _i)
internal
returns (uint256)
{
uint256 randomNum =
uint256(
keccak256(
abi.encode(
msg.sender,
tx.gasprice,
block.number,
block.timestamp,
blockhash(block.number - 1),
_numToFetch,
_i
)
)
);
uint256 randomIndex = randomNum % _numAvailableTokens;
return useAvailableTokenAtIndex(randomIndex);
}
function useAvailableTokenAtIndex(uint256 indexToUse)
internal
returns (uint256)
{
uint256 valAtIndex = _availableTokens[indexToUse];
uint256 result;
if (valAtIndex == 0) {
// This means the index itself is still an available token
result = indexToUse;
} else {
// This means the index itself is not an available token, but the val at that index is.
result = valAtIndex;
}
uint256 lastIndex = _numAvailableTokens - 1;
if (indexToUse != lastIndex) {
// Replace the value at indexToUse, now that it's been used.
// Replace it with the data from the last index in the array, since we are going to decrease the array size afterwards.
uint256 lastValInArray = _availableTokens[lastIndex];
if (lastValInArray == 0) {
// This means the index itself is still an available token
_availableTokens[indexToUse] = lastIndex;
} else {
// This means the index itself is not an available token, but the val at that index is.
_availableTokens[indexToUse] = lastValInArray;
}
}
_numAvailableTokens--;
return result;
}
function getCostForMintingPhunks(uint256 _numToMint)
public
view
returns (uint256)
{
require(
totalSupply() + _numToMint <= numTotalPhunks(),
"There aren't this many phunks left."
);
if (_numToMint == 1) {
return 0.02 ether;
} else if (_numToMint == 3) {
return 0.05 ether;
} else if (_numToMint == 5) {
return 0.07 ether;
} else if (_numToMint == 10) {
return 0.10 ether;
} else {
revert("Unsupported mint amount");
}
}
function getPhunksBelongingToOwner(address _owner)
external
view
returns (uint256[] memory)
{
uint256 numPhunks = balanceOf(_owner);
if (numPhunks == 0) {
return new uint256[](0);
} else {
uint256[] memory result = new uint256[](numPhunks);
for (uint256 i = 0; i < numPhunks; i++) {
result[i] = tokenOfOwnerByIndex(_owner, i);
}
return result;
}
}
/*
* Dev stuff.
*/
// metadata URI
string private _baseTokenURI;
function _baseURI() internal view virtual override returns (string memory) {
return _baseTokenURI;
}
function tokenURI(uint256 _tokenId)
public
view
override
returns (string memory)
{
string memory base = _baseURI();
string memory _tokenURI = Strings.toString(_tokenId);
// If there is no base URI, return the token URI.
if (bytes(base).length == 0) {
return _tokenURI;
}
return string(abi.encodePacked(base, _tokenURI));
}
// contract metadata URI for opensea
string public contractURI;
/*
* Owner stuff
*/
function startSale() public onlyOwner {
isSaleOn = true;
saleHasBeenStarted = true;
}
function endSale() public onlyOwner {
isSaleOn = false;
}
function giveFreeRoll(address receiver) public onlyOwner {
// max number of free mints we can give to the community for promotions/marketing
require(_numFreeRollsGiven < 200, "already given max number of free rolls");
uint256 freeRolls = freeRollPhunks[receiver];
freeRollPhunks[receiver] = freeRolls + 1;
_numFreeRollsGiven = _numFreeRollsGiven + 1;
}
// for handing out free rolls to v1 phunk owners
// details on seeding info here: https://gist.github.com/cryptophunks/7f542feaee510e12464da3bb2a922713
function seedFreeRolls(
address[] memory tokenOwners,
uint256[] memory numOfFreeRolls
) public onlyOwner {
require(
!saleHasBeenStarted,
"cannot seed free rolls after sale has started"
);
require(
tokenOwners.length == numOfFreeRolls.length,
"tokenOwners does not match numOfFreeRolls length"
);
// light check to make sure the proper values are being passed
require(numOfFreeRolls[0] <= 3, "cannot give more than 3 free rolls");
for (uint256 i = 0; i < tokenOwners.length; i++) {
freeRollPhunks[tokenOwners[i]] = numOfFreeRolls[i];
}
}
// for seeding the v2 contract with v1 state
// details on seeding info here: https://gist.github.com/cryptophunks/7f542feaee510e12464da3bb2a922713
function seedInitialContractState(
address[] memory tokenOwners,
uint256[] memory tokens
) public onlyOwner {
require(
!saleHasBeenStarted,
"cannot initial phunk mint if sale has started"
);
require(
tokenOwners.length == tokens.length,
"tokenOwners does not match tokens length"
);
uint256 lastTokenIdMintedInInitialSetCopy = _lastTokenIdMintedInInitialSet;
for (uint256 i = 0; i < tokenOwners.length; i++) {
uint256 token = tokens[i];
require(
lastTokenIdMintedInInitialSetCopy > token,
"initial phunk mints must be in decreasing order for our availableToken index to work"
);
lastTokenIdMintedInInitialSetCopy = token;
useAvailableTokenAtIndex(token);
_safeMint(tokenOwners[i], token);
}
_lastTokenIdMintedInInitialSet = lastTokenIdMintedInInitialSetCopy;
}
// URIs
function setBaseURI(string memory baseURI) external onlyOwner {
_baseTokenURI = baseURI;
}
function setContractURI(string memory _contractURI) external onlyOwner {
contractURI = _contractURI;
}
function withdrawMoney() public payable onlyOwner {
(bool success, ) = msg.sender.call{value: address(this).balance}("");
require(success, "Transfer failed.");
}
function _beforeTokenTransfer(
address from,
address to,
uint256 tokenId
) internal virtual override(ERC721Enumerable) {
super._beforeTokenTransfer(from, to, tokenId);
}
function supportsInterface(bytes4 interfaceId)
public
view
virtual
override(ERC721Enumerable)
returns (bool)
{
return super.supportsInterface(interfaceId);
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import "../utils/Context.sol";
/**
* @dev Contract module which provides a basic access control mechanism, where
* there is an account (an owner) that can be granted exclusive access to
* specific functions.
*
* By default, the owner account will be the one that deploys the contract. This
* can later be changed with {transferOwnership}.
*
* This module is used through inheritance. It will make available the modifier
* `onlyOwner`, which can be applied to your functions to restrict their use to
* the owner.
*/
abstract contract Ownable is Context {
address private _owner;
event OwnershipTransferred(address indexed previousOwner, address indexed newOwner);
/**
* @dev Initializes the contract setting the deployer as the initial owner.
*/
constructor () {
address msgSender = _msgSender();
_owner = msgSender;
emit OwnershipTransferred(address(0), msgSender);
}
/**
* @dev Returns the address of the current owner.
*/
function owner() public view virtual returns (address) {
return _owner;
}
/**
* @dev Throws if called by any account other than the owner.
*/
modifier onlyOwner() {
require(owner() == _msgSender(), "Ownable: caller is not the owner");
_;
}
/**
* @dev Leaves the contract without owner. It will not be possible to call
* `onlyOwner` functions anymore. Can only be called by the current owner.
*
* NOTE: Renouncing ownership will leave the contract without an owner,
* thereby removing any functionality that is only available to the owner.
*/
function renounceOwnership() public virtual onlyOwner {
emit OwnershipTransferred(_owner, address(0));
_owner = address(0);
}
/**
* @dev Transfers ownership of the contract to a new account (`newOwner`).
* Can only be called by the current owner.
*/
function transferOwnership(address newOwner) public virtual onlyOwner {
require(newOwner != address(0), "Ownable: new owner is the zero address");
emit OwnershipTransferred(_owner, newOwner);
_owner = newOwner;
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
/**
* @dev Contract module that helps prevent reentrant calls to a function.
*
* Inheriting from `ReentrancyGuard` will make the {nonReentrant} modifier
* available, which can be applied to functions to make sure there are no nested
* (reentrant) calls to them.
*
* Note that because there is a single `nonReentrant` guard, functions marked as
* `nonReentrant` may not call one another. This can be worked around by making
* those functions `private`, and then adding `external` `nonReentrant` entry
* points to them.
*
* TIP: If you would like to learn more about reentrancy and alternative ways
* to protect against it, check out our blog post
* https://blog.openzeppelin.com/reentrancy-after-istanbul/[Reentrancy After Istanbul].
*/
abstract contract ReentrancyGuard {
// Booleans are more expensive than uint256 or any type that takes up a full
// word because each write operation emits an extra SLOAD to first read the
// slot's contents, replace the bits taken up by the boolean, and then write
// back. This is the compiler's defense against contract upgrades and
// pointer aliasing, and it cannot be disabled.
// The values being non-zero value makes deployment a bit more expensive,
// but in exchange the refund on every call to nonReentrant will be lower in
// amount. Since refunds are capped to a percentage of the total
// transaction's gas, it is best to keep them low in cases like this one, to
// increase the likelihood of the full refund coming into effect.
uint256 private constant _NOT_ENTERED = 1;
uint256 private constant _ENTERED = 2;
uint256 private _status;
constructor () {
_status = _NOT_ENTERED;
}
/**
* @dev Prevents a contract from calling itself, directly or indirectly.
* Calling a `nonReentrant` function from another `nonReentrant`
* function is not supported. It is possible to prevent this from happening
* by making the `nonReentrant` function external, and make it call a
* `private` function that does the actual work.
*/
modifier nonReentrant() {
// On the first call to nonReentrant, _notEntered will be true
require(_status != _ENTERED, "ReentrancyGuard: reentrant call");
// Any calls to nonReentrant after this point will fail
_status = _ENTERED;
_;
// By storing the original value once again, a refund is triggered (see
// https://eips.ethereum.org/EIPS/eip-2200)
_status = _NOT_ENTERED;
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import "./IERC721.sol";
import "./IERC721Receiver.sol";
import "./extensions/IERC721Metadata.sol";
import "../../utils/Address.sol";
import "../../utils/Context.sol";
import "../../utils/Strings.sol";
import "../../utils/introspection/ERC165.sol";
/**
* @dev Implementation of https://eips.ethereum.org/EIPS/eip-721[ERC721] Non-Fungible Token Standard, including
* the Metadata extension, but not including the Enumerable extension, which is available separately as
* {ERC721Enumerable}.
*/
contract ERC721 is Context, ERC165, IERC721, IERC721Metadata {
using Address for address;
using Strings for uint256;
// Token name
string private _name;
// Token symbol
string private _symbol;
// Mapping from token ID to owner address
mapping (uint256 => address) private _owners;
// Mapping owner address to token count
mapping (address => uint256) private _balances;
// Mapping from token ID to approved address
mapping (uint256 => address) private _tokenApprovals;
// Mapping from owner to operator approvals
mapping (address => mapping (address => bool)) private _operatorApprovals;
/**
* @dev Initializes the contract by setting a `name` and a `symbol` to the token collection.
*/
constructor (string memory name_, string memory symbol_) {
_name = name_;
_symbol = symbol_;
}
/**
* @dev See {IERC165-supportsInterface}.
*/
function supportsInterface(bytes4 interfaceId) public view virtual override(ERC165, IERC165) returns (bool) {
return interfaceId == type(IERC721).interfaceId
|| interfaceId == type(IERC721Metadata).interfaceId
|| super.supportsInterface(interfaceId);
}
/**
* @dev See {IERC721-balanceOf}.
*/
function balanceOf(address owner) public view virtual override returns (uint256) {
require(owner != address(0), "ERC721: balance query for the zero address");
return _balances[owner];
}
/**
* @dev See {IERC721-ownerOf}.
*/
function ownerOf(uint256 tokenId) public view virtual override returns (address) {
address owner = _owners[tokenId];
require(owner != address(0), "ERC721: owner query for nonexistent token");
return owner;
}
/**
* @dev See {IERC721Metadata-name}.
*/
function name() public view virtual override returns (string memory) {
return _name;
}
/**
* @dev See {IERC721Metadata-symbol}.
*/
function symbol() public view virtual override returns (string memory) {
return _symbol;
}
/**
* @dev See {IERC721Metadata-tokenURI}.
*/
function tokenURI(uint256 tokenId) public view virtual override returns (string memory) {
require(_exists(tokenId), "ERC721Metadata: URI query for nonexistent token");
string memory baseURI = _baseURI();
return bytes(baseURI).length > 0
? string(abi.encodePacked(baseURI, tokenId.toString()))
: '';
}
/**
* @dev Base URI for computing {tokenURI}. Empty by default, can be overriden
* in child contracts.
*/
function _baseURI() internal view virtual returns (string memory) {
return "";
}
/**
* @dev See {IERC721-approve}.
*/
function approve(address to, uint256 tokenId) public virtual override {
address owner = ERC721.ownerOf(tokenId);
require(to != owner, "ERC721: approval to current owner");
require(_msgSender() == owner || isApprovedForAll(owner, _msgSender()),
"ERC721: approve caller is not owner nor approved for all"
);
_approve(to, tokenId);
}
/**
* @dev See {IERC721-getApproved}.
*/
function getApproved(uint256 tokenId) public view virtual override returns (address) {
require(_exists(tokenId), "ERC721: approved query for nonexistent token");
return _tokenApprovals[tokenId];
}
/**
* @dev See {IERC721-setApprovalForAll}.
*/
function setApprovalForAll(address operator, bool approved) public virtual override {
require(operator != _msgSender(), "ERC721: approve to caller");
_operatorApprovals[_msgSender()][operator] = approved;
emit ApprovalForAll(_msgSender(), operator, approved);
}
/**
* @dev See {IERC721-isApprovedForAll}.
*/
function isApprovedForAll(address owner, address operator) public view virtual override returns (bool) {
return _operatorApprovals[owner][operator];
}
/**
* @dev See {IERC721-transferFrom}.
*/
function transferFrom(address from, address to, uint256 tokenId) public virtual override {
//solhint-disable-next-line max-line-length
require(_isApprovedOrOwner(_msgSender(), tokenId), "ERC721: transfer caller is not owner nor approved");
_transfer(from, to, tokenId);
}
/**
* @dev See {IERC721-safeTransferFrom}.
*/
function safeTransferFrom(address from, address to, uint256 tokenId) public virtual override {
safeTransferFrom(from, to, tokenId, "");
}
/**
* @dev See {IERC721-safeTransferFrom}.
*/
function safeTransferFrom(address from, address to, uint256 tokenId, bytes memory _data) public virtual override {
require(_isApprovedOrOwner(_msgSender(), tokenId), "ERC721: transfer caller is not owner nor approved");
_safeTransfer(from, to, tokenId, _data);
}
/**
* @dev Safely transfers `tokenId` token from `from` to `to`, checking first that contract recipients
* are aware of the ERC721 protocol to prevent tokens from being forever locked.
*
* `_data` is additional data, it has no specified format and it is sent in call to `to`.
*
* This internal function is equivalent to {safeTransferFrom}, and can be used to e.g.
* implement alternative mechanisms to perform token transfer, such as signature-based.
*
* Requirements:
*
* - `from` cannot be the zero address.
* - `to` cannot be the zero address.
* - `tokenId` token must exist and be owned by `from`.
* - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer.
*
* Emits a {Transfer} event.
*/
function _safeTransfer(address from, address to, uint256 tokenId, bytes memory _data) internal virtual {
_transfer(from, to, tokenId);
require(_checkOnERC721Received(from, to, tokenId, _data), "ERC721: transfer to non ERC721Receiver implementer");
}
/**
* @dev Returns whether `tokenId` exists.
*
* Tokens can be managed by their owner or approved accounts via {approve} or {setApprovalForAll}.
*
* Tokens start existing when they are minted (`_mint`),
* and stop existing when they are burned (`_burn`).
*/
function _exists(uint256 tokenId) internal view virtual returns (bool) {
return _owners[tokenId] != address(0);
}
/**
* @dev Returns whether `spender` is allowed to manage `tokenId`.
*
* Requirements:
*
* - `tokenId` must exist.
*/
function _isApprovedOrOwner(address spender, uint256 tokenId) internal view virtual returns (bool) {
require(_exists(tokenId), "ERC721: operator query for nonexistent token");
address owner = ERC721.ownerOf(tokenId);
return (spender == owner || getApproved(tokenId) == spender || isApprovedForAll(owner, spender));
}
/**
* @dev Safely mints `tokenId` and transfers it to `to`.
*
* Requirements:
*
* - `tokenId` must not exist.
* - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer.
*
* Emits a {Transfer} event.
*/
function _safeMint(address to, uint256 tokenId) internal virtual {
_safeMint(to, tokenId, "");
}
/**
* @dev Same as {xref-ERC721-_safeMint-address-uint256-}[`_safeMint`], with an additional `data` parameter which is
* forwarded in {IERC721Receiver-onERC721Received} to contract recipients.
*/
function _safeMint(address to, uint256 tokenId, bytes memory _data) internal virtual {
_mint(to, tokenId);
require(_checkOnERC721Received(address(0), to, tokenId, _data), "ERC721: transfer to non ERC721Receiver implementer");
}
/**
* @dev Mints `tokenId` and transfers it to `to`.
*
* WARNING: Usage of this method is discouraged, use {_safeMint} whenever possible
*
* Requirements:
*
* - `tokenId` must not exist.
* - `to` cannot be the zero address.
*
* Emits a {Transfer} event.
*/
function _mint(address to, uint256 tokenId) internal virtual {
require(to != address(0), "ERC721: mint to the zero address");
require(!_exists(tokenId), "ERC721: token already minted");
_beforeTokenTransfer(address(0), to, tokenId);
_balances[to] += 1;
_owners[tokenId] = to;
emit Transfer(address(0), to, tokenId);
}
/**
* @dev Destroys `tokenId`.
* The approval is cleared when the token is burned.
*
* Requirements:
*
* - `tokenId` must exist.
*
* Emits a {Transfer} event.
*/
function _burn(uint256 tokenId) internal virtual {
address owner = ERC721.ownerOf(tokenId);
_beforeTokenTransfer(owner, address(0), tokenId);
// Clear approvals
_approve(address(0), tokenId);
_balances[owner] -= 1;
delete _owners[tokenId];
emit Transfer(owner, address(0), tokenId);
}
/**
* @dev Transfers `tokenId` from `from` to `to`.
* As opposed to {transferFrom}, this imposes no restrictions on msg.sender.
*
* Requirements:
*
* - `to` cannot be the zero address.
* - `tokenId` token must be owned by `from`.
*
* Emits a {Transfer} event.
*/
function _transfer(address from, address to, uint256 tokenId) internal virtual {
require(ERC721.ownerOf(tokenId) == from, "ERC721: transfer of token that is not own");
require(to != address(0), "ERC721: transfer to the zero address");
_beforeTokenTransfer(from, to, tokenId);
// Clear approvals from the previous owner
_approve(address(0), tokenId);
_balances[from] -= 1;
_balances[to] += 1;
_owners[tokenId] = to;
emit Transfer(from, to, tokenId);
}
/**
* @dev Approve `to` to operate on `tokenId`
*
* Emits a {Approval} event.
*/
function _approve(address to, uint256 tokenId) internal virtual {
_tokenApprovals[tokenId] = to;
emit Approval(ERC721.ownerOf(tokenId), to, tokenId);
}
/**
* @dev Internal function to invoke {IERC721Receiver-onERC721Received} on a target address.
* The call is not executed if the target address is not a contract.
*
* @param from address representing the previous owner of the given token ID
* @param to target address that will receive the tokens
* @param tokenId uint256 ID of the token to be transferred
* @param _data bytes optional data to send along with the call
* @return bool whether the call correctly returned the expected magic value
*/
function _checkOnERC721Received(address from, address to, uint256 tokenId, bytes memory _data)
private returns (bool)
{
if (to.isContract()) {
try IERC721Receiver(to).onERC721Received(_msgSender(), from, tokenId, _data) returns (bytes4 retval) {
return retval == IERC721Receiver(to).onERC721Received.selector;
} catch (bytes memory reason) {
if (reason.length == 0) {
revert("ERC721: transfer to non ERC721Receiver implementer");
} else {
// solhint-disable-next-line no-inline-assembly
assembly {
revert(add(32, reason), mload(reason))
}
}
}
} else {
return true;
}
}
/**
* @dev Hook that is called before any token transfer. This includes minting
* and burning.
*
* Calling conditions:
*
* - When `from` and `to` are both non-zero, ``from``'s `tokenId` will be
* transferred to `to`.
* - When `from` is zero, `tokenId` will be minted for `to`.
* - When `to` is zero, ``from``'s `tokenId` will be burned.
* - `from` cannot be the zero address.
* - `to` cannot be the zero address.
*
* To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks].
*/
function _beforeTokenTransfer(address from, address to, uint256 tokenId) internal virtual { }
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import "../ERC721.sol";
import "./IERC721Enumerable.sol";
/**
* @dev This implements an optional extension of {ERC721} defined in the EIP that adds
* enumerability of all the token ids in the contract as well as all token ids owned by each
* account.
*/
abstract contract ERC721Enumerable is ERC721, IERC721Enumerable {
// Mapping from owner to list of owned token IDs
mapping(address => mapping(uint256 => uint256)) private _ownedTokens;
// Mapping from token ID to index of the owner tokens list
mapping(uint256 => uint256) private _ownedTokensIndex;
// Array with all token ids, used for enumeration
uint256[] private _allTokens;
// Mapping from token id to position in the allTokens array
mapping(uint256 => uint256) private _allTokensIndex;
/**
* @dev See {IERC165-supportsInterface}.
*/
function supportsInterface(bytes4 interfaceId) public view virtual override(IERC165, ERC721) returns (bool) {
return interfaceId == type(IERC721Enumerable).interfaceId
|| super.supportsInterface(interfaceId);
}
/**
* @dev See {IERC721Enumerable-tokenOfOwnerByIndex}.
*/
function tokenOfOwnerByIndex(address owner, uint256 index) public view virtual override returns (uint256) {
require(index < ERC721.balanceOf(owner), "ERC721Enumerable: owner index out of bounds");
return _ownedTokens[owner][index];
}
/**
* @dev See {IERC721Enumerable-totalSupply}.
*/
function totalSupply() public view virtual override returns (uint256) {
return _allTokens.length;
}
/**
* @dev See {IERC721Enumerable-tokenByIndex}.
*/
function tokenByIndex(uint256 index) public view virtual override returns (uint256) {
require(index < ERC721Enumerable.totalSupply(), "ERC721Enumerable: global index out of bounds");
return _allTokens[index];
}
/**
* @dev Hook that is called before any token transfer. This includes minting
* and burning.
*
* Calling conditions:
*
* - When `from` and `to` are both non-zero, ``from``'s `tokenId` will be
* transferred to `to`.
* - When `from` is zero, `tokenId` will be minted for `to`.
* - When `to` is zero, ``from``'s `tokenId` will be burned.
* - `from` cannot be the zero address.
* - `to` cannot be the zero address.
*
* To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks].
*/
function _beforeTokenTransfer(address from, address to, uint256 tokenId) internal virtual override {
super._beforeTokenTransfer(from, to, tokenId);
if (from == address(0)) {
_addTokenToAllTokensEnumeration(tokenId);
} else if (from != to) {
_removeTokenFromOwnerEnumeration(from, tokenId);
}
if (to == address(0)) {
_removeTokenFromAllTokensEnumeration(tokenId);
} else if (to != from) {
_addTokenToOwnerEnumeration(to, tokenId);
}
}
/**
* @dev Private function to add a token to this extension's ownership-tracking data structures.
* @param to address representing the new owner of the given token ID
* @param tokenId uint256 ID of the token to be added to the tokens list of the given address
*/
function _addTokenToOwnerEnumeration(address to, uint256 tokenId) private {
uint256 length = ERC721.balanceOf(to);
_ownedTokens[to][length] = tokenId;
_ownedTokensIndex[tokenId] = length;
}
/**
* @dev Private function to add a token to this extension's token tracking data structures.
* @param tokenId uint256 ID of the token to be added to the tokens list
*/
function _addTokenToAllTokensEnumeration(uint256 tokenId) private {
_allTokensIndex[tokenId] = _allTokens.length;
_allTokens.push(tokenId);
}
/**
* @dev Private function to remove a token from this extension's ownership-tracking data structures. Note that
* while the token is not assigned a new owner, the `_ownedTokensIndex` mapping is _not_ updated: this allows for
* gas optimizations e.g. when performing a transfer operation (avoiding double writes).
* This has O(1) time complexity, but alters the order of the _ownedTokens array.
* @param from address representing the previous owner of the given token ID
* @param tokenId uint256 ID of the token to be removed from the tokens list of the given address
*/
function _removeTokenFromOwnerEnumeration(address from, uint256 tokenId) private {
// To prevent a gap in from's tokens array, we store the last token in the index of the token to delete, and
// then delete the last slot (swap and pop).
uint256 lastTokenIndex = ERC721.balanceOf(from) - 1;
uint256 tokenIndex = _ownedTokensIndex[tokenId];
// When the token to delete is the last token, the swap operation is unnecessary
if (tokenIndex != lastTokenIndex) {
uint256 lastTokenId = _ownedTokens[from][lastTokenIndex];
_ownedTokens[from][tokenIndex] = lastTokenId; // Move the last token to the slot of the to-delete token
_ownedTokensIndex[lastTokenId] = tokenIndex; // Update the moved token's index
}
// This also deletes the contents at the last position of the array
delete _ownedTokensIndex[tokenId];
delete _ownedTokens[from][lastTokenIndex];
}
/**
* @dev Private function to remove a token from this extension's token tracking data structures.
* This has O(1) time complexity, but alters the order of the _allTokens array.
* @param tokenId uint256 ID of the token to be removed from the tokens list
*/
function _removeTokenFromAllTokensEnumeration(uint256 tokenId) private {
// To prevent a gap in the tokens array, we store the last token in the index of the token to delete, and
// then delete the last slot (swap and pop).
uint256 lastTokenIndex = _allTokens.length - 1;
uint256 tokenIndex = _allTokensIndex[tokenId];
// When the token to delete is the last token, the swap operation is unnecessary. However, since this occurs so
// rarely (when the last minted token is burnt) that we still do the swap here to avoid the gas cost of adding
// an 'if' statement (like in _removeTokenFromOwnerEnumeration)
uint256 lastTokenId = _allTokens[lastTokenIndex];
_allTokens[tokenIndex] = lastTokenId; // Move the last token to the slot of the to-delete token
_allTokensIndex[lastTokenId] = tokenIndex; // Update the moved token's index
// This also deletes the contents at the last position of the array
delete _allTokensIndex[tokenId];
_allTokens.pop();
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
/**
* @title Counters
* @author Matt Condon (@shrugs)
* @dev Provides counters that can only be incremented or decremented by one. This can be used e.g. to track the number
* of elements in a mapping, issuing ERC721 ids, or counting request ids.
*
* Include with `using Counters for Counters.Counter;`
*/
library Counters {
struct Counter {
// This variable should never be directly accessed by users of the library: interactions must be restricted to
// the library's function. As of Solidity v0.5.2, this cannot be enforced, though there is a proposal to add
// this feature: see https://github.com/ethereum/solidity/issues/4637
uint256 _value; // default: 0
}
function current(Counter storage counter) internal view returns (uint256) {
return counter._value;
}
function increment(Counter storage counter) internal {
unchecked {
counter._value += 1;
}
}
function decrement(Counter storage counter) internal {
uint256 value = counter._value;
require(value > 0, "Counter: decrement overflow");
unchecked {
counter._value = value - 1;
}
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
/**
* @dev String operations.
*/
library Strings {
bytes16 private constant alphabet = "0123456789abcdef";
/**
* @dev Converts a `uint256` to its ASCII `string` decimal representation.
*/
function toString(uint256 value) internal pure returns (string memory) {
// Inspired by OraclizeAPI's implementation - MIT licence
// https://github.com/oraclize/ethereum-api/blob/b42146b063c7d6ee1358846c198246239e9360e8/oraclizeAPI_0.4.25.sol
if (value == 0) {
return "0";
}
uint256 temp = value;
uint256 digits;
while (temp != 0) {
digits++;
temp /= 10;
}
bytes memory buffer = new bytes(digits);
while (value != 0) {
digits -= 1;
buffer[digits] = bytes1(uint8(48 + uint256(value % 10)));
value /= 10;
}
return string(buffer);
}
/**
* @dev Converts a `uint256` to its ASCII `string` hexadecimal representation.
*/
function toHexString(uint256 value) internal pure returns (string memory) {
if (value == 0) {
return "0x00";
}
uint256 temp = value;
uint256 length = 0;
while (temp != 0) {
length++;
temp >>= 8;
}
return toHexString(value, length);
}
/**
* @dev Converts a `uint256` to its ASCII `string` hexadecimal representation with fixed length.
*/
function toHexString(uint256 value, uint256 length) internal pure returns (string memory) {
bytes memory buffer = new bytes(2 * length + 2);
buffer[0] = "0";
buffer[1] = "x";
for (uint256 i = 2 * length + 1; i > 1; --i) {
buffer[i] = alphabet[value & 0xf];
value >>= 4;
}
require(value == 0, "Strings: hex length insufficient");
return string(buffer);
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
/*
* @dev Provides information about the current execution context, including the
* sender of the transaction and its data. While these are generally available
* via msg.sender and msg.data, they should not be accessed in such a direct
* manner, since when dealing with meta-transactions the account sending and
* paying for execution may not be the actual sender (as far as an application
* is concerned).
*
* This contract is only required for intermediate, library-like contracts.
*/
abstract contract Context {
function _msgSender() internal view virtual returns (address) {
return msg.sender;
}
function _msgData() internal view virtual returns (bytes calldata) {
this; // silence state mutability warning without generating bytecode - see https://github.com/ethereum/solidity/issues/2691
return msg.data;
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import "../../utils/introspection/IERC165.sol";
/**
* @dev Required interface of an ERC721 compliant contract.
*/
interface IERC721 is IERC165 {
/**
* @dev Emitted when `tokenId` token is transferred from `from` to `to`.
*/
event Transfer(address indexed from, address indexed to, uint256 indexed tokenId);
/**
* @dev Emitted when `owner` enables `approved` to manage the `tokenId` token.
*/
event Approval(address indexed owner, address indexed approved, uint256 indexed tokenId);
/**
* @dev Emitted when `owner` enables or disables (`approved`) `operator` to manage all of its assets.
*/
event ApprovalForAll(address indexed owner, address indexed operator, bool approved);
/**
* @dev Returns the number of tokens in ``owner``'s account.
*/
function balanceOf(address owner) external view returns (uint256 balance);
/**
* @dev Returns the owner of the `tokenId` token.
*
* Requirements:
*
* - `tokenId` must exist.
*/
function ownerOf(uint256 tokenId) external view returns (address owner);
/**
* @dev Safely transfers `tokenId` token from `from` to `to`, checking first that contract recipients
* are aware of the ERC721 protocol to prevent tokens from being forever locked.
*
* Requirements:
*
* - `from` cannot be the zero address.
* - `to` cannot be the zero address.
* - `tokenId` token must exist and be owned by `from`.
* - If the caller is not `from`, it must be have been allowed to move this token by either {approve} or {setApprovalForAll}.
* - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer.
*
* Emits a {Transfer} event.
*/
function safeTransferFrom(address from, address to, uint256 tokenId) external;
/**
* @dev Transfers `tokenId` token from `from` to `to`.
*
* WARNING: Usage of this method is discouraged, use {safeTransferFrom} whenever possible.
*
* Requirements:
*
* - `from` cannot be the zero address.
* - `to` cannot be the zero address.
* - `tokenId` token must be owned by `from`.
* - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}.
*
* Emits a {Transfer} event.
*/
function transferFrom(address from, address to, uint256 tokenId) external;
/**
* @dev Gives permission to `to` to transfer `tokenId` token to another account.
* The approval is cleared when the token is transferred.
*
* Only a single account can be approved at a time, so approving the zero address clears previous approvals.
*
* Requirements:
*
* - The caller must own the token or be an approved operator.
* - `tokenId` must exist.
*
* Emits an {Approval} event.
*/
function approve(address to, uint256 tokenId) external;
/**
* @dev Returns the account approved for `tokenId` token.
*
* Requirements:
*
* - `tokenId` must exist.
*/
function getApproved(uint256 tokenId) external view returns (address operator);
/**
* @dev Approve or remove `operator` as an operator for the caller.
* Operators can call {transferFrom} or {safeTransferFrom} for any token owned by the caller.
*
* Requirements:
*
* - The `operator` cannot be the caller.
*
* Emits an {ApprovalForAll} event.
*/
function setApprovalForAll(address operator, bool _approved) external;
/**
* @dev Returns if the `operator` is allowed to manage all of the assets of `owner`.
*
* See {setApprovalForAll}
*/
function isApprovedForAll(address owner, address operator) external view returns (bool);
/**
* @dev Safely transfers `tokenId` token from `from` to `to`.
*
* Requirements:
*
* - `from` cannot be the zero address.
* - `to` cannot be the zero address.
* - `tokenId` token must exist and be owned by `from`.
* - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}.
* - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer.
*
* Emits a {Transfer} event.
*/
function safeTransferFrom(address from, address to, uint256 tokenId, bytes calldata data) external;
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
/**
* @title ERC721 token receiver interface
* @dev Interface for any contract that wants to support safeTransfers
* from ERC721 asset contracts.
*/
interface IERC721Receiver {
/**
* @dev Whenever an {IERC721} `tokenId` token is transferred to this contract via {IERC721-safeTransferFrom}
* by `operator` from `from`, this function is called.
*
* It must return its Solidity selector to confirm the token transfer.
* If any other value is returned or the interface is not implemented by the recipient, the transfer will be reverted.
*
* The selector can be obtained in Solidity with `IERC721.onERC721Received.selector`.
*/
function onERC721Received(address operator, address from, uint256 tokenId, bytes calldata data) external returns (bytes4);
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import "../IERC721.sol";
/**
* @title ERC-721 Non-Fungible Token Standard, optional metadata extension
* @dev See https://eips.ethereum.org/EIPS/eip-721
*/
interface IERC721Metadata is IERC721 {
/**
* @dev Returns the token collection name.
*/
function name() external view returns (string memory);
/**
* @dev Returns the token collection symbol.
*/
function symbol() external view returns (string memory);
/**
* @dev Returns the Uniform Resource Identifier (URI) for `tokenId` token.
*/
function tokenURI(uint256 tokenId) external view returns (string memory);
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
/**
* @dev Collection of functions related to the address type
*/
library Address {
/**
* @dev Returns true if `account` is a contract.
*
* [IMPORTANT]
* ====
* It is unsafe to assume that an address for which this function returns
* false is an externally-owned account (EOA) and not a contract.
*
* Among others, `isContract` will return false for the following
* types of addresses:
*
* - an externally-owned account
* - a contract in construction
* - an address where a contract will be created
* - an address where a contract lived, but was destroyed
* ====
*/
function isContract(address account) internal view returns (bool) {
// This method relies on extcodesize, which returns 0 for contracts in
// construction, since the code is only stored at the end of the
// constructor execution.
uint256 size;
// solhint-disable-next-line no-inline-assembly
assembly { size := extcodesize(account) }
return size > 0;
}
/**
* @dev Replacement for Solidity's `transfer`: sends `amount` wei to
* `recipient`, forwarding all available gas and reverting on errors.
*
* https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost
* of certain opcodes, possibly making contracts go over the 2300 gas limit
* imposed by `transfer`, making them unable to receive funds via
* `transfer`. {sendValue} removes this limitation.
*
* https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more].
*
* IMPORTANT: because control is transferred to `recipient`, care must be
* taken to not create reentrancy vulnerabilities. Consider using
* {ReentrancyGuard} or the
* https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern].
*/
function sendValue(address payable recipient, uint256 amount) internal {
require(address(this).balance >= amount, "Address: insufficient balance");
// solhint-disable-next-line avoid-low-level-calls, avoid-call-value
(bool success, ) = recipient.call{ value: amount }("");
require(success, "Address: unable to send value, recipient may have reverted");
}
/**
* @dev Performs a Solidity function call using a low level `call`. A
* plain`call` is an unsafe replacement for a function call: use this
* function instead.
*
* If `target` reverts with a revert reason, it is bubbled up by this
* function (like regular Solidity function calls).
*
* Returns the raw returned data. To convert to the expected return value,
* use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`].
*
* 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");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with
* `errorMessage` as a fallback revert reason when `target` reverts.
*
* _Available since v3.1._
*/
function functionCall(address target, bytes memory data, string memory errorMessage) internal returns (bytes memory) {
return functionCallWithValue(target, data, 0, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but also transferring `value` wei to `target`.
*
* Requirements:
*
* - the calling contract must have an ETH balance of at least `value`.
* - the called Solidity function must be `payable`.
*
* _Available since v3.1._
*/
function functionCallWithValue(address target, bytes memory data, uint256 value) internal returns (bytes memory) {
return functionCallWithValue(target, data, value, "Address: low-level call with value failed");
}
/**
* @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but
* with `errorMessage` as a fallback revert reason when `target` reverts.
*
* _Available since v3.1._
*/
function functionCallWithValue(address target, bytes memory data, uint256 value, string memory errorMessage) internal returns (bytes memory) {
require(address(this).balance >= value, "Address: insufficient balance for call");
require(isContract(target), "Address: call to non-contract");
// solhint-disable-next-line avoid-low-level-calls
(bool success, bytes memory returndata) = target.call{ value: value }(data);
return _verifyCallResult(success, returndata, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but performing a static call.
*
* _Available since v3.3._
*/
function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) {
return functionStaticCall(target, data, "Address: low-level static call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`],
* but performing a static call.
*
* _Available since v3.3._
*/
function functionStaticCall(address target, bytes memory data, string memory errorMessage) internal view returns (bytes memory) {
require(isContract(target), "Address: static call to non-contract");
// solhint-disable-next-line avoid-low-level-calls
(bool success, bytes memory returndata) = target.staticcall(data);
return _verifyCallResult(success, returndata, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but performing a delegate call.
*
* _Available since v3.4._
*/
function functionDelegateCall(address target, bytes memory data) internal returns (bytes memory) {
return functionDelegateCall(target, data, "Address: low-level delegate call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`],
* but performing a delegate call.
*
* _Available since v3.4._
*/
function functionDelegateCall(address target, bytes memory data, string memory errorMessage) internal returns (bytes memory) {
require(isContract(target), "Address: delegate call to non-contract");
// solhint-disable-next-line avoid-low-level-calls
(bool success, bytes memory returndata) = target.delegatecall(data);
return _verifyCallResult(success, returndata, errorMessage);
}
function _verifyCallResult(bool success, bytes memory returndata, string memory errorMessage) private pure returns(bytes memory) {
if (success) {
return returndata;
} else {
// Look for revert reason and bubble it up if present
if (returndata.length > 0) {
// The easiest way to bubble the revert reason is using memory via assembly
// solhint-disable-next-line no-inline-assembly
assembly {
let returndata_size := mload(returndata)
revert(add(32, returndata), returndata_size)
}
} else {
revert(errorMessage);
}
}
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import "./IERC165.sol";
/**
* @dev Implementation of the {IERC165} interface.
*
* Contracts that want to implement ERC165 should inherit from this contract and override {supportsInterface} to check
* for the additional interface id that will be supported. For example:
*
* ```solidity
* function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) {
* return interfaceId == type(MyInterface).interfaceId || super.supportsInterface(interfaceId);
* }
* ```
*
* Alternatively, {ERC165Storage} provides an easier to use but more expensive implementation.
*/
abstract contract ERC165 is IERC165 {
/**
* @dev See {IERC165-supportsInterface}.
*/
function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) {
return interfaceId == type(IERC165).interfaceId;
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
/**
* @dev Interface of the ERC165 standard, as defined in the
* https://eips.ethereum.org/EIPS/eip-165[EIP].
*
* Implementers can declare support of contract interfaces, which can then be
* queried by others ({ERC165Checker}).
*
* For an implementation, see {ERC165}.
*/
interface IERC165 {
/**
* @dev Returns true if this contract implements the interface defined by
* `interfaceId`. See the corresponding
* https://eips.ethereum.org/EIPS/eip-165#how-interfaces-are-identified[EIP section]
* to learn more about how these ids are created.
*
* This function call must use less than 30 000 gas.
*/
function supportsInterface(bytes4 interfaceId) external view returns (bool);
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import "../IERC721.sol";
/**
* @title ERC-721 Non-Fungible Token Standard, optional enumeration extension
* @dev See https://eips.ethereum.org/EIPS/eip-721
*/
interface IERC721Enumerable is IERC721 {
/**
* @dev Returns the total amount of tokens stored by the contract.
*/
function totalSupply() external view returns (uint256);
/**
* @dev Returns a token ID owned by `owner` at a given `index` of its token list.
* Use along with {balanceOf} to enumerate all of ``owner``'s tokens.
*/
function tokenOfOwnerByIndex(address owner, uint256 index) external view returns (uint256 tokenId);
/**
* @dev Returns a token ID at a given `index` of all the tokens stored by the contract.
* Use along with {totalSupply} to enumerate all tokens.
*/
function tokenByIndex(uint256 index) external view returns (uint256);
}
|
max number of free mints we can give to the community for promotions/marketing
|
function giveFreeRoll(address receiver) public onlyOwner {
require(_numFreeRollsGiven < 200, "already given max number of free rolls");
uint256 freeRolls = freeRollPhunks[receiver];
freeRollPhunks[receiver] = freeRolls + 1;
_numFreeRollsGiven = _numFreeRollsGiven + 1;
}
| 1,156,512 |
./full_match/84531/0xd7149865d07cCfdfB10f858AFAb297A8251882Cc/sources/contracts/stores/FundingStore.sol
|
updates `fundingTracker` mapping Only callable by other protocol contracts Invoked by Funding.updateFundingTracker asset Asset address, e.g. address(0) for ETH market Market, e.g. "ETH-USD" fundingIncrement Accrued funding of given asset and market
|
function updateFundingTracker(
address asset,
string calldata market,
int256 fundingIncrement
) external onlyContract {
fundingTrackers[asset][market] += fundingIncrement;
}
| 11,525,415 |
./full_match/1/0xc94E3Fd7270be44da019c8c3dB1D2e4d0064063A/sources/contracts/adapters/alchemix/alEthAdapter.sol
|
Since harvest deposits all assets, that would include the users' deposit
|
function afterDeposit(uint256, uint256) internal virtual override {
harvest();
}
| 3,007,944 |
./full_match/43113/0x0fE2b51D3B543C6F359480BffBf8C4E6964aE40E/sources/src/lib/LibMath.sol
|
Checks if rounding error >= 0.1% when rounding down. numerator Numerator. denominator Denominator. target Value to multiply with numerator/denominator. return isError Rounding error is present. The absolute rounding error is the difference between the rounded value and the ideal value. The relative rounding error is the absolute rounding error divided by the absolute value of the ideal value. This is undefined when the ideal value is zero. The ideal value is `numerator target / denominator`. Let's call `numerator target % denominator` the remainder. The absolute error is `remainder / denominator`. When the ideal value is zero, we require the absolute error to be zero. Fortunately, this is always the case. The ideal value is zero iff `numerator == 0` and/or `target == 0`. In this case the remainder and absolute error are also zero.
|
function isRoundingErrorFloor(
uint256 numerator,
uint256 denominator,
uint256 target
) internal pure returns (bool isError) {
if (denominator == 0) {
revert("division by zero");
}
if (target == 0 || numerator == 0) {
return false;
}
isError = remainder.mul(1000) >= numerator.mul(target);
}
| 13,147,975 |
./partial_match/3/0xb2da1FA1f7EB50713738b6FBcf6b5467f1fE2d65/sources/Invitation.sol
|
Transfers `tokenId` from `from` to `to`. As opposed to {transferFrom}, this imposes no restrictions on msg.sender. Requirements: - `to` cannot be the zero address. - `tokenId` token must be owned by `from`. Emits a {Transfer} event./ Clear approvals from the previous owner
|
function _transfer(address from, address to, uint256 tokenId) internal virtual {
require(tokenOfFreeze[tokenId] == false);
require(ownerOf(tokenId) == from, "ERC721: transfer of token that is not own");
require(to != address(0), "ERC721: transfer to the zero address");
_beforeTokenTransfer(from, to, tokenId);
_approve(address(0), tokenId);
_holderTokens[from].remove(tokenId);
_holderTokens[to].add(tokenId);
_tokenOwners.set(tokenId, to);
emit Transfer(from, to, tokenId);
}
| 5,111,639 |
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
/// @author 1001.digital
/// @title A helper to distinguish external and contract addresses
library CheckAddress {
/// Check whether an address is a smart contract.
/// @param account the address to check
/// @dev checks if the `extcodesize` of `address` is greater zero
/// @return true for contracts
function isContract(address account) external view returns (bool) {
return getSize(account) > 0;
}
/// Check whether an address is an external wallet.
/// @param account the address to check
/// @dev checks if the `extcodesize` of `address` is zero
/// @return true for external wallets
function isExternal(address account) external view returns (bool) {
return getSize(account) == 0;
}
/// Get the size of the code of an address
/// @param account the address to check
/// @dev gets the `extcodesize` of `address`
/// @return the size of the address
function getSize(address account) internal view returns (uint256) {
uint256 size;
assembly {
size := extcodesize(account)
}
return size;
}
}
|
Get the size of the code of an address account the address to check gets the `extcodesize` of `address` return the size of the address
|
function getSize(address account) internal view returns (uint256) {
uint256 size;
assembly {
size := extcodesize(account)
}
return size;
}
| 937,564 |
./full_match/1/0x2af3948308797e259023835faBc56e2e9ba0963e/sources/contracts/YoloToken.sol
|
0x36372b07 is IERC20 id
|
function supportsInterface(
bytes4 interfaceId
) public view override returns (bool) {
return
interfaceId == type(IERC20).interfaceId ||
super.supportsInterface(interfaceId);
}
| 16,595,540 |
contract SoccerBet {
enum Team { A, B }
struct BettingParty {
Team bettedTeam;
uint amount;
address account;
}
BettingParty A;
BettingParty B;
address oracle;
uint spareAmount;
function SoccerBet(address bettingPartyA, address bettingPartyB) {
oracle = msg.sender;
A.account = bettingPartyA;
B.account = bettingPartyB;
A.amount = 0;
B.amount = 0;
spareAmount = msg.value;
}
function depositFunds(Team t) {
if (msg.sender == A.account) {
//Is the caller betting party A
A.amount += msg.value;
A.bettedTeam = t;
} else if (msg.sender == B.account) {
//Or is the caller betting party B
B.amount += msg.value;
B.bettedTeam = t;
} else {
//Just in off chance someone sent some money to this account,
//lets store it and distribute it to the winner
spareAmount += msg.value;
}
}
/**
* We are going to allow setting of the outcome as long as
* one party has deposited money. It is upon the Oracle to not
* set the outcome of the contract before both parties have
* gotten a chance to deposit money.
* */
function setOutcome(Team t, uint8 posession) {
//We just need to calculate the losing party's earnings
uint loserEarnings = 0;
//Send money logic here
//Winner gets money of the losing party * posession of winning side / 100
if (A.bettedTeam == t) {
loserEarnings = B.amount - (B.amount * posession/100);
B.account.send(loserEarnings);
//Kill the contract, and send all the money to the winner, which is:
//B.amount * (1 - posession)/100
suicide(A.account);
} else if (B.bettedTeam == t) {
loserEarnings = A.amount - (A.amount * posession/100);
A.account.send(loserEarnings);
//Kill the contract, and send all the money to the winner, which is:
//A.amount * (1 - posession)/100
suicide(B.account);
}
}
}
|
We are going to allow setting of the outcome as long as one party has deposited money. It is upon the Oracle to not set the outcome of the contract before both parties have gotten a chance to deposit money. /We just need to calculate the losing party's earningsSend money logic hereWinner gets money of the losing party posession of winning side / 100Kill the contract, and send all the money to the winner, which is:B.amount (1 - posession)/100Kill the contract, and send all the money to the winner, which is:A.amount (1 - posession)/100
|
function setOutcome(Team t, uint8 posession) {
uint loserEarnings = 0;
if (A.bettedTeam == t) {
loserEarnings = B.amount - (B.amount * posession/100);
B.account.send(loserEarnings);
suicide(A.account);
loserEarnings = A.amount - (A.amount * posession/100);
A.account.send(loserEarnings);
suicide(B.account);
}
}
| 2,488,348 |
// SPDX-License-Identifier: GPL-3.0
// Author: Pagzi Tech Inc. | 2022
// DeadTownZeds | 2022
pragma solidity >=0.8.0 <0.9.0;
import "@openzeppelin/contracts/access/Ownable.sol";
import "./ERC721Enumerable.sol";
contract DeadTownZeds is ERC721Enumerable, Ownable {
string public baseURI;
uint256 public cost = 0.042 ether;
address pagzi = 0xF4617b57ad853f4Bc2Ce3f06C0D74958c240633c;
address macroverse = 0x02F91c73C0B3D50C79821f2F205Cd5268f0D7E57;
address steven = 0x275715709500a38a86fA48D280Ed88D201681601;
//date settings
uint256 public publicDate = 1644426000;
uint256 public endDate = 1644512400;
//mint passes/claims
mapping(address => uint256) public mintPasses;
address public proxyRegistryAddress;
constructor(
string memory _initBaseURI,
address _proxyRegistryAddress
) ERC721("DeadTownZeds", "ZEDS") {
setBaseURI(_initBaseURI);
proxyRegistryAddress = _proxyRegistryAddress;
initMintPasses();
}
// external
function mint(uint256 count) external payable{
require((publicDate <= block.timestamp) && (endDate >= block.timestamp),"DATE");
require(msg.value >= cost * count,"LOW");
uint256 totalSupply = _owners.length;
for(uint i; i < count; i++) {
_mint(_msgSender(), totalSupply + i + 1);
}
}
function claim() external{
uint256 totalSupply = _owners.length;
require((publicDate <= block.timestamp) && (endDate >= block.timestamp));
uint256 reserve = mintPasses[msg.sender];
require(reserve > 0, "Low reserve");
_mint(_msgSender(), totalSupply + 1);
mintPasses[msg.sender] = reserve - 1;
delete reserve;
}
//only owner
function gift(uint[] calldata quantity, address[] calldata recipient) external onlyOwner{
require(quantity.length == recipient.length, "Provide quantities and recipients" );
uint256 totalSupply = _owners.length;
for(uint i; i < recipient.length; ++i){
for(uint j; j < quantity[i]; ++j){
_mint(recipient[i], totalSupply + j + 1);
}
}
}
function setCost(uint256 _cost) external onlyOwner {
cost = _cost;
}
function setPublicDate(uint256 _publicDate) external onlyOwner {
publicDate = _publicDate;
}
function setEndDate(uint256 _endDate) external onlyOwner {
endDate = _endDate;
}
function setDates(uint256 _publicDate, uint256 _endDate) external onlyOwner {
publicDate = _publicDate;
endDate = _endDate;
}
function setMintPass(address _address,uint256 _quantity) external onlyOwner {
mintPasses[_address] = _quantity;
}
function setMintPasses(address[] calldata _addresses, uint256[] calldata _amounts) external onlyOwner {
for(uint256 i; i < _addresses.length; i++){
mintPasses[_addresses[i]] = _amounts[i];
}
}
//internal
function initMintPasses() internal {
mintPasses[0x275715709500a38a86fA48D280Ed88D201681601] = 10;
mintPasses[0xE2542857B06Ae5cdf7c4664f417e7a56312Da84E] = 5;
mintPasses[0x68fFfD5e532f8ED2727ACFEd097Ee1D065030b9c] = 5;
mintPasses[0x6fa1D14fB34C002c30419BbBFfD725e0A70B43Aa] = 5;
mintPasses[0xF4617b57ad853f4Bc2Ce3f06C0D74958c240633c] = 10;
mintPasses[0x8894802E3599EAA22e729a2DfFAab09c055eE84c] = 100;
mintPasses[0xF1ff23e094C3f83C39d1F5deb92A3e72Ca501cFc] = 5;
mintPasses[0x8500C52ca27f326D3a64B792aA215B1166503076] = 5;
//winners
mintPasses[0x2ad6623Ca66DC36610270fDd7327D904Be6305d7] = 1;
mintPasses[0x815CD9963ed67Fc9a11b18C3f7523885dF2869F7] = 1;
mintPasses[0x664D7462634fAC1815353A10f138750Ee11a91F6] = 1;
mintPasses[0x04aFa47203132436Cd4aAFA10547304B25F7006B] = 1;
mintPasses[0xa2116eB15F9DA56190d5Ac7f500101558b707968] = 1;
mintPasses[0x2a5a847DFeF231ED9a680d32C3Bb39582423E72F] = 1;
mintPasses[0x79c6174F46bD6a90f8d775887F90fBe7ba8A2ae3] = 1;
//twitter contest
mintPasses[0xB2E0f2fb1313FCD8870D683A812a35a483e4E843] = 1;
mintPasses[0xD1570F6B6B37Ad73494A1a7199A2922b1C32b914] = 1;
mintPasses[0x09129Fe9c5D4074B747814b8eCF6D1f43CC39AaC] = 1;
mintPasses[0xfd86Fb68cbC6759Ed4cDd806303e756c53A93887] = 1;
mintPasses[0xe16C26D3435DCCe67752fb5fEB0749F5e184d057] = 1;
mintPasses[0xC6c8347F41916F09B5fa0553100762Dd148e79f8] = 1;
mintPasses[0x67A50fF70d234D89B59Ed3DCBfAd65c4b96e1fa1] = 1;
mintPasses[0x9Bc67600E69d5d2Ab62006ca878D95A894492005] = 1;
mintPasses[0x71Fd9c2440D593AEb4d3C01322F3bcEE32E0712c] = 1;
mintPasses[0x32B4Cc9c6ef7Ea5A3694403704c12AFc46786C03] = 1;
}
function setBaseURI(string memory _baseURI) public onlyOwner {
baseURI = _baseURI;
}
function setProxyRegistryAddress(address _proxyRegistryAddress) external onlyOwner {
proxyRegistryAddress = _proxyRegistryAddress;
}
function tokenURI(uint256 _tokenId) public view override returns (string memory) {
require(_exists(_tokenId), "Token does not exist.");
return string(abi.encodePacked(baseURI, Strings.toString(_tokenId)));
}
function burn(uint256 tokenId) public {
require(_isApprovedOrOwner(_msgSender(), tokenId), "Not approved to burn.");
_burn(tokenId);
}
function tokensOfOwner(address _owner) public view returns (uint256[] memory) {
uint256 tokenCount = balanceOf(_owner);
if (tokenCount == 0) return new uint256[](0);
uint256[] memory tokensId = new uint256[](tokenCount);
for (uint256 i; i < tokenCount; i++) {
tokensId[i] = tokenOfOwnerByIndex(_owner, i);
}
return tokensId;
}
function batchTransferFrom(address _from, address _to, uint256[] memory _tokenIds) public {
for (uint256 i = 0; i < _tokenIds.length; i++) {
transferFrom(_from, _to, _tokenIds[i]);
}
}
function batchSafeTransferFrom(address _from, address _to, uint256[] memory _tokenIds, bytes memory data_) public {
for (uint256 i = 0; i < _tokenIds.length; i++) {
safeTransferFrom(_from, _to, _tokenIds[i], data_);
}
}
function isOwnerOf(address account, uint256[] calldata _tokenIds) external view returns (bool){
for(uint256 i; i < _tokenIds.length; ++i ){
if(_owners[_tokenIds[i]] != account)
return false;
}
return true;
}
function isApprovedForAll(address _owner, address operator) public view override returns (bool) {
OpenSeaProxyRegistry proxyRegistry = OpenSeaProxyRegistry(proxyRegistryAddress);
if (address(proxyRegistry.proxies(_owner)) == operator) return true;
return super.isApprovedForAll(_owner, operator);
}
function _mint(address to, uint256 tokenId) internal virtual override {
_owners.push(to);
emit Transfer(address(0), to, tokenId);
}
function withdraw() public onlyOwner {
uint256 balance = address(this).balance;
payable(pagzi).transfer((balance * 200) / 1000);
payable(macroverse).transfer((balance * 750) / 1000);
payable(steven).transfer((balance * 50) / 1000);
}
}
contract OwnableDelegateProxy { }
contract OpenSeaProxyRegistry {
mapping(address => OwnableDelegateProxy) public proxies;
}
// SPDX-License-Identifier: GPL-3.0
// Author: Pagzi Tech Inc. | 2022
// DeadTownZeds | 2022
pragma solidity >=0.8.0 <0.9.0;
import "./ERC721.sol";
import "@openzeppelin/contracts/token/ERC721/extensions/IERC721Enumerable.sol";
/**
* @dev This implements an optional extension of {ERC721} defined in the EIP that adds
* enumerability of all the token ids in the contract as well as all token ids owned by each
* account but rips out the core of the gas-wasting processing that comes from OpenZeppelin.
*/
abstract contract ERC721Enumerable is ERC721, IERC721Enumerable {
/**
* @dev See {IERC165-supportsInterface}.
*/
function supportsInterface(bytes4 interfaceId) public view virtual override(IERC165, ERC721) returns (bool) {
return interfaceId == type(IERC721Enumerable).interfaceId || super.supportsInterface(interfaceId);
}
/**
* @dev See {IERC721Enumerable-totalSupply}.
*/
function totalSupply() public view virtual override returns (uint256) {
return _owners.length;
}
/**
* @dev See {IERC721Enumerable-tokenByIndex}.
*/
function tokenByIndex(uint256 index) public view virtual override returns (uint256) {
require(index < _owners.length, "ERC721Enumerable: global index out of bounds");
return index + 1;
}
/**
* @dev See {IERC721Enumerable-tokenOfOwnerByIndex}.
*/
function tokenOfOwnerByIndex(address owner, uint256 index) public view virtual override returns (uint256 tokenId) {
require(index < balanceOf(owner), "ERC721Enumerable: owner index out of bounds");
uint count;
for(uint i; i < _owners.length; i++){
if(owner == _owners[i]){
if(count == index) return i+1;
else count++;
}
}
revert("ERC721Enumerable: owner index out of bounds");
}
}
// SPDX-License-Identifier: GPL-3.0
// Author: Pagzi Tech Inc. | 2022
// DeadTownZeds | 2022
pragma solidity >=0.8.0 <0.9.0;
import "@openzeppelin/contracts/token/ERC721/IERC721.sol";
import "@openzeppelin/contracts/token/ERC721/IERC721Receiver.sol";
import "@openzeppelin/contracts/token/ERC721/extensions/IERC721Metadata.sol";
import "@openzeppelin/contracts/utils/Context.sol";
import "@openzeppelin/contracts/utils/Strings.sol";
import "@openzeppelin/contracts/utils/introspection/ERC165.sol";
import "./Address.sol";
abstract contract ERC721 is Context, ERC165, IERC721, IERC721Metadata {
using Address for address;
using Strings for uint256;
string private _name;
string private _symbol;
// Mapping from token ID to owner address
address[] internal _owners;
mapping(uint256 => address) private _tokenApprovals;
mapping(address => mapping(address => bool)) private _operatorApprovals;
/**
* @dev Initializes the contract by setting a `name` and a `symbol` to the token collection.
*/
constructor(string memory name_, string memory symbol_) {
_name = name_;
_symbol = symbol_;
}
/**
* @dev See {IERC165-supportsInterface}.
*/
function supportsInterface(bytes4 interfaceId)
public
view
virtual
override(ERC165, IERC165)
returns (bool)
{
return
interfaceId == type(IERC721).interfaceId ||
interfaceId == type(IERC721Metadata).interfaceId ||
super.supportsInterface(interfaceId);
}
/**
* @dev See {IERC721-balanceOf}.
*/
function balanceOf(address owner)
public
view
virtual
override
returns (uint)
{
require(owner != address(0), "ERC721: balance query for the zero address");
uint count;
for( uint i; i < _owners.length; ++i ){
if( owner == _owners[i] )
++count;
}
return count;
}
/**
* @dev See {IERC721-ownerOf}.
*/
function ownerOf(uint256 tokenId)
public
view
virtual
override
returns (address)
{
address owner = _owners[tokenId - 1];
require(
owner != address(0),
"ERC721: owner query for nonexistent token"
);
return owner;
}
/**
* @dev See {IERC721Metadata-name}.
*/
function name() public view virtual override returns (string memory) {
return _name;
}
/**
* @dev See {IERC721Metadata-symbol}.
*/
function symbol() public view virtual override returns (string memory) {
return _symbol;
}
/**
* @dev See {IERC721-approve}.
*/
function approve(address to, uint256 tokenId) public virtual override {
address owner = ERC721.ownerOf(tokenId);
require(to != owner, "ERC721: approval to current owner");
require(
_msgSender() == owner || isApprovedForAll(owner, _msgSender()),
"ERC721: approve caller is not owner nor approved for all"
);
_approve(to, tokenId);
}
/**
* @dev See {IERC721-getApproved}.
*/
function getApproved(uint256 tokenId)
public
view
virtual
override
returns (address)
{
require(
_exists(tokenId),
"ERC721: approved query for nonexistent token"
);
return _tokenApprovals[tokenId - 1];
}
/**
* @dev See {IERC721-setApprovalForAll}.
*/
function setApprovalForAll(address operator, bool approved)
public
virtual
override
{
require(operator != _msgSender(), "ERC721: approve to caller");
_operatorApprovals[_msgSender()][operator] = approved;
emit ApprovalForAll(_msgSender(), operator, approved);
}
/**
* @dev See {IERC721-isApprovedForAll}.
*/
function isApprovedForAll(address owner, address operator)
public
view
virtual
override
returns (bool)
{
return _operatorApprovals[owner][operator];
}
/**
* @dev See {IERC721-transferFrom}.
*/
function transferFrom(
address from,
address to,
uint256 tokenId
) public virtual override {
//solhint-disable-next-line max-line-length
require(
_isApprovedOrOwner(_msgSender(), tokenId),
"ERC721: transfer caller is not owner nor approved"
);
_transfer(from, to, tokenId);
}
/**
* @dev See {IERC721-safeTransferFrom}.
*/
function safeTransferFrom(
address from,
address to,
uint256 tokenId
) public virtual override {
safeTransferFrom(from, to, tokenId, "");
}
/**
* @dev See {IERC721-safeTransferFrom}.
*/
function safeTransferFrom(
address from,
address to,
uint256 tokenId,
bytes memory _data
) public virtual override {
require(
_isApprovedOrOwner(_msgSender(), tokenId),
"ERC721: transfer caller is not owner nor approved"
);
_safeTransfer(from, to, tokenId, _data);
}
/**
* @dev Safely transfers `tokenId` token from `from` to `to`, checking first that contract recipients
* are aware of the ERC721 protocol to prevent tokens from being forever locked.
*
* `_data` is additional data, it has no specified format and it is sent in call to `to`.
*
* This internal function is equivalent to {safeTransferFrom}, and can be used to e.g.
* implement alternative mechanisms to perform token transfer, such as signature-based.
*
* Requirements:
*
* - `from` cannot be the zero address.
* - `to` cannot be the zero address.
* - `tokenId` token must exist and be owned by `from`.
* - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer.
*
* Emits a {Transfer} event.
*/
function _safeTransfer(
address from,
address to,
uint256 tokenId,
bytes memory _data
) internal virtual {
_transfer(from, to, tokenId);
require(
_checkOnERC721Received(from, to, tokenId, _data),
"ERC721: transfer to non ERC721Receiver implementer"
);
}
/**
* @dev Returns whether `tokenId` exists.
*
* Tokens can be managed by their owner or approved accounts via {approve} or {setApprovalForAll}.
*
* Tokens start existing when they are minted (`_mint`),
* and stop existing when they are burned (`_burn`).
*/
function _exists(uint256 tokenId) internal view virtual returns (bool) {
return tokenId < (_owners.length + 1) && _owners[tokenId - 1] != address(0);
}
/**
* @dev Returns whether `spender` is allowed to manage `tokenId`.
*
* Requirements:
*
* - `tokenId` must exist.
*/
function _isApprovedOrOwner(address spender, uint256 tokenId)
internal
view
virtual
returns (bool)
{
require(
_exists(tokenId),
"ERC721: operator query for nonexistent token"
);
address owner = ERC721.ownerOf(tokenId);
return (spender == owner ||
getApproved(tokenId) == spender ||
isApprovedForAll(owner, spender));
}
/**
* @dev Safely mints `tokenId` and transfers it to `to`.
*
* Requirements:
*
* - `tokenId` must not exist.
* - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer.
*
* Emits a {Transfer} event.
*/
function _safeMint(address to, uint256 tokenId) internal virtual {
_safeMint(to, tokenId, "");
}
/**
* @dev Same as {xref-ERC721-_safeMint-address-uint256-}[`_safeMint`], with an additional `data` parameter which is
* forwarded in {IERC721Receiver-onERC721Received} to contract recipients.
*/
function _safeMint(
address to,
uint256 tokenId,
bytes memory _data
) internal virtual {
_mint(to, tokenId);
require(
_checkOnERC721Received(address(0), to, tokenId, _data),
"ERC721: transfer to non ERC721Receiver implementer"
);
}
/**
* @dev Mints `tokenId` and transfers it to `to`.
*
* WARNING: Usage of this method is discouraged, use {_safeMint} whenever possible
*
* Requirements:
*
* - `tokenId` must not exist.
* - `to` cannot be the zero address.
*
* Emits a {Transfer} event.
*/
function _mint(address to, uint256 tokenId) internal virtual {
require(to != address(0), "ERC721: mint to the zero address");
require(!_exists(tokenId), "ERC721: token already minted");
_beforeTokenTransfer(address(0), to, tokenId);
_owners.push(to);
emit Transfer(address(0), to, tokenId);
}
/**
* @dev Destroys `tokenId`.
* The approval is cleared when the token is burned.
*
* Requirements:
*
* - `tokenId` must exist.
*
* Emits a {Transfer} event.
*/
function _burn(uint256 tokenId) internal virtual {
address owner = ERC721.ownerOf(tokenId);
_beforeTokenTransfer(owner, address(0), tokenId);
// Clear approvals
_approve(address(0), tokenId);
_owners[tokenId - 1] = address(0);
emit Transfer(owner, address(0), tokenId);
}
/**
* @dev Transfers `tokenId` from `from` to `to`.
* As opposed to {transferFrom}, this imposes no restrictions on msg.sender.
*
* Requirements:
*
* - `to` cannot be the zero address.
* - `tokenId` token must be owned by `from`.
*
* Emits a {Transfer} event.
*/
function _transfer(
address from,
address to,
uint256 tokenId
) internal virtual {
require(
ERC721.ownerOf(tokenId) == from,
"ERC721: transfer of token that is not own"
);
require(to != address(0), "ERC721: transfer to the zero address");
_beforeTokenTransfer(from, to, tokenId);
// Clear approvals from the previous owner
_approve(address(0), tokenId);
_owners[tokenId - 1] = to;
emit Transfer(from, to, tokenId);
}
/**
* @dev Approve `to` to operate on `tokenId`
*
* Emits a {Approval} event.
*/
function _approve(address to, uint256 tokenId) internal virtual {
_tokenApprovals[tokenId - 1] = to;
emit Approval(ERC721.ownerOf(tokenId), to, tokenId);
}
/**
* @dev Internal function to invoke {IERC721Receiver-onERC721Received} on a target address.
* The call is not executed if the target address is not a contract.
*
* @param from address representing the previous owner of the given token ID
* @param to target address that will receive the tokens
* @param tokenId uint256 ID of the token to be transferred
* @param _data bytes optional data to send along with the call
* @return bool whether the call correctly returned the expected magic value
*/
function _checkOnERC721Received(
address from,
address to,
uint256 tokenId,
bytes memory _data
) private returns (bool) {
if (to.isContract()) {
try
IERC721Receiver(to).onERC721Received(
_msgSender(),
from,
tokenId,
_data
)
returns (bytes4 retval) {
return retval == IERC721Receiver.onERC721Received.selector;
} catch (bytes memory reason) {
if (reason.length == 0) {
revert(
"ERC721: transfer to non ERC721Receiver implementer"
);
} else {
assembly {
revert(add(32, reason), mload(reason))
}
}
}
} else {
return true;
}
}
/**
* @dev Hook that is called before any token transfer. This includes minting
* and burning.
*
* Calling conditions:
*
* - When `from` and `to` are both non-zero, ``from``'s `tokenId` will be
* transferred to `to`.
* - When `from` is zero, `tokenId` will be minted for `to`.
* - When `to` is zero, ``from``'s `tokenId` will be burned.
* - `from` and `to` are never both zero.
*
* To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks].
*/
function _beforeTokenTransfer(
address from,
address to,
uint256 tokenId
) internal virtual {}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.6;
library Address {
function isContract(address account) internal view returns (bool) {
uint size;
assembly {
size := extcodesize(account)
}
return size > 0;
}
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (utils/introspection/IERC165.sol)
pragma solidity ^0.8.0;
/**
* @dev Interface of the ERC165 standard, as defined in the
* https://eips.ethereum.org/EIPS/eip-165[EIP].
*
* Implementers can declare support of contract interfaces, which can then be
* queried by others ({ERC165Checker}).
*
* For an implementation, see {ERC165}.
*/
interface IERC165 {
/**
* @dev Returns true if this contract implements the interface defined by
* `interfaceId`. See the corresponding
* https://eips.ethereum.org/EIPS/eip-165#how-interfaces-are-identified[EIP section]
* to learn more about how these ids are created.
*
* This function call must use less than 30 000 gas.
*/
function supportsInterface(bytes4 interfaceId) external view returns (bool);
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (utils/introspection/ERC165.sol)
pragma solidity ^0.8.0;
import "./IERC165.sol";
/**
* @dev Implementation of the {IERC165} interface.
*
* Contracts that want to implement ERC165 should inherit from this contract and override {supportsInterface} to check
* for the additional interface id that will be supported. For example:
*
* ```solidity
* function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) {
* return interfaceId == type(MyInterface).interfaceId || super.supportsInterface(interfaceId);
* }
* ```
*
* Alternatively, {ERC165Storage} provides an easier to use but more expensive implementation.
*/
abstract contract ERC165 is IERC165 {
/**
* @dev See {IERC165-supportsInterface}.
*/
function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) {
return interfaceId == type(IERC165).interfaceId;
}
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (utils/Strings.sol)
pragma solidity ^0.8.0;
/**
* @dev String operations.
*/
library Strings {
bytes16 private constant _HEX_SYMBOLS = "0123456789abcdef";
/**
* @dev Converts a `uint256` to its ASCII `string` decimal representation.
*/
function toString(uint256 value) internal pure returns (string memory) {
// Inspired by OraclizeAPI's implementation - MIT licence
// https://github.com/oraclize/ethereum-api/blob/b42146b063c7d6ee1358846c198246239e9360e8/oraclizeAPI_0.4.25.sol
if (value == 0) {
return "0";
}
uint256 temp = value;
uint256 digits;
while (temp != 0) {
digits++;
temp /= 10;
}
bytes memory buffer = new bytes(digits);
while (value != 0) {
digits -= 1;
buffer[digits] = bytes1(uint8(48 + uint256(value % 10)));
value /= 10;
}
return string(buffer);
}
/**
* @dev Converts a `uint256` to its ASCII `string` hexadecimal representation.
*/
function toHexString(uint256 value) internal pure returns (string memory) {
if (value == 0) {
return "0x00";
}
uint256 temp = value;
uint256 length = 0;
while (temp != 0) {
length++;
temp >>= 8;
}
return toHexString(value, length);
}
/**
* @dev Converts a `uint256` to its ASCII `string` hexadecimal representation with fixed length.
*/
function toHexString(uint256 value, uint256 length) internal pure returns (string memory) {
bytes memory buffer = new bytes(2 * length + 2);
buffer[0] = "0";
buffer[1] = "x";
for (uint256 i = 2 * length + 1; i > 1; --i) {
buffer[i] = _HEX_SYMBOLS[value & 0xf];
value >>= 4;
}
require(value == 0, "Strings: hex length insufficient");
return string(buffer);
}
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (utils/Context.sol)
pragma solidity ^0.8.0;
/**
* @dev Provides information about the current execution context, including the
* sender of the transaction and its data. While these are generally available
* via msg.sender and msg.data, they should not be accessed in such a direct
* manner, since when dealing with meta-transactions the account sending and
* paying for execution may not be the actual sender (as far as an application
* is concerned).
*
* This contract is only required for intermediate, library-like contracts.
*/
abstract contract Context {
function _msgSender() internal view virtual returns (address) {
return msg.sender;
}
function _msgData() internal view virtual returns (bytes calldata) {
return msg.data;
}
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (token/ERC721/extensions/IERC721Metadata.sol)
pragma solidity ^0.8.0;
import "../IERC721.sol";
/**
* @title ERC-721 Non-Fungible Token Standard, optional metadata extension
* @dev See https://eips.ethereum.org/EIPS/eip-721
*/
interface IERC721Metadata is IERC721 {
/**
* @dev Returns the token collection name.
*/
function name() external view returns (string memory);
/**
* @dev Returns the token collection symbol.
*/
function symbol() external view returns (string memory);
/**
* @dev Returns the Uniform Resource Identifier (URI) for `tokenId` token.
*/
function tokenURI(uint256 tokenId) external view returns (string memory);
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (token/ERC721/extensions/IERC721Enumerable.sol)
pragma solidity ^0.8.0;
import "../IERC721.sol";
/**
* @title ERC-721 Non-Fungible Token Standard, optional enumeration extension
* @dev See https://eips.ethereum.org/EIPS/eip-721
*/
interface IERC721Enumerable is IERC721 {
/**
* @dev Returns the total amount of tokens stored by the contract.
*/
function totalSupply() external view returns (uint256);
/**
* @dev Returns a token ID owned by `owner` at a given `index` of its token list.
* Use along with {balanceOf} to enumerate all of ``owner``'s tokens.
*/
function tokenOfOwnerByIndex(address owner, uint256 index) external view returns (uint256 tokenId);
/**
* @dev Returns a token ID at a given `index` of all the tokens stored by the contract.
* Use along with {totalSupply} to enumerate all tokens.
*/
function tokenByIndex(uint256 index) external view returns (uint256);
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (token/ERC721/IERC721Receiver.sol)
pragma solidity ^0.8.0;
/**
* @title ERC721 token receiver interface
* @dev Interface for any contract that wants to support safeTransfers
* from ERC721 asset contracts.
*/
interface IERC721Receiver {
/**
* @dev Whenever an {IERC721} `tokenId` token is transferred to this contract via {IERC721-safeTransferFrom}
* by `operator` from `from`, this function is called.
*
* It must return its Solidity selector to confirm the token transfer.
* If any other value is returned or the interface is not implemented by the recipient, the transfer will be reverted.
*
* The selector can be obtained in Solidity with `IERC721.onERC721Received.selector`.
*/
function onERC721Received(
address operator,
address from,
uint256 tokenId,
bytes calldata data
) external returns (bytes4);
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (token/ERC721/IERC721.sol)
pragma solidity ^0.8.0;
import "../../utils/introspection/IERC165.sol";
/**
* @dev Required interface of an ERC721 compliant contract.
*/
interface IERC721 is IERC165 {
/**
* @dev Emitted when `tokenId` token is transferred from `from` to `to`.
*/
event Transfer(address indexed from, address indexed to, uint256 indexed tokenId);
/**
* @dev Emitted when `owner` enables `approved` to manage the `tokenId` token.
*/
event Approval(address indexed owner, address indexed approved, uint256 indexed tokenId);
/**
* @dev Emitted when `owner` enables or disables (`approved`) `operator` to manage all of its assets.
*/
event ApprovalForAll(address indexed owner, address indexed operator, bool approved);
/**
* @dev Returns the number of tokens in ``owner``'s account.
*/
function balanceOf(address owner) external view returns (uint256 balance);
/**
* @dev Returns the owner of the `tokenId` token.
*
* Requirements:
*
* - `tokenId` must exist.
*/
function ownerOf(uint256 tokenId) external view returns (address owner);
/**
* @dev Safely transfers `tokenId` token from `from` to `to`, checking first that contract recipients
* are aware of the ERC721 protocol to prevent tokens from being forever locked.
*
* Requirements:
*
* - `from` cannot be the zero address.
* - `to` cannot be the zero address.
* - `tokenId` token must exist and be owned by `from`.
* - If the caller is not `from`, it must be have been allowed to move this token by either {approve} or {setApprovalForAll}.
* - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer.
*
* Emits a {Transfer} event.
*/
function safeTransferFrom(
address from,
address to,
uint256 tokenId
) external;
/**
* @dev Transfers `tokenId` token from `from` to `to`.
*
* WARNING: Usage of this method is discouraged, use {safeTransferFrom} whenever possible.
*
* Requirements:
*
* - `from` cannot be the zero address.
* - `to` cannot be the zero address.
* - `tokenId` token must be owned by `from`.
* - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}.
*
* Emits a {Transfer} event.
*/
function transferFrom(
address from,
address to,
uint256 tokenId
) external;
/**
* @dev Gives permission to `to` to transfer `tokenId` token to another account.
* The approval is cleared when the token is transferred.
*
* Only a single account can be approved at a time, so approving the zero address clears previous approvals.
*
* Requirements:
*
* - The caller must own the token or be an approved operator.
* - `tokenId` must exist.
*
* Emits an {Approval} event.
*/
function approve(address to, uint256 tokenId) external;
/**
* @dev Returns the account approved for `tokenId` token.
*
* Requirements:
*
* - `tokenId` must exist.
*/
function getApproved(uint256 tokenId) external view returns (address operator);
/**
* @dev Approve or remove `operator` as an operator for the caller.
* Operators can call {transferFrom} or {safeTransferFrom} for any token owned by the caller.
*
* Requirements:
*
* - The `operator` cannot be the caller.
*
* Emits an {ApprovalForAll} event.
*/
function setApprovalForAll(address operator, bool _approved) external;
/**
* @dev Returns if the `operator` is allowed to manage all of the assets of `owner`.
*
* See {setApprovalForAll}
*/
function isApprovedForAll(address owner, address operator) external view returns (bool);
/**
* @dev Safely transfers `tokenId` token from `from` to `to`.
*
* Requirements:
*
* - `from` cannot be the zero address.
* - `to` cannot be the zero address.
* - `tokenId` token must exist and be owned by `from`.
* - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}.
* - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer.
*
* Emits a {Transfer} event.
*/
function safeTransferFrom(
address from,
address to,
uint256 tokenId,
bytes calldata data
) external;
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (access/Ownable.sol)
pragma solidity ^0.8.0;
import "../utils/Context.sol";
/**
* @dev Contract module which provides a basic access control mechanism, where
* there is an account (an owner) that can be granted exclusive access to
* specific functions.
*
* By default, the owner account will be the one that deploys the contract. This
* can later be changed with {transferOwnership}.
*
* This module is used through inheritance. It will make available the modifier
* `onlyOwner`, which can be applied to your functions to restrict their use to
* the owner.
*/
abstract contract Ownable is Context {
address private _owner;
event OwnershipTransferred(address indexed previousOwner, address indexed newOwner);
/**
* @dev Initializes the contract setting the deployer as the initial owner.
*/
constructor() {
_transferOwnership(_msgSender());
}
/**
* @dev Returns the address of the current owner.
*/
function owner() public view virtual returns (address) {
return _owner;
}
/**
* @dev Throws if called by any account other than the owner.
*/
modifier onlyOwner() {
require(owner() == _msgSender(), "Ownable: caller is not the owner");
_;
}
/**
* @dev Leaves the contract without owner. It will not be possible to call
* `onlyOwner` functions anymore. Can only be called by the current owner.
*
* NOTE: Renouncing ownership will leave the contract without an owner,
* thereby removing any functionality that is only available to the owner.
*/
function renounceOwnership() public virtual onlyOwner {
_transferOwnership(address(0));
}
/**
* @dev Transfers ownership of the contract to a new account (`newOwner`).
* Can only be called by the current owner.
*/
function transferOwnership(address newOwner) public virtual onlyOwner {
require(newOwner != address(0), "Ownable: new owner is the zero address");
_transferOwnership(newOwner);
}
/**
* @dev Transfers ownership of the contract to a new account (`newOwner`).
* Internal function without access restriction.
*/
function _transferOwnership(address newOwner) internal virtual {
address oldOwner = _owner;
_owner = newOwner;
emit OwnershipTransferred(oldOwner, newOwner);
}
}
|
Returns whether `tokenId` exists. Tokens can be managed by their owner or approved accounts via {approve} or {setApprovalForAll}. Tokens start existing when they are minted (`_mint`), and stop existing when they are burned (`_burn`)./
|
function _exists(uint256 tokenId) internal view virtual returns (bool) {
return tokenId < (_owners.length + 1) && _owners[tokenId - 1] != address(0);
}
| 5,711,316 |
./partial_match/84531/0xA39039AF66e9c7bd3CE53aa56B95F46D0b6BB364/sources/contracts/src/diamond/facets/governance/votes/VotesBase.sol
|
Returns the amount of votes that `account` had at a specific moment in the past. If the `clock()` is configured to use block numbers, this will return the value at the end of the corresponding block. Requirements: - `timepoint` must be in the past. If operating using block numbers, the block must be already mined./
|
function getPastVotes(
address account,
uint256 timepoint
) public view virtual override returns (uint256) {
require(timepoint < clock(), "Votes: future lookup");
return
VotesStorage.layout()._delegateCheckpoints[account].upperLookupRecent(
SafeCast.toUint32(timepoint)
);
}
| 16,687,980 |
// Copyright (C) 2015 Forecast Foundation OU, full GPL notice in LICENSE
pragma solidity >=0.5.10;
import 'ROOT/reporting/IDisputeWindow.sol';
import 'ROOT/libraries/Initializable.sol';
import 'ROOT/reporting/IUniverse.sol';
import 'ROOT/reporting/IReputationToken.sol';
import 'ROOT/reporting/IMarket.sol';
import 'ROOT/ICash.sol';
import 'ROOT/factories/MarketFactory.sol';
import 'ROOT/libraries/math/SafeMathUint256.sol';
import 'ROOT/reporting/IDisputeWindow.sol';
import 'ROOT/libraries/token/VariableSupplyToken.sol';
import 'ROOT/IAugur.sol';
/**
* @title Dispute Window
* @notice A contract used to encapsulate a window of time in which markets can be disputed as well as the pot where reporting fees are collected and distributed.
*/
contract DisputeWindow is Initializable, VariableSupplyToken, IDisputeWindow {
using SafeMathUint256 for uint256;
IAugur public augur;
IUniverse private universe;
ICash public cash;
address public buyParticipationTokens;
uint256 private startTime;
bool public participationTokensEnabled;
uint256 public windowId;
uint256 public duration;
function initialize(IAugur _augur, IUniverse _universe, uint256 _disputeWindowId, bool _participationTokensEnabled, uint256 _duration, uint256 _startTime, address _erc1820RegistryAddress) public beforeInitialized {
endInitialization();
augur = _augur;
universe = _universe;
duration = _duration;
windowId = _disputeWindowId;
cash = ICash(augur.lookup("Cash"));
buyParticipationTokens = augur.lookup("BuyParticipationTokens");
startTime = _startTime;
participationTokensEnabled = _participationTokensEnabled;
erc1820Registry = IERC1820Registry(_erc1820RegistryAddress);
initialize1820InterfaceImplementations();
}
function onMarketFinalized() public {
IMarket _market = IMarket(msg.sender);
require(universe.isContainerForMarket(_market));
uint256 _currentValidityBond = universe.getOrCacheValidityBond();
uint256 _currentInitialReportBond = universe.getOrCacheDesignatedReportStake();
uint256 _currentNoShowBond = universe.getOrCacheDesignatedReportNoShowBond();
uint256 _validityBond = _market.getValidityBondAttoCash();
uint256 _repBond = _market.getInitialReporter().getSize();
if (_validityBond >= _currentValidityBond / 2) {
validityBondTotal = validityBondTotal.add(_validityBond);
if (_market.isInvalid()) {
invalidMarketsTotal = invalidMarketsTotal.add(_validityBond);
}
}
if (_repBond >= _currentInitialReportBond / 2) {
initialReportBondTotal = initialReportBondTotal.add(_repBond);
if (!_market.designatedReporterWasCorrect()) {
incorrectDesignatedReportTotal = incorrectDesignatedReportTotal.add(_repBond);
}
}
if (_repBond >= _currentNoShowBond / 2) {
designatedReporterNoShowBondTotal = designatedReporterNoShowBondTotal.add(_repBond);
if (!_market.designatedReporterShowed()) {
designatedReportNoShowsTotal = designatedReportNoShowsTotal.add(_repBond);
}
}
}
/**
* @notice Buy tokens which can be redeemed for reporting fees
* @param _attotokens The number of tokens to purchase
* @return bool True
*/
function buy(uint256 _attotokens) public returns (bool) {
buyInternal(msg.sender, _attotokens);
return true;
}
function trustedBuy(address _buyer, uint256 _attotokens) public returns (bool) {
require(msg.sender == buyParticipationTokens);
buyInternal(_buyer, _attotokens);
return true;
}
function buyInternal(address _buyer, uint256 _attotokens) private {
require(participationTokensEnabled, "Cannot buy Participation tokens in initial market dispute windows");
require(_attotokens > 0, "DisputeWindow.buy: amount cannot be 0");
require(isActive(), "DisputeWindow.buy: window is not active");
require(!universe.isForking(), "DisputeWindow.buy: universe is forking");
getReputationToken().trustedDisputeWindowTransfer(_buyer, address(this), _attotokens);
mint(_buyer, _attotokens);
}
/**
* @notice Redeem tokens for reporting fees
* @param _account The account to redeem tokens for
* @return bool True
*/
function redeem(address _account) public returns (bool) {
require(isOver() || universe.isForking(), "DisputeWindow.redeem: window is not over");
uint256 _attoParticipationTokens = balances[_account];
if (_attoParticipationTokens == 0) {
return true;
}
uint256 _cashBalance = cash.balanceOf(address(this));
// Burn tokens and send back REP
uint256 _supply = totalSupply();
burn(_account, _attoParticipationTokens);
require(getReputationToken().transfer(_account, _attoParticipationTokens));
uint256 _feePayoutShare = 0;
if (_cashBalance != 0) {
// Pay out fees
_feePayoutShare = _cashBalance.mul(_attoParticipationTokens).div(_supply);
cash.transfer(_account, _feePayoutShare);
}
augur.logParticipationTokensRedeemed(universe, _account, _attoParticipationTokens, _feePayoutShare);
return true;
}
function getTypeName() public view returns (bytes32) {
return "DisputeWindow";
}
/**
* @return The universe associated with this window
*/
function getUniverse() public view returns (IUniverse) {
return universe;
}
/**
* @return The reputation token associated with this window
*/
function getReputationToken() public view returns (IReputationToken) {
return universe.getReputationToken();
}
/**
* @return When the window begins as a uint256 timestamp
*/
function getStartTime() public view returns (uint256) {
return startTime;
}
/**
* @return When the window ends as a uint256 timestamp
*/
function getEndTime() public view returns (uint256) {
return getStartTime().add(duration);
}
function getWindowId() public view returns (uint256) {
return windowId;
}
/**
* @return Bool indicating if the window has begun and has not yet ended
*/
function isActive() public view returns (bool) {
if (augur.getTimestamp() <= getStartTime()) {
return false;
}
if (augur.getTimestamp() >= getEndTime()) {
return false;
}
return true;
}
/**
* @return Bool indicating if the window has ended
*/
function isOver() public view returns (bool) {
return augur.getTimestamp() >= getEndTime();
}
function onTokenTransfer(address _from, address _to, uint256 _value) internal {
augur.logParticipationTokensTransferred(universe, _from, _to, _value, balances[_from], balances[_to]);
}
function onMint(address _target, uint256 _amount) internal {
augur.logParticipationTokensMinted(universe, _target, _amount, totalSupply(), balances[_target]);
}
function onBurn(address _target, uint256 _amount) internal {
augur.logParticipationTokensBurned(universe, _target, _amount, totalSupply(), balances[_target]);
}
}
|
Redeem tokens for reporting fees _account The account to redeem tokens for return bool True/ Pay out fees
|
function redeem(address _account) public returns (bool) {
require(isOver() || universe.isForking(), "DisputeWindow.redeem: window is not over");
uint256 _attoParticipationTokens = balances[_account];
if (_attoParticipationTokens == 0) {
return true;
}
uint256 _cashBalance = cash.balanceOf(address(this));
burn(_account, _attoParticipationTokens);
require(getReputationToken().transfer(_account, _attoParticipationTokens));
uint256 _feePayoutShare = 0;
if (_cashBalance != 0) {
_feePayoutShare = _cashBalance.mul(_attoParticipationTokens).div(_supply);
cash.transfer(_account, _feePayoutShare);
}
augur.logParticipationTokensRedeemed(universe, _account, _attoParticipationTokens, _feePayoutShare);
return true;
}
| 6,453,355 |
pragma solidity ^0.5.17;
// Brought from https://github.com/aragon/aragonOS/blob/v4.3.0/contracts/lib/math/SafeMath.sol
// Adapted to use pragma ^0.5.17 and satisfy our linter rules
/**
* @title SafeMath
* @dev Math operations with safety checks that revert on error
*/
library SafeMath {
string private constant ERROR_ADD_OVERFLOW = "MATH_ADD_OVERFLOW";
string private constant ERROR_SUB_UNDERFLOW = "MATH_SUB_UNDERFLOW";
string private constant ERROR_MUL_OVERFLOW = "MATH_MUL_OVERFLOW";
string private constant ERROR_DIV_ZERO = "MATH_DIV_ZERO";
/**
* @dev Multiplies two numbers, reverts on overflow.
*/
function mul(uint256 _a, uint256 _b) internal pure returns (uint256) {
// Gas optimization: this is cheaper than requiring 'a' not being zero, but the
// benefit is lost if 'b' is also tested.
// See: https://github.com/OpenZeppelin/openzeppelin-solidity/pull/522
if (_a == 0) {
return 0;
}
uint256 c = _a * _b;
require(c / _a == _b, ERROR_MUL_OVERFLOW);
return c;
}
/**
* @dev Integer division of two numbers truncating the quotient, reverts on division by zero.
*/
function div(uint256 _a, uint256 _b) internal pure returns (uint256) {
require(_b > 0, ERROR_DIV_ZERO); // Solidity only automatically asserts when dividing by 0
uint256 c = _a / _b;
// assert(_a == _b * c + _a % _b); // There is no case in which this doesn't hold
return c;
}
/**
* @dev Subtracts two numbers, reverts on overflow (i.e. if subtrahend is greater than minuend).
*/
function sub(uint256 _a, uint256 _b) internal pure returns (uint256) {
require(_b <= _a, ERROR_SUB_UNDERFLOW);
uint256 c = _a - _b;
return c;
}
/**
* @dev Adds two numbers, reverts on overflow.
*/
function add(uint256 _a, uint256 _b) internal pure returns (uint256) {
uint256 c = _a + _b;
require(c >= _a, ERROR_ADD_OVERFLOW);
return c;
}
/**
* @dev Divides two numbers and returns the remainder (unsigned integer modulo),
* reverts when dividing by zero.
*/
function mod(uint256 a, uint256 b) internal pure returns (uint256) {
require(b != 0, ERROR_DIV_ZERO);
return a % b;
}
}
/*
* SPDX-License-Identifier: MIT
*/
interface ICRVotingOwner {
/**
* @dev Ensure votes can be committed for a vote instance, revert otherwise
* @param _voteId ID of the vote instance to request the weight of a voter for
*/
function ensureCanCommit(uint256 _voteId) external;
/**
* @dev Ensure a certain voter can commit votes for a vote instance, revert otherwise
* @param _voteId ID of the vote instance to request the weight of a voter for
* @param _voter Address of the voter querying the weight of
*/
function ensureCanCommit(uint256 _voteId, address _voter) external;
/**
* @dev Ensure a certain voter can reveal votes for vote instance, revert otherwise
* @param _voteId ID of the vote instance to request the weight of a voter for
* @param _voter Address of the voter querying the weight of
* @return Weight of the requested guardian for the requested vote instance
*/
function ensureCanReveal(uint256 _voteId, address _voter) external returns (uint64);
}
/*
* SPDX-License-Identifier: MIT
*/
interface ICRVoting {
/**
* @dev Create a new vote instance
* @dev This function can only be called by the CRVoting owner
* @param _voteId ID of the new vote instance to be created
* @param _possibleOutcomes Number of possible outcomes for the new vote instance to be created
*/
function createVote(uint256 _voteId, uint8 _possibleOutcomes) external;
/**
* @dev Get the winning outcome of a vote instance
* @param _voteId ID of the vote instance querying the winning outcome of
* @return Winning outcome of the given vote instance or refused in case it's missing
*/
function getWinningOutcome(uint256 _voteId) external view returns (uint8);
/**
* @dev Get the tally of an outcome for a certain vote instance
* @param _voteId ID of the vote instance querying the tally of
* @param _outcome Outcome querying the tally of
* @return Tally of the outcome being queried for the given vote instance
*/
function getOutcomeTally(uint256 _voteId, uint8 _outcome) external view returns (uint256);
/**
* @dev Tell whether an outcome is valid for a given vote instance or not
* @param _voteId ID of the vote instance to check the outcome of
* @param _outcome Outcome to check if valid or not
* @return True if the given outcome is valid for the requested vote instance, false otherwise
*/
function isValidOutcome(uint256 _voteId, uint8 _outcome) external view returns (bool);
/**
* @dev Get the outcome voted by a voter for a certain vote instance
* @param _voteId ID of the vote instance querying the outcome of
* @param _voter Address of the voter querying the outcome of
* @return Outcome of the voter for the given vote instance
*/
function getVoterOutcome(uint256 _voteId, address _voter) external view returns (uint8);
/**
* @dev Tell whether a voter voted in favor of a certain outcome in a vote instance or not
* @param _voteId ID of the vote instance to query if a voter voted in favor of a certain outcome
* @param _outcome Outcome to query if the given voter voted in favor of
* @param _voter Address of the voter to query if voted in favor of the given outcome
* @return True if the given voter voted in favor of the given outcome, false otherwise
*/
function hasVotedInFavorOf(uint256 _voteId, uint8 _outcome, address _voter) external view returns (bool);
/**
* @dev Filter a list of voters based on whether they voted in favor of a certain outcome in a vote instance or not
* @param _voteId ID of the vote instance to be checked
* @param _outcome Outcome to filter the list of voters of
* @param _voters List of addresses of the voters to be filtered
* @return List of results to tell whether a voter voted in favor of the given outcome or not
*/
function getVotersInFavorOf(uint256 _voteId, uint8 _outcome, address[] calldata _voters) external view returns (bool[] memory);
}
// Brought from https://github.com/aragon/aragonOS/blob/v4.3.0/contracts/common/IsContract.sol
// Adapted to use pragma ^0.5.17 and satisfy our linter rules
contract IsContract {
/*
* NOTE: this should NEVER be used for authentication
* (see pitfalls: https://github.com/fergarrui/ethereum-security/tree/master/contracts/extcodesize).
*
* This is only intended to be used as a sanity check that an address is actually a contract,
* RATHER THAN an address not being a contract.
*/
function isContract(address _target) internal view returns (bool) {
if (_target == address(0)) {
return false;
}
uint256 size;
assembly { size := extcodesize(_target) }
return size > 0;
}
}
contract ModuleIds {
// DisputeManager module ID - keccak256(abi.encodePacked("DISPUTE_MANAGER"))
bytes32 internal constant MODULE_ID_DISPUTE_MANAGER = 0x14a6c70f0f6d449c014c7bbc9e68e31e79e8474fb03b7194df83109a2d888ae6;
// GuardiansRegistry module ID - keccak256(abi.encodePacked("GUARDIANS_REGISTRY"))
bytes32 internal constant MODULE_ID_GUARDIANS_REGISTRY = 0x8af7b7118de65da3b974a3fd4b0c702b66442f74b9dff6eaed1037254c0b79fe;
// Voting module ID - keccak256(abi.encodePacked("VOTING"))
bytes32 internal constant MODULE_ID_VOTING = 0x7cbb12e82a6d63ff16fe43977f43e3e2b247ecd4e62c0e340da8800a48c67346;
// PaymentsBook module ID - keccak256(abi.encodePacked("PAYMENTS_BOOK"))
bytes32 internal constant MODULE_ID_PAYMENTS_BOOK = 0xfa275b1417437a2a2ea8e91e9fe73c28eaf0a28532a250541da5ac0d1892b418;
// Treasury module ID - keccak256(abi.encodePacked("TREASURY"))
bytes32 internal constant MODULE_ID_TREASURY = 0x06aa03964db1f7257357ef09714a5f0ca3633723df419e97015e0c7a3e83edb7;
}
contract ACL {
string private constant ERROR_BAD_FREEZE = "ACL_BAD_FREEZE";
string private constant ERROR_ROLE_ALREADY_FROZEN = "ACL_ROLE_ALREADY_FROZEN";
string private constant ERROR_INVALID_BULK_INPUT = "ACL_INVALID_BULK_INPUT";
enum BulkOp { Grant, Revoke, Freeze }
address internal constant FREEZE_FLAG = address(1);
address internal constant ANY_ADDR = address(-1);
// List of all roles assigned to different addresses
mapping (bytes32 => mapping (address => bool)) public roles;
event Granted(bytes32 indexed id, address indexed who);
event Revoked(bytes32 indexed id, address indexed who);
event Frozen(bytes32 indexed id);
/**
* @dev Tell whether an address has a role assigned
* @param _who Address being queried
* @param _id ID of the role being checked
* @return True if the requested address has assigned the given role, false otherwise
*/
function hasRole(address _who, bytes32 _id) public view returns (bool) {
return roles[_id][_who] || roles[_id][ANY_ADDR];
}
/**
* @dev Tell whether a role is frozen
* @param _id ID of the role being checked
* @return True if the given role is frozen, false otherwise
*/
function isRoleFrozen(bytes32 _id) public view returns (bool) {
return roles[_id][FREEZE_FLAG];
}
/**
* @dev Internal function to grant a role to a given address
* @param _id ID of the role to be granted
* @param _who Address to grant the role to
*/
function _grant(bytes32 _id, address _who) internal {
require(!isRoleFrozen(_id), ERROR_ROLE_ALREADY_FROZEN);
require(_who != FREEZE_FLAG, ERROR_BAD_FREEZE);
if (!hasRole(_who, _id)) {
roles[_id][_who] = true;
emit Granted(_id, _who);
}
}
/**
* @dev Internal function to revoke a role from a given address
* @param _id ID of the role to be revoked
* @param _who Address to revoke the role from
*/
function _revoke(bytes32 _id, address _who) internal {
require(!isRoleFrozen(_id), ERROR_ROLE_ALREADY_FROZEN);
if (hasRole(_who, _id)) {
roles[_id][_who] = false;
emit Revoked(_id, _who);
}
}
/**
* @dev Internal function to freeze a role
* @param _id ID of the role to be frozen
*/
function _freeze(bytes32 _id) internal {
require(!isRoleFrozen(_id), ERROR_ROLE_ALREADY_FROZEN);
roles[_id][FREEZE_FLAG] = true;
emit Frozen(_id);
}
/**
* @dev Internal function to enact a bulk list of ACL operations
*/
function _bulk(BulkOp[] memory _op, bytes32[] memory _id, address[] memory _who) internal {
require(_op.length == _id.length && _op.length == _who.length, ERROR_INVALID_BULK_INPUT);
for (uint256 i = 0; i < _op.length; i++) {
BulkOp op = _op[i];
if (op == BulkOp.Grant) {
_grant(_id[i], _who[i]);
} else if (op == BulkOp.Revoke) {
_revoke(_id[i], _who[i]);
} else if (op == BulkOp.Freeze) {
_freeze(_id[i]);
}
}
}
}
interface IModulesLinker {
/**
* @notice Update the implementations of a list of modules
* @param _ids List of IDs of the modules to be updated
* @param _addresses List of module addresses to be updated
*/
function linkModules(bytes32[] calldata _ids, address[] calldata _addresses) external;
}
// Brought from https://github.com/aragon/aragonOS/blob/v4.3.0/contracts/lib/math/SafeMath64.sol
// Adapted to use pragma ^0.5.17 and satisfy our linter rules
/**
* @title SafeMath64
* @dev Math operations for uint64 with safety checks that revert on error
*/
library SafeMath64 {
string private constant ERROR_ADD_OVERFLOW = "MATH64_ADD_OVERFLOW";
string private constant ERROR_SUB_UNDERFLOW = "MATH64_SUB_UNDERFLOW";
string private constant ERROR_MUL_OVERFLOW = "MATH64_MUL_OVERFLOW";
string private constant ERROR_DIV_ZERO = "MATH64_DIV_ZERO";
/**
* @dev Multiplies two numbers, reverts on overflow.
*/
function mul(uint64 _a, uint64 _b) internal pure returns (uint64) {
uint256 c = uint256(_a) * uint256(_b);
require(c < 0x010000000000000000, ERROR_MUL_OVERFLOW); // 2**64 (less gas this way)
return uint64(c);
}
/**
* @dev Integer division of two numbers truncating the quotient, reverts on division by zero.
*/
function div(uint64 _a, uint64 _b) internal pure returns (uint64) {
require(_b > 0, ERROR_DIV_ZERO); // Solidity only automatically asserts when dividing by 0
uint64 c = _a / _b;
// assert(_a == _b * c + _a % _b); // There is no case in which this doesn't hold
return c;
}
/**
* @dev Subtracts two numbers, reverts on overflow (i.e. if subtrahend is greater than minuend).
*/
function sub(uint64 _a, uint64 _b) internal pure returns (uint64) {
require(_b <= _a, ERROR_SUB_UNDERFLOW);
uint64 c = _a - _b;
return c;
}
/**
* @dev Adds two numbers, reverts on overflow.
*/
function add(uint64 _a, uint64 _b) internal pure returns (uint64) {
uint64 c = _a + _b;
require(c >= _a, ERROR_ADD_OVERFLOW);
return c;
}
/**
* @dev Divides two numbers and returns the remainder (unsigned integer modulo),
* reverts when dividing by zero.
*/
function mod(uint64 a, uint64 b) internal pure returns (uint64) {
require(b != 0, ERROR_DIV_ZERO);
return a % b;
}
}
// Brought from https://github.com/aragon/aragonOS/blob/v4.3.0/contracts/common/Uint256Helpers.sol
// Adapted to use pragma ^0.5.17 and satisfy our linter rules
library Uint256Helpers {
uint256 private constant MAX_UINT8 = uint8(-1);
uint256 private constant MAX_UINT64 = uint64(-1);
string private constant ERROR_UINT8_NUMBER_TOO_BIG = "UINT8_NUMBER_TOO_BIG";
string private constant ERROR_UINT64_NUMBER_TOO_BIG = "UINT64_NUMBER_TOO_BIG";
function toUint8(uint256 a) internal pure returns (uint8) {
require(a <= MAX_UINT8, ERROR_UINT8_NUMBER_TOO_BIG);
return uint8(a);
}
function toUint64(uint256 a) internal pure returns (uint64) {
require(a <= MAX_UINT64, ERROR_UINT64_NUMBER_TOO_BIG);
return uint64(a);
}
}
// Brought from https://github.com/aragon/aragonOS/blob/v4.3.0/contracts/common/TimeHelpers.sol
// Adapted to use pragma ^0.5.17 and satisfy our linter rules
contract TimeHelpers {
using Uint256Helpers for uint256;
/**
* @dev Returns the current block number.
* Using a function rather than `block.number` allows us to easily mock the block number in
* tests.
*/
function getBlockNumber() internal view returns (uint256) {
return block.number;
}
/**
* @dev Returns the current block number, converted to uint64.
* Using a function rather than `block.number` allows us to easily mock the block number in
* tests.
*/
function getBlockNumber64() internal view returns (uint64) {
return getBlockNumber().toUint64();
}
/**
* @dev Returns the current timestamp.
* Using a function rather than `block.timestamp` allows us to easily mock it in
* tests.
*/
function getTimestamp() internal view returns (uint256) {
return block.timestamp; // solium-disable-line security/no-block-members
}
/**
* @dev Returns the current timestamp, converted to uint64.
* Using a function rather than `block.timestamp` allows us to easily mock it in
* tests.
*/
function getTimestamp64() internal view returns (uint64) {
return getTimestamp().toUint64();
}
}
interface IClock {
/**
* @dev Ensure that the current term of the clock is up-to-date
* @return Identification number of the current term
*/
function ensureCurrentTerm() external returns (uint64);
/**
* @dev Transition up to a certain number of terms to leave the clock up-to-date
* @param _maxRequestedTransitions Max number of term transitions allowed by the sender
* @return Identification number of the term ID after executing the heartbeat transitions
*/
function heartbeat(uint64 _maxRequestedTransitions) external returns (uint64);
/**
* @dev Ensure that a certain term has its randomness set
* @return Randomness of the current term
*/
function ensureCurrentTermRandomness() external returns (bytes32);
/**
* @dev Tell the last ensured term identification number
* @return Identification number of the last ensured term
*/
function getLastEnsuredTermId() external view returns (uint64);
/**
* @dev Tell the current term identification number. Note that there may be pending term transitions.
* @return Identification number of the current term
*/
function getCurrentTermId() external view returns (uint64);
/**
* @dev Tell the number of terms the clock should transition to be up-to-date
* @return Number of terms the clock should transition to be up-to-date
*/
function getNeededTermTransitions() external view returns (uint64);
/**
* @dev Tell the information related to a term based on its ID
* @param _termId ID of the term being queried
* @return startTime Term start time
* @return randomnessBN Block number used for randomness in the requested term
* @return randomness Randomness computed for the requested term
*/
function getTerm(uint64 _termId) external view returns (uint64 startTime, uint64 randomnessBN, bytes32 randomness);
/**
* @dev Tell the randomness of a term even if it wasn't computed yet
* @param _termId Identification number of the term being queried
* @return Randomness of the requested term
*/
function getTermRandomness(uint64 _termId) external view returns (bytes32);
}
contract CourtClock is IClock, TimeHelpers {
using SafeMath64 for uint64;
string private constant ERROR_TERM_DOES_NOT_EXIST = "CLK_TERM_DOES_NOT_EXIST";
string private constant ERROR_TERM_DURATION_TOO_LONG = "CLK_TERM_DURATION_TOO_LONG";
string private constant ERROR_TERM_RANDOMNESS_NOT_YET = "CLK_TERM_RANDOMNESS_NOT_YET";
string private constant ERROR_TERM_RANDOMNESS_UNAVAILABLE = "CLK_TERM_RANDOMNESS_UNAVAILABLE";
string private constant ERROR_BAD_FIRST_TERM_START_TIME = "CLK_BAD_FIRST_TERM_START_TIME";
string private constant ERROR_TOO_MANY_TRANSITIONS = "CLK_TOO_MANY_TRANSITIONS";
string private constant ERROR_INVALID_TRANSITION_TERMS = "CLK_INVALID_TRANSITION_TERMS";
string private constant ERROR_CANNOT_DELAY_STARTED_COURT = "CLK_CANNOT_DELAY_STARTED_PROT";
string private constant ERROR_CANNOT_DELAY_PAST_START_TIME = "CLK_CANNOT_DELAY_PAST_START_TIME";
// Maximum number of term transitions a callee may have to assume in order to call certain functions that require the Court being up-to-date
uint64 internal constant MAX_AUTO_TERM_TRANSITIONS_ALLOWED = 1;
// Max duration in seconds that a term can last
uint64 internal constant MAX_TERM_DURATION = 365 days;
// Max time until first term starts since contract is deployed
uint64 internal constant MAX_FIRST_TERM_DELAY_PERIOD = 2 * MAX_TERM_DURATION;
struct Term {
uint64 startTime; // Timestamp when the term started
uint64 randomnessBN; // Block number for entropy
bytes32 randomness; // Entropy from randomnessBN block hash
}
// Duration in seconds for each term of the Court
uint64 private termDuration;
// Last ensured term id
uint64 private termId;
// List of Court terms indexed by id
mapping (uint64 => Term) private terms;
event Heartbeat(uint64 previousTermId, uint64 currentTermId);
event StartTimeDelayed(uint64 previousStartTime, uint64 currentStartTime);
/**
* @dev Ensure a certain term has already been processed
* @param _termId Identification number of the term to be checked
*/
modifier termExists(uint64 _termId) {
require(_termId <= termId, ERROR_TERM_DOES_NOT_EXIST);
_;
}
/**
* @dev Constructor function
* @param _termParams Array containing:
* 0. _termDuration Duration in seconds per term
* 1. _firstTermStartTime Timestamp in seconds when the court will open (to give time for guardian on-boarding)
*/
constructor(uint64[2] memory _termParams) public {
uint64 _termDuration = _termParams[0];
uint64 _firstTermStartTime = _termParams[1];
require(_termDuration < MAX_TERM_DURATION, ERROR_TERM_DURATION_TOO_LONG);
require(_firstTermStartTime >= getTimestamp64() + _termDuration, ERROR_BAD_FIRST_TERM_START_TIME);
require(_firstTermStartTime <= getTimestamp64() + MAX_FIRST_TERM_DELAY_PERIOD, ERROR_BAD_FIRST_TERM_START_TIME);
termDuration = _termDuration;
// No need for SafeMath: we already checked values above
terms[0].startTime = _firstTermStartTime - _termDuration;
}
/**
* @notice Ensure that the current term of the Court is up-to-date. If the Court is outdated by more than `MAX_AUTO_TERM_TRANSITIONS_ALLOWED`
* terms, the heartbeat function must be called manually instead.
* @return Identification number of the current term
*/
function ensureCurrentTerm() external returns (uint64) {
return _ensureCurrentTerm();
}
/**
* @notice Transition up to `_maxRequestedTransitions` terms
* @param _maxRequestedTransitions Max number of term transitions allowed by the sender
* @return Identification number of the term ID after executing the heartbeat transitions
*/
function heartbeat(uint64 _maxRequestedTransitions) external returns (uint64) {
return _heartbeat(_maxRequestedTransitions);
}
/**
* @notice Ensure that a certain term has its randomness set. As we allow to draft disputes requested for previous terms, if there
* were mined more than 256 blocks for the current term, the blockhash of its randomness BN is no longer available, given
* round will be able to be drafted in the following term.
* @return Randomness of the current term
*/
function ensureCurrentTermRandomness() external returns (bytes32) {
// If the randomness for the given term was already computed, return
uint64 currentTermId = termId;
Term storage term = terms[currentTermId];
bytes32 termRandomness = term.randomness;
if (termRandomness != bytes32(0)) {
return termRandomness;
}
// Compute term randomness
bytes32 newRandomness = _computeTermRandomness(currentTermId);
require(newRandomness != bytes32(0), ERROR_TERM_RANDOMNESS_UNAVAILABLE);
term.randomness = newRandomness;
return newRandomness;
}
/**
* @dev Tell the term duration of the Court
* @return Duration in seconds of the Court term
*/
function getTermDuration() external view returns (uint64) {
return termDuration;
}
/**
* @dev Tell the last ensured term identification number
* @return Identification number of the last ensured term
*/
function getLastEnsuredTermId() external view returns (uint64) {
return _lastEnsuredTermId();
}
/**
* @dev Tell the current term identification number. Note that there may be pending term transitions.
* @return Identification number of the current term
*/
function getCurrentTermId() external view returns (uint64) {
return _currentTermId();
}
/**
* @dev Tell the number of terms the Court should transition to be up-to-date
* @return Number of terms the Court should transition to be up-to-date
*/
function getNeededTermTransitions() external view returns (uint64) {
return _neededTermTransitions();
}
/**
* @dev Tell the information related to a term based on its ID. Note that if the term has not been reached, the
* information returned won't be computed yet. This function allows querying future terms that were not computed yet.
* @param _termId ID of the term being queried
* @return startTime Term start time
* @return randomnessBN Block number used for randomness in the requested term
* @return randomness Randomness computed for the requested term
*/
function getTerm(uint64 _termId) external view returns (uint64 startTime, uint64 randomnessBN, bytes32 randomness) {
Term storage term = terms[_termId];
return (term.startTime, term.randomnessBN, term.randomness);
}
/**
* @dev Tell the randomness of a term even if it wasn't computed yet
* @param _termId Identification number of the term being queried
* @return Randomness of the requested term
*/
function getTermRandomness(uint64 _termId) external view termExists(_termId) returns (bytes32) {
return _computeTermRandomness(_termId);
}
/**
* @dev Internal function to ensure that the current term of the Court is up-to-date. If the Court is outdated by more than
* `MAX_AUTO_TERM_TRANSITIONS_ALLOWED` terms, the heartbeat function must be called manually.
* @return Identification number of the resultant term ID after executing the corresponding transitions
*/
function _ensureCurrentTerm() internal returns (uint64) {
// Check the required number of transitions does not exceeds the max allowed number to be processed automatically
uint64 requiredTransitions = _neededTermTransitions();
require(requiredTransitions <= MAX_AUTO_TERM_TRANSITIONS_ALLOWED, ERROR_TOO_MANY_TRANSITIONS);
// If there are no transitions pending, return the last ensured term id
if (uint256(requiredTransitions) == 0) {
return termId;
}
// Process transition if there is at least one pending
return _heartbeat(requiredTransitions);
}
/**
* @dev Internal function to transition the Court terms up to a requested number of terms
* @param _maxRequestedTransitions Max number of term transitions allowed by the sender
* @return Identification number of the resultant term ID after executing the requested transitions
*/
function _heartbeat(uint64 _maxRequestedTransitions) internal returns (uint64) {
// Transition the minimum number of terms between the amount requested and the amount actually needed
uint64 neededTransitions = _neededTermTransitions();
uint256 transitions = uint256(_maxRequestedTransitions < neededTransitions ? _maxRequestedTransitions : neededTransitions);
require(transitions > 0, ERROR_INVALID_TRANSITION_TERMS);
uint64 blockNumber = getBlockNumber64();
uint64 previousTermId = termId;
uint64 currentTermId = previousTermId;
for (uint256 transition = 1; transition <= transitions; transition++) {
// Term IDs are incremented by one based on the number of time periods since the Court started. Since time is represented in uint64,
// even if we chose the minimum duration possible for a term (1 second), we can ensure terms will never reach 2^64 since time is
// already assumed to fit in uint64.
Term storage previousTerm = terms[currentTermId++];
Term storage currentTerm = terms[currentTermId];
_onTermTransitioned(currentTermId);
// Set the start time of the new term. Note that we are using a constant term duration value to guarantee
// equally long terms, regardless of heartbeats.
currentTerm.startTime = previousTerm.startTime.add(termDuration);
// In order to draft a random number of guardians in a term, we use a randomness factor for each term based on a
// block number that is set once the term has started. Note that this information could not be known beforehand.
currentTerm.randomnessBN = blockNumber + 1;
}
termId = currentTermId;
emit Heartbeat(previousTermId, currentTermId);
return currentTermId;
}
/**
* @dev Internal function to delay the first term start time only if it wasn't reached yet
* @param _newFirstTermStartTime New timestamp in seconds when the court will open
*/
function _delayStartTime(uint64 _newFirstTermStartTime) internal {
require(_currentTermId() == 0, ERROR_CANNOT_DELAY_STARTED_COURT);
Term storage term = terms[0];
uint64 currentFirstTermStartTime = term.startTime.add(termDuration);
require(_newFirstTermStartTime > currentFirstTermStartTime, ERROR_CANNOT_DELAY_PAST_START_TIME);
// No need for SafeMath: we already checked above that `_newFirstTermStartTime` > `currentFirstTermStartTime` >= `termDuration`
term.startTime = _newFirstTermStartTime - termDuration;
emit StartTimeDelayed(currentFirstTermStartTime, _newFirstTermStartTime);
}
/**
* @dev Internal function to notify when a term has been transitioned. This function must be overridden to provide custom behavior.
* @param _termId Identification number of the new current term that has been transitioned
*/
function _onTermTransitioned(uint64 _termId) internal;
/**
* @dev Internal function to tell the last ensured term identification number
* @return Identification number of the last ensured term
*/
function _lastEnsuredTermId() internal view returns (uint64) {
return termId;
}
/**
* @dev Internal function to tell the current term identification number. Note that there may be pending term transitions.
* @return Identification number of the current term
*/
function _currentTermId() internal view returns (uint64) {
return termId.add(_neededTermTransitions());
}
/**
* @dev Internal function to tell the number of terms the Court should transition to be up-to-date
* @return Number of terms the Court should transition to be up-to-date
*/
function _neededTermTransitions() internal view returns (uint64) {
// Note that the Court is always initialized providing a start time for the first-term in the future. If that's the case,
// no term transitions are required.
uint64 currentTermStartTime = terms[termId].startTime;
if (getTimestamp64() < currentTermStartTime) {
return uint64(0);
}
// No need for SafeMath: we already know that the start time of the current term is in the past
return (getTimestamp64() - currentTermStartTime) / termDuration;
}
/**
* @dev Internal function to compute the randomness that will be used to draft guardians for the given term. This
* function assumes the given term exists. To determine the randomness factor for a term we use the hash of a
* block number that is set once the term has started to ensure it cannot be known beforehand. Note that the
* hash function being used only works for the 256 most recent block numbers.
* @param _termId Identification number of the term being queried
* @return Randomness computed for the given term
*/
function _computeTermRandomness(uint64 _termId) internal view returns (bytes32) {
Term storage term = terms[_termId];
require(getBlockNumber64() > term.randomnessBN, ERROR_TERM_RANDOMNESS_NOT_YET);
return blockhash(term.randomnessBN);
}
}
library PctHelpers {
using SafeMath for uint256;
uint256 internal constant PCT_BASE = 10000; // ‱ (1 / 10,000)
function isValid(uint16 _pct) internal pure returns (bool) {
return _pct <= PCT_BASE;
}
function pct(uint256 self, uint16 _pct) internal pure returns (uint256) {
return self.mul(uint256(_pct)) / PCT_BASE;
}
function pct256(uint256 self, uint256 _pct) internal pure returns (uint256) {
return self.mul(_pct) / PCT_BASE;
}
function pctIncrease(uint256 self, uint16 _pct) internal pure returns (uint256) {
// No need for SafeMath: for addition note that `PCT_BASE` is lower than (2^256 - 2^16)
return self.mul(PCT_BASE + uint256(_pct)) / PCT_BASE;
}
}
/*
* SPDX-License-Identifier: MIT
*/
/**
* @title ERC20 interface
* @dev see https://github.com/ethereum/EIPs/issues/20
*/
contract IERC20 {
event Transfer(address indexed from, address indexed to, uint256 value);
event Approval(address indexed owner, address indexed spender, uint256 value);
function totalSupply() external view returns (uint256);
function balanceOf(address _who) external view returns (uint256);
function allowance(address _owner, address _spender) external view returns (uint256);
function transfer(address _to, uint256 _value) external returns (bool);
function approve(address _spender, uint256 _value) external returns (bool);
function transferFrom(address _from, address _to, uint256 _value) external returns (bool);
}
interface IConfig {
/**
* @dev Tell the full Court configuration parameters at a certain term
* @param _termId Identification number of the term querying the Court config of
* @return token Address of the token used to pay for fees
* @return fees Array containing:
* 0. guardianFee Amount of fee tokens that is paid per guardian per dispute
* 1. draftFee Amount of fee tokens per guardian to cover the drafting cost
* 2. settleFee Amount of fee tokens per guardian to cover round settlement cost
* @return roundStateDurations Array containing the durations in terms of the different phases of a dispute:
* 0. evidenceTerms Max submitting evidence period duration in terms
* 1. commitTerms Commit period duration in terms
* 2. revealTerms Reveal period duration in terms
* 3. appealTerms Appeal period duration in terms
* 4. appealConfirmationTerms Appeal confirmation period duration in terms
* @return pcts Array containing:
* 0. penaltyPct Permyriad of min active tokens balance to be locked for each drafted guardian (‱ - 1/10,000)
* 1. finalRoundReduction Permyriad of fee reduction for the last appeal round (‱ - 1/10,000)
* @return roundParams Array containing params for rounds:
* 0. firstRoundGuardiansNumber Number of guardians to be drafted for the first round of disputes
* 1. appealStepFactor Increasing factor for the number of guardians of each round of a dispute
* 2. maxRegularAppealRounds Number of regular appeal rounds before the final round is triggered
* @return appealCollateralParams Array containing params for appeal collateral:
* 0. appealCollateralFactor Multiple of dispute fees required to appeal a preliminary ruling
* 1. appealConfirmCollateralFactor Multiple of dispute fees required to confirm appeal
* @return minActiveBalance Minimum amount of tokens guardians have to activate to participate in the Court
*/
function getConfig(uint64 _termId) external view
returns (
IERC20 feeToken,
uint256[3] memory fees,
uint64[5] memory roundStateDurations,
uint16[2] memory pcts,
uint64[4] memory roundParams,
uint256[2] memory appealCollateralParams,
uint256 minActiveBalance
);
/**
* @dev Tell the draft config at a certain term
* @param _termId Identification number of the term querying the draft config of
* @return feeToken Address of the token used to pay for fees
* @return draftFee Amount of fee tokens per guardian to cover the drafting cost
* @return penaltyPct Permyriad of min active tokens balance to be locked for each drafted guardian (‱ - 1/10,000)
*/
function getDraftConfig(uint64 _termId) external view returns (IERC20 feeToken, uint256 draftFee, uint16 penaltyPct);
/**
* @dev Tell the min active balance config at a certain term
* @param _termId Term querying the min active balance config of
* @return Minimum amount of tokens guardians have to activate to participate in the Court
*/
function getMinActiveBalance(uint64 _termId) external view returns (uint256);
}
contract CourtConfigData {
struct Config {
FeesConfig fees; // Full fees-related config
DisputesConfig disputes; // Full disputes-related config
uint256 minActiveBalance; // Minimum amount of tokens guardians have to activate to participate in the Court
}
struct FeesConfig {
IERC20 token; // ERC20 token to be used for the fees of the Court
uint16 finalRoundReduction; // Permyriad of fees reduction applied for final appeal round (‱ - 1/10,000)
uint256 guardianFee; // Amount of tokens paid to draft a guardian to adjudicate a dispute
uint256 draftFee; // Amount of tokens paid per round to cover the costs of drafting guardians
uint256 settleFee; // Amount of tokens paid per round to cover the costs of slashing guardians
}
struct DisputesConfig {
uint64 evidenceTerms; // Max submitting evidence period duration in terms
uint64 commitTerms; // Committing period duration in terms
uint64 revealTerms; // Revealing period duration in terms
uint64 appealTerms; // Appealing period duration in terms
uint64 appealConfirmTerms; // Confirmation appeal period duration in terms
uint16 penaltyPct; // Permyriad of min active tokens balance to be locked for each drafted guardian (‱ - 1/10,000)
uint64 firstRoundGuardiansNumber; // Number of guardians drafted on first round
uint64 appealStepFactor; // Factor in which the guardians number is increased on each appeal
uint64 finalRoundLockTerms; // Period a coherent guardian in the final round will remain locked
uint256 maxRegularAppealRounds; // Before the final appeal
uint256 appealCollateralFactor; // Permyriad multiple of dispute fees required to appeal a preliminary ruling (‱ - 1/10,000)
uint256 appealConfirmCollateralFactor; // Permyriad multiple of dispute fees required to confirm appeal (‱ - 1/10,000)
}
struct DraftConfig {
IERC20 feeToken; // ERC20 token to be used for the fees of the Court
uint16 penaltyPct; // Permyriad of min active tokens balance to be locked for each drafted guardian (‱ - 1/10,000)
uint256 draftFee; // Amount of tokens paid per round to cover the costs of drafting guardians
}
}
contract CourtConfig is IConfig, CourtConfigData {
using SafeMath64 for uint64;
using PctHelpers for uint256;
string private constant ERROR_TOO_OLD_TERM = "CONF_TOO_OLD_TERM";
string private constant ERROR_INVALID_PENALTY_PCT = "CONF_INVALID_PENALTY_PCT";
string private constant ERROR_INVALID_FINAL_ROUND_REDUCTION_PCT = "CONF_INVALID_FINAL_ROUND_RED_PCT";
string private constant ERROR_INVALID_MAX_APPEAL_ROUNDS = "CONF_INVALID_MAX_APPEAL_ROUNDS";
string private constant ERROR_LARGE_ROUND_PHASE_DURATION = "CONF_LARGE_ROUND_PHASE_DURATION";
string private constant ERROR_BAD_INITIAL_GUARDIANS_NUMBER = "CONF_BAD_INITIAL_GUARDIAN_NUMBER";
string private constant ERROR_BAD_APPEAL_STEP_FACTOR = "CONF_BAD_APPEAL_STEP_FACTOR";
string private constant ERROR_ZERO_COLLATERAL_FACTOR = "CONF_ZERO_COLLATERAL_FACTOR";
string private constant ERROR_ZERO_MIN_ACTIVE_BALANCE = "CONF_ZERO_MIN_ACTIVE_BALANCE";
// Max number of terms that each of the different adjudication states can last (if lasted 1h, this would be a year)
uint64 internal constant MAX_ADJ_STATE_DURATION = 8670;
// Cap the max number of regular appeal rounds
uint256 internal constant MAX_REGULAR_APPEAL_ROUNDS_LIMIT = 10;
// Future term ID in which a config change has been scheduled
uint64 private configChangeTermId;
// List of all the configs used in the Court
Config[] private configs;
// List of configs indexed by id
mapping (uint64 => uint256) private configIdByTerm;
event NewConfig(uint64 fromTermId, uint64 courtConfigId);
/**
* @dev Constructor function
* @param _feeToken Address of the token contract that is used to pay for fees
* @param _fees Array containing:
* 0. guardianFee Amount of fee tokens that is paid per guardian per dispute
* 1. draftFee Amount of fee tokens per guardian to cover the drafting cost
* 2. settleFee Amount of fee tokens per guardian to cover round settlement cost
* @param _roundStateDurations Array containing the durations in terms of the different phases of a dispute:
* 0. evidenceTerms Max submitting evidence period duration in terms
* 1. commitTerms Commit period duration in terms
* 2. revealTerms Reveal period duration in terms
* 3. appealTerms Appeal period duration in terms
* 4. appealConfirmationTerms Appeal confirmation period duration in terms
* @param _pcts Array containing:
* 0. penaltyPct Permyriad of min active tokens balance to be locked for each drafted guardian (‱ - 1/10,000)
* 1. finalRoundReduction Permyriad of fee reduction for the last appeal round (‱ - 1/10,000)
* @param _roundParams Array containing params for rounds:
* 0. firstRoundGuardiansNumber Number of guardians to be drafted for the first round of disputes
* 1. appealStepFactor Increasing factor for the number of guardians of each round of a dispute
* 2. maxRegularAppealRounds Number of regular appeal rounds before the final round is triggered
* 3. finalRoundLockTerms Number of terms that a coherent guardian in a final round is disallowed to withdraw (to prevent 51% attacks)
* @param _appealCollateralParams Array containing params for appeal collateral:
* 0. appealCollateralFactor Multiple of dispute fees required to appeal a preliminary ruling
* 1. appealConfirmCollateralFactor Multiple of dispute fees required to confirm appeal
* @param _minActiveBalance Minimum amount of guardian tokens that can be activated
*/
constructor(
IERC20 _feeToken,
uint256[3] memory _fees,
uint64[5] memory _roundStateDurations,
uint16[2] memory _pcts,
uint64[4] memory _roundParams,
uint256[2] memory _appealCollateralParams,
uint256 _minActiveBalance
)
public
{
// Leave config at index 0 empty for non-scheduled config changes
configs.length = 1;
_setConfig(
0,
0,
_feeToken,
_fees,
_roundStateDurations,
_pcts,
_roundParams,
_appealCollateralParams,
_minActiveBalance
);
}
/**
* @dev Tell the full Court configuration parameters at a certain term
* @param _termId Identification number of the term querying the Court config of
* @return token Address of the token used to pay for fees
* @return fees Array containing:
* 0. guardianFee Amount of fee tokens that is paid per guardian per dispute
* 1. draftFee Amount of fee tokens per guardian to cover the drafting cost
* 2. settleFee Amount of fee tokens per guardian to cover round settlement cost
* @return roundStateDurations Array containing the durations in terms of the different phases of a dispute:
* 0. evidenceTerms Max submitting evidence period duration in terms
* 1. commitTerms Commit period duration in terms
* 2. revealTerms Reveal period duration in terms
* 3. appealTerms Appeal period duration in terms
* 4. appealConfirmationTerms Appeal confirmation period duration in terms
* @return pcts Array containing:
* 0. penaltyPct Permyriad of min active tokens balance to be locked for each drafted guardian (‱ - 1/10,000)
* 1. finalRoundReduction Permyriad of fee reduction for the last appeal round (‱ - 1/10,000)
* @return roundParams Array containing params for rounds:
* 0. firstRoundGuardiansNumber Number of guardians to be drafted for the first round of disputes
* 1. appealStepFactor Increasing factor for the number of guardians of each round of a dispute
* 2. maxRegularAppealRounds Number of regular appeal rounds before the final round is triggered
* @return appealCollateralParams Array containing params for appeal collateral:
* 0. appealCollateralFactor Multiple of dispute fees required to appeal a preliminary ruling
* 1. appealConfirmCollateralFactor Multiple of dispute fees required to confirm appeal
* @return minActiveBalance Minimum amount of tokens guardians have to activate to participate in the Court
*/
function getConfig(uint64 _termId) external view
returns (
IERC20 feeToken,
uint256[3] memory fees,
uint64[5] memory roundStateDurations,
uint16[2] memory pcts,
uint64[4] memory roundParams,
uint256[2] memory appealCollateralParams,
uint256 minActiveBalance
);
/**
* @dev Tell the draft config at a certain term
* @param _termId Identification number of the term querying the draft config of
* @return feeToken Address of the token used to pay for fees
* @return draftFee Amount of fee tokens per guardian to cover the drafting cost
* @return penaltyPct Permyriad of min active tokens balance to be locked for each drafted guardian (‱ - 1/10,000)
*/
function getDraftConfig(uint64 _termId) external view returns (IERC20 feeToken, uint256 draftFee, uint16 penaltyPct);
/**
* @dev Tell the min active balance config at a certain term
* @param _termId Term querying the min active balance config of
* @return Minimum amount of tokens guardians have to activate to participate in the Court
*/
function getMinActiveBalance(uint64 _termId) external view returns (uint256);
/**
* @dev Tell the term identification number of the next scheduled config change
* @return Term identification number of the next scheduled config change
*/
function getConfigChangeTermId() external view returns (uint64) {
return configChangeTermId;
}
/**
* @dev Internal to make sure to set a config for the new term, it will copy the previous term config if none
* @param _termId Identification number of the new current term that has been transitioned
*/
function _ensureTermConfig(uint64 _termId) internal {
// If the term being transitioned had no config change scheduled, keep the previous one
uint256 currentConfigId = configIdByTerm[_termId];
if (currentConfigId == 0) {
uint256 previousConfigId = configIdByTerm[_termId.sub(1)];
configIdByTerm[_termId] = previousConfigId;
}
}
/**
* @dev Assumes that sender it's allowed (either it's from governor or it's on init)
* @param _termId Identification number of the current Court term
* @param _fromTermId Identification number of the term in which the config will be effective at
* @param _feeToken Address of the token contract that is used to pay for fees.
* @param _fees Array containing:
* 0. guardianFee Amount of fee tokens that is paid per guardian per dispute
* 1. draftFee Amount of fee tokens per guardian to cover the drafting cost
* 2. settleFee Amount of fee tokens per guardian to cover round settlement cost
* @param _roundStateDurations Array containing the durations in terms of the different phases of a dispute:
* 0. evidenceTerms Max submitting evidence period duration in terms
* 1. commitTerms Commit period duration in terms
* 2. revealTerms Reveal period duration in terms
* 3. appealTerms Appeal period duration in terms
* 4. appealConfirmationTerms Appeal confirmation period duration in terms
* @param _pcts Array containing:
* 0. penaltyPct Permyriad of min active tokens balance to be locked for each drafted guardian (‱ - 1/10,000)
* 1. finalRoundReduction Permyriad of fee reduction for the last appeal round (‱ - 1/10,000)
* @param _roundParams Array containing params for rounds:
* 0. firstRoundGuardiansNumber Number of guardians to be drafted for the first round of disputes
* 1. appealStepFactor Increasing factor for the number of guardians of each round of a dispute
* 2. maxRegularAppealRounds Number of regular appeal rounds before the final round is triggered
* 3. finalRoundLockTerms Number of terms that a coherent guardian in a final round is disallowed to withdraw (to prevent 51% attacks)
* @param _appealCollateralParams Array containing params for appeal collateral:
* 0. appealCollateralFactor Multiple of dispute fees required to appeal a preliminary ruling
* 1. appealConfirmCollateralFactor Multiple of dispute fees required to confirm appeal
* @param _minActiveBalance Minimum amount of guardian tokens that can be activated
*/
function _setConfig(
uint64 _termId,
uint64 _fromTermId,
IERC20 _feeToken,
uint256[3] memory _fees,
uint64[5] memory _roundStateDurations,
uint16[2] memory _pcts,
uint64[4] memory _roundParams,
uint256[2] memory _appealCollateralParams,
uint256 _minActiveBalance
)
internal
{
// If the current term is not zero, changes must be scheduled at least after the current period.
// No need to ensure delays for on-going disputes since these already use their creation term for that.
require(_termId == 0 || _fromTermId > _termId, ERROR_TOO_OLD_TERM);
// Make sure appeal collateral factors are greater than zero
require(_appealCollateralParams[0] > 0 && _appealCollateralParams[1] > 0, ERROR_ZERO_COLLATERAL_FACTOR);
// Make sure the given penalty and final round reduction pcts are not greater than 100%
require(PctHelpers.isValid(_pcts[0]), ERROR_INVALID_PENALTY_PCT);
require(PctHelpers.isValid(_pcts[1]), ERROR_INVALID_FINAL_ROUND_REDUCTION_PCT);
// Disputes must request at least one guardian to be drafted initially
require(_roundParams[0] > 0, ERROR_BAD_INITIAL_GUARDIANS_NUMBER);
// Prevent that further rounds have zero guardians
require(_roundParams[1] > 0, ERROR_BAD_APPEAL_STEP_FACTOR);
// Make sure the max number of appeals allowed does not reach the limit
uint256 _maxRegularAppealRounds = _roundParams[2];
bool isMaxAppealRoundsValid = _maxRegularAppealRounds > 0 && _maxRegularAppealRounds <= MAX_REGULAR_APPEAL_ROUNDS_LIMIT;
require(isMaxAppealRoundsValid, ERROR_INVALID_MAX_APPEAL_ROUNDS);
// Make sure each adjudication round phase duration is valid
for (uint i = 0; i < _roundStateDurations.length; i++) {
require(_roundStateDurations[i] > 0 && _roundStateDurations[i] < MAX_ADJ_STATE_DURATION, ERROR_LARGE_ROUND_PHASE_DURATION);
}
// Make sure min active balance is not zero
require(_minActiveBalance > 0, ERROR_ZERO_MIN_ACTIVE_BALANCE);
// If there was a config change already scheduled, reset it (in that case we will overwrite last array item).
// Otherwise, schedule a new config.
if (configChangeTermId > _termId) {
configIdByTerm[configChangeTermId] = 0;
} else {
configs.length++;
}
uint64 courtConfigId = uint64(configs.length - 1);
Config storage config = configs[courtConfigId];
config.fees = FeesConfig({
token: _feeToken,
guardianFee: _fees[0],
draftFee: _fees[1],
settleFee: _fees[2],
finalRoundReduction: _pcts[1]
});
config.disputes = DisputesConfig({
evidenceTerms: _roundStateDurations[0],
commitTerms: _roundStateDurations[1],
revealTerms: _roundStateDurations[2],
appealTerms: _roundStateDurations[3],
appealConfirmTerms: _roundStateDurations[4],
penaltyPct: _pcts[0],
firstRoundGuardiansNumber: _roundParams[0],
appealStepFactor: _roundParams[1],
maxRegularAppealRounds: _maxRegularAppealRounds,
finalRoundLockTerms: _roundParams[3],
appealCollateralFactor: _appealCollateralParams[0],
appealConfirmCollateralFactor: _appealCollateralParams[1]
});
config.minActiveBalance = _minActiveBalance;
configIdByTerm[_fromTermId] = courtConfigId;
configChangeTermId = _fromTermId;
emit NewConfig(_fromTermId, courtConfigId);
}
/**
* @dev Internal function to get the Court config for a given term
* @param _termId Identification number of the term querying the Court config of
* @param _lastEnsuredTermId Identification number of the last ensured term of the Court
* @return token Address of the token used to pay for fees
* @return fees Array containing:
* 0. guardianFee Amount of fee tokens that is paid per guardian per dispute
* 1. draftFee Amount of fee tokens per guardian to cover the drafting cost
* 2. settleFee Amount of fee tokens per guardian to cover round settlement cost
* @return roundStateDurations Array containing the durations in terms of the different phases of a dispute:
* 0. evidenceTerms Max submitting evidence period duration in terms
* 1. commitTerms Commit period duration in terms
* 2. revealTerms Reveal period duration in terms
* 3. appealTerms Appeal period duration in terms
* 4. appealConfirmationTerms Appeal confirmation period duration in terms
* @return pcts Array containing:
* 0. penaltyPct Permyriad of min active tokens balance to be locked for each drafted guardian (‱ - 1/10,000)
* 1. finalRoundReduction Permyriad of fee reduction for the last appeal round (‱ - 1/10,000)
* @return roundParams Array containing params for rounds:
* 0. firstRoundGuardiansNumber Number of guardians to be drafted for the first round of disputes
* 1. appealStepFactor Increasing factor for the number of guardians of each round of a dispute
* 2. maxRegularAppealRounds Number of regular appeal rounds before the final round is triggered
* 3. finalRoundLockTerms Number of terms that a coherent guardian in a final round is disallowed to withdraw (to prevent 51% attacks)
* @return appealCollateralParams Array containing params for appeal collateral:
* 0. appealCollateralFactor Multiple of dispute fees required to appeal a preliminary ruling
* 1. appealConfirmCollateralFactor Multiple of dispute fees required to confirm appeal
* @return minActiveBalance Minimum amount of guardian tokens that can be activated
*/
function _getConfigAt(uint64 _termId, uint64 _lastEnsuredTermId) internal view
returns (
IERC20 feeToken,
uint256[3] memory fees,
uint64[5] memory roundStateDurations,
uint16[2] memory pcts,
uint64[4] memory roundParams,
uint256[2] memory appealCollateralParams,
uint256 minActiveBalance
)
{
Config storage config = _getConfigFor(_termId, _lastEnsuredTermId);
FeesConfig storage feesConfig = config.fees;
feeToken = feesConfig.token;
fees = [feesConfig.guardianFee, feesConfig.draftFee, feesConfig.settleFee];
DisputesConfig storage disputesConfig = config.disputes;
roundStateDurations = [
disputesConfig.evidenceTerms,
disputesConfig.commitTerms,
disputesConfig.revealTerms,
disputesConfig.appealTerms,
disputesConfig.appealConfirmTerms
];
pcts = [disputesConfig.penaltyPct, feesConfig.finalRoundReduction];
roundParams = [
disputesConfig.firstRoundGuardiansNumber,
disputesConfig.appealStepFactor,
uint64(disputesConfig.maxRegularAppealRounds),
disputesConfig.finalRoundLockTerms
];
appealCollateralParams = [disputesConfig.appealCollateralFactor, disputesConfig.appealConfirmCollateralFactor];
minActiveBalance = config.minActiveBalance;
}
/**
* @dev Tell the draft config at a certain term
* @param _termId Identification number of the term querying the draft config of
* @param _lastEnsuredTermId Identification number of the last ensured term of the Court
* @return feeToken Address of the token used to pay for fees
* @return draftFee Amount of fee tokens per guardian to cover the drafting cost
* @return penaltyPct Permyriad of min active tokens balance to be locked for each drafted guardian (‱ - 1/10,000)
*/
function _getDraftConfig(uint64 _termId, uint64 _lastEnsuredTermId) internal view
returns (IERC20 feeToken, uint256 draftFee, uint16 penaltyPct)
{
Config storage config = _getConfigFor(_termId, _lastEnsuredTermId);
return (config.fees.token, config.fees.draftFee, config.disputes.penaltyPct);
}
/**
* @dev Internal function to get the min active balance config for a given term
* @param _termId Identification number of the term querying the min active balance config of
* @param _lastEnsuredTermId Identification number of the last ensured term of the Court
* @return Minimum amount of guardian tokens that can be activated at the given term
*/
function _getMinActiveBalance(uint64 _termId, uint64 _lastEnsuredTermId) internal view returns (uint256) {
Config storage config = _getConfigFor(_termId, _lastEnsuredTermId);
return config.minActiveBalance;
}
/**
* @dev Internal function to get the Court config for a given term
* @param _termId Identification number of the term querying the min active balance config of
* @param _lastEnsuredTermId Identification number of the last ensured term of the Court
* @return Court config for the given term
*/
function _getConfigFor(uint64 _termId, uint64 _lastEnsuredTermId) internal view returns (Config storage) {
uint256 id = _getConfigIdFor(_termId, _lastEnsuredTermId);
return configs[id];
}
/**
* @dev Internal function to get the Court config ID for a given term
* @param _termId Identification number of the term querying the Court config of
* @param _lastEnsuredTermId Identification number of the last ensured term of the Court
* @return Identification number of the config for the given terms
*/
function _getConfigIdFor(uint64 _termId, uint64 _lastEnsuredTermId) internal view returns (uint256) {
// If the given term is lower or equal to the last ensured Court term, it is safe to use a past Court config
if (_termId <= _lastEnsuredTermId) {
return configIdByTerm[_termId];
}
// If the given term is in the future but there is a config change scheduled before it, use the incoming config
uint64 scheduledChangeTermId = configChangeTermId;
if (scheduledChangeTermId <= _termId) {
return configIdByTerm[scheduledChangeTermId];
}
// If no changes are scheduled, use the Court config of the last ensured term
return configIdByTerm[_lastEnsuredTermId];
}
}
/*
* SPDX-License-Identifier: MIT
*/
interface IArbitrator {
/**
* @dev Create a dispute over the Arbitrable sender with a number of possible rulings
* @param _possibleRulings Number of possible rulings allowed for the dispute
* @param _metadata Optional metadata that can be used to provide additional information on the dispute to be created
* @return Dispute identification number
*/
function createDispute(uint256 _possibleRulings, bytes calldata _metadata) external returns (uint256);
/**
* @dev Submit evidence for a dispute
* @param _disputeId Id of the dispute in the Court
* @param _submitter Address of the account submitting the evidence
* @param _evidence Data submitted for the evidence related to the dispute
*/
function submitEvidence(uint256 _disputeId, address _submitter, bytes calldata _evidence) external;
/**
* @dev Close the evidence period of a dispute
* @param _disputeId Identification number of the dispute to close its evidence submitting period
*/
function closeEvidencePeriod(uint256 _disputeId) external;
/**
* @notice Rule dispute #`_disputeId` if ready
* @param _disputeId Identification number of the dispute to be ruled
* @return subject Subject associated to the dispute
* @return ruling Ruling number computed for the given dispute
*/
function rule(uint256 _disputeId) external returns (address subject, uint256 ruling);
/**
* @dev Tell the dispute fees information to create a dispute
* @return recipient Address where the corresponding dispute fees must be transferred to
* @return feeToken ERC20 token used for the fees
* @return feeAmount Total amount of fees that must be allowed to the recipient
*/
function getDisputeFees() external view returns (address recipient, IERC20 feeToken, uint256 feeAmount);
/**
* @dev Tell the payments recipient address
* @return Address of the payments recipient module
*/
function getPaymentsRecipient() external view returns (address);
}
/*
* SPDX-License-Identifier: MIT
*/
/**
* @dev The Arbitrable instances actually don't require to follow any specific interface.
* Note that this is actually optional, although it does allow the Court to at least have a way to identify a specific set of instances.
*/
contract IArbitrable {
/**
* @dev Emitted when an IArbitrable instance's dispute is ruled by an IArbitrator
* @param arbitrator IArbitrator instance ruling the dispute
* @param disputeId Identification number of the dispute being ruled by the arbitrator
* @param ruling Ruling given by the arbitrator
*/
event Ruled(IArbitrator indexed arbitrator, uint256 indexed disputeId, uint256 ruling);
}
interface IDisputeManager {
enum DisputeState {
PreDraft,
Adjudicating,
Ruled
}
enum AdjudicationState {
Invalid,
Committing,
Revealing,
Appealing,
ConfirmingAppeal,
Ended
}
/**
* @dev Create a dispute to be drafted in a future term
* @param _subject Arbitrable instance creating the dispute
* @param _possibleRulings Number of possible rulings allowed for the drafted guardians to vote on the dispute
* @param _metadata Optional metadata that can be used to provide additional information on the dispute to be created
* @return Dispute identification number
*/
function createDispute(IArbitrable _subject, uint8 _possibleRulings, bytes calldata _metadata) external returns (uint256);
/**
* @dev Submit evidence for a dispute
* @param _subject Arbitrable instance submitting the dispute
* @param _disputeId Identification number of the dispute receiving new evidence
* @param _submitter Address of the account submitting the evidence
* @param _evidence Data submitted for the evidence of the dispute
*/
function submitEvidence(IArbitrable _subject, uint256 _disputeId, address _submitter, bytes calldata _evidence) external;
/**
* @dev Close the evidence period of a dispute
* @param _subject IArbitrable instance requesting to close the evidence submission period
* @param _disputeId Identification number of the dispute to close its evidence submitting period
*/
function closeEvidencePeriod(IArbitrable _subject, uint256 _disputeId) external;
/**
* @dev Draft guardians for the next round of a dispute
* @param _disputeId Identification number of the dispute to be drafted
*/
function draft(uint256 _disputeId) external;
/**
* @dev Appeal round of a dispute in favor of a certain ruling
* @param _disputeId Identification number of the dispute being appealed
* @param _roundId Identification number of the dispute round being appealed
* @param _ruling Ruling appealing a dispute round in favor of
*/
function createAppeal(uint256 _disputeId, uint256 _roundId, uint8 _ruling) external;
/**
* @dev Confirm appeal for a round of a dispute in favor of a ruling
* @param _disputeId Identification number of the dispute confirming an appeal of
* @param _roundId Identification number of the dispute round confirming an appeal of
* @param _ruling Ruling being confirmed against a dispute round appeal
*/
function confirmAppeal(uint256 _disputeId, uint256 _roundId, uint8 _ruling) external;
/**
* @dev Compute the final ruling for a dispute
* @param _disputeId Identification number of the dispute to compute its final ruling
* @return subject Arbitrable instance associated to the dispute
* @return finalRuling Final ruling decided for the given dispute
*/
function computeRuling(uint256 _disputeId) external returns (IArbitrable subject, uint8 finalRuling);
/**
* @dev Settle penalties for a round of a dispute
* @param _disputeId Identification number of the dispute to settle penalties for
* @param _roundId Identification number of the dispute round to settle penalties for
* @param _guardiansToSettle Maximum number of guardians to be slashed in this call
*/
function settlePenalties(uint256 _disputeId, uint256 _roundId, uint256 _guardiansToSettle) external;
/**
* @dev Claim rewards for a round of a dispute for guardian
* @dev For regular rounds, it will only reward winning guardians
* @param _disputeId Identification number of the dispute to settle rewards for
* @param _roundId Identification number of the dispute round to settle rewards for
* @param _guardian Address of the guardian to settle their rewards
*/
function settleReward(uint256 _disputeId, uint256 _roundId, address _guardian) external;
/**
* @dev Settle appeal deposits for a round of a dispute
* @param _disputeId Identification number of the dispute to settle appeal deposits for
* @param _roundId Identification number of the dispute round to settle appeal deposits for
*/
function settleAppealDeposit(uint256 _disputeId, uint256 _roundId) external;
/**
* @dev Tell the amount of token fees required to create a dispute
* @return feeToken ERC20 token used for the fees
* @return feeAmount Total amount of fees to be paid for a dispute at the given term
*/
function getDisputeFees() external view returns (IERC20 feeToken, uint256 feeAmount);
/**
* @dev Tell information of a certain dispute
* @param _disputeId Identification number of the dispute being queried
* @return subject Arbitrable subject being disputed
* @return possibleRulings Number of possible rulings allowed for the drafted guardians to vote on the dispute
* @return state Current state of the dispute being queried: pre-draft, adjudicating, or ruled
* @return finalRuling The winning ruling in case the dispute is finished
* @return lastRoundId Identification number of the last round created for the dispute
* @return createTermId Identification number of the term when the dispute was created
*/
function getDispute(uint256 _disputeId) external view
returns (IArbitrable subject, uint8 possibleRulings, DisputeState state, uint8 finalRuling, uint256 lastRoundId, uint64 createTermId);
/**
* @dev Tell information of a certain adjudication round
* @param _disputeId Identification number of the dispute being queried
* @param _roundId Identification number of the round being queried
* @return draftTerm Term from which the requested round can be drafted
* @return delayedTerms Number of terms the given round was delayed based on its requested draft term id
* @return guardiansNumber Number of guardians requested for the round
* @return selectedGuardians Number of guardians already selected for the requested round
* @return settledPenalties Whether or not penalties have been settled for the requested round
* @return collectedTokens Amount of guardian tokens that were collected from slashed guardians for the requested round
* @return coherentGuardians Number of guardians that voted in favor of the final ruling in the requested round
* @return state Adjudication state of the requested round
*/
function getRound(uint256 _disputeId, uint256 _roundId) external view
returns (
uint64 draftTerm,
uint64 delayedTerms,
uint64 guardiansNumber,
uint64 selectedGuardians,
uint256 guardianFees,
bool settledPenalties,
uint256 collectedTokens,
uint64 coherentGuardians,
AdjudicationState state
);
/**
* @dev Tell appeal-related information of a certain adjudication round
* @param _disputeId Identification number of the dispute being queried
* @param _roundId Identification number of the round being queried
* @return maker Address of the account appealing the given round
* @return appealedRuling Ruling confirmed by the appealer of the given round
* @return taker Address of the account confirming the appeal of the given round
* @return opposedRuling Ruling confirmed by the appeal taker of the given round
*/
function getAppeal(uint256 _disputeId, uint256 _roundId) external view
returns (address maker, uint64 appealedRuling, address taker, uint64 opposedRuling);
/**
* @dev Tell information related to the next round due to an appeal of a certain round given.
* @param _disputeId Identification number of the dispute being queried
* @param _roundId Identification number of the round requesting the appeal details of
* @return nextRoundStartTerm Term ID from which the next round will start
* @return nextRoundGuardiansNumber Guardians number for the next round
* @return newDisputeState New state for the dispute associated to the given round after the appeal
* @return feeToken ERC20 token used for the next round fees
* @return guardianFees Total amount of fees to be distributed between the winning guardians of the next round
* @return totalFees Total amount of fees for a regular round at the given term
* @return appealDeposit Amount to be deposit of fees for a regular round at the given term
* @return confirmAppealDeposit Total amount of fees for a regular round at the given term
*/
function getNextRoundDetails(uint256 _disputeId, uint256 _roundId) external view
returns (
uint64 nextRoundStartTerm,
uint64 nextRoundGuardiansNumber,
DisputeState newDisputeState,
IERC20 feeToken,
uint256 totalFees,
uint256 guardianFees,
uint256 appealDeposit,
uint256 confirmAppealDeposit
);
/**
* @dev Tell guardian-related information of a certain adjudication round
* @param _disputeId Identification number of the dispute being queried
* @param _roundId Identification number of the round being queried
* @param _guardian Address of the guardian being queried
* @return weight Guardian weight drafted for the requested round
* @return rewarded Whether or not the given guardian was rewarded based on the requested round
*/
function getGuardian(uint256 _disputeId, uint256 _roundId, address _guardian) external view returns (uint64 weight, bool rewarded);
}
contract Controller is IsContract, ModuleIds, CourtClock, CourtConfig, ACL {
string private constant ERROR_SENDER_NOT_GOVERNOR = "CTR_SENDER_NOT_GOVERNOR";
string private constant ERROR_INVALID_GOVERNOR_ADDRESS = "CTR_INVALID_GOVERNOR_ADDRESS";
string private constant ERROR_MODULE_NOT_SET = "CTR_MODULE_NOT_SET";
string private constant ERROR_MODULE_ALREADY_ENABLED = "CTR_MODULE_ALREADY_ENABLED";
string private constant ERROR_MODULE_ALREADY_DISABLED = "CTR_MODULE_ALREADY_DISABLED";
string private constant ERROR_DISPUTE_MANAGER_NOT_ACTIVE = "CTR_DISPUTE_MANAGER_NOT_ACTIVE";
string private constant ERROR_CUSTOM_FUNCTION_NOT_SET = "CTR_CUSTOM_FUNCTION_NOT_SET";
string private constant ERROR_IMPLEMENTATION_NOT_CONTRACT = "CTR_IMPLEMENTATION_NOT_CONTRACT";
string private constant ERROR_INVALID_IMPLS_INPUT_LENGTH = "CTR_INVALID_IMPLS_INPUT_LENGTH";
address private constant ZERO_ADDRESS = address(0);
/**
* @dev Governor of the whole system. Set of three addresses to recover funds, change configuration settings and setup modules
*/
struct Governor {
address funds; // This address can be unset at any time. It is allowed to recover funds from the ControlledRecoverable modules
address config; // This address is meant not to be unset. It is allowed to change the different configurations of the whole system
address modules; // This address can be unset at any time. It is allowed to plug/unplug modules from the system
}
/**
* @dev Module information
*/
struct Module {
bytes32 id; // ID associated to a module
bool disabled; // Whether the module is disabled
}
// Governor addresses of the system
Governor private governor;
// List of current modules registered for the system indexed by ID
mapping (bytes32 => address) internal currentModules;
// List of all historical modules registered for the system indexed by address
mapping (address => Module) internal allModules;
// List of custom function targets indexed by signature
mapping (bytes4 => address) internal customFunctions;
event ModuleSet(bytes32 id, address addr);
event ModuleEnabled(bytes32 id, address addr);
event ModuleDisabled(bytes32 id, address addr);
event CustomFunctionSet(bytes4 signature, address target);
event FundsGovernorChanged(address previousGovernor, address currentGovernor);
event ConfigGovernorChanged(address previousGovernor, address currentGovernor);
event ModulesGovernorChanged(address previousGovernor, address currentGovernor);
/**
* @dev Ensure the msg.sender is the funds governor
*/
modifier onlyFundsGovernor {
require(msg.sender == governor.funds, ERROR_SENDER_NOT_GOVERNOR);
_;
}
/**
* @dev Ensure the msg.sender is the modules governor
*/
modifier onlyConfigGovernor {
require(msg.sender == governor.config, ERROR_SENDER_NOT_GOVERNOR);
_;
}
/**
* @dev Ensure the msg.sender is the modules governor
*/
modifier onlyModulesGovernor {
require(msg.sender == governor.modules, ERROR_SENDER_NOT_GOVERNOR);
_;
}
/**
* @dev Ensure the given dispute manager is active
*/
modifier onlyActiveDisputeManager(IDisputeManager _disputeManager) {
require(!_isModuleDisabled(address(_disputeManager)), ERROR_DISPUTE_MANAGER_NOT_ACTIVE);
_;
}
/**
* @dev Constructor function
* @param _termParams Array containing:
* 0. _termDuration Duration in seconds per term
* 1. _firstTermStartTime Timestamp in seconds when the court will open (to give time for guardian on-boarding)
* @param _governors Array containing:
* 0. _fundsGovernor Address of the funds governor
* 1. _configGovernor Address of the config governor
* 2. _modulesGovernor Address of the modules governor
* @param _feeToken Address of the token contract that is used to pay for fees
* @param _fees Array containing:
* 0. guardianFee Amount of fee tokens that is paid per guardian per dispute
* 1. draftFee Amount of fee tokens per guardian to cover the drafting cost
* 2. settleFee Amount of fee tokens per guardian to cover round settlement cost
* @param _roundStateDurations Array containing the durations in terms of the different phases of a dispute:
* 0. evidenceTerms Max submitting evidence period duration in terms
* 1. commitTerms Commit period duration in terms
* 2. revealTerms Reveal period duration in terms
* 3. appealTerms Appeal period duration in terms
* 4. appealConfirmationTerms Appeal confirmation period duration in terms
* @param _pcts Array containing:
* 0. penaltyPct Permyriad of min active tokens balance to be locked to each drafted guardians (‱ - 1/10,000)
* 1. finalRoundReduction Permyriad of fee reduction for the last appeal round (‱ - 1/10,000)
* @param _roundParams Array containing params for rounds:
* 0. firstRoundGuardiansNumber Number of guardians to be drafted for the first round of disputes
* 1. appealStepFactor Increasing factor for the number of guardians of each round of a dispute
* 2. maxRegularAppealRounds Number of regular appeal rounds before the final round is triggered
* 3. finalRoundLockTerms Number of terms that a coherent guardian in a final round is disallowed to withdraw (to prevent 51% attacks)
* @param _appealCollateralParams Array containing params for appeal collateral:
* 1. appealCollateralFactor Permyriad multiple of dispute fees required to appeal a preliminary ruling
* 2. appealConfirmCollateralFactor Permyriad multiple of dispute fees required to confirm appeal
* @param _minActiveBalance Minimum amount of guardian tokens that can be activated
*/
constructor(
uint64[2] memory _termParams,
address[3] memory _governors,
IERC20 _feeToken,
uint256[3] memory _fees,
uint64[5] memory _roundStateDurations,
uint16[2] memory _pcts,
uint64[4] memory _roundParams,
uint256[2] memory _appealCollateralParams,
uint256 _minActiveBalance
)
public
CourtClock(_termParams)
CourtConfig(_feeToken, _fees, _roundStateDurations, _pcts, _roundParams, _appealCollateralParams, _minActiveBalance)
{
_setFundsGovernor(_governors[0]);
_setConfigGovernor(_governors[1]);
_setModulesGovernor(_governors[2]);
}
/**
* @dev Fallback function allows to forward calls to a specific address in case it was previously registered
* Note the sender will be always the controller in case it is forwarded
*/
function () external payable {
address target = customFunctions[msg.sig];
require(target != address(0), ERROR_CUSTOM_FUNCTION_NOT_SET);
// solium-disable-next-line security/no-call-value
(bool success,) = address(target).call.value(msg.value)(msg.data);
assembly {
let size := returndatasize
let ptr := mload(0x40)
returndatacopy(ptr, 0, size)
let result := success
switch result case 0 { revert(ptr, size) }
default { return(ptr, size) }
}
}
/**
* @notice Change Court configuration params
* @param _fromTermId Identification number of the term in which the config will be effective at
* @param _feeToken Address of the token contract that is used to pay for fees
* @param _fees Array containing:
* 0. guardianFee Amount of fee tokens that is paid per guardian per dispute
* 1. draftFee Amount of fee tokens per guardian to cover the drafting cost
* 2. settleFee Amount of fee tokens per guardian to cover round settlement cost
* @param _roundStateDurations Array containing the durations in terms of the different phases of a dispute:
* 0. evidenceTerms Max submitting evidence period duration in terms
* 1. commitTerms Commit period duration in terms
* 2. revealTerms Reveal period duration in terms
* 3. appealTerms Appeal period duration in terms
* 4. appealConfirmationTerms Appeal confirmation period duration in terms
* @param _pcts Array containing:
* 0. penaltyPct Permyriad of min active tokens balance to be locked to each drafted guardians (‱ - 1/10,000)
* 1. finalRoundReduction Permyriad of fee reduction for the last appeal round (‱ - 1/10,000)
* @param _roundParams Array containing params for rounds:
* 0. firstRoundGuardiansNumber Number of guardians to be drafted for the first round of disputes
* 1. appealStepFactor Increasing factor for the number of guardians of each round of a dispute
* 2. maxRegularAppealRounds Number of regular appeal rounds before the final round is triggered
* 3. finalRoundLockTerms Number of terms that a coherent guardian in a final round is disallowed to withdraw (to prevent 51% attacks)
* @param _appealCollateralParams Array containing params for appeal collateral:
* 1. appealCollateralFactor Permyriad multiple of dispute fees required to appeal a preliminary ruling
* 2. appealConfirmCollateralFactor Permyriad multiple of dispute fees required to confirm appeal
* @param _minActiveBalance Minimum amount of guardian tokens that can be activated
*/
function setConfig(
uint64 _fromTermId,
IERC20 _feeToken,
uint256[3] calldata _fees,
uint64[5] calldata _roundStateDurations,
uint16[2] calldata _pcts,
uint64[4] calldata _roundParams,
uint256[2] calldata _appealCollateralParams,
uint256 _minActiveBalance
)
external
onlyConfigGovernor
{
uint64 currentTermId = _ensureCurrentTerm();
_setConfig(
currentTermId,
_fromTermId,
_feeToken,
_fees,
_roundStateDurations,
_pcts,
_roundParams,
_appealCollateralParams,
_minActiveBalance
);
}
/**
* @notice Delay the Court start time to `_newFirstTermStartTime`
* @param _newFirstTermStartTime New timestamp in seconds when the court will open
*/
function delayStartTime(uint64 _newFirstTermStartTime) external onlyConfigGovernor {
_delayStartTime(_newFirstTermStartTime);
}
/**
* @notice Change funds governor address to `_newFundsGovernor`
* @param _newFundsGovernor Address of the new funds governor to be set
*/
function changeFundsGovernor(address _newFundsGovernor) external onlyFundsGovernor {
require(_newFundsGovernor != ZERO_ADDRESS, ERROR_INVALID_GOVERNOR_ADDRESS);
_setFundsGovernor(_newFundsGovernor);
}
/**
* @notice Change config governor address to `_newConfigGovernor`
* @param _newConfigGovernor Address of the new config governor to be set
*/
function changeConfigGovernor(address _newConfigGovernor) external onlyConfigGovernor {
require(_newConfigGovernor != ZERO_ADDRESS, ERROR_INVALID_GOVERNOR_ADDRESS);
_setConfigGovernor(_newConfigGovernor);
}
/**
* @notice Change modules governor address to `_newModulesGovernor`
* @param _newModulesGovernor Address of the new governor to be set
*/
function changeModulesGovernor(address _newModulesGovernor) external onlyModulesGovernor {
require(_newModulesGovernor != ZERO_ADDRESS, ERROR_INVALID_GOVERNOR_ADDRESS);
_setModulesGovernor(_newModulesGovernor);
}
/**
* @notice Remove the funds governor. Set the funds governor to the zero address.
* @dev This action cannot be rolled back, once the funds governor has been unset, funds cannot be recovered from recoverable modules anymore
*/
function ejectFundsGovernor() external onlyFundsGovernor {
_setFundsGovernor(ZERO_ADDRESS);
}
/**
* @notice Remove the modules governor. Set the modules governor to the zero address.
* @dev This action cannot be rolled back, once the modules governor has been unset, system modules cannot be changed anymore
*/
function ejectModulesGovernor() external onlyModulesGovernor {
_setModulesGovernor(ZERO_ADDRESS);
}
/**
* @notice Grant `_id` role to `_who`
* @param _id ID of the role to be granted
* @param _who Address to grant the role to
*/
function grant(bytes32 _id, address _who) external onlyConfigGovernor {
_grant(_id, _who);
}
/**
* @notice Revoke `_id` role from `_who`
* @param _id ID of the role to be revoked
* @param _who Address to revoke the role from
*/
function revoke(bytes32 _id, address _who) external onlyConfigGovernor {
_revoke(_id, _who);
}
/**
* @notice Freeze `_id` role
* @param _id ID of the role to be frozen
*/
function freeze(bytes32 _id) external onlyConfigGovernor {
_freeze(_id);
}
/**
* @notice Enact a bulk list of ACL operations
*/
function bulk(BulkOp[] calldata _op, bytes32[] calldata _id, address[] calldata _who) external onlyConfigGovernor {
_bulk(_op, _id, _who);
}
/**
* @notice Set module `_id` to `_addr`
* @param _id ID of the module to be set
* @param _addr Address of the module to be set
*/
function setModule(bytes32 _id, address _addr) external onlyModulesGovernor {
_setModule(_id, _addr);
}
/**
* @notice Set and link many modules at once
* @param _newModuleIds List of IDs of the new modules to be set
* @param _newModuleAddresses List of addresses of the new modules to be set
* @param _newModuleLinks List of IDs of the modules that will be linked in the new modules being set
* @param _currentModulesToBeSynced List of addresses of current modules to be re-linked to the new modules being set
*/
function setModules(
bytes32[] calldata _newModuleIds,
address[] calldata _newModuleAddresses,
bytes32[] calldata _newModuleLinks,
address[] calldata _currentModulesToBeSynced
)
external
onlyModulesGovernor
{
// We only care about the modules being set, links are optional
require(_newModuleIds.length == _newModuleAddresses.length, ERROR_INVALID_IMPLS_INPUT_LENGTH);
// First set the addresses of the new modules or the modules to be updated
for (uint256 i = 0; i < _newModuleIds.length; i++) {
_setModule(_newModuleIds[i], _newModuleAddresses[i]);
}
// Then sync the links of the new modules based on the list of IDs specified (ideally the IDs of their dependencies)
_syncModuleLinks(_newModuleAddresses, _newModuleLinks);
// Finally sync the links of the existing modules to be synced to the new modules being set
_syncModuleLinks(_currentModulesToBeSynced, _newModuleIds);
}
/**
* @notice Sync modules for a list of modules IDs based on their current implementation address
* @param _modulesToBeSynced List of addresses of connected modules to be synced
* @param _idsToBeSet List of IDs of the modules included in the sync
*/
function syncModuleLinks(address[] calldata _modulesToBeSynced, bytes32[] calldata _idsToBeSet)
external
onlyModulesGovernor
{
require(_idsToBeSet.length > 0 && _modulesToBeSynced.length > 0, ERROR_INVALID_IMPLS_INPUT_LENGTH);
_syncModuleLinks(_modulesToBeSynced, _idsToBeSet);
}
/**
* @notice Disable module `_addr`
* @dev Current modules can be disabled to allow pausing the court. However, these can be enabled back again, see `enableModule`
* @param _addr Address of the module to be disabled
*/
function disableModule(address _addr) external onlyModulesGovernor {
Module storage module = allModules[_addr];
_ensureModuleExists(module);
require(!module.disabled, ERROR_MODULE_ALREADY_DISABLED);
module.disabled = true;
emit ModuleDisabled(module.id, _addr);
}
/**
* @notice Enable module `_addr`
* @param _addr Address of the module to be enabled
*/
function enableModule(address _addr) external onlyModulesGovernor {
Module storage module = allModules[_addr];
_ensureModuleExists(module);
require(module.disabled, ERROR_MODULE_ALREADY_ENABLED);
module.disabled = false;
emit ModuleEnabled(module.id, _addr);
}
/**
* @notice Set custom function `_sig` for `_target`
* @param _sig Signature of the function to be set
* @param _target Address of the target implementation to be registered for the given signature
*/
function setCustomFunction(bytes4 _sig, address _target) external onlyModulesGovernor {
customFunctions[_sig] = _target;
emit CustomFunctionSet(_sig, _target);
}
/**
* @dev Tell the full Court configuration parameters at a certain term
* @param _termId Identification number of the term querying the Court config of
* @return token Address of the token used to pay for fees
* @return fees Array containing:
* 0. guardianFee Amount of fee tokens that is paid per guardian per dispute
* 1. draftFee Amount of fee tokens per guardian to cover the drafting cost
* 2. settleFee Amount of fee tokens per guardian to cover round settlement cost
* @return roundStateDurations Array containing the durations in terms of the different phases of a dispute:
* 0. evidenceTerms Max submitting evidence period duration in terms
* 1. commitTerms Commit period duration in terms
* 2. revealTerms Reveal period duration in terms
* 3. appealTerms Appeal period duration in terms
* 4. appealConfirmationTerms Appeal confirmation period duration in terms
* @return pcts Array containing:
* 0. penaltyPct Permyriad of min active tokens balance to be locked for each drafted guardian (‱ - 1/10,000)
* 1. finalRoundReduction Permyriad of fee reduction for the last appeal round (‱ - 1/10,000)
* @return roundParams Array containing params for rounds:
* 0. firstRoundGuardiansNumber Number of guardians to be drafted for the first round of disputes
* 1. appealStepFactor Increasing factor for the number of guardians of each round of a dispute
* 2. maxRegularAppealRounds Number of regular appeal rounds before the final round is triggered
* 3. finalRoundLockTerms Number of terms that a coherent guardian in a final round is disallowed to withdraw (to prevent 51% attacks)
* @return appealCollateralParams Array containing params for appeal collateral:
* 0. appealCollateralFactor Multiple of dispute fees required to appeal a preliminary ruling
* 1. appealConfirmCollateralFactor Multiple of dispute fees required to confirm appeal
*/
function getConfig(uint64 _termId) external view
returns (
IERC20 feeToken,
uint256[3] memory fees,
uint64[5] memory roundStateDurations,
uint16[2] memory pcts,
uint64[4] memory roundParams,
uint256[2] memory appealCollateralParams,
uint256 minActiveBalance
)
{
uint64 lastEnsuredTermId = _lastEnsuredTermId();
return _getConfigAt(_termId, lastEnsuredTermId);
}
/**
* @dev Tell the draft config at a certain term
* @param _termId Identification number of the term querying the draft config of
* @return feeToken Address of the token used to pay for fees
* @return draftFee Amount of fee tokens per guardian to cover the drafting cost
* @return penaltyPct Permyriad of min active tokens balance to be locked for each drafted guardian (‱ - 1/10,000)
*/
function getDraftConfig(uint64 _termId) external view returns (IERC20 feeToken, uint256 draftFee, uint16 penaltyPct) {
uint64 lastEnsuredTermId = _lastEnsuredTermId();
return _getDraftConfig(_termId, lastEnsuredTermId);
}
/**
* @dev Tell the min active balance config at a certain term
* @param _termId Identification number of the term querying the min active balance config of
* @return Minimum amount of tokens guardians have to activate to participate in the Court
*/
function getMinActiveBalance(uint64 _termId) external view returns (uint256) {
uint64 lastEnsuredTermId = _lastEnsuredTermId();
return _getMinActiveBalance(_termId, lastEnsuredTermId);
}
/**
* @dev Tell the address of the funds governor
* @return Address of the funds governor
*/
function getFundsGovernor() external view returns (address) {
return governor.funds;
}
/**
* @dev Tell the address of the config governor
* @return Address of the config governor
*/
function getConfigGovernor() external view returns (address) {
return governor.config;
}
/**
* @dev Tell the address of the modules governor
* @return Address of the modules governor
*/
function getModulesGovernor() external view returns (address) {
return governor.modules;
}
/**
* @dev Tell if a given module is active
* @param _id ID of the module to be checked
* @param _addr Address of the module to be checked
* @return True if the given module address has the requested ID and is enabled
*/
function isActive(bytes32 _id, address _addr) external view returns (bool) {
Module storage module = allModules[_addr];
return module.id == _id && !module.disabled;
}
/**
* @dev Tell the current ID and disable status of a module based on a given address
* @param _addr Address of the requested module
* @return id ID of the module being queried
* @return disabled Whether the module has been disabled
*/
function getModuleByAddress(address _addr) external view returns (bytes32 id, bool disabled) {
Module storage module = allModules[_addr];
id = module.id;
disabled = module.disabled;
}
/**
* @dev Tell the current address and disable status of a module based on a given ID
* @param _id ID of the module being queried
* @return addr Current address of the requested module
* @return disabled Whether the module has been disabled
*/
function getModule(bytes32 _id) external view returns (address addr, bool disabled) {
return _getModule(_id);
}
/**
* @dev Tell the information for the current DisputeManager module
* @return addr Current address of the DisputeManager module
* @return disabled Whether the module has been disabled
*/
function getDisputeManager() external view returns (address addr, bool disabled) {
return _getModule(MODULE_ID_DISPUTE_MANAGER);
}
/**
* @dev Tell the information for the current GuardiansRegistry module
* @return addr Current address of the GuardiansRegistry module
* @return disabled Whether the module has been disabled
*/
function getGuardiansRegistry() external view returns (address addr, bool disabled) {
return _getModule(MODULE_ID_GUARDIANS_REGISTRY);
}
/**
* @dev Tell the information for the current Voting module
* @return addr Current address of the Voting module
* @return disabled Whether the module has been disabled
*/
function getVoting() external view returns (address addr, bool disabled) {
return _getModule(MODULE_ID_VOTING);
}
/**
* @dev Tell the information for the current PaymentsBook module
* @return addr Current address of the PaymentsBook module
* @return disabled Whether the module has been disabled
*/
function getPaymentsBook() external view returns (address addr, bool disabled) {
return _getModule(MODULE_ID_PAYMENTS_BOOK);
}
/**
* @dev Tell the information for the current Treasury module
* @return addr Current address of the Treasury module
* @return disabled Whether the module has been disabled
*/
function getTreasury() external view returns (address addr, bool disabled) {
return _getModule(MODULE_ID_TREASURY);
}
/**
* @dev Tell the target registered for a custom function
* @param _sig Signature of the function being queried
* @return Address of the target where the function call will be forwarded
*/
function getCustomFunction(bytes4 _sig) external view returns (address) {
return customFunctions[_sig];
}
/**
* @dev Internal function to set the address of the funds governor
* @param _newFundsGovernor Address of the new config governor to be set
*/
function _setFundsGovernor(address _newFundsGovernor) internal {
emit FundsGovernorChanged(governor.funds, _newFundsGovernor);
governor.funds = _newFundsGovernor;
}
/**
* @dev Internal function to set the address of the config governor
* @param _newConfigGovernor Address of the new config governor to be set
*/
function _setConfigGovernor(address _newConfigGovernor) internal {
emit ConfigGovernorChanged(governor.config, _newConfigGovernor);
governor.config = _newConfigGovernor;
}
/**
* @dev Internal function to set the address of the modules governor
* @param _newModulesGovernor Address of the new modules governor to be set
*/
function _setModulesGovernor(address _newModulesGovernor) internal {
emit ModulesGovernorChanged(governor.modules, _newModulesGovernor);
governor.modules = _newModulesGovernor;
}
/**
* @dev Internal function to set an address as the current implementation for a module
* Note that the disabled condition is not affected, if the module was not set before it will be enabled by default
* @param _id Id of the module to be set
* @param _addr Address of the module to be set
*/
function _setModule(bytes32 _id, address _addr) internal {
require(isContract(_addr), ERROR_IMPLEMENTATION_NOT_CONTRACT);
currentModules[_id] = _addr;
allModules[_addr].id = _id;
emit ModuleSet(_id, _addr);
}
/**
* @dev Internal function to sync the modules for a list of modules IDs based on their current implementation address
* @param _modulesToBeSynced List of addresses of connected modules to be synced
* @param _idsToBeSet List of IDs of the modules to be linked
*/
function _syncModuleLinks(address[] memory _modulesToBeSynced, bytes32[] memory _idsToBeSet) internal {
address[] memory addressesToBeSet = new address[](_idsToBeSet.length);
// Load the addresses associated with the requested module ids
for (uint256 i = 0; i < _idsToBeSet.length; i++) {
address moduleAddress = _getModuleAddress(_idsToBeSet[i]);
Module storage module = allModules[moduleAddress];
_ensureModuleExists(module);
addressesToBeSet[i] = moduleAddress;
}
// Update the links of all the requested modules
for (uint256 j = 0; j < _modulesToBeSynced.length; j++) {
IModulesLinker(_modulesToBeSynced[j]).linkModules(_idsToBeSet, addressesToBeSet);
}
}
/**
* @dev Internal function to notify when a term has been transitioned
* @param _termId Identification number of the new current term that has been transitioned
*/
function _onTermTransitioned(uint64 _termId) internal {
_ensureTermConfig(_termId);
}
/**
* @dev Internal function to check if a module was set
* @param _module Module to be checked
*/
function _ensureModuleExists(Module storage _module) internal view {
require(_module.id != bytes32(0), ERROR_MODULE_NOT_SET);
}
/**
* @dev Internal function to tell the information for a module based on a given ID
* @param _id ID of the module being queried
* @return addr Current address of the requested module
* @return disabled Whether the module has been disabled
*/
function _getModule(bytes32 _id) internal view returns (address addr, bool disabled) {
addr = _getModuleAddress(_id);
disabled = _isModuleDisabled(addr);
}
/**
* @dev Tell the current address for a module by ID
* @param _id ID of the module being queried
* @return Current address of the requested module
*/
function _getModuleAddress(bytes32 _id) internal view returns (address) {
return currentModules[_id];
}
/**
* @dev Tell whether a module is disabled
* @param _addr Address of the module being queried
* @return True if the module is disabled, false otherwise
*/
function _isModuleDisabled(address _addr) internal view returns (bool) {
return allModules[_addr].disabled;
}
}
contract ConfigConsumer is CourtConfigData {
/**
* @dev Internal function to fetch the address of the Config module from the controller
* @return Address of the Config module
*/
function _courtConfig() internal view returns (IConfig);
/**
* @dev Internal function to get the Court config for a certain term
* @param _termId Identification number of the term querying the Court config of
* @return Court config for the given term
*/
function _getConfigAt(uint64 _termId) internal view returns (Config memory) {
(IERC20 _feeToken,
uint256[3] memory _fees,
uint64[5] memory _roundStateDurations,
uint16[2] memory _pcts,
uint64[4] memory _roundParams,
uint256[2] memory _appealCollateralParams,
uint256 _minActiveBalance) = _courtConfig().getConfig(_termId);
Config memory config;
config.fees = FeesConfig({
token: _feeToken,
guardianFee: _fees[0],
draftFee: _fees[1],
settleFee: _fees[2],
finalRoundReduction: _pcts[1]
});
config.disputes = DisputesConfig({
evidenceTerms: _roundStateDurations[0],
commitTerms: _roundStateDurations[1],
revealTerms: _roundStateDurations[2],
appealTerms: _roundStateDurations[3],
appealConfirmTerms: _roundStateDurations[4],
penaltyPct: _pcts[0],
firstRoundGuardiansNumber: _roundParams[0],
appealStepFactor: _roundParams[1],
maxRegularAppealRounds: _roundParams[2],
finalRoundLockTerms: _roundParams[3],
appealCollateralFactor: _appealCollateralParams[0],
appealConfirmCollateralFactor: _appealCollateralParams[1]
});
config.minActiveBalance = _minActiveBalance;
return config;
}
/**
* @dev Internal function to get the draft config for a given term
* @param _termId Identification number of the term querying the draft config of
* @return Draft config for the given term
*/
function _getDraftConfig(uint64 _termId) internal view returns (DraftConfig memory) {
(IERC20 feeToken, uint256 draftFee, uint16 penaltyPct) = _courtConfig().getDraftConfig(_termId);
return DraftConfig({ feeToken: feeToken, draftFee: draftFee, penaltyPct: penaltyPct });
}
/**
* @dev Internal function to get the min active balance config for a given term
* @param _termId Identification number of the term querying the min active balance config of
* @return Minimum amount of guardian tokens that can be activated
*/
function _getMinActiveBalance(uint64 _termId) internal view returns (uint256) {
return _courtConfig().getMinActiveBalance(_termId);
}
}
/*
* SPDX-License-Identifier: MIT
*/
interface ITreasury {
/**
* @dev Assign a certain amount of tokens to an account
* @param _token ERC20 token to be assigned
* @param _to Address of the recipient that will be assigned the tokens to
* @param _amount Amount of tokens to be assigned to the recipient
*/
function assign(IERC20 _token, address _to, uint256 _amount) external;
/**
* @dev Withdraw a certain amount of tokens
* @param _token ERC20 token to be withdrawn
* @param _from Address withdrawing the tokens from
* @param _to Address of the recipient that will receive the tokens
* @param _amount Amount of tokens to be withdrawn from the sender
*/
function withdraw(IERC20 _token, address _from, address _to, uint256 _amount) external;
}
/*
* SPDX-License-Identifier: MIT
*/
interface IGuardiansRegistry {
/**
* @dev Assign a requested amount of guardian tokens to a guardian
* @param _guardian Guardian to add an amount of tokens to
* @param _amount Amount of tokens to be added to the available balance of a guardian
*/
function assignTokens(address _guardian, uint256 _amount) external;
/**
* @dev Burn a requested amount of guardian tokens
* @param _amount Amount of tokens to be burned
*/
function burnTokens(uint256 _amount) external;
/**
* @dev Draft a set of guardians based on given requirements for a term id
* @param _params Array containing draft requirements:
* 0. bytes32 Term randomness
* 1. uint256 Dispute id
* 2. uint64 Current term id
* 3. uint256 Number of seats already filled
* 4. uint256 Number of seats left to be filled
* 5. uint64 Number of guardians required for the draft
* 6. uint16 Permyriad of the minimum active balance to be locked for the draft
*
* @return guardians List of guardians selected for the draft
* @return length Size of the list of the draft result
*/
function draft(uint256[7] calldata _params) external returns (address[] memory guardians, uint256 length);
/**
* @dev Slash a set of guardians based on their votes compared to the winning ruling
* @param _termId Current term id
* @param _guardians List of guardian addresses to be slashed
* @param _lockedAmounts List of amounts locked for each corresponding guardian that will be either slashed or returned
* @param _rewardedGuardians List of booleans to tell whether a guardian's active balance has to be slashed or not
* @return Total amount of slashed tokens
*/
function slashOrUnlock(uint64 _termId, address[] calldata _guardians, uint256[] calldata _lockedAmounts, bool[] calldata _rewardedGuardians)
external
returns (uint256 collectedTokens);
/**
* @dev Try to collect a certain amount of tokens from a guardian for the next term
* @param _guardian Guardian to collect the tokens from
* @param _amount Amount of tokens to be collected from the given guardian and for the requested term id
* @param _termId Current term id
* @return True if the guardian has enough unlocked tokens to be collected for the requested term, false otherwise
*/
function collectTokens(address _guardian, uint256 _amount, uint64 _termId) external returns (bool);
/**
* @dev Lock a guardian's withdrawals until a certain term ID
* @param _guardian Address of the guardian to be locked
* @param _termId Term ID until which the guardian's withdrawals will be locked
*/
function lockWithdrawals(address _guardian, uint64 _termId) external;
/**
* @dev Tell the active balance of a guardian for a given term id
* @param _guardian Address of the guardian querying the active balance of
* @param _termId Term ID querying the active balance for
* @return Amount of active tokens for guardian in the requested past term id
*/
function activeBalanceOfAt(address _guardian, uint64 _termId) external view returns (uint256);
/**
* @dev Tell the total amount of active guardian tokens at the given term id
* @param _termId Term ID querying the total active balance for
* @return Total amount of active guardian tokens at the given term id
*/
function totalActiveBalanceAt(uint64 _termId) external view returns (uint256);
}
/*
* SPDX-License-Identifier: MIT
*/
interface IPaymentsBook {
/**
* @dev Pay an amount of tokens
* @param _token Address of the token being paid
* @param _amount Amount of tokens being paid
* @param _payer Address paying on behalf of
* @param _data Optional data
*/
function pay(address _token, uint256 _amount, address _payer, bytes calldata _data) external payable;
}
contract Controlled is IModulesLinker, IsContract, ModuleIds, ConfigConsumer {
string private constant ERROR_MODULE_NOT_SET = "CTD_MODULE_NOT_SET";
string private constant ERROR_INVALID_MODULES_LINK_INPUT = "CTD_INVALID_MODULES_LINK_INPUT";
string private constant ERROR_CONTROLLER_NOT_CONTRACT = "CTD_CONTROLLER_NOT_CONTRACT";
string private constant ERROR_SENDER_NOT_ALLOWED = "CTD_SENDER_NOT_ALLOWED";
string private constant ERROR_SENDER_NOT_CONTROLLER = "CTD_SENDER_NOT_CONTROLLER";
string private constant ERROR_SENDER_NOT_CONFIG_GOVERNOR = "CTD_SENDER_NOT_CONFIG_GOVERNOR";
string private constant ERROR_SENDER_NOT_ACTIVE_VOTING = "CTD_SENDER_NOT_ACTIVE_VOTING";
string private constant ERROR_SENDER_NOT_ACTIVE_DISPUTE_MANAGER = "CTD_SEND_NOT_ACTIVE_DISPUTE_MGR";
string private constant ERROR_SENDER_NOT_CURRENT_DISPUTE_MANAGER = "CTD_SEND_NOT_CURRENT_DISPUTE_MGR";
// Address of the controller
Controller public controller;
// List of modules linked indexed by ID
mapping (bytes32 => address) public linkedModules;
event ModuleLinked(bytes32 id, address addr);
/**
* @dev Ensure the msg.sender is the controller's config governor
*/
modifier onlyConfigGovernor {
require(msg.sender == _configGovernor(), ERROR_SENDER_NOT_CONFIG_GOVERNOR);
_;
}
/**
* @dev Ensure the msg.sender is the controller
*/
modifier onlyController() {
require(msg.sender == address(controller), ERROR_SENDER_NOT_CONTROLLER);
_;
}
/**
* @dev Ensure the msg.sender is an active DisputeManager module
*/
modifier onlyActiveDisputeManager() {
require(controller.isActive(MODULE_ID_DISPUTE_MANAGER, msg.sender), ERROR_SENDER_NOT_ACTIVE_DISPUTE_MANAGER);
_;
}
/**
* @dev Ensure the msg.sender is the current DisputeManager module
*/
modifier onlyCurrentDisputeManager() {
(address addr, bool disabled) = controller.getDisputeManager();
require(msg.sender == addr, ERROR_SENDER_NOT_CURRENT_DISPUTE_MANAGER);
require(!disabled, ERROR_SENDER_NOT_ACTIVE_DISPUTE_MANAGER);
_;
}
/**
* @dev Ensure the msg.sender is an active Voting module
*/
modifier onlyActiveVoting() {
require(controller.isActive(MODULE_ID_VOTING, msg.sender), ERROR_SENDER_NOT_ACTIVE_VOTING);
_;
}
/**
* @dev This modifier will check that the sender is the user to act on behalf of or someone with the required permission
* @param _user Address of the user to act on behalf of
*/
modifier authenticateSender(address _user) {
_authenticateSender(_user);
_;
}
/**
* @dev Constructor function
* @param _controller Address of the controller
*/
constructor(Controller _controller) public {
require(isContract(address(_controller)), ERROR_CONTROLLER_NOT_CONTRACT);
controller = _controller;
}
/**
* @notice Update the implementation links of a list of modules
* @dev The controller is expected to ensure the given addresses are correct modules
* @param _ids List of IDs of the modules to be updated
* @param _addresses List of module addresses to be updated
*/
function linkModules(bytes32[] calldata _ids, address[] calldata _addresses) external onlyController {
require(_ids.length == _addresses.length, ERROR_INVALID_MODULES_LINK_INPUT);
for (uint256 i = 0; i < _ids.length; i++) {
linkedModules[_ids[i]] = _addresses[i];
emit ModuleLinked(_ids[i], _addresses[i]);
}
}
/**
* @dev Internal function to ensure the Court term is up-to-date, it will try to update it if not
* @return Identification number of the current Court term
*/
function _ensureCurrentTerm() internal returns (uint64) {
return _clock().ensureCurrentTerm();
}
/**
* @dev Internal function to fetch the last ensured term ID of the Court
* @return Identification number of the last ensured term
*/
function _getLastEnsuredTermId() internal view returns (uint64) {
return _clock().getLastEnsuredTermId();
}
/**
* @dev Internal function to tell the current term identification number
* @return Identification number of the current term
*/
function _getCurrentTermId() internal view returns (uint64) {
return _clock().getCurrentTermId();
}
/**
* @dev Internal function to fetch the controller's config governor
* @return Address of the controller's config governor
*/
function _configGovernor() internal view returns (address) {
return controller.getConfigGovernor();
}
/**
* @dev Internal function to fetch the address of the DisputeManager module
* @return Address of the DisputeManager module
*/
function _disputeManager() internal view returns (IDisputeManager) {
return IDisputeManager(_getLinkedModule(MODULE_ID_DISPUTE_MANAGER));
}
/**
* @dev Internal function to fetch the address of the GuardianRegistry module implementation
* @return Address of the GuardianRegistry module implementation
*/
function _guardiansRegistry() internal view returns (IGuardiansRegistry) {
return IGuardiansRegistry(_getLinkedModule(MODULE_ID_GUARDIANS_REGISTRY));
}
/**
* @dev Internal function to fetch the address of the Voting module implementation
* @return Address of the Voting module implementation
*/
function _voting() internal view returns (ICRVoting) {
return ICRVoting(_getLinkedModule(MODULE_ID_VOTING));
}
/**
* @dev Internal function to fetch the address of the PaymentsBook module implementation
* @return Address of the PaymentsBook module implementation
*/
function _paymentsBook() internal view returns (IPaymentsBook) {
return IPaymentsBook(_getLinkedModule(MODULE_ID_PAYMENTS_BOOK));
}
/**
* @dev Internal function to fetch the address of the Treasury module implementation
* @return Address of the Treasury module implementation
*/
function _treasury() internal view returns (ITreasury) {
return ITreasury(_getLinkedModule(MODULE_ID_TREASURY));
}
/**
* @dev Internal function to tell the address linked for a module based on a given ID
* @param _id ID of the module being queried
* @return Linked address of the requested module
*/
function _getLinkedModule(bytes32 _id) internal view returns (address) {
address module = linkedModules[_id];
require(module != address(0), ERROR_MODULE_NOT_SET);
return module;
}
/**
* @dev Internal function to fetch the address of the Clock module from the controller
* @return Address of the Clock module
*/
function _clock() internal view returns (IClock) {
return IClock(controller);
}
/**
* @dev Internal function to fetch the address of the Config module from the controller
* @return Address of the Config module
*/
function _courtConfig() internal view returns (IConfig) {
return IConfig(controller);
}
/**
* @dev Ensure that the sender is the user to act on behalf of or someone with the required permission
* @param _user Address of the user to act on behalf of
*/
function _authenticateSender(address _user) internal view {
require(_isSenderAllowed(_user), ERROR_SENDER_NOT_ALLOWED);
}
/**
* @dev Tell whether the sender is the user to act on behalf of or someone with the required permission
* @param _user Address of the user to act on behalf of
* @return True if the sender is the user to act on behalf of or someone with the required permission, false otherwise
*/
function _isSenderAllowed(address _user) internal view returns (bool) {
return msg.sender == _user || _hasRole(msg.sender);
}
/**
* @dev Tell whether an address holds the required permission to access the requested functionality
* @param _addr Address being checked
* @return True if the given address has the required permission to access the requested functionality, false otherwise
*/
function _hasRole(address _addr) internal view returns (bool) {
bytes32 roleId = keccak256(abi.encodePacked(address(this), msg.sig));
return controller.hasRole(_addr, roleId);
}
}
contract CRVoting is ICRVoting, Controlled {
using SafeMath for uint256;
string private constant ERROR_VOTE_ALREADY_EXISTS = "CRV_VOTE_ALREADY_EXISTS";
string private constant ERROR_VOTE_DOES_NOT_EXIST = "CRV_VOTE_DOES_NOT_EXIST";
string private constant ERROR_VOTE_ALREADY_COMMITTED = "CRV_VOTE_ALREADY_COMMITTED";
string private constant ERROR_VOTE_ALREADY_REVEALED = "CRV_VOTE_ALREADY_REVEALED";
string private constant ERROR_SENDER_NOT_DELEGATE = "CRV_SENDER_NOT_DELEGATE";
string private constant ERROR_INVALID_OUTCOME = "CRV_INVALID_OUTCOME";
string private constant ERROR_INVALID_OUTCOMES_AMOUNT = "CRV_INVALID_OUTCOMES_AMOUNT";
string private constant ERROR_INVALID_COMMITMENT_SALT = "CRV_INVALID_COMMITMENT_SALT";
// Outcome nr. 0 is used to denote a missing vote (default)
uint8 internal constant OUTCOME_MISSING = uint8(0);
// Outcome nr. 1 is used to denote a leaked vote
uint8 internal constant OUTCOME_LEAKED = uint8(1);
// Outcome nr. 2 is used to denote a refused vote
uint8 internal constant OUTCOME_REFUSED = uint8(2);
// Besides the options listed above, every vote instance must provide at least 2 outcomes
uint8 internal constant MIN_POSSIBLE_OUTCOMES = uint8(2);
// Max number of outcomes excluding the default ones
uint8 internal constant MAX_POSSIBLE_OUTCOMES = uint8(-1) - 3;
struct CastVote {
bytes32 commitment; // Hash of the outcome casted by the voter
uint8 outcome; // Outcome submitted by the voter
}
struct Vote {
uint8 winningOutcome; // Outcome winner of a vote instance
uint8 maxAllowedOutcome; // Highest outcome allowed for the vote instance
mapping (address => CastVote) votes; // Mapping of voters addresses to their casted votes
mapping (uint8 => uint256) outcomesTally; // Tally for each of the possible outcomes
}
// Vote records indexed by their ID
mapping (uint256 => Vote) internal voteRecords;
// Delegates indexed by principals
mapping (address => address) internal delegates;
event VotingCreated(uint256 indexed voteId, uint8 possibleOutcomes);
event VoteCommitted(uint256 indexed voteId, address indexed voter, bytes32 commitment);
event VoteRevealed(uint256 indexed voteId, address indexed voter, uint8 outcome);
event VoteLeaked(uint256 indexed voteId, address indexed voter, uint8 outcome);
event DelegateSet(address indexed voter, address delegate);
/**
* @dev Ensure a certain vote exists
* @param _voteId ID of the vote instance to be checked
*/
modifier voteExists(uint256 _voteId) {
require(_existsVote(_voteId), ERROR_VOTE_DOES_NOT_EXIST);
_;
}
/**
* @dev Constructor function
* @param _controller Address of the controller
*/
constructor(Controller _controller) Controlled(_controller) public {
// solium-disable-previous-line no-empty-blocks
}
/**
* @notice Set `_delegate` as the delegate for `_voter`
* @param _voter Address of the voter updating the delegate for
* @param _delegate Address of the delegate to be set
*/
function delegate(address _voter, address _delegate) external authenticateSender(_voter) {
delegates[_voter] = _delegate;
emit DelegateSet(_voter, _delegate);
}
/**
* @notice Create a new vote instance with ID #`_voteId` and `_possibleOutcomes` possible outcomes
* @dev This function can only be called by the CRVoting owner
* @param _voteId ID of the new vote instance to be created
* @param _possibleOutcomes Number of possible outcomes for the new vote instance to be created
*/
function createVote(uint256 _voteId, uint8 _possibleOutcomes) external onlyCurrentDisputeManager {
require(_possibleOutcomes >= MIN_POSSIBLE_OUTCOMES && _possibleOutcomes <= MAX_POSSIBLE_OUTCOMES, ERROR_INVALID_OUTCOMES_AMOUNT);
require(!_existsVote(_voteId), ERROR_VOTE_ALREADY_EXISTS);
// No need for SafeMath: we already checked the number of outcomes above
Vote storage vote = voteRecords[_voteId];
vote.maxAllowedOutcome = OUTCOME_REFUSED + _possibleOutcomes;
emit VotingCreated(_voteId, _possibleOutcomes);
}
/**
* @notice Commit a vote for `_voter` on vote #`_voteId`
* @param _voteId ID of the vote instance to commit a vote to
* @param _voter Address of the voter to commit a vote for
* @param _commitment Hashed outcome to be stored for future reveal
*/
function commit(uint256 _voteId, address _voter, bytes32 _commitment) external voteExists(_voteId) {
bool isSenderAllowed = _isDelegateOf(_voter, msg.sender) || _isSenderAllowed(_voter);
require(isSenderAllowed, ERROR_SENDER_NOT_DELEGATE);
CastVote storage castVote = voteRecords[_voteId].votes[_voter];
require(castVote.commitment == bytes32(0), ERROR_VOTE_ALREADY_COMMITTED);
_ensureVoterCanCommit(_voteId, _voter);
castVote.commitment = _commitment;
emit VoteCommitted(_voteId, _voter, _commitment);
}
/**
* @notice Leak `_outcome` vote of `_voter` for vote #`_voteId`
* @param _voteId ID of the vote instance to leak a vote of
* @param _voter Address of the voter to leak a vote of
* @param _outcome Outcome leaked for the voter
* @param _salt Salt to decrypt and validate the committed vote of the voter
*/
function leak(uint256 _voteId, address _voter, uint8 _outcome, bytes32 _salt) external voteExists(_voteId) {
CastVote storage castVote = voteRecords[_voteId].votes[_voter];
_checkValidSalt(castVote, _outcome, _salt);
_ensureCanCommit(_voteId);
// There is no need to check if an outcome is valid if it was leaked.
// Additionally, leaked votes are not considered for the tally.
castVote.outcome = OUTCOME_LEAKED;
emit VoteLeaked(_voteId, _voter, _outcome);
}
/**
* @notice Reveal `_outcome` vote of `_voter` for vote #`_voteId`
* @param _voteId ID of the vote instance to reveal a vote of
* @param _voter Address of the voter to reveal a vote for
* @param _outcome Outcome revealed by the voter
* @param _salt Salt to decrypt and validate the committed vote of the voter
*/
function reveal(uint256 _voteId, address _voter, uint8 _outcome, bytes32 _salt) external voteExists(_voteId) {
Vote storage vote = voteRecords[_voteId];
CastVote storage castVote = vote.votes[_voter];
_checkValidSalt(castVote, _outcome, _salt);
require(_isValidOutcome(vote, _outcome), ERROR_INVALID_OUTCOME);
uint256 weight = _ensureVoterCanReveal(_voteId, _voter);
castVote.outcome = _outcome;
_updateTally(vote, _outcome, weight);
emit VoteRevealed(_voteId, _voter, _outcome);
}
/**
* @dev Tell if a delegate currently represents another voter
* @param _voter Address of the principal being queried
* @param _delegate Address of the delegate being queried
* @return True if the given delegate currently represents the voter
*/
function isDelegateOf(address _voter, address _delegate) external view returns (bool) {
return _isDelegateOf(_voter, _delegate);
}
/**
* @dev Get the maximum allowed outcome for a given vote instance
* @param _voteId ID of the vote instance querying the max allowed outcome of
* @return Max allowed outcome for the given vote instance
*/
function getMaxAllowedOutcome(uint256 _voteId) external view voteExists(_voteId) returns (uint8) {
Vote storage vote = voteRecords[_voteId];
return vote.maxAllowedOutcome;
}
/**
* @dev Get the winning outcome of a vote instance. If the winning outcome is missing, which means no one voted in
* the given vote instance, it will be considered refused.
* @param _voteId ID of the vote instance querying the winning outcome of
* @return Winning outcome of the given vote instance or refused in case it's missing
*/
function getWinningOutcome(uint256 _voteId) external view voteExists(_voteId) returns (uint8) {
Vote storage vote = voteRecords[_voteId];
uint8 winningOutcome = vote.winningOutcome;
return winningOutcome == OUTCOME_MISSING ? OUTCOME_REFUSED : winningOutcome;
}
/**
* @dev Get the tally of an outcome for a certain vote instance
* @param _voteId ID of the vote instance querying the tally of
* @param _outcome Outcome querying the tally of
* @return Tally of the outcome being queried for the given vote instance
*/
function getOutcomeTally(uint256 _voteId, uint8 _outcome) external view voteExists(_voteId) returns (uint256) {
Vote storage vote = voteRecords[_voteId];
return vote.outcomesTally[_outcome];
}
/**
* @dev Tell whether an outcome is valid for a given vote instance or not. Missing and leaked outcomes are not considered
* valid. The only valid outcomes are refused or any of the custom outcomes of the given vote instance.
* @param _voteId ID of the vote instance to check the outcome of
* @param _outcome Outcome to check if valid or not
* @return True if the given outcome is valid for the requested vote instance, false otherwise.
*/
function isValidOutcome(uint256 _voteId, uint8 _outcome) external view voteExists(_voteId) returns (bool) {
Vote storage vote = voteRecords[_voteId];
return _isValidOutcome(vote, _outcome);
}
/**
* @dev Get the outcome voted by a voter for a certain vote instance
* @param _voteId ID of the vote instance querying the outcome of
* @param _voter Address of the voter querying the outcome of
* @return Outcome of the voter for the given vote instance
*/
function getVoterOutcome(uint256 _voteId, address _voter) external view voteExists(_voteId) returns (uint8) {
Vote storage vote = voteRecords[_voteId];
return vote.votes[_voter].outcome;
}
/**
* @dev Tell whether a voter voted in favor of a certain outcome in a vote instance or not.
* @param _voteId ID of the vote instance to query if a voter voted in favor of a certain outcome
* @param _outcome Outcome to query if the given voter voted in favor of
* @param _voter Address of the voter to query if voted in favor of the given outcome
* @return True if the given voter voted in favor of the given outcome, false otherwise
*/
function hasVotedInFavorOf(uint256 _voteId, uint8 _outcome, address _voter) external view voteExists(_voteId) returns (bool) {
Vote storage vote = voteRecords[_voteId];
return vote.votes[_voter].outcome == _outcome;
}
/**
* @dev Filter a list of voters based on whether they voted in favor of a certain outcome in a vote instance or not.
* Note that if there was no winning outcome, it means that no one voted, then all voters will be considered
* voting against any of the given outcomes.
* @param _voteId ID of the vote instance to be checked
* @param _outcome Outcome to filter the list of voters of
* @param _voters List of addresses of the voters to be filtered
* @return List of results to tell whether a voter voted in favor of the given outcome or not
*/
function getVotersInFavorOf(uint256 _voteId, uint8 _outcome, address[] calldata _voters) external view voteExists(_voteId)
returns (bool[] memory)
{
Vote storage vote = voteRecords[_voteId];
bool[] memory votersInFavor = new bool[](_voters.length);
// If there was a winning outcome, filter those voters that voted in favor of the given outcome.
for (uint256 i = 0; i < _voters.length; i++) {
votersInFavor[i] = _outcome == vote.votes[_voters[i]].outcome;
}
return votersInFavor;
}
/**
* @dev Hash a vote outcome using a given salt
* @param _outcome Outcome to be hashed
* @param _salt Encryption salt
* @return Hashed outcome
*/
function hashVote(uint8 _outcome, bytes32 _salt) external pure returns (bytes32) {
return _hashVote(_outcome, _salt);
}
/**
* @dev Internal function to ensure votes can be committed for a vote
* @param _voteId ID of the vote instance to be checked
*/
function _ensureCanCommit(uint256 _voteId) internal {
ICRVotingOwner owner = _votingOwner();
owner.ensureCanCommit(_voteId);
}
/**
* @dev Internal function to ensure a voter can commit votes
* @param _voteId ID of the vote instance to be checked
* @param _voter Address of the voter willing to commit a vote
*/
function _ensureVoterCanCommit(uint256 _voteId, address _voter) internal {
ICRVotingOwner owner = _votingOwner();
owner.ensureCanCommit(_voteId, _voter);
}
/**
* @dev Internal function to ensure a voter can reveal votes
* @param _voteId ID of the vote instance to be checked
* @param _voter Address of the voter willing to reveal a vote
* @return Weight of the voter willing to reveal a vote
*/
function _ensureVoterCanReveal(uint256 _voteId, address _voter) internal returns (uint256) {
// There's no need to check voter weight, as this was done on commit
ICRVotingOwner owner = _votingOwner();
uint64 weight = owner.ensureCanReveal(_voteId, _voter);
return uint256(weight);
}
/**
* @dev Internal function to fetch the address of the Voting module's owner
* @return Address of the Voting module's owner
*/
function _votingOwner() internal view returns (ICRVotingOwner) {
return ICRVotingOwner(address(_disputeManager()));
}
/**
* @dev Internal function to check if a vote can be revealed for the given outcome and salt
* @param _castVote Cast vote to be revealed
* @param _outcome Outcome of the cast vote to be proved
* @param _salt Salt to decrypt and validate the provided outcome for a cast vote
*/
function _checkValidSalt(CastVote storage _castVote, uint8 _outcome, bytes32 _salt) internal view {
require(_castVote.outcome == OUTCOME_MISSING, ERROR_VOTE_ALREADY_REVEALED);
require(_castVote.commitment == _hashVote(_outcome, _salt), ERROR_INVALID_COMMITMENT_SALT);
}
/**
* @dev Internal function to tell whether a certain outcome is valid for a given vote instance or not. Note that
* the missing and leaked outcomes are not considered valid. The only outcomes considered valid are refused
* or any of the possible outcomes of the given vote instance. This function assumes the given vote exists.
* @param _vote Vote instance to check the outcome of
* @param _outcome Outcome to check if valid or not
* @return True if the given outcome is valid for the requested vote instance, false otherwise.
*/
function _isValidOutcome(Vote storage _vote, uint8 _outcome) internal view returns (bool) {
return _outcome >= OUTCOME_REFUSED && _outcome <= _vote.maxAllowedOutcome;
}
/**
* @dev Internal function to check if a vote instance was already created
* @param _voteId ID of the vote instance to be checked
* @return True if the given vote instance was already created, false otherwise
*/
function _existsVote(uint256 _voteId) internal view returns (bool) {
Vote storage vote = voteRecords[_voteId];
return vote.maxAllowedOutcome != OUTCOME_MISSING;
}
/**
* @dev Tell if a delegates represents another voter
* @param _voter Address of the principal being queried
* @param _delegate Address of the delegate being queried
* @return True if the given delegate currently represents the voter
*/
function _isDelegateOf(address _voter, address _delegate) internal view returns (bool) {
return _voter == _delegate || delegates[_voter] == _delegate;
}
/**
* @dev Internal function to hash a vote outcome using a given salt
* @param _outcome Outcome to be hashed
* @param _salt Encryption salt
* @return Hashed outcome
*/
function _hashVote(uint8 _outcome, bytes32 _salt) internal pure returns (bytes32) {
return keccak256(abi.encodePacked(_outcome, _salt));
}
/**
* @dev Tell chain ID
* @return chainId Chain ID
*/
function _chainId() internal pure returns (uint256 chainId) {
assembly { chainId := chainid() }
}
/**
* @dev Private function to update the tally of a given vote instance based on a new weight in favor of an outcome.
* This function assumes the vote instance exists.
* @param _vote Vote instance to update the tally of
* @param _outcome Outcome of the vote instance to update the tally of
* @param _weight Weight to be added to the given outcome of the vote instance
*/
function _updateTally(Vote storage _vote, uint8 _outcome, uint256 _weight) private {
// Check if the given outcome is valid. Missing and leaked votes are ignored for the tally.
if (!_isValidOutcome(_vote, _outcome)) {
return;
}
uint256 newOutcomeTally = _vote.outcomesTally[_outcome].add(_weight);
_vote.outcomesTally[_outcome] = newOutcomeTally;
// Update the winning outcome only if its support was passed or if the given outcome represents a lowest
// option than the winning outcome in case of a tie.
uint8 winningOutcome = _vote.winningOutcome;
uint256 winningOutcomeTally = _vote.outcomesTally[winningOutcome];
if (newOutcomeTally > winningOutcomeTally || (newOutcomeTally == winningOutcomeTally && _outcome < winningOutcome)) {
_vote.winningOutcome = _outcome;
}
}
}
|
Tell if a delegates represents another voter _voter Address of the principal being queried _delegate Address of the delegate being queried return True if the given delegate currently represents the voter/
|
function _isDelegateOf(address _voter, address _delegate) internal view returns (bool) {
return _voter == _delegate || delegates[_voter] == _delegate;
}
| 6,846,826 |
pragma solidity ^0.4.25;
/*******************************************************************************
*
* Copyright (c) 2019 Decentralization Authority MDAO.
* Released under the MIT License.
*
* Minado - Crypto Token Mining & Forging Community
*
* Minado has been optimized for mining ERC918-compatible tokens via
* the InfinityPool; a public storage of mineable ERC-20 tokens.
*
* Learn more below:
*
* Official : https://minado.network
* Ethereum : https://eips.ethereum.org/EIPS/eip-918
* Github : https://github.com/ethereum/EIPs/pull/918
* Reddit : https://www.reddit.com/r/Tokenmining
*
* Version 19.7.18
*
* Web : https://d14na.org
* Email : [email protected]
*/
/*******************************************************************************
*
* SafeMath
*/
library SafeMath {
function add(uint a, uint b) internal pure returns (uint c) {
c = a + b;
require(c >= a);
}
function sub(uint a, uint b) internal pure returns (uint c) {
require(b <= a);
c = a - b;
}
function mul(uint a, uint b) internal pure returns (uint c) {
c = a * b;
require(a == 0 || c / a == b);
}
function div(uint a, uint b) internal pure returns (uint c) {
require(b > 0);
c = a / b;
}
}
/*******************************************************************************
*
* ECRecovery
*
* Contract function to validate signature of pre-approved token transfers.
* (borrowed from LavaWallet)
*/
contract ECRecovery {
function recover(bytes32 hash, bytes sig) public pure returns (address);
}
/*******************************************************************************
*
* Owned contract
*/
contract Owned {
address public owner;
address public newOwner;
event OwnershipTransferred(address indexed _from, address indexed _to);
constructor() public {
owner = msg.sender;
}
modifier onlyOwner {
require(msg.sender == owner);
_;
}
function transferOwnership(address _newOwner) public onlyOwner {
newOwner = _newOwner;
}
function acceptOwnership() public {
require(msg.sender == newOwner);
emit OwnershipTransferred(owner, newOwner);
owner = newOwner;
newOwner = address(0);
}
}
/*******************************************************************************
*
* Zer0netDb Interface
*/
contract Zer0netDbInterface {
/* Interface getters. */
function getAddress(bytes32 _key) external view returns (address);
function getBool(bytes32 _key) external view returns (bool);
function getBytes(bytes32 _key) external view returns (bytes);
function getInt(bytes32 _key) external view returns (int);
function getString(bytes32 _key) external view returns (string);
function getUint(bytes32 _key) external view returns (uint);
/* Interface setters. */
function setAddress(bytes32 _key, address _value) external;
function setBool(bytes32 _key, bool _value) external;
function setBytes(bytes32 _key, bytes _value) external;
function setInt(bytes32 _key, int _value) external;
function setString(bytes32 _key, string _value) external;
function setUint(bytes32 _key, uint _value) external;
/* Interface deletes. */
function deleteAddress(bytes32 _key) external;
function deleteBool(bytes32 _key) external;
function deleteBytes(bytes32 _key) external;
function deleteInt(bytes32 _key) external;
function deleteString(bytes32 _key) external;
function deleteUint(bytes32 _key) external;
}
/*******************************************************************************
*
* ERC Token Standard #20 Interface
* https://github.com/ethereum/EIPs/blob/master/EIPS/eip-20-token-standard.md
*/
contract ERC20Interface {
function totalSupply() public constant returns (uint);
function balanceOf(address tokenOwner) public constant returns (uint balance);
function allowance(address tokenOwner, address spender) public constant returns (uint remaining);
function transfer(address to, uint tokens) public returns (bool success);
function approve(address spender, uint tokens) public returns (bool success);
function transferFrom(address from, address to, uint tokens) public returns (bool success);
event Transfer(address indexed from, address indexed to, uint tokens);
event Approval(address indexed tokenOwner, address indexed spender, uint tokens);
}
/*******************************************************************************
*
* InfinityPool Interface
*/
contract InfinityPoolInterface {
function transfer(address _token, address _to, uint _tokens) external returns (bool success);
}
/*******************************************************************************
*
* InfinityWell Interface
*/
contract InfinityWellInterface {
function forgeStones(address _owner, uint _tokens) external returns (bool success);
function destroyStones(address _owner, uint _tokens) external returns (bool success);
function transferERC20(address _token, address _to, uint _tokens) external returns (bool success);
function transferERC721(address _token, address _to, uint256 _tokenId) external returns (bool success);
}
/*******************************************************************************
*
* Staek(house) Factory Interface
*/
contract StaekFactoryInterface {
function balanceOf(bytes32 _staekhouseId) public view returns (uint balance);
function balanceOf(bytes32 _staekhouseId, address _owner) public view returns (uint balance);
function getStaekhouse(bytes32 _staekhouseId, address _staeker) external view returns (address factory, address token, address owner, uint ownerLockTime, uint providerLockTime, uint debtLimit, uint lockInterval, uint balance);
}
/*******************************************************************************
*
* @notice Minado - Token Mining Contract
*
* @dev This is a multi-token mining contract, which manages the proof-of-work
* verifications before authorizing the movement of tokens from the
* InfinityPool and InfinityWell.
*/
contract Minado is Owned {
using SafeMath for uint;
/* Initialize predecessor contract. */
address private _predecessor;
/* Initialize successor contract. */
address private _successor;
/* Initialize revision number. */
uint private _revision;
/* Initialize Zer0net Db contract. */
Zer0netDbInterface private _zer0netDb;
/**
* Set Namespace
*
* Provides a "unique" name for generating "unique" data identifiers,
* most commonly used as database "key-value" keys.
*
* NOTE: Use of `namespace` is REQUIRED when generating ANY & ALL
* Zer0netDb keys; in order to prevent ANY accidental or
* malicious SQL-injection vulnerabilities / attacks.
*/
string private _namespace = 'minado';
/**
* Large Target
*
* A big number used for difficulty targeting.
*
* NOTE: Bitcoin uses `2**224`.
*/
uint private _MAXIMUM_TARGET = 2**234;
/**
* Minimum Targets
*
* Minimum number used for difficulty targeting.
*/
uint private _MINIMUM_TARGET = 2**16;
/**
* Set basis-point multiplier.
*
* NOTE: Used for (integer-based) fractional calculations.
*/
uint private _BP_MUL = 10000;
/* Set InfinityStone decimals. */
uint private _STONE_DECIMALS = 18;
/* Set single InfinityStone. */
uint private _SINGLE_STONE = 1 * 10**_STONE_DECIMALS;
/**
* (Ethereum) Blocks Per Forge
*
* NOTE: Ethereum blocks take approx 15 seconds each.
* 1,000 blocks takes approx 4 hours.
*/
uint private _BLOCKS_PER_STONE_FORGE = 1000;
/**
* (Ethereum) Blocks Per Generation
*
* NOTE: We mirror the Bitcoin POW mining algorithm.
* We want miners to spend 10 minutes to mine each 'block'.
* (about 40 Ethereum blocks for every 1 Bitcoin block)
*/
uint BLOCKS_PER_GENERATION = 40; // Mainnet & Ropsten
// uint BLOCKS_PER_GENERATION = 120; // Kovan
/**
* (Mint) Generations Per Re-adjustment
*
* By default, we automatically trigger a difficulty adjustment
* after 144 generations / mints (approx 24 hours).
*
* Frequent adjustments are especially important with low-liquidity
* tokens, which are more susceptible to mining manipulation.
*
* For additional control, token providers retain the ability to trigger
* a difficulty re-calculation at any time.
*
* NOTE: Bitcoin re-adjusts its difficulty every 2,016 generations,
* which occurs approx. every 14 days.
*/
uint private _DEFAULT_GENERATIONS_PER_ADJUSTMENT = 144; // approx. 24hrs
event Claim(
address owner,
address token,
uint amount,
address collectible,
uint collectibleId
);
event Excavate(
address indexed token,
address indexed miner,
uint mintAmount,
uint epochCount,
bytes32 newChallenge
);
event Mint(
address indexed from,
uint rewardAmount,
uint epochCount,
bytes32 newChallenge
);
event ReCalculate(
address token,
uint newDifficulty
);
event Solution(
address indexed token,
address indexed miner,
uint difficulty,
uint nonce,
bytes32 challenge,
bytes32 newChallenge
);
/* Constructor. */
constructor() public {
/* Initialize Zer0netDb (eternal) storage database contract. */
// NOTE We hard-code the address here, since it should never change.
_zer0netDb = Zer0netDbInterface(0xE865Fe1A1A3b342bF0E2fcB11fF4E3BCe58263af);
// _zer0netDb = Zer0netDbInterface(0x4C2f68bCdEEB88764b1031eC330aD4DF8d6F64D6); // ROPSTEN
// _zer0netDb = Zer0netDbInterface(0x3e246C5038287DEeC6082B95b5741c147A3f49b3); // KOVAN
/* Initialize (aname) hash. */
bytes32 hash = keccak256(abi.encodePacked('aname.', _namespace));
/* Set predecessor address. */
_predecessor = _zer0netDb.getAddress(hash);
/* Verify predecessor address. */
if (_predecessor != 0x0) {
/* Retrieve the last revision number (if available). */
uint lastRevision = Minado(_predecessor).getRevision();
/* Set (current) revision number. */
_revision = lastRevision + 1;
}
}
/**
* @dev Only allow access to an authorized Zer0net administrator.
*/
modifier onlyAuthBy0Admin() {
/* Verify write access is only permitted to authorized accounts. */
require(_zer0netDb.getBool(keccak256(
abi.encodePacked(msg.sender, '.has.auth.for.', _namespace))) == true);
_; // function code is inserted here
}
/**
* @dev Only allow access to "registered" authorized user/contract.
*/
modifier onlyTokenProvider(
address _token
) {
/* Validate authorized token manager. */
require(_zer0netDb.getBool(keccak256(abi.encodePacked(
_namespace, '.',
msg.sender,
'.has.auth.for.',
_token
))) == true);
_; // function code is inserted here
}
/**
* THIS CONTRACT DOES NOT ACCEPT DIRECT ETHER
*/
function () public payable {
/* Cancel this transaction. */
revert('Oops! Direct payments are NOT permitted here.');
}
/***************************************************************************
*
* ACTIONS
*
*/
/**
* Initialize Token
*/
function init(
address _token,
address _provider
) external onlyAuthBy0Admin returns (bool success) {
/* Set hash. */
bytes32 hash = keccak256(abi.encodePacked(
_namespace, '.',
_token,
'.last.adjustment'
));
/* Set current adjustment time in Zer0net Db. */
_zer0netDb.setUint(hash, block.number);
/* Set hash. */
hash = keccak256(abi.encodePacked(
_namespace, '.',
_token,
'.generations.per.adjustment'
));
/* Set value in Zer0net Db. */
_zer0netDb.setUint(hash, _DEFAULT_GENERATIONS_PER_ADJUSTMENT);
/* Set hash. */
hash = keccak256(abi.encodePacked(
_namespace, '.',
_token,
'.challenge'
));
/* Set current adjustment time in Zer0net Db. */
_zer0netDb.setBytes(
hash,
_bytes32ToBytes(blockhash(block.number - 1))
);
/* Set mining target. */
// NOTE: This is the default difficulty of 1.
_setMiningTarget(
_token,
_MAXIMUM_TARGET
);
/* Set hash. */
hash = keccak256(abi.encodePacked(
_namespace, '.',
_provider,
'.has.auth.for.',
_token
));
/* Set value in Zer0net Db. */
_zer0netDb.setBool(hash, true);
return true;
}
/**
* Mint
*/
function mint(
address _token,
bytes32 _digest,
uint _nonce
) public returns (bool success) {
/* Retrieve the current challenge. */
uint challenge = getChallenge(_token);
/* Get mint digest. */
bytes32 digest = getMintDigest(
challenge,
msg.sender,
_nonce
);
/* The challenge digest must match the expected. */
if (digest != _digest) {
revert('Oops! That solution is NOT valid.');
}
/* The digest must be smaller than the target. */
if (uint(digest) > getTarget(_token)) {
revert('Oops! That solution is NOT valid.');
}
/* Set hash. */
bytes32 hash = keccak256(abi.encodePacked(
_namespace, '.',
digest,
'.solutions'
));
/* Retrieve value from Zer0net Db. */
uint solution = _zer0netDb.getUint(hash);
/* Validate solution. */
if (solution != 0x0) {
revert('Oops! That solution is a DUPLICATE.');
}
/* Save this digest to 'solved' solutions. */
_zer0netDb.setUint(hash, uint(digest));
/* Set hash. */
hash = keccak256(abi.encodePacked(
_namespace, '.',
_token,
'.generation'
));
/* Retrieve value from Zer0net Db. */
uint generation = _zer0netDb.getUint(hash);
/* Increment the generation. */
generation = generation.add(1);
/* Increment the generation count by 1. */
_zer0netDb.setUint(hash, generation);
/* Set hash. */
hash = keccak256(abi.encodePacked(
_namespace, '.',
_token,
'.generations.per.adjustment'
));
/* Retrieve value from Zer0net Db. */
uint genPerAdjustment = _zer0netDb.getUint(hash);
// every so often, readjust difficulty. Dont readjust when deploying
if (generation % genPerAdjustment == 0) {
_reAdjustDifficulty(_token);
}
/* Set hash. */
hash = keccak256(abi.encodePacked(
_namespace, '.',
_token,
'.challenge'
));
/**
* Make the latest ethereum block hash a part of the next challenge
* for PoW to prevent pre-mining future blocks. Do this last,
* since this is a protection mechanism in the mint() function.
*/
_zer0netDb.setBytes(
hash,
_bytes32ToBytes(blockhash(block.number - 1))
);
/* Retrieve mining reward. */
// FIXME Add support for percentage reward.
uint rewardAmount = getMintFixed(_token);
/* Transfer (token) reward to minter. */
_infinityPool().transfer(
_token,
msg.sender,
rewardAmount
);
/* Emit log info. */
emit Mint(
msg.sender,
rewardAmount,
generation,
blockhash(block.number - 1) // next target
);
/* Return success. */
return true;
}
/**
* Test Mint Solution
*/
function testMint(
bytes32 _digest,
uint _challenge,
address _minter,
uint _nonce,
uint _target
) public pure returns (bool success) {
/* Retrieve digest. */
bytes32 digest = getMintDigest(
_challenge,
_minter,
_nonce
);
/* Validate digest. */
// NOTE: Cast type to 256-bit integer
if (uint(digest) > _target) {
/* Set flag. */
success = false;
} else {
/* Verify success. */
success = (digest == _digest);
}
}
/**
* Re-calculate Difficulty
*
* Token owner(s) can "manually" trigger the re-calculation of their token,
* based on the parameters that have been set.
*
* NOTE: This will help deter malicious miners from gaming the difficulty
* parameter, to the detriment of the token's community.
*/
function reCalculateDifficulty(
address _token
) external onlyTokenProvider(_token) returns (bool success) {
/* Re-calculate difficulty. */
return _reAdjustDifficulty(_token);
}
/**
* Re-adjust Difficulty
*
* Re-adjust the target by 5 percent.
* (source: https://en.bitcoin.it/wiki/Difficulty#What_is_the_formula_for_difficulty.3F)
*
* NOTE: Assume 240 ethereum blocks per hour (approx. 15/sec)
*
* NOTE: As of 2017 the bitcoin difficulty was up to 17 zeroes,
* it was only 8 in the early days.
*/
function _reAdjustDifficulty(
address _token
) private returns (bool success) {
/* Set hash. */
bytes32 lastAdjustmentHash = keccak256(abi.encodePacked(
_namespace, '.',
_token,
'.last.adjustment'
));
/* Retrieve value from Zer0net Db. */
uint lastAdjustment = _zer0netDb.getUint(lastAdjustmentHash);
/* Retrieve value from Zer0net Db. */
uint blocksSinceLastAdjustment = block.number - lastAdjustment;
/* Set hash. */
bytes32 adjustmentHash = keccak256(abi.encodePacked(
_namespace, '.',
_token,
'.generations.per.adjustment'
));
/* Retrieve value from Zer0net Db. */
uint genPerAdjustment = _zer0netDb.getUint(adjustmentHash);
/* Calculate number of expected blocks per adjustment. */
uint expectedBlocksPerAdjustment = genPerAdjustment.mul(BLOCKS_PER_GENERATION);
/* Retrieve mining target. */
uint miningTarget = getTarget(_token);
/* Validate the number of blocks passed; if there were less eth blocks
* passed in time than expected, then miners are excavating too quickly.
*/
if (blocksSinceLastAdjustment < expectedBlocksPerAdjustment) {
// NOTE: This number will be an integer greater than 10000.
uint excess_block_pct = expectedBlocksPerAdjustment.mul(10000)
.div(blocksSinceLastAdjustment);
/**
* Excess Block Percentage Extra
*
* For example:
* If there were 5% more blocks mined than expected, then this is 500.
* If there were 25% more blocks mined than expected, then this is 2500.
*/
uint excess_block_pct_extra = excess_block_pct.sub(10000);
/* Set a maximum difficulty INCREASE of 50%. */
// NOTE: By default, this is within a 24hr period.
if (excess_block_pct_extra > 5000) {
excess_block_pct_extra = 5000;
}
/**
* Reset the Mining Target
*
* Calculate the difficulty difference, then SUBTRACT
* that value from the current difficulty.
*/
miningTarget = miningTarget.sub(
/* Calculate difficulty difference. */
miningTarget
.mul(excess_block_pct_extra)
.div(10000)
);
} else {
// NOTE: This number will be an integer greater than 10000.
uint shortage_block_pct = blocksSinceLastAdjustment.mul(10000)
.div(expectedBlocksPerAdjustment);
/**
* Shortage Block Percentage Extra
*
* For example:
* If it took 5% longer to mine than expected, then this is 500.
* If it took 25% longer to mine than expected, then this is 2500.
*/
uint shortage_block_pct_extra = shortage_block_pct.sub(10000);
// NOTE: There is NO limit on the amount of difficulty DECREASE.
/**
* Reset the Mining Target
*
* Calculate the difficulty difference, then ADD
* that value to the current difficulty.
*/
miningTarget = miningTarget.add(
miningTarget
.mul(shortage_block_pct_extra)
.div(10000)
);
}
/* Set current adjustment time in Zer0net Db. */
_zer0netDb.setUint(lastAdjustmentHash, block.number);
/* Validate TOO SMALL mining target. */
// NOTE: This is very difficult to guess.
if (miningTarget < _MINIMUM_TARGET) {
miningTarget = _MINIMUM_TARGET;
}
/* Validate TOO LARGE mining target. */
// NOTE: This is very easy to guess.
if (miningTarget > _MAXIMUM_TARGET) {
miningTarget = _MAXIMUM_TARGET;
}
/* Set mining target. */
_setMiningTarget(
_token,
miningTarget
);
/* Return success. */
return true;
}
/***************************************************************************
*
* GETTERS
*
*/
/**
* Get Starting Block
*
* Starting Blocks
* ---------------
*
* First blocks honoring the start of Miss Piggy's celebration year:
* - Mainnet : 7,175,716
* - Ropsten : 4,956,268
* - Kovan : 10,283,438
*
* NOTE: Pulls value from db `minado.starting.block` using the
* respective networks.
*/
function getStartingBlock() public view returns (uint startingBlock) {
/* Set hash. */
bytes32 hash = keccak256(abi.encodePacked(
_namespace,
'.starting.block'
));
/* Retrieve value from Zer0net Db. */
startingBlock = _zer0netDb.getUint(hash);
}
/**
* Get minter's mintng address.
*/
function getMinter() external view returns (address minter) {
/* Set hash. */
bytes32 hash = keccak256(abi.encodePacked(
_namespace,
'.minter'
));
/* Retrieve value from Zer0net Db. */
minter = _zer0netDb.getAddress(hash);
}
/**
* Get generation details.
*/
function getGeneration(
address _token
) external view returns (
uint generation,
uint cycle
) {
/* Set hash. */
bytes32 hash = keccak256(abi.encodePacked(
_namespace, '.',
_token,
'.generation'
));
/* Retrieve value from Zer0net Db. */
generation = _zer0netDb.getUint(hash);
/* Set hash. */
hash = keccak256(abi.encodePacked(
_namespace, '.',
_token,
'.generations.per.adjustment'
));
/* Retrieve value from Zer0net Db. */
cycle = _zer0netDb.getUint(hash);
}
/**
* Get Minting FIXED amount
*/
function getMintFixed(
address _token
) public view returns (uint amount) {
/* Set hash. */
bytes32 hash = keccak256(abi.encodePacked(
_namespace, '.',
_token,
'.mint.fixed'
));
/* Retrieve value from Zer0net Db. */
amount = _zer0netDb.getUint(hash);
}
/**
* Get Minting PERCENTAGE amount
*/
function getMintPct(
address _token
) public view returns (uint amount) {
/* Set hash. */
bytes32 hash = keccak256(abi.encodePacked(
_namespace, '.',
_token,
'.mint.pct'
));
/* Retrieve value from Zer0net Db. */
amount = _zer0netDb.getUint(hash);
}
/**
* Get (Mining) Challenge
*
* This is an integer representation of a recent ethereum block hash,
* used to prevent pre-mining future blocks.
*/
function getChallenge(
address _token
) public view returns (uint challenge) {
/* Set hash. */
bytes32 hash = keccak256(abi.encodePacked(
_namespace, '.',
_token,
'.challenge'
));
/* Retrieve value from Zer0net Db. */
// NOTE: Convert from bytes to integer.
challenge = uint(_bytesToBytes32(
_zer0netDb.getBytes(hash)
));
}
/**
* Get (Mining) Difficulty
*
* The number of zeroes the digest of the PoW solution requires.
* (auto adjusts)
*/
function getDifficulty(
address _token
) public view returns (uint difficulty) {
/* Caclulate difficulty. */
difficulty = _MAXIMUM_TARGET.div(getTarget(_token));
}
/**
* Get (Mining) Target
*/
function getTarget(
address _token
) public view returns (uint target) {
/* Set hash. */
bytes32 hash = keccak256(abi.encodePacked(
_namespace, '.',
_token,
'.target'
));
/* Retrieve value from Zer0net Db. */
target = _zer0netDb.getUint(hash);
}
/**
* Get Mint Digest
*
* The PoW must contain work that includes a recent
* ethereum block hash (challenge hash) and the
* msg.sender's address to prevent MITM attacks
*/
function getMintDigest(
uint _challenge,
address _minter,
uint _nonce
) public pure returns (bytes32 digest) {
/* Calculate digest. */
digest = keccak256(abi.encodePacked(
_challenge,
_minter,
_nonce
));
}
/**
* Get Revision (Number)
*/
function getRevision() public view returns (uint) {
return _revision;
}
/***************************************************************************
*
* SETTERS
*
*/
/**
* Set Generations Per (Difficulty) Adjustment
*
* Token owner(s) can adjust the number of generations
* per difficulty re-calculation.
*
* NOTE: This will help deter malicious miners from gaming the difficulty
* parameter, to the detriment of the token's community.
*/
function setGenPerAdjustment(
address _token,
uint _numBlocks
) external onlyTokenProvider(_token) returns (bool success) {
/* Set hash. */
bytes32 hash = keccak256(abi.encodePacked(
_namespace, '.',
_token,
'.generations.per.adjustment'
));
/* Set value in Zer0net Db. */
_zer0netDb.setUint(hash, _numBlocks);
/* Return success. */
return true;
}
/**
* Set (Fixed) Mint Amount
*/
function setMintFixed(
address _token,
uint _amount
) external onlyTokenProvider(_token) returns (bool success) {
/* Set hash. */
bytes32 hash = keccak256(abi.encodePacked(
_namespace, '.',
_token,
'.mint.fixed'
));
/* Set value in Zer0net Db. */
_zer0netDb.setUint(hash, _amount);
/* Return success. */
return true;
}
/**
* Set (Dynamic) Mint Percentage
*/
function setMintPct(
address _token,
uint _pct
) external onlyTokenProvider(_token) returns (bool success) {
/* Set hash. */
bytes32 hash = keccak256(abi.encodePacked(
_namespace, '.',
_token,
'.mint.pct'
));
/* Set value in Zer0net Db. */
_zer0netDb.setUint(hash, _pct);
/* Return success. */
return true;
}
/**
* Set Token Parent(s)
*
* Enables the use of merged mining by specifying (parent) tokens
* that offer an acceptibly HIGH difficulty for the child's own
* mining challenge.
*
* Parents are saved in priority levels:
* 1 - Most significant parent
* 2 - 2nd most significant parent
* ...
* # - Least significant parent
*/
function setTokenParents(
address _token,
address[] _parents
) external onlyTokenProvider(_token) returns (bool success) {
/* Set hash. */
bytes32 hash = keccak256(abi.encodePacked(
_namespace, '.',
_token,
'.parents'
));
// FIXME How should we store a dynamic amount of parents?
// Packed as bytes??
// FIXME TEMPORARILY LIMITED TO 3
bytes memory allParents = abi.encodePacked(
_parents[0],
_parents[1],
_parents[2]
);
/* Set value in Zer0net Db. */
_zer0netDb.setBytes(hash, allParents);
/* Return success. */
return true;
}
/**
* Set Token Provider
*/
function setTokenProvider(
address _token,
address _provider,
bool _auth
) external onlyAuthBy0Admin returns (bool success) {
/* Set hash. */
bytes32 hash = keccak256(abi.encodePacked(
_namespace, '.',
_provider,
'.has.auth.for.',
_token
));
/* Set value in Zer0net Db. */
_zer0netDb.setBool(hash, _auth);
/* Return success. */
return true;
}
/**
* Set Mining Target
*/
function _setMiningTarget(
address _token,
uint _target
) private returns (bool success) {
/* Set hash. */
bytes32 hash = keccak256(abi.encodePacked(
_namespace, '.',
_token,
'.target'
));
/* Set value in Zer0net Db. */
_zer0netDb.setUint(hash, _target);
/* Return success. */
return true;
}
/***************************************************************************
*
* INTERFACES
*
*/
/**
* Supports Interface (EIP-165)
*
* (see: https://github.com/ethereum/EIPs/blob/master/EIPS/eip-165.md)
*
* NOTE: Must support the following conditions:
* 1. (true) when interfaceID is 0x01ffc9a7 (EIP165 interface)
* 2. (false) when interfaceID is 0xffffffff
* 3. (true) for any other interfaceID this contract implements
* 4. (false) for any other interfaceID
*/
function supportsInterface(
bytes4 _interfaceID
) external pure returns (bool) {
/* Initialize constants. */
bytes4 InvalidId = 0xffffffff;
bytes4 ERC165Id = 0x01ffc9a7;
/* Validate condition #2. */
if (_interfaceID == InvalidId) {
return false;
}
/* Validate condition #1. */
if (_interfaceID == ERC165Id) {
return true;
}
// TODO Add additional interfaces here.
/* Return false (for condition #4). */
return false;
}
/**
* ECRecovery Interface
*/
function _ecRecovery() private view returns (
ECRecovery ecrecovery
) {
/* Initialize hash. */
bytes32 hash = keccak256('aname.ecrecovery');
/* Retrieve value from Zer0net Db. */
address aname = _zer0netDb.getAddress(hash);
/* Initialize interface. */
ecrecovery = ECRecovery(aname);
}
/**
* InfinityPool Interface
*
* Retrieves the current InfinityPool interface,
* using the aname record from Zer0netDb.
*/
function _infinityPool() private view returns (
InfinityPoolInterface infinityPool
) {
/* Initailze hash. */
bytes32 hash = keccak256('aname.infinitypool');
/* Retrieve value from Zer0net Db. */
address aname = _zer0netDb.getAddress(hash);
/* Initialize interface. */
infinityPool = InfinityPoolInterface(aname);
}
/**
* InfinityWell Interface
*
* Retrieves the current InfinityWell interface,
* using the aname record from Zer0netDb.
*/
function _infinityWell() private view returns (
InfinityWellInterface infinityWell
) {
/* Initailze hash. */
bytes32 hash = keccak256('aname.infinitywell');
/* Retrieve value from Zer0net Db. */
address aname = _zer0netDb.getAddress(hash);
/* Initialize interface. */
infinityWell = InfinityWellInterface(aname);
}
/***************************************************************************
*
* UTILITIES
*
*/
/**
* Bytes-to-Address
*
* Converts bytes into type address.
*/
function _bytesToAddress(bytes _address) private pure returns (address) {
uint160 m = 0;
uint160 b = 0;
for (uint8 i = 0; i < 20; i++) {
m *= 256;
b = uint160(_address[i]);
m += (b);
}
return address(m);
}
/**
* Convert Bytes to Bytes32
*/
function _bytesToBytes32(
bytes _data
) private pure returns (bytes32 result) {
/* Loop through each byte. */
for (uint i = 0; i < 32; i++) {
/* Shift bytes onto result. */
result |= bytes32(_data[i] & 0xFF) >> (i * 8);
}
}
/**
* Convert Bytes32 to Bytes
*
* NOTE: Since solidity v0.4.22, you can use `abi.encodePacked()` for this,
* which returns bytes. (https://ethereum.stackexchange.com/a/55963)
*/
function _bytes32ToBytes(
bytes32 _data
) private pure returns (bytes result) {
/* Pack the data. */
return abi.encodePacked(_data);
}
}
|
Supports Interface (EIP-165) NOTE: Must support the following conditions: 1. (true) when interfaceID is 0x01ffc9a7 (EIP165 interface) 2. (false) when interfaceID is 0xffffffff 3. (true) for any other interfaceID this contract implements 4. (false) for any other interfaceID/ Initialize constants. / Validate condition 2. / Validate condition 1. /
|
function supportsInterface(
bytes4 _interfaceID
) external pure returns (bool) {
bytes4 InvalidId = 0xffffffff;
bytes4 ERC165Id = 0x01ffc9a7;
if (_interfaceID == InvalidId) {
return false;
}
if (_interfaceID == ERC165Id) {
return true;
}
}
| 902,663 |
./full_match/8453/0x33d34437238A91c18242715a523c2F0A4d74C904/sources/contracts/CorePair.sol
|
this low-level function should be called from a contract which performs important safety checks gas savings gas savings, must be defined here since totalSupply can update in _mintFee permanently lock the first MINIMUM_LIQUIDITY tokens
|
function mint(address to) external lock returns (uint liquidity) {
(uint112 _reserve0, uint112 _reserve1,,) = getReserves();
uint balance0 = IERC20(token0).balanceOf(address(this));
uint balance1 = IERC20(token1).balanceOf(address(this));
uint amount0 = balance0.sub(_reserve0);
uint amount1 = balance1.sub(_reserve1);
bool feeOn = _mintFee(_reserve0, _reserve1);
uint _totalSupply = totalSupply;
if (_totalSupply == 0) {
liquidity = Math.sqrt(amount0.mul(amount1)).sub(MINIMUM_LIQUIDITY);
_mint(address(0), MINIMUM_LIQUIDITY);
liquidity = Math.min(amount0.mul(_totalSupply) / _reserve0, amount1.mul(_totalSupply) / _reserve1);
}
require(liquidity > 0, 'CorePair: INSUFFICIENT_LIQUIDITY_MINTED');
_mint(to, liquidity);
_update(balance0, balance1);
if (feeOn) kLast = _k(uint(reserve0), uint(reserve1));
}
| 11,558,413 |
./full_match/44787/0x59916829f0d01d8F05a2389928CaC6FecBAd4937/sources/contracts/governor/ubiCommittee/UBICommitteeImplementation.sol
|
Executes a queued proposal if eta has passed _proposalId The id of the proposal to execute/
|
function execute(uint256 _proposalId) external onlyMember payable {
require(
state(_proposalId) == ProposalState.Succeeded,
"PACT::execute: proposal can only be executed if it is succeeded"
);
Proposal storage _proposal = proposals[_proposalId];
_proposal.executed = true;
for (uint256 i = 0; i < proposalCalldatas[_proposalId].length; i++) {
bytes memory _callData;
if (bytes(proposalSignatures[_proposalId][i]).length == 0) {
_callData = proposalCalldatas[_proposalId][i];
_callData = abi.encodePacked(
bytes4(keccak256(bytes(proposalSignatures[_proposalId][i]))),
proposalCalldatas[_proposalId][i]
);
}
require(_success, "PACT::execute: Transaction execution reverted.");
}
emit ProposalExecuted(_proposalId);
}
| 13,275,485 |
./full_match/1/0x5682dC851C33adb48F6958a963A5d3Aa31F6f184/sources/contracts/router/quoter/SwapQuoterV2.sol
|
Returns the data for the given pool: pool address, LP token address (if applicable), and tokens. Populate LP token field only for default pools
|
function _getPoolData(PoolType poolType, address pool) internal view returns (Pool memory poolData) {
poolData.pool = pool;
if (poolType == PoolType.Default) poolData.lpToken = _lpToken(pool);
poolData.tokens = _getPoolTokens(pool);
}
| 4,844,618 |
// SPDX-License-Identifier: MIT
pragma solidity 0.8.11;
import "@openzeppelin/contracts/utils/Strings.sol";
import "@openzeppelin/contracts/access/Ownable.sol";
import "@openzeppelin/contracts/security/ReentrancyGuard.sol";
import "@openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol";
import "./ERC721Min.sol";
contract OwnableDelegateProxy {}
contract OpenSeaProxyRegistry {
mapping(address => OwnableDelegateProxy) public proxies;
}
contract NFTSales is Ownable, ERC721Min, ReentrancyGuard {
using Strings for uint256;
using SafeERC20 for IERC20;
address public immutable proxyRegistryAddress; // opensea proxy
mapping(address => bool) proxyToApproved; // proxy allowance for interaction with future contract
string private _contractURI;
string private _tokenBaseURI = ""; // SET TO THE METADATA URI
address private treasuryAddress = 0x14891CD5d3Aa2D858b1daEB1eDeEAB605eebcFCb;
bool useBaseUriOnly = true;
mapping(uint256 => string) public TokenURIMap; // allows for assigning individual/unique metada per token
struct NftType {
uint16 purchaseCount;
uint16 maxPerAddress;
uint16 maxPerMint;
uint16 maxPerAddressForThree;
uint16 maxMint;
uint16 maxMintForOne;
uint16 maxMintForThree;
bool saleActive;
uint256 price;
uint256 priceForThree;
mapping(address => uint256) PurchasesByAddress;
string uri;
}
struct FeeRecipient {
address recipient;
uint256 basisPoints;
}
mapping(uint256 => FeeRecipient) public FeeRecipients;
uint256 feeRecipientCount;
uint256 totalFeeBasisPoints;
mapping(uint256 => NftType) public NftTypes;
uint256 public nftTypeCount;
bool public transferDisabled;
mapping(uint256 => uint256) public NftIdToNftType;
constructor() ERC721Min("ASSASSIN-8 UTILITY NFT", "ASS8U") {
proxyRegistryAddress = 0xa5409ec958C83C3f309868babACA7c86DCB077c1;
}
function totalSupply() external view returns(uint256) {
return _owners.length;
}
// ** - CORE - ** //
function buyOne(uint256 nftTypeId) external payable {
require(NftTypes[nftTypeId].saleActive, "SALE_CLOSED");
require(NftTypes[nftTypeId].price == msg.value, "INCORRECT_ETH");
require(NftTypes[nftTypeId].maxMintForOne > NftTypes[nftTypeId].purchaseCount, "EXCEED_MAX_SALE_SUPPLY");
require(NftTypes[nftTypeId].maxPerAddress == 0 ||
NftTypes[nftTypeId].PurchasesByAddress[_msgSender()] < NftTypes[nftTypeId].maxPerAddress, "EXCEED_MAX_PER_USER");
NftIdToNftType[_owners.length] = nftTypeId;
_mintMin();
if (NftTypes[nftTypeId].maxPerAddress > 0) NftTypes[nftTypeId].PurchasesByAddress[_msgSender()]++;
NftTypes[nftTypeId].purchaseCount++;
}
function buyThree(uint256 nftTypeId) external payable {
require(NftTypes[nftTypeId].saleActive, "SALE_CLOSED");
require(NftTypes[nftTypeId].priceForThree == msg.value, "INCORRECT_ETH");
require(NftTypes[nftTypeId].maxMintForThree > NftTypes[nftTypeId].purchaseCount, "EXCEED_MAX_SALE_SUPPLY");
require(NftTypes[nftTypeId].maxPerAddress == 0 ||
NftTypes[nftTypeId].PurchasesByAddress[_msgSender()] < NftTypes[nftTypeId].maxPerAddressForThree, "EXCEED_MAX_PER_USER");
NftIdToNftType[_owners.length] = nftTypeId;
_mintMin();
NftIdToNftType[_owners.length] = nftTypeId;
_mintMin();
NftIdToNftType[_owners.length] = nftTypeId;
_mintMin();
if (NftTypes[nftTypeId].maxPerAddress > 0) {
NftTypes[nftTypeId].PurchasesByAddress[_msgSender()] += 3;
}
NftTypes[nftTypeId].purchaseCount += 3;
}
function buy(uint256 nftTypeId, uint16 amount) external payable {
require(NftTypes[nftTypeId].saleActive, "SALE_CLOSED");
require(NftTypes[nftTypeId].price * amount == msg.value, "INCORRECT_ETH");
require(NftTypes[nftTypeId].maxMint > NftTypes[nftTypeId].purchaseCount + amount, "EXCEED_MAX_SALE_SUPPLY");
require(amount < NftTypes[nftTypeId].maxPerMint, "EXCEED_MAX_PER_MINT");
require(NftTypes[nftTypeId].maxPerAddress > 0 ||
NftTypes[nftTypeId].PurchasesByAddress[_msgSender()] + amount - 1 < NftTypes[nftTypeId].maxPerAddress, "EXCEED_MAX_PER_USER");
for (uint256 i = 0; i < amount; i++) {
NftIdToNftType[_owners.length] = nftTypeId;
_mintMin();
}
NftTypes[nftTypeId].purchaseCount += amount;
}
// ** - PROXY - ** //
function mintOne(address receiver, uint256 nftTypeId) external onlyProxy {
NftIdToNftType[_owners.length] = nftTypeId;
_mintMin2(receiver);
}
function mintThree(address receiver, uint256 nftTypeId) external onlyProxy {
NftIdToNftType[_owners.length] = nftTypeId;
_mintMin2(receiver);
NftIdToNftType[_owners.length] = nftTypeId;
_mintMin2(receiver);
NftIdToNftType[_owners.length] = nftTypeId;
_mintMin2(receiver);
}
function mint(address receiver, uint256 nftTypeId, uint256 tokenQuantity) external onlyProxy {
for (uint256 i = 0; i < tokenQuantity; i++) {
NftIdToNftType[_owners.length] = nftTypeId;
_mintMin2(receiver);
}
}
function getNftTokenIdForUserForNftType(address user, uint nftType) external view returns(uint) {
uint result;
uint bal = balanceOf(user);
for (uint x = 0; x < bal; x++) {
uint id = tokenOfOwnerByIndex(user, x);
if (NftIdToNftType[id] == nftType) {
return id;
}
}
return result;
}
function userHasNftType(address user, uint nftType) external view returns(bool) {
uint bal = balanceOf(user);
for (uint x = 0; x < bal; x++) {
uint id = tokenOfOwnerByIndex(user, x);
if (NftIdToNftType[id] == nftType) return true;
}
return false;
}
// ** - ADMIN - ** //
function addFeeRecipient(address recipient, uint256 basisPoints) external onlyOwner {
feeRecipientCount++;
FeeRecipients[feeRecipientCount].recipient = recipient;
FeeRecipients[feeRecipientCount].basisPoints = basisPoints;
totalFeeBasisPoints += basisPoints;
}
function editFeeRecipient(uint256 id, address recipient, uint256 basisPoints) external onlyOwner {
require(id <= feeRecipientCount, "INVALID_ID");
totalFeeBasisPoints = totalFeeBasisPoints - FeeRecipients[feeRecipientCount].basisPoints + basisPoints;
FeeRecipients[feeRecipientCount].recipient = recipient;
FeeRecipients[feeRecipientCount].basisPoints = basisPoints;
}
function distributeETH() public {
require(treasuryAddress != address(0), "TREASURY_NOT_SET");
uint256 bal = address(this).balance;
for(uint256 x = 1; x <= feeRecipientCount; x++) {
uint256 amount = bal * FeeRecipients[x].basisPoints / totalFeeBasisPoints;
amount = amount > address(this).balance ? address(this).balance : amount;
(bool sent, ) = FeeRecipients[x].recipient.call{value: amount}("");
require(sent, "FAILED_SENDING_FUNDS");
}
emit DistributeETH(_msgSender(), bal);
}
function withdrawETH() public {
require(treasuryAddress != address(0), "TREASURY_NOT_SET");
uint256 bal = address(this).balance;
(bool sent, ) = treasuryAddress.call{value: bal}("");
require(sent, "FAILED_SENDING_FUNDS");
emit WithdrawETH(_msgSender(), bal);
}
function withdraw(address _token) external nonReentrant {
require(_msgSender() == owner() || _msgSender() == treasuryAddress, "NOT_ALLOWED");
require(treasuryAddress != address(0), "TREASURY_NOT_SET");
IERC20(_token).safeTransfer(
treasuryAddress,
IERC20(_token).balanceOf(address(this))
);
}
function gift(uint256 nftTypeId, address[] calldata receivers, uint256[] memory amounts) external onlyOwner {
for (uint256 x = 0; x < receivers.length; x++) {
for (uint256 i = 0; i < amounts[x]; i++) {
NftIdToNftType[_owners.length] = nftTypeId;
_mintMin2(receivers[x]);
}
}
}
// ** - NFT Types - ** //
function addNftType(uint16 _maxMint, uint16 _maxPerMint, uint256 _price,
uint16 _maxPerAddress, bool _saleActive, string calldata _uri) external onlyOwner
{
nftTypeCount++;
NftTypes[nftTypeCount].maxMint = _maxMint+1;
NftTypes[nftTypeCount].maxMintForOne = _maxMint;
NftTypes[nftTypeCount].maxMintForThree = _maxMint-2;
NftTypes[nftTypeCount].maxPerMint = _maxPerMint;
NftTypes[nftTypeCount].price = _price;
NftTypes[nftTypeCount].priceForThree = _price * 3;
NftTypes[nftTypeCount].maxPerAddress = _maxPerAddress > 0 ? _maxPerAddress : NftTypes[nftTypeCount].maxPerAddress;
NftTypes[nftTypeCount].maxPerAddressForThree = _maxPerAddress > 1 ? _maxPerAddress - 2 : NftTypes[nftTypeCount].maxPerAddress;
NftTypes[nftTypeCount].saleActive = _saleActive;
NftTypes[nftTypeCount].uri = _uri;
}
function toggleSaleActive(uint256 nftTypeId) external onlyOwner {
NftTypes[nftTypeId].saleActive = !NftTypes[nftTypeId].saleActive;
}
function setMaxPerMint(uint256 nftTypeId, uint16 maxPerMint) external onlyOwner {
NftTypes[nftTypeId].maxPerMint = maxPerMint;
}
function setMaxMint(uint256 nftTypeId, uint16 maxMint_) external onlyOwner {
NftTypes[nftTypeId].maxMint = maxMint_ + 1;
NftTypes[nftTypeId].maxMintForOne = maxMint_;
NftTypes[nftTypeId].maxMintForThree = maxMint_ - 2;
}
function setMaxPerAddress(uint256 nftTypeId, uint16 _maxPerAddress) external onlyOwner {
NftTypes[nftTypeId].maxPerAddress = _maxPerAddress > 0 ? _maxPerAddress : 0;
NftTypes[nftTypeId].maxPerAddressForThree = _maxPerAddress > 1 ? _maxPerAddress - 2 : NftTypes[nftTypeCount].maxPerAddress;
}
function setPrice(uint256 nftTypeId, uint256 _price) external onlyOwner {
NftTypes[nftTypeId].price = _price;
NftTypes[nftTypeId].priceForThree = _price * 3;
}
function setNftTypeUri(uint256 nftTypeId, string calldata uri) external onlyOwner {
NftTypes[nftTypeId].uri = uri;
}
// to avoid opensea listing costs
function isApprovedForAll(address _owner, address operator) public view override returns (bool) {
OpenSeaProxyRegistry proxyRegistry = OpenSeaProxyRegistry(proxyRegistryAddress);
if (
address(proxyRegistry.proxies(_owner)) == operator ||
proxyToApproved[operator]
) return true;
return super.isApprovedForAll(_owner, operator);
}
function flipProxyState(address proxyAddress) public onlyOwner {
proxyToApproved[proxyAddress] = !proxyToApproved[proxyAddress];
}
// ** - SETTERS - ** //
function setVaultAddress(address addr) external onlyOwner {
treasuryAddress = addr;
}
function setContractURI(string calldata URI) external onlyOwner {
_contractURI = URI;
}
function setBaseURI(string calldata URI) external onlyOwner {
_tokenBaseURI = URI;
}
// ** - MISC - ** //
function contractURI() public view returns (string memory) {
return _contractURI;
}
function toggleUseBaseUri() external onlyOwner {
useBaseUriOnly = !useBaseUriOnly;
}
function tokenURI(uint256 tokenId) external view virtual override returns (string memory) {
require(_exists(tokenId), "ERC721Metadata: URI query for nonexistent token");
if (bytes(TokenURIMap[tokenId]).length > 0) return TokenURIMap[tokenId];
if (bytes(NftTypes[NftIdToNftType[tokenId]].uri).length > 0) return NftTypes[NftIdToNftType[tokenId]].uri;
if (useBaseUriOnly) return _tokenBaseURI;
return bytes(_tokenBaseURI).length > 0
? string(abi.encodePacked(_tokenBaseURI, tokenId.toString()))
: "";
}
function setTokenUri(uint256 tokenId, string calldata uri) external onlyOwner {
TokenURIMap[tokenId] = uri;
}
function isOwnerOf(address account, uint256[] calldata _tokenIds) external view returns (bool) {
for (uint256 i; i < _tokenIds.length; ++i) {
if (_owners[_tokenIds[i]] != account) return false;
}
return true;
}
function setTransferDisabled(bool _transferDisabled) external onlyOwner {
transferDisabled = _transferDisabled;
}
function setStakingContract(address stakingContract) external onlyOwner {
_setStakingContract(stakingContract);
}
function unStake(uint256 tokenId) external onlyOwner {
_unstake(tokenId);
}
function batchSafeTransferFrom(address _from, address _to, uint256[] memory _tokenIds, bytes memory data_) public override {
require(!transferDisabled || _msgSender() == owner() || proxyToApproved[_msgSender()], "TRANSFER_DISABLED");
super.batchSafeTransferFrom(_from, _to, _tokenIds, data_);
}
function batchTransferFrom(address _from, address _to, uint256[] memory _tokenIds) public override {
require(!transferDisabled || _msgSender() == owner() || proxyToApproved[_msgSender()], "TRANSFER_DISABLED");
super.batchTransferFrom(_from, _to, _tokenIds);
}
function safeTransferFrom(address from, address to, uint256 tokenId, bytes memory _data) public override {
require(!transferDisabled || _msgSender() == owner() || proxyToApproved[_msgSender()], "TRANSFER_DISABLED");
super.safeTransferFrom(from, to, tokenId, _data);
}
function transferFrom(address from, address to, uint256 tokenId) public override {
require(!transferDisabled || _msgSender() == owner() || proxyToApproved[_msgSender()], "TRANSFER_DISABLED");
super.transferFrom(from, to, tokenId);
}
modifier onlyProxy() {
require(proxyToApproved[_msgSender()] == true, "onlyProxy");
_;
}
event DistributeETH(address indexed sender, uint256 indexed balance);
event WithdrawETH(address indexed sender, uint256 indexed balance);
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (utils/Strings.sol)
pragma solidity ^0.8.0;
/**
* @dev String operations.
*/
library Strings {
bytes16 private constant _HEX_SYMBOLS = "0123456789abcdef";
/**
* @dev Converts a `uint256` to its ASCII `string` decimal representation.
*/
function toString(uint256 value) internal pure returns (string memory) {
// Inspired by OraclizeAPI's implementation - MIT licence
// https://github.com/oraclize/ethereum-api/blob/b42146b063c7d6ee1358846c198246239e9360e8/oraclizeAPI_0.4.25.sol
if (value == 0) {
return "0";
}
uint256 temp = value;
uint256 digits;
while (temp != 0) {
digits++;
temp /= 10;
}
bytes memory buffer = new bytes(digits);
while (value != 0) {
digits -= 1;
buffer[digits] = bytes1(uint8(48 + uint256(value % 10)));
value /= 10;
}
return string(buffer);
}
/**
* @dev Converts a `uint256` to its ASCII `string` hexadecimal representation.
*/
function toHexString(uint256 value) internal pure returns (string memory) {
if (value == 0) {
return "0x00";
}
uint256 temp = value;
uint256 length = 0;
while (temp != 0) {
length++;
temp >>= 8;
}
return toHexString(value, length);
}
/**
* @dev Converts a `uint256` to its ASCII `string` hexadecimal representation with fixed length.
*/
function toHexString(uint256 value, uint256 length) internal pure returns (string memory) {
bytes memory buffer = new bytes(2 * length + 2);
buffer[0] = "0";
buffer[1] = "x";
for (uint256 i = 2 * length + 1; i > 1; --i) {
buffer[i] = _HEX_SYMBOLS[value & 0xf];
value >>= 4;
}
require(value == 0, "Strings: hex length insufficient");
return string(buffer);
}
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (access/Ownable.sol)
pragma solidity ^0.8.0;
import "../utils/Context.sol";
/**
* @dev Contract module which provides a basic access control mechanism, where
* there is an account (an owner) that can be granted exclusive access to
* specific functions.
*
* By default, the owner account will be the one that deploys the contract. This
* can later be changed with {transferOwnership}.
*
* This module is used through inheritance. It will make available the modifier
* `onlyOwner`, which can be applied to your functions to restrict their use to
* the owner.
*/
abstract contract Ownable is Context {
address private _owner;
event OwnershipTransferred(address indexed previousOwner, address indexed newOwner);
/**
* @dev Initializes the contract setting the deployer as the initial owner.
*/
constructor() {
_transferOwnership(_msgSender());
}
/**
* @dev Returns the address of the current owner.
*/
function owner() public view virtual returns (address) {
return _owner;
}
/**
* @dev Throws if called by any account other than the owner.
*/
modifier onlyOwner() {
require(owner() == _msgSender(), "Ownable: caller is not the owner");
_;
}
/**
* @dev Leaves the contract without owner. It will not be possible to call
* `onlyOwner` functions anymore. Can only be called by the current owner.
*
* NOTE: Renouncing ownership will leave the contract without an owner,
* thereby removing any functionality that is only available to the owner.
*/
function renounceOwnership() public virtual onlyOwner {
_transferOwnership(address(0));
}
/**
* @dev Transfers ownership of the contract to a new account (`newOwner`).
* Can only be called by the current owner.
*/
function transferOwnership(address newOwner) public virtual onlyOwner {
require(newOwner != address(0), "Ownable: new owner is the zero address");
_transferOwnership(newOwner);
}
/**
* @dev Transfers ownership of the contract to a new account (`newOwner`).
* Internal function without access restriction.
*/
function _transferOwnership(address newOwner) internal virtual {
address oldOwner = _owner;
_owner = newOwner;
emit OwnershipTransferred(oldOwner, newOwner);
}
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (security/ReentrancyGuard.sol)
pragma solidity ^0.8.0;
/**
* @dev Contract module that helps prevent reentrant calls to a function.
*
* Inheriting from `ReentrancyGuard` will make the {nonReentrant} modifier
* available, which can be applied to functions to make sure there are no nested
* (reentrant) calls to them.
*
* Note that because there is a single `nonReentrant` guard, functions marked as
* `nonReentrant` may not call one another. This can be worked around by making
* those functions `private`, and then adding `external` `nonReentrant` entry
* points to them.
*
* TIP: If you would like to learn more about reentrancy and alternative ways
* to protect against it, check out our blog post
* https://blog.openzeppelin.com/reentrancy-after-istanbul/[Reentrancy After Istanbul].
*/
abstract contract ReentrancyGuard {
// Booleans are more expensive than uint256 or any type that takes up a full
// word because each write operation emits an extra SLOAD to first read the
// slot's contents, replace the bits taken up by the boolean, and then write
// back. This is the compiler's defense against contract upgrades and
// pointer aliasing, and it cannot be disabled.
// The values being non-zero value makes deployment a bit more expensive,
// but in exchange the refund on every call to nonReentrant will be lower in
// amount. Since refunds are capped to a percentage of the total
// transaction's gas, it is best to keep them low in cases like this one, to
// increase the likelihood of the full refund coming into effect.
uint256 private constant _NOT_ENTERED = 1;
uint256 private constant _ENTERED = 2;
uint256 private _status;
constructor() {
_status = _NOT_ENTERED;
}
/**
* @dev Prevents a contract from calling itself, directly or indirectly.
* Calling a `nonReentrant` function from another `nonReentrant`
* function is not supported. It is possible to prevent this from happening
* by making the `nonReentrant` function external, and making it call a
* `private` function that does the actual work.
*/
modifier nonReentrant() {
// On the first call to nonReentrant, _notEntered will be true
require(_status != _ENTERED, "ReentrancyGuard: reentrant call");
// Any calls to nonReentrant after this point will fail
_status = _ENTERED;
_;
// By storing the original value once again, a refund is triggered (see
// https://eips.ethereum.org/EIPS/eip-2200)
_status = _NOT_ENTERED;
}
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (token/ERC20/utils/SafeERC20.sol)
pragma solidity ^0.8.0;
import "../IERC20.sol";
import "../../../utils/Address.sol";
/**
* @title SafeERC20
* @dev Wrappers around ERC20 operations that throw on failure (when the token
* contract returns false). Tokens that return no value (and instead revert or
* throw on failure) are also supported, non-reverting calls are assumed to be
* successful.
* To use this library you can add a `using SafeERC20 for IERC20;` statement to your contract,
* which allows you to call the safe operations as `token.safeTransfer(...)`, etc.
*/
library SafeERC20 {
using Address for address;
function safeTransfer(
IERC20 token,
address to,
uint256 value
) internal {
_callOptionalReturn(token, abi.encodeWithSelector(token.transfer.selector, to, value));
}
function safeTransferFrom(
IERC20 token,
address from,
address to,
uint256 value
) internal {
_callOptionalReturn(token, abi.encodeWithSelector(token.transferFrom.selector, from, to, value));
}
/**
* @dev Deprecated. This function has issues similar to the ones found in
* {IERC20-approve}, and its usage is discouraged.
*
* Whenever possible, use {safeIncreaseAllowance} and
* {safeDecreaseAllowance} instead.
*/
function safeApprove(
IERC20 token,
address spender,
uint256 value
) internal {
// safeApprove should only be called when setting an initial allowance,
// or when resetting it to zero. To increase and decrease it, use
// 'safeIncreaseAllowance' and 'safeDecreaseAllowance'
require(
(value == 0) || (token.allowance(address(this), spender) == 0),
"SafeERC20: approve from non-zero to non-zero allowance"
);
_callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, value));
}
function safeIncreaseAllowance(
IERC20 token,
address spender,
uint256 value
) internal {
uint256 newAllowance = token.allowance(address(this), spender) + value;
_callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance));
}
function safeDecreaseAllowance(
IERC20 token,
address spender,
uint256 value
) internal {
unchecked {
uint256 oldAllowance = token.allowance(address(this), spender);
require(oldAllowance >= value, "SafeERC20: decreased allowance below zero");
uint256 newAllowance = oldAllowance - value;
_callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance));
}
}
/**
* @dev Imitates a Solidity high-level call (i.e. a regular function call to a contract), relaxing the requirement
* on the return value: the return value is optional (but if data is returned, it must not be false).
* @param token The token targeted by the call.
* @param data The call data (encoded using abi.encode or one of its variants).
*/
function _callOptionalReturn(IERC20 token, bytes memory data) private {
// We need to perform a low level call here, to bypass Solidity's return data size checking mechanism, since
// we're implementing it ourselves. We use {Address.functionCall} to perform this call, which verifies that
// the target address contains contract code and also asserts for success in the low-level call.
bytes memory returndata = address(token).functionCall(data, "SafeERC20: low-level call failed");
if (returndata.length > 0) {
// Return data is optional
require(abi.decode(returndata, (bool)), "SafeERC20: ERC20 operation did not succeed");
}
}
}
// SPDX-License-Identifier: MIT
pragma solidity 0.8.11;
import "@openzeppelin/contracts/utils/introspection/ERC165.sol";
import "@openzeppelin/contracts/utils/introspection/IERC165.sol";
import "@openzeppelin/contracts/utils/Context.sol";
import "@openzeppelin/contracts/token/ERC721/IERC721.sol";
import "@openzeppelin/contracts/token/ERC721/IERC721Receiver.sol";
import "@openzeppelin/contracts/token/ERC721/extensions/IERC721Metadata.sol";
import "@openzeppelin/contracts/utils/Address.sol";
abstract contract ERC721Min is Context, ERC165, IERC721, IERC721Metadata {
using Address for address;
// Token name
string private _name;
// Token symbol
string private _symbol;
// Mapping from token ID to owner address
address[] internal _owners;
// Mapping from token ID to approved address
mapping(uint256 => address) private _tokenApprovals;
// Mapping from owner to operator approvals
mapping(address => mapping(address => bool)) private _operatorApprovals;
/**
* @dev Initializes the contract by setting a `name` and a `symbol` to the token collection.
*/
constructor(string memory name_, string memory symbol_) {
_name = name_;
_symbol = symbol_;
}
/**
* @dev See {IERC165-supportsInterface}.
*/
function supportsInterface(bytes4 interfaceId)
public
view
virtual
override(ERC165, IERC165)
returns (bool)
{
return
interfaceId == type(IERC721).interfaceId ||
interfaceId == type(IERC721Metadata).interfaceId ||
super.supportsInterface(interfaceId);
}
/**
* @dev See {IERC721-balanceOf}.
*/
function balanceOf(address owner)
public
view
virtual
override
returns (uint256)
{
require(
owner != address(0),
"ERC721: balance query for the zero address"
);
uint256 count = 0;
uint256 length = _owners.length;
for (uint256 i = 0; i < length; ++i) {
if (owner == _owners[i]) {
++count;
}
}
delete length;
return count;
}
function getOwnerCount() external view returns(uint256) {
return _owners.length;
}
/**
* @dev See {IERC721-ownerOf}.
*/
function ownerOf(uint256 tokenId)
public
view
virtual
override
returns (address)
{
address owner = _owners[tokenId];
require(
owner != address(0),
"ERC721: owner query for nonexistent token"
);
return owner;
}
/**
* @dev See {IERC721Metadata-name}.
*/
function name() public view virtual override returns (string memory) {
return _name;
}
/**
* @dev See {IERC721Metadata-symbol}.
*/
function symbol() public view virtual override returns (string memory) {
return _symbol;
}
/**
* @dev See {IERC721-approve}.
*/
function approve(address to, uint256 tokenId) public virtual override {
address owner = ERC721Min.ownerOf(tokenId);
require(to != owner, "ERC721: approval to current owner");
require(
_msgSender() == owner || isApprovedForAll(owner, _msgSender()),
"ERC721: approve caller is not owner nor approved for all"
);
_approve(to, tokenId);
}
/**
* @dev See {IERC721-getApproved}.
*/
function getApproved(uint256 tokenId)
public
view
virtual
override
returns (address)
{
require(
_exists(tokenId),
"ERC721: approved query for nonexistent token"
);
return _tokenApprovals[tokenId];
}
/**
* @dev See {IERC721-setApprovalForAll}.
*/
function setApprovalForAll(address operator, bool approved)
public
virtual
override
{
require(operator != _msgSender(), "ERC721: approve to caller");
_operatorApprovals[_msgSender()][operator] = approved;
emit ApprovalForAll(_msgSender(), operator, approved);
}
/**
* @dev See {IERC721-isApprovedForAll}.
*/
function isApprovedForAll(address owner, address operator)
public
view
virtual
override
returns (bool)
{
return _operatorApprovals[owner][operator];
}
/**
* @dev See {IERC721-transferFrom}.
*/
function transferFrom(
address from,
address to,
uint256 tokenId
) public virtual override {
//solhint-disable-next-line max-line-length
require(
_isApprovedOrOwner(_msgSender(), tokenId),
"ERC721: transfer caller is not owner nor approved"
);
_transfer(from, to, tokenId);
}
/**
* @dev See {IERC721-safeTransferFrom}.
*/
function safeTransferFrom(
address from,
address to,
uint256 tokenId
) public virtual override {
safeTransferFrom(from, to, tokenId, "");
}
/**
* @dev See {IERC721-safeTransferFrom}.
*/
function safeTransferFrom(
address from,
address to,
uint256 tokenId,
bytes memory _data
) public virtual override {
require(
_isApprovedOrOwner(_msgSender(), tokenId),
"ERC721: transfer caller is not owner nor approved"
);
_safeTransfer(from, to, tokenId, _data);
}
function batchTransferFrom(
address _from,
address _to,
uint256[] memory _tokenIds
) public virtual {
for (uint256 i = 0; i < _tokenIds.length; i++) {
transferFrom(_from, _to, _tokenIds[i]);
}
}
function batchSafeTransferFrom(
address _from,
address _to,
uint256[] memory _tokenIds,
bytes memory data_
) public virtual {
for (uint256 i = 0; i < _tokenIds.length; i++) {
safeTransferFrom(_from, _to, _tokenIds[i], data_);
}
}
/**
* @dev Safely transfers `tokenId` token from `from` to `to`, checking first that contract recipients
* are aware of the ERC721 protocol to prevent tokens from being forever locked.
*
* `_data` is additional data, it has no specified format and it is sent in call to `to`.
*
* This internal function is equivalent to {safeTransferFrom}, and can be used to e.g.
* implement alternative mechanisms to perform token transfer, such as signature-based.
*
* Requirements:
*
* - `from` cannot be the zero address.
* - `to` cannot be the zero address.
* - `tokenId` token must exist and be owned by `from`.
* - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer.
*
* Emits a {Transfer} event.
*/
function _safeTransfer(
address from,
address to,
uint256 tokenId,
bytes memory _data
) internal virtual {
_transfer(from, to, tokenId);
require(
_checkOnERC721Received(from, to, tokenId, _data),
"ERC721: transfer to non ERC721Receiver implementer"
);
}
/**
* @dev Returns whether `tokenId` exists.
*
* Tokens can be managed by their owner or approved accounts via {approve} or {setApprovalForAll}.
*
* Tokens start existing when they are minted (`_mint`),
* and stop existing when they are burned (`_burn`).
*/
function _exists(uint256 tokenId) internal view virtual returns (bool) {
return tokenId < _owners.length && _owners[tokenId] != address(0);
}
/**
* @dev Returns whether `spender` is allowed to manage `tokenId`.
*
* Requirements:
*
* - `tokenId` must exist.
*/
function _isApprovedOrOwner(address spender, uint256 tokenId)
internal
view
virtual
returns (bool)
{
require(
_exists(tokenId),
"ERC721: operator query for nonexistent token"
);
address owner = ERC721Min.ownerOf(tokenId);
return (spender == owner ||
getApproved(tokenId) == spender ||
isApprovedForAll(owner, spender));
}
/**
* @dev Safely mints `tokenId` and transfers it to `to`.
*
* Requirements:
*
* - `tokenId` must not exist.
* - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer.
*
* Emits a {Transfer} event.
*/
function _safeMint(address to, uint256 tokenId) internal virtual {
_safeMint(to, tokenId, "");
}
/**
* @dev Same as {xref-ERC721-_safeMint-address-uint256-}[`_safeMint`], with an additional `data` parameter which is
* forwarded in {IERC721Receiver-onERC721Received} to contract recipients.
*/
function _safeMint(
address to,
uint256 tokenId,
bytes memory _data
) internal virtual {
_mint(to, tokenId);
require(
_checkOnERC721Received(address(0), to, tokenId, _data),
"ERC721: transfer to non ERC721Receiver implementer"
);
}
/**
* @dev Mints `tokenId` and transfers it to `to`.
*
* WARNING: Usage of this method is discouraged, use {_safeMint} whenever possible
*
* Requirements:
*
* - `tokenId` must not exist.
* - `to` cannot be the zero address.
*
* Emits a {Transfer} event.
*/
function _mint(address to, uint256 tokenId) internal virtual {
require(to != address(0), "MINT_TO_ZERO");
require(!_exists(tokenId), "TOKEN_MINTED");
_owners.push(to);
emit Transfer(address(0), to, tokenId);
}
function _mintMin() internal virtual {
_owners.push(_msgSender());
emit Transfer(address(0), _msgSender(), _owners.length - 1);
}
// check to != address(0) in calling function
function _mintMin2(address to) internal virtual {
_owners.push(to);
emit Transfer(address(0), to, _owners.length - 1);
}
/**
* @dev Destroys `tokenId`.
* The approval is cleared when the token is burned.
*
* Requirements:
*
* - `tokenId` must exist.
*
* Emits a {Transfer} event.
*/
function _burn(uint256 tokenId) internal virtual {
address owner = ERC721Min.ownerOf(tokenId);
_beforeTokenTransfer(owner, address(0), tokenId);
// Clear approvals
_approve(address(0), tokenId);
_owners[tokenId] = address(0);
emit Transfer(owner, address(0), tokenId);
}
/**
* @dev Transfers `tokenId` from `from` to `to`.
* As opposed to {transferFrom}, this imposes no restrictions on msg.sender.
*
* Requirements:
*
* - `to` cannot be the zero address.
* - `tokenId` token must be owned by `from`.
*
* Emits a {Transfer} event.
*/
function _transfer(
address from,
address to,
uint256 tokenId
) internal virtual {
require(
ERC721Min.ownerOf(tokenId) == from,
"ERC721: transfer of token that is not own"
);
require(to != address(0), "ERC721: transfer to the zero address");
_beforeTokenTransfer(from, to, tokenId);
// Clear approvals from the previous owner
_approve(address(0), tokenId);
_owners[tokenId] = to;
emit Transfer(from, to, tokenId);
}
/**
* @dev Approve `to` to operate on `tokenId`
*
* Emits a {Approval} event.
*/
function _approve(address to, uint256 tokenId) internal virtual {
_tokenApprovals[tokenId] = to;
emit Approval(ERC721Min.ownerOf(tokenId), to, tokenId);
}
/**
* @dev Internal function to invoke {IERC721Receiver-onERC721Received} on a target address.
* The call is not executed if the target address is not a contract.
*
* @param from address representing the previous owner of the given token ID
* @param to target address that will receive the tokens
* @param tokenId uint256 ID of the token to be transferred
* @param _data bytes optional data to send along with the call
* @return bool whether the call correctly returned the expected magic value
*/
function _checkOnERC721Received(
address from,
address to,
uint256 tokenId,
bytes memory _data
) private returns (bool) {
if (to.isContract()) {
try
IERC721Receiver(to).onERC721Received(
_msgSender(),
from,
tokenId,
_data
)
returns (bytes4 retval) {
return retval == IERC721Receiver.onERC721Received.selector;
} catch (bytes memory reason) {
if (reason.length == 0) {
revert(
"ERC721: transfer to non ERC721Receiver implementer"
);
} else {
assembly {
revert(add(32, reason), mload(reason))
}
}
}
} else {
return true;
}
}
/**
* @dev Hook that is called before any token transfer. This includes minting
* and burning.
*
* Calling conditions:
*
* - When `from` and `to` are both non-zero, ``from``'s `tokenId` will be
* transferred to `to`.
* - When `from` is zero, `tokenId` will be minted for `to`.
* - When `to` is zero, ``from``'s `tokenId` will be burned.
* - `from` and `to` are never both zero.
*
* To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks].
*/
function _beforeTokenTransfer(
address from,
address to,
uint256 tokenId
) internal virtual {}
mapping(uint256 => bool) _isStaked;
address internal stakingContract;
function _setStakingContract(address _stakingContract) internal virtual {
stakingContract = _stakingContract;
}
modifier onlyStakingContract() {
require(
_msgSender() == stakingContract,
"ONLY_STAKING_CONTRACT"
);
_;
}
function isStaked(uint256 tokenId) external view returns(bool) {
return _isStaked[tokenId];
}
function stake(address user, uint256 tokenId) external onlyStakingContract {
require(ownerOf(tokenId) == user, "NOT_OWNER");
require(!_isStaked[tokenId], "ALREADY_STAKED");
_isStaked[tokenId] = !_isStaked[tokenId];
}
/* should only be called by contract owner */
function _unstake(uint256 tokenId) internal virtual {
_isStaked[tokenId] = false;
}
function unstake(address user, uint256 tokenId) external onlyStakingContract {
require(ownerOf(tokenId) == user, "NOT_OWNER");
_isStaked[tokenId] = false;
}
function tokenOfOwnerByIndex(address account, uint256 index) public view returns (uint256) {
uint256 foundCount;
for (uint256 i; i < _owners.length; ++i) {
if (_owners[i] == account) {
if (foundCount == index) return i;
foundCount++;
}
}
require(foundCount > 0, "NONE_FOUND");
revert("OUT_OF_INDEX");
}
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (utils/Context.sol)
pragma solidity ^0.8.0;
/**
* @dev Provides information about the current execution context, including the
* sender of the transaction and its data. While these are generally available
* via msg.sender and msg.data, they should not be accessed in such a direct
* manner, since when dealing with meta-transactions the account sending and
* paying for execution may not be the actual sender (as far as an application
* is concerned).
*
* This contract is only required for intermediate, library-like contracts.
*/
abstract contract Context {
function _msgSender() internal view virtual returns (address) {
return msg.sender;
}
function _msgData() internal view virtual returns (bytes calldata) {
return msg.data;
}
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v4.5.0) (token/ERC20/IERC20.sol)
pragma solidity ^0.8.0;
/**
* @dev Interface of the ERC20 standard as defined in the EIP.
*/
interface IERC20 {
/**
* @dev Returns the amount of tokens in existence.
*/
function totalSupply() external view returns (uint256);
/**
* @dev Returns the amount of tokens owned by `account`.
*/
function balanceOf(address account) external view returns (uint256);
/**
* @dev Moves `amount` tokens from the caller's account to `to`.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/
function transfer(address to, uint256 amount) external returns (bool);
/**
* @dev Returns the remaining number of tokens that `spender` will be
* allowed to spend on behalf of `owner` through {transferFrom}. This is
* zero by default.
*
* This value changes when {approve} or {transferFrom} are called.
*/
function allowance(address owner, address spender) external view returns (uint256);
/**
* @dev Sets `amount` as the allowance of `spender` over the caller's tokens.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* IMPORTANT: 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
*
* Emits an {Approval} event.
*/
function approve(address spender, uint256 amount) external returns (bool);
/**
* @dev Moves `amount` tokens from `from` to `to` using the
* allowance mechanism. `amount` is then deducted from the caller's
* allowance.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/
function transferFrom(
address from,
address to,
uint256 amount
) external returns (bool);
/**
* @dev Emitted when `value` tokens are moved from one account (`from`) to
* another (`to`).
*
* Note that `value` may be zero.
*/
event Transfer(address indexed from, address indexed to, uint256 value);
/**
* @dev Emitted when the allowance of a `spender` for an `owner` is set by
* a call to {approve}. `value` is the new allowance.
*/
event Approval(address indexed owner, address indexed spender, uint256 value);
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v4.5.0) (utils/Address.sol)
pragma solidity ^0.8.1;
/**
* @dev Collection of functions related to the address type
*/
library Address {
/**
* @dev Returns true if `account` is a contract.
*
* [IMPORTANT]
* ====
* It is unsafe to assume that an address for which this function returns
* false is an externally-owned account (EOA) and not a contract.
*
* Among others, `isContract` will return false for the following
* types of addresses:
*
* - an externally-owned account
* - a contract in construction
* - an address where a contract will be created
* - an address where a contract lived, but was destroyed
* ====
*
* [IMPORTANT]
* ====
* You shouldn't rely on `isContract` to protect against flash loan attacks!
*
* Preventing calls from contracts is highly discouraged. It breaks composability, breaks support for smart wallets
* like Gnosis Safe, and does not provide security since it can be circumvented by calling from a contract
* constructor.
* ====
*/
function isContract(address account) internal view returns (bool) {
// This method relies on extcodesize/address.code.length, which returns 0
// for contracts in construction, since the code is only stored at the end
// of the constructor execution.
return account.code.length > 0;
}
/**
* @dev Replacement for Solidity's `transfer`: sends `amount` wei to
* `recipient`, forwarding all available gas and reverting on errors.
*
* https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost
* of certain opcodes, possibly making contracts go over the 2300 gas limit
* imposed by `transfer`, making them unable to receive funds via
* `transfer`. {sendValue} removes this limitation.
*
* https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more].
*
* IMPORTANT: because control is transferred to `recipient`, care must be
* taken to not create reentrancy vulnerabilities. Consider using
* {ReentrancyGuard} or the
* https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern].
*/
function sendValue(address payable recipient, uint256 amount) internal {
require(address(this).balance >= amount, "Address: insufficient balance");
(bool success, ) = recipient.call{value: amount}("");
require(success, "Address: unable to send value, recipient may have reverted");
}
/**
* @dev Performs a Solidity function call using a low level `call`. A
* plain `call` is an unsafe replacement for a function call: use this
* function instead.
*
* If `target` reverts with a revert reason, it is bubbled up by this
* function (like regular Solidity function calls).
*
* Returns the raw returned data. To convert to the expected return value,
* use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`].
*
* 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");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with
* `errorMessage` as a fallback revert reason when `target` reverts.
*
* _Available since v3.1._
*/
function functionCall(
address target,
bytes memory data,
string memory errorMessage
) internal returns (bytes memory) {
return functionCallWithValue(target, data, 0, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but also transferring `value` wei to `target`.
*
* Requirements:
*
* - the calling contract must have an ETH balance of at least `value`.
* - the called Solidity function must be `payable`.
*
* _Available since v3.1._
*/
function functionCallWithValue(
address target,
bytes memory data,
uint256 value
) internal returns (bytes memory) {
return functionCallWithValue(target, data, value, "Address: low-level call with value failed");
}
/**
* @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but
* with `errorMessage` as a fallback revert reason when `target` reverts.
*
* _Available since v3.1._
*/
function functionCallWithValue(
address target,
bytes memory data,
uint256 value,
string memory errorMessage
) internal returns (bytes memory) {
require(address(this).balance >= value, "Address: insufficient balance for call");
require(isContract(target), "Address: call to non-contract");
(bool success, bytes memory returndata) = target.call{value: value}(data);
return verifyCallResult(success, returndata, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but performing a static call.
*
* _Available since v3.3._
*/
function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) {
return functionStaticCall(target, data, "Address: low-level static call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`],
* but performing a static call.
*
* _Available since v3.3._
*/
function functionStaticCall(
address target,
bytes memory data,
string memory errorMessage
) internal view returns (bytes memory) {
require(isContract(target), "Address: static call to non-contract");
(bool success, bytes memory returndata) = target.staticcall(data);
return verifyCallResult(success, returndata, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but performing a delegate call.
*
* _Available since v3.4._
*/
function functionDelegateCall(address target, bytes memory data) internal returns (bytes memory) {
return functionDelegateCall(target, data, "Address: low-level delegate call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`],
* but performing a delegate call.
*
* _Available since v3.4._
*/
function functionDelegateCall(
address target,
bytes memory data,
string memory errorMessage
) internal returns (bytes memory) {
require(isContract(target), "Address: delegate call to non-contract");
(bool success, bytes memory returndata) = target.delegatecall(data);
return verifyCallResult(success, returndata, errorMessage);
}
/**
* @dev Tool to verifies that a low level call was successful, and revert if it wasn't, either by bubbling the
* revert reason using the provided one.
*
* _Available since v4.3._
*/
function verifyCallResult(
bool success,
bytes memory returndata,
string memory errorMessage
) internal pure returns (bytes memory) {
if (success) {
return returndata;
} else {
// Look for revert reason and bubble it up if present
if (returndata.length > 0) {
// The easiest way to bubble the revert reason is using memory via assembly
assembly {
let returndata_size := mload(returndata)
revert(add(32, returndata), returndata_size)
}
} else {
revert(errorMessage);
}
}
}
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (utils/introspection/ERC165.sol)
pragma solidity ^0.8.0;
import "./IERC165.sol";
/**
* @dev Implementation of the {IERC165} interface.
*
* Contracts that want to implement ERC165 should inherit from this contract and override {supportsInterface} to check
* for the additional interface id that will be supported. For example:
*
* ```solidity
* function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) {
* return interfaceId == type(MyInterface).interfaceId || super.supportsInterface(interfaceId);
* }
* ```
*
* Alternatively, {ERC165Storage} provides an easier to use but more expensive implementation.
*/
abstract contract ERC165 is IERC165 {
/**
* @dev See {IERC165-supportsInterface}.
*/
function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) {
return interfaceId == type(IERC165).interfaceId;
}
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (utils/introspection/IERC165.sol)
pragma solidity ^0.8.0;
/**
* @dev Interface of the ERC165 standard, as defined in the
* https://eips.ethereum.org/EIPS/eip-165[EIP].
*
* Implementers can declare support of contract interfaces, which can then be
* queried by others ({ERC165Checker}).
*
* For an implementation, see {ERC165}.
*/
interface IERC165 {
/**
* @dev Returns true if this contract implements the interface defined by
* `interfaceId`. See the corresponding
* https://eips.ethereum.org/EIPS/eip-165#how-interfaces-are-identified[EIP section]
* to learn more about how these ids are created.
*
* This function call must use less than 30 000 gas.
*/
function supportsInterface(bytes4 interfaceId) external view returns (bool);
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (token/ERC721/IERC721.sol)
pragma solidity ^0.8.0;
import "../../utils/introspection/IERC165.sol";
/**
* @dev Required interface of an ERC721 compliant contract.
*/
interface IERC721 is IERC165 {
/**
* @dev Emitted when `tokenId` token is transferred from `from` to `to`.
*/
event Transfer(address indexed from, address indexed to, uint256 indexed tokenId);
/**
* @dev Emitted when `owner` enables `approved` to manage the `tokenId` token.
*/
event Approval(address indexed owner, address indexed approved, uint256 indexed tokenId);
/**
* @dev Emitted when `owner` enables or disables (`approved`) `operator` to manage all of its assets.
*/
event ApprovalForAll(address indexed owner, address indexed operator, bool approved);
/**
* @dev Returns the number of tokens in ``owner``'s account.
*/
function balanceOf(address owner) external view returns (uint256 balance);
/**
* @dev Returns the owner of the `tokenId` token.
*
* Requirements:
*
* - `tokenId` must exist.
*/
function ownerOf(uint256 tokenId) external view returns (address owner);
/**
* @dev Safely transfers `tokenId` token from `from` to `to`, checking first that contract recipients
* are aware of the ERC721 protocol to prevent tokens from being forever locked.
*
* Requirements:
*
* - `from` cannot be the zero address.
* - `to` cannot be the zero address.
* - `tokenId` token must exist and be owned by `from`.
* - If the caller is not `from`, it must be have been allowed to move this token by either {approve} or {setApprovalForAll}.
* - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer.
*
* Emits a {Transfer} event.
*/
function safeTransferFrom(
address from,
address to,
uint256 tokenId
) external;
/**
* @dev Transfers `tokenId` token from `from` to `to`.
*
* WARNING: Usage of this method is discouraged, use {safeTransferFrom} whenever possible.
*
* Requirements:
*
* - `from` cannot be the zero address.
* - `to` cannot be the zero address.
* - `tokenId` token must be owned by `from`.
* - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}.
*
* Emits a {Transfer} event.
*/
function transferFrom(
address from,
address to,
uint256 tokenId
) external;
/**
* @dev Gives permission to `to` to transfer `tokenId` token to another account.
* The approval is cleared when the token is transferred.
*
* Only a single account can be approved at a time, so approving the zero address clears previous approvals.
*
* Requirements:
*
* - The caller must own the token or be an approved operator.
* - `tokenId` must exist.
*
* Emits an {Approval} event.
*/
function approve(address to, uint256 tokenId) external;
/**
* @dev Returns the account approved for `tokenId` token.
*
* Requirements:
*
* - `tokenId` must exist.
*/
function getApproved(uint256 tokenId) external view returns (address operator);
/**
* @dev Approve or remove `operator` as an operator for the caller.
* Operators can call {transferFrom} or {safeTransferFrom} for any token owned by the caller.
*
* Requirements:
*
* - The `operator` cannot be the caller.
*
* Emits an {ApprovalForAll} event.
*/
function setApprovalForAll(address operator, bool _approved) external;
/**
* @dev Returns if the `operator` is allowed to manage all of the assets of `owner`.
*
* See {setApprovalForAll}
*/
function isApprovedForAll(address owner, address operator) external view returns (bool);
/**
* @dev Safely transfers `tokenId` token from `from` to `to`.
*
* Requirements:
*
* - `from` cannot be the zero address.
* - `to` cannot be the zero address.
* - `tokenId` token must exist and be owned by `from`.
* - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}.
* - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer.
*
* Emits a {Transfer} event.
*/
function safeTransferFrom(
address from,
address to,
uint256 tokenId,
bytes calldata data
) external;
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (token/ERC721/IERC721Receiver.sol)
pragma solidity ^0.8.0;
/**
* @title ERC721 token receiver interface
* @dev Interface for any contract that wants to support safeTransfers
* from ERC721 asset contracts.
*/
interface IERC721Receiver {
/**
* @dev Whenever an {IERC721} `tokenId` token is transferred to this contract via {IERC721-safeTransferFrom}
* by `operator` from `from`, this function is called.
*
* It must return its Solidity selector to confirm the token transfer.
* If any other value is returned or the interface is not implemented by the recipient, the transfer will be reverted.
*
* The selector can be obtained in Solidity with `IERC721.onERC721Received.selector`.
*/
function onERC721Received(
address operator,
address from,
uint256 tokenId,
bytes calldata data
) external returns (bytes4);
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (token/ERC721/extensions/IERC721Metadata.sol)
pragma solidity ^0.8.0;
import "../IERC721.sol";
/**
* @title ERC-721 Non-Fungible Token Standard, optional metadata extension
* @dev See https://eips.ethereum.org/EIPS/eip-721
*/
interface IERC721Metadata is IERC721 {
/**
* @dev Returns the token collection name.
*/
function name() external view returns (string memory);
/**
* @dev Returns the token collection symbol.
*/
function symbol() external view returns (string memory);
/**
* @dev Returns the Uniform Resource Identifier (URI) for `tokenId` token.
*/
function tokenURI(uint256 tokenId) external view returns (string memory);
}
|
- NFT Types -
|
function addNftType(uint16 _maxMint, uint16 _maxPerMint, uint256 _price,
uint16 _maxPerAddress, bool _saleActive, string calldata _uri) external onlyOwner
{
nftTypeCount++;
NftTypes[nftTypeCount].maxMint = _maxMint+1;
NftTypes[nftTypeCount].maxMintForOne = _maxMint;
NftTypes[nftTypeCount].maxMintForThree = _maxMint-2;
NftTypes[nftTypeCount].maxPerMint = _maxPerMint;
NftTypes[nftTypeCount].price = _price;
NftTypes[nftTypeCount].priceForThree = _price * 3;
NftTypes[nftTypeCount].maxPerAddress = _maxPerAddress > 0 ? _maxPerAddress : NftTypes[nftTypeCount].maxPerAddress;
NftTypes[nftTypeCount].maxPerAddressForThree = _maxPerAddress > 1 ? _maxPerAddress - 2 : NftTypes[nftTypeCount].maxPerAddress;
NftTypes[nftTypeCount].saleActive = _saleActive;
NftTypes[nftTypeCount].uri = _uri;
}
| 451,923 |
// SPDX-License-Identifier: MIT
pragma solidity 0.8.10;
import "./IEIP20.sol";
// Implementation of eip20 standard.
// https://eips.ethereum.org/EIPS/eip-20.
contract EIP20 is IEIP20 {
mapping(address => uint256) private _balanceOf;
mapping(address => mapping(address => uint256)) private _allowances;
string private _name;
string private _symbol;
uint256 private _totalSupply;
// constructor will set name and symbol of the token.
// It will take 2 params : string name_ for name of the token
// string symbol_ for symbol of the token.
constructor(string memory name_, string memory symbol_) {
_name = name_;
_symbol = symbol_;
}
// Returns the name of the token - e.g. "MyToken".
// OPTIONAL - This method can be used to improve usability,
// but interfaces and other contracts MUST NOT expect these values to be present.
function name() public view virtual override returns (string memory) {
return _name;
}
// Returns the symbol of the token. E.g. “HIX”.
// OPTIONAL - This method can be used to improve usability,
// but interfaces and other contracts MUST NOT expect these values to be present.
function symbol() public view virtual override returns (string memory) {
return _symbol;
}
// Returns the number of decimals the token uses - e.g. 8,
// means to divide the token amount by 100000000 to get its user representation.
// OPTIONAL - This method can be used to improve usability,
// but interfaces and other contracts MUST NOT expect these values to be present.
function decimals() public view virtual override returns (uint8) {
return 18;
}
// Returns the total token supply.
function totalSupply() public view virtual override returns (uint256) {
return _totalSupply;
}
// Returns the account balance of another account with address _owner.
function balanceOf(address _owner) public view virtual override returns (uint256) {
return _balanceOf[_owner];
}
// Transfers _value amount of tokens to address _to, and MUST fire the Transfer event.
// The function SHOULD throw if the message caller’s account balance does not have enough tokens to spend.
// Note Transfers of 0 values MUST be treated as normal transfers and fire the Transfer event.
function transfer(address _to, uint256 _value) public virtual override returns (bool) {
return _safeTransfer(msg.sender, _to, _value);
}
// Transfers _value amount of tokens from address _from to address _to, and MUST fire the Transfer event.
// The transferFrom method is used for a withdraw workflow,
// allowing contracts to transfer tokens on your behalf.
// This can be used for example to allow a contract to transfer tokens on your behalf and/or to charge fees in sub-currencies.
// The function SHOULD throw unless the _from account has deliberately authorized the sender of the message via some mechanism.
// Note Transfers of 0 values MUST be treated as normal transfers and fire the Transfer event.
function transferFrom(address _from, address _to, uint256 _value) public virtual override returns (bool) {
return _safeTransfer(_from, _to, _value);
}
// Allows _spender to withdraw from your account multiple times, up to the _value amount.
// If this function is called again it overwrites the current allowance with _value.
// NOTE: To prevent attack vectors like the one described https://docs.google.com/document/d/1YLPtQxZu1UAvO9cZ1O2RPXBbT0mooh4DYKjA_jp-RLM/ and discussed https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729,
// clients SHOULD make sure to create user interfaces in such a way that they set the allowance first to 0 before setting it to another value for the same spender.
// THOUGH The contract itself shouldn’t enforce it, to allow backwards compatibility with contracts deployed before.
function approve(address _spender, uint256 _value) public virtual override returns (bool) {
return _safeApprove(_spender, _value);
}
// Returns the amount which _spender is still allowed to withdraw from _owner.
function allowance(address _owner, address _spender) public view virtual override returns (uint256) {
return _allowances[_owner][_spender];
}
// Will transfer token balance from _from to _to in safe way with few check.
function _safeTransfer(address _from, address _to, uint256 _value) internal virtual returns (bool) {
// check if address not zero address.
require(_from != address(0), "Transfer from zero address");
require(_to != address(0), "Transfer to zero address");
// check if _from has enough balance.
require(balanceOf(_from) >= _value, "Not enough balance for transaction");
// if msg.sender not _from then check if msg.sender has enough allowance.
if (_from != msg.sender) {
require(allowance(_from, msg.sender) >= _value, "Not enough allowance for this transaction");
_allowances[_from][msg.sender] -= _value;
}
// set balance of both after transaction.
_balanceOf[_from] -= _value;
_balanceOf[_to] += _value;
// emit the transaction into blockchain.
emit Transfer(_from, _to, _value);
return true;
}
// Will give certain `amount` of allowance to _spender in safe way with few check.
function _safeApprove(address _spender, uint256 _value) internal virtual returns (bool) {
// check if _spender not zero address.
require(_spender != address(0), "Approval tp zero address");
// set allowance after transaction.
_allowances[msg.sender][_spender] = _value;
// emit transaction into blockchain.
emit Approval(msg.sender, _spender, _value);
return true;
}
// Minting new token, asign amount to the address and increase totalSupply.
function _mint(address _to, uint256 _value) internal virtual {
// check if _to not an zero address.
require(_to != address(0), "Token minting to zero address");
// set balance after transaction.
_balanceOf[_to] += _value;
// set totalSupply after transaction.
_totalSupply += _value;
// emit transaction into blockchain.
emit Transfer(address(0), _to, _value);
}
// Burning certain amount of token from _owner and decrease totalSupply.
function _burn(address _owner, uint256 _value) internal virtual {
// check if _owner is not an zero address.
require(_owner != address(0), "Burning from zero address");
// check if _owner has enough balance for burning.
require(balanceOf(_owner) >= _value, "Not enough balance for transaction");
// check if _owner is msg.sender and if not check if msg.sender has enough allowance
if (_owner != msg.sender) {
require(allowance(_owner, msg.sender) >= _value, "Not enough allowance for transaction");
// decrease allowance.
_allowances[_owner][msg.sender] -= _value;
}
// decrease balance after transaction.
_balanceOf[_owner] -= _value;
// decrease totalSupply after transaction
_totalSupply -= _value;
// emit transaction into blockchain.
emit Transfer(_owner, address(0), _value);
}
}
|
Transfers _value amount of tokens from address _from to address _to, and MUST fire the Transfer event. The transferFrom method is used for a withdraw workflow, allowing contracts to transfer tokens on your behalf. This can be used for example to allow a contract to transfer tokens on your behalf and/or to charge fees in sub-currencies. The function SHOULD throw unless the _from account has deliberately authorized the sender of the message via some mechanism. Note Transfers of 0 values MUST be treated as normal transfers and fire the Transfer event.
|
function transferFrom(address _from, address _to, uint256 _value) public virtual override returns (bool) {
return _safeTransfer(_from, _to, _value);
}
| 6,388,419 |
pragma solidity 0.6.8;
pragma experimental ABIEncoderV2;
contract Initializable {
/**
* @dev Indicates that the contract has been initialized.
*/
bool private initialized;
/**
* @dev Indicates that the contract is in the process of being initialized.
*/
bool private initializing;
/**
* @dev Modifier to use in the initializer function of a contract.
*/
modifier initializer() {
require(initializing || isConstructor() || !initialized, "Contract instance has already been initialized");
bool isTopLevelCall = !initializing;
if (isTopLevelCall) {
initializing = true;
initialized = true;
}
_;
if (isTopLevelCall) {
initializing = false;
}
}
/// @dev Returns true if and only if the function is running in the constructor
function isConstructor() private view returns (bool) {
// extcodesize checks the size of the code stored in an address, and
// address returns the current address. Since the code is still not
// deployed when running a constructor, any checks on its code size will
// yield zero, making it an effective way to detect if a contract is
// under construction or not.
address self = address(this);
uint256 cs;
assembly { cs := extcodesize(self) }
return cs == 0;
}
// Reserved storage space to allow for layout changes in the future.
uint256[50] private ______gap;
}
library Math {
/**
* @dev Returns the largest of two numbers.
*/
function max(uint256 a, uint256 b) internal pure returns (uint256) {
return a >= b ? a : b;
}
/**
* @dev Returns the smallest of two numbers.
*/
function min(uint256 a, uint256 b) internal pure returns (uint256) {
return a < b ? a : b;
}
/**
* @dev Returns the average of two numbers. The result is rounded towards
* zero.
*/
function average(uint256 a, uint256 b) internal pure returns (uint256) {
// (a + b) / 2 can overflow, so we distribute
return (a / 2) + (b / 2) + ((a % 2 + b % 2) / 2);
}
}
library SafeMath {
/**
* @dev Returns the addition of two unsigned integers, reverting on
* overflow.
*
* Counterpart to Solidity's `+` operator.
*
* Requirements:
* - Addition cannot overflow.
*/
function add(uint256 a, uint256 b) internal pure returns (uint256) {
uint256 c = a + b;
require(c >= a, "SafeMath: addition overflow");
return c;
}
/**
* @dev Returns the subtraction of two unsigned integers, reverting on
* overflow (when the result is negative).
*
* Counterpart to Solidity's `-` operator.
*
* Requirements:
* - Subtraction cannot overflow.
*/
function sub(uint256 a, uint256 b) internal pure returns (uint256) {
return sub(a, b, "SafeMath: subtraction overflow");
}
/**
* @dev Returns the subtraction of two unsigned integers, reverting with custom message on
* overflow (when the result is negative).
*
* Counterpart to Solidity's `-` operator.
*
* Requirements:
* - Subtraction cannot overflow.
*/
function sub(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
require(b <= a, errorMessage);
uint256 c = a - b;
return c;
}
/**
* @dev Returns the multiplication of two unsigned integers, reverting on
* overflow.
*
* Counterpart to Solidity's `*` operator.
*
* Requirements:
* - Multiplication cannot overflow.
*/
function mul(uint256 a, uint256 b) internal pure returns (uint256) {
// Gas optimization: this is cheaper than requiring 'a' not being zero, but the
// benefit is lost if 'b' is also tested.
// See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522
if (a == 0) {
return 0;
}
uint256 c = a * b;
require(c / a == b, "SafeMath: multiplication overflow");
return c;
}
/**
* @dev Returns the integer division of two unsigned integers. Reverts on
* division by zero. The result is rounded towards zero.
*
* Counterpart to Solidity's `/` operator. Note: this function uses a
* `revert` opcode (which leaves remaining gas untouched) while Solidity
* uses an invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
* - The divisor cannot be zero.
*/
function div(uint256 a, uint256 b) internal pure returns (uint256) {
return div(a, b, "SafeMath: division by zero");
}
/**
* @dev Returns the integer division of two unsigned integers. Reverts with custom message on
* division by zero. The result is rounded towards zero.
*
* Counterpart to Solidity's `/` operator. Note: this function uses a
* `revert` opcode (which leaves remaining gas untouched) while Solidity
* uses an invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
* - The divisor cannot be zero.
*/
function div(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
// Solidity only automatically asserts when dividing by 0
require(b > 0, errorMessage);
uint256 c = a / b;
// assert(a == b * c + a % b); // There is no case in which this doesn't hold
return c;
}
/**
* @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo),
* Reverts when dividing by zero.
*
* Counterpart to Solidity's `%` operator. This function uses a `revert`
* opcode (which leaves remaining gas untouched) while Solidity uses an
* invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
* - The divisor cannot be zero.
*/
function mod(uint256 a, uint256 b) internal pure returns (uint256) {
return mod(a, b, "SafeMath: modulo by zero");
}
/**
* @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo),
* Reverts with custom message when dividing by zero.
*
* Counterpart to Solidity's `%` operator. This function uses a `revert`
* opcode (which leaves remaining gas untouched) while Solidity uses an
* invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
* - The divisor cannot be zero.
*/
function mod(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
require(b != 0, errorMessage);
return a % b;
}
}
interface IERC20 {
/**
* @dev Returns the amount of tokens in existence.
*/
function totalSupply() external view returns (uint256);
/**
* @dev Returns the amount of tokens owned by `account`.
*/
function balanceOf(address account) external view returns (uint256);
/**
* @dev Moves `amount` tokens from the caller's account to `recipient`.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/
function transfer(address recipient, uint256 amount) external returns (bool);
/**
* @dev Returns the remaining number of tokens that `spender` will be
* allowed to spend on behalf of `owner` through {transferFrom}. This is
* zero by default.
*
* This value changes when {approve} or {transferFrom} are called.
*/
function allowance(address owner, address spender) external view returns (uint256);
/**
* @dev Sets `amount` as the allowance of `spender` over the caller's tokens.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* IMPORTANT: 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
*
* Emits an {Approval} event.
*/
function approve(address spender, uint256 amount) external returns (bool);
/**
* @dev Moves `amount` tokens from `sender` to `recipient` using the
* allowance mechanism. `amount` is then deducted from the caller's
* allowance.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/
function transferFrom(address sender, address recipient, uint256 amount) external returns (bool);
/**
* @dev Emitted when `value` tokens are moved from one account (`from`) to
* another (`to`).
*
* Note that `value` may be zero.
*/
event Transfer(address indexed from, address indexed to, uint256 value);
/**
* @dev Emitted when the allowance of a `spender` for an `owner` is set by
* a call to {approve}. `value` is the new allowance.
*/
event Approval(address indexed owner, address indexed spender, uint256 value);
}
library Address {
/**
* @dev Returns true if `account` is a contract.
*
* [IMPORTANT]
* ====
* It is unsafe to assume that an address for which this function returns
* false is an externally-owned account (EOA) and not a contract.
*
* Among others, `isContract` will return false for the following
* types of addresses:
*
* - an externally-owned account
* - a contract in construction
* - an address where a contract will be created
* - an address where a contract lived, but was destroyed
* ====
*/
function isContract(address account) internal view returns (bool) {
// According to EIP-1052, 0x0 is the value returned for not-yet created accounts
// and 0xc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470 is returned
// for accounts without code, i.e. `keccak256('')`
bytes32 codehash;
bytes32 accountHash = 0xc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470;
// solhint-disable-next-line no-inline-assembly
assembly { codehash := extcodehash(account) }
return (codehash != accountHash && codehash != 0x0);
}
/**
* @dev Replacement for Solidity's `transfer`: sends `amount` wei to
* `recipient`, forwarding all available gas and reverting on errors.
*
* https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost
* of certain opcodes, possibly making contracts go over the 2300 gas limit
* imposed by `transfer`, making them unable to receive funds via
* `transfer`. {sendValue} removes this limitation.
*
* https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more].
*
* IMPORTANT: because control is transferred to `recipient`, care must be
* taken to not create reentrancy vulnerabilities. Consider using
* {ReentrancyGuard} or the
* https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern].
*/
function sendValue(address payable recipient, uint256 amount) internal {
require(address(this).balance >= amount, "Address: insufficient balance");
// solhint-disable-next-line avoid-low-level-calls, avoid-call-value
(bool success, ) = recipient.call{ value: amount }("");
require(success, "Address: unable to send value, recipient may have reverted");
}
}
library Accountant {
using SafeMath for uint256;
uint public constant interestDecimals = 1e18;
uint public constant blocksPerDay = 5760;
uint public constant blocksPerYear = (blocksPerDay * 365);
struct PaymentAllocation {
uint interestPayment;
uint principalPayment;
uint additionalBalancePayment;
}
function calculateInterestAndPrincipalAccrued(CreditLine cl, uint blockNumber) public view returns(uint, uint) {
uint totalPayment = calculateAnnuityPayment(cl.balance(), cl.interestApr(), cl.termInDays(), cl.paymentPeriodInDays());
uint interestAccrued = calculateInterestAccrued(cl, blockNumber);
uint principalAccrued = calculatePrincipalAccrued(cl, totalPayment, interestAccrued, blockNumber);
return (interestAccrued, principalAccrued);
}
function calculatePrincipalAccrued(CreditLine cl, uint periodPayment, uint interestAccrued, uint blockNumber) public view returns(uint) {
uint blocksPerPaymentPeriod = blocksPerDay * cl.paymentPeriodInDays();
// Math.min guards against overflow. See comment in the calculateInterestAccrued for further explanation.
uint lastUpdatedBlock = Math.min(blockNumber, cl.lastUpdatedBlock());
uint numBlocksElapsed = blockNumber.sub(lastUpdatedBlock);
int128 fractionOfPeriod = FPMath.divi(int256(numBlocksElapsed), int256(blocksPerPaymentPeriod));
uint periodPaymentFraction = uint(FPMath.muli(fractionOfPeriod, int256(periodPayment)));
return periodPaymentFraction.sub(interestAccrued);
}
function calculateInterestAccrued(CreditLine cl, uint blockNumber) public view returns(uint) {
// We use Math.min here to prevent integer overflow (ie. go negative) when calculating
// numBlocksElapsed. Typically this shouldn't be possible, because
// the lastUpdatedBlock couldn't be *after* the current blockNumber. However, when assessing
// we allow this function to be called with a past block number, which raises the possibility
// of overflow.
// This use of min should not generate incorrect interest calculations, since
// this functions purpose is just to normalize balances, and will be called any time
// a balance affecting action takes place (eg. drawdown, repayment, assessment)
uint lastUpdatedBlock = Math.min(blockNumber, cl.lastUpdatedBlock());
uint numBlocksElapsed = blockNumber.sub(lastUpdatedBlock);
uint totalInterestPerYear = (cl.balance().mul(cl.interestApr())).div(interestDecimals);
return totalInterestPerYear.mul(numBlocksElapsed).div(blocksPerYear);
}
function calculateAnnuityPayment(uint balance, uint interestApr, uint termInDays, uint paymentPeriodInDays) public pure returns(uint) {
/*
This is the standard amortization formula for an annuity payment amount.
See: https://en.wikipedia.org/wiki/Amortization_calculator
The specific formula we're interested in can be expressed as:
`balance * (periodRate / (1 - (1 / ((1 + periodRate) ^ periods_per_term))))`
FPMath is a library designed for emulating floating point numbers in solidity.
At a high level, we are just turning all our uint256 numbers into floating points and
doing the formula above, and then turning it back into an int64 at the end.
*/
// Components used in the formula
uint periodsPerTerm = termInDays / paymentPeriodInDays;
int128 one = FPMath.fromInt(int256(1));
int128 annualRate = FPMath.divi(int256(interestApr), int256(interestDecimals));
int128 dailyRate = FPMath.div(annualRate, FPMath.fromInt(int256(365)));
int128 periodRate = FPMath.mul(dailyRate, FPMath.fromInt(int256(paymentPeriodInDays)));
int128 termRate = FPMath.pow(FPMath.add(one, periodRate), periodsPerTerm);
int128 denominator = FPMath.sub(one, FPMath.div(one, termRate));
if (denominator == 0) {
return balance / periodsPerTerm;
}
int128 paymentFractionFP = FPMath.div(periodRate, denominator);
uint paymentFraction = uint(FPMath.muli(paymentFractionFP, int256(1e18)));
return (balance * paymentFraction) / 1e18;
}
function allocatePayment(uint paymentAmount, uint balance, uint interestOwed, uint principalOwed) public pure returns(PaymentAllocation memory) {
uint paymentRemaining = paymentAmount;
uint interestPayment = Math.min(interestOwed, paymentRemaining);
paymentRemaining = paymentRemaining.sub(interestPayment);
uint principalPayment = Math.min(principalOwed, paymentRemaining);
paymentRemaining = paymentRemaining.sub(principalPayment);
uint balanceRemaining = balance.sub(principalPayment);
uint additionalBalancePayment = Math.min(paymentRemaining, balanceRemaining);
return PaymentAllocation({
interestPayment: interestPayment,
principalPayment: principalPayment,
additionalBalancePayment: additionalBalancePayment
});
}
}
ibrary FPMath {
/**
@dev
* Minimum value signed 64.64-bit fixed point number may have.
*/
int128 private constant MIN_64x64 = -0x80000000000000000000000000000000;
/**
@dev
* Maximum value signed 64.64-bit fixed point number may have.
*/
int128 private constant MAX_64x64 = 0x7FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF;
/**
* Convert signed 256-bit integer number into signed 64.64-bit fixed point
* number. Revert on overflow.
*
* @param x signed 256-bit integer number
* @return signed 64.64-bit fixed point number
*/
function fromInt (int256 x) internal pure returns (int128) {
require (x >= -0x8000000000000000 && x <= 0x7FFFFFFFFFFFFFFF);
return int128 (x << 64);
}
/**
* Convert signed 64.64 fixed point number into signed 64-bit integer number
* rounding down.
*
* @param x signed 64.64-bit fixed point number
* @return signed 64-bit integer number
*/
function toInt (int128 x) internal pure returns (int64) {
return int64 (x >> 64);
}
/**
* Convert unsigned 256-bit integer number into signed 64.64-bit fixed point
* number. Revert on overflow.
*
* @param x unsigned 256-bit integer number
* @return signed 64.64-bit fixed point number
*/
function fromUInt (uint256 x) internal pure returns (int128) {
require (x <= 0x7FFFFFFFFFFFFFFF);
return int128 (x << 64);
}
/**
* Convert signed 64.64 fixed point number into unsigned 64-bit integer
* number rounding down. Revert on underflow.
*
* @param x signed 64.64-bit fixed point number
* @return unsigned 64-bit integer number
*/
function toUInt (int128 x) internal pure returns (uint64) {
require (x >= 0);
return uint64 (x >> 64);
}
/**
* Convert signed 128.128 fixed point number into signed 64.64-bit fixed point
* number rounding down. Revert on overflow.
*
* @param x signed 128.128-bin fixed point number
* @return signed 64.64-bit fixed point number
*/
function from128x128 (int256 x) internal pure returns (int128) {
int256 result = x >> 64;
require (result >= MIN_64x64 && result <= MAX_64x64);
return int128 (result);
}
/**
* Convert signed 64.64 fixed point number into signed 128.128 fixed point
* number.
*
* @param x signed 64.64-bit fixed point number
* @return signed 128.128 fixed point number
*/
function to128x128 (int128 x) internal pure returns (int256) {
return int256 (x) << 64;
}
/**
* Calculate x + y. Revert on overflow.
*
* @param x signed 64.64-bit fixed point number
* @param y signed 64.64-bit fixed point number
* @return signed 64.64-bit fixed point number
*/
function add (int128 x, int128 y) internal pure returns (int128) {
int256 result = int256(x) + y;
require (result >= MIN_64x64 && result <= MAX_64x64);
return int128 (result);
}
/**
* Calculate x - y. Revert on overflow.
*
* @param x signed 64.64-bit fixed point number
* @param y signed 64.64-bit fixed point number
* @return signed 64.64-bit fixed point number
*/
function sub (int128 x, int128 y) internal pure returns (int128) {
int256 result = int256(x) - y;
require (result >= MIN_64x64 && result <= MAX_64x64);
return int128 (result);
}
/**
* Calculate x * y rounding down. Revert on overflow.
*
* @param x signed 64.64-bit fixed point number
* @param y signed 64.64-bit fixed point number
* @return signed 64.64-bit fixed point number
*/
function mul (int128 x, int128 y) internal pure returns (int128) {
int256 result = int256(x) * y >> 64;
require (result >= MIN_64x64 && result <= MAX_64x64);
return int128 (result);
}
/**
* Calculate x * y rounding towards zero, where x is signed 64.64 fixed point
* number and y is signed 256-bit integer number. Revert on overflow.
*
* @param x signed 64.64 fixed point number
* @param y signed 256-bit integer number
* @return signed 256-bit integer number
*/
function muli (int128 x, int256 y) internal pure returns (int256) {
if (x == MIN_64x64) {
require (y >= -0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF &&
y <= 0x1000000000000000000000000000000000000000000000000);
return -y << 63;
} else {
bool negativeResult = false;
if (x < 0) {
x = -x;
negativeResult = true;
}
if (y < 0) {
y = -y; // We rely on overflow behavior here
negativeResult = !negativeResult;
}
uint256 absoluteResult = mulu (x, uint256 (y));
if (negativeResult) {
require (absoluteResult <=
0x8000000000000000000000000000000000000000000000000000000000000000);
return -int256 (absoluteResult); // We rely on overflow behavior here
} else {
require (absoluteResult <=
0x7FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF);
return int256 (absoluteResult);
}
}
}
/**
* Calculate x * y rounding down, where x is signed 64.64 fixed point number
* and y is unsigned 256-bit integer number. Revert on overflow.
*
* @param x signed 64.64 fixed point number
* @param y unsigned 256-bit integer number
* @return unsigned 256-bit integer number
*/
function mulu (int128 x, uint256 y) internal pure returns (uint256) {
if (y == 0) return 0;
require (x >= 0);
uint256 lo = (uint256 (x) * (y & 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF)) >> 64;
uint256 hi = uint256 (x) * (y >> 128);
require (hi <= 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF);
hi <<= 64;
require (hi <=
0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF - lo);
return hi + lo;
}
/**
* Calculate x / y rounding towards zero. Revert on overflow or when y is
* zero.
*
* @param x signed 64.64-bit fixed point number
* @param y signed 64.64-bit fixed point number
* @return signed 64.64-bit fixed point number
*/
function div (int128 x, int128 y) internal pure returns (int128) {
require (y != 0);
int256 result = (int256 (x) << 64) / y;
require (result >= MIN_64x64 && result <= MAX_64x64);
return int128 (result);
}
/**
* Calculate x / y rounding towards zero, where x and y are signed 256-bit
* integer numbers. Revert on overflow or when y is zero.
*
* @param x signed 256-bit integer number
* @param y signed 256-bit integer number
* @return signed 64.64-bit fixed point number
*/
function divi (int256 x, int256 y) internal pure returns (int128) {
require (y != 0);
bool negativeResult = false;
if (x < 0) {
x = -x; // We rely on overflow behavior here
negativeResult = true;
}
if (y < 0) {
y = -y; // We rely on overflow behavior here
negativeResult = !negativeResult;
}
uint128 absoluteResult = divuu (uint256 (x), uint256 (y));
if (negativeResult) {
require (absoluteResult <= 0x80000000000000000000000000000000);
return -int128 (absoluteResult); // We rely on overflow behavior here
} else {
require (absoluteResult <= 0x7FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF);
return int128 (absoluteResult); // We rely on overflow behavior here
}
}
/**
* Calculate x / y rounding towards zero, where x and y are unsigned 256-bit
* integer numbers. Revert on overflow or when y is zero.
*
* @param x unsigned 256-bit integer number
* @param y unsigned 256-bit integer number
* @return signed 64.64-bit fixed point number
*/
function divu (uint256 x, uint256 y) internal pure returns (int128) {
require (y != 0);
uint128 result = divuu (x, y);
require (result <= uint128 (MAX_64x64));
return int128 (result);
}
/**
* Calculate -x. Revert on overflow.
*
* @param x signed 64.64-bit fixed point number
* @return signed 64.64-bit fixed point number
*/
function neg (int128 x) internal pure returns (int128) {
require (x != MIN_64x64);
return -x;
}
/**
* Calculate |x|. Revert on overflow.
*
* @param x signed 64.64-bit fixed point number
* @return signed 64.64-bit fixed point number
*/
function abs (int128 x) internal pure returns (int128) {
require (x != MIN_64x64);
return x < 0 ? -x : x;
}
/**
* Calculate 1 / x rounding towards zero. Revert on overflow or when x is
* zero.
*
* @param x signed 64.64-bit fixed point number
* @return signed 64.64-bit fixed point number
*/
function inv (int128 x) internal pure returns (int128) {
require (x != 0);
int256 result = int256 (0x100000000000000000000000000000000) / x;
require (result >= MIN_64x64 && result <= MAX_64x64);
return int128 (result);
}
/**
* Calculate arithmetics average of x and y, i.e. (x + y) / 2 rounding down.
*
* @param x signed 64.64-bit fixed point number
* @param y signed 64.64-bit fixed point number
* @return signed 64.64-bit fixed point number
*/
function avg (int128 x, int128 y) internal pure returns (int128) {
return int128 ((int256 (x) + int256 (y)) >> 1);
}
/**
* Calculate geometric average of x and y, i.e. sqrt (x * y) rounding down.
* Revert on overflow or in case x * y is negative.
*
* @param x signed 64.64-bit fixed point number
* @param y signed 64.64-bit fixed point number
* @return signed 64.64-bit fixed point number
*/
function gavg (int128 x, int128 y) internal pure returns (int128) {
int256 m = int256 (x) * int256 (y);
require (m >= 0);
require (m <
0x4000000000000000000000000000000000000000000000000000000000000000);
return int128 (sqrtu (uint256 (m), uint256 (x) + uint256 (y) >> 1));
}
/**
* Calculate x^y assuming 0^0 is 1, where x is signed 64.64 fixed point number
* and y is unsigned 256-bit integer number. Revert on overflow.
*
* @param x signed 64.64-bit fixed point number
* @param y uint256 value
* @return signed 64.64-bit fixed point number
*/
function pow (int128 x, uint256 y) internal pure returns (int128) {
uint256 absoluteResult;
bool negativeResult = false;
if (x >= 0) {
absoluteResult = powu (uint256 (x) << 63, y);
} else {
// We rely on overflow behavior here
absoluteResult = powu (uint256 (uint128 (-x)) << 63, y);
negativeResult = y & 1 > 0;
}
absoluteResult >>= 63;
if (negativeResult) {
require (absoluteResult <= 0x80000000000000000000000000000000);
return -int128 (absoluteResult); // We rely on overflow behavior here
} else {
require (absoluteResult <= 0x7FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF);
return int128 (absoluteResult); // We rely on overflow behavior here
}
}
/**
* Calculate sqrt (x) rounding down. Revert if x < 0.
*
* @param x signed 64.64-bit fixed point number
* @return signed 64.64-bit fixed point number
*/
function sqrt (int128 x) internal pure returns (int128) {
require (x >= 0);
return int128 (sqrtu (uint256 (x) << 64, 0x10000000000000000));
}
/**
* Calculate binary logarithm of x. Revert if x <= 0.
*
* @param x signed 64.64-bit fixed point number
* @return signed 64.64-bit fixed point number
*/
function log_2 (int128 x) internal pure returns (int128) {
require (x > 0);
int256 msb = 0;
int256 xc = x;
if (xc >= 0x10000000000000000) { xc >>= 64; msb += 64; }
if (xc >= 0x100000000) { xc >>= 32; msb += 32; }
if (xc >= 0x10000) { xc >>= 16; msb += 16; }
if (xc >= 0x100) { xc >>= 8; msb += 8; }
if (xc >= 0x10) { xc >>= 4; msb += 4; }
if (xc >= 0x4) { xc >>= 2; msb += 2; }
if (xc >= 0x2) msb += 1; // No need to shift xc anymore
int256 result = msb - 64 << 64;
uint256 ux = uint256 (x) << 127 - msb;
for (int256 bit = 0x8000000000000000; bit > 0; bit >>= 1) {
ux *= ux;
uint256 b = ux >> 255;
ux >>= 127 + b;
result += bit * int256 (b);
}
return int128 (result);
}
/**
* Calculate natural logarithm of x. Revert if x <= 0.
*
* @param x signed 64.64-bit fixed point number
* @return signed 64.64-bit fixed point number
*/
function ln (int128 x) internal pure returns (int128) {
require (x > 0);
return int128 (
uint256 (log_2 (x)) * 0xB17217F7D1CF79ABC9E3B39803F2F6AF >> 128);
}
/**
* Calculate binary exponent of x. Revert on overflow.
*
* @param x signed 64.64-bit fixed point number
* @return signed 64.64-bit fixed point number
*/
function exp_2 (int128 x) internal pure returns (int128) {
require (x < 0x400000000000000000); // Overflow
if (x < -0x400000000000000000) return 0; // Underflow
uint256 result = 0x80000000000000000000000000000000;
if (x & 0x8000000000000000 > 0)
result = result * 0x16A09E667F3BCC908B2FB1366EA957D3E >> 128;
if (x & 0x4000000000000000 > 0)
result = result * 0x1306FE0A31B7152DE8D5A46305C85EDEC >> 128;
if (x & 0x2000000000000000 > 0)
result = result * 0x1172B83C7D517ADCDF7C8C50EB14A791F >> 128;
if (x & 0x1000000000000000 > 0)
result = result * 0x10B5586CF9890F6298B92B71842A98363 >> 128;
if (x & 0x800000000000000 > 0)
result = result * 0x1059B0D31585743AE7C548EB68CA417FD >> 128;
if (x & 0x400000000000000 > 0)
result = result * 0x102C9A3E778060EE6F7CACA4F7A29BDE8 >> 128;
if (x & 0x200000000000000 > 0)
result = result * 0x10163DA9FB33356D84A66AE336DCDFA3F >> 128;
if (x & 0x100000000000000 > 0)
result = result * 0x100B1AFA5ABCBED6129AB13EC11DC9543 >> 128;
if (x & 0x80000000000000 > 0)
result = result * 0x10058C86DA1C09EA1FF19D294CF2F679B >> 128;
if (x & 0x40000000000000 > 0)
result = result * 0x1002C605E2E8CEC506D21BFC89A23A00F >> 128;
if (x & 0x20000000000000 > 0)
result = result * 0x100162F3904051FA128BCA9C55C31E5DF >> 128;
if (x & 0x10000000000000 > 0)
result = result * 0x1000B175EFFDC76BA38E31671CA939725 >> 128;
if (x & 0x8000000000000 > 0)
result = result * 0x100058BA01FB9F96D6CACD4B180917C3D >> 128;
if (x & 0x4000000000000 > 0)
result = result * 0x10002C5CC37DA9491D0985C348C68E7B3 >> 128;
if (x & 0x2000000000000 > 0)
result = result * 0x1000162E525EE054754457D5995292026 >> 128;
if (x & 0x1000000000000 > 0)
result = result * 0x10000B17255775C040618BF4A4ADE83FC >> 128;
if (x & 0x800000000000 > 0)
result = result * 0x1000058B91B5BC9AE2EED81E9B7D4CFAB >> 128;
if (x & 0x400000000000 > 0)
result = result * 0x100002C5C89D5EC6CA4D7C8ACC017B7C9 >> 128;
if (x & 0x200000000000 > 0)
result = result * 0x10000162E43F4F831060E02D839A9D16D >> 128;
if (x & 0x100000000000 > 0)
result = result * 0x100000B1721BCFC99D9F890EA06911763 >> 128;
if (x & 0x80000000000 > 0)
result = result * 0x10000058B90CF1E6D97F9CA14DBCC1628 >> 128;
if (x & 0x40000000000 > 0)
result = result * 0x1000002C5C863B73F016468F6BAC5CA2B >> 128;
if (x & 0x20000000000 > 0)
result = result * 0x100000162E430E5A18F6119E3C02282A5 >> 128;
if (x & 0x10000000000 > 0)
result = result * 0x1000000B1721835514B86E6D96EFD1BFE >> 128;
if (x & 0x8000000000 > 0)
result = result * 0x100000058B90C0B48C6BE5DF846C5B2EF >> 128;
if (x & 0x4000000000 > 0)
result = result * 0x10000002C5C8601CC6B9E94213C72737A >> 128;
if (x & 0x2000000000 > 0)
result = result * 0x1000000162E42FFF037DF38AA2B219F06 >> 128;
if (x & 0x1000000000 > 0)
result = result * 0x10000000B17217FBA9C739AA5819F44F9 >> 128;
if (x & 0x800000000 > 0)
result = result * 0x1000000058B90BFCDEE5ACD3C1CEDC823 >> 128;
if (x & 0x400000000 > 0)
result = result * 0x100000002C5C85FE31F35A6A30DA1BE50 >> 128;
if (x & 0x200000000 > 0)
result = result * 0x10000000162E42FF0999CE3541B9FFFCF >> 128;
if (x & 0x100000000 > 0)
result = result * 0x100000000B17217F80F4EF5AADDA45554 >> 128;
if (x & 0x80000000 > 0)
result = result * 0x10000000058B90BFBF8479BD5A81B51AD >> 128;
if (x & 0x40000000 > 0)
result = result * 0x1000000002C5C85FDF84BD62AE30A74CC >> 128;
if (x & 0x20000000 > 0)
result = result * 0x100000000162E42FEFB2FED257559BDAA >> 128;
if (x & 0x10000000 > 0)
result = result * 0x1000000000B17217F7D5A7716BBA4A9AE >> 128;
if (x & 0x8000000 > 0)
result = result * 0x100000000058B90BFBE9DDBAC5E109CCE >> 128;
if (x & 0x4000000 > 0)
result = result * 0x10000000002C5C85FDF4B15DE6F17EB0D >> 128;
if (x & 0x2000000 > 0)
result = result * 0x1000000000162E42FEFA494F1478FDE05 >> 128;
if (x & 0x1000000 > 0)
result = result * 0x10000000000B17217F7D20CF927C8E94C >> 128;
if (x & 0x800000 > 0)
result = result * 0x1000000000058B90BFBE8F71CB4E4B33D >> 128;
if (x & 0x400000 > 0)
result = result * 0x100000000002C5C85FDF477B662B26945 >> 128;
if (x & 0x200000 > 0)
result = result * 0x10000000000162E42FEFA3AE53369388C >> 128;
if (x & 0x100000 > 0)
result = result * 0x100000000000B17217F7D1D351A389D40 >> 128;
if (x & 0x80000 > 0)
result = result * 0x10000000000058B90BFBE8E8B2D3D4EDE >> 128;
if (x & 0x40000 > 0)
result = result * 0x1000000000002C5C85FDF4741BEA6E77E >> 128;
if (x & 0x20000 > 0)
result = result * 0x100000000000162E42FEFA39FE95583C2 >> 128;
if (x & 0x10000 > 0)
result = result * 0x1000000000000B17217F7D1CFB72B45E1 >> 128;
if (x & 0x8000 > 0)
result = result * 0x100000000000058B90BFBE8E7CC35C3F0 >> 128;
if (x & 0x4000 > 0)
result = result * 0x10000000000002C5C85FDF473E242EA38 >> 128;
if (x & 0x2000 > 0)
result = result * 0x1000000000000162E42FEFA39F02B772C >> 128;
if (x & 0x1000 > 0)
result = result * 0x10000000000000B17217F7D1CF7D83C1A >> 128;
if (x & 0x800 > 0)
result = result * 0x1000000000000058B90BFBE8E7BDCBE2E >> 128;
if (x & 0x400 > 0)
result = result * 0x100000000000002C5C85FDF473DEA871F >> 128;
if (x & 0x200 > 0)
result = result * 0x10000000000000162E42FEFA39EF44D91 >> 128;
if (x & 0x100 > 0)
result = result * 0x100000000000000B17217F7D1CF79E949 >> 128;
if (x & 0x80 > 0)
result = result * 0x10000000000000058B90BFBE8E7BCE544 >> 128;
if (x & 0x40 > 0)
result = result * 0x1000000000000002C5C85FDF473DE6ECA >> 128;
if (x & 0x20 > 0)
result = result * 0x100000000000000162E42FEFA39EF366F >> 128;
if (x & 0x10 > 0)
result = result * 0x1000000000000000B17217F7D1CF79AFA >> 128;
if (x & 0x8 > 0)
result = result * 0x100000000000000058B90BFBE8E7BCD6D >> 128;
if (x & 0x4 > 0)
result = result * 0x10000000000000002C5C85FDF473DE6B2 >> 128;
if (x & 0x2 > 0)
result = result * 0x1000000000000000162E42FEFA39EF358 >> 128;
if (x & 0x1 > 0)
result = result * 0x10000000000000000B17217F7D1CF79AB >> 128;
result >>= 63 - (x >> 64);
require (result <= uint256 (MAX_64x64));
return int128 (result);
}
/**
* Calculate natural exponent of x. Revert on overflow.
*
* @param x signed 64.64-bit fixed point number
* @return signed 64.64-bit fixed point number
*/
function exp (int128 x) internal pure returns (int128) {
require (x < 0x400000000000000000); // Overflow
if (x < -0x400000000000000000) return 0; // Underflow
return exp_2 (
int128 (int256 (x) * 0x171547652B82FE1777D0FFDA0D23A7D12 >> 128));
}
/**
* Calculate x / y rounding towards zero, where x and y are unsigned 256-bit
* integer numbers. Revert on overflow or when y is zero.
*
* @param x unsigned 256-bit integer number
* @param y unsigned 256-bit integer number
* @return unsigned 64.64-bit fixed point number
*/
function divuu (uint256 x, uint256 y) private pure returns (uint128) {
require (y != 0);
uint256 result;
if (x <= 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF)
result = (x << 64) / y;
else {
uint256 msb = 192;
uint256 xc = x >> 192;
if (xc >= 0x100000000) { xc >>= 32; msb += 32; }
if (xc >= 0x10000) { xc >>= 16; msb += 16; }
if (xc >= 0x100) { xc >>= 8; msb += 8; }
if (xc >= 0x10) { xc >>= 4; msb += 4; }
if (xc >= 0x4) { xc >>= 2; msb += 2; }
if (xc >= 0x2) msb += 1; // No need to shift xc anymore
result = (x << 255 - msb) / ((y - 1 >> msb - 191) + 1);
require (result <= 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF);
uint256 hi = result * (y >> 128);
uint256 lo = result * (y & 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF);
uint256 xh = x >> 192;
uint256 xl = x << 64;
if (xl < lo) xh -= 1;
xl -= lo; // We rely on overflow behavior here
lo = hi << 128;
if (xl < lo) xh -= 1;
xl -= lo; // We rely on overflow behavior here
assert (xh == hi >> 128);
result += xl / y;
}
require (result <= 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF);
return uint128 (result);
}
/**
* Calculate x^y assuming 0^0 is 1, where x is unsigned 129.127 fixed point
* number and y is unsigned 256-bit integer number. Revert on overflow.
*
* @param x unsigned 129.127-bit fixed point number
* @param y uint256 value
* @return unsigned 129.127-bit fixed point number
*/
function powu (uint256 x, uint256 y) private pure returns (uint256) {
if (y == 0) return 0x80000000000000000000000000000000;
else if (x == 0) return 0;
else {
int256 msb = 0;
uint256 xc = x;
if (xc >= 0x100000000000000000000000000000000) { xc >>= 128; msb += 128; }
if (xc >= 0x10000000000000000) { xc >>= 64; msb += 64; }
if (xc >= 0x100000000) { xc >>= 32; msb += 32; }
if (xc >= 0x10000) { xc >>= 16; msb += 16; }
if (xc >= 0x100) { xc >>= 8; msb += 8; }
if (xc >= 0x10) { xc >>= 4; msb += 4; }
if (xc >= 0x4) { xc >>= 2; msb += 2; }
if (xc >= 0x2) msb += 1; // No need to shift xc anymore
int256 xe = msb - 127;
if (xe > 0) x >>= xe;
else x <<= -xe;
uint256 result = 0x80000000000000000000000000000000;
int256 re = 0;
while (y > 0) {
if (y & 1 > 0) {
result = result * x;
y -= 1;
re += xe;
if (result >=
0x8000000000000000000000000000000000000000000000000000000000000000) {
result >>= 128;
re += 1;
} else result >>= 127;
if (re < -127) return 0; // Underflow
require (re < 128); // Overflow
} else {
x = x * x;
y >>= 1;
xe <<= 1;
if (x >=
0x8000000000000000000000000000000000000000000000000000000000000000) {
x >>= 128;
xe += 1;
} else x >>= 127;
if (xe < -127) return 0; // Underflow
require (xe < 128); // Overflow
}
}
if (re > 0) result <<= re;
else if (re < 0) result >>= -re;
return result;
}
}
/**
* Calculate sqrt (x) rounding down, where x is unsigned 256-bit integer
* number.
*
* @param x unsigned 256-bit integer number
* @return unsigned 128-bit integer number
*/
function sqrtu (uint256 x, uint256 r) private pure returns (uint128) {
if (x == 0) return 0;
else {
require (r > 0);
while (true) {
uint256 rr = x / r;
if (r == rr || r + 1 == rr) return uint128 (r);
else if (r == rr + 1) return uint128 (rr);
r = r + rr + 1 >> 1;
}
}
}
}
contract ContextUpgradeSafe is Initializable {
// Empty internal constructor, to prevent people from mistakenly deploying
// an instance of this contract, which should be used via inheritance.
function __Context_init() internal initializer {
__Context_init_unchained();
}
function __Context_init_unchained() internal initializer {
}
function _msgSender() internal view virtual returns (address payable) {
return msg.sender;
}
function _msgData() internal view virtual returns (bytes memory) {
this; // silence state mutability warning without generating bytecode - see https://github.com/ethereum/solidity/issues/2691
return msg.data;
}
uint256[50] private __gap;
}
contract OwnableUpgradeSafe is Initializable, ContextUpgradeSafe {
address private _owner;
event OwnershipTransferred(address indexed previousOwner, address indexed newOwner);
/**
* @dev Initializes the contract setting the deployer as the initial owner.
*/
function __Ownable_init() internal initializer {
__Context_init_unchained();
__Ownable_init_unchained();
}
function __Ownable_init_unchained() internal initializer {
address msgSender = _msgSender();
_owner = msgSender;
emit OwnershipTransferred(address(0), msgSender);
}
/**
* @dev Returns the address of the current owner.
*/
function owner() public view returns (address) {
return _owner;
}
/**
* @dev Throws if called by any account other than the owner.
*/
modifier onlyOwner() {
require(_owner == _msgSender(), "Ownable: caller is not the owner");
_;
}
/**
* @dev Leaves the contract without owner. It will not be possible to call
* `onlyOwner` functions anymore. Can only be called by the current owner.
*
* NOTE: Renouncing ownership will leave the contract without an owner,
* thereby removing any functionality that is only available to the owner.
*/
function renounceOwnership() public virtual onlyOwner {
emit OwnershipTransferred(_owner, address(0));
_owner = address(0);
}
/**
* @dev Transfers ownership of the contract to a new account (`newOwner`).
* Can only be called by the current owner.
*/
function transferOwnership(address newOwner) public virtual onlyOwner {
require(newOwner != address(0), "Ownable: new owner is the zero address");
emit OwnershipTransferred(_owner, newOwner);
_owner = newOwner;
}
uint256[49] private __gap;
}
contract ERC20UpgradeSafe is Initializable, ContextUpgradeSafe, IERC20 {
using SafeMath for uint256;
using Address for address;
mapping (address => uint256) private _balances;
mapping (address => mapping (address => uint256)) private _allowances;
uint256 private _totalSupply;
string private _name;
string private _symbol;
uint8 private _decimals;
/**
* @dev Sets the values for {name} and {symbol}, initializes {decimals} with
* a default value of 18.
*
* To select a different value for {decimals}, use {_setupDecimals}.
*
* All three of these values are immutable: they can only be set once during
* construction.
*/
function __ERC20_init(string memory name, string memory symbol) internal initializer {
__Context_init_unchained();
__ERC20_init_unchained(name, symbol);
}
function __ERC20_init_unchained(string memory name, string memory symbol) internal initializer {
_name = name;
_symbol = symbol;
_decimals = 18;
}
/**
* @dev Returns the name of the token.
*/
function name() public view returns (string memory) {
return _name;
}
/**
* @dev Returns the symbol of the token, usually a shorter version of the
* name.
*/
function symbol() public view returns (string memory) {
return _symbol;
}
/**
* @dev Returns the number of decimals used to get its user representation.
* For example, if `decimals` equals `2`, a balance of `505` tokens should
* be displayed to a user as `5,05` (`505 / 10 ** 2`).
*
* Tokens usually opt for a value of 18, imitating the relationship between
* Ether and Wei. This is the value {ERC20} uses, unless {_setupDecimals} is
* called.
*
* NOTE: This information is only used for _display_ purposes: it in
* no way affects any of the arithmetic of the contract, including
* {IERC20-balanceOf} and {IERC20-transfer}.
*/
function decimals() public view returns (uint8) {
return _decimals;
}
/**
* @dev See {IERC20-totalSupply}.
*/
function totalSupply() public view override returns (uint256) {
return _totalSupply;
}
/**
* @dev See {IERC20-balanceOf}.
*/
function balanceOf(address account) public view override returns (uint256) {
return _balances[account];
}
/**
* @dev See {IERC20-transfer}.
*
* Requirements:
*
* - `recipient` cannot be the zero address.
* - the caller must have a balance of at least `amount`.
*/
function transfer(address recipient, uint256 amount) public virtual override returns (bool) {
_transfer(_msgSender(), recipient, amount);
return true;
}
/**
* @dev See {IERC20-allowance}.
*/
function allowance(address owner, address spender) public view virtual override returns (uint256) {
return _allowances[owner][spender];
}
/**
* @dev See {IERC20-approve}.
*
* Requirements:
*
* - `spender` cannot be the zero address.
*/
function approve(address spender, uint256 amount) public virtual override returns (bool) {
_approve(_msgSender(), spender, amount);
return true;
}
/**
* @dev See {IERC20-transferFrom}.
*
* Emits an {Approval} event indicating the updated allowance. This is not
* required by the EIP. See the note at the beginning of {ERC20};
*
* Requirements:
* - `sender` and `recipient` cannot be the zero address.
* - `sender` must have a balance of at least `amount`.
* - the caller must have allowance for ``sender``'s tokens of at least
* `amount`.
*/
function transferFrom(address sender, address recipient, uint256 amount) public virtual override returns (bool) {
_transfer(sender, recipient, amount);
_approve(sender, _msgSender(), _allowances[sender][_msgSender()].sub(amount, "ERC20: transfer amount exceeds allowance"));
return true;
}
/**
* @dev Atomically increases the allowance granted to `spender` by the caller.
*
* This is an alternative to {approve} that can be used as a mitigation for
* problems described in {IERC20-approve}.
*
* Emits an {Approval} event indicating the updated allowance.
*
* Requirements:
*
* - `spender` cannot be the zero address.
*/
function increaseAllowance(address spender, uint256 addedValue) public virtual returns (bool) {
_approve(_msgSender(), spender, _allowances[_msgSender()][spender].add(addedValue));
return true;
}
/**
* @dev Atomically decreases the allowance granted to `spender` by the caller.
*
* This is an alternative to {approve} that can be used as a mitigation for
* problems described in {IERC20-approve}.
*
* Emits an {Approval} event indicating the updated allowance.
*
* Requirements:
*
* - `spender` cannot be the zero address.
* - `spender` must have allowance for the caller of at least
* `subtractedValue`.
*/
function decreaseAllowance(address spender, uint256 subtractedValue) public virtual returns (bool) {
_approve(_msgSender(), spender, _allowances[_msgSender()][spender].sub(subtractedValue, "ERC20: decreased allowance below zero"));
return true;
}
/**
* @dev 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);
}
/** @dev Creates `amount` tokens and assigns them to `account`, increasing
* the total supply.
*
* Emits a {Transfer} event with `from` set to the zero address.
*
* Requirements
*
* - `to` cannot be the zero address.
*/
function _mint(address account, uint256 amount) internal virtual {
require(account != address(0), "ERC20: mint to the zero address");
_beforeTokenTransfer(address(0), account, amount);
_totalSupply = _totalSupply.add(amount);
_balances[account] = _balances[account].add(amount);
emit Transfer(address(0), account, amount);
}
/**
* @dev Destroys `amount` tokens from `account`, reducing the
* total supply.
*
* Emits a {Transfer} event with `to` set to the zero address.
*
* Requirements
*
* - `account` cannot be the zero address.
* - `account` must have at least `amount` tokens.
*/
function _burn(address account, uint256 amount) internal virtual {
require(account != address(0), "ERC20: burn from the zero address");
_beforeTokenTransfer(account, address(0), amount);
_balances[account] = _balances[account].sub(amount, "ERC20: burn amount exceeds balance");
_totalSupply = _totalSupply.sub(amount);
emit Transfer(account, address(0), amount);
}
/**
* @dev Sets `amount` as the allowance of `spender` over the `owner`s tokens.
*
* This is internal function is equivalent to `approve`, and can be used to
* e.g. set automatic allowances for certain subsystems, etc.
*
* Emits an {Approval} event.
*
* Requirements:
*
* - `owner` cannot be the zero address.
* - `spender` cannot be the zero address.
*/
function _approve(address owner, address spender, uint256 amount) internal virtual {
require(owner != address(0), "ERC20: approve from the zero address");
require(spender != address(0), "ERC20: approve to the zero address");
_allowances[owner][spender] = amount;
emit Approval(owner, spender, amount);
}
/**
* @dev Sets {decimals} to a value other than the default one of 18.
*
* WARNING: This function should only be called from the constructor. Most
* applications that interact with token contracts will not expect
* {decimals} to ever change, and may work incorrectly if it does.
*/
function _setupDecimals(uint8 decimals_) internal {
_decimals = decimals_;
}
/**
* @dev Hook that is called before any transfer of tokens. This includes
* minting and burning.
*
* Calling conditions:
*
* - when `from` and `to` are both non-zero, `amount` of ``from``'s tokens
* will be to transferred to `to`.
* - when `from` is zero, `amount` tokens will be minted for `to`.
* - when `to` is zero, `amount` of ``from``'s tokens will be burned.
* - `from` and `to` are never both zero.
*
* To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks].
*/
function _beforeTokenTransfer(address from, address to, uint256 amount) internal virtual { }
uint256[44] private __gap;
}
contract PausableUpgradeSafe is Initializable, ContextUpgradeSafe {
/**
* @dev Emitted when the pause is triggered by `account`.
*/
event Paused(address account);
/**
* @dev Emitted when the pause is lifted by `account`.
*/
event Unpaused(address account);
bool private _paused;
/**
* @dev Initializes the contract in unpaused state.
*/
function __Pausable_init() internal initializer {
__Context_init_unchained();
__Pausable_init_unchained();
}
function __Pausable_init_unchained() internal initializer {
_paused = false;
}
/**
* @dev Returns true if the contract is paused, and false otherwise.
*/
function paused() public view returns (bool) {
return _paused;
}
/**
* @dev Modifier to make a function callable only when the contract is not paused.
*/
modifier whenNotPaused() {
require(!_paused, "Pausable: paused");
_;
}
/**
* @dev Modifier to make a function callable only when the contract is paused.
*/
modifier whenPaused() {
require(_paused, "Pausable: not paused");
_;
}
/**
* @dev Triggers stopped state.
*/
function _pause() internal virtual whenNotPaused {
_paused = true;
emit Paused(_msgSender());
}
/**
* @dev Returns to normal state.
*/
function _unpause() internal virtual whenPaused {
_paused = false;
emit Unpaused(_msgSender());
}
uint256[49] private __gap;
}
contract CreditLine is Initializable, OwnableUpgradeSafe {
// Credit line terms
address public borrower;
uint public collateral;
uint public limit;
uint public interestApr;
uint public minCollateralPercent;
uint public paymentPeriodInDays;
uint public termInDays;
// Accounting variables
uint public balance;
uint public interestOwed;
uint public principalOwed;
uint public prepaymentBalance;
uint public collateralBalance;
uint public termEndBlock;
uint public nextDueBlock;
uint public lastUpdatedBlock;
function initialize(
address _borrower,
uint _limit,
uint _interestApr,
uint _minCollateralPercent,
uint _paymentPeriodInDays,
uint _termInDays
) public initializer {
__Ownable_init();
borrower = _borrower;
limit = _limit;
interestApr = _interestApr;
minCollateralPercent = _minCollateralPercent;
paymentPeriodInDays = _paymentPeriodInDays;
termInDays = _termInDays;
lastUpdatedBlock = block.number;
}
function setTermEndBlock(uint newTermEndBlock) external onlyOwner returns (uint) {
return termEndBlock = newTermEndBlock;
}
function setNextDueBlock(uint newNextDueBlock) external onlyOwner returns (uint) {
return nextDueBlock = newNextDueBlock;
}
function setBalance(uint newBalance) external onlyOwner returns(uint) {
return balance = newBalance;
}
function setInterestOwed(uint newInterestOwed) external onlyOwner returns (uint) {
return interestOwed = newInterestOwed;
}
function setPrincipalOwed(uint newPrincipalOwed) external onlyOwner returns (uint) {
return principalOwed = newPrincipalOwed;
}
function setPrepaymentBalance(uint newPrepaymentBalance) external onlyOwner returns (uint) {
return prepaymentBalance = newPrepaymentBalance;
}
function setCollateralBalance(uint newCollateralBalance) external onlyOwner returns (uint) {
return collateralBalance = newCollateralBalance;
}
function setLastUpdatedBlock(uint newLastUpdatedBlock) external onlyOwner returns (uint) {
return lastUpdatedBlock = newLastUpdatedBlock;
}
function setLimit(uint newAmount) external onlyOwner returns (uint) {
return limit = newAmount;
}
function authorizePool(address poolAddress) external onlyOwner {
address erc20address = Pool(poolAddress).erc20address();
// Approve the pool for an infinite amount
ERC20UpgradeSafe(erc20address).approve(poolAddress, uint(-1));
}
}
contract OwnerPausable is OwnableUpgradeSafe, PausableUpgradeSafe {
function __OwnerPausable__init() public {
__Pausable_init_unchained();
}
/**
* @dev Pauses all functions guarded by Pause
*
* See {Pausable-_pause}.
*
* Requirements:
*
* - the caller must be the owner.
*/
function pause() public onlyOwner {
_pause();
}
/**
* @dev Unpauses the contract
*
* See {Pausable-_unpause}.
*
* Requirements:
*
* - the caller must be the owner`.
*/
function unpause() public onlyOwner {
_unpause();
}
}
contract Pool is Initializable, OwnableUpgradeSafe, OwnerPausable {
using SafeMath for uint256;
uint public sharePrice;
uint mantissa;
uint public totalShares;
mapping(address => uint) public capitalProviders;
address public erc20address;
string name;
uint public totalFundsLimit = 0;
uint public transactionLimit = 0;
event DepositMade(address indexed capitalProvider, uint amount);
event WithdrawalMade(address indexed capitalProvider, uint amount);
event TransferMade(address indexed from, address indexed to, uint amount);
event InterestCollected(address indexed payer, uint amount);
event PrincipalCollected(address indexed payer, uint amount);
event LimitChanged(address indexed owner, string limitType, uint amount);
function initialize(address _erc20address, string memory _name, uint _mantissa) public initializer {
__Context_init_unchained();
__Ownable_init_unchained();
__OwnerPausable__init();
name = _name;
erc20address = _erc20address;
mantissa = _mantissa;
sharePrice = _mantissa;
// Sanity check the address
ERC20UpgradeSafe(erc20address).totalSupply();
// Unlock self for infinite amount
ERC20UpgradeSafe(erc20address).approve(address(this), uint(-1));
}
function deposit(uint amount) external payable whenNotPaused {
require(transactionWithinLimit(amount), "Amount is over the per-transaction limit.");
// Determine current shares the address has, and the amount of new shares to be added
uint currentShares = capitalProviders[msg.sender];
uint depositShares = getNumShares(amount, mantissa, sharePrice);
uint potentialNewTotalShares = totalShares.add(depositShares);
require(poolWithinLimit(potentialNewTotalShares), "Deposit would put the Pool over the total limit.");
doERC20Transfer(msg.sender, address(this), amount);
// Add the new shares to both the pool and the address
totalShares = totalShares.add(depositShares);
capitalProviders[msg.sender] = currentShares.add(depositShares);
emit DepositMade(msg.sender, amount);
}
function withdraw(uint amount) external whenNotPaused {
// Determine current shares the address has and the shares requested to withdraw
require(transactionWithinLimit(amount), "Amount is over the per-transaction limit");
uint currentShares = capitalProviders[msg.sender];
uint withdrawShares = getNumShares(amount, mantissa, sharePrice);
// Ensure the address has enough value in the pool
require(withdrawShares <= currentShares, "Amount requested is greater than what this address owns");
// Remove the new shares from both the pool and the address
totalShares = totalShares.sub(withdrawShares);
capitalProviders[msg.sender] = currentShares.sub(withdrawShares);
// Send the amount to the address
doERC20Transfer(address(this), msg.sender, amount);
emit WithdrawalMade(msg.sender, amount);
}
function collectInterestRepayment(address from, uint amount) external whenNotPaused {
doERC20Transfer(from, address(this), amount);
uint increment = amount.mul(mantissa).div(totalShares);
sharePrice = sharePrice + increment;
emit InterestCollected(from, amount);
}
function collectPrincipalRepayment(address from, uint amount) external whenNotPaused {
// Purposefully does nothing except receive money. No share price updates for principal.
doERC20Transfer(from, address(this), amount);
emit PrincipalCollected(from, amount);
}
function setTotalFundsLimit(uint amount) public onlyOwner whenNotPaused {
totalFundsLimit = amount;
emit LimitChanged(msg.sender, "totalFundsLimit", amount);
}
function setTransactionLimit(uint amount) public onlyOwner whenNotPaused {
transactionLimit = amount;
emit LimitChanged(msg.sender, "transactionLimit", amount);
}
function transferFrom(address from, address to, uint amount) public onlyOwner whenNotPaused returns (bool) {
bool result = doERC20Transfer(from, to, amount);
emit TransferMade(from, to, amount);
return result;
}
function enoughBalance(address user, uint amount) public view whenNotPaused returns(bool) {
return ERC20UpgradeSafe(erc20address).balanceOf(user) >= amount;
}
/* Internal Functions */
function poolWithinLimit(uint _totalShares) internal view returns (bool) {
return _totalShares.mul(sharePrice).div(mantissa) <= totalFundsLimit;
}
function transactionWithinLimit(uint amount) internal view returns (bool) {
return amount <= transactionLimit;
}
function getNumShares(uint amount, uint multiplier, uint price) internal pure returns (uint) {
return amount.mul(multiplier).div(price);
}
function doERC20Transfer(address from, address to, uint amount) internal returns (bool) {
ERC20UpgradeSafe erc20 = ERC20UpgradeSafe(erc20address);
uint balanceBefore = erc20.balanceOf(to);
bool success = erc20.transferFrom(from, to, amount);
// Calculate the amount that was *actually* transferred
uint balanceAfter = erc20.balanceOf(to);
require(balanceAfter >= balanceBefore, "Token Transfer Overflow Error");
return success;
}
function doERC20Withdraw(address payable to, uint amount) internal returns (bool) {
ERC20UpgradeSafe erc20 = ERC20UpgradeSafe(erc20address);
bool success = erc20.transfer(to, amount);
require(success, "Token Withdraw Failed");
return success;
}
}
contract FakeV2CreditDesk is Initializable, OwnableUpgradeSafe, OwnerPausable {
using SafeMath for uint256;
// Approximate number of blocks
uint public constant blocksPerDay = 5760;
address public poolAddress;
uint public maxUnderwriterLimit = 0;
uint public transactionLimit = 0;
struct Underwriter {
uint governanceLimit;
address[] creditLines;
}
struct Borrower {
address[] creditLines;
}
event PaymentMade(address indexed payer, address indexed creditLine, uint interestAmount, uint principalAmount, uint remainingAmount);
event PrepaymentMade(address indexed payer, address indexed creditLine, uint prepaymentAmount);
event DrawdownMade(address indexed borrower, address indexed creditLine, uint drawdownAmount);
event CreditLineCreated(address indexed borrower, address indexed creditLine);
event PoolAddressUpdated(address indexed oldAddress, address indexed newAddress);
event GovernanceUpdatedUnderwriterLimit(address indexed underwriter, uint newLimit);
event LimitChanged(address indexed owner, string limitType, uint amount);
mapping(address => Underwriter) public underwriters;
mapping(address => Borrower) private borrowers;
function initialize(address _poolAddress) public initializer {
__Ownable_init();
poolAddress = _poolAddress;
}
function someBrandNewFunction() public pure returns(uint) {
return 5;
}
function getUnderwriterCreditLines(address underwriterAddress) public view returns (address[] memory) {
return underwriters[underwriterAddress].creditLines;
}
/*
* Internal Functions
*/
}
contract TestERC20 is ERC20UpgradeSafe {
constructor(uint256 initialSupply, uint8 decimals) public {
__ERC20_init("USDC", "USDC");
_setupDecimals(decimals);
_mint(msg.sender, initialSupply);
}
}
contract TestPool is Pool {
function _getNumShares(uint amount, uint multiplier, uint price) public pure returns (uint) {
return getNumShares(amount, multiplier, price);
}
}
contract CreditDesk is Initializable, OwnableUpgradeSafe, OwnerPausable {
using SafeMath for uint256;
// Approximate number of blocks
uint public constant blocksPerDay = 5760;
address public poolAddress;
uint public maxUnderwriterLimit = 0;
uint public transactionLimit = 0;
struct Underwriter {
uint governanceLimit;
address[] creditLines;
}
struct Borrower {
address[] creditLines;
}
event PaymentMade(address indexed payer, address indexed creditLine, uint interestAmount, uint principalAmount, uint remainingAmount);
event PrepaymentMade(address indexed payer, address indexed creditLine, uint prepaymentAmount);
event DrawdownMade(address indexed borrower, address indexed creditLine, uint drawdownAmount);
event CreditLineCreated(address indexed borrower, address indexed creditLine);
event PoolAddressUpdated(address indexed oldAddress, address indexed newAddress);
event GovernanceUpdatedUnderwriterLimit(address indexed underwriter, uint newLimit);
event LimitChanged(address indexed owner, string limitType, uint amount);
mapping(address => Underwriter) public underwriters;
mapping(address => Borrower) private borrowers;
function initialize(address _poolAddress) public initializer {
__Ownable_init();
__OwnerPausable__init();
setPoolAddress(_poolAddress);
}
function setUnderwriterGovernanceLimit(address underwriterAddress, uint limit) external onlyOwner whenNotPaused {
Underwriter storage underwriter = underwriters[underwriterAddress];
require(withinMaxUnderwriterLimit(limit), "This limit is greater than the max allowed by the protocol");
underwriter.governanceLimit = limit;
emit GovernanceUpdatedUnderwriterLimit(underwriterAddress, limit);
}
function createCreditLine(
address _borrower,
uint _limit,
uint _interestApr,
uint _minCollateralPercent,
uint _paymentPeriodInDays,
uint _termInDays
) external whenNotPaused {
Underwriter storage underwriter = underwriters[msg.sender];
Borrower storage borrower = borrowers[_borrower];
require(underwriterCanCreateThisCreditLine(_limit, underwriter), "The underwriter cannot create this credit line");
CreditLine cl = new CreditLine();
cl.initialize(_borrower, _limit, _interestApr, _minCollateralPercent, _paymentPeriodInDays, _termInDays);
cl.authorizePool(poolAddress);
underwriter.creditLines.push(address(cl));
borrower.creditLines.push(address(cl));
emit CreditLineCreated(_borrower, address(cl));
}
function drawdown(uint amount, address creditLineAddress) external whenNotPaused {
CreditLine cl = CreditLine(creditLineAddress);
require(cl.borrower() == msg.sender, "You do not belong to this credit line");
// Not strictly necessary, but provides a better error message to the user
require(getPool().enoughBalance(poolAddress, amount), "Pool does not have enough balance for this drawdown");
require(withinTransactionLimit(amount), "Amount is over the per-transaction limit");
require(withinCreditLimit(amount, cl), "The borrower does not have enough credit limit for this drawdown");
if (cl.balance() == 0) {
cl.setTermEndBlock(calculateNewTermEndBlock(cl));
cl.setNextDueBlock(calculateNextDueBlock(cl));
}
(uint interestOwed, uint principalOwed) = getInterestAndPrincipalOwedAsOf(cl, block.number);
uint balance = cl.balance().add(amount);
updateCreditLineAccounting(cl, balance, interestOwed, principalOwed);
getPool().transferFrom(poolAddress, msg.sender, amount);
emit DrawdownMade(msg.sender, address(cl), amount);
}
function pay(address creditLineAddress, uint amount) external payable whenNotPaused {
CreditLine cl = CreditLine(creditLineAddress);
require(withinTransactionLimit(amount), "Amount is over the per-transaction limit");
// Not strictly necessary, but provides a faster/better error message to the user
require(getPool().enoughBalance(msg.sender, amount), "You have insufficent balance for this payment");
(uint paymentRemaining, uint interestPayment, uint principalPayment) = handlePayment(cl, amount, block.number, true);
if (paymentRemaining > 0) {
getPool().transferFrom(msg.sender, creditLineAddress, paymentRemaining);
cl.setCollateralBalance(cl.collateralBalance().add(paymentRemaining));
}
if (interestPayment > 0) {
getPool().collectInterestRepayment(msg.sender, interestPayment);
}
if (principalPayment > 0) {
getPool().collectPrincipalRepayment(msg.sender, principalPayment);
}
emit PaymentMade(cl.borrower(), address(cl), interestPayment, principalPayment, paymentRemaining);
}
function prepay(address payable creditLineAddress, uint amount) external payable whenNotPaused {
CreditLine cl = CreditLine(creditLineAddress);
require(withinTransactionLimit(amount), "Amount is over the per-transaction limit");
getPool().transferFrom(msg.sender, creditLineAddress, amount);
uint newPrepaymentBalance = cl.prepaymentBalance().add(amount);
cl.setPrepaymentBalance(newPrepaymentBalance);
emit PrepaymentMade(msg.sender, address(cl), amount);
}
function addCollateral(address payable creditLineAddress, uint amount) external payable whenNotPaused {
CreditLine cl = CreditLine(creditLineAddress);
getPool().transferFrom(msg.sender, creditLineAddress, amount);
uint newCollateralBalance = cl.collateralBalance().add(amount);
cl.setCollateralBalance(newCollateralBalance);
}
function assessCreditLine(address creditLineAddress) external whenNotPaused {
CreditLine cl = CreditLine(creditLineAddress);
// Do not assess until a full period has elapsed
if (block.number < cl.nextDueBlock()) {
return;
}
(uint paymentRemaining, uint interestPayment, uint principalPayment) = handlePayment(cl, cl.prepaymentBalance(), cl.nextDueBlock(), false);
cl.setPrepaymentBalance(paymentRemaining);
getPool().collectInterestRepayment(msg.sender, interestPayment);
getPool().collectPrincipalRepayment(msg.sender, principalPayment);
cl.setNextDueBlock(calculateNextDueBlock(cl));
if (cl.principalOwed() > 0) {
handleLatePayments(cl);
}
emit PaymentMade(cl.borrower(), address(cl), interestPayment, principalPayment, paymentRemaining);
}
function setPoolAddress(address newPoolAddress) public onlyOwner whenNotPaused returns (address) {
// Sanity check the new address;
Pool(newPoolAddress).totalShares();
emit PoolAddressUpdated(poolAddress, newPoolAddress);
return poolAddress = newPoolAddress;
}
function setMaxUnderwriterLimit(uint amount) public onlyOwner whenNotPaused {
maxUnderwriterLimit = amount;
emit LimitChanged(msg.sender, "maxUnderwriterLimit", amount);
}
function setTransactionLimit(uint amount) public onlyOwner whenNotPaused {
transactionLimit = amount;
emit LimitChanged(msg.sender, "transactionLimit", amount);
}
// Public View Functions (Getters)
function getUnderwriterCreditLines(address underwriterAddress) public view whenNotPaused returns (address[] memory) {
return underwriters[underwriterAddress].creditLines;
}
function getBorrowerCreditLines(address borrowerAddress) public view whenNotPaused returns (address[] memory) {
return borrowers[borrowerAddress].creditLines;
}
/*
* Internal Functions
*/
function handlePayment(CreditLine cl, uint paymentAmount, uint asOfBlock, bool allowFullBalancePayOff) internal returns (uint, uint, uint) {
(uint interestOwed, uint principalOwed) = getInterestAndPrincipalOwedAsOf(cl, asOfBlock);
Accountant.PaymentAllocation memory pa = Accountant.allocatePayment(paymentAmount, cl.balance(), interestOwed, principalOwed);
uint newBalance = cl.balance().sub(pa.principalPayment);
if (allowFullBalancePayOff) {
newBalance = newBalance.sub(pa.additionalBalancePayment);
}
uint totalPrincipalPayment = cl.balance().sub(newBalance);
uint paymentRemaining = paymentAmount.sub(pa.interestPayment).sub(totalPrincipalPayment);
updateCreditLineAccounting(cl, newBalance, interestOwed.sub(pa.interestPayment), principalOwed.sub(pa.principalPayment));
assert(paymentRemaining.add(pa.interestPayment).add(totalPrincipalPayment) == paymentAmount);
return (paymentRemaining, pa.interestPayment, totalPrincipalPayment);
}
function handleLatePayments(CreditLine cl) internal {
// No op for now;
}
function getPool() internal view returns (Pool) {
return Pool(poolAddress);
}
function getInterestAndPrincipalOwedAsOf(CreditLine cl, uint blockNumber) internal view returns (uint, uint) {
(uint interestAccrued, uint principalAccrued) = Accountant.calculateInterestAndPrincipalAccrued(cl, blockNumber);
return (cl.interestOwed().add(interestAccrued), cl.principalOwed().add(principalAccrued));
}
function withinCreditLimit(uint amount, CreditLine cl) internal view returns(bool) {
return cl.balance().add(amount) <= cl.limit();
}
function withinTransactionLimit(uint amount) internal view returns(bool) {
return amount <= transactionLimit;
}
function calculateNewTermEndBlock(CreditLine cl) internal view returns (uint) {
return block.number.add(blocksPerDay.mul(cl.termInDays()));
}
function calculateNextDueBlock(CreditLine cl) internal view returns (uint) {
uint blocksPerPeriod = cl.paymentPeriodInDays().mul(blocksPerDay);
uint currentNextDueBlock;
if (cl.nextDueBlock() != 0) {
currentNextDueBlock = cl.nextDueBlock();
} else {
currentNextDueBlock = block.number;
}
return currentNextDueBlock.add(blocksPerPeriod);
}
function underwriterCanCreateThisCreditLine(uint newAmount, Underwriter storage underwriter) internal view returns(bool) {
uint creditCurrentlyExtended = getCreditCurrentlyExtended(underwriter);
uint totalToBeExtended = creditCurrentlyExtended.add(newAmount);
return totalToBeExtended <= underwriter.governanceLimit;
}
function withinMaxUnderwriterLimit(uint amount) internal view returns (bool) {
return amount <= maxUnderwriterLimit;
}
function getCreditCurrentlyExtended(Underwriter storage underwriter) internal view returns (uint) {
uint creditExtended = 0;
for (uint i = 0; i < underwriter.creditLines.length; i++) {
CreditLine cl = CreditLine(underwriter.creditLines[i]);
creditExtended = creditExtended.add(cl.limit());
}
return creditExtended;
}
function updateCreditLineAccounting(CreditLine cl, uint balance, uint interestOwed, uint principalOwed) internal {
cl.setBalance(balance);
cl.setInterestOwed(interestOwed);
cl.setPrincipalOwed(principalOwed);
cl.setLastUpdatedBlock(block.number);
if (balance == 0) {
cl.setTermEndBlock(0);
cl.setNextDueBlock(0);
}
}
}
|
Sanity check the new address;
|
function setPoolAddress(address newPoolAddress) public onlyOwner whenNotPaused returns (address) {
Pool(newPoolAddress).totalShares();
emit PoolAddressUpdated(poolAddress, newPoolAddress);
return poolAddress = newPoolAddress;
}
| 7,330,733 |
pragma solidity ^0.5.10;
import "./Ownable.sol";
import "./ERC20Interface.sol";
import "./SafeMath.sol";
contract ERC20Token is Ownable, ERC20Interface {
using SafeMath for uint256;
mapping(address => uint256) internal balances;
mapping (address => mapping (address => uint256)) internal allowed;
// CONSTRUCTORS
constructor() public {
}
// EXTERNAL FUNCTIONS
// PUBLIC FUNCTIONS
/// @notice send `_value` token to `_to` from `msg.sender`
/// @param _to The address of the recipient
/// @param _value The amount of token to be transferred
/// @return Whether the transfer was successful or not
function transfer(address _to, uint256 _value) public returns (bool success) {
return transferInternal(msg.sender, _to, _value);
}
/* ALLOW FUNCTIONS */
/**
* @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
*/
/// @notice `msg.sender` approves `_spender` to spend `_value` tokens
/// @param _spender The address of the account able to transfer the tokens
/// @param _value The amount of tokens to be approved for transfer
/// @return Whether the approval was successful or not
function approve(address _spender, uint256 _value) public notNull(_spender) returns (bool success) {
allowed[msg.sender][_spender] = _value;
emit Approval(msg.sender, _spender, _value);
return true;
}
/// @notice send `_value` token to `_to` from `_from` on the condition it is approved by `_from`
/// @param _from The address of the sender
/// @param _to The address of the recipient
/// @param _value The amount of token to be transferred
/// @return Whether the transfer was successful or not
function transferFrom(address _from, address _to, uint256 _value) public returns (bool success) {
require(_value <= allowed[_from][msg.sender], "insufficient tokens");
allowed[_from][msg.sender] = allowed[_from][msg.sender].sub(_value);
return transferInternal(_from, _to, _value);
}
/**
* @dev Returns balance of the `_owner`.
*
* @param _owner The address whose balance will be returned.
* @return balance Balance of the `_owner`.
*/
function balanceOf(address _owner) public view returns (uint256) {
return balances[_owner];
}
/// @param _owner The address of the account owning tokens
/// @param _spender The address of the account able to transfer the tokens
/// @return Amount of remaining tokens allowed to spent
function allowance(address _owner, address _spender) public view returns (uint256) {
return allowed[_owner][_spender];
}
// INTERNAL FUNCTIONS
/// @notice internal send `_value` token to `_to` from `_from`
/// @param _from The address of the sender (null check performed in subTokens)
/// @param _to The address of the recipient (null check performed in addTokens)
/// @param _value The amount of token to be transferred
/// @return Whether the transfer was successful or not
function transferInternal(address _from, address _to, uint256 _value) internal returns (bool) {
uint256 value = subTokens(_from, _value);
addTokens(_to, value);
emit Transfer(_from, _to, value);
return true;
}
/// @notice add tokens `_value` tokens to `owner`
/// @param _owner The address of the account
/// @param _value The amount of tokens to be added
function addTokens(address _owner, uint256 _value) internal;
/// @notice subtract tokens `_value` tokens from `owner`
/// @param _owner The address of the account
/// @param _value The amount of tokens to be subtracted
function subTokens(address _owner, uint256 _value) internal returns (uint256 _valueDeducted );
/// @notice set balance of account `owner` to `_value`
/// @param _owner The address of the account
/// @param _value The new balance
function setBalance(address _owner, uint256 _value) internal notNull(_owner) {
balances[_owner] = _value;
}
// PRIVATE FUNCTIONS
}
|
send `_value` token to `_to` from `msg.sender` _to The address of the recipient _value The amount of token to be transferred return Whether the transfer was successful or not
|
function transfer(address _to, uint256 _value) public returns (bool success) {
return transferInternal(msg.sender, _to, _value);
}
| 6,465,778 |
pragma solidity ^0.5.16;
interface IERC20 {
function TOTALSUPPLY271() external view returns (uint); //inject NONSTANDARD NAMING
function BALANCEOF29(address account) external view returns (uint); //inject NONSTANDARD NAMING
function TRANSFER864(address recipient, uint amount) external returns (bool); //inject NONSTANDARD NAMING
function ALLOWANCE821(address owner, address spender) external view returns (uint); //inject NONSTANDARD NAMING
function APPROVE56(address spender, uint amount) external returns (bool); //inject NONSTANDARD NAMING
function TRANSFERFROM782(address sender, address recipient, uint amount) external returns (bool); //inject NONSTANDARD NAMING
event TRANSFER882(address indexed from, address indexed to, uint value); //inject NONSTANDARD NAMING
event APPROVAL38(address indexed owner, address indexed spender, uint value); //inject NONSTANDARD NAMING
}
contract Context {
constructor () internal { }
function _MSGSENDER939() internal view returns (address payable) { //inject NONSTANDARD NAMING
return msg.sender;
}
}
contract ERC20 is Context, IERC20 {
using SafeMath for uint;
mapping (address => uint) private _balances;
mapping (address => mapping (address => uint)) private _allowances;
uint private _totalSupply;
function TOTALSUPPLY271() public view returns (uint) { //inject NONSTANDARD NAMING
return _totalSupply;
}
function BALANCEOF29(address account) public view returns (uint) { //inject NONSTANDARD NAMING
return _balances[account];
}
function TRANSFER864(address recipient, uint amount) public returns (bool) { //inject NONSTANDARD NAMING
_TRANSFER3(_MSGSENDER939(), recipient, amount);
return true;
}
function ALLOWANCE821(address owner, address spender) public view returns (uint) { //inject NONSTANDARD NAMING
return _allowances[owner][spender];
}
function APPROVE56(address spender, uint amount) public returns (bool) { //inject NONSTANDARD NAMING
_APPROVE188(_MSGSENDER939(), spender, amount);
return true;
}
function TRANSFERFROM782(address sender, address recipient, uint amount) public returns (bool) { //inject NONSTANDARD NAMING
_TRANSFER3(sender, recipient, amount);
_APPROVE188(sender, _MSGSENDER939(), _allowances[sender][_MSGSENDER939()].SUB987(amount, "ERC20: transfer amount exceeds allowance"));
return true;
}
function INCREASEALLOWANCE479(address spender, uint addedValue) public returns (bool) { //inject NONSTANDARD NAMING
_APPROVE188(_MSGSENDER939(), spender, _allowances[_MSGSENDER939()][spender].ADD671(addedValue));
return true;
}
function DECREASEALLOWANCE547(address spender, uint subtractedValue) public returns (bool) { //inject NONSTANDARD NAMING
_APPROVE188(_MSGSENDER939(), spender, _allowances[_MSGSENDER939()][spender].SUB987(subtractedValue, "ERC20: decreased allowance below zero"));
return true;
}
function _TRANSFER3(address sender, address recipient, uint amount) internal { //inject NONSTANDARD NAMING
require(sender != address(0), "ERC20: transfer from the zero address");
require(recipient != address(0), "ERC20: transfer to the zero address");
_balances[sender] = _balances[sender].SUB987(amount, "ERC20: transfer amount exceeds balance");
_balances[recipient] = _balances[recipient].ADD671(amount);
emit TRANSFER882(sender, recipient, amount);
}
function _MINT404(address account, uint amount) internal { //inject NONSTANDARD NAMING
require(account != address(0), "ERC20: mint to the zero address");
_totalSupply = _totalSupply.ADD671(amount);
_balances[account] = _balances[account].ADD671(amount);
emit TRANSFER882(address(0), account, amount);
}
function _BURN359(address account, uint amount) internal { //inject NONSTANDARD NAMING
require(account != address(0), "ERC20: burn from the zero address");
_balances[account] = _balances[account].SUB987(amount, "ERC20: burn amount exceeds balance");
_totalSupply = _totalSupply.SUB987(amount);
emit TRANSFER882(account, address(0), amount);
}
function _APPROVE188(address owner, address spender, uint amount) internal { //inject NONSTANDARD NAMING
require(owner != address(0), "ERC20: approve from the zero address");
require(spender != address(0), "ERC20: approve to the zero address");
_allowances[owner][spender] = amount;
emit APPROVAL38(owner, spender, amount);
}
}
contract ERC20Detailed is IERC20 {
string private _name;
string private _symbol;
uint8 private _decimals;
constructor (string memory name, string memory symbol, uint8 decimals) public {
_name = name;
_symbol = symbol;
_decimals = decimals;
}
function NAME730() public view returns (string memory) { //inject NONSTANDARD NAMING
return _name;
}
function SYMBOL333() public view returns (string memory) { //inject NONSTANDARD NAMING
return _symbol;
}
function DECIMALS459() public view returns (uint8) { //inject NONSTANDARD NAMING
return _decimals;
}
}
library SafeMath {
function ADD671(uint a, uint b) internal pure returns (uint) { //inject NONSTANDARD NAMING
uint c = a + b;
require(c >= a, "SafeMath: addition overflow");
return c;
}
function SUB987(uint a, uint b) internal pure returns (uint) { //inject NONSTANDARD NAMING
return SUB987(a, b, "SafeMath: subtraction overflow");
}
function SUB987(uint a, uint b, string memory errorMessage) internal pure returns (uint) { //inject NONSTANDARD NAMING
require(b <= a, errorMessage);
uint c = a - b;
return c;
}
function MUL833(uint a, uint b) internal pure returns (uint) { //inject NONSTANDARD NAMING
if (a == 0) {
return 0;
}
uint c = a * b;
require(c / a == b, "SafeMath: multiplication overflow");
return c;
}
function DIV482(uint a, uint b) internal pure returns (uint) { //inject NONSTANDARD NAMING
return DIV482(a, b, "SafeMath: division by zero");
}
function DIV482(uint a, uint b, string memory errorMessage) internal pure returns (uint) { //inject NONSTANDARD NAMING
// Solidity only automatically asserts when dividing by 0
require(b > 0, errorMessage);
uint c = a / b;
return c;
}
}
library Address {
function ISCONTRACT215(address account) internal view returns (bool) { //inject NONSTANDARD NAMING
bytes32 codehash;
bytes32 accountHash = 0xc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470;
// solhint-disable-next-line no-inline-assembly
assembly { codehash := extcodehash(account) }
return (codehash != 0x0 && codehash != accountHash);
}
}
library SafeERC20 {
using SafeMath for uint;
using Address for address;
function SAFETRANSFER802(IERC20 token, address to, uint value) internal { //inject NONSTANDARD NAMING
CALLOPTIONALRETURN834(token, abi.encodeWithSelector(token.TRANSFER864.selector, to, value));
}
function SAFETRANSFERFROM543(IERC20 token, address from, address to, uint value) internal { //inject NONSTANDARD NAMING
CALLOPTIONALRETURN834(token, abi.encodeWithSelector(token.TRANSFERFROM782.selector, from, to, value));
}
function SAFEAPPROVE220(IERC20 token, address spender, uint value) internal { //inject NONSTANDARD NAMING
require((value == 0) || (token.ALLOWANCE821(address(this), spender) == 0),
"SafeERC20: approve from non-zero to non-zero allowance"
);
CALLOPTIONALRETURN834(token, abi.encodeWithSelector(token.APPROVE56.selector, spender, value));
}
function CALLOPTIONALRETURN834(IERC20 token, bytes memory data) private { //inject NONSTANDARD NAMING
require(address(token).ISCONTRACT215(), "SafeERC20: call to non-contract");
// solhint-disable-next-line avoid-low-level-calls
(bool success, bytes memory returndata) = address(token).call(data);
require(success, "SafeERC20: low-level call failed");
if (returndata.length > 0) { // Return data is optional
// solhint-disable-next-line max-line-length
require(abi.decode(returndata, (bool)), "SafeERC20: ERC20 operation did not succeed");
}
}
}
contract OnitContract is ERC20, ERC20Detailed {
using SafeERC20 for IERC20;
using Address for address;
using SafeMath for uint;
address public governance;
mapping (address => bool) public minters;
uint256 private _initSeedRound = 150;
constructor () public ERC20Detailed("onbuff.io", "ONIT", 0) {
governance = msg.sender;
_MINT404(governance,_initSeedRound*10**uint(DECIMALS459()));
}
function MINT706(address account, uint amount) public { //inject NONSTANDARD NAMING
require(minters[msg.sender], "!minter");
_MINT404(account, amount);
}
function SETGOVERNANCE359(address _governance) public { //inject NONSTANDARD NAMING
require(msg.sender == governance, "!governance");
governance = _governance;
}
function ADDMINTER824(address _minter) public { //inject NONSTANDARD NAMING
require(msg.sender == governance, "!governance");
minters[_minter] = true;
}
function REMOVEMINTER93(address _minter) public { //inject NONSTANDARD NAMING
require(msg.sender == governance, "!governance");
minters[_minter] = false;
}
}
|
inject NONSTANDARD NAMING
|
function ADDMINTER824(address _minter) public {
| 12,602,604 |
./full_match/82/0xC6658Cee7C586BA9820f78E61b6b0E91542F111B/sources/src/backend/contracts/TokenFT.sol
|
require(false, "Staking not available");
|
function getReward() external updateReward(msg.sender) {
uint _reward = rewards[msg.sender];
rewards[msg.sender] = 0;
IERC20Upgradeable(address(this)).transfer(msg.sender, _reward);
}
| 7,094,492 |
pragma solidity ^0.5.0;
import "../node_modules/@openzeppelin/contracts/ownership/Ownable.sol";
// A generic contract for computing the timestamp
contract Timestamp is Ownable {
uint256 secondsPerBlock = 13;
//---Setter---
function setSecondsPerBlock(uint256 _seconds) public onlyOwner {
secondsPerBlock = _seconds;
}
/**
* Calculates the future block timestamp from the current block timestamp given a duration
* @param _duration The amount of time in seconds till the future block timestamp
* @return The future block timestamp
*/
function getFutureTimestamp(uint256 _duration) public view returns (uint256) {
return block.timestamp + _duration / secondsPerBlock;
}
}
// A contract that keeps track of the balance of an account.
// The account balance can be timelocked for the contract owner to earn interest for the duration
contract Account is Timestamp {
uint256 totalUserBalance; // The total balance that is locked up by the users
struct LockedBalance {
uint256 balance; // The underlying balance
uint256 timestamp; // The block number of when this balance will be available to be withdrawn
}
// Keeps track of an array of LockedBalance per account
mapping (address => LockedBalance[]) accountBalance;
//---Interface---
// Get the total balance of an address
function getAccountBalance(address _address) external view returns (uint256) {
uint256 totalBalance;
LockedBalance[] memory wrappedBalance = accountBalance[_address];
for (uint i = 0; i < wrappedBalance.length; i++) {
totalBalance += wrappedBalance[i].balance;
}
return totalBalance;
}
// Get the balance that is withdrawable
function getWithdrawableBalance(address _address) external view returns (uint256) {
uint256 totalBalance;
LockedBalance[] memory wrappedBalance = accountBalance[_address];
for (uint i = 0; i < wrappedBalance.length; i++) {
if (block.timestamp > wrappedBalance[i].timestamp) {
totalBalance += wrappedBalance[i].balance;
}
}
return totalBalance;
}
// Gets the total user balance
function getTotalUserBalance() external view returns (uint256) {
return totalUserBalance;
}
// Withdraw returns the user's current balance that is not timelocked
// Prepares the balance to be withdrawn
function _withdraw() internal returns (uint256) {
uint256 totalBalance;
LockedBalance[] storage wrappedBalance = accountBalance[msg.sender];
for (uint i = 0; i < wrappedBalance.length; i++) {
if (block.timestamp > wrappedBalance[i].timestamp) {
totalBalance += wrappedBalance[i].balance;
// Protect against reentrancy
delete wrappedBalance[i];
}
}
require(totalBalance > 0,"No balance to withdraw");
totalUserBalance -= totalBalance;
return totalBalance;
}
/**
* Transfer a balance to an address
* @param _to The address of the recipient
* @param _value The amount of token to send
* @param _duration The amount of time in seconds till the DAI can be unlocked
*/
function _transfer(address _to, uint256 _value, uint256 _duration) internal {
uint256 timestamp = getFutureTimestamp(_duration);
accountBalance[_to].push(LockedBalance(_value, timestamp));
totalUserBalance += _value;
}
}
|
Withdraw returns the user's current balance that is not timelocked Prepares the balance to be withdrawn Protect against reentrancy
|
function _withdraw() internal returns (uint256) {
uint256 totalBalance;
LockedBalance[] storage wrappedBalance = accountBalance[msg.sender];
for (uint i = 0; i < wrappedBalance.length; i++) {
if (block.timestamp > wrappedBalance[i].timestamp) {
totalBalance += wrappedBalance[i].balance;
delete wrappedBalance[i];
}
}
require(totalBalance > 0,"No balance to withdraw");
totalUserBalance -= totalBalance;
return totalBalance;
}
| 6,411,603 |
// File: @openzeppelin\contracts\token\ERC20\IERC20.sol
pragma solidity >=0.6.0 <0.8.0;
/**
* @dev Interface of the ERC20 standard as defined in the EIP.
*/
interface IERC20 {
/**
* @dev Returns the amount of tokens in existence.
*/
function totalSupply() external view returns (uint256);
/**
* @dev Returns the amount of tokens owned by `account`.
*/
function balanceOf(address account) external view returns (uint256);
/**
* @dev Moves `amount` tokens from the caller's account to `recipient`.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/
function transfer(address recipient, uint256 amount) external returns (bool);
/**
* @dev Returns the remaining number of tokens that `spender` will be
* allowed to spend on behalf of `owner` through {transferFrom}. This is
* zero by default.
*
* This value changes when {approve} or {transferFrom} are called.
*/
function allowance(address owner, address spender) external view returns (uint256);
/**
* @dev Sets `amount` as the allowance of `spender` over the caller's tokens.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* IMPORTANT: 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
*
* Emits an {Approval} event.
*/
function approve(address spender, uint256 amount) external returns (bool);
/**
* @dev Moves `amount` tokens from `sender` to `recipient` using the
* allowance mechanism. `amount` is then deducted from the caller's
* allowance.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/
function transferFrom(address sender, address recipient, uint256 amount) external returns (bool);
/**
* @dev Emitted when `value` tokens are moved from one account (`from`) to
* another (`to`).
*
* Note that `value` may be zero.
*/
event Transfer(address indexed from, address indexed to, uint256 value);
/**
* @dev Emitted when the allowance of a `spender` for an `owner` is set by
* a call to {approve}. `value` is the new allowance.
*/
event Approval(address indexed owner, address indexed spender, uint256 value);
}
// File: node_modules\@openzeppelin\contracts\math\SafeMath.sol
pragma solidity >=0.6.0 <0.8.0;
/**
* @dev Wrappers over Solidity's arithmetic operations with added overflow
* checks.
*
* Arithmetic operations in Solidity wrap on overflow. This can easily result
* in bugs, because programmers usually assume that an overflow raises an
* error, which is the standard behavior in high level programming languages.
* `SafeMath` restores this intuition by reverting the transaction when an
* operation overflows.
*
* Using this library instead of the unchecked operations eliminates an entire
* class of bugs, so it's recommended to use it always.
*/
library SafeMath {
/**
* @dev Returns the addition of two unsigned integers, reverting on
* overflow.
*
* Counterpart to Solidity's `+` operator.
*
* Requirements:
*
* - Addition cannot overflow.
*/
function add(uint256 a, uint256 b) internal pure returns (uint256) {
uint256 c = a + b;
require(c >= a, "SafeMath: addition overflow");
return c;
}
/**
* @dev Returns the subtraction of two unsigned integers, reverting on
* overflow (when the result is negative).
*
* Counterpart to Solidity's `-` operator.
*
* Requirements:
*
* - Subtraction cannot overflow.
*/
function sub(uint256 a, uint256 b) internal pure returns (uint256) {
return sub(a, b, "SafeMath: subtraction overflow");
}
/**
* @dev Returns the subtraction of two unsigned integers, reverting with custom message on
* overflow (when the result is negative).
*
* Counterpart to Solidity's `-` operator.
*
* Requirements:
*
* - Subtraction cannot overflow.
*/
function sub(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
require(b <= a, errorMessage);
uint256 c = a - b;
return c;
}
/**
* @dev Returns the multiplication of two unsigned integers, reverting on
* overflow.
*
* Counterpart to Solidity's `*` operator.
*
* Requirements:
*
* - Multiplication cannot overflow.
*/
function mul(uint256 a, uint256 b) internal pure returns (uint256) {
// Gas optimization: this is cheaper than requiring 'a' not being zero, but the
// benefit is lost if 'b' is also tested.
// See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522
if (a == 0) {
return 0;
}
uint256 c = a * b;
require(c / a == b, "SafeMath: multiplication overflow");
return c;
}
/**
* @dev Returns the integer division of two unsigned integers. Reverts on
* division by zero. The result is rounded towards zero.
*
* Counterpart to Solidity's `/` operator. Note: this function uses a
* `revert` opcode (which leaves remaining gas untouched) while Solidity
* uses an invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function div(uint256 a, uint256 b) internal pure returns (uint256) {
return div(a, b, "SafeMath: division by zero");
}
/**
* @dev Returns the integer division of two unsigned integers. Reverts with custom message on
* division by zero. The result is rounded towards zero.
*
* Counterpart to Solidity's `/` operator. Note: this function uses a
* `revert` opcode (which leaves remaining gas untouched) while Solidity
* uses an invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function div(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
require(b > 0, errorMessage);
uint256 c = a / b;
// assert(a == b * c + a % b); // There is no case in which this doesn't hold
return c;
}
/**
* @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo),
* Reverts when dividing by zero.
*
* Counterpart to Solidity's `%` operator. This function uses a `revert`
* opcode (which leaves remaining gas untouched) while Solidity uses an
* invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function mod(uint256 a, uint256 b) internal pure returns (uint256) {
return mod(a, b, "SafeMath: modulo by zero");
}
/**
* @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo),
* Reverts with custom message when dividing by zero.
*
* Counterpart to Solidity's `%` operator. This function uses a `revert`
* opcode (which leaves remaining gas untouched) while Solidity uses an
* invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function mod(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
require(b != 0, errorMessage);
return a % b;
}
}
// File: node_modules\@openzeppelin\contracts\utils\Address.sol
pragma solidity >=0.6.2 <0.8.0;
/**
* @dev Collection of functions related to the address type
*/
library Address {
/**
* @dev Returns true if `account` is a contract.
*
* [IMPORTANT]
* ====
* It is unsafe to assume that an address for which this function returns
* false is an externally-owned account (EOA) and not a contract.
*
* Among others, `isContract` will return false for the following
* types of addresses:
*
* - an externally-owned account
* - a contract in construction
* - an address where a contract will be created
* - an address where a contract lived, but was destroyed
* ====
*/
function isContract(address account) internal view returns (bool) {
// This method relies on extcodesize, which returns 0 for contracts in
// construction, since the code is only stored at the end of the
// constructor execution.
uint256 size;
// solhint-disable-next-line no-inline-assembly
assembly { size := extcodesize(account) }
return size > 0;
}
/**
* @dev Replacement for Solidity's `transfer`: sends `amount` wei to
* `recipient`, forwarding all available gas and reverting on errors.
*
* https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost
* of certain opcodes, possibly making contracts go over the 2300 gas limit
* imposed by `transfer`, making them unable to receive funds via
* `transfer`. {sendValue} removes this limitation.
*
* https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more].
*
* IMPORTANT: because control is transferred to `recipient`, care must be
* taken to not create reentrancy vulnerabilities. Consider using
* {ReentrancyGuard} or the
* https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern].
*/
function sendValue(address payable recipient, uint256 amount) internal {
require(address(this).balance >= amount, "Address: insufficient balance");
// solhint-disable-next-line avoid-low-level-calls, avoid-call-value
(bool success, ) = recipient.call{ value: amount }("");
require(success, "Address: unable to send value, recipient may have reverted");
}
/**
* @dev Performs a Solidity function call using a low level `call`. A
* plain`call` is an unsafe replacement for a function call: use this
* function instead.
*
* If `target` reverts with a revert reason, it is bubbled up by this
* function (like regular Solidity function calls).
*
* Returns the raw returned data. To convert to the expected return value,
* use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`].
*
* 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");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with
* `errorMessage` as a fallback revert reason when `target` reverts.
*
* _Available since v3.1._
*/
function functionCall(address target, bytes memory data, string memory errorMessage) internal returns (bytes memory) {
return functionCallWithValue(target, data, 0, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but also transferring `value` wei to `target`.
*
* Requirements:
*
* - the calling contract must have an ETH balance of at least `value`.
* - the called Solidity function must be `payable`.
*
* _Available since v3.1._
*/
function functionCallWithValue(address target, bytes memory data, uint256 value) internal returns (bytes memory) {
return functionCallWithValue(target, data, value, "Address: low-level call with value failed");
}
/**
* @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but
* with `errorMessage` as a fallback revert reason when `target` reverts.
*
* _Available since v3.1._
*/
function functionCallWithValue(address target, bytes memory data, uint256 value, string memory errorMessage) internal returns (bytes memory) {
require(address(this).balance >= value, "Address: insufficient balance for call");
require(isContract(target), "Address: call to non-contract");
// solhint-disable-next-line avoid-low-level-calls
(bool success, bytes memory returndata) = target.call{ value: value }(data);
return _verifyCallResult(success, returndata, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but performing a static call.
*
* _Available since v3.3._
*/
function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) {
return functionStaticCall(target, data, "Address: low-level static call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`],
* but performing a static call.
*
* _Available since v3.3._
*/
function functionStaticCall(address target, bytes memory data, string memory errorMessage) internal view returns (bytes memory) {
require(isContract(target), "Address: static call to non-contract");
// solhint-disable-next-line avoid-low-level-calls
(bool success, bytes memory returndata) = target.staticcall(data);
return _verifyCallResult(success, returndata, errorMessage);
}
function _verifyCallResult(bool success, bytes memory returndata, string memory errorMessage) private pure returns(bytes memory) {
if (success) {
return returndata;
} else {
// Look for revert reason and bubble it up if present
if (returndata.length > 0) {
// The easiest way to bubble the revert reason is using memory via assembly
// solhint-disable-next-line no-inline-assembly
assembly {
let returndata_size := mload(returndata)
revert(add(32, returndata), returndata_size)
}
} else {
revert(errorMessage);
}
}
}
}
// File: @openzeppelin\contracts\token\ERC20\SafeERC20.sol
pragma solidity >=0.6.0 <0.8.0;
/**
* @title SafeERC20
* @dev Wrappers around ERC20 operations that throw on failure (when the token
* contract returns false). Tokens that return no value (and instead revert or
* throw on failure) are also supported, non-reverting calls are assumed to be
* successful.
* To use this library you can add a `using SafeERC20 for IERC20;` statement to your contract,
* which allows you to call the safe operations as `token.safeTransfer(...)`, etc.
*/
library SafeERC20 {
using SafeMath for uint256;
using Address for address;
function safeTransfer(IERC20 token, address to, uint256 value) internal {
_callOptionalReturn(token, abi.encodeWithSelector(token.transfer.selector, to, value));
}
function safeTransferFrom(IERC20 token, address from, address to, uint256 value) internal {
_callOptionalReturn(token, abi.encodeWithSelector(token.transferFrom.selector, from, to, value));
}
/**
* @dev Deprecated. This function has issues similar to the ones found in
* {IERC20-approve}, and its usage is discouraged.
*
* Whenever possible, use {safeIncreaseAllowance} and
* {safeDecreaseAllowance} instead.
*/
function safeApprove(IERC20 token, address spender, uint256 value) internal {
// safeApprove should only be called when setting an initial allowance,
// or when resetting it to zero. To increase and decrease it, use
// 'safeIncreaseAllowance' and 'safeDecreaseAllowance'
// solhint-disable-next-line max-line-length
require((value == 0) || (token.allowance(address(this), spender) == 0),
"SafeERC20: approve from non-zero to non-zero allowance"
);
_callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, value));
}
function safeIncreaseAllowance(IERC20 token, address spender, uint256 value) internal {
uint256 newAllowance = token.allowance(address(this), spender).add(value);
_callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance));
}
function safeDecreaseAllowance(IERC20 token, address spender, uint256 value) internal {
uint256 newAllowance = token.allowance(address(this), spender).sub(value, "SafeERC20: decreased allowance below zero");
_callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance));
}
/**
* @dev Imitates a Solidity high-level call (i.e. a regular function call to a contract), relaxing the requirement
* on the return value: the return value is optional (but if data is returned, it must not be false).
* @param token The token targeted by the call.
* @param data The call data (encoded using abi.encode or one of its variants).
*/
function _callOptionalReturn(IERC20 token, bytes memory data) private {
// We need to perform a low level call here, to bypass Solidity's return data size checking mechanism, since
// we're implementing it ourselves. We use {Address.functionCall} to perform this call, which verifies that
// the target address contains contract code and also asserts for success in the low-level call.
bytes memory returndata = address(token).functionCall(data, "SafeERC20: low-level call failed");
if (returndata.length > 0) { // Return data is optional
// solhint-disable-next-line max-line-length
require(abi.decode(returndata, (bool)), "SafeERC20: ERC20 operation did not succeed");
}
}
}
// File: node_modules\@openzeppelin\contracts\GSN\Context.sol
pragma solidity >=0.6.0 <0.8.0;
/*
* @dev Provides information about the current execution context, including the
* sender of the transaction and its data. While these are generally available
* via msg.sender and msg.data, they should not be accessed in such a direct
* manner, since when dealing with GSN meta-transactions the account sending and
* paying for execution may not be the actual sender (as far as an application
* is concerned).
*
* This contract is only required for intermediate, library-like contracts.
*/
abstract contract Context {
function _msgSender() internal view virtual returns (address payable) {
return msg.sender;
}
function _msgData() internal view virtual returns (bytes memory) {
this; // silence state mutability warning without generating bytecode - see https://github.com/ethereum/solidity/issues/2691
return msg.data;
}
}
// File: @openzeppelin\contracts\access\Ownable.sol
pragma solidity >=0.6.0 <0.8.0;
/**
* @dev Contract module which provides a basic access control mechanism, where
* there is an account (an owner) that can be granted exclusive access to
* specific functions.
*
* By default, the owner account will be the one that deploys the contract. This
* can later be changed with {transferOwnership}.
*
* This module is used through inheritance. It will make available the modifier
* `onlyOwner`, which can be applied to your functions to restrict their use to
* the owner.
*/
abstract contract Ownable is Context {
address private _owner;
event OwnershipTransferred(address indexed previousOwner, address indexed newOwner);
/**
* @dev Initializes the contract setting the deployer as the initial owner.
*/
constructor () internal {
address msgSender = _msgSender();
_owner = msgSender;
emit OwnershipTransferred(address(0), msgSender);
}
/**
* @dev Returns the address of the current owner.
*/
function owner() public view returns (address) {
return _owner;
}
/**
* @dev Throws if called by any account other than the owner.
*/
modifier onlyOwner() {
require(_owner == _msgSender(), "Ownable: caller is not the owner");
_;
}
/**
* @dev Leaves the contract without owner. It will not be possible to call
* `onlyOwner` functions anymore. Can only be called by the current owner.
*
* NOTE: Renouncing ownership will leave the contract without an owner,
* thereby removing any functionality that is only available to the owner.
*/
function renounceOwnership() public virtual onlyOwner {
emit OwnershipTransferred(_owner, address(0));
_owner = address(0);
}
/**
* @dev Transfers ownership of the contract to a new account (`newOwner`).
* Can only be called by the current owner.
*/
function transferOwnership(address newOwner) public virtual onlyOwner {
require(newOwner != address(0), "Ownable: new owner is the zero address");
emit OwnershipTransferred(_owner, newOwner);
_owner = newOwner;
}
}
// File: @openzeppelin\contracts\utils\ReentrancyGuard.sol
pragma solidity >=0.6.0 <0.8.0;
/**
* @dev Contract module that helps prevent reentrant calls to a function.
*
* Inheriting from `ReentrancyGuard` will make the {nonReentrant} modifier
* available, which can be applied to functions to make sure there are no nested
* (reentrant) calls to them.
*
* Note that because there is a single `nonReentrant` guard, functions marked as
* `nonReentrant` may not call one another. This can be worked around by making
* those functions `private`, and then adding `external` `nonReentrant` entry
* points to them.
*
* TIP: If you would like to learn more about reentrancy and alternative ways
* to protect against it, check out our blog post
* https://blog.openzeppelin.com/reentrancy-after-istanbul/[Reentrancy After Istanbul].
*/
abstract contract ReentrancyGuard {
// Booleans are more expensive than uint256 or any type that takes up a full
// word because each write operation emits an extra SLOAD to first read the
// slot's contents, replace the bits taken up by the boolean, and then write
// back. This is the compiler's defense against contract upgrades and
// pointer aliasing, and it cannot be disabled.
// The values being non-zero value makes deployment a bit more expensive,
// but in exchange the refund on every call to nonReentrant will be lower in
// amount. Since refunds are capped to a percentage of the total
// transaction's gas, it is best to keep them low in cases like this one, to
// increase the likelihood of the full refund coming into effect.
uint256 private constant _NOT_ENTERED = 1;
uint256 private constant _ENTERED = 2;
uint256 private _status;
constructor () internal {
_status = _NOT_ENTERED;
}
/**
* @dev Prevents a contract from calling itself, directly or indirectly.
* Calling a `nonReentrant` function from another `nonReentrant`
* function is not supported. It is possible to prevent this from happening
* by making the `nonReentrant` function external, and make it call a
* `private` function that does the actual work.
*/
modifier nonReentrant() {
// On the first call to nonReentrant, _notEntered will be true
require(_status != _ENTERED, "ReentrancyGuard: reentrant call");
// Any calls to nonReentrant after this point will fail
_status = _ENTERED;
_;
// By storing the original value once again, a refund is triggered (see
// https://eips.ethereum.org/EIPS/eip-2200)
_status = _NOT_ENTERED;
}
}
// File: node_modules\@openzeppelin\contracts\token\ERC20\ERC20.sol
pragma solidity >=0.6.0 <0.8.0;
/**
* @dev Implementation of the {IERC20} interface.
*
* This implementation is agnostic to the way tokens are created. This means
* that a supply mechanism has to be added in a derived contract using {_mint}.
* For a generic mechanism see {ERC20PresetMinterPauser}.
*
* TIP: For a detailed writeup see our guide
* https://forum.zeppelin.solutions/t/how-to-implement-erc20-supply-mechanisms/226[How
* to implement supply mechanisms].
*
* We have followed general OpenZeppelin guidelines: functions revert instead
* of returning `false` on failure. This behavior is nonetheless conventional
* and does not conflict with the expectations of ERC20 applications.
*
* Additionally, an {Approval} event is emitted on calls to {transferFrom}.
* This allows applications to reconstruct the allowance for all accounts just
* by listening to said events. Other implementations of the EIP may not emit
* these events, as it isn't required by the specification.
*
* Finally, the non-standard {decreaseAllowance} and {increaseAllowance}
* functions have been added to mitigate the well-known issues around setting
* allowances. See {IERC20-approve}.
*/
contract ERC20 is Context, IERC20 {
using SafeMath for uint256;
mapping (address => uint256) private _balances;
mapping (address => mapping (address => uint256)) private _allowances;
uint256 private _totalSupply;
string private _name;
string private _symbol;
uint8 private _decimals;
/**
* @dev Sets the values for {name} and {symbol}, initializes {decimals} with
* a default value of 18.
*
* To select a different value for {decimals}, use {_setupDecimals}.
*
* All three of these values are immutable: they can only be set once during
* construction.
*/
constructor (string memory name_, string memory symbol_) public {
_name = name_;
_symbol = symbol_;
_decimals = 18;
}
/**
* @dev Returns the name of the token.
*/
function name() public view returns (string memory) {
return _name;
}
/**
* @dev Returns the symbol of the token, usually a shorter version of the
* name.
*/
function symbol() public view returns (string memory) {
return _symbol;
}
/**
* @dev Returns the number of decimals used to get its user representation.
* For example, if `decimals` equals `2`, a balance of `505` tokens should
* be displayed to a user as `5,05` (`505 / 10 ** 2`).
*
* Tokens usually opt for a value of 18, imitating the relationship between
* Ether and Wei. This is the value {ERC20} uses, unless {_setupDecimals} is
* called.
*
* NOTE: This information is only used for _display_ purposes: it in
* no way affects any of the arithmetic of the contract, including
* {IERC20-balanceOf} and {IERC20-transfer}.
*/
function decimals() public view returns (uint8) {
return _decimals;
}
/**
* @dev See {IERC20-totalSupply}.
*/
function totalSupply() public view override returns (uint256) {
return _totalSupply;
}
/**
* @dev See {IERC20-balanceOf}.
*/
function balanceOf(address account) public view override returns (uint256) {
return _balances[account];
}
/**
* @dev See {IERC20-transfer}.
*
* Requirements:
*
* - `recipient` cannot be the zero address.
* - the caller must have a balance of at least `amount`.
*/
function transfer(address recipient, uint256 amount) public virtual override returns (bool) {
_transfer(_msgSender(), recipient, amount);
return true;
}
/**
* @dev See {IERC20-allowance}.
*/
function allowance(address owner, address spender) public view virtual override returns (uint256) {
return _allowances[owner][spender];
}
/**
* @dev See {IERC20-approve}.
*
* Requirements:
*
* - `spender` cannot be the zero address.
*/
function approve(address spender, uint256 amount) public virtual override returns (bool) {
_approve(_msgSender(), spender, amount);
return true;
}
/**
* @dev See {IERC20-transferFrom}.
*
* Emits an {Approval} event indicating the updated allowance. This is not
* required by the EIP. See the note at the beginning of {ERC20}.
*
* Requirements:
*
* - `sender` and `recipient` cannot be the zero address.
* - `sender` must have a balance of at least `amount`.
* - the caller must have allowance for ``sender``'s tokens of at least
* `amount`.
*/
function transferFrom(address sender, address recipient, uint256 amount) public virtual override returns (bool) {
_transfer(sender, recipient, amount);
_approve(sender, _msgSender(), _allowances[sender][_msgSender()].sub(amount, "ERC20: transfer amount exceeds allowance"));
return true;
}
/**
* @dev Atomically increases the allowance granted to `spender` by the caller.
*
* This is an alternative to {approve} that can be used as a mitigation for
* problems described in {IERC20-approve}.
*
* Emits an {Approval} event indicating the updated allowance.
*
* Requirements:
*
* - `spender` cannot be the zero address.
*/
function increaseAllowance(address spender, uint256 addedValue) public virtual returns (bool) {
_approve(_msgSender(), spender, _allowances[_msgSender()][spender].add(addedValue));
return true;
}
/**
* @dev Atomically decreases the allowance granted to `spender` by the caller.
*
* This is an alternative to {approve} that can be used as a mitigation for
* problems described in {IERC20-approve}.
*
* Emits an {Approval} event indicating the updated allowance.
*
* Requirements:
*
* - `spender` cannot be the zero address.
* - `spender` must have allowance for the caller of at least
* `subtractedValue`.
*/
function decreaseAllowance(address spender, uint256 subtractedValue) public virtual returns (bool) {
_approve(_msgSender(), spender, _allowances[_msgSender()][spender].sub(subtractedValue, "ERC20: decreased allowance below zero"));
return true;
}
/**
* @dev 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);
}
/** @dev Creates `amount` tokens and assigns them to `account`, increasing
* the total supply.
*
* Emits a {Transfer} event with `from` set to the zero address.
*
* Requirements:
*
* - `to` cannot be the zero address.
*/
function _mint(address account, uint256 amount) internal virtual {
require(account != address(0), "ERC20: mint to the zero address");
_beforeTokenTransfer(address(0), account, amount);
_totalSupply = _totalSupply.add(amount);
_balances[account] = _balances[account].add(amount);
emit Transfer(address(0), account, amount);
}
/**
* @dev Destroys `amount` tokens from `account`, reducing the
* total supply.
*
* Emits a {Transfer} event with `to` set to the zero address.
*
* Requirements:
*
* - `account` cannot be the zero address.
* - `account` must have at least `amount` tokens.
*/
function _burn(address account, uint256 amount) internal virtual {
require(account != address(0), "ERC20: burn from the zero address");
_beforeTokenTransfer(account, address(0), amount);
_balances[account] = _balances[account].sub(amount, "ERC20: burn amount exceeds balance");
_totalSupply = _totalSupply.sub(amount);
emit Transfer(account, address(0), amount);
}
/**
* @dev Sets `amount` as the allowance of `spender` over the `owner` s tokens.
*
* This internal function is equivalent to `approve`, and can be used to
* e.g. set automatic allowances for certain subsystems, etc.
*
* Emits an {Approval} event.
*
* Requirements:
*
* - `owner` cannot be the zero address.
* - `spender` cannot be the zero address.
*/
function _approve(address owner, address spender, uint256 amount) internal virtual {
require(owner != address(0), "ERC20: approve from the zero address");
require(spender != address(0), "ERC20: approve to the zero address");
_allowances[owner][spender] = amount;
emit Approval(owner, spender, amount);
}
/**
* @dev Sets {decimals} to a value other than the default one of 18.
*
* WARNING: This function should only be called from the constructor. Most
* applications that interact with token contracts will not expect
* {decimals} to ever change, and may work incorrectly if it does.
*/
function _setupDecimals(uint8 decimals_) internal {
_decimals = decimals_;
}
/**
* @dev Hook that is called before any transfer of tokens. This includes
* minting and burning.
*
* Calling conditions:
*
* - when `from` and `to` are both non-zero, `amount` of ``from``'s tokens
* will be to transferred to `to`.
* - when `from` is zero, `amount` tokens will be minted for `to`.
* - when `to` is zero, `amount` of ``from``'s tokens will be burned.
* - `from` and `to` are never both zero.
*
* To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks].
*/
function _beforeTokenTransfer(address from, address to, uint256 amount) internal virtual { }
}
// File: @openzeppelin\contracts\token\ERC20\ERC20Burnable.sol
pragma solidity >=0.6.0 <0.8.0;
/**
* @dev Extension of {ERC20} that allows token holders to destroy both their own
* tokens and those that they have an allowance for, in a way that can be
* recognized off-chain (via event analysis).
*/
abstract contract ERC20Burnable is Context, ERC20 {
using SafeMath for uint256;
/**
* @dev Destroys `amount` tokens from the caller.
*
* See {ERC20-_burn}.
*/
function burn(uint256 amount) public virtual {
_burn(_msgSender(), amount);
}
/**
* @dev Destroys `amount` tokens from `account`, deducting from the caller's
* allowance.
*
* See {ERC20-_burn} and {ERC20-allowance}.
*
* Requirements:
*
* - the caller must have allowance for ``accounts``'s tokens of at least
* `amount`.
*/
function burnFrom(address account, uint256 amount) public virtual {
uint256 decreasedAllowance = allowance(account, _msgSender()).sub(amount, "ERC20: burn amount exceeds allowance");
_approve(account, _msgSender(), decreasedAllowance);
_burn(account, amount);
}
}
// File: contracts\SHEESHA.sol
pragma solidity 0.7.6;
contract SHEESHA is ERC20Burnable, Ownable {
using SafeMath for uint256;
//100,000 tokens
uint256 public constant initialSupply = 100000e18;
address public devAddress;
address public teamAddress;
address public marketingAddress;
address public reserveAddress;
bool public vaultTransferDone;
bool public vaultLPTransferDone;
// 15% team (4% monthly unlock over 25 months)
// 10% dev
// 10% marketing
// 15% liquidity provision
// 10% SHEESHA staking rewards
// 20% LP rewards
// 20% Reserve
constructor(address _devAddress, address _marketingAddress, address _teamAddress, address _reserveAddress) ERC20("Sheesha Finance", "SHEESHA") {
devAddress = _devAddress;
marketingAddress = _marketingAddress;
teamAddress = _teamAddress;
reserveAddress = _reserveAddress;
_mint(address(this), initialSupply);
_transfer(address(this), devAddress, initialSupply.mul(10).div(100));
_transfer(address(this), teamAddress, initialSupply.mul(15).div(100));
_transfer(address(this), marketingAddress, initialSupply.mul(10).div(100));
_transfer(address(this), reserveAddress, initialSupply.mul(20).div(100));
}
//one time only
function transferVaultRewards(address _vaultAddress) public onlyOwner {
require(!vaultTransferDone, "Already transferred");
_transfer(address(this), _vaultAddress, initialSupply.mul(10).div(100));
vaultTransferDone = true;
}
//one time only
function transferVaultLPRewards(address _vaultLPAddress) public onlyOwner {
require(!vaultLPTransferDone, "Already transferred");
_transfer(address(this), _vaultLPAddress, initialSupply.mul(20).div(100));
vaultLPTransferDone = true;
}
}
// File: contracts\SHEESHAVault.sol
pragma solidity 0.7.6;
contract SHEESHAVault is Ownable, ReentrancyGuard {
using SafeMath for uint256;
using SafeERC20 for IERC20;
// Info of each user.
struct UserInfo {
uint256 amount; // How many LP tokens the user has provided.
uint256 rewardDebt; // Reward debt. See explanation below.
//
// We do some fancy math here. Basically, any point in time, the amount of SHEESHAs
// entitled to a user but is pending to be distributed is:
//
// pending reward = (user.amount * pool.accSheeshaPerShare) - user.rewardDebt
//
// Whenever a user deposits or withdraws LP tokens to a pool. Here's what happens:
// 1. The pool's `accSheeshaPerShare` (and `lastRewardBlock`) gets updated.
// 2. User receives the pending reward sent to his/her address.
// 3. User's `amount` gets updated.
// 4. User's `rewardDebt` gets updated.
}
// Info of each pool.
struct PoolInfo {
IERC20 token; // Address of token contract.
uint256 allocPoint; // How many allocation points assigned to this pool. SHEESHAs to distribute per block.
uint256 lastRewardBlock; // Last block number that SHEESHAs distribution occurs.
uint256 accSheeshaPerShare; // Accumulated SHEESHAs per share, times 1e12. See below.
}
// The SHEESHA TOKEN!
SHEESHA public sheesha;
// Info of each pool.
PoolInfo[] public poolInfo;
// Info of each user that stakes tokens.
mapping(uint256 => mapping(address => UserInfo)) public userInfo;
// Total allocation points. Must be the sum of all allocation points in all pools.
uint256 public totalAllocPoint;
// The block number when SHEESHA mining starts.
uint256 public startBlock;
// SHEESHA tokens percenatge created per block based on rewards pool- 0.01%
uint256 public constant sheeshaPerBlock = 1;
//handle case till 0.01(2 decimal places)
uint256 public constant percentageDivider = 10000;
//10,000 sheesha 10% of supply
uint256 public tokenRewards = 10000e18;
event Deposit(address indexed user, uint256 indexed pid, uint256 amount);
event Withdraw(address indexed user, uint256 indexed pid, uint256 amount);
event EmergencyWithdraw(
address indexed user,
uint256 indexed pid,
uint256 amount
);
constructor(
SHEESHA _sheesha
) {
sheesha = _sheesha;
startBlock = block.number;
IERC20(sheesha).safeApprove(msg.sender, uint256(-1));
}
function poolLength() external view returns (uint256) {
return poolInfo.length;
}
// Add a new lp to the pool. Can only be called by the owner.
// DO NOT add the same LP token more than once. Rewards will be messed up if you do.
function add(
uint256 _allocPoint,
IERC20 _token,
bool _withUpdate
) public onlyOwner {
if (_withUpdate) {
massUpdatePools();
}
uint256 lastRewardBlock = block.number;
totalAllocPoint = totalAllocPoint.add(_allocPoint);
poolInfo.push(
PoolInfo({
token: _token,
allocPoint: _allocPoint,
lastRewardBlock: lastRewardBlock,
accSheeshaPerShare: 0
})
);
}
// Update the given pool's SHEESHA allocation point. Can only be called by the owner.
function set(
uint256 _pid,
uint256 _allocPoint,
bool _withUpdate
) public onlyOwner {
if (_withUpdate) {
massUpdatePools();
}
totalAllocPoint = totalAllocPoint.sub(poolInfo[_pid].allocPoint).add(_allocPoint);
poolInfo[_pid].allocPoint = _allocPoint;
}
// Update reward vairables for all pools. Be careful of gas spending!
function massUpdatePools() public {
uint256 length = poolInfo.length;
for (uint256 pid = 0; pid < length; ++pid) {
updatePool(pid);
}
}
// Update reward variables of the given pool to be up-to-date.
function updatePool(uint256 _pid) public {
PoolInfo storage pool = poolInfo[_pid];
if (block.number <= pool.lastRewardBlock) {
return;
}
uint256 tokenSupply = pool.token.balanceOf(address(this));
if (tokenSupply == 0) {
pool.lastRewardBlock = block.number;
return;
}
uint256 sheeshaReward = (tokenRewards.mul(sheeshaPerBlock).div(percentageDivider)).mul(pool.allocPoint).div(totalAllocPoint);
tokenRewards = tokenRewards.sub(sheeshaReward);
pool.accSheeshaPerShare = pool.accSheeshaPerShare.add(sheeshaReward.mul(1e12).div(tokenSupply));
}
// Deposit LP tokens to MasterChef for SHEESHA allocation.
function deposit(uint256 _pid, uint256 _amount) public {
_deposit(msg.sender, _pid, _amount);
}
// stake from LGE directly
// Test coverage
// [x] Does user get the deposited amounts?
// [x] Does user that its deposited for update correcty?
// [x] Does the depositor get their tokens decreased
function depositFor(address _depositFor, uint256 _pid, uint256 _amount) public {
_deposit(_depositFor, _pid, _amount);
}
function _deposit(address _depositFor, uint256 _pid, uint256 _amount) internal nonReentrant {
PoolInfo storage pool = poolInfo[_pid];
UserInfo storage user = userInfo[_pid][_depositFor];
updatePool(_pid);
if (user.amount > 0) {
uint256 pending = user.amount.mul(pool.accSheeshaPerShare).div(1e12).sub(user.rewardDebt);
safeSheeshaTransfer(_depositFor, pending);
}
if(_amount > 0) {
pool.token.safeTransferFrom(address(msg.sender), address(this), _amount);
user.amount = user.amount.add(_amount); // This is depositedFor address
}
user.rewardDebt = user.amount.mul(pool.accSheeshaPerShare).div(1e12); /// This is deposited for address
emit Deposit(_depositFor, _pid, _amount);
}
// Withdraw LP tokens or claim rewards if amount is 0.
function withdraw(uint256 _pid, uint256 _amount) public {
PoolInfo storage pool = poolInfo[_pid];
UserInfo storage user = userInfo[_pid][msg.sender];
require(user.amount >= _amount, "withdraw: not good");
updatePool(_pid);
uint256 pending = user.amount.mul(pool.accSheeshaPerShare).div(1e12).sub(user.rewardDebt);
safeSheeshaTransfer(msg.sender, pending);
if(_amount > 0) {
user.amount = user.amount.sub(_amount);
uint256 fees = _amount.mul(4).div(100);
uint256 burnAmount = fees.mul(1).div(100);
sheesha.burn(burnAmount);
//add tax into rewards distribution
tokenRewards = tokenRewards.add(fees.sub(burnAmount));
pool.token.safeTransfer(address(msg.sender), _amount.sub(fees.sub(burnAmount)));
}
user.rewardDebt = user.amount.mul(pool.accSheeshaPerShare).div(1e12);
emit Withdraw(msg.sender, _pid, _amount);
}
//user must approve this contract to add rewards
function addRewards(uint256 _amount) public onlyOwner {
require(_amount > 0, "Invalid amount");
IERC20(sheesha).safeTransferFrom(address(msg.sender), address(this), _amount);
tokenRewards = tokenRewards.add(_amount);
}
// Withdraw without caring about rewards. EMERGENCY ONLY
function emergencyWithdraw(uint256 _pid) public {
PoolInfo storage pool = poolInfo[_pid];
UserInfo storage user = userInfo[_pid][msg.sender];
pool.token.safeTransfer(address(msg.sender), user.amount);
emit EmergencyWithdraw(msg.sender, _pid, user.amount);
user.amount = 0;
user.rewardDebt = 0;
}
// Safe sheesha transfer function, just in case if rounding error causes pool to not have enough SHEESHAs
function safeSheeshaTransfer(address _to, uint256 _amount) internal {
uint256 sheeshaBal = sheesha.balanceOf(address(this));
if (_amount > sheeshaBal) {
sheesha.transfer(_to, sheeshaBal);
} else {
sheesha.transfer(_to, _amount);
}
}
// View function to see pending SHEESHAs on frontend
function pendingSheesha(uint256 _pid, address _user) external view returns (uint256) {
PoolInfo storage pool = poolInfo[_pid];
UserInfo storage user = userInfo[_pid][_user];
uint256 accSheeshaPerShare = pool.accSheeshaPerShare;
uint256 tokenSupply = pool.token.balanceOf(address(this));
if (block.number > pool.lastRewardBlock && tokenSupply != 0) {
uint256 sheeshaReward = (tokenRewards.mul(sheeshaPerBlock).div(percentageDivider)).mul(pool.allocPoint).div(totalAllocPoint);
accSheeshaPerShare = accSheeshaPerShare.add(sheeshaReward.mul(1e12).div(tokenSupply));
}
return user.amount.mul(accSheeshaPerShare).div(1e12).sub(user.rewardDebt);
}
}
|
user must approve this contract to add rewards
|
function addRewards(uint256 _amount) public onlyOwner {
require(_amount > 0, "Invalid amount");
IERC20(sheesha).safeTransferFrom(address(msg.sender), address(this), _amount);
tokenRewards = tokenRewards.add(_amount);
}
| 413,073 |
./full_match/421613/0x31DfCC1168601537b2BAB3d11065cAfd7E38a3D5/sources/project_/contracts/marketplace/DinoMarketplaceUpgradeable.sol
|
Escrows the NFT, assigning ownership to this contract. Throws if the escrow fails. _nftAddress - The address of the NFT. _owner - Current owner address of token to escrow. _tokenId - ID of token whose approval to verify. It will throw if transfer fails
|
function _escrow(
address _nftAddress,
address _owner,
uint256 _tokenId
) internal {
IERC721 _nftContract = IERC721(_nftAddress);
_nftContract.transferFrom(_owner, address(this), _tokenId);
}
| 11,572,758 |
./full_match/43113/0xc371e397d3aD848696f1F0c6E27Bb641840D4b89/sources/project:/contracts/superfluid/Superfluid.sol
|
context.agreementSelector =; back to old msg.sender
|
function callAgreementWithContext(
ISuperAgreement agreementClass,
bytes calldata callData,
bytes calldata userData,
bytes calldata ctx
)
external override
requireValidCtx(ctx)
isAgreement(agreementClass)
returns (bytes memory newCtx, bytes memory returnedData)
{
Context memory context = decodeCtx(ctx);
if (context.appAddress != msg.sender) revert HOST_CALL_AGREEMENT_WITH_CTX_FROM_WRONG_ADDRESS();
address oldSender = context.msgSender;
context.msgSender = msg.sender;
context.userData = userData;
newCtx = _updateContext(context);
bool success;
(success, returnedData) = _callExternalWithReplacedCtx(address(agreementClass), callData, 0, newCtx);
if (success) {
(newCtx) = abi.decode(returnedData, (bytes));
assert(_isCtxValid(newCtx));
context = decodeCtx(newCtx);
context.msgSender = oldSender;
newCtx = _updateContext(context);
CallUtils.revertFromReturnedData(returnedData);
}
}
| 13,146,873 |
./full_match/5/0x0F265cA07bBdF16700ae7E1C7e1efD04f6e22718/sources/_connext/smart-contracts/contracts/shared/libraries/TypedMemView.sol
|
Return the null view. return bytes29 - The null view/
|
function nullView() internal pure returns (bytes29) {
return NULL;
}
| 11,604,182 |
./full_match/42/0x86C9b267A2E04A17cd938A33D053abba9C814010/sources/contracts/VsnFactory.sol
|
verify create user token balance is > _amount_percent
|
function test(address _tokenAddr,address user) external returns(uint){
uint amount = IERC20(_tokenAddr).balanceOf(user);
balance = amount;
uint createUserAmount = amount.mul(10).div(100);
userAmount = createUserAmount;
return createUserAmount;
}
| 9,578,979 |
./full_match/1/0xfec4545cbEf445d2816b7E1923057d5d7cD1A18c/sources/contracts/CREEMDividendTracker.sol
|
make sure that values are natural numbers which represent the dollar value needed
|
function setTierThreshold(uint tier1, uint tier2, uint tier3, uint tier4) external onlyOwner{
require(tier1>0 && tier2>tier1 && tier3>tier2 && tier4>tier3, "CREEM_D: tiers are not in order");
minTiers[0] = tier1;
minTiers[1] = tier2;
minTiers[2] = tier3;
minTiers[3] = tier4;
}
| 4,944,444 |
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.9;
// @title: Crypto Panther Club
// @developer: Arthur V.
// @artist: https://marcinglod.com
// @url: https://cryptopanther.club
//
// ,,,.
// ,(%&&&&/ ,@@@#//&@@#.
// (@&@# .* .&@@&&@@% (@% &@@.#@&@.
// #@&@,/@@@( .#@@@@@@#, #@@@@@@@@&@( #@*,%*,%@@@(
// &@&@* /%* *@@@@&#(/,. *@@@. .,,*/* * &@@@@@@@@@&&&%@@@&/
// .*#%(,*. *(#%@%*./@(,@&@#.&@@@@@@&&&./@&&&&&&&&&&&&@*
// ,@@&@./@@@@@&* *.,@&&@# ,#&&%, /@&&&&&&&&&&&&&&@%
// ,@&&@@&( .*/#&@@& /@&&&&&&@@&&&@&&&&@&&&&&&&&&&&&@&
// #@* *@@@@@@@@@# %@&&&&&&&@@&&&&&@@*[email protected]&&&&&&&&&&&@*
// .* .,*(&@&&&&&#,.***,./&@&&&&&&&&&&@(
// *. /@@@@( ,@&&&&&@/ @@&&&&&&&&&&&@&.
// %@@#. .#@@@@@@@@% (@@&*.#@&&&&&&&&&@@#,
// %@@@@@@( #@@@@@@@@@@@@# .%@&&&@@@@@@@@(
// (/(&@@@@@.*@@@@@@@@@@&##&* &&&&&&/,#%#%*
// (@@@@@@@/*@@@@@@@@@@@&@& (%#((, *,.,,/&#
// .,,(#, ,**/((#(//.*&@&&@/ #@&&@@@%
// %@@@@@@@@@@* *@@@( %@&@* *@&&&&@*
// ,**, /%@@@@&* /@@&&&&@.,@&, .&@&&@&
// %@&&&@@% * *@@&&&&&&@/ @% &@&&@# ,&@@&%/.
// (@@&&@&*.#@&&&&&&&@# #&, .&@&@/.&@&&&&&&&@@&%(*.
// %@ @@&&&&&&@@/ .* (@&&&&&&&&&&&&&&&&&&&&@@&(.
// %@&&&&&&/,/%&@@@@%. #@&&@&#(%&@&&&&&&&&&&&&&&&&&&&@@&#*.
// /@&&&&&%%@&&&&@@@%%* *@&@( /@@@( %@&&&##&@@@@&&&&&&&&&&&&@@%
// &@&&&&&&&&&#*/#%&&@#. /@@,[email protected]@@@@@@@* %@&&&&/ .*(%&@&&&&&&&&
// %@&&&&&&&@@&&&&&&&&@/ /@( @@@@@@@@@@@ *@&&&@# *&@@&&&
// /@&&&&&&&&@%(@@&&&@% *@*[email protected]@@@@@@@@@@@.,@&&&@% ,/%
// &@&&&&&&&&@/ #@@@, ,@*[email protected]@@@@@@@@@@@@, @&&&&@,
// /@&&&&&&&&&@%, [email protected]( @@@@@@@@@@@@@@/ &@&&&@/
// &@&&&&&&&&&@* &@ (@@@@@@@@@@@@@@# %@&&&@%
// (@&&&&&&@#. %@/ @@@@@@@@@@@@@@@&.*@&&&&@*
// ,@&&&@# #@@ /@@@@@@@@@@@@@@@@/ &@&&&@&
// .&@&&@&, #@@% %@@@@@@@@@@@@@@@@&./@&&&&@#
// (@&&&@@. (@&@( &@@@@@@@@@@@@@@@@@# &@&&&&@(
// ,@&&&&@&* /@&&@/ &@@@@@@@@@@@@@@@@@@*,&&&&&&@(
import "@openzeppelin/contracts/token/ERC721/ERC721.sol";
import "@openzeppelin/contracts/security/ReentrancyGuard.sol";
import "@openzeppelin/contracts/access/Ownable.sol";
import "@openzeppelin/contracts/utils/Counters.sol";
import "@chainlink/contracts/src/v0.8/VRFConsumerBase.sol";
import "@openzeppelin/contracts/utils/Strings.sol";
contract CryptoPantherClub is ERC721, ReentrancyGuard, VRFConsumerBase, Ownable {
// ======== Counter =========
using Counters for Counters.Counter;
Counters.Counter private supplyCounter;
// ======== Supply =========
uint256 public constant MAX_SUPPLY = 5555;
// ======== Max Mints Per Address =========
uint256 public maxPerAddressWhitelist;
uint256 public maxPerAddressPublic;
// ======== Price =========
uint256 public priceWhitelist;
uint256 public pricePublic;
// ======== Mints Per Address Mapping ========
struct MintTypes {
uint256 _numberOfMintsByAddress;
}
mapping(address => MintTypes) public addressToMints;
// ======== Base URI =========
string private baseURI;
// ======== Phase =========
enum SalePhase{ Locked, Whitelist, PrePublic, Public, Ended }
SalePhase public phase = SalePhase.Locked;
// ======== Chainlink VRF (v.1) ========
bytes32 internal immutable keyHash;
uint256 internal immutable fee;
uint256 public indexShift = 0;
// ======== Whitelist Coupons ========
address private constant ownerSigner = 0x493e23ed0756415107993FE3D777Ca1A356FB038;
enum CouponType{ Whitelist }
struct Coupon {
bytes32 r;
bytes32 s;
uint8 v;
}
// ======== Constructor =========
constructor(
string memory name_,
string memory symbol_,
string memory hiddenURI_
)
VRFConsumerBase(
0xf0d54349aDdcf704F77AE15b96510dEA15cb7952, // VRF Coordinator
0x514910771AF9Ca656af840dff83E8264EcF986CA // LINK Token
)
ERC721(name_, symbol_) {
baseURI = hiddenURI_;
keyHash = 0xAA77729D3466CA35AE8D28B3BBAC7CC36A5031EFDC430821C02BC31A238AF445; // VRF keyHash
fee = 2 * 10 ** 18; // 2 LINK
}
// ======== Team Reserve (Events, Promotions, etc.) =========
function reserve(uint256 amount_)
external
onlyLockedPhase
onlyOwner
{
require(amount_ > 0, "Amount can't be zero.");
for(uint256 ind_ = 0; ind_ < amount_; ind_++) {
_safeMint(msg.sender, totalSupply() + 1);
supplyCounter.increment();
}
}
// ======== Set Whitelist Price ========
function setPriceWhitelist(uint256 price_)
external
onlyLockedPhase
onlyOwner
{
priceWhitelist = price_;
}
// ======== Set Public Pirce ========
function setPricePublic(uint256 price_)
external
onlyPrePublicPhase
onlyOwner
{
pricePublic = price_;
}
// ======== Set Max Whitelist Mint Amount Per Address ========
function setMaxPerAddressWhitelist(uint256 amount_)
external
onlyLockedPhase
onlyOwner
{
maxPerAddressWhitelist = amount_;
}
// ======== Set Max Public Mint Amount Per Address ========
function setMaxPerAddressPublic(uint256 amount_)
external
onlyPrePublicPhase
onlyOwner
{
maxPerAddressPublic = amount_;
}
// ======== Enable Whitelist Mint =========
function setWhitelistPhase()
external
onlyLockedPhase
onlyOwner
{
require(priceWhitelist != 0, "Whitelist price is not set.");
require(maxPerAddressWhitelist != 0, "Max whitelist mint amount not set.");
phase = SalePhase.Whitelist;
}
// ======== Enable PrePublic Phase =========
function setPrePublicPhase()
external
onlyWhitelistPhase
onlyOwner
{
phase = SalePhase.PrePublic;
}
// ======== Enable Public Mint =========
function setPublicPhase()
external
onlyPrePublicPhase
onlyOwner
{
require(pricePublic != 0, "Public price is not set.");
require(maxPerAddressPublic != 0, "Max public mint amount not set.");
phase = SalePhase.Public;
}
// ======== End Sale =========
function setEndedPhase() external onlyOwner {
phase = SalePhase.Ended;
}
// ======== Whitelist Mint =========
function whitelistMint(uint256 amount_, Coupon memory coupon_)
public
payable
onlyWhitelistPhase
validateAmount(amount_, maxPerAddressWhitelist)
validateSupply(amount_)
validateEthPayment(amount_, priceWhitelist)
nonReentrant
{
require(amount_ + addressToMints[msg.sender]._numberOfMintsByAddress <= maxPerAddressWhitelist, "Exceeds number of whitelist mints allowed.");
bytes32 digest = keccak256(abi.encode(CouponType.Whitelist, msg.sender));
require(isVerifiedCoupon(digest, coupon_), "Invalid coupon");
addressToMints[msg.sender]._numberOfMintsByAddress += amount_;
for(uint256 ind_ = 0; ind_ < amount_; ind_++) {
_safeMint(msg.sender, totalSupply() + 1);
supplyCounter.increment();
}
if (totalSupply() == MAX_SUPPLY) {
phase = SalePhase.Ended;
}
}
// ======== Public Mint =========
function mint(uint256 amount_)
public
payable
onlyPublicPhase
validateAmount(amount_, maxPerAddressPublic)
validateSupply(amount_)
validateEthPayment(amount_, pricePublic)
nonReentrant
{
require(amount_ + addressToMints[msg.sender]._numberOfMintsByAddress <= maxPerAddressPublic, "Exceeds number of mints allowed.");
addressToMints[msg.sender]._numberOfMintsByAddress += amount_;
for(uint256 ind_ = 0; ind_ < amount_; ind_++) {
_safeMint(msg.sender, totalSupply() + 1);
supplyCounter.increment();
}
if (totalSupply() == MAX_SUPPLY) {
phase = SalePhase.Ended;
}
}
// ======== Reveal Metadata =========
function reveal(string memory baseURI_)
external
onlyEndedPhase
onlyZeroIndexShift
onlyOwner
{
baseURI = baseURI_;
requestRandomIndexShift();
}
// ======== Return Base URI =========
function _baseURI() internal view virtual override returns (string memory) {
return baseURI;
}
// ======== Return Token URI =========
function tokenURI(uint256 tokenId) public view virtual override(ERC721) returns (string memory) {
require(_exists(tokenId), "Nonexistent token.");
string memory sequenceId;
if (indexShift > 0) {
sequenceId = Strings.toString((tokenId + indexShift) % MAX_SUPPLY + 1);
} else {
sequenceId = "0";
}
return string(abi.encodePacked(baseURI, sequenceId));
}
// ======== Get Total Supply ========
function totalSupply() public view returns (uint256) {
return supplyCounter.current();
}
// ======== Get Random Number Using Chainlink VRF =========
function requestRandomIndexShift() private returns (bytes32 requestId) {
require(LINK.balanceOf(address(this)) >= fee, "Not enough LINK.");
return requestRandomness(keyHash, fee);
}
// ======== Set Random Starting Index =========
function fulfillRandomness(bytes32 requestId, uint256 randomness) internal override {
indexShift = (randomness % MAX_SUPPLY) + 1;
}
// ======== Verify Coupon =========
function isVerifiedCoupon(bytes32 digest_, Coupon memory coupon_) internal view returns (bool) {
address signer = ecrecover(digest_, coupon_.v, coupon_.r, coupon_.s);
require(signer != address(0), 'ECDSA: invalid signature');
return signer == ownerSigner;
}
// ======== Withdraw =========
function withdraw(address payee_, uint256 amount_) external onlyOwner {
(bool success, ) = payee_.call{value: amount_}('');
require(success, 'Transfer failed.');
}
// ======== Modifiers ========
modifier validateEthPayment(uint256 amount_, uint256 price_) {
require(amount_ * price_ <= msg.value, "Ether value sent is not correct.");
_;
}
modifier validateSupply(uint256 amount_) {
require(totalSupply() + amount_ <= MAX_SUPPLY, "Max supply exceeded.");
_;
}
modifier validateAmount(uint256 amount_, uint256 max_) {
require(amount_ > 0 && amount_ <= max_, "Amount is out of range.");
_;
}
modifier onlyLockedPhase() {
require(phase == SalePhase.Locked, "Minting is not locked.");
_;
}
modifier onlyWhitelistPhase() {
require(phase == SalePhase.Whitelist, "Whitelist sale is not active.");
_;
}
modifier onlyPrePublicPhase() {
require(phase == SalePhase.PrePublic, "PrePublic phase is not active.");
_;
}
modifier onlyPublicPhase() {
require(phase == SalePhase.Public, "Public sale is not active.");
_;
}
modifier onlyEndedPhase() {
require(phase == SalePhase.Ended, "Sale has not ended.");
_;
}
modifier onlyZeroIndexShift() {
require(indexShift == 0, "Already randomized.");
_;
}
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (token/ERC721/ERC721.sol)
pragma solidity ^0.8.0;
import "./IERC721.sol";
import "./IERC721Receiver.sol";
import "./extensions/IERC721Metadata.sol";
import "../../utils/Address.sol";
import "../../utils/Context.sol";
import "../../utils/Strings.sol";
import "../../utils/introspection/ERC165.sol";
/**
* @dev Implementation of https://eips.ethereum.org/EIPS/eip-721[ERC721] Non-Fungible Token Standard, including
* the Metadata extension, but not including the Enumerable extension, which is available separately as
* {ERC721Enumerable}.
*/
contract ERC721 is Context, ERC165, IERC721, IERC721Metadata {
using Address for address;
using Strings for uint256;
// Token name
string private _name;
// Token symbol
string private _symbol;
// Mapping from token ID to owner address
mapping(uint256 => address) private _owners;
// Mapping owner address to token count
mapping(address => uint256) private _balances;
// Mapping from token ID to approved address
mapping(uint256 => address) private _tokenApprovals;
// Mapping from owner to operator approvals
mapping(address => mapping(address => bool)) private _operatorApprovals;
/**
* @dev Initializes the contract by setting a `name` and a `symbol` to the token collection.
*/
constructor(string memory name_, string memory symbol_) {
_name = name_;
_symbol = symbol_;
}
/**
* @dev See {IERC165-supportsInterface}.
*/
function supportsInterface(bytes4 interfaceId) public view virtual override(ERC165, IERC165) returns (bool) {
return
interfaceId == type(IERC721).interfaceId ||
interfaceId == type(IERC721Metadata).interfaceId ||
super.supportsInterface(interfaceId);
}
/**
* @dev See {IERC721-balanceOf}.
*/
function balanceOf(address owner) public view virtual override returns (uint256) {
require(owner != address(0), "ERC721: balance query for the zero address");
return _balances[owner];
}
/**
* @dev See {IERC721-ownerOf}.
*/
function ownerOf(uint256 tokenId) public view virtual override returns (address) {
address owner = _owners[tokenId];
require(owner != address(0), "ERC721: owner query for nonexistent token");
return owner;
}
/**
* @dev See {IERC721Metadata-name}.
*/
function name() public view virtual override returns (string memory) {
return _name;
}
/**
* @dev See {IERC721Metadata-symbol}.
*/
function symbol() public view virtual override returns (string memory) {
return _symbol;
}
/**
* @dev See {IERC721Metadata-tokenURI}.
*/
function tokenURI(uint256 tokenId) public view virtual override returns (string memory) {
require(_exists(tokenId), "ERC721Metadata: URI query for nonexistent token");
string memory baseURI = _baseURI();
return bytes(baseURI).length > 0 ? string(abi.encodePacked(baseURI, tokenId.toString())) : "";
}
/**
* @dev Base URI for computing {tokenURI}. If set, the resulting URI for each
* token will be the concatenation of the `baseURI` and the `tokenId`. Empty
* by default, can be overriden in child contracts.
*/
function _baseURI() internal view virtual returns (string memory) {
return "";
}
/**
* @dev See {IERC721-approve}.
*/
function approve(address to, uint256 tokenId) public virtual override {
address owner = ERC721.ownerOf(tokenId);
require(to != owner, "ERC721: approval to current owner");
require(
_msgSender() == owner || isApprovedForAll(owner, _msgSender()),
"ERC721: approve caller is not owner nor approved for all"
);
_approve(to, tokenId);
}
/**
* @dev See {IERC721-getApproved}.
*/
function getApproved(uint256 tokenId) public view virtual override returns (address) {
require(_exists(tokenId), "ERC721: approved query for nonexistent token");
return _tokenApprovals[tokenId];
}
/**
* @dev See {IERC721-setApprovalForAll}.
*/
function setApprovalForAll(address operator, bool approved) public virtual override {
_setApprovalForAll(_msgSender(), operator, approved);
}
/**
* @dev See {IERC721-isApprovedForAll}.
*/
function isApprovedForAll(address owner, address operator) public view virtual override returns (bool) {
return _operatorApprovals[owner][operator];
}
/**
* @dev See {IERC721-transferFrom}.
*/
function transferFrom(
address from,
address to,
uint256 tokenId
) public virtual override {
//solhint-disable-next-line max-line-length
require(_isApprovedOrOwner(_msgSender(), tokenId), "ERC721: transfer caller is not owner nor approved");
_transfer(from, to, tokenId);
}
/**
* @dev See {IERC721-safeTransferFrom}.
*/
function safeTransferFrom(
address from,
address to,
uint256 tokenId
) public virtual override {
safeTransferFrom(from, to, tokenId, "");
}
/**
* @dev See {IERC721-safeTransferFrom}.
*/
function safeTransferFrom(
address from,
address to,
uint256 tokenId,
bytes memory _data
) public virtual override {
require(_isApprovedOrOwner(_msgSender(), tokenId), "ERC721: transfer caller is not owner nor approved");
_safeTransfer(from, to, tokenId, _data);
}
/**
* @dev Safely transfers `tokenId` token from `from` to `to`, checking first that contract recipients
* are aware of the ERC721 protocol to prevent tokens from being forever locked.
*
* `_data` is additional data, it has no specified format and it is sent in call to `to`.
*
* This internal function is equivalent to {safeTransferFrom}, and can be used to e.g.
* implement alternative mechanisms to perform token transfer, such as signature-based.
*
* Requirements:
*
* - `from` cannot be the zero address.
* - `to` cannot be the zero address.
* - `tokenId` token must exist and be owned by `from`.
* - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer.
*
* Emits a {Transfer} event.
*/
function _safeTransfer(
address from,
address to,
uint256 tokenId,
bytes memory _data
) internal virtual {
_transfer(from, to, tokenId);
require(_checkOnERC721Received(from, to, tokenId, _data), "ERC721: transfer to non ERC721Receiver implementer");
}
/**
* @dev Returns whether `tokenId` exists.
*
* Tokens can be managed by their owner or approved accounts via {approve} or {setApprovalForAll}.
*
* Tokens start existing when they are minted (`_mint`),
* and stop existing when they are burned (`_burn`).
*/
function _exists(uint256 tokenId) internal view virtual returns (bool) {
return _owners[tokenId] != address(0);
}
/**
* @dev Returns whether `spender` is allowed to manage `tokenId`.
*
* Requirements:
*
* - `tokenId` must exist.
*/
function _isApprovedOrOwner(address spender, uint256 tokenId) internal view virtual returns (bool) {
require(_exists(tokenId), "ERC721: operator query for nonexistent token");
address owner = ERC721.ownerOf(tokenId);
return (spender == owner || getApproved(tokenId) == spender || isApprovedForAll(owner, spender));
}
/**
* @dev Safely mints `tokenId` and transfers it to `to`.
*
* Requirements:
*
* - `tokenId` must not exist.
* - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer.
*
* Emits a {Transfer} event.
*/
function _safeMint(address to, uint256 tokenId) internal virtual {
_safeMint(to, tokenId, "");
}
/**
* @dev Same as {xref-ERC721-_safeMint-address-uint256-}[`_safeMint`], with an additional `data` parameter which is
* forwarded in {IERC721Receiver-onERC721Received} to contract recipients.
*/
function _safeMint(
address to,
uint256 tokenId,
bytes memory _data
) internal virtual {
_mint(to, tokenId);
require(
_checkOnERC721Received(address(0), to, tokenId, _data),
"ERC721: transfer to non ERC721Receiver implementer"
);
}
/**
* @dev Mints `tokenId` and transfers it to `to`.
*
* WARNING: Usage of this method is discouraged, use {_safeMint} whenever possible
*
* Requirements:
*
* - `tokenId` must not exist.
* - `to` cannot be the zero address.
*
* Emits a {Transfer} event.
*/
function _mint(address to, uint256 tokenId) internal virtual {
require(to != address(0), "ERC721: mint to the zero address");
require(!_exists(tokenId), "ERC721: token already minted");
_beforeTokenTransfer(address(0), to, tokenId);
_balances[to] += 1;
_owners[tokenId] = to;
emit Transfer(address(0), to, tokenId);
}
/**
* @dev Destroys `tokenId`.
* The approval is cleared when the token is burned.
*
* Requirements:
*
* - `tokenId` must exist.
*
* Emits a {Transfer} event.
*/
function _burn(uint256 tokenId) internal virtual {
address owner = ERC721.ownerOf(tokenId);
_beforeTokenTransfer(owner, address(0), tokenId);
// Clear approvals
_approve(address(0), tokenId);
_balances[owner] -= 1;
delete _owners[tokenId];
emit Transfer(owner, address(0), tokenId);
}
/**
* @dev Transfers `tokenId` from `from` to `to`.
* As opposed to {transferFrom}, this imposes no restrictions on msg.sender.
*
* Requirements:
*
* - `to` cannot be the zero address.
* - `tokenId` token must be owned by `from`.
*
* Emits a {Transfer} event.
*/
function _transfer(
address from,
address to,
uint256 tokenId
) internal virtual {
require(ERC721.ownerOf(tokenId) == from, "ERC721: transfer of token that is not own");
require(to != address(0), "ERC721: transfer to the zero address");
_beforeTokenTransfer(from, to, tokenId);
// Clear approvals from the previous owner
_approve(address(0), tokenId);
_balances[from] -= 1;
_balances[to] += 1;
_owners[tokenId] = to;
emit Transfer(from, to, tokenId);
}
/**
* @dev Approve `to` to operate on `tokenId`
*
* Emits a {Approval} event.
*/
function _approve(address to, uint256 tokenId) internal virtual {
_tokenApprovals[tokenId] = to;
emit Approval(ERC721.ownerOf(tokenId), to, tokenId);
}
/**
* @dev Approve `operator` to operate on all of `owner` tokens
*
* Emits a {ApprovalForAll} event.
*/
function _setApprovalForAll(
address owner,
address operator,
bool approved
) internal virtual {
require(owner != operator, "ERC721: approve to caller");
_operatorApprovals[owner][operator] = approved;
emit ApprovalForAll(owner, operator, approved);
}
/**
* @dev Internal function to invoke {IERC721Receiver-onERC721Received} on a target address.
* The call is not executed if the target address is not a contract.
*
* @param from address representing the previous owner of the given token ID
* @param to target address that will receive the tokens
* @param tokenId uint256 ID of the token to be transferred
* @param _data bytes optional data to send along with the call
* @return bool whether the call correctly returned the expected magic value
*/
function _checkOnERC721Received(
address from,
address to,
uint256 tokenId,
bytes memory _data
) private returns (bool) {
if (to.isContract()) {
try IERC721Receiver(to).onERC721Received(_msgSender(), from, tokenId, _data) returns (bytes4 retval) {
return retval == IERC721Receiver.onERC721Received.selector;
} catch (bytes memory reason) {
if (reason.length == 0) {
revert("ERC721: transfer to non ERC721Receiver implementer");
} else {
assembly {
revert(add(32, reason), mload(reason))
}
}
}
} else {
return true;
}
}
/**
* @dev Hook that is called before any token transfer. This includes minting
* and burning.
*
* Calling conditions:
*
* - When `from` and `to` are both non-zero, ``from``'s `tokenId` will be
* transferred to `to`.
* - When `from` is zero, `tokenId` will be minted for `to`.
* - When `to` is zero, ``from``'s `tokenId` will be burned.
* - `from` and `to` are never both zero.
*
* To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks].
*/
function _beforeTokenTransfer(
address from,
address to,
uint256 tokenId
) internal virtual {}
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (security/ReentrancyGuard.sol)
pragma solidity ^0.8.0;
/**
* @dev Contract module that helps prevent reentrant calls to a function.
*
* Inheriting from `ReentrancyGuard` will make the {nonReentrant} modifier
* available, which can be applied to functions to make sure there are no nested
* (reentrant) calls to them.
*
* Note that because there is a single `nonReentrant` guard, functions marked as
* `nonReentrant` may not call one another. This can be worked around by making
* those functions `private`, and then adding `external` `nonReentrant` entry
* points to them.
*
* TIP: If you would like to learn more about reentrancy and alternative ways
* to protect against it, check out our blog post
* https://blog.openzeppelin.com/reentrancy-after-istanbul/[Reentrancy After Istanbul].
*/
abstract contract ReentrancyGuard {
// Booleans are more expensive than uint256 or any type that takes up a full
// word because each write operation emits an extra SLOAD to first read the
// slot's contents, replace the bits taken up by the boolean, and then write
// back. This is the compiler's defense against contract upgrades and
// pointer aliasing, and it cannot be disabled.
// The values being non-zero value makes deployment a bit more expensive,
// but in exchange the refund on every call to nonReentrant will be lower in
// amount. Since refunds are capped to a percentage of the total
// transaction's gas, it is best to keep them low in cases like this one, to
// increase the likelihood of the full refund coming into effect.
uint256 private constant _NOT_ENTERED = 1;
uint256 private constant _ENTERED = 2;
uint256 private _status;
constructor() {
_status = _NOT_ENTERED;
}
/**
* @dev Prevents a contract from calling itself, directly or indirectly.
* Calling a `nonReentrant` function from another `nonReentrant`
* function is not supported. It is possible to prevent this from happening
* by making the `nonReentrant` function external, and making it call a
* `private` function that does the actual work.
*/
modifier nonReentrant() {
// On the first call to nonReentrant, _notEntered will be true
require(_status != _ENTERED, "ReentrancyGuard: reentrant call");
// Any calls to nonReentrant after this point will fail
_status = _ENTERED;
_;
// By storing the original value once again, a refund is triggered (see
// https://eips.ethereum.org/EIPS/eip-2200)
_status = _NOT_ENTERED;
}
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (access/Ownable.sol)
pragma solidity ^0.8.0;
import "../utils/Context.sol";
/**
* @dev Contract module which provides a basic access control mechanism, where
* there is an account (an owner) that can be granted exclusive access to
* specific functions.
*
* By default, the owner account will be the one that deploys the contract. This
* can later be changed with {transferOwnership}.
*
* This module is used through inheritance. It will make available the modifier
* `onlyOwner`, which can be applied to your functions to restrict their use to
* the owner.
*/
abstract contract Ownable is Context {
address private _owner;
event OwnershipTransferred(address indexed previousOwner, address indexed newOwner);
/**
* @dev Initializes the contract setting the deployer as the initial owner.
*/
constructor() {
_transferOwnership(_msgSender());
}
/**
* @dev Returns the address of the current owner.
*/
function owner() public view virtual returns (address) {
return _owner;
}
/**
* @dev Throws if called by any account other than the owner.
*/
modifier onlyOwner() {
require(owner() == _msgSender(), "Ownable: caller is not the owner");
_;
}
/**
* @dev Leaves the contract without owner. It will not be possible to call
* `onlyOwner` functions anymore. Can only be called by the current owner.
*
* NOTE: Renouncing ownership will leave the contract without an owner,
* thereby removing any functionality that is only available to the owner.
*/
function renounceOwnership() public virtual onlyOwner {
_transferOwnership(address(0));
}
/**
* @dev Transfers ownership of the contract to a new account (`newOwner`).
* Can only be called by the current owner.
*/
function transferOwnership(address newOwner) public virtual onlyOwner {
require(newOwner != address(0), "Ownable: new owner is the zero address");
_transferOwnership(newOwner);
}
/**
* @dev Transfers ownership of the contract to a new account (`newOwner`).
* Internal function without access restriction.
*/
function _transferOwnership(address newOwner) internal virtual {
address oldOwner = _owner;
_owner = newOwner;
emit OwnershipTransferred(oldOwner, newOwner);
}
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (utils/Counters.sol)
pragma solidity ^0.8.0;
/**
* @title Counters
* @author Matt Condon (@shrugs)
* @dev Provides counters that can only be incremented, decremented or reset. This can be used e.g. to track the number
* of elements in a mapping, issuing ERC721 ids, or counting request ids.
*
* Include with `using Counters for Counters.Counter;`
*/
library Counters {
struct Counter {
// This variable should never be directly accessed by users of the library: interactions must be restricted to
// the library's function. As of Solidity v0.5.2, this cannot be enforced, though there is a proposal to add
// this feature: see https://github.com/ethereum/solidity/issues/4637
uint256 _value; // default: 0
}
function current(Counter storage counter) internal view returns (uint256) {
return counter._value;
}
function increment(Counter storage counter) internal {
unchecked {
counter._value += 1;
}
}
function decrement(Counter storage counter) internal {
uint256 value = counter._value;
require(value > 0, "Counter: decrement overflow");
unchecked {
counter._value = value - 1;
}
}
function reset(Counter storage counter) internal {
counter._value = 0;
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import "./interfaces/LinkTokenInterface.sol";
import "./VRFRequestIDBase.sol";
/** ****************************************************************************
* @notice Interface for contracts using VRF randomness
* *****************************************************************************
* @dev PURPOSE
*
* @dev Reggie the Random Oracle (not his real job) wants to provide randomness
* @dev to Vera the verifier in such a way that Vera can be sure he's not
* @dev making his output up to suit himself. Reggie provides Vera a public key
* @dev to which he knows the secret key. Each time Vera provides a seed to
* @dev Reggie, he gives back a value which is computed completely
* @dev deterministically from the seed and the secret key.
*
* @dev Reggie provides a proof by which Vera can verify that the output was
* @dev correctly computed once Reggie tells it to her, but without that proof,
* @dev the output is indistinguishable to her from a uniform random sample
* @dev from the output space.
*
* @dev The purpose of this contract is to make it easy for unrelated contracts
* @dev to talk to Vera the verifier about the work Reggie is doing, to provide
* @dev simple access to a verifiable source of randomness.
* *****************************************************************************
* @dev USAGE
*
* @dev Calling contracts must inherit from VRFConsumerBase, and can
* @dev initialize VRFConsumerBase's attributes in their constructor as
* @dev shown:
*
* @dev contract VRFConsumer {
* @dev constuctor(<other arguments>, address _vrfCoordinator, address _link)
* @dev VRFConsumerBase(_vrfCoordinator, _link) public {
* @dev <initialization with other arguments goes here>
* @dev }
* @dev }
*
* @dev The oracle will have given you an ID for the VRF keypair they have
* @dev committed to (let's call it keyHash), and have told you the minimum LINK
* @dev price for VRF service. Make sure your contract has sufficient LINK, and
* @dev call requestRandomness(keyHash, fee, seed), where seed is the input you
* @dev want to generate randomness from.
*
* @dev Once the VRFCoordinator has received and validated the oracle's response
* @dev to your request, it will call your contract's fulfillRandomness method.
*
* @dev The randomness argument to fulfillRandomness is the actual random value
* @dev generated from your seed.
*
* @dev The requestId argument is generated from the keyHash and the seed by
* @dev makeRequestId(keyHash, seed). If your contract could have concurrent
* @dev requests open, you can use the requestId to track which seed is
* @dev associated with which randomness. See VRFRequestIDBase.sol for more
* @dev details. (See "SECURITY CONSIDERATIONS" for principles to keep in mind,
* @dev if your contract could have multiple requests in flight simultaneously.)
*
* @dev Colliding `requestId`s are cryptographically impossible as long as seeds
* @dev differ. (Which is critical to making unpredictable randomness! See the
* @dev next section.)
*
* *****************************************************************************
* @dev SECURITY CONSIDERATIONS
*
* @dev A method with the ability to call your fulfillRandomness method directly
* @dev could spoof a VRF response with any random value, so it's critical that
* @dev it cannot be directly called by anything other than this base contract
* @dev (specifically, by the VRFConsumerBase.rawFulfillRandomness method).
*
* @dev For your users to trust that your contract's random behavior is free
* @dev from malicious interference, it's best if you can write it so that all
* @dev behaviors implied by a VRF response are executed *during* your
* @dev fulfillRandomness method. If your contract must store the response (or
* @dev anything derived from it) and use it later, you must ensure that any
* @dev user-significant behavior which depends on that stored value cannot be
* @dev manipulated by a subsequent VRF request.
*
* @dev Similarly, both miners and the VRF oracle itself have some influence
* @dev over the order in which VRF responses appear on the blockchain, so if
* @dev your contract could have multiple VRF requests in flight simultaneously,
* @dev you must ensure that the order in which the VRF responses arrive cannot
* @dev be used to manipulate your contract's user-significant behavior.
*
* @dev Since the ultimate input to the VRF is mixed with the block hash of the
* @dev block in which the request is made, user-provided seeds have no impact
* @dev on its economic security properties. They are only included for API
* @dev compatability with previous versions of this contract.
*
* @dev Since the block hash of the block which contains the requestRandomness
* @dev call is mixed into the input to the VRF *last*, a sufficiently powerful
* @dev miner could, in principle, fork the blockchain to evict the block
* @dev containing the request, forcing the request to be included in a
* @dev different block with a different hash, and therefore a different input
* @dev to the VRF. However, such an attack would incur a substantial economic
* @dev cost. This cost scales with the number of blocks the VRF oracle waits
* @dev until it calls responds to a request.
*/
abstract contract VRFConsumerBase is VRFRequestIDBase {
/**
* @notice fulfillRandomness handles the VRF response. Your contract must
* @notice implement it. See "SECURITY CONSIDERATIONS" above for important
* @notice principles to keep in mind when implementing your fulfillRandomness
* @notice method.
*
* @dev VRFConsumerBase expects its subcontracts to have a method with this
* @dev signature, and will call it once it has verified the proof
* @dev associated with the randomness. (It is triggered via a call to
* @dev rawFulfillRandomness, below.)
*
* @param requestId The Id initially returned by requestRandomness
* @param randomness the VRF output
*/
function fulfillRandomness(bytes32 requestId, uint256 randomness) internal virtual;
/**
* @dev In order to keep backwards compatibility we have kept the user
* seed field around. We remove the use of it because given that the blockhash
* enters later, it overrides whatever randomness the used seed provides.
* Given that it adds no security, and can easily lead to misunderstandings,
* we have removed it from usage and can now provide a simpler API.
*/
uint256 private constant USER_SEED_PLACEHOLDER = 0;
/**
* @notice requestRandomness initiates a request for VRF output given _seed
*
* @dev The fulfillRandomness method receives the output, once it's provided
* @dev by the Oracle, and verified by the vrfCoordinator.
*
* @dev The _keyHash must already be registered with the VRFCoordinator, and
* @dev the _fee must exceed the fee specified during registration of the
* @dev _keyHash.
*
* @dev The _seed parameter is vestigial, and is kept only for API
* @dev compatibility with older versions. It can't *hurt* to mix in some of
* @dev your own randomness, here, but it's not necessary because the VRF
* @dev oracle will mix the hash of the block containing your request into the
* @dev VRF seed it ultimately uses.
*
* @param _keyHash ID of public key against which randomness is generated
* @param _fee The amount of LINK to send with the request
*
* @return requestId unique ID for this request
*
* @dev The returned requestId can be used to distinguish responses to
* @dev concurrent requests. It is passed as the first argument to
* @dev fulfillRandomness.
*/
function requestRandomness(bytes32 _keyHash, uint256 _fee) internal returns (bytes32 requestId) {
LINK.transferAndCall(vrfCoordinator, _fee, abi.encode(_keyHash, USER_SEED_PLACEHOLDER));
// This is the seed passed to VRFCoordinator. The oracle will mix this with
// the hash of the block containing this request to obtain the seed/input
// which is finally passed to the VRF cryptographic machinery.
uint256 vRFSeed = makeVRFInputSeed(_keyHash, USER_SEED_PLACEHOLDER, address(this), nonces[_keyHash]);
// nonces[_keyHash] must stay in sync with
// VRFCoordinator.nonces[_keyHash][this], which was incremented by the above
// successful LINK.transferAndCall (in VRFCoordinator.randomnessRequest).
// This provides protection against the user repeating their input seed,
// which would result in a predictable/duplicate output, if multiple such
// requests appeared in the same block.
nonces[_keyHash] = nonces[_keyHash] + 1;
return makeRequestId(_keyHash, vRFSeed);
}
LinkTokenInterface internal immutable LINK;
address private immutable vrfCoordinator;
// Nonces for each VRF key from which randomness has been requested.
//
// Must stay in sync with VRFCoordinator[_keyHash][this]
mapping(bytes32 => uint256) /* keyHash */ /* nonce */
private nonces;
/**
* @param _vrfCoordinator address of VRFCoordinator contract
* @param _link address of LINK token contract
*
* @dev https://docs.chain.link/docs/link-token-contracts
*/
constructor(address _vrfCoordinator, address _link) {
vrfCoordinator = _vrfCoordinator;
LINK = LinkTokenInterface(_link);
}
// rawFulfillRandomness is called by VRFCoordinator when it receives a valid VRF
// proof. rawFulfillRandomness then calls fulfillRandomness, after validating
// the origin of the call
function rawFulfillRandomness(bytes32 requestId, uint256 randomness) external {
require(msg.sender == vrfCoordinator, "Only VRFCoordinator can fulfill");
fulfillRandomness(requestId, randomness);
}
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (utils/Strings.sol)
pragma solidity ^0.8.0;
/**
* @dev String operations.
*/
library Strings {
bytes16 private constant _HEX_SYMBOLS = "0123456789abcdef";
/**
* @dev Converts a `uint256` to its ASCII `string` decimal representation.
*/
function toString(uint256 value) internal pure returns (string memory) {
// Inspired by OraclizeAPI's implementation - MIT licence
// https://github.com/oraclize/ethereum-api/blob/b42146b063c7d6ee1358846c198246239e9360e8/oraclizeAPI_0.4.25.sol
if (value == 0) {
return "0";
}
uint256 temp = value;
uint256 digits;
while (temp != 0) {
digits++;
temp /= 10;
}
bytes memory buffer = new bytes(digits);
while (value != 0) {
digits -= 1;
buffer[digits] = bytes1(uint8(48 + uint256(value % 10)));
value /= 10;
}
return string(buffer);
}
/**
* @dev Converts a `uint256` to its ASCII `string` hexadecimal representation.
*/
function toHexString(uint256 value) internal pure returns (string memory) {
if (value == 0) {
return "0x00";
}
uint256 temp = value;
uint256 length = 0;
while (temp != 0) {
length++;
temp >>= 8;
}
return toHexString(value, length);
}
/**
* @dev Converts a `uint256` to its ASCII `string` hexadecimal representation with fixed length.
*/
function toHexString(uint256 value, uint256 length) internal pure returns (string memory) {
bytes memory buffer = new bytes(2 * length + 2);
buffer[0] = "0";
buffer[1] = "x";
for (uint256 i = 2 * length + 1; i > 1; --i) {
buffer[i] = _HEX_SYMBOLS[value & 0xf];
value >>= 4;
}
require(value == 0, "Strings: hex length insufficient");
return string(buffer);
}
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (token/ERC721/IERC721.sol)
pragma solidity ^0.8.0;
import "../../utils/introspection/IERC165.sol";
/**
* @dev Required interface of an ERC721 compliant contract.
*/
interface IERC721 is IERC165 {
/**
* @dev Emitted when `tokenId` token is transferred from `from` to `to`.
*/
event Transfer(address indexed from, address indexed to, uint256 indexed tokenId);
/**
* @dev Emitted when `owner` enables `approved` to manage the `tokenId` token.
*/
event Approval(address indexed owner, address indexed approved, uint256 indexed tokenId);
/**
* @dev Emitted when `owner` enables or disables (`approved`) `operator` to manage all of its assets.
*/
event ApprovalForAll(address indexed owner, address indexed operator, bool approved);
/**
* @dev Returns the number of tokens in ``owner``'s account.
*/
function balanceOf(address owner) external view returns (uint256 balance);
/**
* @dev Returns the owner of the `tokenId` token.
*
* Requirements:
*
* - `tokenId` must exist.
*/
function ownerOf(uint256 tokenId) external view returns (address owner);
/**
* @dev Safely transfers `tokenId` token from `from` to `to`, checking first that contract recipients
* are aware of the ERC721 protocol to prevent tokens from being forever locked.
*
* Requirements:
*
* - `from` cannot be the zero address.
* - `to` cannot be the zero address.
* - `tokenId` token must exist and be owned by `from`.
* - If the caller is not `from`, it must be have been allowed to move this token by either {approve} or {setApprovalForAll}.
* - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer.
*
* Emits a {Transfer} event.
*/
function safeTransferFrom(
address from,
address to,
uint256 tokenId
) external;
/**
* @dev Transfers `tokenId` token from `from` to `to`.
*
* WARNING: Usage of this method is discouraged, use {safeTransferFrom} whenever possible.
*
* Requirements:
*
* - `from` cannot be the zero address.
* - `to` cannot be the zero address.
* - `tokenId` token must be owned by `from`.
* - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}.
*
* Emits a {Transfer} event.
*/
function transferFrom(
address from,
address to,
uint256 tokenId
) external;
/**
* @dev Gives permission to `to` to transfer `tokenId` token to another account.
* The approval is cleared when the token is transferred.
*
* Only a single account can be approved at a time, so approving the zero address clears previous approvals.
*
* Requirements:
*
* - The caller must own the token or be an approved operator.
* - `tokenId` must exist.
*
* Emits an {Approval} event.
*/
function approve(address to, uint256 tokenId) external;
/**
* @dev Returns the account approved for `tokenId` token.
*
* Requirements:
*
* - `tokenId` must exist.
*/
function getApproved(uint256 tokenId) external view returns (address operator);
/**
* @dev Approve or remove `operator` as an operator for the caller.
* Operators can call {transferFrom} or {safeTransferFrom} for any token owned by the caller.
*
* Requirements:
*
* - The `operator` cannot be the caller.
*
* Emits an {ApprovalForAll} event.
*/
function setApprovalForAll(address operator, bool _approved) external;
/**
* @dev Returns if the `operator` is allowed to manage all of the assets of `owner`.
*
* See {setApprovalForAll}
*/
function isApprovedForAll(address owner, address operator) external view returns (bool);
/**
* @dev Safely transfers `tokenId` token from `from` to `to`.
*
* Requirements:
*
* - `from` cannot be the zero address.
* - `to` cannot be the zero address.
* - `tokenId` token must exist and be owned by `from`.
* - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}.
* - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer.
*
* Emits a {Transfer} event.
*/
function safeTransferFrom(
address from,
address to,
uint256 tokenId,
bytes calldata data
) external;
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (token/ERC721/IERC721Receiver.sol)
pragma solidity ^0.8.0;
/**
* @title ERC721 token receiver interface
* @dev Interface for any contract that wants to support safeTransfers
* from ERC721 asset contracts.
*/
interface IERC721Receiver {
/**
* @dev Whenever an {IERC721} `tokenId` token is transferred to this contract via {IERC721-safeTransferFrom}
* by `operator` from `from`, this function is called.
*
* It must return its Solidity selector to confirm the token transfer.
* If any other value is returned or the interface is not implemented by the recipient, the transfer will be reverted.
*
* The selector can be obtained in Solidity with `IERC721.onERC721Received.selector`.
*/
function onERC721Received(
address operator,
address from,
uint256 tokenId,
bytes calldata data
) external returns (bytes4);
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (token/ERC721/extensions/IERC721Metadata.sol)
pragma solidity ^0.8.0;
import "../IERC721.sol";
/**
* @title ERC-721 Non-Fungible Token Standard, optional metadata extension
* @dev See https://eips.ethereum.org/EIPS/eip-721
*/
interface IERC721Metadata is IERC721 {
/**
* @dev Returns the token collection name.
*/
function name() external view returns (string memory);
/**
* @dev Returns the token collection symbol.
*/
function symbol() external view returns (string memory);
/**
* @dev Returns the Uniform Resource Identifier (URI) for `tokenId` token.
*/
function tokenURI(uint256 tokenId) external view returns (string memory);
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (utils/Address.sol)
pragma solidity ^0.8.0;
/**
* @dev Collection of functions related to the address type
*/
library Address {
/**
* @dev Returns true if `account` is a contract.
*
* [IMPORTANT]
* ====
* It is unsafe to assume that an address for which this function returns
* false is an externally-owned account (EOA) and not a contract.
*
* Among others, `isContract` will return false for the following
* types of addresses:
*
* - an externally-owned account
* - a contract in construction
* - an address where a contract will be created
* - an address where a contract lived, but was destroyed
* ====
*/
function isContract(address account) internal view returns (bool) {
// This method relies on extcodesize, which returns 0 for contracts in
// construction, since the code is only stored at the end of the
// constructor execution.
uint256 size;
assembly {
size := extcodesize(account)
}
return size > 0;
}
/**
* @dev Replacement for Solidity's `transfer`: sends `amount` wei to
* `recipient`, forwarding all available gas and reverting on errors.
*
* https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost
* of certain opcodes, possibly making contracts go over the 2300 gas limit
* imposed by `transfer`, making them unable to receive funds via
* `transfer`. {sendValue} removes this limitation.
*
* https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more].
*
* IMPORTANT: because control is transferred to `recipient`, care must be
* taken to not create reentrancy vulnerabilities. Consider using
* {ReentrancyGuard} or the
* https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern].
*/
function sendValue(address payable recipient, uint256 amount) internal {
require(address(this).balance >= amount, "Address: insufficient balance");
(bool success, ) = recipient.call{value: amount}("");
require(success, "Address: unable to send value, recipient may have reverted");
}
/**
* @dev Performs a Solidity function call using a low level `call`. A
* plain `call` is an unsafe replacement for a function call: use this
* function instead.
*
* If `target` reverts with a revert reason, it is bubbled up by this
* function (like regular Solidity function calls).
*
* Returns the raw returned data. To convert to the expected return value,
* use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`].
*
* 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");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with
* `errorMessage` as a fallback revert reason when `target` reverts.
*
* _Available since v3.1._
*/
function functionCall(
address target,
bytes memory data,
string memory errorMessage
) internal returns (bytes memory) {
return functionCallWithValue(target, data, 0, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but also transferring `value` wei to `target`.
*
* Requirements:
*
* - the calling contract must have an ETH balance of at least `value`.
* - the called Solidity function must be `payable`.
*
* _Available since v3.1._
*/
function functionCallWithValue(
address target,
bytes memory data,
uint256 value
) internal returns (bytes memory) {
return functionCallWithValue(target, data, value, "Address: low-level call with value failed");
}
/**
* @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but
* with `errorMessage` as a fallback revert reason when `target` reverts.
*
* _Available since v3.1._
*/
function functionCallWithValue(
address target,
bytes memory data,
uint256 value,
string memory errorMessage
) internal returns (bytes memory) {
require(address(this).balance >= value, "Address: insufficient balance for call");
require(isContract(target), "Address: call to non-contract");
(bool success, bytes memory returndata) = target.call{value: value}(data);
return verifyCallResult(success, returndata, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but performing a static call.
*
* _Available since v3.3._
*/
function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) {
return functionStaticCall(target, data, "Address: low-level static call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`],
* but performing a static call.
*
* _Available since v3.3._
*/
function functionStaticCall(
address target,
bytes memory data,
string memory errorMessage
) internal view returns (bytes memory) {
require(isContract(target), "Address: static call to non-contract");
(bool success, bytes memory returndata) = target.staticcall(data);
return verifyCallResult(success, returndata, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but performing a delegate call.
*
* _Available since v3.4._
*/
function functionDelegateCall(address target, bytes memory data) internal returns (bytes memory) {
return functionDelegateCall(target, data, "Address: low-level delegate call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`],
* but performing a delegate call.
*
* _Available since v3.4._
*/
function functionDelegateCall(
address target,
bytes memory data,
string memory errorMessage
) internal returns (bytes memory) {
require(isContract(target), "Address: delegate call to non-contract");
(bool success, bytes memory returndata) = target.delegatecall(data);
return verifyCallResult(success, returndata, errorMessage);
}
/**
* @dev Tool to verifies that a low level call was successful, and revert if it wasn't, either by bubbling the
* revert reason using the provided one.
*
* _Available since v4.3._
*/
function verifyCallResult(
bool success,
bytes memory returndata,
string memory errorMessage
) internal pure returns (bytes memory) {
if (success) {
return returndata;
} else {
// Look for revert reason and bubble it up if present
if (returndata.length > 0) {
// The easiest way to bubble the revert reason is using memory via assembly
assembly {
let returndata_size := mload(returndata)
revert(add(32, returndata), returndata_size)
}
} else {
revert(errorMessage);
}
}
}
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (utils/Context.sol)
pragma solidity ^0.8.0;
/**
* @dev Provides information about the current execution context, including the
* sender of the transaction and its data. While these are generally available
* via msg.sender and msg.data, they should not be accessed in such a direct
* manner, since when dealing with meta-transactions the account sending and
* paying for execution may not be the actual sender (as far as an application
* is concerned).
*
* This contract is only required for intermediate, library-like contracts.
*/
abstract contract Context {
function _msgSender() internal view virtual returns (address) {
return msg.sender;
}
function _msgData() internal view virtual returns (bytes calldata) {
return msg.data;
}
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (utils/introspection/ERC165.sol)
pragma solidity ^0.8.0;
import "./IERC165.sol";
/**
* @dev Implementation of the {IERC165} interface.
*
* Contracts that want to implement ERC165 should inherit from this contract and override {supportsInterface} to check
* for the additional interface id that will be supported. For example:
*
* ```solidity
* function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) {
* return interfaceId == type(MyInterface).interfaceId || super.supportsInterface(interfaceId);
* }
* ```
*
* Alternatively, {ERC165Storage} provides an easier to use but more expensive implementation.
*/
abstract contract ERC165 is IERC165 {
/**
* @dev See {IERC165-supportsInterface}.
*/
function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) {
return interfaceId == type(IERC165).interfaceId;
}
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (utils/introspection/IERC165.sol)
pragma solidity ^0.8.0;
/**
* @dev Interface of the ERC165 standard, as defined in the
* https://eips.ethereum.org/EIPS/eip-165[EIP].
*
* Implementers can declare support of contract interfaces, which can then be
* queried by others ({ERC165Checker}).
*
* For an implementation, see {ERC165}.
*/
interface IERC165 {
/**
* @dev Returns true if this contract implements the interface defined by
* `interfaceId`. See the corresponding
* https://eips.ethereum.org/EIPS/eip-165#how-interfaces-are-identified[EIP section]
* to learn more about how these ids are created.
*
* This function call must use less than 30 000 gas.
*/
function supportsInterface(bytes4 interfaceId) external view returns (bool);
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
interface LinkTokenInterface {
function allowance(address owner, address spender) external view returns (uint256 remaining);
function approve(address spender, uint256 value) external returns (bool success);
function balanceOf(address owner) external view returns (uint256 balance);
function decimals() external view returns (uint8 decimalPlaces);
function decreaseApproval(address spender, uint256 addedValue) external returns (bool success);
function increaseApproval(address spender, uint256 subtractedValue) external;
function name() external view returns (string memory tokenName);
function symbol() external view returns (string memory tokenSymbol);
function totalSupply() external view returns (uint256 totalTokensIssued);
function transfer(address to, uint256 value) external returns (bool success);
function transferAndCall(
address to,
uint256 value,
bytes calldata data
) external returns (bool success);
function transferFrom(
address from,
address to,
uint256 value
) external returns (bool success);
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
contract VRFRequestIDBase {
/**
* @notice returns the seed which is actually input to the VRF coordinator
*
* @dev To prevent repetition of VRF output due to repetition of the
* @dev user-supplied seed, that seed is combined in a hash with the
* @dev user-specific nonce, and the address of the consuming contract. The
* @dev risk of repetition is mostly mitigated by inclusion of a blockhash in
* @dev the final seed, but the nonce does protect against repetition in
* @dev requests which are included in a single block.
*
* @param _userSeed VRF seed input provided by user
* @param _requester Address of the requesting contract
* @param _nonce User-specific nonce at the time of the request
*/
function makeVRFInputSeed(
bytes32 _keyHash,
uint256 _userSeed,
address _requester,
uint256 _nonce
) internal pure returns (uint256) {
return uint256(keccak256(abi.encode(_keyHash, _userSeed, _requester, _nonce)));
}
/**
* @notice Returns the id for this request
* @param _keyHash The serviceAgreement ID to be used for this request
* @param _vRFInputSeed The seed to be passed directly to the VRF
* @return The id for this request
*
* @dev Note that _vRFInputSeed is not the seed passed by the consuming
* @dev contract, but the one generated by makeVRFInputSeed
*/
function makeRequestId(bytes32 _keyHash, uint256 _vRFInputSeed) internal pure returns (bytes32) {
return keccak256(abi.encodePacked(_keyHash, _vRFInputSeed));
}
}
|
======== Verify Coupon =========
|
function isVerifiedCoupon(bytes32 digest_, Coupon memory coupon_) internal view returns (bool) {
address signer = ecrecover(digest_, coupon_.v, coupon_.r, coupon_.s);
require(signer != address(0), 'ECDSA: invalid signature');
return signer == ownerSigner;
}
| 614,612 |
// SPDX-License-Identifier: MIT
pragma solidity 0.7.6;
pragma experimental ABIEncoderV2;
import "../libs/Ownable.sol";
import "./ERC20ForwarderStorage.sol";
import "@openzeppelin/contracts/token/ERC20/IERC20.sol";
import "@openzeppelin/contracts/token/ERC20/SafeERC20.sol";
import "@openzeppelin/contracts/math/SafeMath.sol";
import "../interfaces/IFeeManager.sol";
import "./BiconomyForwarder.sol";
import "../interfaces/IERC20Permit.sol";
/**
* @title ERC20 Forwarder
*
* @notice A contract for dApps to coordinate meta transactions paid for with ERC20 transfers
* @notice This contract is upgradeable and using using unstructured proxy pattern.
* https://blog.openzeppelin.com/proxy-patterns/
* Users always interact with Proxy contract (storage layer) - ERC20ForwarderProxy.sol
* @dev Inherits the ERC20ForwarderRequest struct from Storage contract (using same storage contract inherited by Proxy to avoid storage collisions) - essential for compatibility with The BiconomyForwarder
* @dev Tx Flow : calls BiconomyForwarder to handle forwarding, call _transferHandler() to charge fee after
*
*/
contract ERC20Forwarder is Ownable, ERC20ForwarderStorage{
using SafeMath for uint256;
bool internal initialized;
constructor(
address _owner
) public Ownable(_owner){
require(_owner != address(0), "Owner Address cannot be 0");
}
/**
* @dev sets contract variables
*
* @param _feeReceiver : address that will receive fees charged in ERC20 tokens
* @param _feeManager : the address of the contract that controls the charging of fees
* @param _forwarder : the address of the BiconomyForwarder contract
*
*/
function initialize(
address _feeReceiver,
address _feeManager,
address payable _forwarder
) public {
require(!initialized, "ERC20 Forwarder: contract is already initialized");
require(
_feeReceiver != address(0),
"ERC20Forwarder: new fee receiver is the zero address"
);
require(
_feeManager != address(0),
"ERC20Forwarder: new fee manager is the zero address"
);
require(
_forwarder != address(0),
"ERC20Forwarder: new forwarder is the zero address"
);
initialized = true;
feeReceiver = _feeReceiver;
feeManager = _feeManager;
forwarder = _forwarder;
}
function setOracleAggregator(address oa) external onlyOwner{
require(
oa != address(0),
"ERC20Forwarder: new oracle aggregator can not be a zero address"
);
oracleAggregator = oa;
emit OracleAggregatorChanged(oracleAggregator, msg.sender);
}
function setTrustedForwarder(address payable _forwarder) external onlyOwner {
require(
_forwarder != address(0),
"ERC20Forwarder: new trusted forwarder can not be a zero address"
);
forwarder = _forwarder;
emit TrustedForwarderChanged(forwarder, msg.sender);
}
/**
* @dev enable dApps to change fee receiver addresses, e.g. for rotating keys/security purposes
* @param _feeReceiver : address that will receive fees charged in ERC20 tokens */
function setFeeReceiver(address _feeReceiver) external onlyOwner{
require(
_feeReceiver != address(0),
"ERC20Forwarder: new fee receiver can not be a zero address"
);
feeReceiver = _feeReceiver;
}
/**
* @dev enable dApps to change the contract that manages fee collection logic
* @param _feeManager : the address of the contract that controls the charging of fees */
function setFeeManager(address _feeManager) external onlyOwner{
require(
_feeManager != address(0),
"ERC20Forwarder: new fee manager can not be a zero address"
);
feeManager = _feeManager;
}
function setBaseGas(uint128 gas) external onlyOwner{
baseGas = gas;
emit BaseGasChanged(baseGas,msg.sender);
}
function setGasRefund(uint128 refund) external onlyOwner{
gasRefund = refund;
emit GasRefundChanged(gasRefund,msg.sender);
}
function setGasTokenForwarderBaseGas(uint128 gas) external onlyOwner{
gasTokenForwarderBaseGas = gas;
emit GasTokenForwarderBaseGasChanged(gasTokenForwarderBaseGas,msg.sender);
}
/**
* Designed to enable the community to track change in storage variable forwarder which is used
* as a trusted forwarder contract where signature verifiction and replay attack prevention schemes are
* deployed.
*/
event TrustedForwarderChanged(address indexed newForwarderAddress, address indexed actor);
/**
* Designed to enable the community to track change in storage variable oracleAggregator which is used
* as a oracle aggregator contract where different feeds are aggregated
*/
event OracleAggregatorChanged(address indexed newOracleAggregatorAddress, address indexed actor);
/* Designed to enable the community to track change in storage variable baseGas which is used for charge calcuations
Unlikely to change */
event BaseGasChanged(uint128 newBaseGas, address indexed actor);
/* Designed to enable the community to track change in storage variable transfer handler gas for particular ERC20 token which is used for charge calculations
Only likely to change to offset the charged fee */
event TransferHandlerGasChanged(address indexed tokenAddress, address indexed actor, uint256 indexed newGas);
/* Designed to enable the community to track change in refundGas which is used to benefit users when gas tokens are burned
Likely to change in the event of offsetting Biconomy's cost OR when new gas tokens are used */
event GasRefundChanged(uint128 newGasRefund, address indexed actor);
/* Designed to enable the community to track change in gas token forwarder base gas which is Biconomy's cost when gas tokens are burned for refund
Likely to change in the event of offsetting Biconomy's cost OR when new gas token forwarder is used */
event GasTokenForwarderBaseGasChanged(uint128 newGasTokenForwarderBaseGas, address indexed actor);
/**
* @dev change amount of excess gas charged for _transferHandler
* NOT INTENTED TO BE CALLED : may need to be called if :
* - new feeManager consumes more/less gas
* - token contract is upgraded to consume less gas
* - etc
*/
/// @param _transferHandlerGas : max amount of gas the function _transferHandler is expected to use
function setTransferHandlerGas(address token, uint256 _transferHandlerGas) external onlyOwner{
require(
token != address(0),
"token cannot be zero"
);
transferHandlerGas[token] = _transferHandlerGas;
emit TransferHandlerGasChanged(token,msg.sender,_transferHandlerGas);
}
function setSafeTransferRequired(address token, bool _safeTransferRequired) external onlyOwner{
require(
token != address(0),
"token cannot be zero"
);
safeTransferRequired[token] = _safeTransferRequired;
}
/**
* @dev calls the getNonce function of the BiconomyForwarder
* @param from : the user address
* @param batchId : the key of the user's batch being queried
* @return nonce : the number of transaction made within said batch
*/
function getNonce(address from, uint256 batchId)
external view
returns(uint256 nonce){
nonce = BiconomyForwarder(forwarder).getNonce(from,batchId);
}
/**
* @dev
* - Keeps track of gas consumed
* - Calls BiconomyForwarder.executeEIP712 method using arguments given
* - Calls _transferHandler, supplying the gas usage of the executeEIP712 call
*/
/**
* @param req : the request being forwarded
* @param domainSeparator : the domain separator presented to the user when signing
* @param sig : the signature generated by the user's wallet
* @return success : false if call fails. true otherwise
* @return ret : any return data from the call
*/
function executeEIP712(
ERC20ForwardRequest calldata req,
bytes32 domainSeparator,
bytes calldata sig
)
external
returns (bool success, bytes memory ret){
uint256 initialGas = gasleft();
(success,ret) = BiconomyForwarder(forwarder).executeEIP712(req,domainSeparator,sig);
uint256 postGas = gasleft();
uint256 transferHandlerGas = transferHandlerGas[req.token];
uint256 charge = _transferHandler(req,initialGas.add(baseGas).add(transferHandlerGas).sub(postGas));
emit FeeCharged(req.from,charge,req.token);
}
/**
* @dev
* - calls permit method on the underlying ERC20 token contract (DAI permit type) with given permit options
* - Keeps track of gas consumed
* - Calls BiconomyForwarder.executeEIP712 method using arguments given
* - Calls _transferHandler, supplying the gas usage of the executeEIP712 call
*/
/**
* @param req : the request being forwarded
* @param domainSeparator : the domain separator presented to the user when signing
* @param sig : the signature generated by the user's wallet
* @param permitOptions : the permit request options for executing permit. Since it is not EIP2612 permit pass permitOptions.value = 0 for this struct.
* @return success : false if call fails. true otherwise
* @return ret : any return data from the call
*/
function permitAndExecuteEIP712(
ERC20ForwardRequest calldata req,
bytes32 domainSeparator,
bytes calldata sig,
PermitRequest calldata permitOptions
)
external
returns (bool success, bytes memory ret){
uint256 initialGas = gasleft();
(success,ret) = BiconomyForwarder(forwarder).executeEIP712(req,domainSeparator,sig);
//DAI permit
IERC20Permit(req.token).permit(permitOptions.holder, permitOptions.spender, permitOptions.nonce, permitOptions.expiry, permitOptions.allowed, permitOptions.v, permitOptions.r, permitOptions.s);
uint256 postGas = gasleft();
uint256 transferHandlerGas = transferHandlerGas[req.token];
uint256 charge = _transferHandler(req,initialGas.add(baseGas).add(transferHandlerGas).sub(postGas));
emit FeeCharged(req.from,charge,req.token);
}
/**
* @dev
* - calls permit method on the underlying ERC20 token contract (which supports EIP2612 permit) with given permit options
* - Keeps track of gas consumed
* - Calls BiconomyForwarder.executeEIP712 method using arguments given
* - Calls _transferHandler, supplying the gas usage of the executeEIP712 call
*/
/**
* @param req : the request being forwarded
* @param domainSeparator : the domain separator presented to the user when signing
* @param sig : the signature generated by the user's wallet
* @param permitOptions : the permit request options for executing permit. Since it is EIP2612 permit pass permitOptions.allowed = true/false for this struct.
* @return success : false if call fails. true otherwise
* @return ret : any return data from the call
*/
function permitEIP2612AndExecuteEIP712(
ERC20ForwardRequest calldata req,
bytes32 domainSeparator,
bytes calldata sig,
PermitRequest calldata permitOptions
)
external
returns (bool success, bytes memory ret){
uint256 initialGas = gasleft();
(success,ret) = BiconomyForwarder(forwarder).executeEIP712(req,domainSeparator,sig);
//USDC or any EIP2612 permit
IERC20Permit(req.token).permit(permitOptions.holder, permitOptions.spender, permitOptions.value, permitOptions.expiry, permitOptions.v, permitOptions.r, permitOptions.s);
uint256 postGas = gasleft();
uint256 transferHandlerGas = transferHandlerGas[req.token];
uint256 charge = _transferHandler(req,initialGas.add(baseGas).add(transferHandlerGas).sub(postGas));
emit FeeCharged(req.from,charge,req.token);
}
/**
* @dev
* - Keeps track of gas consumed
* - Calls BiconomyForwarder.executeEIP712 method using arguments given
* - Calls _transferHandler, supplying the gas usage of the executeEIP712 call
* * NOT INTENTED TO BE CALLED : may need to be called by Biconomy Relayers
*/
/**
* @param req : the request being forwarded
* @param domainSeparator : the domain separator presented to the user when signing
* @param sig : the signature generated by the user's wallet
* @param gasTokensBurned : number of gas tokens to be burned in this transaction
* @return success : false if call fails. true otherwise
* @return ret : any return data from the call
*/
function executeEIP712WithGasTokens(
ERC20ForwardRequest calldata req,
bytes32 domainSeparator,
bytes calldata sig,
uint256 gasTokensBurned
)
external
returns (bool success, bytes memory ret){
uint256 initialGas = gasleft();
(success,ret) = BiconomyForwarder(forwarder).executeEIP712(req,domainSeparator,sig);
uint256 postGas = gasleft();
uint256 transferHandlerGas = transferHandlerGas[req.token];
uint256 charge = _transferHandler(req,initialGas.add(baseGas).add(gasTokenForwarderBaseGas).add(transferHandlerGas).sub(postGas).sub(gasTokensBurned.mul(gasRefund)));
emit FeeCharged(req.from,charge,req.token);
}
/**
* @dev
* - calls permit method on the underlying ERC20 token contract (DAI permit type) with given permit options
* - Keeps track of gas consumed
* - Calls BiconomyForwarder.executeEIP712 method using arguments given
* - Calls _transferHandler, supplying the gas usage of the executeEIP712 call
* * NOT INTENTED TO BE CALLED : may need to be called by Biconomy Relayers
*/
/**
* @param req : the request being forwarded
* @param domainSeparator : the domain separator presented to the user when signing
* @param sig : the signature generated by the user's wallet
* @param gasTokensBurned : number of gas tokens to be burned in this transaction
* @param permitOptions : the permit request options for executing permit. Since it is not EIP2612 permit pass permitOptions.value = 0 for this struct.
* @return success : false if call fails. true otherwise
* @return ret : any return data from the call
*/
function permitAndExecuteEIP712WithGasTokens(
ERC20ForwardRequest calldata req,
bytes32 domainSeparator,
bytes calldata sig,
PermitRequest calldata permitOptions,
uint256 gasTokensBurned
)
external
returns (bool success, bytes memory ret){
uint256 initialGas = gasleft();
(success,ret) = BiconomyForwarder(forwarder).executeEIP712(req,domainSeparator,sig);
//DAI Permit
IERC20Permit(req.token).permit(permitOptions.holder, permitOptions.spender, permitOptions.nonce, permitOptions.expiry, permitOptions.allowed, permitOptions.v, permitOptions.r, permitOptions.s);
uint256 postGas = gasleft();
uint256 transferHandlerGas = transferHandlerGas[req.token];
uint256 charge = _transferHandler(req,initialGas.add(baseGas).add(gasTokenForwarderBaseGas).add(transferHandlerGas).sub(postGas).sub(gasTokensBurned.mul(gasRefund)));
emit FeeCharged(req.from,charge,req.token);
}
/**
* @dev
* - calls permit method on the underlying ERC20 token contract (which supports EIP2612 permit) with given permit options
* - Keeps track of gas consumed
* - Calls BiconomyForwarder.executeEIP712 method using arguments given
* - Calls _transferHandler, supplying the gas usage of the executeEIP712 call
* * NOT INTENTED TO BE CALLED : may need to be called by Biconomy Relayers
*/
/**
* @param req : the request being forwarded
* @param domainSeparator : the domain separator presented to the user when signing
* @param sig : the signature generated by the user's wallet
* @param gasTokensBurned : number of gas tokens to be burned in this transaction
* @param permitOptions : the permit request options for executing permit. Since it is EIP2612 permit pass permitOptions.allowed = true/false for this struct.
* @return success : false if call fails. true otherwise
* @return ret : any return data from the call
*/
function permitEIP2612AndExecuteEIP712WithGasTokens(
ERC20ForwardRequest calldata req,
bytes32 domainSeparator,
bytes calldata sig,
PermitRequest calldata permitOptions,
uint256 gasTokensBurned
)
external
returns (bool success, bytes memory ret){
uint256 initialGas = gasleft();
(success,ret) = BiconomyForwarder(forwarder).executeEIP712(req,domainSeparator,sig);
//EIP2612 Permit
IERC20Permit(req.token).permit(permitOptions.holder, permitOptions.spender, permitOptions.value, permitOptions.expiry, permitOptions.v, permitOptions.r, permitOptions.s);
uint256 postGas = gasleft();
uint256 transferHandlerGas = transferHandlerGas[req.token];
uint256 charge = _transferHandler(req,initialGas.add(baseGas).add(gasTokenForwarderBaseGas).add(transferHandlerGas).sub(postGas).sub(gasTokensBurned.mul(gasRefund)));
emit FeeCharged(req.from,charge,req.token);
}
/**
* @dev
* - Keeps track of gas consumed
* - Calls BiconomyForwarder.executePersonalSign method using arguments given
* - Calls _transferHandler, supplying the gas usage of the executePersonalSign call
**/
/**
* @param req : the request being forwarded
* @param sig : the signature generated by the user's wallet
* @return success : false if call fails. true otherwise
* @return ret : any return data from the call
*/
function executePersonalSign(
ERC20ForwardRequest calldata req,
bytes calldata sig
)
external
returns (bool success, bytes memory ret){
uint256 initialGas = gasleft();
(success,ret) = BiconomyForwarder(forwarder).executePersonalSign(req,sig);
uint256 postGas = gasleft();
uint256 transferHandlerGas = transferHandlerGas[req.token];
uint256 charge = _transferHandler(req,initialGas.add(baseGas).add(transferHandlerGas).sub(postGas));
emit FeeCharged(req.from,charge,req.token);
}
/**
* @dev
* - Keeps track of gas consumed
* - Calls BiconomyForwarder.executePersonalSign method using arguments given
* - Calls _transferHandler, supplying the gas usage of the executePersonalSign call
* NOT INTENTED TO BE CALLED : may need to be called by Biconomy Relayers
**/
/**
* @param req : the request being forwarded
* @param sig : the signature generated by the user's wallet
* @param gasTokensBurned : number of gas tokens to be burned in this transaction
* @return success : false if call fails. true otherwise
* @return ret : any return data from the call
*/
function executePersonalSignWithGasTokens(
ERC20ForwardRequest calldata req,
bytes calldata sig,
uint256 gasTokensBurned
)
external
returns (bool success, bytes memory ret){
uint256 initialGas = gasleft();
(success,ret) = BiconomyForwarder(forwarder).executePersonalSign(req,sig);
uint256 postGas = gasleft();
uint256 transferHandlerGas = transferHandlerGas[req.token];
uint256 charge = _transferHandler(req,initialGas.add(baseGas).add(gasTokenForwarderBaseGas).add(transferHandlerGas).sub(postGas).sub(gasTokensBurned.mul(gasRefund)));
emit FeeCharged(req.from,charge,req.token);
}
// Designed to enable capturing token fees charged during the execution
event FeeCharged(address indexed from, uint256 indexed charge, address indexed token);
/**
* @dev
* - Verifies if token supplied in request is allowed
* - Transfers tokenGasPrice*totalGas*feeMultiplier $req.token, from req.to to feeReceiver
**/
/**
* @param req : the request being forwarded
* @param executionGas : amount of gas used to execute the forwarded request call
*/
function _transferHandler(ERC20ForwardRequest calldata req,uint256 executionGas) internal returns(uint256 charge){
IFeeManager _feeManager = IFeeManager(feeManager);
require(_feeManager.getTokenAllowed(req.token),"TOKEN NOT ALLOWED BY FEE MANAGER");
charge = req.tokenGasPrice.mul(executionGas).mul(_feeManager.getFeeMultiplier(req.from,req.token)).div(10000);
if (!safeTransferRequired[req.token]){
require(IERC20(req.token).transferFrom(
req.from,
feeReceiver,
charge));
}
else{
SafeERC20.safeTransferFrom(IERC20(req.token), req.from,feeReceiver,charge);
}
}
}
|
- calls permit method on the underlying ERC20 token contract (which supports EIP2612 permit) with given permit options - Keeps track of gas consumed - Calls BiconomyForwarder.executeEIP712 method using arguments given - Calls _transferHandler, supplying the gas usage of the executeEIP712 call/ req : the request being forwarded domainSeparator : the domain separator presented to the user when signing sig : the signature generated by the user's wallet permitOptions : the permit request options for executing permit. Since it is EIP2612 permit pass permitOptions.allowed = true/false for this struct. return success : false if call fails. true otherwise return ret : any return data from the call/USDC or any EIP2612 permit
|
function permitEIP2612AndExecuteEIP712(
ERC20ForwardRequest calldata req,
bytes32 domainSeparator,
bytes calldata sig,
PermitRequest calldata permitOptions
)
external
returns (bool success, bytes memory ret){
uint256 initialGas = gasleft();
(success,ret) = BiconomyForwarder(forwarder).executeEIP712(req,domainSeparator,sig);
IERC20Permit(req.token).permit(permitOptions.holder, permitOptions.spender, permitOptions.value, permitOptions.expiry, permitOptions.v, permitOptions.r, permitOptions.s);
uint256 postGas = gasleft();
uint256 transferHandlerGas = transferHandlerGas[req.token];
uint256 charge = _transferHandler(req,initialGas.add(baseGas).add(transferHandlerGas).sub(postGas));
emit FeeCharged(req.from,charge,req.token);
}
| 14,015,580 |
pragma solidity ^0.4.11;
import "./SafeMath.sol";
import "./Halt.sol";
contract StoremanGroupAdmin is Halt {
using SafeMath for uint;
///smg storeman group
///coin:smg address:balance
uint public constant USE_CONTRACT = 0;
uint public constant USE_SCRIPT = 1;
uint public constant DEFAULT_PRECISE = 10000;
///one days blocks
uint public constant DEFAULT_BONUS_PERIOD_BLOCKS = 6 * 60 * 24;
uint public constant DEFAULT_BONUS_RATIO_FOR_DEPOSIT = 20;
struct CoinInfo {
uint coin2WanRatio; //1 coin to WANs,such as ethereum 880*DEFAULT_PRECISE
uint defaultMinDeposit; //the minimum deposit for storeman group
uint htlcType; //the htlc type,possible value USE_CONTRACT,USE_SCRIPT
bytes originalChainHtlc; //the original chain htlc address if use contract
address wanchainHtlc; //the htlc address on wanchain
address wanchainTokenManager; //the token administrator contract address
uint withdrawDelayTime; //the delay time for withdrawing deposit after storeman group apply exit
bool useWhiteList; //the flag for checking if the storeman group address is in white list if the storeman register is controlled
uint startBonusBlk; //the begin blk for bonus
uint bonusTotal; //the total bonus provided by system
uint bonusPeriodBlks; //the bonus period
uint bonusRatio; //the bonus ratio
}
struct StoremanGroup {
uint deposit; //the storeman group deposit
bytes originalChainAddr; //the account for storeman group on original chain
uint unregisterApplyTime;//the time for storeman group applied exit
uint txFeeRatio; //the fee ratio required by storeman group
uint bonusBlockNumber; //the start block number for bonus calculation for storeman group
address initiator; //the account for registering a storeman group which provide storeman group deposit
uint punishPercent; //punish percent of deposit
}
mapping (uint=>CoinInfo) public mapCoinInfo; //the information for storing different cross chain coin
mapping (uint=>mapping(address => StoremanGroup)) public mapCoinSmgInfo; //the storeman group info
mapping (uint=>mapping(address => bool)) public mapSmgWhiteList; //the white list
/// @notice event for initializing coin
/// @param coin coin name id
/// @param ratio coin Exchange ratio,such as ethereum 1 eth:880 WANs,the precise is 10000,the ratio is 880,0000
/// @param defaultMinDeposit the default min deposit
/// @param htlcType the coin support htlc trade type
/// @param originalChainHtlc the original chain address if the chain support contract address
/// @param wanchainHtlcAddr the htlc contract address on wanchain
/// @param wanchainTokenManagerAddr the token manager address for coin on wanchain
/// @param withdrawDelayTime storeman unregister delay time
event SmginitializeCoin(uint indexed coin,uint indexed ratio,uint indexed defaultMinDeposit, uint htlcType,bytes originalChainHtlc,address wanchainHtlcAddr,address wanchainTokenManagerAddr,uint withdrawDelayTime);
/// @notice event for storeman register
/// @param smgAddress storeman address
/// @param smgOriginalChainAddress storeman group original chain address
/// @param coin coin name
/// @param wancoin deposit wancoin number
/// @param tokenQuota corresponding token quota
/// @param txFeeratio storeman fee ratio
event SmgRegister(address indexed smgAddress,bytes smgOriginalChainAddress,uint indexed coin,uint wancoin, uint tokenQuota,uint txFeeratio);
/// @notice event for storeman register
/// @param sender sender for bonus
/// @param coin coin name
/// @param wancoin deposit wancoin number
event SmgDepositBonus(address indexed sender,uint indexed coin,uint wancoin);
/// @notice event for storeman register
/// @param smgAddress storeman address
/// @param coin coin name
event SmgWhiteList(address indexed smgAddress,uint indexed coin);
/// @notice event for the htlc address on original chain event
/// @param smgAddress storeman address
/// @param coin coin name
/// @param orgSCAddr the htlc address on original chain
event SmgSetOrigSC(address indexed smgAddress,uint indexed coin,bytes indexed orgSCAddr);
/// @notice event for the htlc address on wan chain
/// @param smgAddress storeman address
/// @param coin coin name
/// @param proxySCAddr the htlc address on wan chain
event SmgSetProxySC(address indexed smgAddress,uint indexed coin,address indexed proxySCAddr);
/// @notice event for applying storeman group unregister
/// @param smgAddress storeman address
/// @param coin coin name
/// @param applyTime the time for storeman applying unregister
event SmgApplyUnRegister(address indexed smgAddress,uint indexed coin,uint indexed applyTime);
/// @notice event for storeman group withdraw deposit
/// @param smgAddress storeman address
/// @param coin coin name
/// @param withdrawTime the time for storeman applying unregister
event SmgWithdraw(address indexed smgAddress,uint indexed coin,uint indexed withdrawTime);
/// @notice event for storeman group claiming system bonus
/// @param smgAddress storeman address
/// @param coin coin name
/// @param bonus the bonus for storeman claim
event SmgClaimSystemBonus(address indexed smgAddress,uint indexed coin,uint indexed bonus);
/// @notice event for storeman group be punished
/// @param smgAddress storeman address
/// @param coin coin name
/// @param punishPercent punish percent of deposit
event SmgPunished(address indexed smgAddress,uint indexed coin,uint indexed punishPercent);
/**
*
* MODIFIERS
*
*/
/// @notice modifier for checking if contract is initialized
/// @param coin coin name
modifier initialized(uint coin) {
CoinInfo storage info = mapCoinInfo[coin];
require(info.coin2WanRatio != 0);
require(info.wanchainTokenManager != address(0));
require(info.wanchainHtlc != address(0));
if(info.htlcType == USE_CONTRACT) {
require(info.originalChainHtlc.length != 0x0);
}
_;
}
/**
*
* MANIPULATIONS
*
*/
/// @notice default tranfer to contract
function () public payable {
revert();
}
/// @notice event for initializing coin
/// @param coin coin name id
/// @param ratio coin Exchange ratio,such as ethereum 1 eth:880 WANs,the precise is 10000,the ratio is 880,0000
/// @param defaultMinDeposit the default min deposit
/// @param htlcType the coin support htlc trade type
/// @param originalChainHtlc the original chain address if the chain support contract address
/// @param wanchainHtlcAddr the htlc contract address on wanchain
/// @param wanchainTokenManagerAddr the token manager address for coin on wanchain
/// @param withdrawDelayTime storeman unregister delay time
function initializeCoin(uint coin,
uint ratio,
uint defaultMinDeposit,
uint htlcType,
bytes originalChainHtlc,
address wanchainHtlcAddr,
address wanchainTokenManagerAddr,
uint withdrawDelayTime)
public
onlyOwner
isHalted
{
require(mapCoinInfo[coin].coin2WanRatio == 0);
require(ratio > 0);
require(defaultMinDeposit >= 10 ether);
require(htlcType==USE_CONTRACT || htlcType==USE_SCRIPT);
require(wanchainHtlcAddr != address(0));
require(wanchainTokenManagerAddr != address(0));
require(withdrawDelayTime >= 3600*72);
if(htlcType == USE_CONTRACT) {
require(originalChainHtlc.length != 0);
}
mapCoinInfo[coin] = CoinInfo(ratio,defaultMinDeposit,htlcType,originalChainHtlc,wanchainHtlcAddr,wanchainTokenManagerAddr,withdrawDelayTime,true,0,0,DEFAULT_BONUS_PERIOD_BLOCKS,DEFAULT_BONUS_RATIO_FOR_DEPOSIT);
emit SmginitializeCoin(coin,ratio,defaultMinDeposit,htlcType,originalChainHtlc,wanchainHtlcAddr,wanchainTokenManagerAddr,withdrawDelayTime);
}
/// @notice function for setting the Exchange ration for mint token
/// @param coin coin name
// @param ratio the Exchange ratio between ETH and WAN or between BTC ,such as ethereum 1 eth:880 WANs,the precise is 10000,the ratio is 880,0000
function setWToken2WanRatio(uint coin,uint ratio)
public
onlyOwner
isHalted
initialized(coin)
{
require(ratio > 0);
mapCoinInfo[coin].coin2WanRatio = ratio;
}
/// @notice function for setting bonus ratio
/// @param coin coin name
/// @param ratio the bonus ratio,the ratio need to muliple preicise,such as ratio is 2/1000,the value is 2/1000*10000
function setSystemBonusRatio(uint coin,uint ratio)
public
onlyOwner
isHalted
initialized(coin)
{
require(ratio > 0);
require(ratio <= DEFAULT_PRECISE);
mapCoinInfo[coin].bonusRatio = ratio;
}
/// @notice function for setting the delay time from the time to
/// @param coin coin id value
// @param delayTime the delay time from time for applying unregister to
function setWithdrawDepositDelayTime(uint coin,uint delayTime)
public
onlyOwner
isHalted
initialized(coin)
{
require(delayTime > 0);
mapCoinInfo[coin].withdrawDelayTime = delayTime;
}
/// @notice function for setting current system BonusPeriod
/// @param coin coin name
/// @param isSystemBonusPeriod smg isSystemBonusPeriod,true controlled by foundation,false register freely
/// @param systemBonusPeriod Bonus Period in blocks
function setSystemEnableBonus(uint coin, bool isSystemBonusPeriod,uint systemBonusPeriod)
public
onlyOwner
isHalted
initialized(coin)
{
CoinInfo storage coinInfo = mapCoinInfo[coin];
if(isSystemBonusPeriod){
coinInfo.startBonusBlk = block.number;
coinInfo.bonusPeriodBlks = systemBonusPeriod>0?systemBonusPeriod:DEFAULT_BONUS_PERIOD_BLOCKS;
} else {
coinInfo.startBonusBlk = 0;
coinInfo.bonusPeriodBlks = DEFAULT_BONUS_PERIOD_BLOCKS;
}
}
/// @notice function for setting smg registering mode,control by foundation or registering freely
/// @param coin coin name
// @param enableUserWhiteList smg register mode,true controlled by foundation with white list,false register freely
function setSmgEnableUserWhiteList(uint coin,bool enableUserWhiteList)
public
onlyOwner
isHalted
initialized(coin)
{
mapCoinInfo[coin].useWhiteList = enableUserWhiteList;
}
/// @notice function for storeman register
/// @param coin coin name
/// @param originalChainAddr the htlc info on original chain
/// @param txFeeRatio the transaction fee required by storeman group
function storemanGroupRegister(uint coin,bytes originalChainAddr,uint txFeeRatio)
public
payable
initialized(coin)
notHalted
{
storemanGroupRegisterByDelegate(coin,msg.sender,originalChainAddr,txFeeRatio);
}
/// @notice function for storeman register by sender
/// @param coin coin name
/// @param smgWanAddr the storeman group register address
/// @param originalChainAddr the htlc info on original chain
/// @param txFeeRatio the transaction fee required by storeman group
function storemanGroupRegisterByDelegate(uint coin,address smgWanAddr,bytes originalChainAddr,uint txFeeRatio)
public
payable
initialized(coin)
notHalted
{
require(msg.value >= mapCoinInfo[coin].defaultMinDeposit);
require(originalChainAddr.length != 0);
require(txFeeRatio > 0);
require(smgWanAddr != address(0));
require(mapCoinSmgInfo[coin][smgWanAddr].bonusBlockNumber == 0);
if (mapCoinInfo[coin].useWhiteList) {
assert(mapSmgWhiteList[coin][smgWanAddr]);
mapSmgWhiteList[coin][smgWanAddr] = false;
}
if (smgWanAddr == msg.sender){//if sender same with smgWanAddr,there are no initiator
mapCoinSmgInfo[coin][smgWanAddr] = StoremanGroup(msg.value,originalChainAddr,0,txFeeRatio,block.number,address(0),0);
} else {
mapCoinSmgInfo[coin][smgWanAddr] = StoremanGroup(msg.value,originalChainAddr,0,txFeeRatio,block.number,msg.sender,0);
}
assert(deposit(coin,smgWanAddr));
//send event
emit SmgRegister(smgWanAddr,originalChainAddr,coin,msg.value,getTokens(coin),txFeeRatio);
}
/// @notice function for nonus
/// @param coin coin name
function depositSmgBonus(uint coin)
public
payable
initialized(coin)
onlyOwner
{
require(msg.value > 0);
require(mapCoinInfo[coin].startBonusBlk > 0);
mapCoinInfo[coin].bonusTotal = mapCoinInfo[coin].bonusTotal.add(msg.value);
//send event
emit SmgDepositBonus(msg.sender,coin,msg.value);
}
/// @notice function for setting smg white list by owner
/// @param coin coin name
/// @param smgAddr storeman group address for whitelist
function setSmgWhiteList(uint coin,address smgAddr)
public
initialized(coin)
onlyOwner
{
require(smgAddr!=address(0));
require(mapCoinInfo[coin].useWhiteList);
require(mapCoinSmgInfo[coin][smgAddr].bonusBlockNumber == 0);
require(!mapSmgWhiteList[coin][smgAddr]);
mapSmgWhiteList[coin][smgAddr] = true;
//send event
emit SmgWhiteList(smgAddr,coin);
}
/// @notice function for getting store man eth address
/// @param coin coin name
/// @param storemanAddr htlc contract address on wanchain chain
function getStoremanOriginalChainAddr(uint coin,address storemanAddr)
public
view
returns (bytes)
{
return mapCoinSmgInfo[coin][storemanAddr].originalChainAddr;
}
/// @notice function for getting store man tx fee
/// @param coin coin name
/// @param storemanAddr htlc contract address on wanchain chain
function getStoremanTxFeeRatio(uint coin,address storemanAddr)
public
view
returns (uint)
{
return mapCoinSmgInfo[coin][storemanAddr].txFeeRatio;
}
/// @notice function for storeman applying unregister
/// @param coin coin name
function storemanGroupApplyUnregister(uint coin)
public
initialized(coin)
notHalted
{
StoremanGroup storage info = mapCoinSmgInfo[coin][msg.sender];
assert(info.bonusBlockNumber > 0);
assert(info.unregisterApplyTime == 0);
info.unregisterApplyTime = now;
if ( mapCoinInfo[coin].startBonusBlk > 0 && info.punishPercent==0) {
claimSystemBonus(coin);
}
assert(applyUnregister(coin));
//send event
emit SmgApplyUnRegister(msg.sender,coin,now);//event
}
/// @notice function for storeman withdraw deposit
/// @param coin coin name
function storemanGroupWithdrawDeposit(uint coin)
public
notHalted
initialized(coin)
{
StoremanGroup storage smgInfo = mapCoinSmgInfo[coin][msg.sender];
assert(now > smgInfo.unregisterApplyTime.add(mapCoinInfo[coin].withdrawDelayTime));
assert(smgInfo.deposit > 0);
assert(smgWithdrawAble(coin));
uint restBalance = smgInfo.deposit;
if (smgInfo.punishPercent > 0) {
restBalance = restBalance.sub(restBalance.mul(smgInfo.punishPercent).div(100));
}
smgInfo.deposit = 0;
smgInfo.unregisterApplyTime = 0;
smgInfo.originalChainAddr.length = 0;
smgInfo.bonusBlockNumber = 0;
smgInfo.punishPercent = 0;
if (smgInfo.initiator != address(0)) {
smgInfo.initiator.transfer(restBalance);
} else {
msg.sender.transfer(restBalance);
}
smgInfo.initiator = address(0);
//send event
emit SmgWithdraw(msg.sender,coin,now);
}
/// @notice function for storeman claiming system bonus
/// @param coin coin name
function storemanGroupClaimSystemBonus(uint coin)
public
notHalted
initialized(coin)
{
StoremanGroup storage smgInfo = mapCoinSmgInfo[coin][msg.sender];
assert(smgInfo.bonusBlockNumber != 0);
assert(smgInfo.unregisterApplyTime == 0);//can not claim after unregister applying
claimSystemBonus(coin);
}
/// @notice function for storeman applying unregister
/// @param coin coin name
/// @param punishPercent punished percent of deposit bonus
function punishStoremanGroup(uint coin,address smgAddr,uint punishPercent)
public
initialized(coin)
onlyOwner
{
require(punishPercent<=100);
StoremanGroup storage info = mapCoinSmgInfo[coin][smgAddr];
assert(info.deposit != 0);
info.punishPercent = punishPercent;
//send event
SmgPunished(smgAddr,coin,punishPercent);//event
}
/// @notice function for destroy contract
function kill()
public
isHalted
onlyOwner
{
selfdestruct(owner);
}
/// @notice function for setting smg register mode,control by foundation or register freely
function transferDeposit()
public
onlyOwner
isHalted
{
owner.transfer(this.balance);
}
////////////////private function///////////////////////////////////////////////
function deposit(uint coin,address smgAddr)
private
returns (bool)
{
address tokenManagerAddr = mapCoinInfo[coin].wanchainTokenManager;
bytes4 methodId = bytes4(keccak256("registerStoremanGroup(address,uint256)"));
uint tokenNumber = getTokens(coin);
return tokenManagerAddr.call(methodId,smgAddr,tokenNumber);
}
function applyUnregister(uint coin)
private
returns (bool)
{
address tokenManagerAddr = mapCoinInfo[coin].wanchainTokenManager;
bytes4 methodId = bytes4(keccak256("applyUnregistration(address)"));
return tokenManagerAddr.call(methodId,msg.sender);
}
function smgWithdrawAble(uint coin)
private
returns (bool)
{
address tokenManagerAddr = mapCoinInfo[coin].wanchainTokenManager;
bytes4 methodId = bytes4(keccak256("unregisterStoremanGroup(address)"));
return tokenManagerAddr.call(methodId,msg.sender);
}
function getTokens(uint coin)
private
view
returns(uint)
{
uint calValue = msg.value;
calValue = calValue.div(mapCoinInfo[coin].coin2WanRatio);
return calValue.mul(DEFAULT_PRECISE);
}
function claimSystemBonus(uint coin)
private
notHalted
initialized(coin)
{
StoremanGroup storage smgInfo = mapCoinSmgInfo[coin][msg.sender];
CoinInfo storage coinInfo = mapCoinInfo[coin];
if(smgInfo.punishPercent != 0 || coinInfo.startBonusBlk == 0){
return;
}
uint blks = block.number.sub(smgInfo.bonusBlockNumber);
if(blks >= coinInfo.bonusPeriodBlks && smgInfo.deposit > 0) {
if (smgInfo.bonusBlockNumber<coinInfo.startBonusBlk){
smgInfo.bonusBlockNumber = coinInfo.startBonusBlk;
}
uint cycles = blks.div(coinInfo.bonusPeriodBlks);
smgInfo.bonusBlockNumber = smgInfo.bonusBlockNumber.add(cycles.mul(coinInfo.bonusPeriodBlks));
uint bonus = smgInfo.deposit.mul(coinInfo.bonusRatio).div(DEFAULT_PRECISE);
bonus = bonus.mul(cycles);
if(coinInfo.bonusTotal >= bonus && bonus > 0){
coinInfo.bonusTotal = coinInfo.bonusTotal.sub(bonus);
msg.sender.transfer(bonus);
SmgClaimSystemBonus(msg.sender, coin, bonus);
} else {
SmgClaimSystemBonus(msg.sender, coin, 0);
}
}
}
}
|
function for storeman withdraw deposit coin coin name
|
{
StoremanGroup storage smgInfo = mapCoinSmgInfo[coin][msg.sender];
assert(now > smgInfo.unregisterApplyTime.add(mapCoinInfo[coin].withdrawDelayTime));
assert(smgInfo.deposit > 0);
assert(smgWithdrawAble(coin));
uint restBalance = smgInfo.deposit;
}
function storemanGroupWithdrawDeposit(uint coin)
public
notHalted
initialized(coin)
if (smgInfo.punishPercent > 0) {
restBalance = restBalance.sub(restBalance.mul(smgInfo.punishPercent).div(100));
}
smgInfo.deposit = 0;
smgInfo.unregisterApplyTime = 0;
smgInfo.originalChainAddr.length = 0;
smgInfo.bonusBlockNumber = 0;
smgInfo.punishPercent = 0;
if (smgInfo.initiator != address(0)) {
smgInfo.initiator.transfer(restBalance);
msg.sender.transfer(restBalance);
}
smgInfo.initiator = address(0);
} else {
emit SmgWithdraw(msg.sender,coin,now);
}
| 2,550,315 |
./partial_match/42/0xD4a6DB8Ab2Dabc208f2B034dc6776501F9914eD7/sources/_contracts/JoysNFTMinning.sol
|
update last push new multi = (nrate)/blockPerDay note: 1.0 nrate <= maxRewardPerDay 2.0 mul 1e9
|
function deposit(uint256 _pid, uint256 _heroId, uint256 _weaponId, bool _withWeapon) public {
PoolInfo storage pool = poolInfo[_pid];
UserInfo storage user = userInfo[_pid][_msgSender()];
require(user.point <= 0, "JoysNFTMinning: Do the withdrawal operation first.");
if (pool.withWeapon) {
require(_withWeapon, "JoysNftMinning: Need weapon.");
}
updatePool(_pid);
uint256 th = totalHeroes();
if (th > lastMinersCount) {
minersInfo[minersInfo.length.sub(1)].end = block.number;
uint256 rate = getRate(block.number);
uint256 release = rate.mul(th);
release = release > MAX_REWARD_JOYS_PER_DAY ? MAX_REWARD_JOYS_PER_DAY : release;
minersInfo.push(PeriodInfo({
begin: block.number.add(1),
end: 0,
multiplier: release.mul(1e9).div(BLOCK_PER_DAY)
}));
lastMinersCount = th;
}
uint256 heroStrength;
(, heroStrength, , ) = joysHero.info(_heroId);
user.point = user.point.add(heroStrength);
user.heroPoint = heroStrength;
pool.point = pool.point.add(heroStrength);
joysHero.transferFrom(_msgSender(), address(this), _heroId);
if (_withWeapon) {
uint256 weaponStrength;
(, weaponStrength, , ) = joysWeapon.info(_weaponId);
user.point = user.point.add(weaponStrength);
user.weaponPoint = weaponStrength;
pool.point = pool.point.add(weaponStrength);
joysWeapon.transferFrom(_msgSender(), address(this), _weaponId);
}
user.heroId = _heroId;
user.weaponId = _weaponId;
user.withWeapon = _withWeapon;
user.rewardDebt = user.point.mul(pool.accJoysPerShare).div(1e12);
user.blockNumber = block.number;
emit Deposit(_msgSender(), _pid, _heroId, _withWeapon, _weaponId);
}
| 9,084,267 |
./full_match/7700/0x865dE7F1Bf53B71b296e88E213cBD0503B7913cb/sources/contracts/external/cantolp/CErc20Delegator.sol
|
Sender supplies assets into the market and receives cTokens in exchange Accrues interest whether or not the operation succeeds, unless reverted mintAmount The amount of the underlying asset to supply return uint 0=success, otherwise a failure (see ErrorReporter.sol for details)/
|
function mint(uint256 mintAmount) external override returns (uint256) {
bytes memory data = delegateToImplementation(
abi.encodeWithSignature("mint(uint256)", mintAmount)
);
return abi.decode(data, (uint256));
}
| 4,657,760 |
pragma solidity ^0.4.21;
/**
* Changes by https://www.docademic.com/
*/
/**
* @title Ownable
* @dev The Ownable contract has an owner address, and provides basic authorization control
* functions, this simplifies the implementation of "user permissions".
*/
contract Ownable {
address public owner;
event OwnershipTransferred(address indexed previousOwner, address indexed newOwner);
/**
* @dev The Ownable constructor sets the original `owner` of the contract to the sender
* account.
*/
function Ownable() public {
owner = msg.sender;
}
/**
* @dev Throws if called by any account other than the owner.
*/
modifier onlyOwner() {
require(msg.sender == owner);
_;
}
/**
* @dev Allows the current owner to transfer control of the contract to a newOwner.
* @param newOwner The address to transfer ownership to.
*/
function transferOwnership(address newOwner) public onlyOwner {
require(newOwner != address(0));
emit OwnershipTransferred(owner, newOwner);
owner = newOwner;
}
}
/**
* @title SafeMath
* @dev Math operations with safety checks that throw on error
*/
library SafeMath {
function mul(uint256 a, uint256 b) internal pure returns (uint256) {
if (a == 0) {
return 0;
}
uint256 c = a * b;
assert(c / a == b);
return c;
}
function div(uint256 a, uint256 b) internal pure returns (uint256) {
// assert(b > 0); // Solidity automatically throws when dividing by 0
uint256 c = a / b;
// assert(a == b * c + a % b); // There is no case in which this doesn't hold
return c;
}
function sub(uint256 a, uint256 b) internal pure returns (uint256) {
assert(b <= a);
return a - b;
}
function add(uint256 a, uint256 b) internal pure returns (uint256) {
uint256 c = a + b;
assert(c >= a);
return c;
}
}
contract Destroyable is Ownable{
/**
* @notice Allows to destroy the contract and return the tokens to the owner.
*/
function destroy() public onlyOwner{
selfdestruct(owner);
}
}
interface Token {
function transfer(address _to, uint256 _value) external returns (bool);
function balanceOf(address who) view external returns (uint256);
}
contract Airdrop is Ownable, Destroyable {
using SafeMath for uint256;
/*
* Structures
*/
// Holder of tokens
struct Beneficiary {
uint256 balance;
uint256 airdrop;
bool isBeneficiary;
}
/*
* State
*/
bool public filled;
bool public airdropped;
uint256 public airdropLimit;
uint256 public currentCirculating;
uint256 public toVault;
address public vault;
address[] public addresses;
Token public token;
mapping(address => Beneficiary) public beneficiaries;
/*
* Events
*/
event NewBeneficiary(address _beneficiary);
event SnapshotTaken(uint256 _totalBalance, uint256 _totalAirdrop, uint256 _toBurn,uint256 _numberOfBeneficiaries, uint256 _numberOfAirdrops);
event Airdropped(uint256 _totalAirdrop, uint256 _numberOfAirdrops);
event TokenChanged(address _prevToken, address _token);
event VaultChanged(address _prevVault, address _vault);
event AirdropLimitChanged(uint256 _prevLimit, uint256 _airdropLimit);
event CurrentCirculatingChanged(uint256 _prevCirculating, uint256 _currentCirculating);
event Cleaned(uint256 _numberOfBeneficiaries);
event Vaulted(uint256 _tokensBurned);
/*
* Modifiers
*/
modifier isNotBeneficiary(address _beneficiary) {
require(!beneficiaries[_beneficiary].isBeneficiary);
_;
}
modifier isBeneficiary(address _beneficiary) {
require(beneficiaries[_beneficiary].isBeneficiary);
_;
}
modifier isFilled() {
require(filled);
_;
}
modifier isNotFilled() {
require(!filled);
_;
}
modifier wasAirdropped() {
require(airdropped);
_;
}
modifier wasNotAirdropped() {
require(!airdropped);
_;
}
/*
* Behavior
*/
/**
* @dev Constructor.
* @param _token The token address
* @param _airdropLimit The token limit by airdrop in wei
* @param _currentCirculating The current circulating tokens in wei
* @param _vault The address where tokens will be vaulted
*/
function Airdrop(address _token, uint256 _airdropLimit, uint256 _currentCirculating, address _vault) public{
require(_token != address(0));
token = Token(_token);
airdropLimit = _airdropLimit;
currentCirculating = _currentCirculating;
vault = _vault;
}
/**
* @dev Allows the sender to register itself as a beneficiary for the airdrop.
*/
function() payable public {
addBeneficiary(msg.sender);
}
/**
* @dev Allows the sender to register itself as a beneficiary for the airdrop.
*/
function register() public {
addBeneficiary(msg.sender);
}
/**
* @dev Allows the owner to register a beneficiary for the airdrop.
* @param _beneficiary The address of the beneficiary
*/
function registerBeneficiary(address _beneficiary) public
onlyOwner {
addBeneficiary(_beneficiary);
}
/**
* @dev Allows the owner to register beneficiaries for the airdrop.
* @param _beneficiaries The array of addresses
*/
function registerBeneficiaries(address[] _beneficiaries) public
onlyOwner {
for (uint i = 0; i < _beneficiaries.length; i++) {
addBeneficiary(_beneficiaries[i]);
}
}
/**
* @dev Add a beneficiary for the airdrop.
* @param _beneficiary The address of the beneficiary
*/
function addBeneficiary(address _beneficiary) private
isNotBeneficiary(_beneficiary) {
require(_beneficiary != address(0));
beneficiaries[_beneficiary] = Beneficiary({
balance : 0,
airdrop : 0,
isBeneficiary : true
});
addresses.push(_beneficiary);
emit NewBeneficiary(_beneficiary);
}
/**
* @dev Take the balance of all the beneficiaries.
*/
function takeSnapshot() public
onlyOwner
isNotFilled
wasNotAirdropped {
uint256 totalBalance = 0;
uint256 totalAirdrop = 0;
uint256 airdrops = 0;
for (uint i = 0; i < addresses.length; i++) {
Beneficiary storage beneficiary = beneficiaries[addresses[i]];
beneficiary.balance = token.balanceOf(addresses[i]);
totalBalance = totalBalance.add(beneficiary.balance);
if (beneficiary.balance > 0) {
beneficiary.airdrop = (beneficiary.balance.mul(airdropLimit).div(currentCirculating));
totalAirdrop = totalAirdrop.add(beneficiary.airdrop);
airdrops = airdrops.add(1);
}
}
filled = true;
toVault = airdropLimit.sub(totalAirdrop);
emit SnapshotTaken(totalBalance, totalAirdrop, toVault, addresses.length, airdrops);
}
/**
* @dev Start the airdrop.
*/
function airdropAndVault() public
onlyOwner
isFilled
wasNotAirdropped {
uint256 airdrops = 0;
uint256 totalAirdrop = 0;
for (uint256 i = 0; i < addresses.length; i++)
{
Beneficiary storage beneficiary = beneficiaries[addresses[i]];
if (beneficiary.airdrop > 0) {
require(token.transfer(addresses[i], beneficiary.airdrop));
totalAirdrop = totalAirdrop.add(beneficiary.airdrop);
airdrops = airdrops.add(1);
}
}
airdropped = true;
currentCirculating = currentCirculating.add(airdropLimit);
emit Airdropped(totalAirdrop, airdrops);
token.transfer(vault, toVault);
emit Vaulted(toVault);
}
/**
* @dev Reset all the balances to 0 and the state to false.
*/
function clean() public
onlyOwner {
for (uint256 i = 0; i < addresses.length; i++)
{
Beneficiary storage beneficiary = beneficiaries[addresses[i]];
beneficiary.balance = 0;
beneficiary.airdrop = 0;
}
filled = false;
airdropped = false;
toVault = 0;
emit Cleaned(addresses.length);
}
/**
* @dev Allows the owner to change the token address.
* @param _token New token address.
*/
function changeToken(address _token) public
onlyOwner {
emit TokenChanged(address(token), _token);
token = Token(_token);
}
/**
* @dev Allows the owner to change the vault address.
* @param _vault New vault address.
*/
function changeVault(address _vault) public
onlyOwner {
emit VaultChanged(vault, _vault);
vault = _vault;
}
/**
* @dev Allows the owner to change the token limit by airdrop.
* @param _airdropLimit The token limit by airdrop in wei.
*/
function changeAirdropLimit(uint256 _airdropLimit) public
onlyOwner {
emit AirdropLimitChanged(airdropLimit, _airdropLimit);
airdropLimit = _airdropLimit;
}
/**
* @dev Allows the owner to change the token limit by airdrop.
* @param _currentCirculating The current circulating tokens in wei.
*/
function changeCurrentCirculating(uint256 _currentCirculating) public
onlyOwner {
emit CurrentCirculatingChanged(currentCirculating, _currentCirculating);
currentCirculating = _currentCirculating;
}
/**
* @dev Allows the owner to flush the eth.
*/
function flushEth() public onlyOwner {
owner.transfer(address(this).balance);
}
/**
* @dev Allows the owner to flush the tokens of the contract.
*/
function flushTokens() public onlyOwner {
token.transfer(owner, token.balanceOf(address(this)));
}
/**
* @dev Allows the owner to destroy the contract and return the tokens to the owner.
*/
function destroy() public onlyOwner {
token.transfer(owner, token.balanceOf(address(this)));
selfdestruct(owner);
}
/**
* @dev Get the token balance of the contract.
* @return _balance The token balance of this contract
*/
function tokenBalance() view public returns (uint256 _balance) {
return token.balanceOf(address(this));
}
/**
* @dev Get the token balance of the beneficiary.
* @param _beneficiary The address of the beneficiary
* @return _balance The token balance of the beneficiary
*/
function getBalanceAtSnapshot(address _beneficiary) view public returns (uint256 _balance) {
return beneficiaries[_beneficiary].balance / 1 ether;
}
/**
* @dev Get the airdrop reward of the beneficiary.
* @param _beneficiary The address of the beneficiary
* @return _airdrop The token balance of the beneficiary
*/
function getAirdropAtSnapshot(address _beneficiary) view public returns (uint256 _airdrop) {
return beneficiaries[_beneficiary].airdrop / 1 ether;
}
/**
* @dev Allows a beneficiary to verify if he is already registered.
* @param _beneficiary The address of the beneficiary
* @return _isBeneficiary The boolean value
*/
function amIBeneficiary(address _beneficiary) view public returns (bool _isBeneficiary) {
return beneficiaries[_beneficiary].isBeneficiary;
}
/**
* @dev Get the number of beneficiaries.
* @return _length The number of beneficiaries
*/
function beneficiariesLength() view public returns (uint256 _length) {
return addresses.length;
}
}
|
Allows the owner to change the token address. _token New token address./
|
function changeToken(address _token) public
onlyOwner {
emit TokenChanged(address(token), _token);
token = Token(_token);
}
| 5,819,066 |
pragma solidity ^0.5.0;
contract MailManager {
struct Mail {
// required
uint id;
string from;
string to;
string title;
string text;
// optional
string attachment;
}
// since mail box is private, there is no global mail box
mapping(address => Mail[]) public addrToMailBox; // mapping a address to a mail box;
function addMail(string memory _from, string memory _to, string memory _title, string memory _text) internal {
// add a mail to the mail box
uint id = addrToMailBox[msg.sender].push(Mail(0, _from, _to, _title, _text, "null")) - 1;
// set id
addrToMailBox[msg.sender][id].id = id;
}
function setAttachment(uint _id, string memory _attachment) public {
// set attachment
addrToMailBox[msg.sender][_id].attachment = _attachment;
}
function getMailByIndex(uint _index) public view returns(string memory, string memory, string memory, string memory, string memory) {
Mail memory mail = addrToMailBox[msg.sender][_index];
return (mail.from, mail.to, mail.title, mail.text, mail.attachment);
}
function getMailCount() public view returns(uint) {
return addrToMailBox[msg.sender].length;
}
}
|
add a mail to the mail box set id
|
function addMail(string memory _from, string memory _to, string memory _title, string memory _text) internal {
uint id = addrToMailBox[msg.sender].push(Mail(0, _from, _to, _title, _text, "null")) - 1;
addrToMailBox[msg.sender][id].id = id;
}
| 2,474,672 |
pragma solidity ^0.4.23;
/**
* @title ERC20Basic
* @dev Simpler version of ERC20 interface
* @dev see https://github.com/ethereum/EIPs/issues/179
*/
contract ERC20Basic {
function totalSupply() public view returns (uint256);
function balanceOf(address who) public view returns (uint256);
function transfer(address to, uint256 value) public returns (bool);
event Transfer(address indexed from, address indexed to, uint256 value);
}
/**
* @title Basic token
* @dev Basic version of StandardToken, with no allowances.
*/
contract BasicToken is ERC20Basic {
using SafeMath for uint256;
mapping(address => uint256) balances;
uint256 totalSupply_;
/**
* @dev total number of tokens in existence
*/
function totalSupply() public view returns (uint256) {
return totalSupply_;
}
/**
* @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(_to != address(0));
require(_value <= balances[msg.sender]);
balances[msg.sender] = balances[msg.sender].sub(_value);
balances[_to] = balances[_to].add(_value);
emit Transfer(msg.sender, _to, _value);
return true;
}
/**
* @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];
}
}
/**
* @title ERC20 interface
* @dev see https://github.com/ethereum/EIPs/issues/20
*/
contract ERC20 is ERC20Basic {
function allowance(address owner, address spender) public view returns (uint256);
function transferFrom(address from, address to, uint256 value) public returns (bool);
function approve(address spender, uint256 value) public returns (bool);
event Approval(address indexed owner, address indexed spender, uint256 value);
}
/**
* @title Standard ERC20 token
*
* @dev Implementation of the basic standard token.
* @dev https://github.com/ethereum/EIPs/issues/20
* @dev Based on code by FirstBlood: https://github.com/Firstbloodio/token/blob/master/smart_contract/FirstBloodToken.sol
*/
contract StandardToken is ERC20, BasicToken {
mapping (address => mapping (address => uint256)) internal allowed;
/**
* @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(_to != address(0));
require(_value <= balances[_from]);
require(_value <= allowed[_from][msg.sender]);
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 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) {
allowed[msg.sender][_spender] = _value;
emit Approval(msg.sender, _spender, _value);
return true;
}
/**
* @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 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 increaseApproval(address _spender, uint _addedValue) public returns (bool) {
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 decreaseApproval(address _spender, uint _subtractedValue) public returns (bool) {
uint oldValue = allowed[msg.sender][_spender];
if (_subtractedValue > oldValue) {
allowed[msg.sender][_spender] = 0;
} else {
allowed[msg.sender][_spender] = oldValue.sub(_subtractedValue);
}
emit Approval(msg.sender, _spender, allowed[msg.sender][_spender]);
return true;
}
}
/**
* @title Ownable
* @dev The Ownable contract has an owner address, and provides basic authorization control
* functions, this simplifies the implementation of "user permissions".
*/
contract Ownable {
address public owner;
event OwnershipTransferred(address indexed previousOwner, address indexed newOwner);
/**
* @dev The Ownable constructor sets the original `owner` of the contract to the sender
* account.
*/
function Ownable() public {
owner = msg.sender;
}
/**
* @dev Throws if called by any account other than the owner.
*/
modifier onlyOwner() {
require(msg.sender == owner);
_;
}
/**
* @dev Allows the current owner to transfer control of the contract to a newOwner.
* @param newOwner The address to transfer ownership to.
*/
function transferOwnership(address newOwner) public onlyOwner {
require(newOwner != address(0));
emit OwnershipTransferred(owner, newOwner);
owner = newOwner;
}
}
/**
* @title SafeMath
* @dev Math operations with safety checks that throw on error
*/
library SafeMath {
/**
* @dev Multiplies two numbers, throws on overflow.
*/
function mul(uint256 a, uint256 b) internal pure returns (uint256 c) {
if (a == 0) {
return 0;
}
c = a * b;
assert(c / a == b);
return c;
}
/**
* @dev Integer division of two numbers, truncating the quotient.
*/
function div(uint256 a, uint256 b) internal pure returns (uint256) {
// assert(b > 0); // Solidity automatically throws when dividing by 0
// uint256 c = a / b;
// assert(a == b * c + a % b); // There is no case in which this doesn't hold
return a / b;
}
/**
* @dev Subtracts two numbers, throws on overflow (i.e. if subtrahend is greater than minuend).
*/
function sub(uint256 a, uint256 b) internal pure returns (uint256) {
assert(b <= a);
return a - b;
}
/**
* @dev Adds two numbers, throws on overflow.
*/
function add(uint256 a, uint256 b) internal pure returns (uint256 c) {
c = a + b;
assert(c >= a);
return c;
}
}
/**
* @title Mintable token
* @dev Simple ERC20 Token example, with mintable token creation
* @dev Issue: * https://github.com/OpenZeppelin/openzeppelin-solidity/issues/120
* Based on code by TokenMarketNet: https://github.com/TokenMarketNet/ico/blob/master/contracts/MintableToken.sol
*/
contract MintableToken is StandardToken, Ownable {
event Mint(address indexed to, uint256 amount);
event MintFinished();
bool public mintingFinished = false;
modifier canMint() {
require(!mintingFinished);
_;
}
/**
* @dev Function to mint tokens
* @param _to The address that will receive the minted tokens.
* @param _amount The amount of tokens to mint.
* @return A boolean that indicates if the operation was successful.
*/
function mint(address _to, uint256 _amount) onlyOwner canMint public returns (bool) {
totalSupply_ = totalSupply_.add(_amount);
balances[_to] = balances[_to].add(_amount);
emit Mint(_to, _amount);
emit Transfer(address(0), _to, _amount);
return true;
}
/**
* @dev Function to stop minting new tokens.
* @return True if the operation was successful.
*/
function finishMinting() onlyOwner canMint public returns (bool) {
mintingFinished = true;
emit MintFinished();
return true;
}
}
/**
* @title Burnable Token
* @dev Token that can be irreversibly burned (destroyed).
*/
contract BurnableToken is BasicToken {
event Burn(address indexed burner, uint256 value);
/**
* @dev Burns a specific amount of tokens.
* @param _value The amount of token to be burned.
*/
function burn(uint256 _value) public {
_burn(msg.sender, _value);
}
function _burn(address _who, uint256 _value) internal {
require(_value <= balances[_who]);
// no need to require value <= totalSupply, since that would imply the
// sender's balance is greater than the totalSupply, which *should* be an assertion failure
balances[_who] = balances[_who].sub(_value);
totalSupply_ = totalSupply_.sub(_value);
emit Burn(_who, _value);
emit Transfer(_who, address(0), _value);
}
}
/**
* @title ERC827 interface, an extension of ERC20 token standard
*
* @dev Interface of a ERC827 token, following the ERC20 standard with extra
* @dev methods to transfer value and data and execute calls in transfers and
* @dev approvals.
*/
contract ERC827 is ERC20 {
function approveAndCall( address _spender, uint256 _value, bytes _data) public payable returns (bool);
function transferAndCall( address _to, uint256 _value, bytes _data) public payable returns (bool);
function transferFromAndCall(
address _from,
address _to,
uint256 _value,
bytes _data
)
public
payable
returns (bool);
}
/**
* @title ERC827, an extension of ERC20 token standard
*
* @dev Implementation the ERC827, following the ERC20 standard with extra
* @dev methods to transfer value and data and execute calls in transfers and
* @dev approvals.
*
* @dev Uses OpenZeppelin StandardToken.
*/
contract ERC827Token is ERC827, StandardToken {
/**
* @dev Addition to ERC20 token methods. It allows to
* @dev approve the transfer of value and execute a call with the sent data.
*
* @dev Beware that changing an allowance with this method brings the risk that
* @dev someone may use both the old and the new allowance by unfortunate
* @dev transaction ordering. One possible solution to mitigate this race condition
* @dev is to first reduce the spender's allowance to 0 and set the desired value
* @dev afterwards:
* @dev https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729
*
* @param _spender The address that will spend the funds.
* @param _value The amount of tokens to be spent.
* @param _data ABI-encoded contract call to call `_to` address.
*
* @return true if the call function was executed successfully
*/
function approveAndCall(address _spender, uint256 _value, bytes _data) public payable returns (bool) {
require(_spender != address(this));
super.approve(_spender, _value);
// solium-disable-next-line security/no-call-value
require(_spender.call.value(msg.value)(_data));
return true;
}
/**
* @dev Addition to ERC20 token methods. Transfer tokens to a specified
* @dev address and execute a call with the sent data on the same transaction
*
* @param _to address The address which you want to transfer to
* @param _value uint256 the amout of tokens to be transfered
* @param _data ABI-encoded contract call to call `_to` address.
*
* @return true if the call function was executed successfully
*/
function transferAndCall(address _to, uint256 _value, bytes _data) public payable returns (bool) {
require(_to != address(this));
super.transfer(_to, _value);
// solium-disable-next-line security/no-call-value
require(_to.call.value(msg.value)(_data));
return true;
}
/**
* @dev Addition to ERC20 token methods. Transfer tokens from one address to
* @dev another and make a contract call on the same transaction
*
* @param _from The address which you want to send tokens from
* @param _to The address which you want to transfer to
* @param _value The amout of tokens to be transferred
* @param _data ABI-encoded contract call to call `_to` address.
*
* @return true if the call function was executed successfully
*/
function transferFromAndCall(
address _from,
address _to,
uint256 _value,
bytes _data
)
public payable returns (bool)
{
require(_to != address(this));
super.transferFrom(_from, _to, _value);
// solium-disable-next-line security/no-call-value
require(_to.call.value(msg.value)(_data));
return true;
}
/**
* @dev Addition to StandardToken methods. Increase the amount of tokens that
* @dev an owner allowed to a spender and execute a call with the sent data.
*
* @dev approve should be called when allowed[_spender] == 0. To increment
* @dev allowed value is better to use this function to avoid 2 calls (and wait until
* @dev the first transaction is mined)
* @dev From MonolithDAO Token.sol
*
* @param _spender The address which will spend the funds.
* @param _addedValue The amount of tokens to increase the allowance by.
* @param _data ABI-encoded contract call to call `_spender` address.
*/
function increaseApprovalAndCall(address _spender, uint _addedValue, bytes _data) public payable returns (bool) {
require(_spender != address(this));
super.increaseApproval(_spender, _addedValue);
// solium-disable-next-line security/no-call-value
require(_spender.call.value(msg.value)(_data));
return true;
}
/**
* @dev Addition to StandardToken methods. Decrease the amount of tokens that
* @dev an owner allowed to a spender and execute a call with the sent data.
*
* @dev approve should be called when allowed[_spender] == 0. To decrement
* @dev allowed value is better to use this function to avoid 2 calls (and wait until
* @dev the first transaction is mined)
* @dev From MonolithDAO Token.sol
*
* @param _spender The address which will spend the funds.
* @param _subtractedValue The amount of tokens to decrease the allowance by.
* @param _data ABI-encoded contract call to call `_spender` address.
*/
function decreaseApprovalAndCall(address _spender, uint _subtractedValue, bytes _data) public payable returns (bool) {
require(_spender != address(this));
super.decreaseApproval(_spender, _subtractedValue);
// solium-disable-next-line security/no-call-value
require(_spender.call.value(msg.value)(_data));
return true;
}
}
/**
* @title DAOToken, base on zeppelin contract.
* @dev ERC20 compatible token. It is a mintable, destructible, burnable token.
*/
contract DAOToken is ERC827Token,MintableToken,BurnableToken {
string public name;
string public symbol;
// solium-disable-next-line uppercase
uint8 public constant decimals = 18;
uint public cap;
/**
* @dev Constructor
* @param _name - token name
* @param _symbol - token symbol
* @param _cap - token cap - 0 value means no cap
*/
function DAOToken(string _name, string _symbol,uint _cap) public {
name = _name;
symbol = _symbol;
cap = _cap;
}
/**
* @dev Function to mint tokens
* @param _to The address that will receive the minted tokens.
* @param _amount The amount of tokens to mint.
* @return A boolean that indicates if the operation was successful.
*/
function mint(address _to, uint256 _amount) onlyOwner canMint public returns (bool) {
if (cap > 0)
require(totalSupply_.add(_amount) <= cap);
return super.mint(_to, _amount);
}
}
|
Constructor _name - token name _symbol - token symbol _cap - token cap - 0 value means no cap/
|
function DAOToken(string _name, string _symbol,uint _cap) public {
name = _name;
symbol = _symbol;
cap = _cap;
}
| 10,036,052 |
./partial_match/3/0xA462A609A9dF2C09082C88569175F4fbAa42Ac65/sources/PCToken.sol
|
Create a new Smart Pool Initialize the swap fee to the value provided in the CRP constructor Can be changed if the canChangeSwapFee permission is enabled initialSupply starting token balance/ There is technically reentrancy here, since we're making external calls and then transferring tokens. However, the external calls are all to the underlying BPool To the extent possible, modify state variables before calling functions Deploy new BPool (bFactory and bPool are interfaces; all calls are external) bool returnValue = IERC20(t).transferFrom(msg.sender, address(this), bal); require(returnValue, "ERR_ERC20_FALSE"); Note: we trust BPool, so the approve() attack is not an issue here SafeApprove.safeApprove(IERC20(t), address(bPool), BalancerConstants.MAX_UINT); returnValue = IERC20(t).safeApprove(address(bPool), BalancerConstants.MAX_UINT); require(returnValue, "ERR_ERC20_FALSE"); Modifying state variable after external calls here, but not essential, so not dangerous
|
function createPoolInternal(uint initialSupply) internal {
require(address(bPool) == address(0), "ERR_IS_CREATED");
require(initialSupply >= BalancerConstants.MIN_POOL_SUPPLY, "ERR_INIT_SUPPLY_MIN");
require(initialSupply <= BalancerConstants.MAX_POOL_SUPPLY, "ERR_INIT_SUPPLY_MAX");
_mintPoolShare(initialSupply);
_pushPoolShare(msg.sender, initialSupply);
bPool = bFactory.newBPool();
for (uint i = 0; i < _initialTokens.length; i++) {
address t = _initialTokens[i];
uint bal = _initialBalances[i];
uint denorm = gradualUpdate.startWeights[i];
IERC20(t).safeTransferFrom(msg.sender, address(this), bal);
IERC20(t).safeApprove(address(bPool), BalancerConstants.MAX_UINT);
bPool.bind(t, bal, denorm);
}
while (_initialTokens.length > 0) {
_initialTokens.pop();
}
bPool.setPublicSwap(true);
}
| 5,268,507 |
./partial_match/1/0x48D199Cb3a7190fC25C0347C13d9aFa658FAE1c0/sources/SynthesisStaking.sol
|
Moves `amount` of tokens from `sender` to `recipient`. This 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: - `from` cannot be the zero address. - `to` cannot be the zero address. - `from` must have a balance of at least `amount`./ unchecked { }
|
function _transfer(
address from,
address to,
uint256 amount
) internal virtual {
require(from != address(0), "ERC20: transfer from the zero address");
require(to != address(0), "ERC20: transfer to the zero address");
_beforeTokenTransfer(from, to, amount);
uint256 fromBalance = _balances[from];
require(fromBalance >= amount, "ERC20: transfer amount exceeds balance");
_balances[from] = fromBalance - amount;
_balances[to] += amount;
emit Transfer(from, to, amount);
_afterTokenTransfer(from, to, amount);
}
| 2,860,931 |
./full_match/1/0x11D1463D2D93CB26cAF34C40Cb21539e61Ef47Fa/sources/contracts/vaults/DolletVault.sol
|
Estimates the want amount after calling harvest useful for other estimation _slippage The allowed slippage percentage. return want amount after harvest/
|
function estimateWantAfterHarvest(uint256 _slippage) public returns (uint256) {
return strategy.calculations().estimateWantAfterHarvest(_slippage);
}
| 16,429,860 |
./full_match/4/0xDC750c9a411e3BfA0fB0Dd1248251D5831321352/sources/cache/solpp-generated-contracts/ZkSync.sol
|
zkSync contract initialization. Can be external because Proxy contract intercepts illegal calls of this function. initializationParameters Encoded representation of initialization parameters: _governanceAddress The address of Governance contract _verifierAddress The address of Verifier contract _genesisStateHash Genesis blocks (first block) state tree root hash We need initial state hash because it is used in the commitment of the next block
|
function initialize(bytes calldata initializationParameters) external {
initializeReentrancyGuard();
(address _governanceAddress, address _verifierAddress, bytes32 _genesisStateHash) =
abi.decode(initializationParameters, (address, address, bytes32));
verifier = Verifier(_verifierAddress);
governance = Governance(_governanceAddress);
StoredBlockInfo memory storedBlockZero =
StoredBlockInfo(0, 0, EMPTY_STRING_KECCAK, 0, _genesisStateHash, bytes32(0));
storedBlockHashes[0] = hashStoredBlockInfo(storedBlockZero);
}
| 749,354 |
pragma solidity ^0.5.0;
import "./Purchase.sol";
contract Activate {
// Initialize an instance of the Purchase Contract
Purchase purchase;
// Constructor
constructor(address _purchase) public {
purchase = Purchase(_purchase);
}
// Check if product is activated
function isActive(uint256 saleId) public returns (bool) {
return purchase.getLicenseStatus(saleId);
}
// Activate product
function activateProduct(uint256 saleId, string memory blockHash) public {
// The product must not activated
require(false == isActive(saleId), "License is already active");
// Activate the ID, and store the block hash of the purchase
// on the server side so we know exactly which product was activated
purchase.setLicenseStatus(saleId);
purchase.storeLicense(saleId, blockHash);
}
}
|
Check if product is activated
|
function isActive(uint256 saleId) public returns (bool) {
return purchase.getLicenseStatus(saleId);
}
| 5,468,182 |
pragma solidity 0.4.23;
/**
* @title SafeMath
* @dev Math operations with safety checks that throw on error
*/
library SafeMath {
/**
* @dev Multiplies two numbers, throws on overflow.
*/
function mul(uint256 a, uint256 b) internal pure returns (uint256 c) {
// Gas optimization: this is cheaper than asserting 'a' not being zero, but the
// benefit is lost if 'b' is also tested.
// See: https://github.com/OpenZeppelin/openzeppelin-solidity/pull/522
if (a == 0) {
return 0;
}
c = a * b;
assert(c / a == b);
return c;
}
/**
* @dev Integer division of two numbers, truncating the quotient.
*/
function div(uint256 a, uint256 b) internal pure returns (uint256) {
// assert(b > 0); // Solidity automatically throws when dividing by 0
// uint256 c = a / b;
// assert(a == b * c + a % b); // There is no case in which this doesn't hold
return a / b;
}
/**
* @dev Subtracts two numbers, throws on overflow (i.e. if subtrahend is greater than minuend).
*/
function sub(uint256 a, uint256 b) internal pure returns (uint256) {
assert(b <= a);
return a - b;
}
/**
* @dev Adds two numbers, throws on overflow.
*/
function add(uint256 a, uint256 b) internal pure returns (uint256 c) {
c = a + b;
assert(c >= a);
return c;
}
}
/**
* Utility library of inline functions on addresses
*/
library AddressUtils {
/**
* Returns whether the target address is a contract
* @dev This function will return false if invoked during the constructor of a contract,
* as the code is not actually created until after the constructor finishes.
* @param addr address to check
* @return whether the target address is a contract
*/
function isContract(address addr) internal view returns (bool) {
uint256 size;
// XXX Currently there is no better way to check if there is a contract in an address
// than to check the size of the code at that address.
// See https://ethereum.stackexchange.com/a/14016/36603
// for more details about how this works.
// TODO Check this again before the Serenity release, because all addresses will be
// contracts then.
// solium-disable-next-line security/no-inline-assembly
assembly { size := extcodesize(addr) }
return size > 0;
}
}
/**
* @title ERC721 token receiver interface
* @dev Interface for any contract that wants to support safeTransfers
* from ERC721 asset contracts.
*/
contract ERC721Receiver {
/**
* @dev Magic value to be returned upon successful reception of an NFT
* Equals to `bytes4(keccak256("onERC721Received(address,uint256,bytes)"))`,
* which can be also obtained as `ERC721Receiver(0).onERC721Received.selector`
*/
bytes4 internal constant ERC721_RECEIVED = 0xf0b9e5ba;
/**
* @notice Handle the receipt of an NFT
* @dev The ERC721 smart contract calls this function on the recipient
* after a `safetransfer`. This function MAY throw to revert and reject the
* transfer. This function MUST use 50,000 gas or less. Return of other
* than the magic value MUST result in the transaction being reverted.
* Note: the contract address is always the message sender.
* @param _from The sending address
* @param _tokenId The NFT identifier which is being transfered
* @param _data Additional data with no specified format
* @return `bytes4(keccak256("onERC721Received(address,uint256,bytes)"))`
*/
function onERC721Received(address _from, uint256 _tokenId, bytes _data) public returns(bytes4);
}
/**
* @title ERC165
* @dev https://github.com/ethereum/EIPs/blob/master/EIPS/eip-165.md
*/
interface ERC165 {
/**
* @notice Query if a contract implements an interface
* @param _interfaceId The interface identifier, as specified in ERC-165
* @dev Interface identification is specified in ERC-165. This function
* uses less than 30,000 gas.
*/
function supportsInterface(bytes4 _interfaceId) external view returns (bool);
}
/**
* @title ERC721 Non-Fungible Token Standard basic interface
* @dev see https://github.com/ethereum/EIPs/blob/master/EIPS/eip-721.md
*/
contract ERC721Basic is ERC165 {
event Transfer(address indexed _from, address indexed _to, uint256 indexed _tokenId);
event Approval(address indexed _owner, address indexed _approved, uint256 indexed _tokenId);
event ApprovalForAll(address indexed _owner, address indexed _operator, bool _approved);
function balanceOf(address _owner) public view returns (uint256 _balance);
function ownerOf(uint256 _tokenId) public view returns (address _owner);
function exists(uint256 _tokenId) public view returns (bool _exists);
function approve(address _to, uint256 _tokenId) public;
function getApproved(uint256 _tokenId) public view returns (address _operator);
function setApprovalForAll(address _operator, bool _approved) public;
function isApprovedForAll(address _owner, address _operator) public view returns (bool);
function transferFrom(address _from, address _to, uint256 _tokenId) public;
function safeTransferFrom(address _from, address _to, uint256 _tokenId) public;
function safeTransferFrom(address _from, address _to, uint256 _tokenId, bytes _data) public;
}
/**
* @title ERC-721 Non-Fungible Token Standard, optional enumeration extension
* @dev See https://github.com/ethereum/EIPs/blob/master/EIPS/eip-721.md
*/
contract ERC721Enumerable is ERC721Basic {
function totalSupply() public view returns (uint256);
function tokenOfOwnerByIndex(address _owner, uint256 _index) public view returns (uint256 _tokenId);
function tokenByIndex(uint256 _index) public view returns (uint256);
}
/**
* @title ERC-721 Non-Fungible Token Standard, optional metadata extension
* @dev See https://github.com/ethereum/EIPs/blob/master/EIPS/eip-721.md
*/
contract ERC721Metadata is ERC721Basic {
function name() external view returns (string _name);
function symbol() external view returns (string _symbol);
function tokenURI(uint256 _tokenId) public view returns (string);
}
/**
* @title ERC-721 Non-Fungible Token Standard, full implementation interface
* @dev See https://github.com/ethereum/EIPs/blob/master/EIPS/eip-721.md
*/
contract ERC721 is ERC721Basic, ERC721Enumerable, ERC721Metadata {
}
contract ERC721Holder is ERC721Receiver {
function onERC721Received(address, uint256, bytes) public returns(bytes4) {
return ERC721_RECEIVED;
}
}
/**
* @title SupportsInterfaceWithLookup
* @author Matt Condon (@shrugs)
* @dev Implements ERC165 using a lookup table.
*/
contract SupportsInterfaceWithLookup is ERC165 {
bytes4 public constant InterfaceId_ERC165 = 0x01ffc9a7;
/**
* 0x01ffc9a7 ===
* bytes4(keccak256('supportsInterface(bytes4)'))
*/
/**
* @dev a mapping of interface id to whether or not it's supported
*/
mapping(bytes4 => bool) internal supportedInterfaces;
/**
* @dev A contract implementing SupportsInterfaceWithLookup
* implement ERC165 itself
*/
constructor() public {
_registerInterface(InterfaceId_ERC165);
}
/**
* @dev implement supportsInterface(bytes4) using a lookup table
*/
function supportsInterface(bytes4 _interfaceId) external view returns (bool) {
return supportedInterfaces[_interfaceId];
}
/**
* @dev private method for registering an interface
*/
function _registerInterface(bytes4 _interfaceId) internal {
require(_interfaceId != 0xffffffff);
supportedInterfaces[_interfaceId] = true;
}
}
/**
* @title ERC721 Non-Fungible Token Standard basic implementation
* @dev see https://github.com/ethereum/EIPs/blob/master/EIPS/eip-721.md
*/
contract ERC721BasicToken is SupportsInterfaceWithLookup, ERC721Basic {
bytes4 private constant InterfaceId_ERC721 = 0x80ac58cd;
/*
* 0x80ac58cd ===
* bytes4(keccak256('balanceOf(address)')) ^
* bytes4(keccak256('ownerOf(uint256)')) ^
* bytes4(keccak256('approve(address,uint256)')) ^
* bytes4(keccak256('getApproved(uint256)')) ^
* bytes4(keccak256('setApprovalForAll(address,bool)')) ^
* bytes4(keccak256('isApprovedForAll(address,address)')) ^
* bytes4(keccak256('transferFrom(address,address,uint256)')) ^
* bytes4(keccak256('safeTransferFrom(address,address,uint256)')) ^
* bytes4(keccak256('safeTransferFrom(address,address,uint256,bytes)'))
*/
bytes4 private constant InterfaceId_ERC721Exists = 0x4f558e79;
/*
* 0x4f558e79 ===
* bytes4(keccak256('exists(uint256)'))
*/
using SafeMath for uint256;
using AddressUtils for address;
// Equals to `bytes4(keccak256("onERC721Received(address,uint256,bytes)"))`
// which can be also obtained as `ERC721Receiver(0).onERC721Received.selector`
bytes4 constant ERC721_RECEIVED = 0xf0b9e5ba;
// Mapping from token ID to owner
mapping (uint256 => address) internal tokenOwner;
// Mapping from token ID to approved address
mapping (uint256 => address) internal tokenApprovals;
// Mapping from owner to number of owned token
mapping (address => uint256) internal ownedTokensCount;
// Mapping from owner to operator approvals
mapping (address => mapping (address => bool)) internal operatorApprovals;
/**
* @dev Guarantees msg.sender is owner of the given token
* @param _tokenId uint256 ID of the token to validate its ownership belongs to msg.sender
*/
modifier onlyOwnerOf(uint256 _tokenId) {
require(ownerOf(_tokenId) == msg.sender);
_;
}
/**
* @dev Checks msg.sender can transfer a token, by being owner, approved, or operator
* @param _tokenId uint256 ID of the token to validate
*/
modifier canTransfer(uint256 _tokenId) {
require(isApprovedOrOwner(msg.sender, _tokenId));
_;
}
constructor() public {
// register the supported interfaces to conform to ERC721 via ERC165
_registerInterface(InterfaceId_ERC721);
_registerInterface(InterfaceId_ERC721Exists);
}
/**
* @dev Gets the balance of the specified address
* @param _owner address to query the balance of
* @return uint256 representing the amount owned by the passed address
*/
function balanceOf(address _owner) public view returns (uint256) {
require(_owner != address(0));
return ownedTokensCount[_owner];
}
/**
* @dev Gets the owner of the specified token ID
* @param _tokenId uint256 ID of the token to query the owner of
* @return owner address currently marked as the owner of the given token ID
*/
function ownerOf(uint256 _tokenId) public view returns (address) {
address owner = tokenOwner[_tokenId];
require(owner != address(0));
return owner;
}
/**
* @dev Returns whether the specified token exists
* @param _tokenId uint256 ID of the token to query the existence of
* @return whether the token exists
*/
function exists(uint256 _tokenId) public view returns (bool) {
address owner = tokenOwner[_tokenId];
return owner != address(0);
}
/**
* @dev Approves another address to transfer the given token ID
* @dev The zero address indicates there is no approved address.
* @dev There can only be one approved address per token at a given time.
* @dev Can only be called by the token owner or an approved operator.
* @param _to address to be approved for the given token ID
* @param _tokenId uint256 ID of the token to be approved
*/
function approve(address _to, uint256 _tokenId) public {
address owner = ownerOf(_tokenId);
require(_to != owner);
require(msg.sender == owner || isApprovedForAll(owner, msg.sender));
tokenApprovals[_tokenId] = _to;
emit Approval(owner, _to, _tokenId);
}
/**
* @dev Gets the approved address for a token ID, or zero if no address set
* @param _tokenId uint256 ID of the token to query the approval of
* @return address currently approved for the given token ID
*/
function getApproved(uint256 _tokenId) public view returns (address) {
return tokenApprovals[_tokenId];
}
/**
* @dev Sets or unsets the approval of a given operator
* @dev An operator is allowed to transfer all tokens of the sender on their behalf
* @param _to operator address to set the approval
* @param _approved representing the status of the approval to be set
*/
function setApprovalForAll(address _to, bool _approved) public {
require(_to != msg.sender);
operatorApprovals[msg.sender][_to] = _approved;
emit ApprovalForAll(msg.sender, _to, _approved);
}
/**
* @dev Tells whether an operator is approved by a given owner
* @param _owner owner address which you want to query the approval of
* @param _operator operator address which you want to query the approval of
* @return bool whether the given operator is approved by the given owner
*/
function isApprovedForAll(address _owner, address _operator) public view returns (bool) {
return operatorApprovals[_owner][_operator];
}
/**
* @dev Transfers the ownership of a given token ID to another address
* @dev Usage of this method is discouraged, use `safeTransferFrom` whenever possible
* @dev Requires the msg sender to be the owner, approved, or operator
* @param _from current owner of the token
* @param _to address to receive the ownership of the given token ID
* @param _tokenId uint256 ID of the token to be transferred
*/
function transferFrom(address _from, address _to, uint256 _tokenId) public canTransfer(_tokenId) {
require(_from != address(0));
require(_to != address(0));
clearApproval(_from, _tokenId);
removeTokenFrom(_from, _tokenId);
addTokenTo(_to, _tokenId);
emit Transfer(_from, _to, _tokenId);
}
/**
* @dev Safely transfers the ownership of a given token ID to another address
* @dev If the target address is a contract, it must implement `onERC721Received`,
* which is called upon a safe transfer, and return the magic value
* `bytes4(keccak256("onERC721Received(address,uint256,bytes)"))`; otherwise,
* the transfer is reverted.
* @dev Requires the msg sender to be the owner, approved, or operator
* @param _from current owner of the token
* @param _to address to receive the ownership of the given token ID
* @param _tokenId uint256 ID of the token to be transferred
*/
function safeTransferFrom(address _from, address _to, uint256 _tokenId) public canTransfer(_tokenId) {
// solium-disable-next-line arg-overflow
safeTransferFrom(_from, _to, _tokenId, "");
}
/**
* @dev Safely transfers the ownership of a given token ID to another address
* @dev If the target address is a contract, it must implement `onERC721Received`,
* which is called upon a safe transfer, and return the magic value
* `bytes4(keccak256("onERC721Received(address,uint256,bytes)"))`; otherwise,
* the transfer is reverted.
* @dev Requires the msg sender to be the owner, approved, or operator
* @param _from current owner of the token
* @param _to address to receive the ownership of the given token ID
* @param _tokenId uint256 ID of the token to be transferred
* @param _data bytes data to send along with a safe transfer check
*/
function safeTransferFrom(address _from, address _to, uint256 _tokenId, bytes _data) public canTransfer(_tokenId) {
transferFrom(_from, _to, _tokenId);
// solium-disable-next-line arg-overflow
require(checkAndCallSafeTransfer(_from, _to, _tokenId, _data));
}
/**
* @dev Returns whether the given spender can transfer a given token ID
* @param _spender address of the spender to query
* @param _tokenId uint256 ID of the token to be transferred
* @return bool whether the msg.sender is approved for the given token ID,
* is an operator of the owner, or is the owner of the token
*/
function isApprovedOrOwner(
address _spender,
uint256 _tokenId
)
internal
view
returns (bool)
{
address owner = ownerOf(_tokenId);
// Disable solium check because of
// https://github.com/duaraghav8/Solium/issues/175
// solium-disable-next-line operator-whitespace
return (
_spender == owner ||
getApproved(_tokenId) == _spender ||
isApprovedForAll(owner, _spender)
);
}
/**
* @dev Internal function to mint a new token
* @dev Reverts if the given token ID already exists
* @param _to The address that will own the minted token
* @param _tokenId uint256 ID of the token to be minted by the msg.sender
*/
function _mint(address _to, uint256 _tokenId) internal {
require(_to != address(0));
addTokenTo(_to, _tokenId);
emit Transfer(address(0), _to, _tokenId);
}
/**
* @dev Internal function to clear current approval of a given token ID
* @dev Reverts if the given address is not indeed the owner of the token
* @param _owner owner of the token
* @param _tokenId uint256 ID of the token to be transferred
*/
function clearApproval(address _owner, uint256 _tokenId) internal {
require(ownerOf(_tokenId) == _owner);
if (tokenApprovals[_tokenId] != address(0)) {
tokenApprovals[_tokenId] = address(0);
emit Approval(_owner, address(0), _tokenId);
}
}
/**
* @dev Internal function to add a token ID to the list of a given address
* @param _to address representing the new owner of the given token ID
* @param _tokenId uint256 ID of the token to be added to the tokens list of the given address
*/
function addTokenTo(address _to, uint256 _tokenId) internal {
require(tokenOwner[_tokenId] == address(0));
tokenOwner[_tokenId] = _to;
ownedTokensCount[_to] = ownedTokensCount[_to].add(1);
}
/**
* @dev Internal function to remove a token ID from the list of a given address
* @param _from address representing the previous owner of the given token ID
* @param _tokenId uint256 ID of the token to be removed from the tokens list of the given address
*/
function removeTokenFrom(address _from, uint256 _tokenId) internal {
require(ownerOf(_tokenId) == _from);
ownedTokensCount[_from] = ownedTokensCount[_from].sub(1);
tokenOwner[_tokenId] = address(0);
}
/**
* @dev Internal function to invoke `onERC721Received` on a target address
* The call is not executed if the target address is not a contract
* @param _from address representing the previous owner of the given token ID
* @param _to target address that will receive the tokens
* @param _tokenId uint256 ID of the token to be transferred
* @param _data bytes optional data to send along with the call
* @return whether the call correctly returned the expected magic value
*/
function checkAndCallSafeTransfer(
address _from,
address _to,
uint256 _tokenId,
bytes _data
)
internal
returns (bool)
{
if (!_to.isContract()) {
return true;
}
bytes4 retval = ERC721Receiver(_to).onERC721Received(
_from, _tokenId, _data);
return (retval == ERC721_RECEIVED);
}
}
/**
* @title Ownable
* @dev The Ownable contract has an owner address, and provides basic authorization control
* functions, this simplifies the implementation of "user permissions".
*/
contract Ownable {
address public owner;
address public pendingOwner;
address public manager;
event OwnershipTransferred(address indexed previousOwner, address indexed newOwner);
/**
* @dev Throws if called by any account other than the owner.
*/
modifier onlyOwner() {
require(msg.sender == owner);
_;
}
/**
* @dev Modifier throws if called by any account other than the manager.
*/
modifier onlyManager() {
require(msg.sender == manager);
_;
}
/**
* @dev Modifier throws if called by any account other than the pendingOwner.
*/
modifier onlyPendingOwner() {
require(msg.sender == pendingOwner);
_;
}
constructor() public {
owner = msg.sender;
}
/**
* @dev Allows the current owner to set the pendingOwner address.
* @param newOwner The address to transfer ownership to.
*/
function transferOwnership(address newOwner) public onlyOwner {
pendingOwner = newOwner;
}
/**
* @dev Allows the pendingOwner address to finalize the transfer.
*/
function claimOwnership() public onlyPendingOwner {
emit OwnershipTransferred(owner, pendingOwner);
owner = pendingOwner;
pendingOwner = address(0);
}
/**
* @dev Sets the manager address.
* @param _manager The manager address.
*/
function setManager(address _manager) public onlyOwner {
require(_manager != address(0));
manager = _manager;
}
}
/**
* @title Full ERC721 Token
* This implementation includes all the required and some optional functionality of the ERC721 standard
* Moreover, it includes approve all functionality using operator terminology
* @dev see https://github.com/ethereum/EIPs/blob/master/EIPS/eip-721.md
*/
contract GeneralSecurityToken is SupportsInterfaceWithLookup, ERC721, ERC721BasicToken, Ownable {
bytes4 private constant InterfaceId_ERC721Enumerable = 0x780e9d63;
/**
* 0x780e9d63 ===
* bytes4(keccak256('totalSupply()')) ^
* bytes4(keccak256('tokenOfOwnerByIndex(address,uint256)')) ^
* bytes4(keccak256('tokenByIndex(uint256)'))
*/
bytes4 private constant InterfaceId_ERC721Metadata = 0x5b5e139f;
/**
* 0x5b5e139f ===
* bytes4(keccak256('name()')) ^
* bytes4(keccak256('symbol()')) ^
* bytes4(keccak256('tokenURI(uint256)'))
*/
// Token name
string public name_ = "GeneralSecurityToken";
// Token symbol
string public symbol_ = "GST";
uint public tokenIDCount = 0;
// Mapping from owner to list of owned token IDs
mapping(address => uint256[]) internal ownedTokens;
// Mapping from token ID to index of the owner tokens list
mapping(uint256 => uint256) internal ownedTokensIndex;
// Array with all token ids, used for enumeration
uint256[] internal allTokens;
// Mapping from token id to position in the allTokens array
mapping(uint256 => uint256) internal allTokensIndex;
// Optional mapping for token URIs
mapping(uint256 => string) internal tokenURIs;
struct Data{
string information;
string URL;
}
mapping(uint256 => Data) internal tokenData;
/**
* @dev Constructor function
*/
constructor() public {
// register the supported interfaces to conform to ERC721 via ERC165
_registerInterface(InterfaceId_ERC721Enumerable);
_registerInterface(InterfaceId_ERC721Metadata);
}
/**
* @dev External function to mint a new token
* @dev Reverts if the given token ID already exists
* @param _to address the beneficiary that will own the minted token
*/
function mint(address _to) external onlyManager {
_mint(_to, tokenIDCount++);
}
/**
* @dev Gets the token name
* @return string representing the token name
*/
function name() external view returns (string) {
return name_;
}
/**
* @dev Gets the token symbol
* @return string representing the token symbol
*/
function symbol() external view returns (string) {
return symbol_;
}
function arrayOfTokensByAddress(address _holder) public view returns(uint256[]) {
return ownedTokens[_holder];
}
/**
* @dev Returns an URI for a given token ID
* @dev Throws if the token ID does not exist. May return an empty string.
* @param _tokenId uint256 ID of the token to query
*/
function tokenURI(uint256 _tokenId) public view returns (string) {
require(exists(_tokenId));
return tokenURIs[_tokenId];
}
/**
* @dev Gets the token ID at a given index of the tokens list of the requested owner
* @param _owner address owning the tokens list to be accessed
* @param _index uint256 representing the index to be accessed of the requested tokens list
* @return uint256 token ID at the given index of the tokens list owned by the requested address
*/
function tokenOfOwnerByIndex(address _owner, uint256 _index) public view returns (uint256) {
require(_index < balanceOf(_owner));
return ownedTokens[_owner][_index];
}
/**
* @dev Gets the total amount of tokens stored by the contract
* @return uint256 representing the total amount of tokens
*/
function totalSupply() public view returns (uint256) {
return allTokens.length;
}
/**
* @dev Gets the token ID at a given index of all the tokens in this contract
* @dev Reverts if the index is greater or equal to the total number of tokens
* @param _index uint256 representing the index to be accessed of the tokens list
* @return uint256 token ID at the given index of the tokens list
*/
function tokenByIndex(uint256 _index) public view returns (uint256) {
require(_index < totalSupply());
return allTokens[_index];
}
/**
* @dev Internal function to set the token URI for a given token
* @dev Reverts if the token ID does not exist
* @param _tokenId uint256 ID of the token to set its URI
* @param _uri string URI to assign
*/
function _setTokenURI(uint256 _tokenId, string _uri) internal {
require(exists(_tokenId));
tokenURIs[_tokenId] = _uri;
}
/**
* @dev Internal function to add a token ID to the list of a given address
* @param _to address representing the new owner of the given token ID
* @param _tokenId uint256 ID of the token to be added to the tokens list of the given address
*/
function addTokenTo(address _to, uint256 _tokenId) internal {
super.addTokenTo(_to, _tokenId);
uint256 length = ownedTokens[_to].length;
ownedTokens[_to].push(_tokenId);
ownedTokensIndex[_tokenId] = length;
}
/**
* @dev Internal function to remove a token ID from the list of a given address
* @param _from address representing the previous owner of the given token ID
* @param _tokenId uint256 ID of the token to be removed from the tokens list of the given address
*/
function removeTokenFrom(address _from, uint256 _tokenId) internal {
super.removeTokenFrom(_from, _tokenId);
uint256 tokenIndex = ownedTokensIndex[_tokenId];
uint256 lastTokenIndex = ownedTokens[_from].length.sub(1);
uint256 lastToken = ownedTokens[_from][lastTokenIndex];
ownedTokens[_from][tokenIndex] = lastToken;
ownedTokens[_from][lastTokenIndex] = 0;
// Note that this will handle single-element arrays. In that case, both tokenIndex and lastTokenIndex are
// going to be zero. Then we can make sure that we will remove _tokenId from the ownedTokens list since we are
// first swapping the lastToken to the first position, and then dropping the element placed in the last
// position of the list
ownedTokens[_from].length--;
ownedTokensIndex[_tokenId] = 0;
ownedTokensIndex[lastToken] = tokenIndex;
}
/**
* @dev Internal function to mint a new token
* @dev Reverts if the given token ID already exists
* @param _to address the beneficiary that will own the minted token
*/
function _mint(address _to, uint256 _id) internal {
allTokens.push(_id);
allTokensIndex[_id] = _id;
super._mint(_to, _id);
}
function addTokenData(uint _tokenId, string _information, string _URL) public {
require(ownerOf(_tokenId) == msg.sender);
tokenData[_tokenId].information = _information;
tokenData[_tokenId].URL = _URL;
}
function getTokenData(uint _tokenId) public view returns(string Liscence, string URL){
require(exists(_tokenId));
Liscence = tokenData[_tokenId].information;
URL = tokenData[_tokenId].URL;
}
function() payable{
require(msg.value > 0.16 ether);
_mint(msg.sender, tokenIDCount++);
}
}
|
Sets or unsets the approval of a given operator An operator is allowed to transfer all tokens of the sender on their behalf _to operator address to set the approval _approved representing the status of the approval to be set/
|
function setApprovalForAll(address _to, bool _approved) public {
require(_to != msg.sender);
operatorApprovals[msg.sender][_to] = _approved;
emit ApprovalForAll(msg.sender, _to, _approved);
}
| 7,750,101 |
/**
*Submitted for verification at Etherscan.io on 2021-04-22
*/
// Sources flattened with hardhat v2.1.1 https://hardhat.org
// File @openzeppelin/contracts-upgradeable/utils/[email protected]
pragma solidity ^0.8.0;
/**
* @dev Collection of functions related to the address type
*/
library AddressUpgradeable {
/**
* @dev Returns true if `account` is a contract.
*
* [IMPORTANT]
* ====
* It is unsafe to assume that an address for which this function returns
* false is an externally-owned account (EOA) and not a contract.
*
* Among others, `isContract` will return false for the following
* types of addresses:
*
* - an externally-owned account
* - a contract in construction
* - an address where a contract will be created
* - an address where a contract lived, but was destroyed
* ====
*/
function isContract(address account) internal view returns (bool) {
// This method relies on extcodesize, which returns 0 for contracts in
// construction, since the code is only stored at the end of the
// constructor execution.
uint256 size;
// solhint-disable-next-line no-inline-assembly
assembly { size := extcodesize(account) }
return size > 0;
}
/**
* @dev Replacement for Solidity's `transfer`: sends `amount` wei to
* `recipient`, forwarding all available gas and reverting on errors.
*
* https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost
* of certain opcodes, possibly making contracts go over the 2300 gas limit
* imposed by `transfer`, making them unable to receive funds via
* `transfer`. {sendValue} removes this limitation.
*
* https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more].
*
* IMPORTANT: because control is transferred to `recipient`, care must be
* taken to not create reentrancy vulnerabilities. Consider using
* {ReentrancyGuard} or the
* https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern].
*/
function sendValue(address payable recipient, uint256 amount) internal {
require(address(this).balance >= amount, "Address: insufficient balance");
// solhint-disable-next-line avoid-low-level-calls, avoid-call-value
(bool success, ) = recipient.call{ value: amount }("");
require(success, "Address: unable to send value, recipient may have reverted");
}
/**
* @dev Performs a Solidity function call using a low level `call`. A
* plain`call` is an unsafe replacement for a function call: use this
* function instead.
*
* If `target` reverts with a revert reason, it is bubbled up by this
* function (like regular Solidity function calls).
*
* Returns the raw returned data. To convert to the expected return value,
* use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`].
*
* 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");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with
* `errorMessage` as a fallback revert reason when `target` reverts.
*
* _Available since v3.1._
*/
function functionCall(address target, bytes memory data, string memory errorMessage) internal returns (bytes memory) {
return functionCallWithValue(target, data, 0, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but also transferring `value` wei to `target`.
*
* Requirements:
*
* - the calling contract must have an ETH balance of at least `value`.
* - the called Solidity function must be `payable`.
*
* _Available since v3.1._
*/
function functionCallWithValue(address target, bytes memory data, uint256 value) internal returns (bytes memory) {
return functionCallWithValue(target, data, value, "Address: low-level call with value failed");
}
/**
* @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but
* with `errorMessage` as a fallback revert reason when `target` reverts.
*
* _Available since v3.1._
*/
function functionCallWithValue(address target, bytes memory data, uint256 value, string memory errorMessage) internal returns (bytes memory) {
require(address(this).balance >= value, "Address: insufficient balance for call");
require(isContract(target), "Address: call to non-contract");
// solhint-disable-next-line avoid-low-level-calls
(bool success, bytes memory returndata) = target.call{ value: value }(data);
return _verifyCallResult(success, returndata, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but performing a static call.
*
* _Available since v3.3._
*/
function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) {
return functionStaticCall(target, data, "Address: low-level static call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`],
* but performing a static call.
*
* _Available since v3.3._
*/
function functionStaticCall(address target, bytes memory data, string memory errorMessage) internal view returns (bytes memory) {
require(isContract(target), "Address: static call to non-contract");
// solhint-disable-next-line avoid-low-level-calls
(bool success, bytes memory returndata) = target.staticcall(data);
return _verifyCallResult(success, returndata, errorMessage);
}
function _verifyCallResult(bool success, bytes memory returndata, string memory errorMessage) private pure returns(bytes memory) {
if (success) {
return returndata;
} else {
// Look for revert reason and bubble it up if present
if (returndata.length > 0) {
// The easiest way to bubble the revert reason is using memory via assembly
// solhint-disable-next-line no-inline-assembly
assembly {
let returndata_size := mload(returndata)
revert(add(32, returndata), returndata_size)
}
} else {
revert(errorMessage);
}
}
}
}
// File @openzeppelin/contracts-upgradeable/proxy/utils/[email protected]
// solhint-disable-next-line compiler-version
pragma solidity ^0.8.0;
/**
* @dev This is a base contract to aid in writing upgradeable contracts, or any kind of contract that will be deployed
* behind a proxy. Since a proxied contract can't have a constructor, it's common to move constructor logic to an
* external initializer function, usually called `initialize`. It then becomes necessary to protect this initializer
* function so it can only be called once. The {initializer} modifier provided by this contract will have this effect.
*
* TIP: To avoid leaving the proxy in an uninitialized state, the initializer function should be called as early as
* possible by providing the encoded function call as the `_data` argument to {UpgradeableProxy-constructor}.
*
* CAUTION: When used with inheritance, manual care must be taken to not invoke a parent initializer twice, or to ensure
* that all initializers are idempotent. This is not verified automatically as constructors are by Solidity.
*/
abstract contract Initializable {
/**
* @dev Indicates that the contract has been initialized.
*/
bool private _initialized;
/**
* @dev Indicates that the contract is in the process of being initialized.
*/
bool private _initializing;
/**
* @dev Modifier to protect an initializer function from being invoked twice.
*/
modifier initializer() {
require(_initializing || !_initialized, "Initializable: contract is already initialized");
bool isTopLevelCall = !_initializing;
if (isTopLevelCall) {
_initializing = true;
_initialized = true;
}
_;
if (isTopLevelCall) {
_initializing = false;
}
}
}
// File @openzeppelin/contracts-upgradeable/token/ERC20/[email protected]
pragma solidity ^0.8.0;
/**
* @dev Interface of the ERC20 standard as defined in the EIP.
*/
interface IERC20Upgradeable {
/**
* @dev Returns the amount of tokens in existence.
*/
function totalSupply() external view returns (uint256);
/**
* @dev Returns the amount of tokens owned by `account`.
*/
function balanceOf(address account) external view returns (uint256);
/**
* @dev Moves `amount` tokens from the caller's account to `recipient`.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/
function transfer(address recipient, uint256 amount) external returns (bool);
/**
* @dev Returns the remaining number of tokens that `spender` will be
* allowed to spend on behalf of `owner` through {transferFrom}. This is
* zero by default.
*
* This value changes when {approve} or {transferFrom} are called.
*/
function allowance(address owner, address spender) external view returns (uint256);
/**
* @dev Sets `amount` as the allowance of `spender` over the caller's tokens.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* IMPORTANT: 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
*
* Emits an {Approval} event.
*/
function approve(address spender, uint256 amount) external returns (bool);
/**
* @dev Moves `amount` tokens from `sender` to `recipient` using the
* allowance mechanism. `amount` is then deducted from the caller's
* allowance.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/
function transferFrom(address sender, address recipient, uint256 amount) external returns (bool);
/**
* @dev Emitted when `value` tokens are moved from one account (`from`) to
* another (`to`).
*
* Note that `value` may be zero.
*/
event Transfer(address indexed from, address indexed to, uint256 value);
/**
* @dev Emitted when the allowance of a `spender` for an `owner` is set by
* a call to {approve}. `value` is the new allowance.
*/
event Approval(address indexed owner, address indexed spender, uint256 value);
}
// File contracts/library/ERC20ReInitializable.sol
pragma solidity ^0.8.0;
contract ERC20ReInitializable is Initializable, IERC20Upgradeable {
mapping (address => uint256) private _balances;
mapping (address => mapping (address => uint256)) private _allowances;
uint256 private _totalSupply;
string private _name;
string private _symbol;
/**
* @dev Sets the values for {name} and {symbol}.
*
* The defaut value of {decimals} is 18. To select a different value for
* {decimals} you should overload it.
*
* All three of these values are immutable: they can only be set once during
* construction.
*/
function __ERC20_init(string memory name_, string memory symbol_) internal initializer {
__ERC20_init_unchained(name_, symbol_);
}
function __ERC20_init_unchained(string memory name_, string memory symbol_) internal initializer {
_name = name_;
_symbol = symbol_;
}
function __ERC20_re_initialize(string memory name_, string memory symbol_) internal {
_name = name_;
_symbol = symbol_;
}
/**
* @dev Returns the name of the token.
*/
function name() public view virtual returns (string memory) {
return _name;
}
/**
* @dev Returns the symbol of the token, usually a shorter version of the
* name.
*/
function symbol() public view virtual returns (string memory) {
return _symbol;
}
/**
* @dev Returns the number of decimals used to get its user representation.
* For example, if `decimals` equals `2`, a balance of `505` tokens should
* be displayed to a user as `5,05` (`505 / 10 ** 2`).
*
* Tokens usually opt for a value of 18, imitating the relationship between
* Ether and Wei. This is the value {ERC20} uses, unless this function is
* overloaded;
*
* NOTE: This information is only used for _display_ purposes: it in
* no way affects any of the arithmetic of the contract, including
* {IERC20-balanceOf} and {IERC20-transfer}.
*/
function decimals() public view virtual returns (uint8) {
return 18;
}
/**
* @dev See {IERC20-totalSupply}.
*/
function totalSupply() public view virtual override returns (uint256) {
return _totalSupply;
}
/**
* @dev See {IERC20-balanceOf}.
*/
function balanceOf(address account) public view virtual override returns (uint256) {
return _balances[account];
}
/**
* @dev See {IERC20-transfer}.
*
* Requirements:
*
* - `recipient` cannot be the zero address.
* - the caller must have a balance of at least `amount`.
*/
function transfer(address recipient, uint256 amount) public virtual override returns (bool) {
_transfer(msg.sender, recipient, amount);
return true;
}
/**
* @dev See {IERC20-allowance}.
*/
function allowance(address owner, address spender) public view virtual override returns (uint256) {
return _allowances[owner][spender];
}
/**
* @dev See {IERC20-approve}.
*
* Requirements:
*
* - `spender` cannot be the zero address.
*/
function approve(address spender, uint256 amount) public virtual override returns (bool) {
_approve(msg.sender, spender, amount);
return true;
}
/**
* @dev See {IERC20-transferFrom}.
*
* Emits an {Approval} event indicating the updated allowance. This is not
* required by the EIP. See the note at the beginning of {ERC20}.
*
* Requirements:
*
* - `sender` and `recipient` cannot be the zero address.
* - `sender` must have a balance of at least `amount`.
* - the caller must have allowance for ``sender``'s tokens of at least
* `amount`.
*/
function transferFrom(address sender, address recipient, uint256 amount) public virtual override returns (bool) {
_transfer(sender, recipient, amount);
uint256 currentAllowance = _allowances[sender][msg.sender];
require(currentAllowance >= amount, "ERC20: transfer amount exceeds allowance");
_approve(sender, msg.sender, currentAllowance - amount);
return true;
}
/**
* @dev Atomically increases the allowance granted to `spender` by the caller.
*
* This is an alternative to {approve} that can be used as a mitigation for
* problems described in {IERC20-approve}.
*
* Emits an {Approval} event indicating the updated allowance.
*
* Requirements:
*
* - `spender` cannot be the zero address.
*/
function increaseAllowance(address spender, uint256 addedValue) public virtual returns (bool) {
_approve(msg.sender, spender, _allowances[msg.sender][spender] + addedValue);
return true;
}
/**
* @dev Atomically decreases the allowance granted to `spender` by the caller.
*
* This is an alternative to {approve} that can be used as a mitigation for
* problems described in {IERC20-approve}.
*
* Emits an {Approval} event indicating the updated allowance.
*
* Requirements:
*
* - `spender` cannot be the zero address.
* - `spender` must have allowance for the caller of at least
* `subtractedValue`.
*/
function decreaseAllowance(address spender, uint256 subtractedValue) public virtual returns (bool) {
uint256 currentAllowance = _allowances[msg.sender][spender];
require(currentAllowance >= subtractedValue, "ERC20: decreased allowance below zero");
_approve(msg.sender, spender, currentAllowance - subtractedValue);
return true;
}
/**
* @dev 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);
uint256 senderBalance = _balances[sender];
require(senderBalance >= amount, "ERC20: transfer amount exceeds balance");
_balances[sender] = senderBalance - amount;
_balances[recipient] += amount;
emit Transfer(sender, recipient, amount);
}
/** @dev Creates `amount` tokens and assigns them to `account`, increasing
* the total supply.
*
* Emits a {Transfer} event with `from` set to the zero address.
*
* Requirements:
*
* - `to` cannot be the zero address.
*/
function _mint(address account, uint256 amount) internal virtual {
require(account != address(0), "ERC20: mint to the zero address");
_beforeTokenTransfer(address(0), account, amount);
_totalSupply += amount;
_balances[account] += amount;
emit Transfer(address(0), account, amount);
}
/**
* @dev Destroys `amount` tokens from `account`, reducing the
* total supply.
*
* Emits a {Transfer} event with `to` set to the zero address.
*
* Requirements:
*
* - `account` cannot be the zero address.
* - `account` must have at least `amount` tokens.
*/
function _burn(address account, uint256 amount) internal virtual {
require(account != address(0), "ERC20: burn from the zero address");
_beforeTokenTransfer(account, address(0), amount);
uint256 accountBalance = _balances[account];
require(accountBalance >= amount, "ERC20: burn amount exceeds balance");
_balances[account] = accountBalance - amount;
_totalSupply -= amount;
emit Transfer(account, address(0), amount);
}
/**
* @dev Sets `amount` as the allowance of `spender` over the `owner` s tokens.
*
* This internal function is equivalent to `approve`, and can be used to
* e.g. set automatic allowances for certain subsystems, etc.
*
* Emits an {Approval} event.
*
* Requirements:
*
* - `owner` cannot be the zero address.
* - `spender` cannot be the zero address.
*/
function _approve(address owner, address spender, uint256 amount) internal virtual {
require(owner != address(0), "ERC20: approve from the zero address");
require(spender != address(0), "ERC20: approve to the zero address");
_allowances[owner][spender] = amount;
emit Approval(owner, spender, amount);
}
/**
* @dev Hook that is called before any transfer of tokens. This includes
* minting and burning.
*
* Calling conditions:
*
* - when `from` and `to` are both non-zero, `amount` of ``from``'s tokens
* will be to transferred to `to`.
* - when `from` is zero, `amount` tokens will be minted for `to`.
* - when `to` is zero, `amount` of ``from``'s tokens will be burned.
* - `from` and `to` are never both zero.
*
* To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks].
*/
function _beforeTokenTransfer(address from, address to, uint256 amount) internal virtual { }
uint256[45] private __gap;
}
// File contracts/interfaces/IOwnable.sol
pragma solidity ^0.8.0;
interface IOwnable{
function owner() external view returns(address);
}
// File contracts/interfaces/IWhitelist.sol
pragma solidity ^0.8.0;
/**
* Source: https://raw.githubusercontent.com/simple-restricted-token/reference-implementation/master/contracts/token/ERC1404/ERC1404.sol
* With ERC-20 APIs removed (will be implemented as a separate contract).
* And adding authorizeTransfer.
*/
interface IWhitelist {
/**
* @notice Detects if a transfer will be reverted and if so returns an appropriate reference code
* @param from Sending address
* @param to Receiving address
* @param value Amount of tokens being transferred
* @return Code by which to reference message for rejection reasoning
* @dev Overwrite with your custom transfer restriction logic
*/
function detectTransferRestriction(
address from,
address to,
uint value
) external view returns (uint8);
/**
* @notice Returns a human-readable message for a given restriction code
* @param restrictionCode Identifier for looking up a message
* @return Text showing the restriction's reasoning
* @dev Overwrite with your custom message and restrictionCode handling
*/
function messageForTransferRestriction(uint8 restrictionCode)
external
pure
returns (string memory);
/**
* @notice Called by the DAT contract before a transfer occurs.
* @dev This call will revert when the transfer is not authorized.
* This is a mutable call to allow additional data to be recorded,
* such as when the user aquired their tokens.
*/
function authorizeTransfer(
address _from,
address _to,
uint _value,
bool _isSell
) external;
}
// File @openzeppelin/contracts/token/ERC20/[email protected]
pragma solidity ^0.8.0;
/**
* @dev Interface of the ERC20 standard as defined in the EIP.
*/
interface IERC20 {
/**
* @dev Returns the amount of tokens in existence.
*/
function totalSupply() external view returns (uint256);
/**
* @dev Returns the amount of tokens owned by `account`.
*/
function balanceOf(address account) external view returns (uint256);
/**
* @dev Moves `amount` tokens from the caller's account to `recipient`.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/
function transfer(address recipient, uint256 amount) external returns (bool);
/**
* @dev Returns the remaining number of tokens that `spender` will be
* allowed to spend on behalf of `owner` through {transferFrom}. This is
* zero by default.
*
* This value changes when {approve} or {transferFrom} are called.
*/
function allowance(address owner, address spender) external view returns (uint256);
/**
* @dev Sets `amount` as the allowance of `spender` over the caller's tokens.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* IMPORTANT: 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
*
* Emits an {Approval} event.
*/
function approve(address spender, uint256 amount) external returns (bool);
/**
* @dev Moves `amount` tokens from `sender` to `recipient` using the
* allowance mechanism. `amount` is then deducted from the caller's
* allowance.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/
function transferFrom(address sender, address recipient, uint256 amount) external returns (bool);
/**
* @dev Emitted when `value` tokens are moved from one account (`from`) to
* another (`to`).
*
* Note that `value` may be zero.
*/
event Transfer(address indexed from, address indexed to, uint256 value);
/**
* @dev Emitted when the allowance of a `spender` for an `owner` is set by
* a call to {approve}. `value` is the new allowance.
*/
event Approval(address indexed owner, address indexed spender, uint256 value);
}
// File contracts/interfaces/IERC20Metadata.sol
pragma solidity ^0.8.0;
/**
* @dev Interface for the optional metadata functions from the ERC20 standard.
*/
interface IERC20Metadata is IERC20 {
/**
* @dev Returns the name of the token.
*/
function name() external view returns (string memory);
/**
* @dev Returns the symbol of the token.
*/
function symbol() external view returns (string memory);
/**
* @dev Returns the decimals places of the token.
*/
function decimals() external view returns (uint8);
}
// File contracts/math/BigDiv.sol
pragma solidity ^0.8.0;
/**
* @title Reduces the size of terms before multiplication, to avoid an overflow, and then
*stores the proper size after division.
* @notice This effectively allows us to overflow values in the numerator and/or denominator
* a fraction, so long as the end result does not overflow as well.
* @dev Results may be off by 1 + 0.000001% for 2x1 calls and 2 + 0.00001% for 2x2 calls.
* Do not use if your contract expects very small result values to be accurate.
*/
library BigDiv {
// When multiplying 2 terms <= this value the result won't overflow
uint private constant MAX_BEFORE_SQUARE = 2**128 - 1;
// The max error target is off by 1 plus up to 0.000001% error
// for bigDiv2x1 and that `* 2` for bigDiv2x2
uint private constant MAX_ERROR = 100000000;
// A larger error threshold to use when multiple rounding errors may apply
uint private constant MAX_ERROR_BEFORE_DIV = MAX_ERROR * 2;
/**
* @notice Returns the approx result of `a * b / d` so long as the result is <= MAX_UINT
* @param _numA the first numerator term
* @param _numB the second numerator term
* @param _den the denominator
* @return the approx result with up to off by 1 + MAX_ERROR, rounding down if needed
*/
function bigDiv2x1(
uint _numA,
uint _numB,
uint _den
) internal pure returns (uint) {
if (_numA == 0 || _numB == 0) {
// would div by 0 or underflow if we don't special case 0
return 0;
}
uint value;
if (type(uint256).max / _numA >= _numB) {
// a*b does not overflow, return exact math
value = _numA * _numB;
value /= _den;
return value;
}
// Sort numerators
uint numMax = _numB;
uint numMin = _numA;
if (_numA > _numB) {
numMax = _numA;
numMin = _numB;
}
value = numMax / _den;
if (value > MAX_ERROR) {
// _den is small enough to be MAX_ERROR or better w/o a factor
value = value * numMin;
return value;
}
// formula = ((a / f) * b) / (d / f)
// factor >= a / sqrt(MAX) * (b / sqrt(MAX))
uint factor = numMin - 1;
factor /= MAX_BEFORE_SQUARE;
factor += 1;
uint temp = numMax - 1;
temp /= MAX_BEFORE_SQUARE;
temp += 1;
if (type(uint256).max / factor >= temp) {
factor *= temp;
value = numMax / factor;
if (value > MAX_ERROR_BEFORE_DIV) {
value = value * numMin;
temp = _den - 1;
temp /= factor;
temp = temp + 1;
value /= temp;
return value;
}
}
// formula: (a / (d / f)) * (b / f)
// factor: b / sqrt(MAX)
factor = numMin - 1;
factor /= MAX_BEFORE_SQUARE;
factor += 1;
value = numMin / factor;
temp = _den - 1;
temp /= factor;
temp += 1;
temp = numMax / temp;
value = value * temp;
return value;
}
/**
* @notice Returns the approx result of `a * b / d` so long as the result is <= MAX_UINT
* @param _numA the first numerator term
* @param _numB the second numerator term
* @param _den the denominator
* @return the approx result with up to off by 1 + MAX_ERROR, rounding down if needed
* @dev roundUp is implemented by first rounding down and then adding the max error to the result
*/
function bigDiv2x1RoundUp(
uint _numA,
uint _numB,
uint _den
) internal pure returns (uint) {
// first get the rounded down result
uint value = bigDiv2x1(_numA, _numB, _den);
if (value == 0) {
// when the value rounds down to 0, assume up to an off by 1 error
return 1;
}
// round down has a max error of MAX_ERROR, add that to the result
// for a round up error of <= MAX_ERROR
uint temp = value - 1;
temp /= MAX_ERROR;
temp += 1;
if (type(uint256).max - value < temp) {
// value + error would overflow, return MAX
return type(uint256).max;
}
value += temp;
return value;
}
/**
* @notice Returns the approx result of `a * b / (c * d)` so long as the result is <= MAX_UINT
* @param _numA the first numerator term
* @param _numB the second numerator term
* @param _denA the first denominator term
* @param _denB the second denominator term
* @return the approx result with up to off by 2 + MAX_ERROR*10 error, rounding down if needed
* @dev this uses bigDiv2x1 and adds additional rounding error so the max error of this
* formula is larger
*/
function bigDiv2x2(
uint _numA,
uint _numB,
uint _denA,
uint _denB
) internal pure returns (uint) {
if (type(uint256).max / _denA >= _denB) {
// denA*denB does not overflow, use bigDiv2x1 instead
return bigDiv2x1(_numA, _numB, _denA * _denB);
}
if (_numA == 0 || _numB == 0) {
// would div by 0 or underflow if we don't special case 0
return 0;
}
// Sort denominators
uint denMax = _denB;
uint denMin = _denA;
if (_denA > _denB) {
denMax = _denA;
denMin = _denB;
}
uint value;
if (type(uint256).max / _numA >= _numB) {
// a*b does not overflow, use `a / d / c`
value = _numA * _numB;
value /= denMin;
value /= denMax;
return value;
}
// `ab / cd` where both `ab` and `cd` would overflow
// Sort numerators
uint numMax = _numB;
uint numMin = _numA;
if (_numA > _numB) {
numMax = _numA;
numMin = _numB;
}
// formula = (a/d) * b / c
uint temp = numMax / denMin;
if (temp > MAX_ERROR_BEFORE_DIV) {
return bigDiv2x1(temp, numMin, denMax);
}
// formula: ((a/f) * b) / d then either * f / c or / c * f
// factor >= a / sqrt(MAX) * (b / sqrt(MAX))
uint factor = numMin - 1;
factor /= MAX_BEFORE_SQUARE;
factor += 1;
temp = numMax - 1;
temp /= MAX_BEFORE_SQUARE;
temp += 1;
if (type(uint256).max / factor >= temp) {
factor *= temp;
value = numMax / factor;
if (value > MAX_ERROR_BEFORE_DIV) {
value = value * numMin;
value /= denMin;
if (value > 0 && type(uint256).max / value >= factor) {
value *= factor;
value /= denMax;
return value;
}
}
}
// formula: (a/f) * b / ((c*d)/f)
// factor >= c / sqrt(MAX) * (d / sqrt(MAX))
factor = denMin;
factor /= MAX_BEFORE_SQUARE;
temp = denMax;
// + 1 here prevents overflow of factor*temp
temp /= MAX_BEFORE_SQUARE + 1;
factor *= temp;
return bigDiv2x1(numMax / factor, numMin, type(uint256).max);
}
}
// File contracts/math/Sqrt.sol
pragma solidity ^0.8.0;
/**
* @title Calculates the square root of a given value.
* @dev Results may be off by 1.
*/
library Sqrt {
// Source: https://github.com/ethereum/dapp-bin/pull/50
function sqrt(uint x) internal pure returns (uint y) {
if (x == 0) {
return 0;
} else if (x <= 3) {
return 1;
} else if (x == type(uint256).max) {
// Without this we fail on x + 1 below
return 2**128 - 1;
}
uint z = (x + 1) / 2;
y = x;
while (z < y) {
y = z;
z = (x / z + z) / 2;
}
}
}
// File @openzeppelin/contracts-upgradeable/utils/[email protected]
pragma solidity ^0.8.0;
/*
* @dev Provides information about the current execution context, including the
* sender of the transaction and its data. While these are generally available
* via msg.sender and msg.data, they should not be accessed in such a direct
* manner, since when dealing with meta-transactions the account sending and
* paying for execution may not be the actual sender (as far as an application
* is concerned).
*
* This contract is only required for intermediate, library-like contracts.
*/
abstract contract ContextUpgradeable is Initializable {
function __Context_init() internal initializer {
__Context_init_unchained();
}
function __Context_init_unchained() internal initializer {
}
function _msgSender() internal view virtual returns (address) {
return msg.sender;
}
function _msgData() internal view virtual returns (bytes calldata) {
this; // silence state mutability warning without generating bytecode - see https://github.com/ethereum/solidity/issues/2691
return msg.data;
}
uint256[50] private __gap;
}
// File @openzeppelin/contracts-upgradeable/access/[email protected]
pragma solidity ^0.8.0;
/**
* @dev Contract module which provides a basic access control mechanism, where
* there is an account (an owner) that can be granted exclusive access to
* specific functions.
*
* By default, the owner account will be the one that deploys the contract. This
* can later be changed with {transferOwnership}.
*
* This module is used through inheritance. It will make available the modifier
* `onlyOwner`, which can be applied to your functions to restrict their use to
* the owner.
*/
abstract contract OwnableUpgradeable is Initializable, ContextUpgradeable {
address private _owner;
event OwnershipTransferred(address indexed previousOwner, address indexed newOwner);
/**
* @dev Initializes the contract setting the deployer as the initial owner.
*/
function __Ownable_init() internal initializer {
__Context_init_unchained();
__Ownable_init_unchained();
}
function __Ownable_init_unchained() internal initializer {
address msgSender = _msgSender();
_owner = msgSender;
emit OwnershipTransferred(address(0), msgSender);
}
/**
* @dev Returns the address of the current owner.
*/
function owner() public view virtual returns (address) {
return _owner;
}
/**
* @dev Throws if called by any account other than the owner.
*/
modifier onlyOwner() {
require(owner() == _msgSender(), "Ownable: caller is not the owner");
_;
}
/**
* @dev Leaves the contract without owner. It will not be possible to call
* `onlyOwner` functions anymore. Can only be called by the current owner.
*
* NOTE: Renouncing ownership will leave the contract without an owner,
* thereby removing any functionality that is only available to the owner.
*/
function renounceOwnership() public virtual onlyOwner {
emit OwnershipTransferred(_owner, address(0));
_owner = address(0);
}
/**
* @dev Transfers ownership of the contract to a new account (`newOwner`).
* Can only be called by the current owner.
*/
function transferOwnership(address newOwner) public virtual onlyOwner {
require(newOwner != address(0), "Ownable: new owner is the zero address");
emit OwnershipTransferred(_owner, newOwner);
_owner = newOwner;
}
uint256[49] private __gap;
}
// File contracts/mixins/OperatorRole.sol
pragma solidity ^0.8.0;
// Original source: openzeppelin's SignerRole
/**
* @notice allows a single owner to manage a group of operators which may
* have some special permissions in the contract.
*/
contract OperatorRole is OwnableUpgradeable {
mapping (address => bool) internal _operators;
event OperatorAdded(address indexed account);
event OperatorRemoved(address indexed account);
function _initializeOperatorRole() internal {
__Ownable_init();
_addOperator(msg.sender);
}
modifier onlyOperator() {
require(
isOperator(msg.sender),
"OperatorRole: caller does not have the Operator role"
);
_;
}
function isOperator(address account) public view returns (bool) {
return _operators[account];
}
function addOperator(address account) public onlyOwner {
_addOperator(account);
}
function removeOperator(address account) public onlyOwner {
_removeOperator(account);
}
function renounceOperator() public {
_removeOperator(msg.sender);
}
function _addOperator(address account) internal {
_operators[account] = true;
emit OperatorAdded(account);
}
function _removeOperator(address account) internal {
_operators[account] = false;
emit OperatorRemoved(account);
}
uint[50] private ______gap;
}
// File @openzeppelin/contracts/utils/[email protected]
pragma solidity ^0.8.0;
/**
* @dev Collection of functions related to the address type
*/
library Address {
/**
* @dev Returns true if `account` is a contract.
*
* [IMPORTANT]
* ====
* It is unsafe to assume that an address for which this function returns
* false is an externally-owned account (EOA) and not a contract.
*
* Among others, `isContract` will return false for the following
* types of addresses:
*
* - an externally-owned account
* - a contract in construction
* - an address where a contract will be created
* - an address where a contract lived, but was destroyed
* ====
*/
function isContract(address account) internal view returns (bool) {
// This method relies on extcodesize, which returns 0 for contracts in
// construction, since the code is only stored at the end of the
// constructor execution.
uint256 size;
// solhint-disable-next-line no-inline-assembly
assembly { size := extcodesize(account) }
return size > 0;
}
/**
* @dev Replacement for Solidity's `transfer`: sends `amount` wei to
* `recipient`, forwarding all available gas and reverting on errors.
*
* https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost
* of certain opcodes, possibly making contracts go over the 2300 gas limit
* imposed by `transfer`, making them unable to receive funds via
* `transfer`. {sendValue} removes this limitation.
*
* https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more].
*
* IMPORTANT: because control is transferred to `recipient`, care must be
* taken to not create reentrancy vulnerabilities. Consider using
* {ReentrancyGuard} or the
* https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern].
*/
function sendValue(address payable recipient, uint256 amount) internal {
require(address(this).balance >= amount, "Address: insufficient balance");
// solhint-disable-next-line avoid-low-level-calls, avoid-call-value
(bool success, ) = recipient.call{ value: amount }("");
require(success, "Address: unable to send value, recipient may have reverted");
}
/**
* @dev Performs a Solidity function call using a low level `call`. A
* plain`call` is an unsafe replacement for a function call: use this
* function instead.
*
* If `target` reverts with a revert reason, it is bubbled up by this
* function (like regular Solidity function calls).
*
* Returns the raw returned data. To convert to the expected return value,
* use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`].
*
* 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");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with
* `errorMessage` as a fallback revert reason when `target` reverts.
*
* _Available since v3.1._
*/
function functionCall(address target, bytes memory data, string memory errorMessage) internal returns (bytes memory) {
return functionCallWithValue(target, data, 0, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but also transferring `value` wei to `target`.
*
* Requirements:
*
* - the calling contract must have an ETH balance of at least `value`.
* - the called Solidity function must be `payable`.
*
* _Available since v3.1._
*/
function functionCallWithValue(address target, bytes memory data, uint256 value) internal returns (bytes memory) {
return functionCallWithValue(target, data, value, "Address: low-level call with value failed");
}
/**
* @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but
* with `errorMessage` as a fallback revert reason when `target` reverts.
*
* _Available since v3.1._
*/
function functionCallWithValue(address target, bytes memory data, uint256 value, string memory errorMessage) internal returns (bytes memory) {
require(address(this).balance >= value, "Address: insufficient balance for call");
require(isContract(target), "Address: call to non-contract");
// solhint-disable-next-line avoid-low-level-calls
(bool success, bytes memory returndata) = target.call{ value: value }(data);
return _verifyCallResult(success, returndata, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but performing a static call.
*
* _Available since v3.3._
*/
function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) {
return functionStaticCall(target, data, "Address: low-level static call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`],
* but performing a static call.
*
* _Available since v3.3._
*/
function functionStaticCall(address target, bytes memory data, string memory errorMessage) internal view returns (bytes memory) {
require(isContract(target), "Address: static call to non-contract");
// solhint-disable-next-line avoid-low-level-calls
(bool success, bytes memory returndata) = target.staticcall(data);
return _verifyCallResult(success, returndata, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but performing a delegate call.
*
* _Available since v3.4._
*/
function functionDelegateCall(address target, bytes memory data) internal returns (bytes memory) {
return functionDelegateCall(target, data, "Address: low-level delegate call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`],
* but performing a delegate call.
*
* _Available since v3.4._
*/
function functionDelegateCall(address target, bytes memory data, string memory errorMessage) internal returns (bytes memory) {
require(isContract(target), "Address: delegate call to non-contract");
// solhint-disable-next-line avoid-low-level-calls
(bool success, bytes memory returndata) = target.delegatecall(data);
return _verifyCallResult(success, returndata, errorMessage);
}
function _verifyCallResult(bool success, bytes memory returndata, string memory errorMessage) private pure returns(bytes memory) {
if (success) {
return returndata;
} else {
// Look for revert reason and bubble it up if present
if (returndata.length > 0) {
// The easiest way to bubble the revert reason is using memory via assembly
// solhint-disable-next-line no-inline-assembly
assembly {
let returndata_size := mload(returndata)
revert(add(32, returndata), returndata_size)
}
} else {
revert(errorMessage);
}
}
}
}
// File @openzeppelin/contracts/token/ERC20/utils/[email protected]
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
/**
* @title SafeERC20
* @dev Wrappers around ERC20 operations that throw on failure (when the token
* contract returns false). Tokens that return no value (and instead revert or
* throw on failure) are also supported, non-reverting calls are assumed to be
* successful.
* To use this library you can add a `using SafeERC20 for IERC20;` statement to your contract,
* which allows you to call the safe operations as `token.safeTransfer(...)`, etc.
*/
library SafeERC20 {
using Address for address;
function safeTransfer(IERC20 token, address to, uint256 value) internal {
_callOptionalReturn(token, abi.encodeWithSelector(token.transfer.selector, to, value));
}
function safeTransferFrom(IERC20 token, address from, address to, uint256 value) internal {
_callOptionalReturn(token, abi.encodeWithSelector(token.transferFrom.selector, from, to, value));
}
/**
* @dev Deprecated. This function has issues similar to the ones found in
* {IERC20-approve}, and its usage is discouraged.
*
* Whenever possible, use {safeIncreaseAllowance} and
* {safeDecreaseAllowance} instead.
*/
function safeApprove(IERC20 token, address spender, uint256 value) internal {
// safeApprove should only be called when setting an initial allowance,
// or when resetting it to zero. To increase and decrease it, use
// 'safeIncreaseAllowance' and 'safeDecreaseAllowance'
// solhint-disable-next-line max-line-length
require((value == 0) || (token.allowance(address(this), spender) == 0),
"SafeERC20: approve from non-zero to non-zero allowance"
);
_callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, value));
}
function safeIncreaseAllowance(IERC20 token, address spender, uint256 value) internal {
uint256 newAllowance = token.allowance(address(this), spender) + value;
_callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance));
}
function safeDecreaseAllowance(IERC20 token, address spender, uint256 value) internal {
unchecked {
uint256 oldAllowance = token.allowance(address(this), spender);
require(oldAllowance >= value, "SafeERC20: decreased allowance below zero");
uint256 newAllowance = oldAllowance - value;
_callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance));
}
}
/**
* @dev Imitates a Solidity high-level call (i.e. a regular function call to a contract), relaxing the requirement
* on the return value: the return value is optional (but if data is returned, it must not be false).
* @param token The token targeted by the call.
* @param data The call data (encoded using abi.encode or one of its variants).
*/
function _callOptionalReturn(IERC20 token, bytes memory data) private {
// We need to perform a low level call here, to bypass Solidity's return data size checking mechanism, since
// we're implementing it ourselves. We use {Address.functionCall} to perform this call, which verifies that
// the target address contains contract code and also asserts for success in the low-level call.
bytes memory returndata = address(token).functionCall(data, "SafeERC20: low-level call failed");
if (returndata.length > 0) { // Return data is optional
// solhint-disable-next-line max-line-length
require(abi.decode(returndata, (bool)), "SafeERC20: ERC20 operation did not succeed");
}
}
}
// File contracts/CAFE.sol
pragma solidity ^0.8.3;
pragma abicoder v2;
/**
* @title Continuous Agreement for Future Equity
*/
contract CAFE
is ERC20ReInitializable
{
using Sqrt for uint;
using SafeERC20 for IERC20;
event Buy(
address indexed _from,
address indexed _to,
uint _currencyValue,
uint _fairValue
);
event Sell(
address indexed _from,
address indexed _to,
uint _currencyValue,
uint _fairValue
);
event Burn(
address indexed _from,
uint _fairValue
);
event StateChange(
uint _previousState,
uint _newState
);
event Close();
event UpdateConfig(
address _whitelistAddress,
address indexed _beneficiary,
address indexed _control,
address indexed _feeCollector,
uint _feeBasisPoints,
uint _minInvestment,
uint _minDuration,
uint _stakeholdersPoolAuthorized,
uint _gasFee
);
//
// Constants
//
enum State {
Init,
Run,
Close,
Cancel
}
// The denominator component for values specified in basis points.
uint internal constant BASIS_POINTS_DEN = 10000;
uint internal constant MAX_ITERATION = 10;
/**
* Data specific to our token business logic
*/
/// @notice The contract for transfer authorizations, if any.
IWhitelist public whitelist;
/// @notice The total number of burned FAIR tokens, excluding tokens burned from a `Sell` action in the DAT.
uint public burnedSupply;
/**
* Data for DAT business logic
*/
/// @notice The address of the beneficiary organization which receives the investments.
/// Points to the wallet of the organization.
address payable public beneficiary;
struct BuySlope {
uint128 num;
uint128 den;
}
BuySlope public buySlope;
/// @notice The address from which the updatable variables can be updated
address public control;
/// @notice The address of the token used as reserve in the bonding curve
/// (e.g. the DAI contract). Use ETH if 0.
IERC20 public currency;
/// @notice The address where fees are sent.
address payable public feeCollector;
/// @notice The percent fee collected each time new FAIR are issued expressed in basis points.
uint public feeBasisPoints;
/// @notice The initial fundraising goal (expressed in FAIR) to start the c-org.
/// `0` means that there is no initial fundraising and the c-org immediately moves to run state.
uint public initGoal;
/// @notice A map with all investors in init state using address as a key and amount as value.
/// @dev This structure's purpose is to make sure that only investors can withdraw their money if init_goal is not reached.
mapping(address => uint) public initInvestors;
/// @notice The initial number of FAIR created at initialization for the beneficiary.
/// Technically however, this variable is not a constant as we must always have
///`init_reserve>=total_supply+burnt_supply` which means that `init_reserve` will be automatically
/// decreased to equal `total_supply+burnt_supply` in case `init_reserve>total_supply+burnt_supply`
/// after an investor sells his FAIRs.
/// @dev Organizations may move these tokens into vesting contract(s)
uint public initReserve;
/// @notice The minimum amount of `currency` investment accepted.
uint public minInvestment;
/// @notice The current state of the contract.
/// @dev See the constants above for possible state values.
State public state;
/// @dev If this value changes we need to reconstruct the DOMAIN_SEPARATOR
string public constant version = "cafe-2.0";
// --- EIP712 niceties ---
// Original source: https://etherscan.io/address/0x6b175474e89094c44da98b954eedeac495271d0f#code
mapping (address => uint) public nonces;
bytes32 public DOMAIN_SEPARATOR;
// keccak256("Permit(address owner,address spender,uint256 value,uint256 nonce,uint256 deadline)");
bytes32 public constant PERMIT_TYPEHASH = 0x6e71edae12b1b97f4d1f60370fef10105fa2faae0126114a169c64845d6126c9;
// The success fee (expressed in currency) that will be earned by setupFeeRecipient as soon as initGoal
// is reached. We must have setup_fee <= buy_slope*init_goal^(2)/2
uint public setupFee;
// The recipient of the setup_fee once init_goal is reached
address payable public setupFeeRecipient;
/// @notice The minimum time before which the c-org contract cannot be closed once the contract has
/// reached the `run` state.
/// @dev When updated, the new value of `minimum_duration` cannot be earlier than the previous value.
uint public minDuration;
/// @dev Initialized at `0` and updated when the contract switches from `init` state to `run` state
/// or when the initial trial period ends.
uint private startedOn;
// keccak256("PermitBuy(address from,address to,uint256 currencyValue,uint256 minTokensBought,uint256 nonce,uint256 deadline)");
bytes32 public constant PERMIT_BUY_TYPEHASH = 0xaf42a244b3020d6a2253d9f291b4d3e82240da42b22129a8113a58aa7a3ddb6a;
// keccak256("PermitSell(address from,address to,uint256 quantityToSell,uint256 minCurrencyReturned,uint256 nonce,uint256 deadline)");
bytes32 public constant PERMIT_SELL_TYPEHASH = 0x5dfdc7fb4c68a4c249de5e08597626b84fbbe7bfef4ed3500f58003e722cc548;
// stkaeholdersPool struct separated
uint public stakeholdersPoolIssued;
uint public stakeholdersPoolAuthorized;
// The orgs commitement that backs the value of CAFEs.
// This value may be increased but not decreased.
uint public equityCommitment;
// Total number of tokens that have been attributed to current shareholders
uint public shareholdersPool;
// The max number of CAFEs investors can purchase (excludes the stakeholdersPool)
uint public maxGoal;
// The amount of CAFE to be sold to exit the trial mode.
// 0 means there is no trial.
uint public initTrial;
// Represents the fundraising amount that can be sold as a fixed price
uint public fundraisingGoal;
// To fund operator a gasFee
uint public gasFee;
// increased when manual buy
uint public manualBuybackReserve;
uint public totalInvested;
bytes32 private constant BEACON_SLOT = keccak256(abi.encodePacked("fairmint.beaconproxy.beacon"));
modifier onlyBeaconOperator() {
bytes32 slot = BEACON_SLOT;
address beacon;
assembly {
beacon := sload(slot)
}
require(beacon == address(0) || OperatorRole(beacon).isOperator(msg.sender), "!BeaconOperator");
_;
}
modifier authorizeTransfer(
address _from,
address _to,
uint _value,
bool _isSell
)
{
require(state != State.Close, "INVALID_STATE");
if(address(whitelist) != address(0))
{
// This is not set for the minting of initialReserve
whitelist.authorizeTransfer(_from, _to, _value, _isSell);
}
_;
}
/**
* BuySlope
*/
function buySlopeNum() external view returns(uint256) {
return uint256(buySlope.num);
}
function buySlopeDen() external view returns(uint256) {
return uint256(buySlope.den);
}
/**
* Stakeholders Pool
*/
function stakeholdersPool() public view returns (uint256 issued, uint256 authorized) {
return (stakeholdersPoolIssued, stakeholdersPoolAuthorized);
}
function trialEndedOn() public view returns(uint256 timestamp) {
return startedOn;
}
/**
* Buyback reserve
*/
/// @notice The total amount of currency value currently locked in the contract and available to sellers.
function buybackReserve() public view returns (uint)
{
uint reserve = address(this).balance;
if(address(currency) != address(0))
{
reserve = currency.balanceOf(address(this));
}
if(reserve > type(uint128).max)
{
/// Math: If the reserve becomes excessive, cap the value to prevent overflowing in other formulas
return type(uint128).max;
}
return reserve + manualBuybackReserve;
}
/**
* Functions required by the ERC-20 token standard
*/
/// @dev Moves tokens from one account to another if authorized.
function _transfer(
address _from,
address _to,
uint _amount
) internal override
authorizeTransfer(_from, _to, _amount, false)
{
require(state != State.Init || _from == beneficiary, "ONLY_BENEFICIARY_DURING_INIT");
super._transfer(_from, _to, _amount);
}
/// @dev Removes tokens from the circulating supply.
function _burn(
address _from,
uint _amount,
bool _isSell
) internal
authorizeTransfer(_from, address(0), _amount, _isSell)
{
super._burn(_from, _amount);
if(!_isSell)
{
// This is a burn
// SafeMath not required as we cap how high this value may get during mint
burnedSupply += _amount;
emit Burn(_from, _amount);
}
}
/// @notice Called to mint tokens on `buy`.
function _mint(
address _to,
uint _quantity
) internal override
authorizeTransfer(address(0), _to, _quantity, false)
{
super._mint(_to, _quantity);
// Math: If this value got too large, the DAT may overflow on sell
require(totalSupply() + burnedSupply <= type(uint128).max, "EXCESSIVE_SUPPLY");
}
/**
* Transaction Helpers
*/
/// @notice Confirms the transfer of `_quantityToInvest` currency to the contract.
function _collectInvestment(
address payable _from,
uint _quantityToInvest,
uint _msgValue
) internal
{
if(address(currency) == address(0))
{
// currency is ETH
require(_quantityToInvest == _msgValue, "INCORRECT_MSG_VALUE");
}
else
{
// currency is ERC20
require(_msgValue == 0, "DO_NOT_SEND_ETH");
currency.safeTransferFrom(_from, address(this), _quantityToInvest);
}
}
/// @dev Send `_amount` currency from the contract to the `_to` account.
function _transferCurrency(
address payable _to,
uint _amount
) internal
{
if(_amount > 0)
{
if(address(currency) == address(0))
{
Address.sendValue(_to, _amount);
}
else
{
currency.safeTransfer(_to, _amount);
}
}
}
/**
* Config / Control
*/
struct MileStone {
uint128 initReserve;
uint128 initTrial;
uint128 initGoal;
uint128 maxGoal;
}
/// @notice Called once after deploy to set the initial configuration.
/// None of the values provided here may change once initially set.
/// @dev using the init pattern in order to support zos upgrades
function initialize(
string calldata _name,
string calldata _symbol,
address _currencyAddress,
MileStone calldata _mileStone,
BuySlope calldata _buySlope,
uint _stakeholdersAuthorized,
uint _equityCommitment,
uint _setupFee,
address payable _setupFeeRecipient
) external
onlyBeaconOperator
{
// _initialize will enforce this is only called once
// The ERC-20 implementation will confirm initialize is only run once
ERC20ReInitializable.__ERC20_init(_name, _symbol);
_initialize(
_currencyAddress,
_mileStone,
_buySlope,
_stakeholdersAuthorized,
_equityCommitment,
_setupFee,
_setupFeeRecipient
);
}
function reInitialize(
string calldata _name,
string calldata _symbol,
address _currencyAddress,
MileStone calldata _mileStone,
BuySlope calldata _buySlope,
uint _stakeholdersAuthorized,
uint _equityCommitment,
uint _setupFee,
address payable _setupFeeRecipient
) external {
require(msg.sender == beneficiary, "ONLY_BENEFICIARY_CAN_REINITIALIZE");
require(balanceOf(msg.sender) == totalSupply(), "BENEFICIARY_SHOULD_HAVE_ALL_TOKENS");
require(initReserve == totalSupply(), "SHOULD_NOT_HAVE_RECEIVED_ANY_FUND");
ERC20ReInitializable.__ERC20_re_initialize(_name, _symbol);
_burn(msg.sender, totalSupply());
_initialize(
_currencyAddress,
_mileStone,
_buySlope,
_stakeholdersAuthorized,
_equityCommitment,
_setupFee,
_setupFeeRecipient
);
}
function _initialize(
address _currencyAddress,
MileStone memory _mileStone,
BuySlope memory _buySlope,
uint _stakeholdersAuthorized,
uint _equityCommitment,
uint _setupFee,
address payable _setupFeeRecipient
) internal {
require(_buySlope.num > 0, "INVALID_SLOPE_NUM");
require(_buySlope.den > 0, "INVALID_SLOPE_DEN");
buySlope = _buySlope;
// Setup Fee
require(_setupFee == 0 || _setupFeeRecipient != address(0), "MISSING_SETUP_FEE_RECIPIENT");
require(_setupFeeRecipient == address(0) || _setupFee != 0, "MISSING_SETUP_FEE");
// setup_fee <= (n/d)*(g^2)/2
uint initGoalInCurrency = uint256(_mileStone.initGoal) * uint256(_mileStone.initGoal);
initGoalInCurrency = initGoalInCurrency * uint256(_buySlope.num);
initGoalInCurrency /= 2 * uint256(_buySlope.den);
require(_setupFee <= initGoalInCurrency, "EXCESSIVE_SETUP_FEE");
setupFee = _setupFee;
setupFeeRecipient = _setupFeeRecipient;
// Set default values (which may be updated using `updateConfig`)
uint decimals = 18;
if(_currencyAddress != address(0)){
decimals = IERC20Metadata(_currencyAddress).decimals();
}
minInvestment = 100 * (10 ** decimals);
beneficiary = payable(msg.sender);
control = msg.sender;
feeCollector = payable(msg.sender);
// Save currency
currency = IERC20(_currencyAddress);
// Mint the initial reserve
if(_mileStone.initReserve > 0)
{
initReserve = _mileStone.initReserve;
_mint(beneficiary, initReserve);
}
initializeDomainSeparator();
// Math: If this value got too large, the DAT would overflow on sell
// new settings for CAFE
require(_mileStone.maxGoal == 0 || _mileStone.initGoal == 0 || _mileStone.maxGoal >= _mileStone.initGoal, "MAX_GOAL_SMALLER_THAN_INIT_GOAL");
require(_mileStone.initGoal == 0 || _mileStone.initTrial == 0 || _mileStone.initGoal >= _mileStone.initTrial, "INIT_GOAL_SMALLER_THAN_INIT_TRIAL");
maxGoal = _mileStone.maxGoal;
initTrial = _mileStone.initTrial;
stakeholdersPoolIssued = _mileStone.initReserve;
require(_stakeholdersAuthorized <= BASIS_POINTS_DEN, "STAKEHOLDERS_POOL_AUTHORIZED_SHOULD_BE_SMALLER_THAN_BASIS_POINTS_DEN");
stakeholdersPoolAuthorized = _stakeholdersAuthorized;
require(_equityCommitment > 0, "EQUITY_COMMITMENT_CANNOT_BE_ZERO");
require(_equityCommitment <= BASIS_POINTS_DEN, "EQUITY_COMMITMENT_SHOULD_BE_LESS_THAN_100%");
equityCommitment = _equityCommitment;
// Set initGoal, which in turn defines the initial state
if(_mileStone.initGoal == 0)
{
_stateChange(State.Run);
startedOn = block.timestamp;
}
else
{
initGoal = _mileStone.initGoal;
state = State.Init;
startedOn = 0;
}
}
function _stateChange(State _state) internal {
emit StateChange(uint256(state), uint256(_state));
state = _state;
}
function updateConfig(
address _whitelistAddress,
address payable _beneficiary,
address _control,
address payable _feeCollector,
uint _feeBasisPoints,
uint _minInvestment,
uint _minDuration,
uint _stakeholdersAuthorized,
uint _gasFee
) external
{
// This require(also confirms that initialize has been called.
require(msg.sender == control, "CONTROL_ONLY");
// address(0) is okay
whitelist = IWhitelist(_whitelistAddress);
require(_control != address(0), "INVALID_ADDRESS");
control = _control;
require(_feeCollector != address(0), "INVALID_ADDRESS");
feeCollector = _feeCollector;
require(_feeBasisPoints <= BASIS_POINTS_DEN, "INVALID_FEE");
feeBasisPoints = _feeBasisPoints;
require(_minInvestment > 0, "INVALID_MIN_INVESTMENT");
minInvestment = _minInvestment;
require(_minDuration >= minDuration, "MIN_DURATION_MAY_NOT_BE_REDUCED");
minDuration = _minDuration;
if(beneficiary != _beneficiary)
{
require(_beneficiary != address(0), "INVALID_ADDRESS");
uint tokens = balanceOf(beneficiary);
initInvestors[_beneficiary] = initInvestors[_beneficiary] + initInvestors[beneficiary];
initInvestors[beneficiary] = 0;
if(tokens > 0)
{
_transfer(beneficiary, _beneficiary, tokens);
}
beneficiary = _beneficiary;
}
// new settings for CAFE
require(_stakeholdersAuthorized <= BASIS_POINTS_DEN, "STAKEHOLDERS_POOL_AUTHORIZED_SHOULD_BE_SMALLER_THAN_BASIS_POINTS_DEN");
stakeholdersPoolAuthorized = _stakeholdersAuthorized;
gasFee = _gasFee;
emit UpdateConfig(
_whitelistAddress,
_beneficiary,
_control,
_feeCollector,
_feeBasisPoints,
_minInvestment,
_minDuration,
_stakeholdersAuthorized,
_gasFee
);
}
/// @notice Used to initialize the domain separator used in meta-transactions
/// @dev This is separate from `initialize` to allow upgraded contracts to update the version
/// There is no harm in calling this multiple times / no permissions required
function initializeDomainSeparator() public
{
uint id;
// solium-disable-next-line
assembly
{
id := chainid()
}
DOMAIN_SEPARATOR = keccak256(
abi.encode(
keccak256("EIP712Domain(string name,string version,uint256 chainId,address verifyingContract)"),
keccak256(bytes(name())),
keccak256(bytes(version)),
id,
address(this)
)
);
}
/**
* Functions for our business logic
*/
/// @notice Burn the amount of tokens from the address msg.sender if authorized.
/// @dev Note that this is not the same as a `sell` via the DAT.
function burn(
uint _amount
) public
{
require(state == State.Run, "INVALID_STATE");
require(msg.sender == beneficiary, "BENEFICIARY_ONLY");
_burn(msg.sender, _amount, false);
}
// Buy
/// @notice Purchase FAIR tokens with the given amount of currency.
/// @param _to The account to receive the FAIR tokens from this purchase.
/// @param _currencyValue How much currency to spend in order to buy FAIR.
/// @param _minTokensBought Buy at least this many FAIR tokens or the transaction reverts.
/// @dev _minTokensBought is necessary as the price will change if some elses transaction mines after
/// yours was submitted.
function buy(
address _to,
uint _currencyValue,
uint _minTokensBought
) public payable
{
_collectInvestment(payable(msg.sender), _currencyValue, msg.value);
//deduct gas fee and send it to feeCollector
uint256 currencyValue = _currencyValue - gasFee;
_transferCurrency(feeCollector, gasFee);
_buy(payable(msg.sender), _to, currencyValue, _minTokensBought, false);
}
/// @notice Allow users to sign a message authorizing a buy
function permitBuy(
address payable _from,
address _to,
uint _currencyValue,
uint _minTokensBought,
uint _deadline,
uint8 _v,
bytes32 _r,
bytes32 _s
) external
{
require(_deadline >= block.timestamp, "EXPIRED");
bytes32 digest = keccak256(abi.encode(PERMIT_BUY_TYPEHASH, _from, _to, _currencyValue, _minTokensBought, nonces[_from]++, _deadline));
digest = keccak256(
abi.encodePacked(
"\x19\x01",
DOMAIN_SEPARATOR,
digest
)
);
address recoveredAddress = ecrecover(digest, _v, _r, _s);
require(recoveredAddress != address(0) && recoveredAddress == _from, "INVALID_SIGNATURE");
// CHECK !!! this is suspicious!! 0 should be msg.value but this is not payable function
// msg.value will be zero since it is non-payable function and designed to be used to usdc-base CAFE contract
_collectInvestment(_from, _currencyValue, 0);
uint256 currencyValue = _currencyValue - gasFee;
_transferCurrency(feeCollector, gasFee);
_buy(_from, _to, currencyValue, _minTokensBought, false);
}
function _buy(
address payable _from,
address _to,
uint _currencyValue,
uint _minTokensBought,
bool _manual
) internal
{
require(_to != address(0), "INVALID_ADDRESS");
require(_to != beneficiary, "BENEFICIARY_CANNOT_BUY");
require(_minTokensBought > 0, "MUST_BUY_AT_LEAST_1");
require(state == State.Init || state == State.Run, "ONLY_BUY_IN_INIT_OR_RUN");
// Calculate the tokenValue for this investment
// returns zero if _currencyValue < minInvestment
uint tokenValue = _estimateBuyValue(_currencyValue);
require(tokenValue >= _minTokensBought, "PRICE_SLIPPAGE");
if(state == State.Init){
if(tokenValue + shareholdersPool < initTrial){
//already received all currency from _collectInvestment
if(!_manual) {
initInvestors[_to] = initInvestors[_to] + tokenValue;
}
initTrial = initTrial - tokenValue;
}
else if (initTrial > shareholdersPool){
//already received all currency from _collectInvestment
//send setup fee to beneficiary
if(setupFee > 0){
_transferCurrency(setupFeeRecipient, setupFee);
}
_distributeInvestment(buybackReserve() - manualBuybackReserve);
manualBuybackReserve = 0;
initTrial = shareholdersPool;
startedOn = block.timestamp;
}
else{
_distributeInvestment(buybackReserve() - manualBuybackReserve);
manualBuybackReserve = 0;
}
}
else { //state == State.Run
require(maxGoal == 0 || tokenValue + totalSupply() - stakeholdersPoolIssued <= maxGoal, "EXCEEDING_MAX_GOAL");
_distributeInvestment(buybackReserve() - manualBuybackReserve);
manualBuybackReserve = 0;
if(fundraisingGoal != 0){
if (tokenValue >= fundraisingGoal){
changeBuySlope(totalSupply() - stakeholdersPoolIssued, fundraisingGoal + totalSupply() - stakeholdersPoolIssued);
fundraisingGoal = 0;
} else { //if (tokenValue < fundraisingGoal) {
changeBuySlope(totalSupply() - stakeholdersPoolIssued, tokenValue + totalSupply() - stakeholdersPoolIssued);
fundraisingGoal -= tokenValue;
}
}
}
totalInvested = totalInvested + _currencyValue;
emit Buy(_from, _to, _currencyValue, tokenValue);
_mint(_to, tokenValue);
if(state == State.Init && totalSupply() - stakeholdersPoolIssued >= initGoal){
_stateChange(State.Run);
}
}
/// @dev Distributes _value currency between the beneficiary and feeCollector.
function _distributeInvestment(
uint _value
) internal
{
uint fee = _value * feeBasisPoints;
fee /= BASIS_POINTS_DEN;
// Math: since feeBasisPoints is <= BASIS_POINTS_DEN, this will never underflow.
_transferCurrency(beneficiary, _value - fee);
_transferCurrency(feeCollector, fee);
}
function estimateBuyValue(
uint _currencyValue
) external view
returns(uint)
{
return _estimateBuyValue(_currencyValue - gasFee);
}
/// @notice Calculate how many FAIR tokens you would buy with the given amount of currency if `buy` was called now.
/// @param _currencyValue How much currency to spend in order to buy FAIR.
function _estimateBuyValue(
uint _currencyValue
) internal view
returns(uint)
{
if(_currencyValue < minInvestment){
return 0;
}
if(state == State.Init){
uint currencyValue = _currencyValue;
uint _totalSupply = totalSupply();
uint max = BigDiv.bigDiv2x1(
initGoal * buySlope.num,
initGoal - (_totalSupply - stakeholdersPoolIssued),
buySlope.den
);
if(currencyValue > max)
{
currencyValue = max;
}
uint256 tokenAmount = BigDiv.bigDiv2x1(
currencyValue,
buySlope.den,
initGoal * buySlope.num
);
if(currencyValue != _currencyValue)
{
currencyValue = _currencyValue - max;
// ((2*next_amount/buy_slope)+init_goal^2)^(1/2)-init_goal
// a: next_amount | currencyValue
// n/d: buy_slope (type(uint128).max / type(uint128).max)
// g: init_goal (type(uint128).max/2)
// r: init_reserve (type(uint128).max/2)
// sqrt(((2*a/(n/d))+g^2)-g
// sqrt((2 d a + n g^2)/n) - g
// currencyValue == 2 d a
uint temp = 2 * buySlope.den;
currencyValue = temp * currencyValue;
// temp == g^2
temp = initGoal;
temp *= temp;
// temp == n g^2
temp = temp * buySlope.num;
// temp == (2 d a) + n g^2
temp = currencyValue + temp;
// temp == (2 d a + n g^2)/n
temp /= buySlope.num;
// temp == sqrt((2 d a + n g^2)/n)
temp = temp.sqrt();
// temp == sqrt((2 d a + n g^2)/n) - g
temp -= initGoal;
tokenAmount = tokenAmount + temp;
}
return tokenAmount;
}
else if(state == State.Run) {//state == State.Run{
uint supply = totalSupply() - stakeholdersPoolIssued;
// calculate fundraising amount (static price)
uint currencyValue = _currencyValue;
uint fundraisedAmount;
if(fundraisingGoal > 0){
uint max = BigDiv.bigDiv2x1(
supply,
fundraisingGoal * buySlope.num,
buySlope.den
);
if(currencyValue > max){
currencyValue = max;
}
fundraisedAmount = BigDiv.bigDiv2x2(
currencyValue,
buySlope.den,
supply,
buySlope.num
);
//forward leftover currency to be used as normal buy
currencyValue = _currencyValue - currencyValue;
}
// initReserve is reduced on sell as necessary to ensure that this line will not overflow
// Math: worst case
// MAX * 2 * type(uint128).max
// / type(uint128).max
uint tokenAmount = BigDiv.bigDiv2x1(
currencyValue,
2 * buySlope.den,
buySlope.num
);
// Math: worst case MAX + (type(uint128).max * type(uint128).max)
tokenAmount = tokenAmount + supply * supply;
tokenAmount = tokenAmount.sqrt();
// Math: small chance of underflow due to possible rounding in sqrt
tokenAmount = tokenAmount - supply;
return fundraisedAmount + tokenAmount;
} else {
return 0;
}
}
// Sell
/// @notice Sell FAIR tokens for at least the given amount of currency.
/// @param _to The account to receive the currency from this sale.
/// @param _quantityToSell How many FAIR tokens to sell for currency value.
/// @param _minCurrencyReturned Get at least this many currency tokens or the transaction reverts.
/// @dev _minCurrencyReturned is necessary as the price will change if some elses transaction mines after
/// yours was submitted.
function sell(
address payable _to,
uint _quantityToSell,
uint _minCurrencyReturned
) public
{
_sell(msg.sender, _to, _quantityToSell, _minCurrencyReturned);
}
/// @notice Allow users to sign a message authorizing a sell
function permitSell(
address _from,
address payable _to,
uint _quantityToSell,
uint _minCurrencyReturned,
uint _deadline,
uint8 _v,
bytes32 _r,
bytes32 _s
) external
{
require(_deadline >= block.timestamp, "EXPIRED");
bytes32 digest = keccak256(
abi.encode(PERMIT_SELL_TYPEHASH, _from, _to, _quantityToSell, _minCurrencyReturned, nonces[_from]++, _deadline)
);
digest = keccak256(
abi.encodePacked(
"\x19\x01",
DOMAIN_SEPARATOR,
digest
)
);
address recoveredAddress = ecrecover(digest, _v, _r, _s);
require(recoveredAddress != address(0) && recoveredAddress == _from, "INVALID_SIGNATURE");
_sell(_from, _to, _quantityToSell, _minCurrencyReturned);
}
function _sell(
address _from,
address payable _to,
uint _quantityToSell,
uint _minCurrencyReturned
) internal
{
require(_from != beneficiary, "BENEFICIARY_CANNOT_SELL");
require(state != State.Init || initTrial != shareholdersPool, "INIT_TRIAL_ENDED");
require(state == State.Init || state == State.Cancel, "ONLY_SELL_IN_INIT_OR_CANCEL");
require(_minCurrencyReturned > 0, "MUST_SELL_AT_LEAST_1");
// check for slippage
uint currencyValue = estimateSellValue(_quantityToSell);
require(currencyValue >= _minCurrencyReturned, "PRICE_SLIPPAGE");
// it will work as checking _from has morethan _quantityToSell as initInvestors
initInvestors[_from] = initInvestors[_from] - _quantityToSell;
_burn(_from, _quantityToSell, true);
_transferCurrency(_to, currencyValue);
if(state == State.Init && initTrial != 0){
// this can only happen if initTrial is set to zero from day one
initTrial = initTrial + _quantityToSell;
}
totalInvested = totalInvested - currencyValue;
emit Sell(_from, _to, currencyValue, _quantityToSell);
}
function estimateSellValue(
uint _quantityToSell
) public view
returns(uint)
{
if(state != State.Init && state != State.Cancel){
return 0;
}
uint reserve = buybackReserve();
// Calculate currencyValue for this sale
uint currencyValue;
// State.Init or State.Cancel
// Math worst case:
// MAX * type(uint128).max
currencyValue = _quantityToSell * reserve;
// Math: FAIR blocks initReserve from being burned unless we reach the RUN state which prevents an underflow
currencyValue /= totalSupply() - stakeholdersPoolIssued - shareholdersPool;
return currencyValue;
}
// Close
/// @notice Called by the beneficiary account to State.Close or State.Cancel the c-org,
/// preventing any more tokens from being minted.
function close() public
{
_close();
emit Close();
}
/// @notice Called by the beneficiary account to State.Close or State.Cancel the c-org,
/// preventing any more tokens from being minted.
/// @dev Requires an `exitFee` to be paid. If the currency is ETH, include a little more than
/// what appears to be required and any remainder will be returned to your account. This is
/// because another user may have a transaction mined which changes the exitFee required.
/// For other `currency` types, the beneficiary account will be billed the exact amount required.
function _close() internal
{
require(msg.sender == beneficiary, "BENEFICIARY_ONLY");
if(state == State.Init)
{
// Allow the org to cancel anytime if the initGoal was not reached.
require(initTrial > shareholdersPool,"CANNOT_CANCEL_IF_INITTRIAL_IS_ZERO");
_stateChange(State.Cancel);
}
else if(state == State.Run)
{
require(type(uint256).max - minDuration > startedOn, "MAY_NOT_CLOSE");
require(minDuration + startedOn <= block.timestamp, "TOO_EARLY");
_stateChange(State.Close);
}
else
{
revert("INVALID_STATE");
}
}
/// @notice mint new CAFE and send them to `wallet`
function mint(
address _wallet,
uint256 _amount
) external
{
require(msg.sender == beneficiary, "ONLY_BENEFICIARY_CAN_MINT");
require(
_amount + stakeholdersPoolIssued <= (stakeholdersPoolAuthorized * (totalSupply() + _amount)) / BASIS_POINTS_DEN,
"CANNOT_MINT_MORE_THAN_AUTHORIZED_PERCENTAGE"
);
//update stakeholdersPool issued value
stakeholdersPoolIssued = stakeholdersPoolIssued + _amount;
address to = _wallet == address(0) ? beneficiary : _wallet;
//check if wallet is whitelist in the _mint() function
_mint(to, _amount);
}
function manualBuy(
address payable _wallet,
uint256 _currencyValue
) external
{
require(msg.sender == beneficiary, "ONLY_BENEFICIARY_CAN_MINT");
manualBuybackReserve += _currencyValue;
_buy(_wallet, _wallet, _currencyValue, 1, true);
}
function increaseCommitment(
uint256 _newCommitment,
uint256 _amount
) external
{
require(state == State.Init || state == State.Run, "ONLY_IN_INIT_OR_RUN");
require(msg.sender == beneficiary, "ONLY_BENEFICIARY_CAN_INCREASE_COMMITMENT");
require(_newCommitment > 0, "COMMITMENT_CANT_BE_ZERO");
require(equityCommitment + _newCommitment <= BASIS_POINTS_DEN, "EQUITY_COMMITMENT_SHOULD_BE_LESS_THAN_100%");
equityCommitment = equityCommitment + _newCommitment;
if(_amount > 0 ){
if(state == State.Init){
changeBuySlope(initGoal, _amount + initGoal);
initGoal = initGoal + _amount;
} else {
fundraisingGoal = _amount;
}
if(maxGoal != 0){
maxGoal = maxGoal + _amount;
}
}
}
function convertToCafe(
uint256 _newCommitment,
uint256 _amount,
address _wallet
) external {
require(state == State.Init || state == State.Run, "ONLY_IN_INIT_OR_RUN");
require(msg.sender == beneficiary, "ONLY_BENEFICIARY_CAN_INCREASE_COMMITMENT");
require(_newCommitment > 0, "COMMITMENT_CANT_BE_ZERO");
require(equityCommitment + _newCommitment <= BASIS_POINTS_DEN, "EQUITY_COMMITMENT_SHOULD_BE_LESS_THAN_100%");
require(_wallet != beneficiary && _wallet != address(0), "WALLET_CANNOT_BE_ZERO_OR_BENEFICIARY");
equityCommitment = equityCommitment + _newCommitment;
if(_amount > 0 ){
shareholdersPool = shareholdersPool + _amount;
if(state == State.Init){
changeBuySlope(initGoal, _amount + initGoal);
initGoal = initGoal + _amount;
if(initTrial != 0){
initTrial = initTrial + _amount;
}
}
else {
changeBuySlope(totalSupply() - stakeholdersPoolIssued, _amount + totalSupply() - stakeholdersPoolIssued);
}
_mint(_wallet, _amount);
if(maxGoal != 0){
maxGoal = maxGoal + _amount;
}
}
}
function increaseValuation(uint256 _newValuation) external {
require(state == State.Init || state == State.Run, "ONLY_IN_INIT_OR_RUN");
require(msg.sender == beneficiary, "ONLY_BENEFICIARY_CAN_INCREASE_VALUATION");
uint256 oldValuation;
if(state == State.Init){
oldValuation = (initGoal * initGoal * buySlope.num * BASIS_POINTS_DEN) / (buySlope.den * equityCommitment);
require(_newValuation > oldValuation, "VALUATION_CAN_NOT_DECREASE");
changeBuySlope(_newValuation, oldValuation);
}else {
oldValuation = ((totalSupply() - stakeholdersPoolIssued) * (totalSupply() - stakeholdersPoolIssued) * buySlope.num * BASIS_POINTS_DEN) / (buySlope.den * equityCommitment);
require(_newValuation > oldValuation, "VALUATION_CAN_NOT_DECREASE");
changeBuySlope(_newValuation, oldValuation);
}
}
function changeBuySlope(uint256 _numerator, uint256 _denominator) internal {
require(_denominator > 0, "DIV_0");
if(_numerator == 0){
buySlope.num = 0;
return;
}
uint256 tryDen = BigDiv.bigDiv2x1(
buySlope.den,
_denominator,
_numerator
);
if(tryDen <= type(uint128).max){
buySlope.den = uint128(tryDen);
return;
}
//if den exceeds type(uint128).max try num
uint256 tryNum = BigDiv.bigDiv2x1(
buySlope.num,
_numerator,
_denominator
);
if(tryNum > 0 && tryNum <= type(uint128).max) {
buySlope.num = uint128(tryNum);
return;
}
revert("error while changing slope");
}
function batchTransfer(address[] calldata recipients, uint256[] calldata amounts) external {
require(msg.sender == beneficiary, "ONLY_BENEFICIARY_CAN_BATCH_TRANSFER");
require(recipients.length == amounts.length, "ARRAY_LENGTH_DIFF");
require(recipients.length <= MAX_ITERATION, "EXCEEDS_MAX_ITERATION");
for(uint256 i = 0; i<recipients.length; i++) {
_transfer(msg.sender, recipients[i], amounts[0]);
}
}
/// @notice Pay the organization on-chain without minting any tokens.
/// @dev This allows you to add funds directly to the buybackReserve.
receive() external payable {
require(address(currency) == address(0), "ONLY_FOR_CURRENCY_ETH");
}
// --- Approve by signature ---
// EIP-2612
// Original source: https://github.com/Uniswap/uniswap-v2-core/blob/master/contracts/UniswapV2ERC20.sol
function permit(
address owner,
address spender,
uint value,
uint deadline,
uint8 v,
bytes32 r,
bytes32 s
) external
{
require(deadline >= block.timestamp, "EXPIRED");
bytes32 digest = keccak256(abi.encode(PERMIT_TYPEHASH, owner, spender, value, nonces[owner]++, deadline));
digest = keccak256(
abi.encodePacked(
"\x19\x01",
DOMAIN_SEPARATOR,
digest
)
);
address recoveredAddress = ecrecover(digest, v, r, s);
require(recoveredAddress != address(0) && recoveredAddress == owner, "INVALID_SIGNATURE");
_approve(owner, spender, value);
}
uint256[50] private __gap;
}
|
Confirms the transfer of `_quantityToInvest` currency to the contract. currency is ETH currency is ERC20
|
function _collectInvestment(
address payable _from,
uint _quantityToInvest,
uint _msgValue
) internal
{
if(address(currency) == address(0))
{
require(_quantityToInvest == _msgValue, "INCORRECT_MSG_VALUE");
}
else
{
require(_msgValue == 0, "DO_NOT_SEND_ETH");
currency.safeTransferFrom(_from, address(this), _quantityToInvest);
}
}
| 10,565,595 |
./full_match/5/0xdB3301b7c6b8EA6082009ECD091F9D0ADFF24087/sources/browser/DODO.sol
|
Create an DODO egg. Egg's `gene` and `energy` will assigned to 0 initially and won't be determined until egg is cracked./
|
function _createEgg(
uint256 _matronId,
uint256 _sireId,
uint256 _generation,
uint256 _cooldownEndBlock,
address _owner
) internal returns (uint256) {
require(_matronId == uint256(uint32(_matronId)));
require(_sireId == uint256(uint32(_sireId)));
require(_generation == uint256(uint16(_generation)));
DODO memory _DODO = DODO({
gene: 0,
energy: 0,
birthTime: uint64(now),
hatchCostMultiplierEndBlock: 0,
hatchingCostMultiplier: 1,
matronId: uint32(_matronId),
sireId: uint32(_sireId),
cooldownEndBlock: uint64(_cooldownEndBlock),
generation: uint16(_generation),
generationFactor: 0,
state: DODOGrowthState.EGG
});
DODOs.push(_DODO);
uint256 eggId = DODOs.length - 1;
_mint(_owner, eggId, 1, "");
return eggId;
}
| 7,057,590 |
./full_match/4/0x06Ed2E51a453750921Cb1Bf9Cc153a5416b4EBAf/sources/browser/TokenLocker.sol
|
Transferring token to smart contract locks[msg.sender].push(tokenLock);
|
function lockTokens(address tokenAddress, uint256 amount, uint256 time) public returns (bool) {
ERC20 token = ERC20(tokenAddress);
TokenLock memory tokenLock;
tokenLock.tokenAddress = tokenAddress;
tokenLock.lockDate = block.timestamp;
tokenLock.amount = amount;
tokenLock.unlockDate = block.timestamp.add(time);
tokenLock.lockID = locks[msg.sender].length;
tokenLock.owner = msg.sender;
tokenLock.retrieved = false;
token.transferFrom(msg.sender, address(this), amount);
return true;
}
| 12,355,709 |
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
/**
████████████████████████████████████████████████████████████████
████████████████████████████████████████████████████████████████
████████████████████████████████████████████████████████████████
██████████████████████████████▓╝╘███████████████████████████████
████████████████████████████▓▓ ▓█████████████████████████████
██████████████████████▓▀╙ ╙▀▓██████████████████████
███████████████████▀" ,▄▄▄▄▄▄▄▄▄▄, "▀███████████████████
████████████████▓╜ ▄█████████████████▓w ╙█████████████████
██████████████▓┘ ╔███████████████████████▓╕ └███████████████
█████████████▓ ╓██▓╝``╙▓████████████▓╩```██▓, ▀█████████████
████████████╝ ▄███▓ `▀████████▓" ████▄ ▐████████████
███████████▓ ▓████▓ ╒ ▀███▓▀ █████▓ ▀███████████
██████████▓ ▐█████▓ ]▓▄ ╙╝ ▄▓[ █████▓L ███████████
█████████▓╝ ██████▓ ]███▓, ,▓██▓[ ██████▓ ╚██████████
███████Ü ███████▓▓▓▓▓▓▓▓▓r ▓▓▓▓▓▓▓▓▓██████▓ ║███████
████████▓▄╖ ██████▓ ██████▓ ╓▄█████████
██████████▓ ▐██████▓&&&&&&&& &&&&&&&&▄█████▓F ███████████
███████████@ █████▓ █████▓ ▐███████████
███████████▓L █████▄╥▄▄▄▄▄╥╓ ▄▄▄▄▄▄▄▄▄████▓ ╔████████████
█████████████N ▀████████████r ███████████▓╝ ▄█████████████
██████████████▓ ▀██████████▓▄▄██████████▓╝ ,███████████████
████████████████▓, "▀▓████████████████▓╝ ,▄████████████████
███████████████████▄ "╙▀▀▓▓▓▀▀▀╩" ,▄███████████████████
██████████████████████▓▄µ ╓▄███████████████████████
█████████████████████████████▓ ██████████████████████████████
██████████████████████████████▓,,███████████████████████████████
████████████████████████████████████████████████████████████████
████████████████████████████████████████████████████████████████
████████████████████████████████████████████████████████████████
*/
import "@openzeppelin/contracts/access/Ownable.sol";
import "@openzeppelin/contracts/utils/Counters.sol";
import "@openzeppelin/contracts/token/ERC721/extensions/ERC721Pausable.sol";
import "@openzeppelin/contracts/token/ERC721/extensions/ERC721Enumerable.sol";
import "@openzeppelin/contracts/token/ERC721/extensions/ERC721Burnable.sol";
import "@chainlink/contracts/src/v0.8/VRFConsumerBase.sol";
contract MetaTravelers is ERC721Enumerable, ERC721Pausable, ERC721Burnable, VRFConsumerBase, Ownable {
using Counters for Counters.Counter;
using Strings for uint256;
Counters.Counter private _tokenIdTracker;
string private _baseTokenURI;
/**
* @dev Minting variables
*/
uint256 public constant PRICE = .09 ether;
uint256 public constant MAX_QUANTITY = 3;
uint256 public constant MAX_EA_QUANTITY = 5; // max quantity that each early adopter can mint
uint256 public constant MAX_SUPPLY = 7777;
uint256 public constant MAX_RESERVE = 33;
uint256 public constant MAX_EARLY_ADOPTER = 2775;
uint256 public constant MAX_PRESALE = 2997;
uint256 public constant MAX_MINTPASS = 1332;
mapping(address => bool) private _earlyAdopterList;
mapping(address => bool) private _preSaleList;
mapping(address => uint256) private _earlyAdopterPurchased;
mapping(address => uint256) private _preSalePurchased;
mapping(address => uint256) private _publicSalePurchased;
mapping(address => uint256) private _mintPassQuantity;
bool public isReserveComplete = false;
bool public isEarlyAdopterSale = false;
bool public isPreSale = false;
bool public isMintPassSale = false;
bool public isPublicSale = false;
/**
* @dev Provenance variables
*/
string public provenanceHash;
uint256 public startingIndex;
/**
* @dev Chainlink VRF variables
*/
bytes32 internal _keyHash;
uint256 internal _fee;
/**
* @dev Initializes the contract with the name, symbol, and baseTokenURI,
* and pauses the contract by default
*/
constructor (
string memory name,
string memory symbol,
string memory baseTokenURI,
address vrfCoordinator,
address linkToken,
bytes32 keyHash,
uint256 fee
)
ERC721(name, symbol)
VRFConsumerBase(vrfCoordinator, linkToken)
{
_baseTokenURI = baseTokenURI;
_keyHash = keyHash;
_fee = fee;
_pause();
}
event AssetsMinted(address owner, uint256 quantity);
event RequestedRandomness(bytes32 requestId);
event StartingIndexSet(bytes32 requestId, uint256 randomNumber);
/**
* @dev Update the base token URI for returning metadata
*/
function setBaseTokenURI(string memory baseTokenURI) external onlyOwner {
_baseTokenURI = baseTokenURI;
}
/**
* @dev Add wallet addresses to the Early Adopter mappings used for private sale
*/
function addToEarlyAdopterList(address[] calldata addresses) external onlyOwner {
for(uint256 i = 0; i < addresses.length; i++) {
require(addresses[i] != address(0), "Cannot add null address");
require(!_earlyAdopterList[addresses[i]], "Duplicate entry");
_earlyAdopterList[addresses[i]] = true;
}
}
/**
* @dev Add wallet addresses to the PreSale mappings used for private sale
*/
function addToPreSaleList(address[] calldata addresses) external onlyOwner {
for(uint256 i = 0; i < addresses.length; i++) {
require(addresses[i] != address(0), "Cannot add null address");
require(!_preSaleList[addresses[i]], "Duplicate entry");
_preSaleList[addresses[i]] = true;
}
}
/**
* @dev Add wallet addresses to the Mint Pass mapping used for private sale
*/
function addToMintPassList(address[] calldata addresses, uint256[] calldata quantities) external onlyOwner {
require(addresses.length == quantities.length);
for(uint256 i = 0; i < addresses.length; i++) {
require(addresses[i] != address(0), "Cannot add null address");
_mintPassQuantity[addresses[i]] = quantities[i];
}
}
/**
* @dev Returns the quantity available for the message sender to mint during the mint pass sale
*/
function getMintPassQuantity(address user) external view returns (uint256) {
return _mintPassQuantity[user];
}
/**
* @dev Toggle whether early adopter minting is enabled/disabled
*/
function toggleEarlyAdopter() external onlyOwner {
isEarlyAdopterSale = !isEarlyAdopterSale;
}
/**
* @dev Toggle whether preSale minting is enabled/disabled
*/
function togglePreSale() external onlyOwner {
isPreSale = !isPreSale;
}
/**
* @dev Toggle whether mint pass minting is enabled/disabled
*/
function toggleMintPassSale() external onlyOwner {
isMintPassSale = !isMintPassSale;
}
/**
* @dev Toggle whether public sale minting is enabled/disabled
*/
function togglePublicSale() external onlyOwner {
isPublicSale = !isPublicSale;
}
/**
* @dev Base minting function to be reused by other minting functions
*/
function _baseMint(address to) private {
_tokenIdTracker.increment();
_mint(to, _tokenIdTracker.current());
}
/**
* @dev Early Adopter sale restricted to a list of specified wallet address
*/
function earlyAdopterMint(address to, uint256 quantity) external payable {
require(isEarlyAdopterSale, 'Early Adopter sale is not live');
require(_earlyAdopterList[_msgSender()], "User not on Early Adopter list");
require(totalSupply() + quantity <= MAX_EARLY_ADOPTER, "Early Adopter sale is sold out");
require(_earlyAdopterPurchased[_msgSender()] + quantity <= MAX_EA_QUANTITY, "Limit per wallet exceeded");
require(msg.value == PRICE * quantity, "Ether value sent is not correct");
for(uint256 i=0; i<quantity; i++){
_earlyAdopterPurchased[_msgSender()]++;
_baseMint(to);
}
emit AssetsMinted(to, quantity);
}
/**
* @dev PreSale restricted to a list of specified wallet address
*/
function preSaleMint(address to, uint256 quantity) external payable {
require(isPreSale, 'PreSale is not live');
require(_preSaleList[_msgSender()], "User not on PreSale list");
require(totalSupply() + quantity <= MAX_EARLY_ADOPTER + MAX_PRESALE, "PreSale is sold out");
require(_preSalePurchased[_msgSender()] + quantity <= MAX_QUANTITY, "Limit per wallet exceeded");
require(msg.value == PRICE * quantity, "Ether value sent is not correct");
for(uint256 i=0; i<quantity; i++){
_preSalePurchased[_msgSender()]++;
_baseMint(to);
}
emit AssetsMinted(to, quantity);
}
/**
* @dev Mint pass sale based on snapshot of mint pass holders
*/
function mintPassMint(address to, uint256 quantity) external payable {
require(isMintPassSale, 'Mint pass sale is not live');
require(_mintPassQuantity[_msgSender()] > 0, "User does not have valid mint pass");
require(totalSupply() + quantity <= MAX_EARLY_ADOPTER + MAX_PRESALE +
MAX_MINTPASS, "Mint pass sale is sold out");
require(msg.value == PRICE * quantity, "Ether value sent is not correct");
for(uint256 i=0; i<quantity; i++){
require(_mintPassQuantity[_msgSender()] > 0, "No mint pass mints left");
_mintPassQuantity[_msgSender()]--;
_baseMint(to);
}
emit AssetsMinted(to, quantity);
}
/**
* @dev Creates a new token for `to`. Its token ID will be automatically
* assigned (and available on the emitted {IERC721-Transfer} event), and the token
* URI autogenerated based on the base URI passed at construction.
*
* See {ERC721-_mint}.
*/
function publicSaleMint(address to, uint256 quantity) external payable {
require(isPublicSale, "Public sale is not live");
require(totalSupply() + quantity <= MAX_SUPPLY, "Purchase exceeds max supply");
require(quantity <= MAX_QUANTITY, "Order exceeds max quantity");
require(msg.value == PRICE * quantity, "Ether value sent is not correct");
require(_publicSalePurchased[_msgSender()] + quantity <= MAX_QUANTITY, "Limit per wallet exceeded");
for(uint256 i=0; i<quantity; i++){
_publicSalePurchased[_msgSender()]++;
_baseMint(to);
}
emit AssetsMinted(to, quantity);
}
/**
* @dev Reserve MetaTravelers
*/
function reserveMetaTravelers() external onlyOwner {
require(!isReserveComplete, "MetaTravelers: Already reserved");
for(uint256 i=0; i<MAX_RESERVE; i++){
_baseMint(_msgSender());
}
isReserveComplete = true;
emit AssetsMinted(_msgSender(), MAX_RESERVE);
}
/**
* @dev Set the provenanceHash used for verifying fair and random distribution
*/
function setProvenanceHash(string memory newProvenanceHash) external onlyOwner {
provenanceHash = newProvenanceHash;
}
/**
* @dev Set the startingIndex using Chainlink VRF for provable on-chain randomness
* See callback function 'fulfillRandomness'
*/
function setStartingIndex() external onlyOwner returns (bytes32) {
bytes memory tempProvenanceHash = bytes(provenanceHash);
require(tempProvenanceHash.length > 0, "Need to set provenance hash");
require(startingIndex == 0, "Starting index is already set");
require(LINK.balanceOf(address(this)) >= _fee, "Not enough LINK");
bytes32 requestId = requestRandomness(_keyHash, _fee);
emit RequestedRandomness(requestId);
return requestId;
}
/**
* @dev Callback function used by VRF Coordinator.
* Sets the startingIndex based on the random number generated by Chainlink VRF
*/
function fulfillRandomness(bytes32 requestId, uint256 randomness) internal override {
startingIndex = randomness % MAX_SUPPLY;
// Prevent default sequence
if (startingIndex == 0) {
startingIndex += 1;
}
emit StartingIndexSet(requestId, randomness);
}
/**
* @dev Used to withdraw funds from the contract
*/
function withdraw() external onlyOwner() {
uint256 balance = address(this).balance;
payable(_msgSender()).transfer(balance);
}
/**
* @dev See {IERC721Metadata-tokenURI}.
*/
function tokenURI(uint256 tokenId) public view virtual override returns (string memory) {
require(_exists(tokenId), "ERC721Metadata: URI query for nonexistent token.");
return bytes(_baseTokenURI).length > 0 ? string(abi.encodePacked(_baseTokenURI, tokenId.toString())) : "";
}
/**
* @dev Used to pause contract minting per ERC721Pausable
*/
function pause() external onlyOwner() {
_pause();
}
/**
* @dev Used to unpause contract minting per ERC721Pausable
*/
function unpause() external onlyOwner() {
_unpause();
}
/**
* @dev Required due to inheritance
*/
function supportsInterface(bytes4 interfaceId) public view virtual override(ERC721, ERC721Enumerable) returns (bool) {
return super.supportsInterface(interfaceId);
}
/**
* @dev Required due to inheritance
*/
function _beforeTokenTransfer(address from, address to, uint256 tokenId) internal virtual override(ERC721, ERC721Enumerable, ERC721Pausable) {
super._beforeTokenTransfer(from, to, tokenId);
}
}
|
Used to unpause contract minting per ERC721Pausable/
|
function unpause() external onlyOwner() {
_unpause();
}
| 6,346,483 |
pragma solidity ^0.4.24;
/*
* -PlayerBook - v0.3.14
* ┌┬┐┌─┐┌─┐┌┬┐ ╦╦ ╦╔═╗╔╦╗ ┌─┐┬─┐┌─┐┌─┐┌─┐┌┐┌┌┬┐┌─┐
* │ ├┤ ├─┤│││ ║║ ║╚═╗ ║ ├─┘├┬┘├┤ └─┐├┤ │││ │ └─┐
* ┴ └─┘┴ ┴┴ ┴ ╚╝╚═╝╚═╝ ╩ ┴ ┴└─└─┘└─┘└─┘┘└┘ ┴ └─┘
* _____ _____
* (, / /) /) /) (, / /) /)
* ┌─┐ / _ (/_ // // / _ // _ __ _(/
* ├─┤ ___/___(/_/(__(_/_(/_(/_ ___/__/_)_(/_(_(_/ (_(_(_
* ┴ ┴ / / .-/ _____ (__ /
* (__ / (_/ (, / /)™
* / __ __ __ __ _ __ __ _ _/_ _ _(/
* ┌─┐┬─┐┌─┐┌┬┐┬ ┬┌─┐┌┬┐ /__/ (_(__(_)/ (_/_)_(_)/ (_(_(_(__(/_(_(_
* ├─┘├┬┘│ │ │││ ││ │ (__ / .-/ © Jekyll Island Inc. 2018
* ┴ ┴└─└─┘─┴┘└─┘└─┘ ┴ (_/
* ______ _ ______ _
*====(_____ \=| |===============================(____ \===============| |=============*
* _____) )| | _____ _ _ _____ ____ ____) ) ___ ___ | | _
* | ____/ | | (____ || | | || ___ | / ___) | __ ( / _ \ / _ \ | |_/ )
* | | | | / ___ || |_| || ____|| | | |__) )| |_| || |_| || _ (
*====|_|=======\_)\_____|=\__ ||_____)|_|======|______/==\___/==\___/=|_|=\_)=========*
* (____/
* ╔═╗┌─┐┌┐┌┌┬┐┬─┐┌─┐┌─┐┌┬┐ ╔═╗┌─┐┌┬┐┌─┐ ┌──────────┐
* ║ │ ││││ │ ├┬┘├─┤│ │ ║ │ │ ││├┤ │ Inventor │
* ╚═╝└─┘┘└┘ ┴ ┴└─┴ ┴└─┘ ┴ ╚═╝└─┘─┴┘└─┘ └──────────┘
*/
interface PlayerBookReceiverInterface {
function receivePlayerInfo(uint256 _pID, address _addr, bytes32 _name, uint256 _laff) external;
function receivePlayerNameList(uint256 _pID, bytes32 _name) external;
}
contract PlayerBook {
using NameFilter for string;
using SafeMath for uint256;
address private admin = msg.sender;
address private mgt;
address private dev;
//==============================================================================
// _| _ _|_ _ _ _ _|_ _ .
// (_|(_| | (_| _\(/_ | |_||_) .
//=============================|================================================
uint256 public registrationFee_ = 10 finney; // price to register a name
mapping(uint256 => PlayerBookReceiverInterface) public games_; // mapping of our game interfaces for sending your account info to games
mapping(address => bytes32) public gameNames_; // lookup a games name
mapping(address => uint256) public gameIDs_; // lokup a games ID
uint256 public gID_; // total number of games
uint256 public pID_; // total number of players
mapping (address => uint256) public pIDxAddr_; // (addr => pID) returns player id by address
mapping (bytes32 => uint256) public pIDxName_; // (name => pID) returns player id by name
mapping (uint256 => Player) public plyr_; // (pID => data) player data
mapping (uint256 => mapping (bytes32 => bool)) public plyrNames_; // (pID => name => bool) list of names a player owns. (used so you can change your display name amoungst any name you own)
mapping (uint256 => mapping (uint256 => bytes32)) public plyrNameList_; // (pID => nameNum => name) list of names a player owns
struct Player {
address addr;
bytes32 name;
uint256 laff;
uint256 names;
}
//==============================================================================
// _ _ _ __|_ _ __|_ _ _ .
// (_(_)| |_\ | | |_|(_ | (_)| . (initial data setup upon contract deploy)
//==============================================================================
constructor(address _mgt, address _dev)
public
{
mgt = _mgt;
dev = _dev;
// premine the dev names (sorry not sorry)
// No keys are purchased with this method, it's simply locking our addresses,
// PID's and names for referral codes.
plyr_[1].addr = 0x8e0d985f3Ec1857BEc39B76aAabDEa6B31B67d53;
plyr_[1].name = "justo";
plyr_[1].names = 1;
pIDxAddr_[0x8e0d985f3Ec1857BEc39B76aAabDEa6B31B67d53] = 1;
pIDxName_["justo"] = 1;
plyrNames_[1]["justo"] = true;
plyrNameList_[1][1] = "justo";
plyr_[2].addr = 0x8b4DA1827932D71759687f925D17F81Fc94e3A9D;
plyr_[2].name = "mantso";
plyr_[2].names = 1;
pIDxAddr_[0x8b4DA1827932D71759687f925D17F81Fc94e3A9D] = 2;
pIDxName_["mantso"] = 2;
plyrNames_[2]["mantso"] = true;
plyrNameList_[2][1] = "mantso";
plyr_[3].addr = 0x7ac74Fcc1a71b106F12c55ee8F802C9F672Ce40C;
plyr_[3].name = "sumpunk";
plyr_[3].names = 1;
pIDxAddr_[0x7ac74Fcc1a71b106F12c55ee8F802C9F672Ce40C] = 3;
pIDxName_["sumpunk"] = 3;
plyrNames_[3]["sumpunk"] = true;
plyrNameList_[3][1] = "sumpunk";
plyr_[4].addr = 0x18E90Fc6F70344f53EBd4f6070bf6Aa23e2D748C;
plyr_[4].name = "inventor";
plyr_[4].names = 1;
pIDxAddr_[0x18E90Fc6F70344f53EBd4f6070bf6Aa23e2D748C] = 4;
pIDxName_["inventor"] = 4;
plyrNames_[4]["inventor"] = true;
plyrNameList_[4][1] = "inventor";
pID_ = 4;
}
//==============================================================================
// _ _ _ _|. |`. _ _ _ .
// | | |(_)(_||~|~|(/_| _\ . (these are safety checks)
//==============================================================================
/**
* @dev prevents contracts from interacting with fomo3d
*/
modifier isHuman() {
address _addr = msg.sender;
uint256 _codeLength;
assembly {_codeLength := extcodesize(_addr)}
require(_codeLength == 0, "sorry humans only");
_;
}
modifier onlyDevs()
{
require(admin == msg.sender, "msg sender is not a dev");
_;
}
modifier isRegisteredGame()
{
require(gameIDs_[msg.sender] != 0);
_;
}
//==============================================================================
// _ _ _ _|_ _ .
// (/_\/(/_| | | _\ .
//==============================================================================
// fired whenever a player registers a name
event onNewName
(
uint256 indexed playerID,
address indexed playerAddress,
bytes32 indexed playerName,
bool isNewPlayer,
uint256 affiliateID,
address affiliateAddress,
bytes32 affiliateName,
uint256 amountPaid,
uint256 timeStamp
);
//==============================================================================
// _ _ _|__|_ _ _ _ .
// (_|(/_ | | (/_| _\ . (for UI & viewing things on etherscan)
//=====_|=======================================================================
function checkIfNameValid(string _nameStr)
public
view
returns(bool)
{
bytes32 _name = _nameStr.nameFilter();
if (pIDxName_[_name] == 0)
return (true);
else
return (false);
}
//==============================================================================
// _ |_ |. _ |` _ __|_. _ _ _ .
// |_)|_||_)||(_ ~|~|_|| |(_ | |(_)| |_\ . (use these to interact with contract)
//====|=========================================================================
/**
* @dev registers a name. UI will always display the last name you registered.
* but you will still own all previously registered names to use as affiliate
* links.
* - must pay a registration fee.
* - name must be unique
* - names will be converted to lowercase
* - name cannot start or end with a space
* - cannot have more than 1 space in a row
* - cannot be only numbers
* - cannot start with 0x
* - name must be at least 1 char
* - max length of 32 characters long
* - allowed characters: a-z, 0-9, and space
* -functionhash- 0x921dec21 (using ID for affiliate)
* -functionhash- 0x3ddd4698 (using address for affiliate)
* -functionhash- 0x685ffd83 (using name for affiliate)
* @param _nameString players desired name
* @param _affCode affiliate ID, address, or name of who refered you
* @param _all set to true if you want this to push your info to all games
* (this might cost a lot of gas)
*/
function registerNameXID(string _nameString, uint256 _affCode, bool _all)
isHuman()
public
payable
{
// make sure name fees paid
require (msg.value >= registrationFee_, "umm..... you have to pay the name fee");
// filter name + condition checks
bytes32 _name = NameFilter.nameFilter(_nameString);
// set up address
address _addr = msg.sender;
// set up our tx event data and determine if player is new or not
bool _isNewPlayer = determinePID(_addr);
// fetch player id
uint256 _pID = pIDxAddr_[_addr];
// manage affiliate residuals
// if no affiliate code was given, no new affiliate code was given, or the
// player tried to use their own pID as an affiliate code, lolz
if (_affCode != 0 && _affCode != plyr_[_pID].laff && _affCode != _pID)
{
// update last affiliate
plyr_[_pID].laff = _affCode;
} else if (_affCode == _pID) {
_affCode = 0;
}
// register name
registerNameCore(_pID, _addr, _affCode, _name, _isNewPlayer, _all);
}
function registerNameXaddr(string _nameString, address _affCode, bool _all)
isHuman()
public
payable
{
// make sure name fees paid
require (msg.value >= registrationFee_, "umm..... you have to pay the name fee");
// filter name + condition checks
bytes32 _name = NameFilter.nameFilter(_nameString);
// set up address
address _addr = msg.sender;
// set up our tx event data and determine if player is new or not
bool _isNewPlayer = determinePID(_addr);
// fetch player id
uint256 _pID = pIDxAddr_[_addr];
// manage affiliate residuals
// if no affiliate code was given or player tried to use their own, lolz
uint256 _affID;
if (_affCode != address(0) && _affCode != _addr)
{
// get affiliate ID from aff Code
_affID = pIDxAddr_[_affCode];
// if affID is not the same as previously stored
if (_affID != plyr_[_pID].laff)
{
// update last affiliate
plyr_[_pID].laff = _affID;
}
}
// register name
registerNameCore(_pID, _addr, _affID, _name, _isNewPlayer, _all);
}
function registerNameXname(string _nameString, bytes32 _affCode, bool _all)
isHuman()
public
payable
{
// make sure name fees paid
require (msg.value >= registrationFee_, "umm..... you have to pay the name fee");
// filter name + condition checks
bytes32 _name = NameFilter.nameFilter(_nameString);
// set up address
address _addr = msg.sender;
// set up our tx event data and determine if player is new or not
bool _isNewPlayer = determinePID(_addr);
// fetch player id
uint256 _pID = pIDxAddr_[_addr];
// manage affiliate residuals
// if no affiliate code was given or player tried to use their own, lolz
uint256 _affID;
if (_affCode != "" && _affCode != _name)
{
// get affiliate ID from aff Code
_affID = pIDxName_[_affCode];
// if affID is not the same as previously stored
if (_affID != plyr_[_pID].laff)
{
// update last affiliate
plyr_[_pID].laff = _affID;
}
}
// register name
registerNameCore(_pID, _addr, _affID, _name, _isNewPlayer, _all);
}
/**
* @dev players, if you registered a profile, before a game was released, or
* set the all bool to false when you registered, use this function to push
* your profile to a single game. also, if you've updated your name, you
* can use this to push your name to games of your choosing.
* -functionhash- 0x81c5b206
* @param _gameID game id
*/
function addMeToGame(uint256 _gameID)
isHuman()
public
{
require(_gameID <= gID_, "silly player, that game doesn't exist yet");
address _addr = msg.sender;
uint256 _pID = pIDxAddr_[_addr];
require(_pID != 0, "hey there buddy, you dont even have an account");
uint256 _totalNames = plyr_[_pID].names;
// add players profile and most recent name
games_[_gameID].receivePlayerInfo(_pID, _addr, plyr_[_pID].name, plyr_[_pID].laff);
// add list of all names
if (_totalNames > 1)
for (uint256 ii = 1; ii <= _totalNames; ii++)
games_[_gameID].receivePlayerNameList(_pID, plyrNameList_[_pID][ii]);
}
/**
* @dev players, use this to push your player profile to all registered games.
* -functionhash- 0x0c6940ea
*/
function addMeToAllGames()
isHuman()
public
{
address _addr = msg.sender;
uint256 _pID = pIDxAddr_[_addr];
require(_pID != 0, "hey there buddy, you dont even have an account");
uint256 _laff = plyr_[_pID].laff;
uint256 _totalNames = plyr_[_pID].names;
bytes32 _name = plyr_[_pID].name;
for (uint256 i = 1; i <= gID_; i++)
{
games_[i].receivePlayerInfo(_pID, _addr, _name, _laff);
if (_totalNames > 1)
for (uint256 ii = 1; ii <= _totalNames; ii++)
games_[i].receivePlayerNameList(_pID, plyrNameList_[_pID][ii]);
}
}
/**
* @dev players use this to change back to one of your old names. tip, you'll
* still need to push that info to existing games.
* -functionhash- 0xb9291296
* @param _nameString the name you want to use
*/
function useMyOldName(string _nameString)
isHuman()
public
{
// filter name, and get pID
bytes32 _name = _nameString.nameFilter();
uint256 _pID = pIDxAddr_[msg.sender];
// make sure they own the name
require(plyrNames_[_pID][_name] == true, "umm... thats not a name you own");
// update their current name
plyr_[_pID].name = _name;
}
//==============================================================================
// _ _ _ _ | _ _ . _ .
// (_(_)| (/_ |(_)(_||(_ .
//=====================_|=======================================================
function registerNameCore(uint256 _pID, address _addr, uint256 _affID, bytes32 _name, bool _isNewPlayer, bool _all)
private
{
// if names already has been used, require that current msg sender owns the name
if (pIDxName_[_name] != 0)
require(plyrNames_[_pID][_name] == true, "sorry that names already taken");
// add name to player profile, registry, and name book
plyr_[_pID].name = _name;
pIDxName_[_name] = _pID;
if (plyrNames_[_pID][_name] == false)
{
plyrNames_[_pID][_name] = true;
plyr_[_pID].names++;
plyrNameList_[_pID][plyr_[_pID].names] = _name;
}
// registration fee goes directly to community rewards
dev.transfer(address(this).balance / 5);
mgt.transfer(address(this).balance);
// push player info to games
if (_all == true)
for (uint256 i = 1; i <= gID_; i++)
games_[i].receivePlayerInfo(_pID, _addr, _name, _affID);
// fire event
emit onNewName(_pID, _addr, _name, _isNewPlayer, _affID, plyr_[_affID].addr, plyr_[_affID].name, msg.value, now);
}
//==============================================================================
// _|_ _ _ | _ .
// | (_)(_)|_\ .
//==============================================================================
function determinePID(address _addr)
private
returns (bool)
{
if (pIDxAddr_[_addr] == 0)
{
pID_++;
pIDxAddr_[_addr] = pID_;
plyr_[pID_].addr = _addr;
// set the new player bool to true
return (true);
} else {
return (false);
}
}
//==============================================================================
// _ _|_ _ _ _ _ | _ _ || _ .
// (/_>< | (/_| | |(_|| (_(_|||_\ .
//==============================================================================
function getPlayerID(address _addr)
isRegisteredGame()
external
returns (uint256)
{
determinePID(_addr);
return (pIDxAddr_[_addr]);
}
function getPlayerName(uint256 _pID)
external
view
returns (bytes32)
{
return (plyr_[_pID].name);
}
function getPlayerLAff(uint256 _pID)
external
view
returns (uint256)
{
return (plyr_[_pID].laff);
}
function getPlayerAddr(uint256 _pID)
external
view
returns (address)
{
return (plyr_[_pID].addr);
}
function getNameFee()
external
view
returns (uint256)
{
return(registrationFee_);
}
function registerNameXIDFromDapp(address _addr, bytes32 _name, uint256 _affCode, bool _all)
isRegisteredGame()
external
payable
returns(bool, uint256)
{
// make sure name fees paid
require (msg.value >= registrationFee_, "umm..... you have to pay the name fee");
// set up our tx event data and determine if player is new or not
bool _isNewPlayer = determinePID(_addr);
// fetch player id
uint256 _pID = pIDxAddr_[_addr];
// manage affiliate residuals
// if no affiliate code was given, no new affiliate code was given, or the
// player tried to use their own pID as an affiliate code, lolz
uint256 _affID = _affCode;
if (_affID != 0 && _affID != plyr_[_pID].laff && _affID != _pID)
{
// update last affiliate
plyr_[_pID].laff = _affID;
} else if (_affID == _pID) {
_affID = 0;
}
// register name
registerNameCore(_pID, _addr, _affID, _name, _isNewPlayer, _all);
return(_isNewPlayer, _affID);
}
function registerNameXaddrFromDapp(address _addr, bytes32 _name, address _affCode, bool _all)
isRegisteredGame()
external
payable
returns(bool, uint256)
{
// make sure name fees paid
require (msg.value >= registrationFee_, "umm..... you have to pay the name fee");
// set up our tx event data and determine if player is new or not
bool _isNewPlayer = determinePID(_addr);
// fetch player id
uint256 _pID = pIDxAddr_[_addr];
// manage affiliate residuals
// if no affiliate code was given or player tried to use their own, lolz
uint256 _affID;
if (_affCode != address(0) && _affCode != _addr)
{
// get affiliate ID from aff Code
_affID = pIDxAddr_[_affCode];
// if affID is not the same as previously stored
if (_affID != plyr_[_pID].laff)
{
// update last affiliate
plyr_[_pID].laff = _affID;
}
}
// register name
registerNameCore(_pID, _addr, _affID, _name, _isNewPlayer, _all);
return(_isNewPlayer, _affID);
}
function registerNameXnameFromDapp(address _addr, bytes32 _name, bytes32 _affCode, bool _all)
isRegisteredGame()
external
payable
returns(bool, uint256)
{
// make sure name fees paid
require (msg.value >= registrationFee_, "umm..... you have to pay the name fee");
// set up our tx event data and determine if player is new or not
bool _isNewPlayer = determinePID(_addr);
// fetch player id
uint256 _pID = pIDxAddr_[_addr];
// manage affiliate residuals
// if no affiliate code was given or player tried to use their own, lolz
uint256 _affID;
if (_affCode != "" && _affCode != _name)
{
// get affiliate ID from aff Code
_affID = pIDxName_[_affCode];
// if affID is not the same as previously stored
if (_affID != plyr_[_pID].laff)
{
// update last affiliate
plyr_[_pID].laff = _affID;
}
}
// register name
registerNameCore(_pID, _addr, _affID, _name, _isNewPlayer, _all);
return(_isNewPlayer, _affID);
}
//==============================================================================
// _ _ _|_ _ .
// _\(/_ | |_||_) .
//=============|================================================================
function addGame(address _gameAddress, string _gameNameStr)
onlyDevs()
public
{
require(gameIDs_[_gameAddress] == 0, "derp, that games already been registered");
gID_++;
bytes32 _name = _gameNameStr.nameFilter();
gameIDs_[_gameAddress] = gID_;
gameNames_[_gameAddress] = _name;
games_[gID_] = PlayerBookReceiverInterface(_gameAddress);
games_[gID_].receivePlayerInfo(1, plyr_[1].addr, plyr_[1].name, 0);
games_[gID_].receivePlayerInfo(2, plyr_[2].addr, plyr_[2].name, 0);
games_[gID_].receivePlayerInfo(3, plyr_[3].addr, plyr_[3].name, 0);
games_[gID_].receivePlayerInfo(4, plyr_[4].addr, plyr_[4].name, 0);
}
function setRegistrationFee(uint256 _fee)
onlyDevs()
public
{
registrationFee_ = _fee;
}
}
/**
* @title -Name Filter- v0.1.9
* ┌┬┐┌─┐┌─┐┌┬┐ ╦╦ ╦╔═╗╔╦╗ ┌─┐┬─┐┌─┐┌─┐┌─┐┌┐┌┌┬┐┌─┐
* │ ├┤ ├─┤│││ ║║ ║╚═╗ ║ ├─┘├┬┘├┤ └─┐├┤ │││ │ └─┐
* ┴ └─┘┴ ┴┴ ┴ ╚╝╚═╝╚═╝ ╩ ┴ ┴└─└─┘└─┘└─┘┘└┘ ┴ └─┘
* _____ _____
* (, / /) /) /) (, / /) /)
* ┌─┐ / _ (/_ // // / _ // _ __ _(/
* ├─┤ ___/___(/_/(__(_/_(/_(/_ ___/__/_)_(/_(_(_/ (_(_(_
* ┴ ┴ / / .-/ _____ (__ /
* (__ / (_/ (, / /)™
* / __ __ __ __ _ __ __ _ _/_ _ _(/
* ┌─┐┬─┐┌─┐┌┬┐┬ ┬┌─┐┌┬┐ /__/ (_(__(_)/ (_/_)_(_)/ (_(_(_(__(/_(_(_
* ├─┘├┬┘│ │ │││ ││ │ (__ / .-/ © Jekyll Island Inc. 2018
* ┴ ┴└─└─┘─┴┘└─┘└─┘ ┴ (_/
* _ __ _ ____ ____ _ _ _____ ____ ___
*=============| |\ | / /\ | |\/| | |_ =====| |_ | | | | | | | |_ | |_)==============*
*=============|_| \| /_/--\ |_| | |_|__=====|_| |_| |_|__ |_| |_|__ |_| \==============*
*
* ╔═╗┌─┐┌┐┌┌┬┐┬─┐┌─┐┌─┐┌┬┐ ╔═╗┌─┐┌┬┐┌─┐ ┌──────────┐
* ║ │ ││││ │ ├┬┘├─┤│ │ ║ │ │ ││├┤ │ Inventor │
* ╚═╝└─┘┘└┘ ┴ ┴└─┴ ┴└─┘ ┴ ╚═╝└─┘─┴┘└─┘ └──────────┘
*/
library NameFilter {
/**
* @dev filters name strings
* -converts uppercase to lower case.
* -makes sure it does not start/end with a space
* -makes sure it does not contain multiple spaces in a row
* -cannot be only numbers
* -cannot start with 0x
* -restricts characters to A-Z, a-z, 0-9, and space.
* @return reprocessed string in bytes32 format
*/
function nameFilter(string _input)
internal
pure
returns(bytes32)
{
bytes memory _temp = bytes(_input);
uint256 _length = _temp.length;
//sorry limited to 32 characters
require (_length <= 32 && _length > 0, "string must be between 1 and 32 characters");
// make sure it doesnt start with or end with space
require(_temp[0] != 0x20 && _temp[_length-1] != 0x20, "string cannot start or end with space");
// make sure first two characters are not 0x
if (_temp[0] == 0x30)
{
require(_temp[1] != 0x78, "string cannot start with 0x");
require(_temp[1] != 0x58, "string cannot start with 0X");
}
// create a bool to track if we have a non number character
bool _hasNonNumber;
// convert & check
for (uint256 i = 0; i < _length; i++)
{
// if its uppercase A-Z
if (_temp[i] > 0x40 && _temp[i] < 0x5b)
{
// convert to lower case a-z
_temp[i] = byte(uint(_temp[i]) + 32);
// we have a non number
if (_hasNonNumber == false)
_hasNonNumber = true;
} else {
require
(
// require character is a space
_temp[i] == 0x20 ||
// OR lowercase a-z
(_temp[i] > 0x60 && _temp[i] < 0x7b) ||
// or 0-9
(_temp[i] > 0x2f && _temp[i] < 0x3a),
"string contains invalid characters"
);
// make sure theres not 2x spaces in a row
if (_temp[i] == 0x20)
require( _temp[i+1] != 0x20, "string cannot contain consecutive spaces");
// see if we have a character other than a number
if (_hasNonNumber == false && (_temp[i] < 0x30 || _temp[i] > 0x39))
_hasNonNumber = true;
}
}
require(_hasNonNumber == true, "string cannot be only numbers");
bytes32 _ret;
assembly {
_ret := mload(add(_temp, 32))
}
return (_ret);
}
}
/**
* @title SafeMath v0.1.9
* @dev Math operations with safety checks that throw on error
* change notes: original SafeMath library from OpenZeppelin modified by Inventor
* - added sqrt
* - added sq
* - added pwr
* - changed asserts to requires with error log outputs
* - removed div, its useless
*/
library SafeMath {
/**
* @dev Multiplies two numbers, throws on overflow.
*/
function mul(uint256 a, uint256 b)
internal
pure
returns (uint256 c)
{
if (a == 0) {
return 0;
}
c = a * b;
require(c / a == b, "SafeMath mul failed");
return c;
}
/**
* @dev Subtracts two numbers, throws on overflow (i.e. if subtrahend is greater than minuend).
*/
function sub(uint256 a, uint256 b)
internal
pure
returns (uint256)
{
require(b <= a, "SafeMath sub failed");
return a - b;
}
/**
* @dev Adds two numbers, throws on overflow.
*/
function add(uint256 a, uint256 b)
internal
pure
returns (uint256 c)
{
c = a + b;
require(c >= a, "SafeMath add failed");
return c;
}
/**
* @dev gives square root of given x.
*/
function sqrt(uint256 x)
internal
pure
returns (uint256 y)
{
uint256 z = ((add(x,1)) / 2);
y = x;
while (z < y)
{
y = z;
z = ((add((x / z),z)) / 2);
}
}
/**
* @dev gives square. multiplies x by x
*/
function sq(uint256 x)
internal
pure
returns (uint256)
{
return (mul(x,x));
}
/**
* @dev x to the power of y
*/
function pwr(uint256 x, uint256 y)
internal
pure
returns (uint256)
{
if (x==0)
return (0);
else if (y==0)
return (1);
else
{
uint256 z = x;
for (uint256 i=1; i < y; i++)
z = mul(z,x);
return (z);
}
}
}
|
make sure name fees paid filter name + condition checks set up address set up our tx event data and determine if player is new or not fetch player id manage affiliate residuals if no affiliate code was given or player tried to use their own, lolz get affiliate ID from aff Code if affID is not the same as previously stored update last affiliate
|
function registerNameXname(string _nameString, bytes32 _affCode, bool _all)
isHuman()
public
payable
{
require (msg.value >= registrationFee_, "umm..... you have to pay the name fee");
bytes32 _name = NameFilter.nameFilter(_nameString);
address _addr = msg.sender;
bool _isNewPlayer = determinePID(_addr);
uint256 _pID = pIDxAddr_[_addr];
uint256 _affID;
if (_affCode != "" && _affCode != _name)
{
_affID = pIDxName_[_affCode];
if (_affID != plyr_[_pID].laff)
{
plyr_[_pID].laff = _affID;
}
}
}
| 121,692 |
pragma solidity ^0.4.18;
library SafeMath {
function mul(uint256 a, uint256 b) internal pure returns (uint256) {
if (a == 0 || b == 0){
return 0;
}
uint256 c = a * b;
assert(c / a == b);
return c;
}
function sub(uint256 a, uint256 b) internal pure returns (uint256) {
assert(b <= a);
return a - b;
}
function add(uint256 a, uint256 b) internal pure returns (uint256) {
uint256 c = a + b;
assert(c >= a);
return c;
}
function pow(uint256 a, uint256 b) internal pure returns (uint256){ //power function
if (b == 0){
return 1;
}
uint256 c = a**b;
assert (c >= a);
return c;
}
}
//it's contract name:
contract YourCustomTokenJABACO{ //ERC - 20 token contract
using SafeMath for uint;
// Triggered when tokens are transferred.
event Transfer(address indexed _from, address indexed _to, uint256 _value);
// Triggered whenever approve(address _spender, uint256 _value) is called.
event Approval(address indexed _owner, address indexed _spender, uint256 _value);
// It's nessesary ERC-20 parameters
string public constant symbol = "JABAS";
string public constant name = "JABATOKENS";
uint8 public constant decimals = 4;
uint256 _totalSupply = 10000000000;
// Owner of this contract
address public owner;
// Balances for each account
mapping(address => uint256) balances;
// Owner of account approves the transfer of an amount to another account
mapping(address => mapping (address => uint256)) allowed;
function totalSupply() public view returns (uint256) { //standart ERC-20 function
return _totalSupply;
}
function balanceOf(address _address) public view returns (uint256 balance) {//standart ERC-20 function
return balances[_address];
}
//standart ERC-20 function
function transfer(address _to, uint256 _amount) public returns (bool success) {
balances[msg.sender] = balances[msg.sender].sub(_amount);
balances[_to] = balances[_to].add(_amount);
Transfer(msg.sender,_to,_amount);
return true;
}
//standart ERC-20 function
function transferFrom(address _from, address _to, uint256 _amount) public returns(bool success){
balances[_from] = balances[_from].sub(_amount);
allowed[_from][msg.sender] = allowed[_from][msg.sender].sub(_amount);
balances[_to] = balances[_to].add(_amount);
Transfer(_from,_to,_amount);
return true;
}
//standart ERC-20 function
function approve(address _spender, uint256 _amount)public returns (bool success) {
allowed[msg.sender][_spender] = _amount;
Approval(msg.sender, _spender, _amount);
return true;
}
//standart ERC-20 function
function allowance(address _owner, address _spender)public constant returns (uint256 remaining) {
return allowed[_owner][_spender];
}
//Constructor
function YourCustomTokenJABACO() public {
owner = msg.sender;
balances[msg.sender] = _totalSupply;
Transfer(this,msg.sender,_totalSupply);
}
}
|
standart ERC-20 function
|
function allowance(address _owner, address _spender)public constant returns (uint256 remaining) {
return allowed[_owner][_spender];
}
| 914,536 |
/*
__/\\\\\\\\\\\\\_____________________________________________________________/\\\\\\\\\\\\________/\\\\\\\\\__________/\\\\\______
_\/\\\/////////\\\__________________________________________________________\/\\\////////\\\____/\\\\\\\\\\\\\______/\\\///\\\____
_\/\\\_______\/\\\__________________________________/\\\_________/\\\__/\\\_\/\\\______\//\\\__/\\\/////////\\\___/\\\/__\///\\\__
_\/\\\\\\\\\\\\\/___/\\\\\\\\\_____/\\/\\\\\\\___/\\\\\\\\\\\___\//\\\/\\\__\/\\\_______\/\\\_\/\\\_______\/\\\__/\\\______\//\\\_
_\/\\\/////////____\////////\\\___\/\\\/////\\\_\////\\\////_____\//\\\\\___\/\\\_______\/\\\_\/\\\\\\\\\\\\\\\_\/\\\_______\/\\\_
_\/\\\_______________/\\\\\\\\\\__\/\\\___\///_____\/\\\__________\//\\\____\/\\\_______\/\\\_\/\\\/////////\\\_\//\\\______/\\\__
_\/\\\______________/\\\/////\\\__\/\\\____________\/\\\_/\\___/\\_/\\\_____\/\\\_______/\\\__\/\\\_______\/\\\__\///\\\__/\\\____
_\/\\\_____________\//\\\\\\\\/\\_\/\\\____________\//\\\\\___\//\\\\/______\/\\\\\\\\\\\\/___\/\\\_______\/\\\____\///\\\\\/_____
_\///_______________\////////\//__\///______________\/////_____\////________\////////////_____\///________\///_______\/////_______
Anna Carroll for PartyDAO
*/
// SPDX-License-Identifier: MIT
pragma solidity 0.8.9;
// ============ External Imports: Inherited Contracts ============
// NOTE: we inherit from OpenZeppelin upgradeable contracts
// because of the proxy structure used for cheaper deploys
// (the proxies are NOT actually upgradeable)
import {ReentrancyGuardUpgradeable} from "@openzeppelin/contracts-upgradeable/security/ReentrancyGuardUpgradeable.sol";
import {ERC721HolderUpgradeable} from "@openzeppelin/contracts-upgradeable/token/ERC721/utils/ERC721HolderUpgradeable.sol";
// ============ External Imports: External Contracts & Contract Interfaces ============
import {IERC721VaultFactory} from "./external/interfaces/IERC721VaultFactory.sol";
import {ITokenVault} from "./external/interfaces/ITokenVault.sol";
import {IWETH} from "./external/interfaces/IWETH.sol";
import {IERC721Metadata} from "@openzeppelin/contracts/token/ERC721/extensions/IERC721Metadata.sol";
import {IERC20} from "@openzeppelin/contracts/token/ERC20/IERC20.sol";
// ============ Internal Imports ============
import {Structs} from "./Structs.sol";
contract Party is ReentrancyGuardUpgradeable, ERC721HolderUpgradeable {
// ============ Enums ============
// State Transitions:
// (0) ACTIVE on deploy
// (1) WON if the Party has won the token
// (2) LOST if the Party is over & did not win the token
enum PartyStatus {
ACTIVE,
WON,
LOST
}
// ============ Structs ============
struct Contribution {
uint256 amount;
uint256 previousTotalContributedToParty;
}
// ============ Internal Constants ============
// tokens are minted at a rate of 1 ETH : 1000 tokens
uint16 internal constant TOKEN_SCALE = 1000;
// PartyDAO receives an ETH fee equal to 2.5% of the amount spent
uint16 internal constant ETH_FEE_BASIS_POINTS = 250;
// PartyDAO receives a token fee equal to 2.5% of the total token supply
uint16 internal constant TOKEN_FEE_BASIS_POINTS = 250;
// token is relisted on Fractional with an
// initial reserve price equal to 2x the price of the token
uint8 internal constant RESALE_MULTIPLIER = 2;
// ============ Immutables ============
address public immutable partyFactory;
address public immutable partyDAOMultisig;
IERC721VaultFactory public immutable tokenVaultFactory;
IWETH public immutable weth;
// ============ Public Not-Mutated Storage ============
// NFT contract
IERC721Metadata public nftContract;
// ID of token within NFT contract
uint256 public tokenId;
// Fractionalized NFT vault responsible for post-purchase experience
ITokenVault public tokenVault;
// the address that will receive a portion of the tokens
// if the Party successfully buys the token
address public splitRecipient;
// percent of the total token supply
// taken by the splitRecipient
uint256 public splitBasisPoints;
// address of token that users need to hold to contribute
// address(0) if party is not token gated
IERC20 public gatedToken;
// amount of token that users need to hold to contribute
// 0 if party is not token gated
uint256 public gatedTokenAmount;
// ERC-20 name and symbol for fractional tokens
string public name;
string public symbol;
// ============ Public Mutable Storage ============
// state of the contract
PartyStatus public partyStatus;
// total ETH deposited by all contributors
uint256 public totalContributedToParty;
// the total spent buying the token;
// 0 if the NFT is not won; price of token + 2.5% PartyDAO fee if NFT is won
uint256 public totalSpent;
// contributor => array of Contributions
mapping(address => Contribution[]) public contributions;
// contributor => total amount contributed
mapping(address => uint256) public totalContributed;
// contributor => true if contribution has been claimed
mapping(address => bool) public claimed;
// ============ Events ============
event Contributed(
address indexed contributor,
uint256 amount,
uint256 previousTotalContributedToParty,
uint256 totalFromContributor
);
event Claimed(
address indexed contributor,
uint256 totalContributed,
uint256 excessContribution,
uint256 tokenAmount
);
// ======== Modifiers =========
modifier onlyPartyDAO() {
require(
msg.sender == partyDAOMultisig,
"Party:: only PartyDAO multisig"
);
_;
}
// ======== Constructor =========
constructor(
address _partyDAOMultisig,
address _tokenVaultFactory,
address _weth
) {
partyFactory = msg.sender;
partyDAOMultisig = _partyDAOMultisig;
tokenVaultFactory = IERC721VaultFactory(_tokenVaultFactory);
weth = IWETH(_weth);
}
// ======== Internal: Initialize =========
function __Party_init(
address _nftContract,
Structs.AddressAndAmount calldata _split,
Structs.AddressAndAmount calldata _tokenGate,
string memory _name,
string memory _symbol
) internal {
require(
msg.sender == partyFactory,
"Party::__Party_init: only factory can init"
);
// if split is non-zero,
if (_split.addr != address(0) && _split.amount != 0) {
// validate that party split won't retain the total token supply
uint256 _remainingBasisPoints = 10000 - TOKEN_FEE_BASIS_POINTS;
require(
_split.amount < _remainingBasisPoints,
"Party::__Party_init: basis points can't take 100%"
);
splitBasisPoints = _split.amount;
splitRecipient = _split.addr;
}
// if token gating is non-zero
if (_tokenGate.addr != address(0) && _tokenGate.amount != 0) {
// call totalSupply to verify that address is ERC-20 token contract
IERC20(_tokenGate.addr).totalSupply();
gatedToken = IERC20(_tokenGate.addr);
gatedTokenAmount = _tokenGate.amount;
}
// initialize ReentrancyGuard and ERC721Holder
__ReentrancyGuard_init();
__ERC721Holder_init();
// set storage variables
nftContract = IERC721Metadata(_nftContract);
name = _name;
symbol = _symbol;
}
// ======== Internal: Contribute =========
/**
* @notice Contribute to the Party's treasury
* while the Party is still active
* @dev Emits a Contributed event upon success; callable by anyone
*/
function _contribute() internal {
require(
partyStatus == PartyStatus.ACTIVE,
"Party::contribute: party not active"
);
address _contributor = msg.sender;
uint256 _amount = msg.value;
// if token gated, require that contributor has balance of gated tokens
if (address(gatedToken) != address(0)) {
require(
gatedToken.balanceOf(_contributor) >= gatedTokenAmount,
"Party::contribute: must hold tokens to contribute"
);
}
require(_amount > 0, "Party::contribute: must contribute more than 0");
// get the current contract balance
uint256 _previousTotalContributedToParty = totalContributedToParty;
// add contribution to contributor's array of contributions
Contribution memory _contribution = Contribution({
amount: _amount,
previousTotalContributedToParty: _previousTotalContributedToParty
});
contributions[_contributor].push(_contribution);
// add to contributor's total contribution
totalContributed[_contributor] =
totalContributed[_contributor] +
_amount;
// add to party's total contribution & emit event
totalContributedToParty = _previousTotalContributedToParty + _amount;
emit Contributed(
_contributor,
_amount,
_previousTotalContributedToParty,
totalContributed[_contributor]
);
}
// ======== External: Claim =========
/**
* @notice Claim the tokens and excess ETH owed
* to a single contributor after the party has ended
* @dev Emits a Claimed event upon success
* callable by anyone (doesn't have to be the contributor)
* @param _contributor the address of the contributor
*/
function claim(address _contributor) external nonReentrant {
// ensure party has finalized
require(
partyStatus != PartyStatus.ACTIVE,
"Party::claim: party not finalized"
);
// ensure contributor submitted some ETH
require(
totalContributed[_contributor] != 0,
"Party::claim: not a contributor"
);
// ensure the contributor hasn't already claimed
require(
!claimed[_contributor],
"Party::claim: contribution already claimed"
);
// mark the contribution as claimed
claimed[_contributor] = true;
// calculate the amount of fractional NFT tokens owed to the user
// based on how much ETH they contributed towards the party,
// and the amount of excess ETH owed to the user
(uint256 _tokenAmount, uint256 _ethAmount) = getClaimAmounts(
_contributor
);
// transfer tokens to contributor for their portion of ETH used
_transferTokens(_contributor, _tokenAmount);
// if there is excess ETH, send it back to the contributor
_transferETHOrWETH(_contributor, _ethAmount);
emit Claimed(
_contributor,
totalContributed[_contributor],
_ethAmount,
_tokenAmount
);
}
// ======== External: Emergency Escape Hatches (PartyDAO Multisig Only) =========
/**
* @notice Escape hatch: in case of emergency,
* PartyDAO can use emergencyWithdrawEth to withdraw
* ETH stuck in the contract
*/
function emergencyWithdrawEth(uint256 _value) external onlyPartyDAO {
_transferETHOrWETH(partyDAOMultisig, _value);
}
/**
* @notice Escape hatch: in case of emergency,
* PartyDAO can use emergencyCall to call an external contract
* (e.g. to withdraw a stuck NFT or stuck ERC-20s)
*/
function emergencyCall(address _contract, bytes memory _calldata)
external
onlyPartyDAO
returns (bool _success, bytes memory _returnData)
{
(_success, _returnData) = _contract.call(_calldata);
require(_success, string(_returnData));
}
/**
* @notice Escape hatch: in case of emergency,
* PartyDAO can force the Party to finalize with status LOST
* (e.g. if finalize is not callable)
*/
function emergencyForceLost() external onlyPartyDAO {
// set partyStatus to LOST
partyStatus = PartyStatus.LOST;
}
// ======== Public: Utility Calculations =========
/**
* @notice Convert ETH value to equivalent token amount
*/
function valueToTokens(uint256 _value)
public
pure
returns (uint256 _tokens)
{
_tokens = _value * TOKEN_SCALE;
}
/**
* @notice The maximum amount that can be spent by the Party
* while paying the ETH fee to PartyDAO
* @return _maxSpend the maximum spend
*/
function getMaximumSpend() public view returns (uint256 _maxSpend) {
_maxSpend =
(totalContributedToParty * 10000) /
(10000 + ETH_FEE_BASIS_POINTS);
}
/**
* @notice Calculate the amount of fractional NFT tokens owed to the contributor
* based on how much ETH they contributed towards buying the token,
* and the amount of excess ETH owed to the contributor
* based on how much ETH they contributed *not* used towards buying the token
* @param _contributor the address of the contributor
* @return _tokenAmount the amount of fractional NFT tokens owed to the contributor
* @return _ethAmount the amount of excess ETH owed to the contributor
*/
function getClaimAmounts(address _contributor)
public
view
returns (uint256 _tokenAmount, uint256 _ethAmount)
{
require(
partyStatus != PartyStatus.ACTIVE,
"Party::getClaimAmounts: party still active; amounts undetermined"
);
uint256 _totalContributed = totalContributed[_contributor];
if (partyStatus == PartyStatus.WON) {
// calculate the amount of this contributor's ETH
// that was used to buy the token
uint256 _totalEthUsed = totalEthUsed(_contributor);
if (_totalEthUsed > 0) {
_tokenAmount = valueToTokens(_totalEthUsed);
}
// the rest of the contributor's ETH should be returned
_ethAmount = _totalContributed - _totalEthUsed;
} else {
// if the token wasn't bought, no ETH was spent;
// all of the contributor's ETH should be returned
_ethAmount = _totalContributed;
}
}
/**
* @notice Calculate the total amount of a contributor's funds
* that were used towards the buying the token
* @dev always returns 0 until the party has been finalized
* @param _contributor the address of the contributor
* @return _total the sum of the contributor's funds that were
* used towards buying the token
*/
function totalEthUsed(address _contributor)
public
view
returns (uint256 _total)
{
require(
partyStatus != PartyStatus.ACTIVE,
"Party::totalEthUsed: party still active; amounts undetermined"
);
// load total amount spent once from storage
uint256 _totalSpent = totalSpent;
// get all of the contributor's contributions
Contribution[] memory _contributions = contributions[_contributor];
for (uint256 i = 0; i < _contributions.length; i++) {
// calculate how much was used from this individual contribution
uint256 _amount = _ethUsed(_totalSpent, _contributions[i]);
// if we reach a contribution that was not used,
// no subsequent contributions will have been used either,
// so we can stop calculating to save some gas
if (_amount == 0) break;
_total = _total + _amount;
}
}
// ============ Internal ============
function _closeSuccessfulParty(uint256 _nftCost)
internal
returns (uint256 _ethFee)
{
// calculate PartyDAO fee & record total spent
_ethFee = _getEthFee(_nftCost);
totalSpent = _nftCost + _ethFee;
// transfer ETH fee to PartyDAO
_transferETHOrWETH(partyDAOMultisig, _ethFee);
// deploy fractionalized NFT vault
// and mint fractional ERC-20 tokens
_fractionalizeNFT(_nftCost);
}
/**
* @notice Calculate ETH fee for PartyDAO
* NOTE: Remove this fee causes a critical vulnerability
* allowing anyone to exploit a Party via price manipulation.
* See Security Review in README for more info.
* @return _fee the portion of _amount represented by scaling to ETH_FEE_BASIS_POINTS
*/
function _getEthFee(uint256 _amount) internal pure returns (uint256 _fee) {
_fee = (_amount * ETH_FEE_BASIS_POINTS) / 10000;
}
/**
* @notice Calculate token amount for specified token recipient
* @return _totalSupply the total token supply
* @return _partyDAOAmount the amount of tokens for partyDAO fee,
* which is equivalent to TOKEN_FEE_BASIS_POINTS of total supply
* @return _splitRecipientAmount the amount of tokens for the token recipient,
* which is equivalent to splitBasisPoints of total supply
*/
function _getTokenInflationAmounts(uint256 _amountSpent)
internal
view
returns (
uint256 _totalSupply,
uint256 _partyDAOAmount,
uint256 _splitRecipientAmount
)
{
// the token supply will be inflated to provide a portion of the
// total supply for PartyDAO, and a portion for the splitRecipient
uint256 inflationBasisPoints = TOKEN_FEE_BASIS_POINTS +
splitBasisPoints;
_totalSupply = valueToTokens(
(_amountSpent * 10000) / (10000 - inflationBasisPoints)
);
// PartyDAO receives TOKEN_FEE_BASIS_POINTS of the total supply
_partyDAOAmount = (_totalSupply * TOKEN_FEE_BASIS_POINTS) / 10000;
// splitRecipient receives splitBasisPoints of the total supply
_splitRecipientAmount = (_totalSupply * splitBasisPoints) / 10000;
}
/**
* @notice Query the NFT contract to get the token owner
* @dev nftContract must implement the ERC-721 token standard exactly:
* function ownerOf(uint256 _tokenId) external view returns (address);
* See https://eips.ethereum.org/EIPS/eip-721
* @dev Returns address(0) if NFT token or NFT contract
* no longer exists (token burned or contract self-destructed)
* @return _owner the owner of the NFT
*/
function _getOwner() internal view returns (address _owner) {
(bool _success, bytes memory _returnData) = address(nftContract)
.staticcall(abi.encodeWithSignature("ownerOf(uint256)", tokenId));
if (_success && _returnData.length > 0) {
_owner = abi.decode(_returnData, (address));
}
}
/**
* @notice Upon winning the token, transfer the NFT
* to fractional.art vault & mint fractional ERC-20 tokens
*/
function _fractionalizeNFT(uint256 _amountSpent) internal {
// approve fractionalized NFT Factory to withdraw NFT
nftContract.approve(address(tokenVaultFactory), tokenId);
// Party "votes" for a reserve price on Fractional
// equal to 2x the price of the token
uint256 _listPrice = RESALE_MULTIPLIER * _amountSpent;
// users receive tokens at a rate of 1:TOKEN_SCALE for each ETH they contributed that was ultimately spent
// partyDAO receives a percentage of the total token supply equivalent to TOKEN_FEE_BASIS_POINTS
// splitRecipient receives a percentage of the total token supply equivalent to splitBasisPoints
(
uint256 _tokenSupply,
uint256 _partyDAOAmount,
uint256 _splitRecipientAmount
) = _getTokenInflationAmounts(totalSpent);
// deploy fractionalized NFT vault
uint256 vaultNumber = tokenVaultFactory.mint(
name,
symbol,
address(nftContract),
tokenId,
_tokenSupply,
_listPrice,
0
);
// store token vault address to storage
tokenVault = ITokenVault(tokenVaultFactory.vaults(vaultNumber));
// transfer curator to null address (burn the curator role)
tokenVault.updateCurator(address(0));
// transfer tokens to PartyDAO multisig
_transferTokens(partyDAOMultisig, _partyDAOAmount);
// transfer tokens to token recipient
if (splitRecipient != address(0)) {
_transferTokens(splitRecipient, _splitRecipientAmount);
}
}
// ============ Internal: Claim ============
/**
* @notice Calculate the amount of a single Contribution
* that was used towards buying the token
* @param _contribution the Contribution struct
* @return the amount of funds from this contribution
* that were used towards buying the token
*/
function _ethUsed(uint256 _totalSpent, Contribution memory _contribution)
internal
pure
returns (uint256)
{
if (
_contribution.previousTotalContributedToParty +
_contribution.amount <=
_totalSpent
) {
// contribution was fully used
return _contribution.amount;
} else if (
_contribution.previousTotalContributedToParty < _totalSpent
) {
// contribution was partially used
return _totalSpent - _contribution.previousTotalContributedToParty;
}
// contribution was not used
return 0;
}
// ============ Internal: TransferTokens ============
/**
* @notice Transfer tokens to a recipient
* @param _to recipient of tokens
* @param _value amount of tokens
*/
function _transferTokens(address _to, uint256 _value) internal {
// skip if attempting to send 0 tokens
if (_value == 0) {
return;
}
// guard against rounding errors;
// if token amount to send is greater than contract balance,
// send full contract balance
uint256 _partyBalance = tokenVault.balanceOf(address(this));
if (_value > _partyBalance) {
_value = _partyBalance;
}
tokenVault.transfer(_to, _value);
}
// ============ Internal: TransferEthOrWeth ============
/**
* @notice Attempt to transfer ETH to a recipient;
* if transferring ETH fails, transfer WETH insteads
* @param _to recipient of ETH or WETH
* @param _value amount of ETH or WETH
*/
function _transferETHOrWETH(address _to, uint256 _value) internal {
// skip if attempting to send 0 ETH
if (_value == 0) {
return;
}
// guard against rounding errors;
// if ETH amount to send is greater than contract balance,
// send full contract balance
if (_value > address(this).balance) {
_value = address(this).balance;
}
// Try to transfer ETH to the given recipient.
if (!_attemptETHTransfer(_to, _value)) {
// If the transfer fails, wrap and send as WETH
weth.deposit{value: _value}();
weth.transfer(_to, _value);
// At this point, the recipient can unwrap WETH.
}
}
/**
* @notice Attempt to transfer ETH to a recipient
* @dev Sending ETH is not guaranteed to succeed
* this method will return false if it fails.
* We will limit the gas used in transfers, and handle failure cases.
* @param _to recipient of ETH
* @param _value amount of ETH
*/
function _attemptETHTransfer(address _to, uint256 _value)
internal
returns (bool)
{
// Here increase the gas limit a reasonable amount above the default, and try
// to send ETH to the recipient.
// NOTE: This might allow the recipient to attempt a limited reentrancy attack.
(bool success, ) = _to.call{value: _value, gas: 30000}("");
return success;
}
}
|
The maximum amount that can be spent by the Party while paying the ETH fee to PartyDAO return _maxSpend the maximum spend/
|
function getMaximumSpend() public view returns (uint256 _maxSpend) {
_maxSpend =
(totalContributedToParty * 10000) /
(10000 + ETH_FEE_BASIS_POINTS);
}
| 6,455,524 |
./full_match/1/0x28472a58A490c5e09A238847F66A68a47cC76f0f/sources/contracts/AdidasOriginals.sol
|
returns the metadata uri for a given id _id the card id to return metadata for/
|
function uri(uint256 _id) public view override returns (string memory) {
require(exists(_id), "URI: nonexistent token");
return string(abi.encodePacked(super.uri(_id), Strings.toString(_id)));
}
| 8,386,398 |
pragma solidity 0.5.3;
library OpenZeppelinUpgradesAddress {
/**
* Returns whether the target address is a contract
* @dev This function will return false if invoked during the constructor of a contract,
* as the code is not actually created until after the constructor finishes.
* @param account address of the account to check
* @return whether the target address is a contract
*/
function isContract(address account) internal view returns (bool) {
uint256 size;
// XXX Currently there is no better way to check if there is a contract in an address
// than to check the size of the code at that address.
// See https://ethereum.stackexchange.com/a/14016/36603
// for more details about how this works.
// TODO Check this again before the Serenity release, because all addresses will be
// contracts then.
// solhint-disable-next-line no-inline-assembly
assembly { size := extcodesize(account) }
return size > 0;
}
}
library OpenZeppelinUpgradesECDSA {
/**
* @dev Recover signer address from a message by using their signature
* @param hash bytes32 message, the hash is the signed message. What is recovered is the signer address.
* @param signature bytes signature, the signature is generated using web3.eth.sign()
*/
function recover(bytes32 hash, bytes memory signature) internal pure returns (address) {
// Check the signature length
if (signature.length != 65) {
return (address(0));
}
// Divide the signature in r, s and v variables
bytes32 r;
bytes32 s;
uint8 v;
// ecrecover takes the signature parameters, and the only way to get them
// currently is to use assembly.
// solhint-disable-next-line no-inline-assembly
assembly {
r := mload(add(signature, 0x20))
s := mload(add(signature, 0x40))
v := byte(0, mload(add(signature, 0x60)))
}
// EIP-2 still allows signature malleability for ecrecover(). Remove this possibility and make the signature
// unique. Appendix F in the Ethereum Yellow paper (https://ethereum.github.io/yellowpaper/paper.pdf), defines
// the valid range for s in (281): 0 < s < secp256k1n ÷ 2 + 1, and for v in (282): v ∈ {27, 28}. Most
// signatures from current libraries generate a unique signature with an s-value in the lower half order.
//
// If your library generates malleable signatures, such as s-values in the upper range, calculate a new s-value
// with 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFEBAAEDCE6AF48A03BBFD25E8CD0364141 - s1 and flip v from 27 to 28 or
// vice versa. If your library also generates signatures with 0/1 for v instead 27/28, add 27 to v to accept
// these malleable signatures as well.
if (uint256(s) > 0x7FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF5D576E7357A4501DDFE92F46681B20A0) {
return address(0);
}
if (v != 27 && v != 28) {
return address(0);
}
// If the signature is valid (and not malleable), return the signer address
return ecrecover(hash, v, r, s);
}
/**
* toEthSignedMessageHash
* @dev prefix a bytes32 value with "\x19Ethereum Signed Message:"
* and hash the result
*/
function toEthSignedMessageHash(bytes32 hash) internal pure returns (bytes32) {
// 32 is the length in bytes of hash,
// enforced by the type signature above
return keccak256(abi.encodePacked("\x19Ethereum Signed Message:\n32", hash));
}
}
contract OpenZeppelinUpgradesOwnable {
address private _owner;
event OwnershipTransferred(address indexed previousOwner, address indexed newOwner);
/**
* @dev The Ownable constructor sets the original `owner` of the contract to the sender
* account.
*/
constructor () internal {
_owner = msg.sender;
emit OwnershipTransferred(address(0), _owner);
}
/**
* @return the address of the owner.
*/
function owner() public view returns (address) {
return _owner;
}
/**
* @dev Throws if called by any account other than the owner.
*/
modifier onlyOwner() {
require(isOwner());
_;
}
/**
* @return true if `msg.sender` is the owner of the contract.
*/
function isOwner() public view returns (bool) {
return msg.sender == _owner;
}
/**
* @dev Allows the current owner to relinquish control of the contract.
* @notice Renouncing to ownership will leave the contract without an owner.
* It will not be possible to call the functions with the `onlyOwner`
* modifier anymore.
*/
function renounceOwnership() public onlyOwner {
emit OwnershipTransferred(_owner, address(0));
_owner = address(0);
}
/**
* @dev Allows the current owner to transfer control of the contract to a newOwner.
* @param newOwner The address to transfer ownership to.
*/
function transferOwnership(address newOwner) public onlyOwner {
_transferOwnership(newOwner);
}
/**
* @dev Transfers control of the contract to a newOwner.
* @param newOwner The address to transfer ownership to.
*/
function _transferOwnership(address newOwner) internal {
require(newOwner != address(0));
emit OwnershipTransferred(_owner, newOwner);
_owner = newOwner;
}
}
contract Proxy {
/**
* @dev Fallback function.
* Implemented entirely in `_fallback`.
*/
function () payable external {
_fallback();
}
/**
* @return The Address of the implementation.
*/
function _implementation() internal view returns (address);
/**
* @dev Delegates execution to an implementation contract.
* This is a low level function that doesn't return to its internal call site.
* It will return to the external caller whatever the implementation returns.
* @param implementation Address to delegate.
*/
function _delegate(address implementation) internal {
assembly {
// Copy msg.data. We take full control of memory in this inline assembly
// block because it will not return to Solidity code. We overwrite the
// Solidity scratch pad at memory position 0.
calldatacopy(0, 0, calldatasize)
// Call the implementation.
// out and outsize are 0 because we don't know the size yet.
let result := delegatecall(gas, implementation, 0, calldatasize, 0, 0)
// Copy the returned data.
returndatacopy(0, 0, returndatasize)
switch result
// delegatecall returns 0 on error.
case 0 { revert(0, returndatasize) }
default { return(0, returndatasize) }
}
}
/**
* @dev Function that is run as the first thing in the fallback function.
* Can be redefined in derived contracts to add functionality.
* Redefinitions must call super._willFallback().
*/
function _willFallback() internal {
}
/**
* @dev fallback implementation.
* Extracted to enable manual triggering.
*/
function _fallback() internal {
_willFallback();
_delegate(_implementation());
}
}
contract ProxyAdmin is OpenZeppelinUpgradesOwnable {
/**
* @dev Returns the current implementation of a proxy.
* This is needed because only the proxy admin can query it.
* @return The address of the current implementation of the proxy.
*/
function getProxyImplementation(AdminUpgradeabilityProxy proxy) public view returns (address) {
// We need to manually run the static call since the getter cannot be flagged as view
// bytes4(keccak256("implementation()")) == 0x5c60da1b
(bool success, bytes memory returndata) = address(proxy).staticcall(hex"5c60da1b");
require(success);
return abi.decode(returndata, (address));
}
/**
* @dev Returns the admin of a proxy. Only the admin can query it.
* @return The address of the current admin of the proxy.
*/
function getProxyAdmin(AdminUpgradeabilityProxy proxy) public view returns (address) {
// We need to manually run the static call since the getter cannot be flagged as view
// bytes4(keccak256("admin()")) == 0xf851a440
(bool success, bytes memory returndata) = address(proxy).staticcall(hex"f851a440");
require(success);
return abi.decode(returndata, (address));
}
/**
* @dev Changes the admin of a proxy.
* @param proxy Proxy to change admin.
* @param newAdmin Address to transfer proxy administration to.
*/
function changeProxyAdmin(AdminUpgradeabilityProxy proxy, address newAdmin) public onlyOwner {
proxy.changeAdmin(newAdmin);
}
/**
* @dev Upgrades a proxy to the newest implementation of a contract.
* @param proxy Proxy to be upgraded.
* @param implementation the address of the Implementation.
*/
function upgrade(AdminUpgradeabilityProxy proxy, address implementation) public onlyOwner {
proxy.upgradeTo(implementation);
}
/**
* @dev Upgrades a proxy to the newest implementation of a contract and forwards a function call to it.
* This is useful to initialize the proxied contract.
* @param proxy Proxy to be upgraded.
* @param implementation Address of the Implementation.
* @param data Data to send as msg.data in the low level call.
* It should include the signature and the parameters of the function to be called, as described in
* https://solidity.readthedocs.io/en/v0.4.24/abi-spec.html#function-selector-and-argument-encoding.
*/
function upgradeAndCall(AdminUpgradeabilityProxy proxy, address implementation, bytes memory data) payable public onlyOwner {
proxy.upgradeToAndCall.value(msg.value)(implementation, data);
}
}
contract ProxyFactory {
event ProxyCreated(address proxy);
bytes32 private contractCodeHash;
constructor() public {
contractCodeHash = keccak256(
type(InitializableAdminUpgradeabilityProxy).creationCode
);
}
function deployMinimal(address _logic, bytes memory _data) public returns (address proxy) {
// Adapted from https://github.com/optionality/clone-factory/blob/32782f82dfc5a00d103a7e61a17a5dedbd1e8e9d/contracts/CloneFactory.sol
bytes20 targetBytes = bytes20(_logic);
assembly {
let clone := mload(0x40)
mstore(clone, 0x3d602d80600a3d3981f3363d3d373d3d3d363d73000000000000000000000000)
mstore(add(clone, 0x14), targetBytes)
mstore(add(clone, 0x28), 0x5af43d82803e903d91602b57fd5bf30000000000000000000000000000000000)
proxy := create(0, clone, 0x37)
}
emit ProxyCreated(address(proxy));
if(_data.length > 0) {
(bool success,) = proxy.call(_data);
require(success);
}
}
function deploy(uint256 _salt, address _logic, address _admin, bytes memory _data) public returns (address) {
return _deployProxy(_salt, _logic, _admin, _data, msg.sender);
}
function deploySigned(uint256 _salt, address _logic, address _admin, bytes memory _data, bytes memory _signature) public returns (address) {
address signer = getSigner(_salt, _logic, _admin, _data, _signature);
require(signer != address(0), "Invalid signature");
return _deployProxy(_salt, _logic, _admin, _data, signer);
}
function getDeploymentAddress(uint256 _salt, address _sender) public view returns (address) {
// Adapted from https://github.com/archanova/solidity/blob/08f8f6bedc6e71c24758d20219b7d0749d75919d/contracts/contractCreator/ContractCreator.sol
bytes32 salt = _getSalt(_salt, _sender);
bytes32 rawAddress = keccak256(
abi.encodePacked(
bytes1(0xff),
address(this),
salt,
contractCodeHash
)
);
return address(bytes20(rawAddress << 96));
}
function getSigner(uint256 _salt, address _logic, address _admin, bytes memory _data, bytes memory _signature) public view returns (address) {
bytes32 msgHash = OpenZeppelinUpgradesECDSA.toEthSignedMessageHash(
keccak256(
abi.encodePacked(
_salt, _logic, _admin, _data, address(this)
)
)
);
return OpenZeppelinUpgradesECDSA.recover(msgHash, _signature);
}
function _deployProxy(uint256 _salt, address _logic, address _admin, bytes memory _data, address _sender) internal returns (address) {
InitializableAdminUpgradeabilityProxy proxy = _createProxy(_salt, _sender);
emit ProxyCreated(address(proxy));
proxy.initialize(_logic, _admin, _data);
return address(proxy);
}
function _createProxy(uint256 _salt, address _sender) internal returns (InitializableAdminUpgradeabilityProxy) {
address payable addr;
bytes memory code = type(InitializableAdminUpgradeabilityProxy).creationCode;
bytes32 salt = _getSalt(_salt, _sender);
assembly {
addr := create2(0, add(code, 0x20), mload(code), salt)
if iszero(extcodesize(addr)) {
revert(0, 0)
}
}
return InitializableAdminUpgradeabilityProxy(addr);
}
function _getSalt(uint256 _salt, address _sender) internal pure returns (bytes32) {
return keccak256(abi.encodePacked(_salt, _sender));
}
}
contract BaseUpgradeabilityProxy is Proxy {
/**
* @dev Emitted when the implementation is upgraded.
* @param implementation Address of the new implementation.
*/
event Upgraded(address indexed implementation);
/**
* @dev Storage slot with the address of the current implementation.
* This is the keccak-256 hash of "eip1967.proxy.implementation" subtracted by 1, and is
* validated in the constructor.
*/
bytes32 internal constant IMPLEMENTATION_SLOT = 0x360894a13ba1a3210667c828492db98dca3e2076cc3735a920a3ca505d382bbc;
/**
* @dev Returns the current implementation.
* @return Address of the current implementation
*/
function _implementation() internal view returns (address impl) {
bytes32 slot = IMPLEMENTATION_SLOT;
assembly {
impl := sload(slot)
}
}
/**
* @dev Upgrades the proxy to a new implementation.
* @param newImplementation Address of the new implementation.
*/
function _upgradeTo(address newImplementation) internal {
_setImplementation(newImplementation);
emit Upgraded(newImplementation);
}
/**
* @dev Sets the implementation address of the proxy.
* @param newImplementation Address of the new implementation.
*/
function _setImplementation(address newImplementation) internal {
require(OpenZeppelinUpgradesAddress.isContract(newImplementation), "Cannot set a proxy implementation to a non-contract address");
bytes32 slot = IMPLEMENTATION_SLOT;
assembly {
sstore(slot, newImplementation)
}
}
}
contract InitializableUpgradeabilityProxy is BaseUpgradeabilityProxy {
/**
* @dev Contract initializer.
* @param _logic Address of the initial implementation.
* @param _data Data to send as msg.data to the implementation to initialize the proxied contract.
* It should include the signature and the parameters of the function to be called, as described in
* https://solidity.readthedocs.io/en/v0.4.24/abi-spec.html#function-selector-and-argument-encoding.
* This parameter is optional, if no data is given the initialization call to proxied contract will be skipped.
*/
function initialize(address _logic, bytes memory _data) public payable {
require(_implementation() == address(0));
assert(IMPLEMENTATION_SLOT == bytes32(uint256(keccak256('eip1967.proxy.implementation')) - 1));
_setImplementation(_logic);
if(_data.length > 0) {
(bool success,) = _logic.delegatecall(_data);
require(success);
}
}
}
contract UpgradeabilityProxy is BaseUpgradeabilityProxy {
/**
* @dev Contract constructor.
* @param _logic Address of the initial implementation.
* @param _data Data to send as msg.data to the implementation to initialize the proxied contract.
* It should include the signature and the parameters of the function to be called, as described in
* https://solidity.readthedocs.io/en/v0.4.24/abi-spec.html#function-selector-and-argument-encoding.
* This parameter is optional, if no data is given the initialization call to proxied contract will be skipped.
*/
constructor(address _logic, bytes memory _data) public payable {
assert(IMPLEMENTATION_SLOT == bytes32(uint256(keccak256('eip1967.proxy.implementation')) - 1));
_setImplementation(_logic);
if(_data.length > 0) {
(bool success,) = _logic.delegatecall(_data);
require(success);
}
}
}
contract BaseAdminUpgradeabilityProxy is BaseUpgradeabilityProxy {
/**
* @dev Emitted when the administration has been transferred.
* @param previousAdmin Address of the previous admin.
* @param newAdmin Address of the new admin.
*/
event AdminChanged(address previousAdmin, address newAdmin);
/**
* @dev Storage slot with the admin of the contract.
* This is the keccak-256 hash of "eip1967.proxy.admin" subtracted by 1, and is
* validated in the constructor.
*/
bytes32 internal constant ADMIN_SLOT = 0xb53127684a568b3173ae13b9f8a6016e243e63b6e8ee1178d6a717850b5d6103;
/**
* @dev Modifier to check whether the `msg.sender` is the admin.
* If it is, it will run the function. Otherwise, it will delegate the call
* to the implementation.
*/
modifier ifAdmin() {
if (msg.sender == _admin()) {
_;
} else {
_fallback();
}
}
/**
* @return The address of the proxy admin.
*/
function admin() external ifAdmin returns (address) {
return _admin();
}
/**
* @return The address of the implementation.
*/
function implementation() external ifAdmin returns (address) {
return _implementation();
}
/**
* @dev Changes the admin of the proxy.
* Only the current admin can call this function.
* @param newAdmin Address to transfer proxy administration to.
*/
function changeAdmin(address newAdmin) external ifAdmin {
require(newAdmin != address(0), "Cannot change the admin of a proxy to the zero address");
emit AdminChanged(_admin(), newAdmin);
_setAdmin(newAdmin);
}
/**
* @dev Upgrade the backing implementation of the proxy.
* Only the admin can call this function.
* @param newImplementation Address of the new implementation.
*/
function upgradeTo(address newImplementation) external ifAdmin {
_upgradeTo(newImplementation);
}
/**
* @dev Upgrade the backing implementation of the proxy and call a function
* on the new implementation.
* This is useful to initialize the proxied contract.
* @param newImplementation Address of the new implementation.
* @param data Data to send as msg.data in the low level call.
* It should include the signature and the parameters of the function to be called, as described in
* https://solidity.readthedocs.io/en/v0.4.24/abi-spec.html#function-selector-and-argument-encoding.
*/
function upgradeToAndCall(address newImplementation, bytes calldata data) payable external ifAdmin {
_upgradeTo(newImplementation);
(bool success,) = newImplementation.delegatecall(data);
require(success);
}
/**
* @return The admin slot.
*/
function _admin() internal view returns (address adm) {
bytes32 slot = ADMIN_SLOT;
assembly {
adm := sload(slot)
}
}
/**
* @dev Sets the address of the proxy admin.
* @param newAdmin Address of the new proxy admin.
*/
function _setAdmin(address newAdmin) internal {
bytes32 slot = ADMIN_SLOT;
assembly {
sstore(slot, newAdmin)
}
}
/**
* @dev Only fall back when the sender is not the admin.
*/
function _willFallback() internal {
require(msg.sender != _admin(), "Cannot call fallback function from the proxy admin");
super._willFallback();
}
}
contract InitializableAdminUpgradeabilityProxy is BaseAdminUpgradeabilityProxy, InitializableUpgradeabilityProxy {
/**
* Contract initializer.
* @param _logic address of the initial implementation.
* @param _admin Address of the proxy administrator.
* @param _data Data to send as msg.data to the implementation to initialize the proxied contract.
* It should include the signature and the parameters of the function to be called, as described in
* https://solidity.readthedocs.io/en/v0.4.24/abi-spec.html#function-selector-and-argument-encoding.
* This parameter is optional, if no data is given the initialization call to proxied contract will be skipped.
*/
function initialize(address _logic, address _admin, bytes memory _data) public payable {
require(_implementation() == address(0));
InitializableUpgradeabilityProxy.initialize(_logic, _data);
assert(ADMIN_SLOT == bytes32(uint256(keccak256('eip1967.proxy.admin')) - 1));
_setAdmin(_admin);
}
}
contract AdminUpgradeabilityProxy is BaseAdminUpgradeabilityProxy, UpgradeabilityProxy {
/**
* Contract constructor.
* @param _logic address of the initial implementation.
* @param _admin Address of the proxy administrator.
* @param _data Data to send as msg.data to the implementation to initialize the proxied contract.
* It should include the signature and the parameters of the function to be called, as described in
* https://solidity.readthedocs.io/en/v0.4.24/abi-spec.html#function-selector-and-argument-encoding.
* This parameter is optional, if no data is given the initialization call to proxied contract will be skipped.
*/
constructor(address _logic, address _admin, bytes memory _data) UpgradeabilityProxy(_logic, _data) public payable {
assert(ADMIN_SLOT == bytes32(uint256(keccak256('eip1967.proxy.admin')) - 1));
_setAdmin(_admin);
}
}
|
We need to manually run the static call since the getter cannot be flagged as view bytes4(keccak256("admin()")) == 0xf851a440
|
function getProxyAdmin(AdminUpgradeabilityProxy proxy) public view returns (address) {
(bool success, bytes memory returndata) = address(proxy).staticcall(hex"f851a440");
require(success);
return abi.decode(returndata, (address));
}
| 7,548,926 |
// to test issue with nodes breaking with large clients over WS
// fixed in web3 with fragmentationThreshold: 8192
pragma solidity ^0.4.17;
contract BigFreakingContract {
event Transfer(address indexed from, address indexed to, uint value);
event Approval( address indexed owner, address indexed spender, uint value);
mapping( address => uint ) _balances;
mapping( address => mapping( address => uint ) ) _approvals;
uint public _supply;
constructor( uint initial_balance ) public {
_balances[msg.sender] = initial_balance;
_supply = initial_balance;
}
function totalSupply() public constant returns (uint supply) {
return _supply;
}
function balanceOf( address who ) public constant returns (uint value) {
return _balances[who];
}
function transfer( address to, uint value) public returns (bool ok) {
if( _balances[msg.sender] < value ) {
revert();
}
if( !safeToAdd(_balances[to], value) ) {
revert();
}
_balances[msg.sender] -= value;
_balances[to] += value;
emit Transfer( msg.sender, to, value );
return true;
}
function transferFrom( address from, address to, uint value) public returns (bool ok) {
// if you don't have enough balance, throw
if( _balances[from] < value ) {
revert();
}
// if you don't have approval, throw
if( _approvals[from][msg.sender] < value ) {
revert();
}
if( !safeToAdd(_balances[to], value) ) {
revert();
}
// transfer and return true
_approvals[from][msg.sender] -= value;
_balances[from] -= value;
_balances[to] += value;
emit Transfer( from, to, value );
return true;
}
function approve(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function allowance(address owner, address spender) public constant returns (uint _allowance) {
return _approvals[owner][spender];
}
function safeToAdd(uint a, uint b) internal pure returns (bool) {
return (a + b >= a);
}
function isAvailable() public pure returns (bool) {
return false;
}
function approve_1(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_2(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_3(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_4(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_5(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_6(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_7(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_8(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_9(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_10(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_11(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_12(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_13(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_14(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_15(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_16(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_17(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_18(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_19(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_20(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_21(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_22(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_23(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_24(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_25(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_26(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_27(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_28(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_29(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_30(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_31(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_32(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_33(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_34(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_35(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_36(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_37(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_38(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_39(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_40(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_41(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_42(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_43(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_44(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_45(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_46(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_47(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_48(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_49(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_50(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_51(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_52(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_53(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_54(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_55(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_56(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_57(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_58(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_59(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_60(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_61(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_62(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_63(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_64(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_65(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_66(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_67(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_68(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_69(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_70(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_71(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_72(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_73(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_74(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_75(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_76(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_77(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_78(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_79(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_80(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_81(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_82(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_83(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_84(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_85(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_86(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_87(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_88(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_89(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_90(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_91(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_92(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_93(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_94(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_95(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_96(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_97(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_98(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_99(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_100(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_101(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_102(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_103(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_104(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_105(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_106(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_107(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_108(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_109(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_110(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_111(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_112(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_113(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_114(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_115(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_116(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_117(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_118(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_119(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_120(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_121(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_122(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_123(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_124(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_125(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_126(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_127(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_128(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_129(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_130(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_131(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_132(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_133(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_134(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_135(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_136(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_137(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_138(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_139(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_140(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_141(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_142(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_143(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_144(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_145(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_146(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_147(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_148(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_149(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_150(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_151(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_152(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_153(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_154(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_155(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_156(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_157(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_158(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_159(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_160(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_161(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_162(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_163(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_164(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_165(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_166(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_167(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_168(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_169(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_170(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_171(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_172(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_173(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_174(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_175(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_176(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_177(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_178(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_179(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_180(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_181(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_182(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_183(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_184(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_185(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_186(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_187(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_188(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_189(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_190(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_191(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_192(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_193(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_194(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_195(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_196(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_197(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_198(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_199(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_200(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_201(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_202(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_203(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_204(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_205(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_206(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_207(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_208(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_209(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_210(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_211(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_212(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_213(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_214(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_215(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_216(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_217(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_218(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_219(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_220(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_221(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_222(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_223(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_224(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_225(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_226(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_227(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_228(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_229(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_230(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_231(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_232(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_233(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_234(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_235(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_236(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_237(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_238(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_239(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_240(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_241(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_242(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_243(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_244(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_245(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_246(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_247(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_248(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_249(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_250(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_251(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_252(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_253(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_254(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_255(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_256(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_257(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_258(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_259(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_260(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_261(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_262(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_263(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_264(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_265(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_266(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_267(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_268(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_269(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_270(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_271(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_272(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_273(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_274(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_275(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_276(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_277(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_278(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_279(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_280(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_281(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_282(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_283(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_284(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_285(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_286(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_287(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_288(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_289(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_290(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_291(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_292(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_293(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_294(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_295(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_296(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_297(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_298(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_299(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_300(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_301(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_302(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_303(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_304(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_305(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_306(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_307(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_308(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_309(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_310(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_311(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_312(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_313(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_314(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_315(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_316(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_317(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_318(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_319(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_320(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_321(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_322(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_323(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_324(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_325(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_326(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_327(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_328(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_329(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_330(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_331(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_332(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_333(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_334(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_335(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_336(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_337(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_338(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_339(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_340(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_341(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_342(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_343(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_344(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_345(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_346(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_347(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_348(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_349(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_350(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_351(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_352(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_353(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_354(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_355(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_356(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_357(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_358(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_359(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_360(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_361(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_362(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_363(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_364(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_365(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_366(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_367(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_368(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_369(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_370(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_371(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_372(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_373(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_374(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_375(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_376(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_377(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_378(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_379(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_380(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_381(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_382(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_383(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_384(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_385(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_386(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_387(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_388(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_389(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_390(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_391(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_392(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_393(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_394(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_395(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_396(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_397(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_398(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_399(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_400(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_401(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_402(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_403(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_404(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_405(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_406(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_407(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_408(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_409(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_410(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_411(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_412(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_413(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_414(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_415(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_416(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_417(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_418(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_419(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_420(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_421(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_422(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_423(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_424(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_425(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_426(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_427(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_428(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_429(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_430(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_431(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_432(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_433(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_434(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_435(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_436(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_437(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_438(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_439(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_440(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_441(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_442(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_443(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_444(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_445(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_446(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_447(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_448(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_449(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_450(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_451(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_452(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_453(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_454(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_455(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_456(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_457(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_458(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_459(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_460(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_461(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_462(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_463(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_464(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_465(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_466(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_467(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_468(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_469(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_470(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_471(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_472(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_473(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_474(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_475(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_476(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_477(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_478(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_479(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_480(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_481(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_482(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_483(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_484(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_485(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_486(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_487(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_488(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_489(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_490(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_491(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_492(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_493(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_494(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_495(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_496(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_497(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_498(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_499(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_500(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_501(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_502(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_503(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_504(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_505(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_506(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_507(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_508(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_509(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_510(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_511(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_512(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_513(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_514(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_515(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_516(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_517(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_518(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_519(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_520(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_521(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_522(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_523(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_524(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_525(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_526(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_527(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_528(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_529(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_530(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_531(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_532(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_533(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_534(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_535(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_536(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_537(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_538(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_539(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_540(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_541(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_542(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_543(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_544(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_545(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_546(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_547(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_548(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_549(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_550(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_551(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_552(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_553(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_554(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_555(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_556(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_557(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_558(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_559(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_560(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_561(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_562(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_563(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_564(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_565(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_566(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_567(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_568(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_569(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_570(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_571(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_572(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_573(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_574(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_575(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_576(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_577(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_578(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_579(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_580(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_581(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_582(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_583(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_584(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_585(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_586(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_587(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_588(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_589(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_590(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_591(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_592(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_593(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_594(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_595(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_596(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_597(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_598(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_599(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_600(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_601(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_602(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_603(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_604(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_605(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_606(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_607(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_608(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_609(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_610(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_611(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_612(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_613(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_614(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_615(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_616(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_617(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_618(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_619(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_620(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_621(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_622(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_623(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_624(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_625(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_626(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_627(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_628(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_629(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_630(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_631(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_632(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_633(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_634(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_635(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_636(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_637(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_638(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_639(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_640(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_641(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_642(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_643(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_644(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_645(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_646(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_647(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_648(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_649(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_650(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_651(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_652(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_653(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_654(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_655(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_656(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_657(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_658(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_659(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_660(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_661(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_662(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_663(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_664(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_665(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_666(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_667(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_668(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_669(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_670(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_671(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_672(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_673(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_674(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_675(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_676(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_677(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_678(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_679(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_680(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_681(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_682(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_683(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_684(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_685(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_686(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_687(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_688(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_689(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_690(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_691(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_692(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_693(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_694(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_695(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_696(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_697(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_698(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_699(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_700(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_701(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_702(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_703(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_704(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_705(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_706(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_707(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_708(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_709(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_710(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_711(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_712(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_713(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_714(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_715(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_716(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_717(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_718(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_719(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_720(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_721(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_722(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_723(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_724(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_725(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_726(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_727(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_728(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_729(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_730(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_731(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_732(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_733(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_734(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_735(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_736(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_737(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_738(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_739(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_740(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_741(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_742(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_743(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_744(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_745(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_746(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_747(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_748(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_749(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_750(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_751(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_752(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_753(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_754(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_755(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_756(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_757(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_758(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_759(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_760(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_761(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_762(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_763(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_764(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_765(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_766(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_767(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_768(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_769(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_770(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_771(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_772(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_773(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_774(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_775(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_776(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_777(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_778(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_779(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_780(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_781(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_782(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_783(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_784(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_785(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_786(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_787(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_788(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_789(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_790(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_791(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_792(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_793(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_794(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_795(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_796(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_797(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_798(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_799(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_800(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_801(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_802(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_803(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_804(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_805(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_806(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_807(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_808(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_809(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_810(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_811(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_812(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_813(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_814(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_815(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_816(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_817(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_818(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_819(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_820(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_821(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_822(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_823(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_824(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_825(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_826(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_827(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_828(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_829(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_830(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_831(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_832(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_833(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_834(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_835(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_836(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_837(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_838(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_839(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_840(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_841(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_842(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_843(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_844(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_845(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_846(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_847(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_848(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_849(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_850(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_851(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_852(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_853(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_854(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_855(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_856(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_857(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_858(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_859(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_860(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_861(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_862(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_863(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_864(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_865(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_866(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_867(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_868(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_869(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_870(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_871(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_872(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_873(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_874(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_875(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_876(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_877(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_878(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_879(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_880(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_881(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_882(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_883(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_884(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_885(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_886(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_887(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_888(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_889(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_890(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_891(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_892(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_893(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_894(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_895(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_896(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_897(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_898(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_899(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_900(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_901(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
}
|
TODO: should increase instead
|
function approve_401(address spender, uint value) public returns (bool ok) {
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
| 6,454,114 |
// to test issue with nodes breaking with large clients over WS
// fixed in web3 with fragmentationThreshold: 8192
pragma solidity ^0.4.17;
contract BigFreakingContract {
event Transfer(address indexed from, address indexed to, uint value);
event Approval( address indexed owner, address indexed spender, uint value);
mapping( address => uint ) _balances;
mapping( address => mapping( address => uint ) ) _approvals;
uint public _supply;
constructor( uint initial_balance ) public {
_balances[msg.sender] = initial_balance;
_supply = initial_balance;
}
function totalSupply() public constant returns (uint supply) {
return _supply;
}
function balanceOf( address who ) public constant returns (uint value) {
return _balances[who];
}
function transfer( address to, uint value) public returns (bool ok) {
if( _balances[msg.sender] < value ) {
revert();
}
if( !safeToAdd(_balances[to], value) ) {
revert();
}
_balances[msg.sender] -= value;
_balances[to] += value;
emit Transfer( msg.sender, to, value );
return true;
}
function transferFrom( address from, address to, uint value) public returns (bool ok) {
// if you don't have enough balance, throw
if( _balances[from] < value ) {
revert();
}
// if you don't have approval, throw
if( _approvals[from][msg.sender] < value ) {
revert();
}
if( !safeToAdd(_balances[to], value) ) {
revert();
}
// transfer and return true
_approvals[from][msg.sender] -= value;
_balances[from] -= value;
_balances[to] += value;
emit Transfer( from, to, value );
return true;
}
function approve(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function allowance(address owner, address spender) public constant returns (uint _allowance) {
return _approvals[owner][spender];
}
function safeToAdd(uint a, uint b) internal pure returns (bool) {
return (a + b >= a);
}
function isAvailable() public pure returns (bool) {
return false;
}
function approve_1(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_2(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_3(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_4(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_5(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_6(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_7(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_8(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_9(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_10(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_11(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_12(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_13(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_14(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_15(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_16(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_17(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_18(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_19(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_20(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_21(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_22(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_23(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_24(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_25(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_26(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_27(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_28(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_29(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_30(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_31(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_32(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_33(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_34(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_35(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_36(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_37(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_38(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_39(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_40(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_41(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_42(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_43(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_44(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_45(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_46(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_47(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_48(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_49(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_50(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_51(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_52(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_53(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_54(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_55(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_56(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_57(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_58(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_59(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_60(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_61(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_62(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_63(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_64(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_65(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_66(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_67(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_68(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_69(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_70(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_71(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_72(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_73(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_74(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_75(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_76(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_77(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_78(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_79(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_80(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_81(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_82(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_83(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_84(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_85(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_86(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_87(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_88(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_89(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_90(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_91(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_92(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_93(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_94(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_95(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_96(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_97(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_98(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_99(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_100(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_101(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_102(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_103(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_104(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_105(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_106(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_107(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_108(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_109(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_110(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_111(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_112(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_113(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_114(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_115(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_116(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_117(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_118(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_119(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_120(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_121(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_122(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_123(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_124(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_125(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_126(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_127(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_128(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_129(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_130(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_131(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_132(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_133(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_134(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_135(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_136(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_137(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_138(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_139(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_140(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_141(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_142(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_143(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_144(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_145(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_146(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_147(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_148(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_149(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_150(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_151(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_152(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_153(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_154(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_155(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_156(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_157(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_158(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_159(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_160(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_161(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_162(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_163(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_164(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_165(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_166(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_167(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_168(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_169(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_170(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_171(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_172(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_173(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_174(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_175(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_176(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_177(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_178(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_179(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_180(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_181(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_182(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_183(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_184(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_185(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_186(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_187(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_188(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_189(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_190(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_191(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_192(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_193(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_194(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_195(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_196(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_197(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_198(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_199(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_200(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_201(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_202(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_203(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_204(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_205(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_206(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_207(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_208(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_209(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_210(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_211(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_212(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_213(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_214(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_215(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_216(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_217(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_218(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_219(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_220(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_221(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_222(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_223(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_224(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_225(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_226(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_227(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_228(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_229(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_230(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_231(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_232(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_233(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_234(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_235(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_236(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_237(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_238(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_239(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_240(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_241(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_242(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_243(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_244(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_245(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_246(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_247(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_248(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_249(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_250(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_251(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_252(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_253(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_254(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_255(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_256(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_257(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_258(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_259(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_260(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_261(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_262(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_263(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_264(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_265(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_266(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_267(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_268(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_269(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_270(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_271(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_272(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_273(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_274(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_275(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_276(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_277(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_278(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_279(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_280(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_281(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_282(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_283(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_284(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_285(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_286(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_287(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_288(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_289(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_290(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_291(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_292(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_293(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_294(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_295(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_296(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_297(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_298(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_299(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_300(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_301(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_302(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_303(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_304(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_305(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_306(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_307(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_308(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_309(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_310(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_311(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_312(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_313(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_314(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_315(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_316(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_317(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_318(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_319(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_320(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_321(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_322(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_323(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_324(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_325(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_326(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_327(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_328(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_329(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_330(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_331(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_332(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_333(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_334(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_335(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_336(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_337(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_338(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_339(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_340(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_341(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_342(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_343(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_344(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_345(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_346(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_347(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_348(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_349(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_350(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_351(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_352(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_353(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_354(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_355(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_356(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_357(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_358(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_359(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_360(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_361(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_362(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_363(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_364(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_365(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_366(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_367(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_368(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_369(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_370(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_371(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_372(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_373(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_374(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_375(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_376(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_377(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_378(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_379(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_380(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_381(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_382(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_383(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_384(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_385(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_386(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_387(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_388(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_389(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_390(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_391(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_392(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_393(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_394(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_395(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_396(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_397(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_398(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_399(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_400(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_401(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_402(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_403(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_404(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_405(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_406(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_407(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_408(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_409(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_410(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_411(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_412(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_413(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_414(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_415(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_416(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_417(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_418(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_419(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_420(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_421(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_422(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_423(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_424(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_425(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_426(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_427(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_428(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_429(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_430(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_431(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_432(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_433(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_434(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_435(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_436(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_437(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_438(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_439(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_440(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_441(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_442(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_443(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_444(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_445(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_446(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_447(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_448(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_449(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_450(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_451(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_452(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_453(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_454(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_455(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_456(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_457(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_458(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_459(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_460(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_461(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_462(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_463(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_464(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_465(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_466(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_467(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_468(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_469(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_470(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_471(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_472(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_473(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_474(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_475(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_476(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_477(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_478(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_479(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_480(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_481(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_482(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_483(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_484(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_485(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_486(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_487(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_488(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_489(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_490(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_491(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_492(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_493(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_494(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_495(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_496(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_497(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_498(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_499(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_500(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_501(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_502(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_503(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_504(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_505(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_506(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_507(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_508(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_509(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_510(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_511(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_512(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_513(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_514(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_515(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_516(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_517(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_518(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_519(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_520(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_521(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_522(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_523(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_524(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_525(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_526(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_527(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_528(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_529(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_530(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_531(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_532(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_533(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_534(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_535(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_536(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_537(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_538(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_539(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_540(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_541(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_542(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_543(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_544(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_545(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_546(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_547(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_548(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_549(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_550(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_551(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_552(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_553(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_554(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_555(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_556(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_557(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_558(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_559(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_560(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_561(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_562(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_563(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_564(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_565(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_566(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_567(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_568(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_569(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_570(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_571(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_572(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_573(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_574(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_575(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_576(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_577(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_578(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_579(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_580(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_581(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_582(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_583(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_584(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_585(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_586(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_587(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_588(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_589(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_590(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_591(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_592(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_593(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_594(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_595(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_596(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_597(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_598(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_599(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_600(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_601(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_602(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_603(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_604(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_605(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_606(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_607(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_608(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_609(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_610(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_611(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_612(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_613(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_614(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_615(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_616(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_617(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_618(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_619(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_620(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_621(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_622(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_623(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_624(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_625(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_626(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_627(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_628(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_629(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_630(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_631(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_632(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_633(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_634(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_635(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_636(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_637(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_638(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_639(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_640(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_641(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_642(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_643(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_644(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_645(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_646(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_647(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_648(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_649(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_650(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_651(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_652(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_653(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_654(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_655(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_656(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_657(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_658(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_659(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_660(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_661(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_662(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_663(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_664(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_665(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_666(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_667(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_668(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_669(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_670(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_671(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_672(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_673(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_674(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_675(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_676(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_677(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_678(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_679(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_680(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_681(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_682(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_683(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_684(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_685(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_686(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_687(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_688(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_689(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_690(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_691(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_692(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_693(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_694(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_695(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_696(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_697(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_698(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_699(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_700(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_701(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_702(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_703(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_704(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_705(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_706(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_707(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_708(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_709(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_710(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_711(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_712(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_713(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_714(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_715(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_716(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_717(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_718(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_719(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_720(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_721(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_722(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_723(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_724(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_725(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_726(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_727(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_728(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_729(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_730(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_731(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_732(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_733(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_734(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_735(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_736(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_737(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_738(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_739(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_740(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_741(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_742(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_743(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_744(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_745(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_746(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_747(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_748(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_749(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_750(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_751(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_752(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_753(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_754(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_755(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_756(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_757(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_758(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_759(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_760(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_761(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_762(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_763(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_764(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_765(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_766(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_767(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_768(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_769(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_770(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_771(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_772(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_773(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_774(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_775(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_776(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_777(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_778(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_779(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_780(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_781(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_782(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_783(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_784(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_785(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_786(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_787(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_788(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_789(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_790(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_791(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_792(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_793(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_794(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_795(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_796(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_797(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_798(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_799(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_800(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_801(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_802(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_803(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_804(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_805(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_806(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_807(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_808(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_809(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_810(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_811(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_812(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_813(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_814(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_815(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_816(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_817(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_818(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_819(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_820(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_821(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_822(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_823(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_824(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_825(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_826(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_827(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_828(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_829(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_830(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_831(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_832(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_833(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_834(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_835(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_836(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_837(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_838(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_839(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_840(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_841(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_842(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_843(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_844(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_845(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_846(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_847(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_848(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_849(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_850(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_851(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_852(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_853(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_854(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_855(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_856(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_857(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_858(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_859(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_860(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_861(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_862(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_863(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_864(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_865(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_866(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_867(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_868(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_869(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_870(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_871(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_872(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_873(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_874(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_875(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_876(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_877(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_878(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_879(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_880(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_881(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_882(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_883(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_884(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_885(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_886(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_887(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_888(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_889(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_890(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_891(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_892(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_893(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_894(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_895(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_896(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_897(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_898(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_899(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_900(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_901(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
}
|
TODO: should increase instead
|
function approve_209(address spender, uint value) public returns (bool ok) {
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
| 6,453,922 |
pragma solidity ^0.8.0;
import "@c-layer/common/contracts/token/TokenERC20.sol";
import "./LockableTransfer.sol";
/**
* @title LockableERC20
* @dev LockableERC20 contract
* This contract provides locking on a ERC20 token
*
* @author Cyril Lapinte - <[email protected]>
* SPDX-License-Identifier: MIT
*
* Error messages
* LE01: transfer must not be locked
*/
contract LockableERC20 is LockableTransfer, TokenERC20 {
/**
* @dev constructor
*/
constructor(
string memory _name,
string memory _symbol,
uint256 _decimals,
address _initialAccount,
uint256 _initialSupply
) TokenERC20(
_name,
_symbol,
_decimals,
_initialAccount,
_initialSupply)
{
}
/**
* @dev transferFromInternal
*/
function transferFromInternal(address _from, address _to, uint256 _value)
internal override returns (bool)
{
require(!isTransferLocked(_from, _to), "LE01");
return super.transferFromInternal(_from, _to, _value);
}
}
|
transferFromInternal/
|
function transferFromInternal(address _from, address _to, uint256 _value)
internal override returns (bool)
{
require(!isTransferLocked(_from, _to), "LE01");
return super.transferFromInternal(_from, _to, _value);
}
| 895,376 |
/**
* Token recurring billing smart contract, which enable recurring billing feature for DREAM token.
* Developed by DreamTeam.GG contributors. Visit dreamteam.gg and github.com/dreamteam-gg/smart-contracts for more info.
* Copyright © 2019 DREAMTEAM.
* Licensed under the Apache License, Version 2.0 (the "License").
*/
pragma solidity 0.5.2;
interface ERC20CompatibleToken {
function balanceOf(address tokenOwner) external view returns (uint balance);
function allowance(address tokenOwner, address spender) external view returns (uint remaining);
function transfer (address to, uint tokens) external returns (bool success);
function transferFrom (address from, address to, uint tokens) external returns (bool success);
}
/**
* Math operations with safety checks that throw on overflows.
*/
library SafeMath {
function mul (uint256 a, uint256 b) internal pure returns (uint256 c) {
if (a == 0) {
return 0;
}
c = a * b;
require(c / a == b);
return c;
}
function div (uint256 a, uint256 b) internal pure returns (uint256) {
return a / b;
}
function sub (uint256 a, uint256 b) internal pure returns (uint256) {
require(b <= a);
return a - b;
}
function add (uint256 a, uint256 b) internal pure returns (uint256 c) {
c = a + b;
require(c >= a);
return c;
}
}
/**
* Smart contract for recurring billing in ERC20-compatible tokens. This smart contract defines workflow between
* a merchant and a customer. Workflow:
* 1. Merchant registers theirselves in this smart contract using `registerNewMerchant`.
* 1.1. Merchant specifies `beneficiary` address, which receives tokens.
* 1.2. Merchant specifies `merchant` address, which is able to change `merchant` and `beneficiary` addresses.
* 1.3. Merchant specified an address that is authorized to call `charge` related to this merchant.
* 1.3.1. Later, merchant can (de)authorize another addresses to call `charge` using `changeMerchantChargingAccount`.
* 1.4. As a result, merchant gets `merchantId`, which is used to initialize recurring billing by customers.
* 1.5. Merchant account can change their `beneficiary`, `merchant` and authorized charging addresses by calling:
* 1.4.1. Function `changeMerchantAccount`, which changes account that can control this merchant (`merchantId`).
* 1.4.2. Function `changeMerchantBeneficiaryAddress`, which changes merchant's `beneficiary`.
* 1.4.3. Function `changeMerchantChargingAccount`, which (de)authorizes addresses to call `charge` on behalf of this merchant.
* 2. According to an off-chain agreement with merchant, customer calls `allowRecurringBilling` and:
* 2.1. Specifies `billingId`, which is given off-chain by merchant (merchant will listen blockchain Event on this ID).
* 2.2. Specifies `merchantId`, the merchant which will receive tokens.
* 2.3. Specifies `period` in seconds, during which only one charge can occur.
* 2.4. Specifies `value`, amount in tokens which can be charged each `period`.
* 2.4.1. If the customer doesn't have at least `value` tokens, `allowRecurringBilling` errors.
* 2.4.2. If the customer haven't approved at least `value` tokens for a smart contract, `allowRecurringBilling` errors.
* 2.5. `billingId` is then used by merchant to charge customer each `period`.
* 3. Merchant use authorized accounts (1.3) to call the `charge` function each `period` to charge agreed amount from a customer.
* 3.1. It is impossible to call `charge` if the date of the last charge is less than `period`.
* 3.2. Calling `charge` cancels billing when called after 2 `period`s from the last charge.
* 3.3. Thus, to successfully charge an account, `charge` must be strictly called within 1 and 2 `period`s after the last charge.
* 3.4. Calling `charge` errors if any of the following occur:
* 3.4.1. Customer canceled recurring billing with `cancelRecurringBilling`.
* 3.4.2. Customer's balance is lower than the chargeable amount.
* 3.4.3. Customer's allowance to the smart contract is less than the chargable amount.
* 3.4.4. Specified `billingId` does not exists.
* 3.4.5. There's no `period` passed since the last charge.
* 3.5. Next charge date increments strictly by `period` each charge, thus, there's no need to exec `charge` strictly on time.
* 4. Customer can cancel further billing by calling `cancelRecurringBilling` and passing `billingId`.
* 5. TokenRecurringBilling smart contract implements `receiveApproval` function for allowing/cancelling billing within one call from
* the token smart contract. Parameter `data` is encoded as tightly-packed (uint256 metadata, uint256 billingId).
* 5.1. `metadata` is encoded using `encodeBillingMetadata`.
* 5.2. As for `receiveApproval`, `lastChargeAt` in `metadata` is used as an action identifier.
* 5.2.1. `lastChargeAt=0` specifies that customer wants to allow new recurring billing.
* 5.2.2. `lastChargeAt=1` specifies that customer wants to cancel existing recurring billing.
* 5.3. Make sure that passed `bytes` parameter is exactly 64 bytes in length.
*/
contract TokenRecurringBilling {
using SafeMath for uint256;
event BillingAllowed(uint256 indexed billingId, address customer, uint256 merchantId, uint256 timestamp, uint256 period, uint256 value);
event BillingCharged(uint256 indexed billingId, uint256 timestamp, uint256 nextChargeTimestamp);
event BillingCanceled(uint256 indexed billingId);
event MerchantRegistered(uint256 indexed merchantId, address merchantAccount, address beneficiaryAddress);
event MerchantAccountChanged(uint256 indexed merchantId, address merchantAccount);
event MerchantBeneficiaryAddressChanged(uint256 indexed merchantId, address beneficiaryAddress);
event MerchantChargingAccountAllowed(uint256 indexed merchantId, address chargingAccount, bool allowed);
struct BillingRecord {
address customer; // Billing address (those who pay).
uint256 metadata; // Metadata packs 5 values to save on storage. Metadata spec (from first to last byte):
// + uint32 period; // Billing period in seconds; configurable period of up to 136 years.
// + uint32 merchantId; // Merchant ID; up to ~4.2 Milliard IDs.
// + uint48 lastChargeAt; // When the last charge occurred; up to year 999999+.
// + uint144 value; // Billing value charrged each period; up to ~22 septillion tokens with 18 decimals
}
struct Merchant {
address merchant; // Merchant admin address that can change all merchant struct properties.
address beneficiary; // Address receiving tokens.
}
enum receiveApprovalAction { // In receiveApproval, `lastChargeAt` in passed `metadata` specifies an action to execute.
allowRecurringBilling, // == 0
cancelRecurringBilling // == 1
}
uint256 public lastMerchantId; // This variable increments on each new merchant registered, generating unique ids for merchant.
ERC20CompatibleToken public token; // Token address.
mapping(uint256 => BillingRecord) public billingRegistry; // List of all billings registered by ID.
mapping(uint256 => Merchant) public merchantRegistry; // List of all merchants registered by ID.
mapping(uint256 => mapping(address => bool)) public merchantChargingAccountAllowed; // Accounts that are allowed to charge customers.
// Checks whether {merchant} owns {merchantId}
modifier isMerchant (uint256 merchantId) {
require(merchantRegistry[merchantId].merchant == msg.sender, "Sender is not a merchant");
_;
}
// Checks whether {customer} owns {billingId}
modifier isCustomer (uint256 billingId) {
require(billingRegistry[billingId].customer == msg.sender, "Sender is not a customer");
_;
}
// Guarantees that the transaction is sent by token smart contract only.
modifier tokenOnly () {
require(msg.sender == address(token), "Sender is not a token");
_;
}
/// ======================================================== Constructor ========================================================= \\\
// Creates a recurring billing smart contract for particular token.
constructor (address tokenAddress) public {
token = ERC20CompatibleToken(tokenAddress);
}
/// ====================================================== Public Functions ====================================================== \\\
// Enables merchant with {merchantId} to charge transaction signer's account according to specified {value} and {period}.
function allowRecurringBilling (uint256 billingId, uint256 merchantId, uint256 value, uint256 period) public {
allowRecurringBillingInternal(msg.sender, merchantId, billingId, value, period);
}
// Enables anyone to become a merchant, charging tokens for their services.
function registerNewMerchant (address beneficiary, address chargingAccount) public returns (uint256 merchantId) {
merchantId = ++lastMerchantId;
Merchant storage record = merchantRegistry[merchantId];
record.merchant = msg.sender;
record.beneficiary = beneficiary;
emit MerchantRegistered(merchantId, msg.sender, beneficiary);
changeMerchantChargingAccount(merchantId, chargingAccount, true);
}
/// =========================================== Public Functions with Restricted Access =========================================== \\\
// Calcels recurring billing with id {billingId} if it is owned by a transaction signer.
function cancelRecurringBilling (uint256 billingId) public isCustomer(billingId) {
cancelRecurringBillingInternal(billingId);
}
// Charges customer's account according to defined {billingId} billing rules. Only merchant's authorized accounts can charge the customer.
function charge (uint256 billingId) public {
BillingRecord storage billingRecord = billingRegistry[billingId];
(uint256 value, uint256 lastChargeAt, uint256 merchantId, uint256 period) = decodeBillingMetadata(billingRecord.metadata);
require(merchantChargingAccountAllowed[merchantId][msg.sender], "Sender is not allowed to charge");
require(merchantId != 0, "Billing does not exist");
require(lastChargeAt.add(period) <= now, "Charged too early");
// If 2 periods have already passed since the last charge (or beginning), no further charges are possible
// and recurring billing is canceled in case of a charge.
if (now > lastChargeAt.add(period.mul(2))) {
cancelRecurringBillingInternal(billingId);
return;
}
require(
token.transferFrom(billingRecord.customer, merchantRegistry[merchantId].beneficiary, value),
"Unable to charge customer"
);
billingRecord.metadata = encodeBillingMetadata(value, lastChargeAt.add(period), merchantId, period);
emit BillingCharged(billingId, now, lastChargeAt.add(period.mul(2)));
}
/**
* Invoked by a token smart contract on approveAndCall. Allows or cancels recurring billing.
* @param sender - Address that approved some tokens for this smart contract.
* @param data - Tightly-packed (uint256,uint256) values of (metadata, billingId). Metadata's `lastChargeAt`
* specifies an action to perform (see `receiveApprovalAction` enum).
*/
function receiveApproval (address sender, uint, address, bytes calldata data) external tokenOnly {
// The token contract MUST guarantee that "sender" is actually the token owner, and metadata is signed by a token owner.
require(data.length == 64, "Invalid data length");
// `action` is used instead of `lastCahrgeAt` to save some space.
(uint256 value, uint256 action, uint256 merchantId, uint256 period) = decodeBillingMetadata(bytesToUint256(data, 0));
uint256 billingId = bytesToUint256(data, 32);
if (action == uint256(receiveApprovalAction.allowRecurringBilling)) {
allowRecurringBillingInternal(sender, merchantId, billingId, value, period);
} else if (action == uint256(receiveApprovalAction.cancelRecurringBilling)) {
require(billingRegistry[billingId].customer == sender, "Unable to cancel recurring billing of another customer");
cancelRecurringBillingInternal(billingId);
} else {
revert("Unknown action provided");
}
}
// Changes merchant account with id {merchantId} to {newMerchantAccount}.
function changeMerchantAccount (uint256 merchantId, address newMerchantAccount) public isMerchant(merchantId) {
merchantRegistry[merchantId].merchant = newMerchantAccount;
emit MerchantAccountChanged(merchantId, newMerchantAccount);
}
// Changes merchant's beneficiary address (address that receives charged tokens) to {newBeneficiaryAddress}.
function changeMerchantBeneficiaryAddress (uint256 merchantId, address newBeneficiaryAddress) public isMerchant(merchantId) {
merchantRegistry[merchantId].beneficiary = newBeneficiaryAddress;
emit MerchantBeneficiaryAddressChanged(merchantId, newBeneficiaryAddress);
}
// Allows or disallows particular {account} to charge customers related to this merchant.
function changeMerchantChargingAccount (uint256 merchantId, address account, bool allowed) public isMerchant(merchantId) {
merchantChargingAccountAllowed[merchantId][account] = allowed;
emit MerchantChargingAccountAllowed(merchantId, account, allowed);
}
/// ================================================== Public Utility Functions ================================================== \\\
// Used to encode 5 values into one uint256 value. This is primarily made for cheaper storage.
function encodeBillingMetadata (
uint256 value,
uint256 lastChargeAt,
uint256 merchantId,
uint256 period
) public pure returns (uint256 result) {
require(
value < 2 ** 144
&& lastChargeAt < 2 ** 48
&& merchantId < 2 ** 32
&& period < 2 ** 32,
"Invalid input sizes to encode"
);
result = value;
result |= lastChargeAt << (144);
result |= merchantId << (144 + 48);
result |= period << (144 + 48 + 32);
return result;
}
// Used to decode 5 values from one uint256 value encoded by `encodeBillingMetadata` function.
function decodeBillingMetadata (uint256 encodedData) public pure returns (
uint256 value,
uint256 lastChargeAt,
uint256 merchantId,
uint256 period
) {
value = uint144(encodedData);
lastChargeAt = uint48(encodedData >> (144));
merchantId = uint32(encodedData >> (144 + 48));
period = uint32(encodedData >> (144 + 48 + 32));
}
/// ================================================ Internal (Private) Functions ================================================ \\\
// Allows recurring billing. Noone but this contract can call this function.
function allowRecurringBillingInternal (
address customer,
uint256 merchantId,
uint256 billingId,
uint256 value,
uint256 period
) internal {
require(merchantId <= lastMerchantId && merchantId != 0, "Invalid merchant specified");
require(period < now, "Invalid period specified");
require(token.balanceOf(customer) >= value, "Not enough tokens for the first charge");
require(token.allowance(customer, address(this)) >= value, "Tokens are not approved for this smart contract");
require(billingRegistry[billingId].customer == address(0x0), "Recurring billing with this ID is already registered");
BillingRecord storage newRecurringBilling = billingRegistry[billingId];
newRecurringBilling.metadata = encodeBillingMetadata(value, now.sub(period), merchantId, period);
newRecurringBilling.customer = customer;
emit BillingAllowed(billingId, customer, merchantId, now, period, value);
}
// Cancels recurring billing. Noone but this contract can call this function.
function cancelRecurringBillingInternal (uint256 billingId) internal {
delete billingRegistry[billingId];
emit BillingCanceled(billingId);
}
// Utility function to convert bytes type to uint256. Noone but this contract can call this function.
function bytesToUint256(bytes memory input, uint offset) internal pure returns (uint256 output) {
assembly { output := mload(add(add(input, 32), offset)) }
}
}
|
Allows or disallows particular {account} to charge customers related to this merchant.
|
function changeMerchantChargingAccount (uint256 merchantId, address account, bool allowed) public isMerchant(merchantId) {
merchantChargingAccountAllowed[merchantId][account] = allowed;
emit MerchantChargingAccountAllowed(merchantId, account, allowed);
}
| 11,861,005 |
./partial_match/3/0x74ba3C428d8D283Cc1631F678f8dAF1fbBb7Df33/sources/MasterChef.sol
|
change the TPB(tokensPerBlock)
|
function changetokensPerBlock(uint256 _newtokensPerBlock) public onlyOwner {
cropsPerBlock = _newtokensPerBlock;
}
| 5,077,290 |
// Flattener_Cratos_Jay
// File: @chainlink/contracts/src/v0.8/interfaces/KeeperCompatibleInterface.sol
pragma solidity ^0.8.0;
interface KeeperCompatibleInterface {
/**
* @notice method that is simulated by the keepers to see if any work actually
* needs to be performed. This method does does not actually need to be
* executable, and since it is only ever simulated it can consume lots of gas.
* @dev To ensure that it is never called, you may want to add the
* cannotExecute modifier from KeeperBase to your implementation of this
* method.
* @param checkData specified in the upkeep registration so it is always the
* same for a registered upkeep. This can easily be broken down into specific
* arguments using `abi.decode`, so multiple upkeeps can be registered on the
* same contract and easily differentiated by the contract.
* @return upkeepNeeded boolean to indicate whether the keeper should call
* performUpkeep or not.
* @return performData bytes that the keeper should call performUpkeep with, if
* upkeep is needed. If you would like to encode data to decode later, try
* `abi.encode`.
*/
function checkUpkeep(bytes calldata checkData) external returns (bool upkeepNeeded, bytes memory performData);
/**
* @notice method that is actually executed by the keepers, via the registry.
* The data returned by the checkUpkeep simulation will be passed into
* this method to actually be executed.
* @dev The input to this method should not be trusted, and the caller of the
* method should not even be restricted to any single registry. Anyone should
* be able call it, and the input should be validated, there is no guarantee
* that the data passed in is the performData returned from checkUpkeep. This
* could happen due to malicious keepers, racing keepers, or simply a state
* change while the performUpkeep transaction is waiting for confirmation.
* Always validate the data passed in.
* @param performData is the data which was passed back from the checkData
* simulation. If it is encoded, it can easily be decoded into other types by
* calling `abi.decode`. This data should not be trusted, and should be
* validated against the contract's current state.
*/
function performUpkeep(bytes calldata performData) external;
}
// File: @chainlink/contracts/src/v0.8/KeeperBase.sol
pragma solidity ^0.8.0;
contract KeeperBase {
error OnlySimulatedBackend();
/**
* @notice method that allows it to be simulated via eth_call by checking that
* the sender is the zero address.
*/
function preventExecution() internal view {
if (tx.origin != address(0)) {
revert OnlySimulatedBackend();
}
}
/**
* @notice modifier that allows it to be simulated via eth_call by checking
* that the sender is the zero address.
*/
modifier cannotExecute() {
preventExecution();
_;
}
}
// File: @chainlink/contracts/src/v0.8/KeeperCompatible.sol
pragma solidity ^0.8.0;
abstract contract KeeperCompatible is KeeperBase, KeeperCompatibleInterface {}
// File: @openzeppelin/contracts/utils/math/SafeMath.sol
// OpenZeppelin Contracts v4.4.1 (utils/math/SafeMath.sol)
pragma solidity ^0.8.0;
// CAUTION
// This version of SafeMath should only be used with Solidity 0.8 or later,
// because it relies on the compiler's built in overflow checks.
/**
* @dev Wrappers over Solidity's arithmetic operations.
*
* NOTE: `SafeMath` is generally not needed starting with Solidity 0.8, since the compiler
* now has built in overflow checking.
*/
library SafeMath {
/**
* @dev Returns the addition of two unsigned integers, with an overflow flag.
*
* _Available since v3.4._
*/
function tryAdd(uint256 a, uint256 b) internal pure returns (bool, uint256) {
unchecked {
uint256 c = a + b;
if (c < a) return (false, 0);
return (true, c);
}
}
/**
* @dev Returns the substraction of two unsigned integers, with an overflow flag.
*
* _Available since v3.4._
*/
function trySub(uint256 a, uint256 b) internal pure returns (bool, uint256) {
unchecked {
if (b > a) return (false, 0);
return (true, a - b);
}
}
/**
* @dev Returns the multiplication of two unsigned integers, with an overflow flag.
*
* _Available since v3.4._
*/
function tryMul(uint256 a, uint256 b) internal pure returns (bool, uint256) {
unchecked {
// Gas optimization: this is cheaper than requiring 'a' not being zero, but the
// benefit is lost if 'b' is also tested.
// See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522
if (a == 0) return (true, 0);
uint256 c = a * b;
if (c / a != b) return (false, 0);
return (true, c);
}
}
/**
* @dev Returns the division of two unsigned integers, with a division by zero flag.
*
* _Available since v3.4._
*/
function tryDiv(uint256 a, uint256 b) internal pure returns (bool, uint256) {
unchecked {
if (b == 0) return (false, 0);
return (true, a / b);
}
}
/**
* @dev Returns the remainder of dividing two unsigned integers, with a division by zero flag.
*
* _Available since v3.4._
*/
function tryMod(uint256 a, uint256 b) internal pure returns (bool, uint256) {
unchecked {
if (b == 0) return (false, 0);
return (true, a % b);
}
}
/**
* @dev Returns the addition of two unsigned integers, reverting on
* overflow.
*
* Counterpart to Solidity's `+` operator.
*
* Requirements:
*
* - Addition cannot overflow.
*/
function add(uint256 a, uint256 b) internal pure returns (uint256) {
return a + b;
}
/**
* @dev Returns the subtraction of two unsigned integers, reverting on
* overflow (when the result is negative).
*
* Counterpart to Solidity's `-` operator.
*
* Requirements:
*
* - Subtraction cannot overflow.
*/
function sub(uint256 a, uint256 b) internal pure returns (uint256) {
return a - b;
}
/**
* @dev Returns the multiplication of two unsigned integers, reverting on
* overflow.
*
* Counterpart to Solidity's `*` operator.
*
* Requirements:
*
* - Multiplication cannot overflow.
*/
function mul(uint256 a, uint256 b) internal pure returns (uint256) {
return a * b;
}
/**
* @dev Returns the integer division of two unsigned integers, reverting on
* division by zero. The result is rounded towards zero.
*
* Counterpart to Solidity's `/` operator.
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function div(uint256 a, uint256 b) internal pure returns (uint256) {
return a / b;
}
/**
* @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo),
* reverting when dividing by zero.
*
* Counterpart to Solidity's `%` operator. This function uses a `revert`
* opcode (which leaves remaining gas untouched) while Solidity uses an
* invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function mod(uint256 a, uint256 b) internal pure returns (uint256) {
return a % b;
}
/**
* @dev Returns the subtraction of two unsigned integers, reverting with custom message on
* overflow (when the result is negative).
*
* CAUTION: This function is deprecated because it requires allocating memory for the error
* message unnecessarily. For custom revert reasons use {trySub}.
*
* Counterpart to Solidity's `-` operator.
*
* Requirements:
*
* - Subtraction cannot overflow.
*/
function sub(
uint256 a,
uint256 b,
string memory errorMessage
) internal pure returns (uint256) {
unchecked {
require(b <= a, errorMessage);
return a - b;
}
}
/**
* @dev Returns the integer division of two unsigned integers, reverting with custom message on
* division by zero. The result is rounded towards zero.
*
* Counterpart to Solidity's `/` operator. Note: this function uses a
* `revert` opcode (which leaves remaining gas untouched) while Solidity
* uses an invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function div(
uint256 a,
uint256 b,
string memory errorMessage
) internal pure returns (uint256) {
unchecked {
require(b > 0, errorMessage);
return a / b;
}
}
/**
* @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo),
* reverting with custom message when dividing by zero.
*
* CAUTION: This function is deprecated because it requires allocating memory for the error
* message unnecessarily. For custom revert reasons use {tryMod}.
*
* Counterpart to Solidity's `%` operator. This function uses a `revert`
* opcode (which leaves remaining gas untouched) while Solidity uses an
* invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function mod(
uint256 a,
uint256 b,
string memory errorMessage
) internal pure returns (uint256) {
unchecked {
require(b > 0, errorMessage);
return a % b;
}
}
}
// File: @openzeppelin/contracts/utils/math/Math.sol
// OpenZeppelin Contracts (last updated v4.5.0) (utils/math/Math.sol)
pragma solidity ^0.8.0;
/**
* @dev Standard math utilities missing in the Solidity language.
*/
library Math {
/**
* @dev Returns the largest of two numbers.
*/
function max(uint256 a, uint256 b) internal pure returns (uint256) {
return a >= b ? a : b;
}
/**
* @dev Returns the smallest of two numbers.
*/
function min(uint256 a, uint256 b) internal pure returns (uint256) {
return a < b ? a : b;
}
/**
* @dev Returns the average of two numbers. The result is rounded towards
* zero.
*/
function average(uint256 a, uint256 b) internal pure returns (uint256) {
// (a + b) / 2 can overflow.
return (a & b) + (a ^ b) / 2;
}
/**
* @dev Returns the ceiling of the division of two numbers.
*
* This differs from standard division with `/` in that it rounds up instead
* of rounding down.
*/
function ceilDiv(uint256 a, uint256 b) internal pure returns (uint256) {
// (a + b - 1) / b can overflow on addition, so we distribute.
return a / b + (a % b == 0 ? 0 : 1);
}
}
// File: @openzeppelin/contracts/utils/Context.sol
// OpenZeppelin Contracts v4.4.1 (utils/Context.sol)
pragma solidity ^0.8.0;
/**
* @dev Provides information about the current execution context, including the
* sender of the transaction and its data. While these are generally available
* via msg.sender and msg.data, they should not be accessed in such a direct
* manner, since when dealing with meta-transactions the account sending and
* paying for execution may not be the actual sender (as far as an application
* is concerned).
*
* This contract is only required for intermediate, library-like contracts.
*/
abstract contract Context {
function _msgSender() internal view virtual returns (address) {
return msg.sender;
}
function _msgData() internal view virtual returns (bytes calldata) {
return msg.data;
}
}
// File: @openzeppelin/contracts/access/Ownable.sol
// OpenZeppelin Contracts v4.4.1 (access/Ownable.sol)
pragma solidity ^0.8.0;
/**
* @dev Contract module which provides a basic access control mechanism, where
* there is an account (an owner) that can be granted exclusive access to
* specific functions.
*
* By default, the owner account will be the one that deploys the contract. This
* can later be changed with {transferOwnership}.
*
* This module is used through inheritance. It will make available the modifier
* `onlyOwner`, which can be applied to your functions to restrict their use to
* the owner.
*/
abstract contract Ownable is Context {
address private _owner;
event OwnershipTransferred(address indexed previousOwner, address indexed newOwner);
/**
* @dev Initializes the contract setting the deployer as the initial owner.
*/
constructor() {
_transferOwnership(_msgSender());
}
/**
* @dev Returns the address of the current owner.
*/
function owner() public view virtual returns (address) {
return _owner;
}
/**
* @dev Throws if called by any account other than the owner.
*/
modifier onlyOwner() {
require(owner() == _msgSender(), "Ownable: caller is not the owner");
_;
}
/**
* @dev Leaves the contract without owner. It will not be possible to call
* `onlyOwner` functions anymore. Can only be called by the current owner.
*
* NOTE: Renouncing ownership will leave the contract without an owner,
* thereby removing any functionality that is only available to the owner.
*/
function renounceOwnership() public virtual onlyOwner {
_transferOwnership(address(0));
}
/**
* @dev Transfers ownership of the contract to a new account (`newOwner`).
* Can only be called by the current owner.
*/
function transferOwnership(address newOwner) public virtual onlyOwner {
require(newOwner != address(0), "Ownable: new owner is the zero address");
_transferOwnership(newOwner);
}
/**
* @dev Transfers ownership of the contract to a new account (`newOwner`).
* Internal function without access restriction.
*/
function _transferOwnership(address newOwner) internal virtual {
address oldOwner = _owner;
_owner = newOwner;
emit OwnershipTransferred(oldOwner, newOwner);
}
}
// File: @openzeppelin/contracts/security/ReentrancyGuard.sol
// OpenZeppelin Contracts v4.4.1 (security/ReentrancyGuard.sol)
pragma solidity ^0.8.0;
/**
* @dev Contract module that helps prevent reentrant calls to a function.
*
* Inheriting from `ReentrancyGuard` will make the {nonReentrant} modifier
* available, which can be applied to functions to make sure there are no nested
* (reentrant) calls to them.
*
* Note that because there is a single `nonReentrant` guard, functions marked as
* `nonReentrant` may not call one another. This can be worked around by making
* those functions `private`, and then adding `external` `nonReentrant` entry
* points to them.
*
* TIP: If you would like to learn more about reentrancy and alternative ways
* to protect against it, check out our blog post
* https://blog.openzeppelin.com/reentrancy-after-istanbul/[Reentrancy After Istanbul].
*/
abstract contract ReentrancyGuard {
// Booleans are more expensive than uint256 or any type that takes up a full
// word because each write operation emits an extra SLOAD to first read the
// slot's contents, replace the bits taken up by the boolean, and then write
// back. This is the compiler's defense against contract upgrades and
// pointer aliasing, and it cannot be disabled.
// The values being non-zero value makes deployment a bit more expensive,
// but in exchange the refund on every call to nonReentrant will be lower in
// amount. Since refunds are capped to a percentage of the total
// transaction's gas, it is best to keep them low in cases like this one, to
// increase the likelihood of the full refund coming into effect.
uint256 private constant _NOT_ENTERED = 1;
uint256 private constant _ENTERED = 2;
uint256 private _status;
constructor() {
_status = _NOT_ENTERED;
}
/**
* @dev Prevents a contract from calling itself, directly or indirectly.
* Calling a `nonReentrant` function from another `nonReentrant`
* function is not supported. It is possible to prevent this from happening
* by making the `nonReentrant` function external, and making it call a
* `private` function that does the actual work.
*/
modifier nonReentrant() {
// On the first call to nonReentrant, _notEntered will be true
require(_status != _ENTERED, "ReentrancyGuard: reentrant call");
// Any calls to nonReentrant after this point will fail
_status = _ENTERED;
_;
// By storing the original value once again, a refund is triggered (see
// https://eips.ethereum.org/EIPS/eip-2200)
_status = _NOT_ENTERED;
}
}
// File: @openzeppelin/contracts/utils/Address.sol
// OpenZeppelin Contracts (last updated v4.5.0) (utils/Address.sol)
pragma solidity ^0.8.1;
/**
* @dev Collection of functions related to the address type
*/
library Address {
/**
* @dev Returns true if `account` is a contract.
*
* [IMPORTANT]
* ====
* It is unsafe to assume that an address for which this function returns
* false is an externally-owned account (EOA) and not a contract.
*
* Among others, `isContract` will return false for the following
* types of addresses:
*
* - an externally-owned account
* - a contract in construction
* - an address where a contract will be created
* - an address where a contract lived, but was destroyed
* ====
*
* [IMPORTANT]
* ====
* You shouldn't rely on `isContract` to protect against flash loan attacks!
*
* Preventing calls from contracts is highly discouraged. It breaks composability, breaks support for smart wallets
* like Gnosis Safe, and does not provide security since it can be circumvented by calling from a contract
* constructor.
* ====
*/
function isContract(address account) internal view returns (bool) {
// This method relies on extcodesize/address.code.length, which returns 0
// for contracts in construction, since the code is only stored at the end
// of the constructor execution.
return account.code.length > 0;
}
/**
* @dev Replacement for Solidity's `transfer`: sends `amount` wei to
* `recipient`, forwarding all available gas and reverting on errors.
*
* https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost
* of certain opcodes, possibly making contracts go over the 2300 gas limit
* imposed by `transfer`, making them unable to receive funds via
* `transfer`. {sendValue} removes this limitation.
*
* https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more].
*
* IMPORTANT: because control is transferred to `recipient`, care must be
* taken to not create reentrancy vulnerabilities. Consider using
* {ReentrancyGuard} or the
* https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern].
*/
function sendValue(address payable recipient, uint256 amount) internal {
require(address(this).balance >= amount, "Address: insufficient balance");
(bool success, ) = recipient.call{value: amount}("");
require(success, "Address: unable to send value, recipient may have reverted");
}
/**
* @dev Performs a Solidity function call using a low level `call`. A
* plain `call` is an unsafe replacement for a function call: use this
* function instead.
*
* If `target` reverts with a revert reason, it is bubbled up by this
* function (like regular Solidity function calls).
*
* Returns the raw returned data. To convert to the expected return value,
* use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`].
*
* 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");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with
* `errorMessage` as a fallback revert reason when `target` reverts.
*
* _Available since v3.1._
*/
function functionCall(
address target,
bytes memory data,
string memory errorMessage
) internal returns (bytes memory) {
return functionCallWithValue(target, data, 0, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but also transferring `value` wei to `target`.
*
* Requirements:
*
* - the calling contract must have an ETH balance of at least `value`.
* - the called Solidity function must be `payable`.
*
* _Available since v3.1._
*/
function functionCallWithValue(
address target,
bytes memory data,
uint256 value
) internal returns (bytes memory) {
return functionCallWithValue(target, data, value, "Address: low-level call with value failed");
}
/**
* @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but
* with `errorMessage` as a fallback revert reason when `target` reverts.
*
* _Available since v3.1._
*/
function functionCallWithValue(
address target,
bytes memory data,
uint256 value,
string memory errorMessage
) internal returns (bytes memory) {
require(address(this).balance >= value, "Address: insufficient balance for call");
require(isContract(target), "Address: call to non-contract");
(bool success, bytes memory returndata) = target.call{value: value}(data);
return verifyCallResult(success, returndata, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but performing a static call.
*
* _Available since v3.3._
*/
function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) {
return functionStaticCall(target, data, "Address: low-level static call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`],
* but performing a static call.
*
* _Available since v3.3._
*/
function functionStaticCall(
address target,
bytes memory data,
string memory errorMessage
) internal view returns (bytes memory) {
require(isContract(target), "Address: static call to non-contract");
(bool success, bytes memory returndata) = target.staticcall(data);
return verifyCallResult(success, returndata, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but performing a delegate call.
*
* _Available since v3.4._
*/
function functionDelegateCall(address target, bytes memory data) internal returns (bytes memory) {
return functionDelegateCall(target, data, "Address: low-level delegate call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`],
* but performing a delegate call.
*
* _Available since v3.4._
*/
function functionDelegateCall(
address target,
bytes memory data,
string memory errorMessage
) internal returns (bytes memory) {
require(isContract(target), "Address: delegate call to non-contract");
(bool success, bytes memory returndata) = target.delegatecall(data);
return verifyCallResult(success, returndata, errorMessage);
}
/**
* @dev Tool to verifies that a low level call was successful, and revert if it wasn't, either by bubbling the
* revert reason using the provided one.
*
* _Available since v4.3._
*/
function verifyCallResult(
bool success,
bytes memory returndata,
string memory errorMessage
) internal pure returns (bytes memory) {
if (success) {
return returndata;
} else {
// Look for revert reason and bubble it up if present
if (returndata.length > 0) {
// The easiest way to bubble the revert reason is using memory via assembly
assembly {
let returndata_size := mload(returndata)
revert(add(32, returndata), returndata_size)
}
} else {
revert(errorMessage);
}
}
}
}
// File: @openzeppelin/contracts/token/ERC20/IERC20.sol
// OpenZeppelin Contracts (last updated v4.5.0) (token/ERC20/IERC20.sol)
pragma solidity ^0.8.0;
/**
* @dev Interface of the ERC20 standard as defined in the EIP.
*/
interface IERC20 {
/**
* @dev Returns the amount of tokens in existence.
*/
function totalSupply() external view returns (uint256);
/**
* @dev Returns the amount of tokens owned by `account`.
*/
function balanceOf(address account) external view returns (uint256);
/**
* @dev Moves `amount` tokens from the caller's account to `to`.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/
function transfer(address to, uint256 amount) external returns (bool);
/**
* @dev Returns the remaining number of tokens that `spender` will be
* allowed to spend on behalf of `owner` through {transferFrom}. This is
* zero by default.
*
* This value changes when {approve} or {transferFrom} are called.
*/
function allowance(address owner, address spender) external view returns (uint256);
/**
* @dev Sets `amount` as the allowance of `spender` over the caller's tokens.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* IMPORTANT: 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
*
* Emits an {Approval} event.
*/
function approve(address spender, uint256 amount) external returns (bool);
/**
* @dev Moves `amount` tokens from `from` to `to` using the
* allowance mechanism. `amount` is then deducted from the caller's
* allowance.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/
function transferFrom(
address from,
address to,
uint256 amount
) external returns (bool);
/**
* @dev Emitted when `value` tokens are moved from one account (`from`) to
* another (`to`).
*
* Note that `value` may be zero.
*/
event Transfer(address indexed from, address indexed to, uint256 value);
/**
* @dev Emitted when the allowance of a `spender` for an `owner` is set by
* a call to {approve}. `value` is the new allowance.
*/
event Approval(address indexed owner, address indexed spender, uint256 value);
}
// File: @openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol
// OpenZeppelin Contracts v4.4.1 (token/ERC20/utils/SafeERC20.sol)
pragma solidity ^0.8.0;
/**
* @title SafeERC20
* @dev Wrappers around ERC20 operations that throw on failure (when the token
* contract returns false). Tokens that return no value (and instead revert or
* throw on failure) are also supported, non-reverting calls are assumed to be
* successful.
* To use this library you can add a `using SafeERC20 for IERC20;` statement to your contract,
* which allows you to call the safe operations as `token.safeTransfer(...)`, etc.
*/
library SafeERC20 {
using Address for address;
function safeTransfer(
IERC20 token,
address to,
uint256 value
) internal {
_callOptionalReturn(token, abi.encodeWithSelector(token.transfer.selector, to, value));
}
function safeTransferFrom(
IERC20 token,
address from,
address to,
uint256 value
) internal {
_callOptionalReturn(token, abi.encodeWithSelector(token.transferFrom.selector, from, to, value));
}
/**
* @dev Deprecated. This function has issues similar to the ones found in
* {IERC20-approve}, and its usage is discouraged.
*
* Whenever possible, use {safeIncreaseAllowance} and
* {safeDecreaseAllowance} instead.
*/
function safeApprove(
IERC20 token,
address spender,
uint256 value
) internal {
// safeApprove should only be called when setting an initial allowance,
// or when resetting it to zero. To increase and decrease it, use
// 'safeIncreaseAllowance' and 'safeDecreaseAllowance'
require(
(value == 0) || (token.allowance(address(this), spender) == 0),
"SafeERC20: approve from non-zero to non-zero allowance"
);
_callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, value));
}
function safeIncreaseAllowance(
IERC20 token,
address spender,
uint256 value
) internal {
uint256 newAllowance = token.allowance(address(this), spender) + value;
_callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance));
}
function safeDecreaseAllowance(
IERC20 token,
address spender,
uint256 value
) internal {
unchecked {
uint256 oldAllowance = token.allowance(address(this), spender);
require(oldAllowance >= value, "SafeERC20: decreased allowance below zero");
uint256 newAllowance = oldAllowance - value;
_callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance));
}
}
/**
* @dev Imitates a Solidity high-level call (i.e. a regular function call to a contract), relaxing the requirement
* on the return value: the return value is optional (but if data is returned, it must not be false).
* @param token The token targeted by the call.
* @param data The call data (encoded using abi.encode or one of its variants).
*/
function _callOptionalReturn(IERC20 token, bytes memory data) private {
// We need to perform a low level call here, to bypass Solidity's return data size checking mechanism, since
// we're implementing it ourselves. We use {Address.functionCall} to perform this call, which verifies that
// the target address contains contract code and also asserts for success in the low-level call.
bytes memory returndata = address(token).functionCall(data, "SafeERC20: low-level call failed");
if (returndata.length > 0) {
// Return data is optional
require(abi.decode(returndata, (bool)), "SafeERC20: ERC20 operation did not succeed");
}
}
}
// File: 3_Chainlink_Test/00.CRTS_Automation_Vesting_Keepers.sol
// contracts/TokenVesting.sol
pragma solidity 0.8.11;
/**
* @title TokenVesting
*/
contract CRTS_Token_Vesting is Ownable, ReentrancyGuard, KeeperCompatibleInterface{
using SafeMath for uint256;
using SafeERC20 for IERC20;
struct VestingSchedule{
bool initialized;
// beneficiary of tokens after they are released
address beneficiary;
// cliff period in seconds
uint256 cliff;
// start time of the vesting period
uint256 start;
// duration of the vesting period in seconds
uint256 duration;
// duration of a slice period for the vesting in seconds
uint256 slicePeriodSeconds;
// whether or not the vesting is revocable
bool revocable;
// total amount of tokens to be released at the end of the vesting
uint256 amountTotal;
// amount of tokens released
uint256 released;
// whether or not the vesting has been revoked
bool revoked;
}
// address of the ERC20 token
IERC20 immutable private _token;
bytes32[] private vestingSchedulesIds;
mapping(bytes32 => VestingSchedule) private vestingSchedules;
uint256 private vestingSchedulesTotalAmount;
mapping(address => uint256) private holdersVestingCount;
uint256 keeperInterval;
uint256 keeperLastUpdatedTime;
event Released(uint256 amount);
event Revoked();
/**
* @dev Reverts if no vesting schedule matches the passed identifier.
*/
modifier onlyIfVestingScheduleExists(bytes32 vestingScheduleId) {
require(vestingSchedules[vestingScheduleId].initialized == true);
_;
}
/**
* @dev Reverts if the vesting schedule does not exist or has been revoked.
*/
modifier onlyIfVestingScheduleNotRevoked(bytes32 vestingScheduleId) {
require(vestingSchedules[vestingScheduleId].initialized == true);
require(vestingSchedules[vestingScheduleId].revoked == false);
_;
}
/**
* @dev Creates a vesting contract.
* @param token_ address of the ERC20 token contract
*/
constructor(address token_) {
require(token_ != address(0x0));
_token = IERC20(token_);
keeperLastUpdatedTime = block.timestamp;
keeperInterval = 2592000; // 30 days GG_CO
}
receive() external payable {}
fallback() external payable {}
/**
* @dev Returns the number of vesting schedules associated to a beneficiary.
* @return the number of vesting schedules
*/
function getVestingSchedulesCountByBeneficiary(address _beneficiary)
external
view
returns(uint256){
return holdersVestingCount[_beneficiary];
}
/**
* @dev Returns the vesting schedule id at the given index.
* @return the vesting id
*/
function getVestingIdAtIndex(uint256 index)
external
view
returns(bytes32){
require(index < getVestingSchedulesCount(), "TokenVesting: index out of bounds");
return vestingSchedulesIds[index];
}
/**
* @notice Returns the vesting schedule information for a given holder and index.
* @return the vesting schedule structure information
*/
function getVestingScheduleByAddressAndIndex(address holder, uint256 index)
external
view
returns(VestingSchedule memory){
return getVestingSchedule(computeVestingScheduleIdForAddressAndIndex(holder, index));
}
/**
* @notice Returns the total amount of vesting schedules.
* @return the total amount of vesting schedules
*/
function getVestingSchedulesTotalAmount()
external
view
returns(uint256){
return vestingSchedulesTotalAmount;
}
/**
* @dev Returns the address of the ERC20 token managed by the vesting contract.
*/
function getToken()
external
view
returns(address){
return address(_token);
}
function addUserDetails(
address[] memory _to,
uint256[] memory _amount,
uint256 _start,
uint256 _cliff,
uint256 _duration,
uint256 _slicePeriodSeconds
) public onlyOwner returns (bool) {
require(_to.length == _amount.length, "Invalid data");
uint256 tokens;
for (uint256 i = 0; i < _to.length; i++) {
require(_to[i] != address(0), "Invalid address");
createVestingSchedule(_to[i],_start,_cliff,_duration, _slicePeriodSeconds,true,_amount[i]);
tokens = tokens.add(_amount[i]);
}
_token.safeTransferFrom(
msg.sender,
address(this),
tokens
);
return true;
}
function checkUpkeep(bytes calldata /* checkData */) external view override returns (bool upkeepNeeded, bytes memory /* performData */) {
upkeepNeeded = block.timestamp> keeperLastUpdatedTime && (block.timestamp.sub(keeperLastUpdatedTime) > keeperInterval);
// if(block.timestamp> keeperLastUpdatedTime && (block.timestamp.sub(keeperLastUpdatedTime) > keeperInterval)){
// upkeepNeeded = true;
// }
// We don't use the checkData in this example. The checkData is defined when the Upkeep was registered.
}
function performUpkeep(bytes calldata /* performData */) external override {
//We highly recommend revalidating the upkeep in the performUpkeep function
if (block.timestamp> keeperLastUpdatedTime && (block.timestamp.sub(keeperLastUpdatedTime) > keeperInterval)) {
for(uint256 i=0; i<vestingSchedulesIds.length; i++){
uint256 _releasableAmount = computeReleasableAmount(vestingSchedulesIds[i]);
release(vestingSchedulesIds[i], _releasableAmount);
}
}
keeperLastUpdatedTime = block.timestamp;
// We don't use the performData in this example. The performData is generated by the Keeper's call to your checkUpkeep function
}
/**
* @notice Creates a new vesting schedule for a beneficiary.
* @param _beneficiary address of the beneficiary to whom vested tokens are transferred
* @param _start start time of the vesting period
* @param _cliff duration in seconds of the cliff in which tokens will begin to vest
* @param _duration duration in seconds of the period in which the tokens will vest
* @param _slicePeriodSeconds duration of a slice period for the vesting in seconds
* @param _revocable whether the vesting is revocable or not
* @param _amount total amount of tokens to be released at the end of the vesting
*/
function createVestingSchedule(
address _beneficiary,
uint256 _start,
uint256 _cliff,
uint256 _duration,
uint256 _slicePeriodSeconds,
bool _revocable,
uint256 _amount
)
public
onlyOwner{
require(
this.getWithdrawableAmount() >= _amount,
"TokenVesting: cannot create vesting schedule because not sufficient tokens"
);
require(_duration > 0, "TokenVesting: duration must be > 0");
require(_amount > 0, "TokenVesting: amount must be > 0");
require(_slicePeriodSeconds >= 1, "TokenVesting: slicePeriodSeconds must be >= 1");
bytes32 vestingScheduleId = this.computeNextVestingScheduleIdForHolder(_beneficiary);
uint256 cliff = _start.add(_cliff);
vestingSchedules[vestingScheduleId] = VestingSchedule(
true,
_beneficiary,
cliff,
_start,
_duration,
_slicePeriodSeconds,
_revocable,
_amount,
0,
false
);
vestingSchedulesTotalAmount = vestingSchedulesTotalAmount.add(_amount);
vestingSchedulesIds.push(vestingScheduleId);
uint256 currentVestingCount = holdersVestingCount[_beneficiary];
holdersVestingCount[_beneficiary] = currentVestingCount.add(1);
}
/**
* @notice Revokes the vesting schedule for given identifier.
* @param vestingScheduleId the vesting schedule identifier
*/
function revoke(bytes32 vestingScheduleId)
public
onlyOwner
onlyIfVestingScheduleNotRevoked(vestingScheduleId){
VestingSchedule storage vestingSchedule = vestingSchedules[vestingScheduleId];
require(vestingSchedule.revocable == true, "TokenVesting: vesting is not revocable");
uint256 vestedAmount = _computeReleasableAmount(vestingSchedule);
if(vestedAmount > 0){
release(vestingScheduleId, vestedAmount);
}
uint256 unreleased = vestingSchedule.amountTotal.sub(vestingSchedule.released);
vestingSchedulesTotalAmount = vestingSchedulesTotalAmount.sub(unreleased);
vestingSchedule.revoked = true;
}
/**
* @notice Withdraw the specified amount if possible.
* @param amount the amount to withdraw
*/
function withdraw(uint256 amount)
public
nonReentrant
onlyOwner{
require(this.getWithdrawableAmount() >= amount, "TokenVesting: not enough withdrawable funds");
_token.safeTransfer(owner(), amount);
}
/**
* @notice Release vested amount of tokens.
* @param vestingScheduleId the vesting schedule identifier
* @param amount the amount to release
*/
function release(
bytes32 vestingScheduleId,
uint256 amount
)
public
nonReentrant
onlyIfVestingScheduleNotRevoked(vestingScheduleId){
VestingSchedule storage vestingSchedule = vestingSchedules[vestingScheduleId];
// bool isBeneficiary = msg.sender == vestingSchedule.beneficiary;
// bool isOwner = msg.sender == owner();
// require(
// isBeneficiary || isOwner,
// "TokenVesting: only beneficiary and owner can release vested tokens"
// );
uint256 vestedAmount = _computeReleasableAmount(vestingSchedule);
require(vestedAmount >= amount, "TokenVesting: cannot release tokens, not enough vested tokens");
vestingSchedule.released = vestingSchedule.released.add(amount);
address payable beneficiaryPayable = payable(vestingSchedule.beneficiary);
vestingSchedulesTotalAmount = vestingSchedulesTotalAmount.sub(amount);
_token.safeTransfer(beneficiaryPayable, amount);
}
/**
* @dev Returns the number of vesting schedules managed by this contract.
* @return the number of vesting schedules
*/
function getVestingSchedulesCount()
public
view
returns(uint256){
return vestingSchedulesIds.length;
}
/**
* @notice Computes the vested amount of tokens for the given vesting schedule identifier.
* @return the vested amount
*/
function computeReleasableAmount(bytes32 vestingScheduleId)
public
onlyIfVestingScheduleNotRevoked(vestingScheduleId)
view
returns(uint256){
VestingSchedule storage vestingSchedule = vestingSchedules[vestingScheduleId];
return _computeReleasableAmount(vestingSchedule);
}
/**
* @notice Returns the vesting schedule information for a given identifier.
* @return the vesting schedule structure information
*/
function getVestingSchedule(bytes32 vestingScheduleId)
public
view
returns(VestingSchedule memory){
return vestingSchedules[vestingScheduleId];
}
/**
* @dev Returns the amount of tokens that can be withdrawn by the owner.
* @return the amount of tokens
*/
function getWithdrawableAmount()
public
view
returns(uint256){
return _token.balanceOf(address(this)).sub(vestingSchedulesTotalAmount);
}
/**
* @dev Computes the next vesting schedule identifier for a given holder address.
*/
function computeNextVestingScheduleIdForHolder(address holder)
public
view
returns(bytes32){
return computeVestingScheduleIdForAddressAndIndex(holder, holdersVestingCount[holder]);
}
/**
* @dev Returns the last vesting schedule for a given holder address.
*/
function getLastVestingScheduleForHolder(address holder)
public
view
returns(VestingSchedule memory){
return vestingSchedules[computeVestingScheduleIdForAddressAndIndex(holder, holdersVestingCount[holder] - 1)];
}
/**
* @dev Computes the vesting schedule identifier for an address and an index.
*/
function computeVestingScheduleIdForAddressAndIndex(address holder, uint256 index)
public
pure
returns(bytes32){
return keccak256(abi.encodePacked(holder, index));
}
/**
* @dev Computes the releasable amount of tokens for a vesting schedule.
* @return the amount of releasable tokens
*/
function _computeReleasableAmount(VestingSchedule memory vestingSchedule)
internal
view
returns(uint256){
uint256 currentTime = getCurrentTime();
if ((currentTime < vestingSchedule.cliff) || vestingSchedule.revoked == true) {
return 0;
} else if (currentTime >= vestingSchedule.start.add(vestingSchedule.duration)) {
return vestingSchedule.amountTotal.sub(vestingSchedule.released);
} else {
uint256 timeFromStart = currentTime.sub(vestingSchedule.start);
uint secondsPerSlice = vestingSchedule.slicePeriodSeconds;
uint256 vestedSlicePeriods = timeFromStart.div(secondsPerSlice);
uint256 vestedSeconds = vestedSlicePeriods.mul(secondsPerSlice);
uint256 vestedAmount = vestingSchedule.amountTotal.mul(vestedSeconds).div(vestingSchedule.duration);
vestedAmount = vestedAmount.sub(vestingSchedule.released);
return vestedAmount;
}
}
function getCurrentTime()
internal
virtual
view
returns(uint256){
return block.timestamp;
}
}
|
Returns the vesting schedule id at the given index. return the vesting id/
|
function getVestingIdAtIndex(uint256 index)
external
view
returns(bytes32){
require(index < getVestingSchedulesCount(), "TokenVesting: index out of bounds");
return vestingSchedulesIds[index];
}
| 498,895 |
pragma solidity ^0.5.17;
/**
* @title Ownable
* @dev The Ownable contract has an owner address, and provides basic authorization control
* functions, this simplifies the implementation of "user permissions".
*/
contract Ownable {
address private _owner;
event OwnershipTransferred(address indexed previousOwner, address indexed newOwner);
/**
* @dev The Ownable constructor sets the original `owner` of the contract to the sender
* account.
*/
constructor () internal {
_owner = msg.sender;
emit OwnershipTransferred(address(0), _owner);
}
/**
* @return the address of the owner.
*/
function owner() public view returns (address) {
return _owner;
}
/**
* @dev Throws if called by any account other than the owner.
*/
modifier onlyOwner() {
require(isOwner());
_;
}
/**
* @return true if `msg.sender` is the owner of the contract.
*/
function isOwner() public view returns (bool) {
return msg.sender == _owner;
}
/**
* @dev Allows the current owner to relinquish control of the contract.
* It will not be possible to call the functions with the `onlyOwner`
* modifier anymore.
* @notice Renouncing ownership will leave the contract without an owner,
* thereby removing any functionality that is only available to the owner.
*/
function renounceOwnership() public onlyOwner {
emit OwnershipTransferred(_owner, address(0));
_owner = address(0);
}
/**
* @dev Allows the current owner to transfer control of the contract to a newOwner.
* @param newOwner The address to transfer ownership to.
*/
function transferOwnership(address newOwner) public onlyOwner {
_transferOwnership(newOwner);
}
/**
* @dev Transfers control of the contract to a newOwner.
* @param newOwner The address to transfer ownership to.
*/
function _transferOwnership(address newOwner) internal {
require(newOwner != address(0));
emit OwnershipTransferred(_owner, newOwner);
_owner = newOwner;
}
}
/**
* @title Secondary
* @dev A Secondary contract can only be used by its primary account (the one that created it)
*/
contract Secondary {
address private _primary;
event PrimaryTransferred(
address recipient
);
/**
* @dev Sets the primary account to the one that is creating the Secondary contract.
*/
constructor () internal {
_primary = msg.sender;
emit PrimaryTransferred(_primary);
}
/**
* @dev Reverts if called from any account other than the primary.
*/
modifier onlyPrimary() {
require(msg.sender == _primary);
_;
}
/**
* @return the address of the primary.
*/
function primary() public view returns (address) {
return _primary;
}
/**
* @dev Transfers contract to a new primary.
* @param recipient The address of new primary.
*/
function transferPrimary(address recipient) public onlyPrimary {
require(recipient != address(0));
_primary = recipient;
emit PrimaryTransferred(_primary);
}
}
// File: node_modules\openzeppelin-solidity\contracts\token\ERC20\IERC20.sol
/**
* @title ERC20 interface
* @dev see https://github.com/ethereum/EIPs/issues/20
*/
interface IERC20 {
function transfer(address to, uint256 value) external returns (bool);
function approve(address spender, uint256 value) external returns (bool);
function transferFrom(address from, address to, uint256 value) external returns (bool);
function totalSupply() external view returns (uint256);
function balanceOf(address who) external view returns (uint256);
function allowance(address owner, address spender) external view returns (uint256);
event Transfer(address indexed from, address indexed to, uint256 value);
event Approval(address indexed owner, address indexed spender, uint256 value);
}
// File: node_modules\openzeppelin-solidity\contracts\math\SafeMath.sol
/**
* @title SafeMath
* @dev Unsigned math operations with safety checks that revert on error
*/
library SafeMath {
/**
* @dev Multiplies two unsigned integers, reverts on overflow.
*/
function mul(uint256 a, uint256 b) internal pure returns (uint256) {
// Gas optimization: this is cheaper than requiring 'a' not being zero, but the
// benefit is lost if 'b' is also tested.
// See: https://github.com/OpenZeppelin/openzeppelin-solidity/pull/522
if (a == 0) {
return 0;
}
uint256 c = a * b;
require(c / a == b);
return c;
}
/**
* @dev Integer division of two unsigned integers truncating the quotient, reverts on division by zero.
*/
function div(uint256 a, uint256 b) internal pure returns (uint256) {
// Solidity only automatically asserts when dividing by 0
require(b > 0);
uint256 c = a / b;
// assert(a == b * c + a % b); // There is no case in which this doesn't hold
return c;
}
/**
* @dev Subtracts two unsigned integers, reverts on overflow (i.e. if subtrahend is greater than minuend).
*/
function sub(uint256 a, uint256 b) internal pure returns (uint256) {
require(b <= a);
uint256 c = a - b;
return c;
}
/**
* @dev Adds two unsigned integers, reverts on overflow.
*/
function add(uint256 a, uint256 b) internal pure returns (uint256) {
uint256 c = a + b;
require(c >= a);
return c;
}
/**
* @dev Divides two unsigned integers and returns the remainder (unsigned integer modulo),
* reverts when dividing by zero.
*/
function mod(uint256 a, uint256 b) internal pure returns (uint256) {
require(b != 0);
return a % b;
}
}
// File: node_modules\openzeppelin-solidity\contracts\token\ERC20\ERC20.sol
/**
* @title Standard ERC20 token
*
* @dev Implementation of the basic standard token.
* https://github.com/ethereum/EIPs/blob/master/EIPS/eip-20.md
* Originally based on code by FirstBlood:
* https://github.com/Firstbloodio/token/blob/master/smart_contract/FirstBloodToken.sol
*
* This implementation emits additional Approval events, allowing applications to reconstruct the allowance status for
* all accounts just by listening to said events. Note that this isn't required by the specification, and other
* compliant implementations may not do it.
*/
/**
* @title Standard ERC20 token
*
* @dev Implementation of the basic standard token.
* https://eips.ethereum.org/EIPS/eip-20
* Originally based on code by FirstBlood:
* https://github.com/Firstbloodio/token/blob/master/smart_contract/FirstBloodToken.sol
*
* This implementation emits additional Approval events, allowing applications to reconstruct the allowance status for
* all accounts just by listening to said events. Note that this isn't required by the specification, and other
* compliant implementations may not do it.
*/
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 balance of.
* @return A 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 to 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) {
_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) {
_approve(msg.sender, spender, value);
return true;
}
/**
* @dev Transfer tokens from one address to another.
* Note that while this function emits an Approval event, this is not required as per the specification,
* and other compliant implementations may not emit the event.
* @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) {
_transfer(from, to, value);
_approve(from, msg.sender, _allowed[from][msg.sender].sub(value));
return true;
}
/**
* @dev Increase the amount of tokens that an owner allowed to a spender.
* approve should be called when _allowed[msg.sender][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
* Emits an Approval event.
* @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) {
_approve(msg.sender, spender, _allowed[msg.sender][spender].add(addedValue));
return true;
}
/**
* @dev Decrease the amount of tokens that an owner allowed to a spender.
* approve should be called when _allowed[msg.sender][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
* Emits an Approval event.
* @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) {
_approve(msg.sender, spender, _allowed[msg.sender][spender].sub(subtractedValue));
return true;
}
/**
* @dev Transfer token for a specified addresses
* @param from The address to transfer from.
* @param to The address to transfer to.
* @param value The amount to be transferred.
*/
function _transfer(address from, address to, uint256 value) internal {
require(to != address(0));
_balances[from] = _balances[from].sub(value);
_balances[to] = _balances[to].add(value);
emit Transfer(from, to, value);
}
/**
* @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 value The amount that will be created.
*/
function _mint(address account, uint256 value) internal {
require(account != address(0));
_totalSupply = _totalSupply.add(value);
_balances[account] = _balances[account].add(value);
emit Transfer(address(0), account, value);
}
/**
* @dev Internal function that burns an amount of the token of a given
* account.
* @param account The account whose tokens will be burnt.
* @param value The amount that will be burnt.
*/
function _burn(address account, uint256 value) internal {
require(account != address(0));
_totalSupply = _totalSupply.sub(value);
_balances[account] = _balances[account].sub(value);
emit Transfer(account, address(0), value);
}
/**
* @dev Approve an address to spend another addresses' tokens.
* @param owner The address that owns the tokens.
* @param spender The address that will spend the tokens.
* @param value The number of tokens that can be spent.
*/
function _approve(address owner, address spender, uint256 value) internal {
require(spender != address(0));
require(owner != address(0));
_allowed[owner][spender] = value;
emit Approval(owner, spender, value);
}
/**
* @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.
* Emits an Approval event (reflecting the reduced allowance).
* @param account The account whose tokens will be burnt.
* @param value The amount that will be burnt.
*/
function _burnFrom(address account, uint256 value) internal {
_burn(account, value);
_approve(account, msg.sender, _allowed[account][msg.sender].sub(value));
}
}
// File: openzeppelin-solidity\contracts\token\ERC20\ERC20Burnable.sol
/**
* @title Burnable Token
* @dev Token that can be irreversibly burned (destroyed).
*/
contract ERC20Burnable is ERC20 {
/**
* @dev Burns a specific amount of tokens.
* @param value The amount of token to be burned.
*/
function burn(uint256 value) public {
_burn(msg.sender, value);
}
/**
* @dev Burns a specific amount of tokens from the target address and decrements allowance
* @param from address The account whose tokens will be burned.
* @param value uint256 The amount of token to be burned.
*/
function burnFrom(address from, uint256 value) public {
_burnFrom(from, value);
}
}
// File: node_modules\openzeppelin-solidity\contracts\access\Roles.sol
/**
* @title Roles
* @dev Library for managing addresses assigned to a Role.
*/
library Roles {
struct Role {
mapping (address => bool) bearer;
}
/**
* @dev give an account access to this role
*/
function add(Role storage role, address account) internal {
require(account != address(0));
require(!has(role, account));
role.bearer[account] = true;
}
/**
* @dev remove an account's access to this role
*/
function remove(Role storage role, address account) internal {
require(account != address(0));
require(has(role, account));
role.bearer[account] = false;
}
/**
* @dev check if an account has this role
* @return bool
*/
function has(Role storage role, address account) internal view returns (bool) {
require(account != address(0));
return role.bearer[account];
}
}
// File: node_modules\openzeppelin-solidity\contracts\access\roles\MinterRole.sol
contract MinterRole {
using Roles for Roles.Role;
event MinterAdded(address indexed account);
event MinterRemoved(address indexed account);
Roles.Role private _minters;
constructor () internal {
_addMinter(msg.sender);
}
modifier onlyMinter() {
require(isMinter(msg.sender));
_;
}
function isMinter(address account) public view returns (bool) {
return _minters.has(account);
}
function addMinter(address account) public onlyMinter {
_addMinter(account);
}
function renounceMinter() public {
_removeMinter(msg.sender);
}
function _addMinter(address account) internal {
_minters.add(account);
emit MinterAdded(account);
}
function _removeMinter(address account) internal {
_minters.remove(account);
emit MinterRemoved(account);
}
}
// File: openzeppelin-solidity\contracts\token\ERC20\ERC20Mintable.sol
/**
* @title ERC20Mintable
* @dev ERC20 minting logic
*/
contract ERC20Mintable is ERC20, MinterRole {
/**
* @dev Function to mint tokens
* @param to The address that will receive the minted tokens.
* @param value The amount of tokens to mint.
* @return A boolean that indicates if the operation was successful.
*/
function mint(address to, uint256 value) public onlyMinter returns (bool) {
_mint(to, value);
return true;
}
}
// File: contracts\ERC20Frozenable.sol
//truffle-flattener Token.sol
contract ERC20Frozenable is ERC20Burnable, ERC20Mintable, Ownable {
mapping (address => bool) private _frozenAccount;
event FrozenFunds(address target, bool frozen);
function frozenAccount(address _address) public view returns(bool isFrozen) {
return _frozenAccount[_address];
}
function freezeAccount(address target, bool freeze) public onlyOwner {
require(_frozenAccount[target] != freeze, "Same as current");
_frozenAccount[target] = freeze;
emit FrozenFunds(target, freeze);
}
function _transfer(address from, address to, uint256 value) internal {
require(!_frozenAccount[from], "error - frozen");
require(!_frozenAccount[to], "error - frozen");
super._transfer(from, to, value);
}
}
// File: openzeppelin-solidity\contracts\token\ERC20\ERC20Detailed.sol
/**
* @title ERC20Detailed token
* @dev The decimals are only for visualization purposes.
* All the operations are done using the smallest and indivisible token unit,
* just as on Ethereum all the operations are done in wei.
*/
contract ERC20Detailed is IERC20 {
string private _name;
string private _symbol;
uint8 private _decimals;
constructor (string memory name, string memory symbol, uint8 decimals) public {
_name = name;
_symbol = symbol;
_decimals = decimals;
}
/**
* @return the name of the token.
*/
function name() public view returns (string memory) {
return _name;
}
/**
* @return the symbol of the token.
*/
function symbol() public view returns (string memory) {
return _symbol;
}
/**
* @return the number of decimals of the token.
*/
function decimals() public view returns (uint8) {
return _decimals;
}
}
/**
* @title Escrow
* @dev Base escrow contract, holds funds designated for a payee until they
* withdraw them.
* @dev Intended usage: This contract (and derived escrow contracts) should be a
* standalone contract, that only interacts with the contract that instantiated
* it. That way, it is guaranteed that all Ether will be handled according to
* the Escrow rules, and there is no need to check for payable functions or
* transfers in the inheritance tree. The contract that uses the escrow as its
* payment method should be its primary, and provide public methods redirecting
* to the escrow's deposit and withdraw.
*/
contract Escrow is Secondary {
using SafeMath for uint256;
event Deposited(address indexed payee, uint256 weiAmount);
event Withdrawn(address indexed payee, uint256 weiAmount);
mapping(address => uint256) private _deposits;
function depositsOf(address payee) public view returns (uint256) {
return _deposits[payee];
}
/**
* @dev Stores the sent amount as credit to be withdrawn.
* @param payee The destination address of the funds.
*/
function deposit(address payee) public onlyPrimary payable {
uint256 amount = msg.value;
_deposits[payee] = _deposits[payee].add(amount);
emit Deposited(payee, amount);
}
/**
* @dev Withdraw accumulated balance for a payee.
* @param payee The address whose funds will be withdrawn and transferred to.
*/
function withdraw(address payable payee) public onlyPrimary {
uint256 payment = _deposits[payee];
_deposits[payee] = 0;
payee.transfer(payment);
emit Withdrawn(payee, payment);
}
}
/**
* @title PullPayment
* @dev Base contract supporting async send for pull payments. Inherit from this
* contract and use _asyncTransfer instead of send or transfer.
*/
contract PullPayment {
Escrow private _escrow;
constructor () internal {
_escrow = new Escrow();
}
/**
* @dev Withdraw accumulated balance.
* @param payee Whose balance will be withdrawn.
*/
function withdrawPayments(address payable payee) public {
_escrow.withdraw(payee);
}
/**
* @dev Returns the credit owed to an address.
* @param dest The creditor's address.
*/
function payments(address dest) public view returns (uint256) {
return _escrow.depositsOf(dest);
}
/**
* @dev Called by the payer to store the sent amount as credit to be pulled.
* @param dest The destination address of the funds.
* @param amount The amount to transfer.
*/
function _asyncTransfer(address dest, uint256 amount) internal {
_escrow.deposit.value(amount)(dest);
}
}
contract PaymentSplitter {
using SafeMath for uint256;
event PayeeAdded(address account, uint256 shares);
event PaymentReleased(address to, uint256 amount);
event PaymentReceived(address from, uint256 amount);
uint256 private _totalShares;
uint256 private _totalReleased;
mapping(address => uint256) private _shares;
mapping(address => uint256) private _released;
address[] private _payees;
/**
* @dev Constructor
*/
constructor (address[] memory payees, uint256[] memory shares) public payable {
require(payees.length == shares.length);
require(payees.length > 0);
for (uint256 i = 0; i < payees.length; i++) {
_addPayee(payees[i], shares[i]);
}
}
/**
* @dev payable fallback
*/
function () external payable {
emit PaymentReceived(msg.sender, msg.value);
}
/**
* @return the total shares of the contract.
*/
function totalShares() public view returns (uint256) {
return _totalShares;
}
/**
* @return the total amount already released.
*/
function totalReleased() public view returns (uint256) {
return _totalReleased;
}
/**
* @return the shares of an account.
*/
function shares(address account) public view returns (uint256) {
return _shares[account];
}
/**
* @return the amount already released to an account.
*/
function released(address account) public view returns (uint256) {
return _released[account];
}
/**
* @return the address of a payee.
*/
function payee(uint256 index) public view returns (address) {
return _payees[index];
}
/**
* @dev Release one of the payee's proportional payment.
* @param account Whose payments will be released.
*/
function release(address payable account) public {
require(_shares[account] > 0);
uint256 totalReceived = address(this).balance.add(_totalReleased);
uint256 payment = totalReceived.mul(_shares[account]).div(_totalShares).sub(_released[account]);
require(payment != 0);
_released[account] = _released[account].add(payment);
_totalReleased = _totalReleased.add(payment);
account.transfer(payment);
emit PaymentReleased(account, payment);
}
/**
* @dev Add a new payee to the contract.
* @param account The address of the payee to add.
* @param shares_ The number of shares owned by the payee.
*/
function _addPayee(address account, uint256 shares_) private {
require(account != address(0));
require(shares_ > 0);
require(_shares[account] == 0);
_payees.push(account);
_shares[account] = shares_;
_totalShares = _totalShares.add(shares_);
emit PayeeAdded(account, shares_);
}
}
contract ConditionalEscrow is Escrow {
/**
* @dev Returns whether an address is allowed to withdraw their funds. To be
* implemented by derived contracts.
* @param payee The destination address of the funds.
*/
function withdrawalAllowed(address payee) public view returns (bool);
function withdraw(address payable payee) public {
require(withdrawalAllowed(payee));
super.withdraw(payee);
}
}
contract RefundEscrow is ConditionalEscrow {
enum State { Active, Refunding, Closed }
event RefundsClosed();
event RefundsEnabled();
State private _state;
address payable private _beneficiary;
/**
* @dev Constructor.
* @param beneficiary The beneficiary of the deposits.
*/
constructor (address payable beneficiary) public {
require(beneficiary != address(0));
_beneficiary = beneficiary;
_state = State.Active;
}
/**
* @return the current state of the escrow.
*/
function state() public view returns (State) {
return _state;
}
/**
* @return the beneficiary of the escrow.
*/
function beneficiary() public view returns (address) {
return _beneficiary;
}
/**
* @dev Stores funds that may later be refunded.
* @param refundee The address funds will be sent to if a refund occurs.
*/
function deposit(address refundee) public payable {
require(_state == State.Active);
super.deposit(refundee);
}
/**
* @dev Allows for the beneficiary to withdraw their funds, rejecting
* further deposits.
*/
function close() public onlyPrimary {
require(_state == State.Active);
_state = State.Closed;
emit RefundsClosed();
}
/**
* @dev Allows for refunds to take place, rejecting further deposits.
*/
function enableRefunds() public onlyPrimary {
require(_state == State.Active);
_state = State.Refunding;
emit RefundsEnabled();
}
/**
* @dev Withdraws the beneficiary's funds.
*/
function beneficiaryWithdraw() public {
require(_state == State.Closed);
_beneficiary.transfer(address(this).balance);
}
/**
* @dev Returns whether refundees can withdraw their deposits (be refunded). The overridden function receives a
* 'payee' argument, but we ignore it here since the condition is global, not per-payee.
*/
function withdrawalAllowed(address) public view returns (bool) {
return _state == State.Refunding;
}
}
// File: contracts\Token.sol
//truffle-flattener Token.sol
contract Blocks is ERC20Frozenable, ERC20Detailed {
constructor()
ERC20Detailed("GEP Token", "GEP", 18)
public {
uint256 supply = 1000000000;
uint256 initialSupply = supply * uint(10) ** decimals();
_mint(msg.sender, initialSupply);
}
}
|
Returns whether refundees can withdraw their deposits (be refunded). The overridden function receives a 'payee' argument, but we ignore it here since the condition is global, not per-payee./
|
function withdrawalAllowed(address) public view returns (bool) {
return _state == State.Refunding;
}
| 572,552 |
pragma solidity ^0.5.16;
interface IERC20 {
function TOTALSUPPLY668() external view returns (uint256); //inject NONSTANDARD NAMING
function BALANCEOF856(address account) external view returns (uint256); //inject NONSTANDARD NAMING
function TRANSFER590(address recipient, uint256 amount) external returns (bool); //inject NONSTANDARD NAMING
function ALLOWANCE439(address owner, address spender) external view returns (uint256); //inject NONSTANDARD NAMING
function APPROVE165(address spender, uint256 amount) external returns (bool); //inject NONSTANDARD NAMING
function TRANSFERFROM946(address sender, address recipient, uint256 amount) external returns (bool); //inject NONSTANDARD NAMING
event TRANSFER113(address indexed from, address indexed to, uint256 value); //inject NONSTANDARD NAMING
event APPROVAL275(address indexed owner, address indexed spender, uint256 value); //inject NONSTANDARD NAMING
}
contract Context {
constructor () internal { }
// solhint-disable-previous-line no-empty-blocks
function _MSGSENDER204() internal view returns (address payable) { //inject NONSTANDARD NAMING
return msg.sender;
}
function _MSGDATA645() internal view returns (bytes memory) { //inject NONSTANDARD NAMING
this; // silence state mutability warning without generating bytecode - see https://github.com/ethereum/solidity/issues/2691
return msg.data;
}
}
contract Ownable is Context {
address private _owner;
event OWNERSHIPTRANSFERRED90(address indexed previousOwner, address indexed newOwner); //inject NONSTANDARD NAMING
constructor () internal {
_owner = _MSGSENDER204();
emit OWNERSHIPTRANSFERRED90(address(0), _owner);
}
function OWNER726() public view returns (address) { //inject NONSTANDARD NAMING
return _owner;
}
modifier ONLYOWNER38() { //inject NONSTANDARD NAMING
require(ISOWNER90(), "Ownable: caller is not the owner");
_;
}
function ISOWNER90() public view returns (bool) { //inject NONSTANDARD NAMING
return _MSGSENDER204() == _owner;
}
function RENOUNCEOWNERSHIP524() public ONLYOWNER38 { //inject NONSTANDARD NAMING
emit OWNERSHIPTRANSFERRED90(_owner, address(0));
_owner = address(0);
}
function TRANSFEROWNERSHIP660(address newOwner) public ONLYOWNER38 { //inject NONSTANDARD NAMING
_TRANSFEROWNERSHIP31(newOwner);
}
function _TRANSFEROWNERSHIP31(address newOwner) internal { //inject NONSTANDARD NAMING
require(newOwner != address(0), "Ownable: new owner is the zero address");
emit OWNERSHIPTRANSFERRED90(_owner, newOwner);
_owner = newOwner;
}
}
contract ERC20 is Context, IERC20 {
using SafeMath for uint256;
mapping (address => uint256) private _balances;
mapping (address => mapping (address => uint256)) private _allowances;
uint256 private _totalSupply;
function TOTALSUPPLY668() public view returns (uint256) { //inject NONSTANDARD NAMING
return _totalSupply;
}
function BALANCEOF856(address account) public view returns (uint256) { //inject NONSTANDARD NAMING
return _balances[account];
}
function TRANSFER590(address recipient, uint256 amount) public returns (bool) { //inject NONSTANDARD NAMING
_TRANSFER132(_MSGSENDER204(), recipient, amount);
return true;
}
function ALLOWANCE439(address owner, address spender) public view returns (uint256) { //inject NONSTANDARD NAMING
return _allowances[owner][spender];
}
function APPROVE165(address spender, uint256 amount) public returns (bool) { //inject NONSTANDARD NAMING
_APPROVE48(_MSGSENDER204(), spender, amount);
return true;
}
function TRANSFERFROM946(address sender, address recipient, uint256 amount) public returns (bool) { //inject NONSTANDARD NAMING
_TRANSFER132(sender, recipient, amount);
_APPROVE48(sender, _MSGSENDER204(), _allowances[sender][_MSGSENDER204()].SUB641(amount, "ERC20: transfer amount exceeds allowance"));
return true;
}
function INCREASEALLOWANCE241(address spender, uint256 addedValue) public returns (bool) { //inject NONSTANDARD NAMING
_APPROVE48(_MSGSENDER204(), spender, _allowances[_MSGSENDER204()][spender].ADD348(addedValue));
return true;
}
function DECREASEALLOWANCE811(address spender, uint256 subtractedValue) public returns (bool) { //inject NONSTANDARD NAMING
_APPROVE48(_MSGSENDER204(), spender, _allowances[_MSGSENDER204()][spender].SUB641(subtractedValue, "ERC20: decreased allowance below zero"));
return true;
}
function _TRANSFER132(address sender, address recipient, uint256 amount) internal { //inject NONSTANDARD NAMING
require(sender != address(0), "ERC20: transfer from the zero address");
require(recipient != address(0), "ERC20: transfer to the zero address");
_balances[sender] = _balances[sender].SUB641(amount, "ERC20: transfer amount exceeds balance");
_balances[recipient] = _balances[recipient].ADD348(amount);
emit TRANSFER113(sender, recipient, amount);
}
function _MINT225(address account, uint256 amount) internal { //inject NONSTANDARD NAMING
require(account != address(0), "ERC20: mint to the zero address");
_totalSupply = _totalSupply.ADD348(amount);
_balances[account] = _balances[account].ADD348(amount);
emit TRANSFER113(address(0), account, amount);
}
function _BURN186(address account, uint256 amount) internal { //inject NONSTANDARD NAMING
require(account != address(0), "ERC20: burn from the zero address");
_balances[account] = _balances[account].SUB641(amount, "ERC20: burn amount exceeds balance");
_totalSupply = _totalSupply.SUB641(amount);
emit TRANSFER113(account, address(0), amount);
}
function _APPROVE48(address owner, address spender, uint256 amount) internal { //inject NONSTANDARD NAMING
require(owner != address(0), "ERC20: approve from the zero address");
require(spender != address(0), "ERC20: approve to the zero address");
_allowances[owner][spender] = amount;
emit APPROVAL275(owner, spender, amount);
}
function _BURNFROM442(address account, uint256 amount) internal { //inject NONSTANDARD NAMING
_BURN186(account, amount);
_APPROVE48(account, _MSGSENDER204(), _allowances[account][_MSGSENDER204()].SUB641(amount, "ERC20: burn amount exceeds allowance"));
}
}
contract ERC20Detailed is IERC20 {
string private _name;
string private _symbol;
uint8 private _decimals;
constructor (string memory name, string memory symbol, uint8 decimals) public {
_name = name;
_symbol = symbol;
_decimals = decimals;
}
function NAME591() public view returns (string memory) { //inject NONSTANDARD NAMING
return _name;
}
function SYMBOL151() public view returns (string memory) { //inject NONSTANDARD NAMING
return _symbol;
}
function DECIMALS443() public view returns (uint8) { //inject NONSTANDARD NAMING
return _decimals;
}
}
library SafeMath {
function ADD348(uint256 a, uint256 b) internal pure returns (uint256) { //inject NONSTANDARD NAMING
uint256 c = a + b;
require(c >= a, "SafeMath: addition overflow");
return c;
}
function SUB641(uint256 a, uint256 b) internal pure returns (uint256) { //inject NONSTANDARD NAMING
return SUB641(a, b, "SafeMath: subtraction overflow");
}
function SUB641(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { //inject NONSTANDARD NAMING
require(b <= a, errorMessage);
uint256 c = a - b;
return c;
}
function MUL714(uint256 a, uint256 b) internal pure returns (uint256) { //inject NONSTANDARD NAMING
if (a == 0) {
return 0;
}
uint256 c = a * b;
require(c / a == b, "SafeMath: multiplication overflow");
return c;
}
function DIV963(uint256 a, uint256 b) internal pure returns (uint256) { //inject NONSTANDARD NAMING
return DIV963(a, b, "SafeMath: division by zero");
}
function DIV963(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { //inject NONSTANDARD NAMING
// Solidity only automatically asserts when dividing by 0
require(b > 0, errorMessage);
uint256 c = a / b;
return c;
}
function MOD537(uint256 a, uint256 b) internal pure returns (uint256) { //inject NONSTANDARD NAMING
return MOD537(a, b, "SafeMath: modulo by zero");
}
function MOD537(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { //inject NONSTANDARD NAMING
require(b != 0, errorMessage);
return a % b;
}
}
library Address {
function ISCONTRACT792(address account) internal view returns (bool) { //inject NONSTANDARD NAMING
bytes32 codehash;
bytes32 accountHash = 0xc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470;
// solhint-disable-next-line no-inline-assembly
assembly { codehash := extcodehash(account) }
return (codehash != 0x0 && codehash != accountHash);
}
function TOPAYABLE613(address account) internal pure returns (address payable) { //inject NONSTANDARD NAMING
return address(uint160(account));
}
function SENDVALUE471(address payable recipient, uint256 amount) internal { //inject NONSTANDARD NAMING
require(address(this).balance >= amount, "Address: insufficient balance");
// solhint-disable-next-line avoid-call-value
(bool success, ) = recipient.call.value(amount)("");
require(success, "Address: unable to send value, recipient may have reverted");
}
}
library SafeERC20 {
using SafeMath for uint256;
using Address for address;
function SAFETRANSFER595(IERC20 token, address to, uint256 value) internal { //inject NONSTANDARD NAMING
CALLOPTIONALRETURN929(token, abi.encodeWithSelector(token.TRANSFER590.selector, to, value));
}
function SAFETRANSFERFROM895(IERC20 token, address from, address to, uint256 value) internal { //inject NONSTANDARD NAMING
CALLOPTIONALRETURN929(token, abi.encodeWithSelector(token.TRANSFERFROM946.selector, from, to, value));
}
function SAFEAPPROVE173(IERC20 token, address spender, uint256 value) internal { //inject NONSTANDARD NAMING
require((value == 0) || (token.ALLOWANCE439(address(this), spender) == 0),
"SafeERC20: approve from non-zero to non-zero allowance"
);
CALLOPTIONALRETURN929(token, abi.encodeWithSelector(token.APPROVE165.selector, spender, value));
}
function SAFEINCREASEALLOWANCE700(IERC20 token, address spender, uint256 value) internal { //inject NONSTANDARD NAMING
uint256 newAllowance = token.ALLOWANCE439(address(this), spender).ADD348(value);
CALLOPTIONALRETURN929(token, abi.encodeWithSelector(token.APPROVE165.selector, spender, newAllowance));
}
function SAFEDECREASEALLOWANCE390(IERC20 token, address spender, uint256 value) internal { //inject NONSTANDARD NAMING
uint256 newAllowance = token.ALLOWANCE439(address(this), spender).SUB641(value, "SafeERC20: decreased allowance below zero");
CALLOPTIONALRETURN929(token, abi.encodeWithSelector(token.APPROVE165.selector, spender, newAllowance));
}
function CALLOPTIONALRETURN929(IERC20 token, bytes memory data) private { //inject NONSTANDARD NAMING
require(address(token).ISCONTRACT792(), "SafeERC20: call to non-contract");
// solhint-disable-next-line avoid-low-level-calls
(bool success, bytes memory returndata) = address(token).call(data);
require(success, "SafeERC20: low-level call failed");
if (returndata.length > 0) { // Return data is optional
// solhint-disable-next-line max-line-length
require(abi.decode(returndata, (bool)), "SafeERC20: ERC20 operation did not succeed");
}
}
}
interface Controller {
function WITHDRAW362(address, uint) external; //inject NONSTANDARD NAMING
function BALANCEOF856(address) external view returns (uint); //inject NONSTANDARD NAMING
function EARN394(address, uint) external; //inject NONSTANDARD NAMING
function WANT709(address) external view returns (address); //inject NONSTANDARD NAMING
}
interface Aave {
function BORROW427(address _reserve, uint _amount, uint _interestRateModel, uint16 _referralCode) external; //inject NONSTANDARD NAMING
function SETUSERUSERESERVEASCOLLATERAL395(address _reserve, bool _useAsCollateral) external; //inject NONSTANDARD NAMING
function REPAY171(address _reserve, uint _amount, address payable _onBehalfOf) external payable; //inject NONSTANDARD NAMING
function GETUSERACCOUNTDATA396(address _user) //inject NONSTANDARD NAMING
external
view
returns (
uint totalLiquidityETH,
uint totalCollateralETH,
uint totalBorrowsETH,
uint totalFeesETH,
uint availableBorrowsETH,
uint currentLiquidationThreshold,
uint ltv,
uint healthFactor
);
function GETUSERRESERVEDATA201(address _reserve, address _user) //inject NONSTANDARD NAMING
external
view
returns (
uint currentATokenBalance,
uint currentBorrowBalance,
uint principalBorrowBalance,
uint borrowRateMode,
uint borrowRate,
uint liquidityRate,
uint originationFee,
uint variableBorrowIndex,
uint lastUpdateTimestamp,
bool usageAsCollateralEnabled
);
}
interface AaveToken {
function UNDERLYINGASSETADDRESS967() external view returns (address); //inject NONSTANDARD NAMING
}
interface Oracle {
function GETASSETPRICE895(address reserve) external view returns (uint); //inject NONSTANDARD NAMING
function LATESTANSWER820() external view returns (uint); //inject NONSTANDARD NAMING
}
interface LendingPoolAddressesProvider {
function GETLENDINGPOOL689() external view returns (address); //inject NONSTANDARD NAMING
function GETLENDINGPOOLCORE785() external view returns (address); //inject NONSTANDARD NAMING
function GETPRICEORACLE709() external view returns (address); //inject NONSTANDARD NAMING
}
contract yDelegatedVault is ERC20, ERC20Detailed {
using SafeERC20 for IERC20;
using Address for address;
using SafeMath for uint256;
IERC20 public token;
address public governance;
address public controller;
uint public insurance;
uint public healthFactor = 4;
address public constant aave533 = address(0x24a42fD28C976A61Df5D00D0599C34c4f90748c8); //inject NONSTANDARD NAMING
constructor (address _token, address _controller) public ERC20Detailed(
string(abi.encodePacked("yearn ", ERC20Detailed(_token).NAME591())),
string(abi.encodePacked("y", ERC20Detailed(_token).SYMBOL151())),
ERC20Detailed(_token).DECIMALS443()
) {
token = IERC20(_token);
governance = msg.sender;
controller = _controller;
}
function DEBT414() public view returns (uint) { //inject NONSTANDARD NAMING
address _reserve = Controller(controller).WANT709(address(this));
(,uint currentBorrowBalance,,,,,,,,) = Aave(GETAAVE93()).GETUSERRESERVEDATA201(_reserve, address(this));
return currentBorrowBalance;
}
function CREDIT327() public view returns (uint) { //inject NONSTANDARD NAMING
return Controller(controller).BALANCEOF856(address(this));
}
// % of tokens locked and cannot be withdrawn per user
// this is impermanent locked, unless the debt out accrues the strategy
function LOCKED694() public view returns (uint) { //inject NONSTANDARD NAMING
return CREDIT327().MUL714(1e18).DIV963(DEBT414());
}
function DEBTSHARE933(address _lp) public view returns (uint) { //inject NONSTANDARD NAMING
return DEBT414().MUL714(BALANCEOF856(_lp)).MUL714(TOTALSUPPLY668());
}
function GETAAVE93() public view returns (address) { //inject NONSTANDARD NAMING
return LendingPoolAddressesProvider(aave533).GETLENDINGPOOL689();
}
function GETAAVECORE229() public view returns (address) { //inject NONSTANDARD NAMING
return LendingPoolAddressesProvider(aave533).GETLENDINGPOOLCORE785();
}
function SETHEALTHFACTOR690(uint _hf) external { //inject NONSTANDARD NAMING
require(msg.sender == governance, "!governance");
healthFactor = _hf;
}
function ACTIVATE169() public { //inject NONSTANDARD NAMING
Aave(GETAAVE93()).SETUSERUSERESERVEASCOLLATERAL395(UNDERLYING289(), true);
}
function REPAY171(address reserve, uint amount) public { //inject NONSTANDARD NAMING
// Required for certain stable coins (USDT for example)
IERC20(reserve).APPROVE165(address(GETAAVECORE229()), 0);
IERC20(reserve).APPROVE165(address(GETAAVECORE229()), amount);
Aave(GETAAVE93()).REPAY171(reserve, amount, address(uint160(address(this))));
}
function REPAYALL522() public { //inject NONSTANDARD NAMING
address _reserve = RESERVE164();
uint _amount = IERC20(_reserve).BALANCEOF856(address(this));
REPAY171(_reserve, _amount);
}
// Used to swap any borrowed reserve over the debt limit to liquidate to 'token'
function HARVEST865(address reserve, uint amount) external { //inject NONSTANDARD NAMING
require(msg.sender == controller, "!controller");
require(reserve != address(token), "token");
IERC20(reserve).SAFETRANSFER595(controller, amount);
}
// Ignore insurance fund for balance calculations
function BALANCE541() public view returns (uint) { //inject NONSTANDARD NAMING
return token.BALANCEOF856(address(this)).SUB641(insurance);
}
function SETCONTROLLER494(address _controller) external { //inject NONSTANDARD NAMING
require(msg.sender == governance, "!governance");
controller = _controller;
}
function GETAAVEORACLE538() public view returns (address) { //inject NONSTANDARD NAMING
return LendingPoolAddressesProvider(aave533).GETPRICEORACLE709();
}
function GETRESERVEPRICEETH945(address reserve) public view returns (uint) { //inject NONSTANDARD NAMING
return Oracle(GETAAVEORACLE538()).GETASSETPRICE895(reserve);
}
function SHOULDREBALANCE804() external view returns (bool) { //inject NONSTANDARD NAMING
return (OVER549() > 0);
}
function OVER549() public view returns (uint) { //inject NONSTANDARD NAMING
OVER549(0);
}
function GETUNDERLYINGPRICEETH537(uint _amount) public view returns (uint) { //inject NONSTANDARD NAMING
return _amount.MUL714(GETUNDERLYINGPRICE909()).DIV963(uint(10)**ERC20Detailed(address(token)).DECIMALS443()); // Calculate the amount we are withdrawing in ETH
}
function OVER549(uint _amount) public view returns (uint) { //inject NONSTANDARD NAMING
address _reserve = RESERVE164();
uint _eth = GETUNDERLYINGPRICEETH537(_amount);
(uint _maxSafeETH,uint _totalBorrowsETH,) = MAXSAFEETH837();
_maxSafeETH = _maxSafeETH.MUL714(105).DIV963(100); // 5% buffer so we don't go into a earn/rebalance loop
if (_eth > _maxSafeETH) {
_maxSafeETH = 0;
} else {
_maxSafeETH = _maxSafeETH.SUB641(_eth); // Add the ETH we are withdrawing
}
if (_maxSafeETH < _totalBorrowsETH) {
uint _over = _totalBorrowsETH.MUL714(_totalBorrowsETH.SUB641(_maxSafeETH)).DIV963(_totalBorrowsETH);
_over = _over.MUL714(uint(10)**ERC20Detailed(_reserve).DECIMALS443()).DIV963(GETRESERVEPRICE515());
return _over;
} else {
return 0;
}
}
function _REBALANCE677(uint _amount) internal { //inject NONSTANDARD NAMING
uint _over = OVER549(_amount);
if (_over > 0) {
Controller(controller).WITHDRAW362(address(this), _over);
REPAYALL522();
}
}
function REBALANCE176() external { //inject NONSTANDARD NAMING
_REBALANCE677(0);
}
function CLAIMINSURANCE254() external { //inject NONSTANDARD NAMING
require(msg.sender == controller, "!controller");
token.SAFETRANSFER595(controller, insurance);
insurance = 0;
}
function MAXSAFEETH837() public view returns (uint maxBorrowsETH, uint totalBorrowsETH, uint availableBorrowsETH) { //inject NONSTANDARD NAMING
(,,uint _totalBorrowsETH,,uint _availableBorrowsETH,,,) = Aave(GETAAVE93()).GETUSERACCOUNTDATA396(address(this));
uint _maxBorrowETH = (_totalBorrowsETH.ADD348(_availableBorrowsETH));
return (_maxBorrowETH.DIV963(healthFactor), _totalBorrowsETH, _availableBorrowsETH);
}
function SHOULDBORROW22() external view returns (bool) { //inject NONSTANDARD NAMING
return (AVAILABLETOBORROWRESERVE235() > 0);
}
function AVAILABLETOBORROWETH693() public view returns (uint) { //inject NONSTANDARD NAMING
(uint _maxSafeETH,uint _totalBorrowsETH, uint _availableBorrowsETH) = MAXSAFEETH837();
_maxSafeETH = _maxSafeETH.MUL714(95).DIV963(100); // 5% buffer so we don't go into a earn/rebalance loop
if (_maxSafeETH > _totalBorrowsETH) {
return _availableBorrowsETH.MUL714(_maxSafeETH.SUB641(_totalBorrowsETH)).DIV963(_availableBorrowsETH);
} else {
return 0;
}
}
function AVAILABLETOBORROWRESERVE235() public view returns (uint) { //inject NONSTANDARD NAMING
address _reserve = RESERVE164();
uint _available = AVAILABLETOBORROWETH693();
if (_available > 0) {
return _available.MUL714(uint(10)**ERC20Detailed(_reserve).DECIMALS443()).DIV963(GETRESERVEPRICE515());
} else {
return 0;
}
}
function GETRESERVEPRICE515() public view returns (uint) { //inject NONSTANDARD NAMING
return GETRESERVEPRICEETH945(RESERVE164());
}
function GETUNDERLYINGPRICE909() public view returns (uint) { //inject NONSTANDARD NAMING
return GETRESERVEPRICEETH945(UNDERLYING289());
}
function EARN394() external { //inject NONSTANDARD NAMING
address _reserve = RESERVE164();
uint _borrow = AVAILABLETOBORROWRESERVE235();
if (_borrow > 0) {
Aave(GETAAVE93()).BORROW427(_reserve, _borrow, 2, 7);
}
//rebalance here
uint _balance = IERC20(_reserve).BALANCEOF856(address(this));
if (_balance > 0) {
IERC20(_reserve).SAFETRANSFER595(controller, _balance);
Controller(controller).EARN394(address(this), _balance);
}
}
function DEPOSITALL399() external { //inject NONSTANDARD NAMING
DEPOSIT764(token.BALANCEOF856(msg.sender));
}
function DEPOSIT764(uint _amount) public { //inject NONSTANDARD NAMING
uint _pool = BALANCE541();
token.SAFETRANSFERFROM895(msg.sender, address(this), _amount);
// 0.5% of deposits go into an insurance fund incase of negative profits to protect withdrawals
// At a 4 health factor, this is a -2% position
uint _insurance = _amount.MUL714(50).DIV963(10000);
_amount = _amount.SUB641(_insurance);
insurance = insurance.ADD348(_insurance);
//Controller can claim insurance to liquidate to cover interest
uint shares = 0;
if (TOTALSUPPLY668() == 0) {
shares = _amount;
ACTIVATE169();
} else {
shares = (_amount.MUL714(TOTALSUPPLY668())).DIV963(_pool);
}
_MINT225(msg.sender, shares);
}
function RESERVE164() public view returns (address) { //inject NONSTANDARD NAMING
return Controller(controller).WANT709(address(this));
}
function UNDERLYING289() public view returns (address) { //inject NONSTANDARD NAMING
return AaveToken(address(token)).UNDERLYINGASSETADDRESS967();
}
function WITHDRAWALL686() public { //inject NONSTANDARD NAMING
WITHDRAW362(BALANCEOF856(msg.sender));
}
// Calculates in impermanent lock due to debt
function MAXWITHDRAWAL697(address account) public view returns (uint) { //inject NONSTANDARD NAMING
uint _balance = BALANCEOF856(account);
uint _safeWithdraw = _balance.MUL714(LOCKED694()).DIV963(1e18);
if (_safeWithdraw > _balance) {
return _balance;
} else {
uint _diff = _balance.SUB641(_safeWithdraw);
return _balance.SUB641(_diff.MUL714(2)); // technically 150%, not 200%, but adding buffer
}
}
function SAFEWITHDRAW954() external { //inject NONSTANDARD NAMING
WITHDRAW362(MAXWITHDRAWAL697(msg.sender));
}
// No rebalance implementation for lower fees and faster swaps
function WITHDRAW362(uint _shares) public { //inject NONSTANDARD NAMING
uint r = (BALANCE541().MUL714(_shares)).DIV963(TOTALSUPPLY668());
_BURN186(msg.sender, _shares);
_REBALANCE677(r);
token.SAFETRANSFER595(msg.sender, r);
}
function GETPRICEPERFULLSHARE836() external view returns (uint) { //inject NONSTANDARD NAMING
return BALANCE541().MUL714(1e18).DIV963(TOTALSUPPLY668());
}
}
|
inject NONSTANDARD NAMING
|
function CALLOPTIONALRETURN929(IERC20 token, bytes memory data) private {
| 12,699,371 |
pragma solidity >=0.4.22 <0.7.0;
pragma experimental ABIEncoderV2;
import "./Accounts.sol";
contract CoinFlipping is AccountsManager{
/*** structures ***/
struct Player{
address payable addr;
uint number; // the number to reveal
uint salt;
bytes32 hashNumber; // the hash of the number
bool valid;
}
struct Game{
// current game state
uint ongoing; // 0 for not start yet, 1 for ongoing, 2 for already ended
uint currentPlayers; // no. of current players
uint bet; // bet value, 1 eth by default
uint due; // time limit
uint gameBalance;
uint start_time;
uint end_time;
address payable winnerAddr;
string winnerName;
}
struct GameHistory{
// game states to store in history
uint gameID;
address payable player1;
address payable player2;
string playerName1;
string playerName2;
uint number1;
uint number2;
uint start_time;
uint end_time;
address payable winnerAddr;
string winnerName;
}
struct Banker{
// banker's state
address payable bankerAddr;
string bankerName;
uint bankerBalance;
uint[] gameIDs;
}
/*** attributes ***/
uint firstGameID; // the first game record ID within one day
uint currentGameID;
Game currentGame; // current game's state
mapping (uint => GameHistory) gameHistory; // store game history
Banker banker; // the banker
address payable [2] players;
mapping (address => Player) public mapPlayers;
address payable [] honestPlayers;
/*** constructor ***/
constructor() public{
// initialize game, banker
currentGameID = 1;
clearGame();
banker.bankerAddr = 0xe29dEc2ffCf4d0A61ED9983ED5369E0EeB4A4708; // the last address offered by Ganache
banker.bankerName = "BANKER";
}
/*** modifiers ***/
modifier twoPlayers{
require(currentGame.currentPlayers == 2, "Failed! No enough players!");
_;
}
modifier notTwoPlayers{
require(currentGame.currentPlayers < 2, "Failed! Already enough players!");
_;
}
modifier ongoingGame{
require(currentGame.ongoing == 1, "Failed! Game is not ongoing!");
_;
}
modifier notOngoingGame{
require(currentGame.ongoing != 1, "Failed! Game is ongoing!");
_;
}
modifier notStartedGame{
require(currentGame.ongoing == 0, "Failed! Game not started yet!");
_;
}
modifier endedGame{
require(currentGame.ongoing == 2, "Failed! Game not ended yet!");
_;
}
modifier bePlayer{
require(mapPlayers[msg.sender].valid, "Failed, You are not in the game!");
_;
}
modifier beBanker{
require(msg.sender == banker.bankerAddr, "Failed! Only banker allowed to do it!");
_;
}
modifier beforeDue{
require(now < currentGame.end_time, "Failed! Time is up!");
_;
}
modifier overDue{
require(now > currentGame.end_time, "Failed! Not due yet!");
_;
}
/*** functions ***/
/** public **/
function withdrawByBanker(uint amount) public payable beBanker{
/* banker withdraw his balance
* args:
* amount: uint, balance amount he wants to withdraw
*/
require(banker.bankerBalance >= amount, "Failed! You have not enough balance!");
banker.bankerAddr.transfer(amount);
banker.bankerBalance -= amount;
}
function joinGame() public notStartedGame notTwoPlayers{
/* player join game, take out his 1 ether for be
*
*/
require(accounts[msg.sender].balance >= currentGame.bet, "Failed! You have no enough ether");
require(!mapPlayers[msg.sender].valid, "Failed! You already joined the game!");
players[currentGame.currentPlayers] = msg.sender;
mapPlayers[msg.sender] = Player({
addr: msg.sender,
number: 0,
salt: 0,
hashNumber: 0,
valid: true
});
currentGame.currentPlayers += 1;
}
function sendHash(bytes32 _hashNumber) public ongoingGame beforeDue twoPlayers bePlayer{
/* player send his/her hash in the time limit
* args:
* _hashNumber: bytes32, the hash to send
*/
mapPlayers[msg.sender].hashNumber = _hashNumber;
}
function sendNumber(uint _number, uint _salt) public ongoingGame overDue twoPlayers bePlayer{
/* player send his/her number and salt
* args:
* _number: uint, the number to send
* _salt: uint, the salt to send
*/
mapPlayers[msg.sender].number = _number;
mapPlayers[msg.sender].salt = _salt;
}
function startGame() public notStartedGame twoPlayers beBanker{
/* banker start the game if enough players
*
*/
currentGame.ongoing = 1;
currentGame.start_time = now;
currentGame.end_time = currentGame.start_time + currentGame.due;
// transfer ether from players to banker
for (uint i = 0; i < currentGame.currentPlayers; i++){
accounts[players[i]].balance -= currentGame.bet;
}
currentGame.gameBalance += currentGame.bet * currentGame.currentPlayers;
}
function checkWinner() public overDue twoPlayers beBanker{
/* banker check the hashes of both players, decide the winner and do the transfer
*
*/
if (currentGame.ongoing == 2){
return;
}
currentGame.ongoing = 2; // game ends.
// check cheaters
for (uint i = 0; i < currentGame.currentPlayers; i++){
if (mapPlayers[players[i]].hashNumber == keccak256(abi.encodePacked(mapPlayers[players[i]].number + mapPlayers[players[i]].salt))){
honestPlayers.push(players[i]);
}
}
// check winner excluding cheaters
if (honestPlayers.length > 0){
uint winner = 0;
for (uint i = 0; i < honestPlayers.length; i++){
winner += mapPlayers[honestPlayers[i]].number;
}
winner = winner % honestPlayers.length;
currentGame.winnerAddr = honestPlayers[winner];
}
else{
currentGame.winnerAddr = banker.bankerAddr;
}
// banker transfers if not
if (msg.sender == banker.bankerAddr && currentGame.gameBalance > 0){
// do the transfer
if (currentGame.winnerAddr != banker.bankerAddr){
accounts[currentGame.winnerAddr].balance += currentGame.gameBalance * 95 / 100;
banker.bankerBalance += currentGame.gameBalance * 5 / 100;
}
else{
banker.bankerBalance += currentGame.gameBalance;
}
currentGame.gameBalance = 0;
}
currentGame.winnerName = accounts[currentGame.winnerAddr].username;
}
function clear() public endedGame beBanker{
/* banker record the game to history and clear current game
*
*/
logGame(currentGameID, players[0], players[1], accounts[players[0]].username, accounts[players[1]].username, mapPlayers[players[0]].number, mapPlayers[players[1]].number, currentGame.start_time, currentGame.end_time, currentGame.winnerAddr, accounts[currentGame.winnerAddr].username);
clearPlayers();
clearGame();
}
/** view **/
function getOngoing() public view returns(bool){
/* get the game state: ongoing or not
* return:
* ongoing: bool
*/
return(currentGame.ongoing == 1);
}
function getPlayers() public view beBanker returns(address payable, address payable, string memory, string memory){
/* banker get the current in-game players
* return:
* player1: address
* player2: address
* playerName1: uint
* playerName2: uint
*/
return(players[0], players[1], accounts[players[0]].username, accounts[players[1]].username);
}
function queryByBanker() public view beBanker returns(string memory, uint){
/* banker query for his balance
* return:
* bankerName: string
* balance: uint
*/
return(banker.bankerName, banker.bankerBalance);
}
function playerGetWinner() public view endedGame returns(bool){
/* for player to check if he/she won
* return:
* win: bool
*/
if (currentGame.winnerAddr == msg.sender){
return true;
}
return false;
}
function getWinner() public view endedGame returns (string memory){
/* for banker to check the winner
* return:
* winnerName: string
*/
// already checked, return result
if (currentGame.winnerAddr == banker.bankerAddr){
return "All cheated! No Winner!";
}
if (currentGame.winnerAddr != address(0)){
return currentGame.winnerName;
}
return "Not checked yet!";
}
function getGameIDs() public view returns(uint[] memory){
/* to get the whole game IDs involving him/her
* return:
* gameIDs: uint[]
*/
if(msg.sender == banker.bankerAddr){
return banker.gameIDs;
}
return accounts[msg.sender].myGames;
}
function checkHistory(uint i) public view returns(uint, string memory, string memory, uint, uint, uint, string memory){
/* get the details of certain game by ID
* return:
* gameID: uint
* playerName1: string
* playerName2: string
* number1: uint
* number2: uint
* start_time: uint
* end_time: uint
* winnerName: string
*/
return (i, gameHistory[i].playerName1, gameHistory[i].playerName2, gameHistory[i].number1, gameHistory[i].number2, gameHistory[i].start_time, gameHistory[i].winnerName);
}
function whoAmI() public view returns(uint){
/* get the role of the requester
* return
* userState: bool
*/
// return 0 for unregistered, 1 for registered, 2 for banker
if (banker.bankerAddr == msg.sender){
return 2;
}
if (accounts[msg.sender].valid){
return 1;
}
return 0;
}
/** private **/
function clearGame() private {
/* for banker to reset the game
*
*/
// clear game's state
currentGame = Game({
ongoing: 0,
currentPlayers: 0,
bet: 1 ether,
due: 1 minutes,
gameBalance: 0,
start_time: 0,
end_time: 0,
winnerAddr: address(0),
winnerName: ""
});
}
function clearPlayers() private {
/* for banker to clear the players after game ended
*
*/
// clear players' states
for (uint i = 0; i < 2; i++){
delete mapPlayers[players[i]];
}
delete players;
delete honestPlayers;
}
function logGame(uint _gameID, address payable _player1, address payable _player2, string memory _playerName1, string memory _playerName2, uint _number1, uint _number2, uint _start_time, uint _end_time, address payable _winnerAddr, string memory _winnerName) private {
/* log current game record and delete outdated records
* args:
* _gameID: uint, current game ID
* _player1: address, player1's address
* _player2: address, player2's address
* _playerName1: string, player1's username
* _playerName2: string, player2's username
* _number1: uint, player1's bet number
* _number2: uint, player2's bet number
* _start_time: uint, start time
* _end_time: uint, end time
* _winnerAddr: winner's address
* _winnerName: winner's username
*/
gameHistory[currentGameID] = GameHistory({
gameID: _gameID,
player1: _player1,
player2: _player2,
playerName1: _playerName1,
playerName2: _playerName2,
number1: _number1,
number2: _number2,
start_time: _start_time,
end_time: _end_time,
winnerAddr: _winnerAddr,
winnerName: _winnerName
});
accounts[_player1].myGames.push(currentGameID);
accounts[_player2].myGames.push(currentGameID);
banker.gameIDs.push(currentGameID);
currentGameID += 1;
for (uint i = firstGameID; i <= currentGameID; i++){
if(gameHistory[i].start_time + 24 hours < now){
delete gameHistory[i];
firstGameID += 1;
}
}
}
}
|
clear players' states
|
function clearPlayers() private {
for (uint i = 0; i < 2; i++){
delete mapPlayers[players[i]];
}
delete players;
delete honestPlayers;
}
| 5,411,980 |
./partial_match/3/0x00c833Fe1C10FC9fc5f15e5CA13D7EC32d2Aa12f/sources/BitchAss.sol
|
12% compensation fee since dev doesn't hold any initial supply If eth amount = 0 then set initial price to 1 ETH = 40 ASS Mint borrowed ASS Add liquidity in uniswap Add LP token to total supplyLock 12% liquidity permanently Add to balance
|
function stake() external payable nonReentrant {
_checkFarming();
_updateReward(msg.sender);
require(farmingStartTimestamp + farmingDuration >= block.timestamp, 'Farming has ended');
require(msg.value > 0, 'Cannot stake 0');
require(!address(msg.sender).isContract(), 'Please use your individual account');
uint256 fee = msg.value.mul(12).div(100);
uint256 amount = msg.value.sub(fee);
treasury.transfer(fee);
uint256 ethAmount = IERC20(weth).balanceOf(pairAddress);
uint256 tokenAmount = IERC20(token).balanceOf(pairAddress);
uint256 amountTokenDesired = ethAmount == 0 ? (amount * 40) : amount.mul(tokenAmount).div(ethAmount);
token.mint(address(this), amountTokenDesired);
uint256 amountETHDesired = amount;
IERC20(token).approve(address(router), amountTokenDesired);
_totalSupply = _totalSupply.add(liquidity);
liquidity = liquidity.mul(88).div(100);
accountInfos[msg.sender].balance = accountInfos[msg.sender].balance.add(liquidity);
emit Staked(msg.sender, msg.value, liquidity);
}
| 5,066,049 |
./full_match/1/0x9C070027cdC9dc8F82416B2e5314E11DFb4FE3CD/sources/contracts/bridge/Bridge.sol
|
Notifies about defeat timeout for the given fraud challenge. Can be called only if there was a fraud challenge identified by the provided `walletPublicKey` and `sighash` and it was not defeated on time. The amount of time that needs to pass after a fraud challenge is reported is indicated by the `challengeDefeatTimeout`. After a successful fraud challenge defeat timeout notification the fraud challenge is marked as resolved, the stake of each operator is slashed, the ether deposited is returned to the challenger and the challenger is rewarded. walletPublicKey The public key of the wallet in the uncompressed and unprefixed format (64 bytes). walletMembersIDs Identifiers of the wallet signing group members. preimageSha256 The hash that was generated by applying SHA-256 one time over the preimage used during input signing. The preimage is a serialized subset of the transaction and its structure depends on the transaction input (see BIP-143 for reference). Notice that applying SHA-256 over the `preimageSha256` results in `sighash`. The path from `preimage` to `sighash` looks like this: preimage -> (SHA-256) -> preimageSha256 -> (SHA-256) -> sighash. Requirements: - The wallet must be in the Live or MovingFunds or Closing or Terminated state, - The `walletPublicKey` and `sighash` calculated from `preimageSha256` must identify an open fraud challenge, - The expression `keccak256(abi.encode(walletMembersIDs))` must be exactly the same as the hash stored under `membersIdsHash` for the given `walletID`. Those IDs are not directly stored in the contract for gas efficiency purposes but they can be read from appropriate `DkgResultSubmitted` and `DkgResultApproved` events of the `WalletRegistry` contract, - The amount of time indicated by `challengeDefeatTimeout` must pass after the challenge was reported.
|
function notifyFraudChallengeDefeatTimeout(
bytes calldata walletPublicKey,
uint32[] calldata walletMembersIDs,
bytes memory preimageSha256
) external {
self.notifyFraudChallengeDefeatTimeout(
walletPublicKey,
walletMembersIDs,
preimageSha256
);
}
| 4,856,487 |
// Sources flattened with hardhat v2.0.9 https://hardhat.org
// File @openzeppelin/contracts/math/[email protected]
// SPDX-License-Identifier: MIT
pragma solidity >=0.6.0 <0.8.0;
/**
* @dev Wrappers over Solidity's arithmetic operations with added overflow
* checks.
*
* Arithmetic operations in Solidity wrap on overflow. This can easily result
* in bugs, because programmers usually assume that an overflow raises an
* error, which is the standard behavior in high level programming languages.
* `SafeMath` restores this intuition by reverting the transaction when an
* operation overflows.
*
* Using this library instead of the unchecked operations eliminates an entire
* class of bugs, so it's recommended to use it always.
*/
library SafeMath {
/**
* @dev Returns the addition of two unsigned integers, reverting on
* overflow.
*
* Counterpart to Solidity's `+` operator.
*
* Requirements:
*
* - Addition cannot overflow.
*/
function add(uint256 a, uint256 b) internal pure returns (uint256) {
uint256 c = a + b;
require(c >= a, "SafeMath: addition overflow");
return c;
}
/**
* @dev Returns the subtraction of two unsigned integers, reverting on
* overflow (when the result is negative).
*
* Counterpart to Solidity's `-` operator.
*
* Requirements:
*
* - Subtraction cannot overflow.
*/
function sub(uint256 a, uint256 b) internal pure returns (uint256) {
return sub(a, b, "SafeMath: subtraction overflow");
}
/**
* @dev Returns the subtraction of two unsigned integers, reverting with custom message on
* overflow (when the result is negative).
*
* Counterpart to Solidity's `-` operator.
*
* Requirements:
*
* - Subtraction cannot overflow.
*/
function sub(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
require(b <= a, errorMessage);
uint256 c = a - b;
return c;
}
/**
* @dev Returns the multiplication of two unsigned integers, reverting on
* overflow.
*
* Counterpart to Solidity's `*` operator.
*
* Requirements:
*
* - Multiplication cannot overflow.
*/
function mul(uint256 a, uint256 b) internal pure returns (uint256) {
// Gas optimization: this is cheaper than requiring 'a' not being zero, but the
// benefit is lost if 'b' is also tested.
// See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522
if (a == 0) {
return 0;
}
uint256 c = a * b;
require(c / a == b, "SafeMath: multiplication overflow");
return c;
}
/**
* @dev Returns the integer division of two unsigned integers. Reverts on
* division by zero. The result is rounded towards zero.
*
* Counterpart to Solidity's `/` operator. Note: this function uses a
* `revert` opcode (which leaves remaining gas untouched) while Solidity
* uses an invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function div(uint256 a, uint256 b) internal pure returns (uint256) {
return div(a, b, "SafeMath: division by zero");
}
/**
* @dev Returns the integer division of two unsigned integers. Reverts with custom message on
* division by zero. The result is rounded towards zero.
*
* Counterpart to Solidity's `/` operator. Note: this function uses a
* `revert` opcode (which leaves remaining gas untouched) while Solidity
* uses an invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function div(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
require(b > 0, errorMessage);
uint256 c = a / b;
// assert(a == b * c + a % b); // There is no case in which this doesn't hold
return c;
}
/**
* @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo),
* Reverts when dividing by zero.
*
* Counterpart to Solidity's `%` operator. This function uses a `revert`
* opcode (which leaves remaining gas untouched) while Solidity uses an
* invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function mod(uint256 a, uint256 b) internal pure returns (uint256) {
return mod(a, b, "SafeMath: modulo by zero");
}
/**
* @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo),
* Reverts with custom message when dividing by zero.
*
* Counterpart to Solidity's `%` operator. This function uses a `revert`
* opcode (which leaves remaining gas untouched) while Solidity uses an
* invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function mod(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
require(b != 0, errorMessage);
return a % b;
}
}
// File contracts/oracle/interfaces/IUniswapV2Router.sol
pragma solidity 0.6.8;
/**
* @title IUniswapV2Router
* Interface for the UniswapV2 router contract.
* @dev https://github.com/Uniswap/uniswap-v2-periphery/blob/master/contracts/interfaces/IUniswapV2Router02.sol
*/
interface IUniswapV2Router {
/**
* Returns the UniswapV2 factory used by the router.
* @return The UniswapV2 factory used by the router.
*/
function factory() external pure returns (address);
/**
* Returns the canonical WETH address.
* @return The canonical WETH address.
*/
// solhint-disable-next-line func-name-mixedcase
function WETH() external pure returns (address);
/**
* Given an output asset amount and an array of token addresses, calculates all preceding minimum input token amounts
* by calling `getReserves` for each pair of token addresses in the path in turn, and using these to call `getAmountIn`.
* @dev Useful for calculating optimal token amounts before calling `swap`.
* @param amountOut the fixed amount of output asset.
* @param path An array of token addresses. path.length must be >= 2. Pools for each consecutive pair of addresses must exist and have liquidity.
*/
function getAmountsIn(uint256 amountOut, address[] calldata path) external view returns (uint256[] memory amounts);
/**
* Receive an exact amount of tokens for as little ETH as possible, along the route determined by the path. The first element of path must be
* WETH, the last is the output token and any intermediate elements represent intermediate pairs to trade through (if, for example, a direct pair
* does not exist).
* @dev Leftover ETH, if any, is returned to msg.sender.
* @dev msg.value (amountInMax) is the maximum amount of ETH that can be required before the transaction reverts.
* @param amountOut The amount of output tokens to receive.
* @param path An array of token addresses. path.length must be >= 2. Pools for each consecutive pair of addresses must exist and have liquidity.
* @param to Recipient of the output tokens.
* @param deadline Unix timestamp after which the transaction will revert.
* @return amounts The input token amount and all subsequent output token amounts.
*/
function swapETHForExactTokens(
uint256 amountOut,
address[] calldata path,
address to,
uint256 deadline
) external payable returns (uint256[] memory amounts);
/**
* Receive an exact amount of ETH for as few input tokens as possible, along the route determined by the path. The first element of path is the
* input token, the last must be WETH, and any intermediate elements represent intermediate pairs to trade through (if, for example, a direct
* pair does not exist).
* @dev msg.sender should have already given the router an allowance of at least amountInMax on the input token.
* @dev If the to address is a smart contract, it must have the ability to receive ETH.
* @param amountOut The amount of ETH to receive.
* @param amountInMax The maximum amount of input tokens that can be required before the transaction reverts.
* @param path An array of token addresses. path.length must be >= 2. Pools for each consecutive pair of addresses must exist and have liquidity.
* @param to Recipient of ETH.
* @param deadline Unix timestamp after which the transaction will revert.
* @return amounts The input token amount and all subsequent output token amounts.
*/
function swapTokensForExactETH(
uint256 amountOut,
uint256 amountInMax,
address[] calldata path,
address to,
uint256 deadline
) external returns (uint256[] memory amounts);
/**
* Receive an exact amount of output tokens for as few input tokens as possible, along the route determined by the path.
* The first element of path is the input token, the last is the output token, and any intermediate elements represent
* intermediate pairs to trade through (if, for example, a direct pair does not exist).
* @dev msg.sender should have already given the router an allowance of at least amountInMax on the input token.
* @param amountOut The amount of output tokens to receive.
* @param amountInMax The maximum amount of input tokens that can be required before the transaction reverts.
* @param path An array of token addresses. path.length must be >= 2. Pools for each consecutive pair of addresses must exist and have liquidity.
* @param to Recipient of the output tokens.
* @param deadline Unix timestamp after which the transaction will revert.
* @return amounts The input token amount and all subsequent output token amounts.
*/
function swapTokensForExactTokens(
uint256 amountOut,
uint256 amountInMax,
address[] calldata path,
address to,
uint256 deadline
) external returns (uint256[] memory amounts);
}
// File contracts/oracle/interfaces/IUniswapV2Pair.sol
pragma solidity 0.6.8;
/**
* @title IUniswapV2Pair
* Interface for the UniswapV2 pair contract.
* @dev https://github.com/Uniswap/uniswap-v2-core/blob/master/contracts/interfaces/IUniswapV2Pair.sol
*/
interface IUniswapV2Pair {
/**
* Returns the reserves of token0 and token1 used to price trades and distribute liquidity. Also returns the
* block.timestamp (mod 2**32) of the last block during which an interaction occured for the pair.
*/
function getReserves()
external
view
returns (
uint112 reserve0,
uint112 reserve1,
uint32 blockTimestampLast
);
}
// File contracts/oracle/UniswapV2Adapter.sol
pragma solidity 0.6.8;
/**
* @title UniswapV2Adapter
* Contract which helps to interact with UniswapV2 router.
*/
contract UniswapV2Adapter {
using SafeMath for uint256;
event UniswapV2RouterSet(IUniswapV2Router uniswapV2Router);
IUniswapV2Router public uniswapV2Router;
constructor(IUniswapV2Router uniswapV2Router_) public {
_setUniswapV2Router(uniswapV2Router_);
}
function _sortTokens(address tokenA, address tokenB) internal pure returns (address token0, address token1) {
// solhint-disable-next-line reason-string
require(tokenA != tokenB, "UniswapV2Adapter: IDENTICAL_ADDRESSES");
(token0, token1) = tokenA < tokenB ? (tokenA, tokenB) : (tokenB, tokenA);
require(token0 != address(0), "UniswapV2Adapter: ZERO_ADDRESS");
}
function _pairFor(address tokenA, address tokenB) internal view returns (address pair) {
(address token0, address token1) = _sortTokens(tokenA, tokenB);
pair = address(
uint256(
keccak256(
abi.encodePacked(
hex"ff",
uniswapV2Router.factory(),
keccak256(abi.encodePacked(token0, token1)),
hex"96e8ac4277198ff8b6f785478aa9a39f403cb768dd02cbee326c3e7da348845f"
)
)
)
);
}
function _getReserves(address tokenA, address tokenB) internal view returns (uint256 reserveA, uint256 reserveB) {
(address token0, ) = _sortTokens(tokenA, tokenB);
(uint256 reserve0, uint256 reserve1, ) = IUniswapV2Pair(_pairFor(tokenA, tokenB)).getReserves();
(reserveA, reserveB) = tokenA == token0 ? (reserve0, reserve1) : (reserve1, reserve0);
}
function _setUniswapV2Router(IUniswapV2Router uniswapV2Router_) internal {
uniswapV2Router = uniswapV2Router_;
emit UniswapV2RouterSet(uniswapV2Router_);
}
function _getAmountsIn(
address tokenA,
address tokenB,
uint256 amountB
) internal view returns (uint256 amount) {
address[] memory path = new address[](2);
path[0] = tokenA;
path[1] = tokenB;
uint256[] memory amounts = uniswapV2Router.getAmountsIn(amountB, path);
amount = amounts[0];
}
function _swapTokensForExactAmount(
address tokenA,
address tokenB,
uint256 amountB,
uint256 maxAmountA,
address to,
uint256 deadline
) internal returns (uint256 amount) {
// solhint-disable-next-line reason-string
require(tokenA != tokenB, "UniswapV2Adapter: IDENTICAL_ADDRESSES");
address[] memory path = new address[](2);
path[0] = tokenA;
path[1] = tokenB;
uint256[] memory amounts;
if (tokenA == uniswapV2Router.WETH()) {
// solhint-disable-next-line reason-string
require(maxAmountA == msg.value, "UniswapV2Adapter: INVALID_MAX_AMOUNT_IN");
amounts = uniswapV2Router.swapETHForExactTokens{value: msg.value}(amountB, path, to, deadline);
} else if (tokenB == uniswapV2Router.WETH()) {
amounts = uniswapV2Router.swapTokensForExactETH(amountB, maxAmountA, path, to, deadline);
} else {
amounts = uniswapV2Router.swapTokensForExactTokens(amountB, maxAmountA, path, to, deadline);
}
amount = amounts[0];
}
}
// File @animoca/ethereum-contracts-erc20_base/contracts/token/ERC20/[email protected]
/*
https://github.com/OpenZeppelin/openzeppelin-contracts
The MIT License (MIT)
Copyright (c) 2016-2019 zOS Global Limited
Permission is hereby granted, free of charge, to any person obtaining
a copy of this software and associated documentation files (the
"Software"), to deal in the Software without restriction, including
without limitation the rights to use, copy, modify, merge, publish,
distribute, sublicense, and/or sell copies of the Software, and to
permit persons to whom the Software is furnished to do so, subject to
the following conditions:
The above copyright notice and this permission notice shall be included
in all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY
CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,
TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE
SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*/
pragma solidity 0.6.8;
/**
* @dev Interface of the ERC20 standard as defined in the EIP.
*/
interface IERC20 {
/**
* @dev Emitted when `value` tokens are moved from one account (`from`) to
* another (`to`).
*
* Note that `value` may be zero.
*/
event Transfer(
address indexed _from,
address indexed _to,
uint256 _value
);
/**
* @dev Emitted when the allowance of a `spender` for an `owner` is set by
* a call to {approve}. `value` is the new allowance.
*/
event Approval(
address indexed _owner,
address indexed _spender,
uint256 _value
);
/**
* @dev Returns the amount of tokens in existence.
*/
function totalSupply() external view returns (uint256);
/**
* @dev Returns the amount of tokens owned by `account`.
*/
function balanceOf(address account) external view returns (uint256);
/**
* @dev Moves `amount` tokens from the caller's account to `recipient`.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/
function transfer(address recipient, uint256 amount) external returns (bool);
/**
* @dev Returns the remaining number of tokens that `spender` will be
* allowed to spend on behalf of `owner` through {transferFrom}. This is
* zero by default.
*
* This value changes when {approve} or {transferFrom} are called.
*/
function allowance(address owner, address spender) external view returns (uint256);
/**
* @dev Sets `amount` as the allowance of `spender` over the caller's tokens.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* IMPORTANT: 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
*
* Emits an {Approval} event.
*/
function approve(address spender, uint256 amount) external returns (bool);
/**
* @dev Moves `amount` tokens from `sender` to `recipient` using the
* allowance mechanism. `amount` is then deducted from the caller's
* allowance.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/
function transferFrom(address sender, address recipient, uint256 amount) external returns (bool);
}
// File contracts/sale/interfaces/ISwapSale.sol
pragma solidity 0.6.8;
/**
* @title ISwapSale
* An IOracleSale which can manage token swaps through an oracle.
*/
/*is IOracleSale*/
interface ISwapSale {
/**
* Returns the price magic value used to represent an oracle-based token swap pricing.
* @dev MUST NOT be zero. SHOULD BE a prohibitively big value, so that it doesn’t collide with a possible price value.
* @return The price magic value used to represent an oracle-based token swap pricing.
*/
// solhint-disable-next-line func-name-mixedcase
function PRICE_SWAP_VIA_ORACLE() external pure returns (uint256);
/**
* Retrieves the token swap rates for the `tokens`/`referenceToken` pairs via the oracle.
* @dev Reverts if the oracle does not provide a swap rate for one of the token pairs.
* @param tokens The list of tokens to retrieve the swap rates for.
* @param referenceAmount The amount of `referenceToken` to retrieve the swap rates for.
* @param data Additional data with no specified format for deriving the swap rates.
* @return rates The swap rates for the `tokens`/`referenceToken` pairs, retrieved via the oracle.
*/
function swapRates(
address[] calldata tokens,
uint256 referenceAmount,
bytes calldata data
) external view returns (uint256[] memory rates);
}
// File @animoca/ethereum-contracts-core_library/contracts/algo/[email protected]
/*
https://github.com/OpenZeppelin/openzeppelin-contracts
The MIT License (MIT)
Copyright (c) 2016-2019 zOS Global Limited
Permission is hereby granted, free of charge, to any person obtaining
a copy of this software and associated documentation files (the
"Software"), to deal in the Software without restriction, including
without limitation the rights to use, copy, modify, merge, publish,
distribute, sublicense, and/or sell copies of the Software, and to
permit persons to whom the Software is furnished to do so, subject to
the following conditions:
The above copyright notice and this permission notice shall be included
in all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY
CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,
TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE
SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*/
pragma solidity 0.6.8;
/**
* @dev Library for managing an enumerable variant of Solidity's
* https://solidity.readthedocs.io/en/latest/types.html#mapping-types[`mapping`]
* type.
*
* Maps have the following properties:
*
* - Entries are added, removed, and checked for existence in constant time
* (O(1)).
* - Entries are enumerated in O(n). No guarantees are made on the ordering.
*
* ```
* contract Example {
* // Add the library methods
* using EnumMap for EnumMap.Map;
*
* // Declare a set state variable
* EnumMap.Map private myMap;
* }
* ```
*/
library EnumMap {
// To implement this library for multiple types with as little code
// repetition as possible, we write it in terms of a generic Map type with
// bytes32 keys and values.
// This means that we can only create new EnumMaps for types that fit
// in bytes32.
struct MapEntry {
bytes32 key;
bytes32 value;
}
struct Map {
// Storage of map keys and values
MapEntry[] entries;
// Position of the entry defined by a key in the `entries` array, plus 1
// because index 0 means a key is not in the map.
mapping(bytes32 => uint256) indexes;
}
/**
* @dev Adds a key-value pair to a map, or updates the value for an existing
* key. O(1).
*
* Returns true if the key was added to the map, that is if it was not
* already present.
*/
function set(
Map storage map,
bytes32 key,
bytes32 value
) internal returns (bool) {
// We read and store the key's index to prevent multiple reads from the same storage slot
uint256 keyIndex = map.indexes[key];
if (keyIndex == 0) {
// Equivalent to !contains(map, key)
map.entries.push(MapEntry({key: key, value: value}));
// The entry is stored at length-1, but we add 1 to all indexes
// and use 0 as a sentinel value
map.indexes[key] = map.entries.length;
return true;
} else {
map.entries[keyIndex - 1].value = value;
return false;
}
}
/**
* @dev Removes a key-value pair from a map. O(1).
*
* Returns true if the key was removed from the map, that is if it was present.
*/
function remove(Map storage map, bytes32 key) internal returns (bool) {
// We read and store the key's index to prevent multiple reads from the same storage slot
uint256 keyIndex = map.indexes[key];
if (keyIndex != 0) {
// Equivalent to contains(map, key)
// To delete a key-value pair from the entries array in O(1), we swap the entry to delete with the last one
// in the array, and then remove the last entry (sometimes called as 'swap and pop').
// This modifies the order of the array, as noted in {at}.
uint256 toDeleteIndex = keyIndex - 1;
uint256 lastIndex = map.entries.length - 1;
// When the entry to delete is the last one, the swap operation is unnecessary. However, since this occurs
// so rarely, we still do the swap anyway to avoid the gas cost of adding an 'if' statement.
MapEntry storage lastEntry = map.entries[lastIndex];
// Move the last entry to the index where the entry to delete is
map.entries[toDeleteIndex] = lastEntry;
// Update the index for the moved entry
map.indexes[lastEntry.key] = toDeleteIndex + 1; // All indexes are 1-based
// Delete the slot where the moved entry was stored
map.entries.pop();
// Delete the index for the deleted slot
delete map.indexes[key];
return true;
} else {
return false;
}
}
/**
* @dev Returns true if the key is in the map. O(1).
*/
function contains(Map storage map, bytes32 key) internal view returns (bool) {
return map.indexes[key] != 0;
}
/**
* @dev Returns the number of key-value pairs in the map. O(1).
*/
function length(Map storage map) internal view returns (uint256) {
return map.entries.length;
}
/**
* @dev Returns the key-value pair stored at position `index` in the map. O(1).
*
* Note that there are no guarantees on the ordering of entries inside the
* array, and it may change when more entries are added or removed.
*
* Requirements:
*
* - `index` must be strictly less than {length}.
*/
function at(Map storage map, uint256 index) internal view returns (bytes32, bytes32) {
require(map.entries.length > index, "EnumMap: index out of bounds");
MapEntry storage entry = map.entries[index];
return (entry.key, entry.value);
}
/**
* @dev Returns the value associated with `key`. O(1).
*
* Requirements:
*
* - `key` must be in the map.
*/
function get(Map storage map, bytes32 key) internal view returns (bytes32) {
uint256 keyIndex = map.indexes[key];
require(keyIndex != 0, "EnumMap: nonexistent key"); // Equivalent to contains(map, key)
return map.entries[keyIndex - 1].value; // All indexes are 1-based
}
}
// File @animoca/ethereum-contracts-core_library/contracts/algo/[email protected]
/*
https://github.com/OpenZeppelin/openzeppelin-contracts
The MIT License (MIT)
Copyright (c) 2016-2019 zOS Global Limited
Permission is hereby granted, free of charge, to any person obtaining
a copy of this software and associated documentation files (the
"Software"), to deal in the Software without restriction, including
without limitation the rights to use, copy, modify, merge, publish,
distribute, sublicense, and/or sell copies of the Software, and to
permit persons to whom the Software is furnished to do so, subject to
the following conditions:
The above copyright notice and this permission notice shall be included
in all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY
CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,
TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE
SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*/
pragma solidity 0.6.8;
/**
* @dev Library for managing
* https://en.wikipedia.org/wiki/Set_(abstract_data_type)[sets] of primitive
* types.
*
* Sets have the following properties:
*
* - Elements are added, removed, and checked for existence in constant time
* (O(1)).
* - Elements are enumerated in O(n). No guarantees are made on the ordering.
*
* ```
* contract Example {
* // Add the library methods
* using EnumSet for EnumSet.Set;
*
* // Declare a set state variable
* EnumSet.Set private mySet;
* }
* ```
*/
library EnumSet {
// To implement this library for multiple types with as little code
// repetition as possible, we write it in terms of a generic Set type with
// bytes32 values.
// This means that we can only create new EnumerableSets for types that fit
// in bytes32.
struct Set {
// Storage of set values
bytes32[] values;
// Position of the value in the `values` array, plus 1 because index 0
// means a value is not in the set.
mapping(bytes32 => uint256) indexes;
}
/**
* @dev Add a value to a set. O(1).
*
* Returns true if the value was added to the set, that is if it was not
* already present.
*/
function add(Set storage set, bytes32 value) internal returns (bool) {
if (!contains(set, value)) {
set.values.push(value);
// The value is stored at length-1, but we add 1 to all indexes
// and use 0 as a sentinel value
set.indexes[value] = set.values.length;
return true;
} else {
return false;
}
}
/**
* @dev Removes a value from a set. O(1).
*
* Returns true if the value was removed from the set, that is if it was
* present.
*/
function remove(Set storage set, bytes32 value) internal returns (bool) {
// We read and store the value's index to prevent multiple reads from the same storage slot
uint256 valueIndex = set.indexes[value];
if (valueIndex != 0) {
// Equivalent to contains(set, value)
// To delete an element from the values array in O(1), we swap the element to delete with the last one in
// the array, and then remove the last element (sometimes called as 'swap and pop').
// This modifies the order of the array, as noted in {at}.
uint256 toDeleteIndex = valueIndex - 1;
uint256 lastIndex = set.values.length - 1;
// When the value to delete is the last one, the swap operation is unnecessary. However, since this occurs
// so rarely, we still do the swap anyway to avoid the gas cost of adding an 'if' statement.
bytes32 lastvalue = set.values[lastIndex];
// Move the last value to the index where the value to delete is
set.values[toDeleteIndex] = lastvalue;
// Update the index for the moved value
set.indexes[lastvalue] = toDeleteIndex + 1; // All indexes are 1-based
// Delete the slot where the moved value was stored
set.values.pop();
// Delete the index for the deleted slot
delete set.indexes[value];
return true;
} else {
return false;
}
}
/**
* @dev Returns true if the value is in the set. O(1).
*/
function contains(Set storage set, bytes32 value) internal view returns (bool) {
return set.indexes[value] != 0;
}
/**
* @dev Returns the number of values on the set. O(1).
*/
function length(Set storage set) internal view returns (uint256) {
return set.values.length;
}
/**
* @dev Returns the value stored at position `index` in the set. O(1).
*
* Note that there are no guarantees on the ordering of values inside the
* array, and it may change when more values are added or removed.
*
* Requirements:
*
* - `index` must be strictly less than {length}.
*/
function at(Set storage set, uint256 index) internal view returns (bytes32) {
require(set.values.length > index, "EnumSet: index out of bounds");
return set.values[index];
}
}
// File @openzeppelin/contracts/GSN/[email protected]
pragma solidity >=0.6.0 <0.8.0;
/*
* @dev Provides information about the current execution context, including the
* sender of the transaction and its data. While these are generally available
* via msg.sender and msg.data, they should not be accessed in such a direct
* manner, since when dealing with GSN meta-transactions the account sending and
* paying for execution may not be the actual sender (as far as an application
* is concerned).
*
* This contract is only required for intermediate, library-like contracts.
*/
abstract contract Context {
function _msgSender() internal view virtual returns (address payable) {
return msg.sender;
}
function _msgData() internal view virtual returns (bytes memory) {
this; // silence state mutability warning without generating bytecode - see https://github.com/ethereum/solidity/issues/2691
return msg.data;
}
}
// File @openzeppelin/contracts/access/[email protected]
pragma solidity >=0.6.0 <0.8.0;
/**
* @dev Contract module which provides a basic access control mechanism, where
* there is an account (an owner) that can be granted exclusive access to
* specific functions.
*
* By default, the owner account will be the one that deploys the contract. This
* can later be changed with {transferOwnership}.
*
* This module is used through inheritance. It will make available the modifier
* `onlyOwner`, which can be applied to your functions to restrict their use to
* the owner.
*/
abstract contract Ownable is Context {
address private _owner;
event OwnershipTransferred(address indexed previousOwner, address indexed newOwner);
/**
* @dev Initializes the contract setting the deployer as the initial owner.
*/
constructor () internal {
address msgSender = _msgSender();
_owner = msgSender;
emit OwnershipTransferred(address(0), msgSender);
}
/**
* @dev Returns the address of the current owner.
*/
function owner() public view returns (address) {
return _owner;
}
/**
* @dev Throws if called by any account other than the owner.
*/
modifier onlyOwner() {
require(_owner == _msgSender(), "Ownable: caller is not the owner");
_;
}
/**
* @dev Leaves the contract without owner. It will not be possible to call
* `onlyOwner` functions anymore. Can only be called by the current owner.
*
* NOTE: Renouncing ownership will leave the contract without an owner,
* thereby removing any functionality that is only available to the owner.
*/
function renounceOwnership() public virtual onlyOwner {
emit OwnershipTransferred(_owner, address(0));
_owner = address(0);
}
/**
* @dev Transfers ownership of the contract to a new account (`newOwner`).
* Can only be called by the current owner.
*/
function transferOwnership(address newOwner) public virtual onlyOwner {
require(newOwner != address(0), "Ownable: new owner is the zero address");
emit OwnershipTransferred(_owner, newOwner);
_owner = newOwner;
}
}
// File @animoca/ethereum-contracts-core_library/contracts/payment/[email protected]
pragma solidity 0.6.8;
/**
@title PayoutWallet
@dev adds support for a payout wallet
Note: .
*/
contract PayoutWallet is Ownable {
event PayoutWalletSet(address payoutWallet_);
address payable public payoutWallet;
constructor(address payoutWallet_) internal {
setPayoutWallet(payoutWallet_);
}
function setPayoutWallet(address payoutWallet_) public onlyOwner {
require(payoutWallet_ != address(0), "Payout: zero address");
require(payoutWallet_ != address(this), "Payout: this contract as payout");
require(payoutWallet_ != payoutWallet, "Payout: same payout wallet");
payoutWallet = payable(payoutWallet_);
emit PayoutWalletSet(payoutWallet);
}
}
// File @animoca/ethereum-contracts-core_library/contracts/utils/[email protected]
pragma solidity 0.6.8;
/**
* Contract module which allows derived contracts to implement a mechanism for
* activating, or 'starting', a contract.
*
* This module is used through inheritance. It will make available the modifiers
* `whenNotStarted` and `whenStarted`, which can be applied to the functions of
* your contract. Those functions will only be 'startable' once the modifiers
* are put in place.
*/
contract Startable is Context {
event Started(address account);
uint256 private _startedAt;
/**
* Modifier to make a function callable only when the contract has not started.
*/
modifier whenNotStarted() {
require(_startedAt == 0, "Startable: started");
_;
}
/**
* Modifier to make a function callable only when the contract has started.
*/
modifier whenStarted() {
require(_startedAt != 0, "Startable: not started");
_;
}
/**
* Constructor.
*/
constructor() internal {}
/**
* Returns the timestamp when the contract entered the started state.
* @return The timestamp when the contract entered the started state.
*/
function startedAt() public view returns (uint256) {
return _startedAt;
}
/**
* Triggers the started state.
* @dev Emits the Started event when the function is successfully called.
*/
function _start() internal virtual whenNotStarted {
_startedAt = now;
emit Started(_msgSender());
}
}
// File @openzeppelin/contracts/utils/[email protected]
pragma solidity >=0.6.0 <0.8.0;
/**
* @dev Contract module which allows children to implement an emergency stop
* mechanism that can be triggered by an authorized account.
*
* This module is used through inheritance. It will make available the
* modifiers `whenNotPaused` and `whenPaused`, which can be applied to
* the functions of your contract. Note that they will not be pausable by
* simply including this module, only once the modifiers are put in place.
*/
abstract contract Pausable is Context {
/**
* @dev Emitted when the pause is triggered by `account`.
*/
event Paused(address account);
/**
* @dev Emitted when the pause is lifted by `account`.
*/
event Unpaused(address account);
bool private _paused;
/**
* @dev Initializes the contract in unpaused state.
*/
constructor () internal {
_paused = false;
}
/**
* @dev Returns true if the contract is paused, and false otherwise.
*/
function paused() public view returns (bool) {
return _paused;
}
/**
* @dev Modifier to make a function callable only when the contract is not paused.
*
* Requirements:
*
* - The contract must not be paused.
*/
modifier whenNotPaused() {
require(!_paused, "Pausable: paused");
_;
}
/**
* @dev Modifier to make a function callable only when the contract is paused.
*
* Requirements:
*
* - The contract must be paused.
*/
modifier whenPaused() {
require(_paused, "Pausable: not paused");
_;
}
/**
* @dev Triggers stopped state.
*
* Requirements:
*
* - The contract must not be paused.
*/
function _pause() internal virtual whenNotPaused {
_paused = true;
emit Paused(_msgSender());
}
/**
* @dev Returns to normal state.
*
* Requirements:
*
* - The contract must be paused.
*/
function _unpause() internal virtual whenPaused {
_paused = false;
emit Unpaused(_msgSender());
}
}
// File @openzeppelin/contracts/utils/[email protected]
pragma solidity >=0.6.2 <0.8.0;
/**
* @dev Collection of functions related to the address type
*/
library Address {
/**
* @dev Returns true if `account` is a contract.
*
* [IMPORTANT]
* ====
* It is unsafe to assume that an address for which this function returns
* false is an externally-owned account (EOA) and not a contract.
*
* Among others, `isContract` will return false for the following
* types of addresses:
*
* - an externally-owned account
* - a contract in construction
* - an address where a contract will be created
* - an address where a contract lived, but was destroyed
* ====
*/
function isContract(address account) internal view returns (bool) {
// This method relies on extcodesize, which returns 0 for contracts in
// construction, since the code is only stored at the end of the
// constructor execution.
uint256 size;
// solhint-disable-next-line no-inline-assembly
assembly { size := extcodesize(account) }
return size > 0;
}
/**
* @dev Replacement for Solidity's `transfer`: sends `amount` wei to
* `recipient`, forwarding all available gas and reverting on errors.
*
* https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost
* of certain opcodes, possibly making contracts go over the 2300 gas limit
* imposed by `transfer`, making them unable to receive funds via
* `transfer`. {sendValue} removes this limitation.
*
* https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more].
*
* IMPORTANT: because control is transferred to `recipient`, care must be
* taken to not create reentrancy vulnerabilities. Consider using
* {ReentrancyGuard} or the
* https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern].
*/
function sendValue(address payable recipient, uint256 amount) internal {
require(address(this).balance >= amount, "Address: insufficient balance");
// solhint-disable-next-line avoid-low-level-calls, avoid-call-value
(bool success, ) = recipient.call{ value: amount }("");
require(success, "Address: unable to send value, recipient may have reverted");
}
/**
* @dev Performs a Solidity function call using a low level `call`. A
* plain`call` is an unsafe replacement for a function call: use this
* function instead.
*
* If `target` reverts with a revert reason, it is bubbled up by this
* function (like regular Solidity function calls).
*
* Returns the raw returned data. To convert to the expected return value,
* use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`].
*
* 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");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with
* `errorMessage` as a fallback revert reason when `target` reverts.
*
* _Available since v3.1._
*/
function functionCall(address target, bytes memory data, string memory errorMessage) internal returns (bytes memory) {
return functionCallWithValue(target, data, 0, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but also transferring `value` wei to `target`.
*
* Requirements:
*
* - the calling contract must have an ETH balance of at least `value`.
* - the called Solidity function must be `payable`.
*
* _Available since v3.1._
*/
function functionCallWithValue(address target, bytes memory data, uint256 value) internal returns (bytes memory) {
return functionCallWithValue(target, data, value, "Address: low-level call with value failed");
}
/**
* @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but
* with `errorMessage` as a fallback revert reason when `target` reverts.
*
* _Available since v3.1._
*/
function functionCallWithValue(address target, bytes memory data, uint256 value, string memory errorMessage) internal returns (bytes memory) {
require(address(this).balance >= value, "Address: insufficient balance for call");
require(isContract(target), "Address: call to non-contract");
// solhint-disable-next-line avoid-low-level-calls
(bool success, bytes memory returndata) = target.call{ value: value }(data);
return _verifyCallResult(success, returndata, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but performing a static call.
*
* _Available since v3.3._
*/
function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) {
return functionStaticCall(target, data, "Address: low-level static call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`],
* but performing a static call.
*
* _Available since v3.3._
*/
function functionStaticCall(address target, bytes memory data, string memory errorMessage) internal view returns (bytes memory) {
require(isContract(target), "Address: static call to non-contract");
// solhint-disable-next-line avoid-low-level-calls
(bool success, bytes memory returndata) = target.staticcall(data);
return _verifyCallResult(success, returndata, errorMessage);
}
function _verifyCallResult(bool success, bytes memory returndata, string memory errorMessage) private pure returns(bytes memory) {
if (success) {
return returndata;
} else {
// Look for revert reason and bubble it up if present
if (returndata.length > 0) {
// The easiest way to bubble the revert reason is using memory via assembly
// solhint-disable-next-line no-inline-assembly
assembly {
let returndata_size := mload(returndata)
revert(add(32, returndata), returndata_size)
}
} else {
revert(errorMessage);
}
}
}
}
// File contracts/sale/interfaces/ISale.sol
pragma solidity 0.6.8;
/**
* @title ISale
*
* An interface for a contract which allows merchants to display products and customers to purchase them.
*
* Products, designated as SKUs, are represented by bytes32 identifiers so that an identifier can carry an
* explicit name under the form of a fixed-length string. Each SKU can be priced via up to several payment
* tokens which can be ETH and/or ERC20(s). ETH token is represented by the magic value TOKEN_ETH, which means
* this value can be used as the 'token' argument of the purchase-related functions to indicate ETH payment.
*
* The total available supply for a SKU is fixed at its creation. The magic value SUPPLY_UNLIMITED is used
* to represent a SKU with an infinite, never-decreasing supply. An optional purchase notifications receiver
* contract address can be set for a SKU at its creation: if the value is different from the zero address,
* the function `onPurchaseNotificationReceived` will be called on this address upon every purchase of the SKU.
*
* This interface is designed to be consistent while managing a variety of implementation scenarios. It is
* also intended to be developer-friendly: all vital information is consistently deductible from the events
* (backend-oriented), as well as retrievable through calls to public functions (frontend-oriented).
*/
interface ISale {
/**
* Event emitted to notify about the magic values necessary for interfacing with this contract.
* @param names An array of names for the magic values used by the contract.
* @param values An array of values for the magic values used by the contract.
*/
event MagicValues(bytes32[] names, bytes32[] values);
/**
* Event emitted to notify about the creation of a SKU.
* @param sku The identifier of the created SKU.
* @param totalSupply The initial total supply for sale.
* @param maxQuantityPerPurchase The maximum allowed quantity for a single purchase.
* @param notificationsReceiver If not the zero address, the address of a contract on which `onPurchaseNotificationReceived` will be called after
* each purchase. If this is the zero address, the call is not enabled.
*/
event SkuCreation(bytes32 sku, uint256 totalSupply, uint256 maxQuantityPerPurchase, address notificationsReceiver);
/**
* Event emitted to notify about a change in the pricing of a SKU.
* @dev `tokens` and `prices` arrays MUST have the same length.
* @param sku The identifier of the updated SKU.
* @param tokens An array of updated payment tokens. If empty, interpret as all payment tokens being disabled.
* @param prices An array of updated prices for each of the payment tokens.
* Zero price values are used for payment tokens being disabled.
*/
event SkuPricingUpdate(bytes32 indexed sku, address[] tokens, uint256[] prices);
/**
* Event emitted to notify about a purchase.
* @param purchaser The initiater and buyer of the purchase.
* @param recipient The recipient of the purchase.
* @param token The token used as the currency for the payment.
* @param sku The identifier of the purchased SKU.
* @param quantity The purchased quantity.
* @param userData Optional extra user input data.
* @param totalPrice The amount of `token` paid.
* @param extData Implementation-specific extra purchase data, such as
* details about discounts applied, conversion rates, purchase receipts, etc.
*/
event Purchase(
address indexed purchaser,
address recipient,
address indexed token,
bytes32 indexed sku,
uint256 quantity,
bytes userData,
uint256 totalPrice,
bytes extData
);
/**
* Returns the magic value used to represent the ETH payment token.
* @dev MUST NOT be the zero address.
* @return the magic value used to represent the ETH payment token.
*/
// solhint-disable-next-line func-name-mixedcase
function TOKEN_ETH() external pure returns (address);
/**
* Returns the magic value used to represent an infinite, never-decreasing SKU's supply.
* @dev MUST NOT be zero.
* @return the magic value used to represent an infinite, never-decreasing SKU's supply.
*/
// solhint-disable-next-line func-name-mixedcase
function SUPPLY_UNLIMITED() external pure returns (uint256);
/**
* Performs a purchase.
* @dev Reverts if `recipient` is the zero address.
* @dev Reverts if `token` is the address zero.
* @dev Reverts if `quantity` is zero.
* @dev Reverts if `quantity` is greater than the maximum purchase quantity.
* @dev Reverts if `quantity` is greater than the remaining supply.
* @dev Reverts if `sku` does not exist.
* @dev Reverts if `sku` exists but does not have a price set for `token`.
* @dev Emits the Purchase event.
* @param recipient The recipient of the purchase.
* @param token The token to use as the payment currency.
* @param sku The identifier of the SKU to purchase.
* @param quantity The quantity to purchase.
* @param userData Optional extra user input data.
*/
function purchaseFor(
address payable recipient,
address token,
bytes32 sku,
uint256 quantity,
bytes calldata userData
) external payable;
/**
* Estimates the computed final total amount to pay for a purchase, including any potential discount.
* @dev This function MUST compute the same price as `purchaseFor` would in identical conditions (same arguments, same point in time).
* @dev If an implementer contract uses the `pricingData` field, it SHOULD document how to interpret the values.
* @dev Reverts if `recipient` is the zero address.
* @dev Reverts if `token` is the zero address.
* @dev Reverts if `quantity` is zero.
* @dev Reverts if `quantity` is greater than the maximum purchase quantity.
* @dev Reverts if `quantity` is greater than the remaining supply.
* @dev Reverts if `sku` does not exist.
* @dev Reverts if `sku` exists but does not have a price set for `token`.
* @param recipient The recipient of the purchase used to calculate the total price amount.
* @param token The payment token used to calculate the total price amount.
* @param sku The identifier of the SKU used to calculate the total price amount.
* @param quantity The quantity used to calculate the total price amount.
* @param userData Optional extra user input data.
* @return totalPrice The computed total price to pay.
* @return pricingData Implementation-specific extra pricing data, such as details about discounts applied.
* If not empty, the implementer MUST document how to interepret the values.
*/
function estimatePurchase(
address payable recipient,
address token,
bytes32 sku,
uint256 quantity,
bytes calldata userData
) external view returns (uint256 totalPrice, bytes32[] memory pricingData);
/**
* Returns the information relative to a SKU.
* @dev WARNING: it is the responsibility of the implementer to ensure that the
* number of payment tokens is bounded, so that this function does not run out of gas.
* @dev Reverts if `sku` does not exist.
* @param sku The SKU identifier.
* @return totalSupply The initial total supply for sale.
* @return remainingSupply The remaining supply for sale.
* @return maxQuantityPerPurchase The maximum allowed quantity for a single purchase.
* @return notificationsReceiver The address of a contract on which to call the `onPurchaseNotificationReceived` function.
* @return tokens The list of supported payment tokens.
* @return prices The list of associated prices for each of the `tokens`.
*/
function getSkuInfo(bytes32 sku)
external
view
returns (
uint256 totalSupply,
uint256 remainingSupply,
uint256 maxQuantityPerPurchase,
address notificationsReceiver,
address[] memory tokens,
uint256[] memory prices
);
/**
* Returns the list of created SKU identifiers.
* @dev WARNING: it is the responsibility of the implementer to ensure that the
* number of SKUs is bounded, so that this function does not run out of gas.
* @return skus the list of created SKU identifiers.
*/
function getSkus() external view returns (bytes32[] memory skus);
}
// File contracts/sale/interfaces/IPurchaseNotificationsReceiver.sol
pragma solidity 0.6.8;
/**
* @title IPurchaseNotificationsReceiver
* Interface for any contract that wants to support purchase notifications from a Sale contract.
*/
interface IPurchaseNotificationsReceiver {
/**
* Handles the receipt of a purchase notification.
* @dev This function MUST return the function selector, otherwise the caller will revert the transaction.
* The selector to be returned can be obtained as `this.onPurchaseNotificationReceived.selector`
* @dev This function MAY throw.
* @param purchaser The purchaser of the purchase.
* @param recipient The recipient of the purchase.
* @param token The token to use as the payment currency.
* @param sku The identifier of the SKU to purchase.
* @param quantity The quantity to purchase.
* @param userData Optional extra user input data.
* @param totalPrice The total price paid.
* @param pricingData Implementation-specific extra pricing data, such as details about discounts applied.
* @param paymentData Implementation-specific extra payment data, such as conversion rates.
* @param deliveryData Implementation-specific extra delivery data, such as purchase receipts.
* @return `bytes4(keccak256(
* "onPurchaseNotificationReceived(address,address,address,bytes32,uint256,bytes,uint256,bytes32[],bytes32[],bytes32[])"))`
*/
function onPurchaseNotificationReceived(
address purchaser,
address recipient,
address token,
bytes32 sku,
uint256 quantity,
bytes calldata userData,
uint256 totalPrice,
bytes32[] calldata pricingData,
bytes32[] calldata paymentData,
bytes32[] calldata deliveryData
) external returns (bytes4);
}
// File contracts/sale/abstract/PurchaseLifeCycles.sol
pragma solidity 0.6.8;
/**
* @title PurchaseLifeCycles
* An abstract contract which define the life cycles for a purchase implementer.
*/
abstract contract PurchaseLifeCycles {
/**
* Wrapper for the purchase data passed as argument to the life cycle functions and down to their step functions.
*/
struct PurchaseData {
address payable purchaser;
address payable recipient;
address token;
bytes32 sku;
uint256 quantity;
bytes userData;
uint256 totalPrice;
bytes32[] pricingData;
bytes32[] paymentData;
bytes32[] deliveryData;
}
/* Internal Life Cycle Functions */
/**
* `estimatePurchase` lifecycle.
* @param purchase The purchase conditions.
*/
function _estimatePurchase(PurchaseData memory purchase) internal view virtual returns (uint256 totalPrice, bytes32[] memory pricingData) {
_validation(purchase);
_pricing(purchase);
totalPrice = purchase.totalPrice;
pricingData = purchase.pricingData;
}
/**
* `purchaseFor` lifecycle.
* @param purchase The purchase conditions.
*/
function _purchaseFor(PurchaseData memory purchase) internal virtual {
_validation(purchase);
_pricing(purchase);
_payment(purchase);
_delivery(purchase);
_notification(purchase);
}
/* Internal Life Cycle Step Functions */
/**
* Lifecycle step which validates the purchase pre-conditions.
* @dev Responsibilities:
* - Ensure that the purchase pre-conditions are met and revert if not.
* @param purchase The purchase conditions.
*/
function _validation(PurchaseData memory purchase) internal view virtual;
/**
* Lifecycle step which computes the purchase price.
* @dev Responsibilities:
* - Computes the pricing formula, including any discount logic and price conversion;
* - Set the value of `purchase.totalPrice`;
* - Add any relevant extra data related to pricing in `purchase.pricingData` and document how to interpret it.
* @param purchase The purchase conditions.
*/
function _pricing(PurchaseData memory purchase) internal view virtual;
/**
* Lifecycle step which manages the transfer of funds from the purchaser.
* @dev Responsibilities:
* - Ensure the payment reaches destination in the expected output token;
* - Handle any token swap logic;
* - Add any relevant extra data related to payment in `purchase.paymentData` and document how to interpret it.
* @param purchase The purchase conditions.
*/
function _payment(PurchaseData memory purchase) internal virtual;
/**
* Lifecycle step which delivers the purchased SKUs to the recipient.
* @dev Responsibilities:
* - Ensure the product is delivered to the recipient, if that is the contract's responsibility.
* - Handle any internal logic related to the delivery, including the remaining supply update;
* - Add any relevant extra data related to delivery in `purchase.deliveryData` and document how to interpret it.
* @param purchase The purchase conditions.
*/
function _delivery(PurchaseData memory purchase) internal virtual;
/**
* Lifecycle step which notifies of the purchase.
* @dev Responsibilities:
* - Manage after-purchase event(s) emission.
* - Handle calls to the notifications receiver contract's `onPurchaseNotificationReceived` function, if applicable.
* @param purchase The purchase conditions.
*/
function _notification(PurchaseData memory purchase) internal virtual;
}
// File contracts/sale/abstract/Sale.sol
pragma solidity 0.6.8;
/**
* @title Sale
* An abstract base sale contract with a minimal implementation of ISale and administration functions.
* A minimal implementation of the `_validation`, `_delivery` and `notification` life cycle step functions
* are provided, but the inheriting contract must implement `_pricing` and `_payment`.
*/
abstract contract Sale is PurchaseLifeCycles, ISale, PayoutWallet, Startable, Pausable {
using Address for address;
using SafeMath for uint256;
using EnumSet for EnumSet.Set;
using EnumMap for EnumMap.Map;
struct SkuInfo {
uint256 totalSupply;
uint256 remainingSupply;
uint256 maxQuantityPerPurchase;
address notificationsReceiver;
EnumMap.Map prices;
}
address public constant override TOKEN_ETH = address(0x00eeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeee);
uint256 public constant override SUPPLY_UNLIMITED = type(uint256).max;
EnumSet.Set internal _skus;
mapping(bytes32 => SkuInfo) internal _skuInfos;
uint256 internal immutable _skusCapacity;
uint256 internal immutable _tokensPerSkuCapacity;
/**
* Constructor.
* @dev Emits the `MagicValues` event.
* @dev Emits the `Paused` event.
* @param payoutWallet_ the payout wallet.
* @param skusCapacity the cap for the number of managed SKUs.
* @param tokensPerSkuCapacity the cap for the number of tokens managed per SKU.
*/
constructor(
address payoutWallet_,
uint256 skusCapacity,
uint256 tokensPerSkuCapacity
) internal PayoutWallet(payoutWallet_) {
_skusCapacity = skusCapacity;
_tokensPerSkuCapacity = tokensPerSkuCapacity;
bytes32[] memory names = new bytes32[](2);
bytes32[] memory values = new bytes32[](2);
(names[0], values[0]) = ("TOKEN_ETH", bytes32(uint256(TOKEN_ETH)));
(names[1], values[1]) = ("SUPPLY_UNLIMITED", bytes32(uint256(SUPPLY_UNLIMITED)));
emit MagicValues(names, values);
_pause();
}
/* Public Admin Functions */
/**
* Actvates, or 'starts', the contract.
* @dev Emits the `Started` event.
* @dev Emits the `Unpaused` event.
* @dev Reverts if called by any other than the contract owner.
* @dev Reverts if the contract has already been started.
* @dev Reverts if the contract is not paused.
*/
function start() public virtual onlyOwner {
_start();
_unpause();
}
/**
* Pauses the contract.
* @dev Emits the `Paused` event.
* @dev Reverts if called by any other than the contract owner.
* @dev Reverts if the contract has not been started yet.
* @dev Reverts if the contract is already paused.
*/
function pause() public virtual onlyOwner whenStarted {
_pause();
}
/**
* Resumes the contract.
* @dev Emits the `Unpaused` event.
* @dev Reverts if called by any other than the contract owner.
* @dev Reverts if the contract has not been started yet.
* @dev Reverts if the contract is not paused.
*/
function unpause() public virtual onlyOwner whenStarted {
_unpause();
}
/**
* Sets the token prices for the specified product SKU.
* @dev Reverts if called by any other than the contract owner.
* @dev Reverts if `tokens` and `prices` have different lengths.
* @dev Reverts if `sku` does not exist.
* @dev Reverts if one of the `tokens` is the zero address.
* @dev Reverts if the update results in too many tokens for the SKU.
* @dev Emits the `SkuPricingUpdate` event.
* @param sku The identifier of the SKU.
* @param tokens The list of payment tokens to update.
* If empty, disable all the existing payment tokens.
* @param prices The list of prices to apply for each payment token.
* Zero price values are used to disable a payment token.
*/
function updateSkuPricing(
bytes32 sku,
address[] memory tokens,
uint256[] memory prices
) public virtual onlyOwner {
uint256 length = tokens.length;
// solhint-disable-next-line reason-string
require(length == prices.length, "Sale: tokens/prices lengths mismatch");
SkuInfo storage skuInfo = _skuInfos[sku];
require(skuInfo.totalSupply != 0, "Sale: non-existent sku");
EnumMap.Map storage tokenPrices = skuInfo.prices;
if (length == 0) {
uint256 currentLength = tokenPrices.length();
for (uint256 i = 0; i < currentLength; ++i) {
// TODO add a clear function in EnumMap and EnumSet and use it
(bytes32 token, ) = tokenPrices.at(0);
tokenPrices.remove(token);
}
} else {
_setTokenPrices(tokenPrices, tokens, prices);
}
emit SkuPricingUpdate(sku, tokens, prices);
}
/* ISale Public Functions */
/**
* Performs a purchase.
* @dev Reverts if the sale has not started.
* @dev Reverts if the sale is paused.
* @dev Reverts if `recipient` is the zero address.
* @dev Reverts if `token` is the zero address.
* @dev Reverts if `quantity` is zero.
* @dev Reverts if `quantity` is greater than the maximum purchase quantity.
* @dev Reverts if `quantity` is greater than the remaining supply.
* @dev Reverts if `sku` does not exist.
* @dev Reverts if `sku` exists but does not have a price set for `token`.
* @dev Emits the Purchase event.
* @param recipient The recipient of the purchase.
* @param token The token to use as the payment currency.
* @param sku The identifier of the SKU to purchase.
* @param quantity The quantity to purchase.
* @param userData Optional extra user input data.
*/
function purchaseFor(
address payable recipient,
address token,
bytes32 sku,
uint256 quantity,
bytes calldata userData
) external payable virtual override whenStarted whenNotPaused {
PurchaseData memory purchase;
purchase.purchaser = _msgSender();
purchase.recipient = recipient;
purchase.token = token;
purchase.sku = sku;
purchase.quantity = quantity;
purchase.userData = userData;
_purchaseFor(purchase);
}
/**
* Estimates the computed final total amount to pay for a purchase, including any potential discount.
* @dev This function MUST compute the same price as `purchaseFor` would in identical conditions (same arguments, same point in time).
* @dev If an implementer contract uses the `pricingData` field, it SHOULD document how to interpret the values.
* @dev Reverts if the sale has not started.
* @dev Reverts if the sale is paused.
* @dev Reverts if `recipient` is the zero address.
* @dev Reverts if `token` is the zero address.
* @dev Reverts if `quantity` is zero.
* @dev Reverts if `quantity` is greater than the maximum purchase quantity.
* @dev Reverts if `quantity` is greater than the remaining supply.
* @dev Reverts if `sku` does not exist.
* @dev Reverts if `sku` exists but does not have a price set for `token`.
* @param recipient The recipient of the purchase used to calculate the total price amount.
* @param token The payment token used to calculate the total price amount.
* @param sku The identifier of the SKU used to calculate the total price amount.
* @param quantity The quantity used to calculate the total price amount.
* @param userData Optional extra user input data.
* @return totalPrice The computed total price.
* @return pricingData Implementation-specific extra pricing data, such as details about discounts applied.
* If not empty, the implementer MUST document how to interepret the values.
*/
function estimatePurchase(
address payable recipient,
address token,
bytes32 sku,
uint256 quantity,
bytes calldata userData
) external view virtual override whenStarted whenNotPaused returns (uint256 totalPrice, bytes32[] memory pricingData) {
PurchaseData memory purchase;
purchase.purchaser = _msgSender();
purchase.recipient = recipient;
purchase.token = token;
purchase.sku = sku;
purchase.quantity = quantity;
purchase.userData = userData;
return _estimatePurchase(purchase);
}
/**
* Returns the information relative to a SKU.
* @dev WARNING: it is the responsibility of the implementer to ensure that the
* number of payment tokens is bounded, so that this function does not run out of gas.
* @dev Reverts if `sku` does not exist.
* @param sku The SKU identifier.
* @return totalSupply The initial total supply for sale.
* @return remainingSupply The remaining supply for sale.
* @return maxQuantityPerPurchase The maximum allowed quantity for a single purchase.
* @return notificationsReceiver The address of a contract on which to call the `onPurchaseNotificationReceived` function.
* @return tokens The list of supported payment tokens.
* @return prices The list of associated prices for each of the `tokens`.
*/
function getSkuInfo(bytes32 sku)
external
view
override
returns (
uint256 totalSupply,
uint256 remainingSupply,
uint256 maxQuantityPerPurchase,
address notificationsReceiver,
address[] memory tokens,
uint256[] memory prices
)
{
SkuInfo storage skuInfo = _skuInfos[sku];
uint256 length = skuInfo.prices.length();
totalSupply = skuInfo.totalSupply;
require(totalSupply != 0, "Sale: non-existent sku");
remainingSupply = skuInfo.remainingSupply;
maxQuantityPerPurchase = skuInfo.maxQuantityPerPurchase;
notificationsReceiver = skuInfo.notificationsReceiver;
tokens = new address[](length);
prices = new uint256[](length);
for (uint256 i = 0; i < length; ++i) {
(bytes32 token, bytes32 price) = skuInfo.prices.at(i);
tokens[i] = address(uint256(token));
prices[i] = uint256(price);
}
}
/**
* Returns the list of created SKU identifiers.
* @return skus the list of created SKU identifiers.
*/
function getSkus() external view override returns (bytes32[] memory skus) {
skus = _skus.values;
}
/* Internal Utility Functions */
/**
* Creates an SKU.
* @dev Reverts if `totalSupply` is zero.
* @dev Reverts if `sku` already exists.
* @dev Reverts if `notificationsReceiver` is not the zero address and is not a contract address.
* @dev Reverts if the update results in too many SKUs.
* @dev Emits the `SkuCreation` event.
* @param sku the SKU identifier.
* @param totalSupply the initial total supply.
* @param maxQuantityPerPurchase The maximum allowed quantity for a single purchase.
* @param notificationsReceiver The purchase notifications receiver contract address.
* If set to the zero address, the notification is not enabled.
*/
function _createSku(
bytes32 sku,
uint256 totalSupply,
uint256 maxQuantityPerPurchase,
address notificationsReceiver
) internal virtual {
require(totalSupply != 0, "Sale: zero supply");
require(_skus.length() < _skusCapacity, "Sale: too many skus");
require(_skus.add(sku), "Sale: sku already created");
if (notificationsReceiver != address(0)) {
// solhint-disable-next-line reason-string
require(notificationsReceiver.isContract(), "Sale: receiver is not a contract");
}
SkuInfo storage skuInfo = _skuInfos[sku];
skuInfo.totalSupply = totalSupply;
skuInfo.remainingSupply = totalSupply;
skuInfo.maxQuantityPerPurchase = maxQuantityPerPurchase;
skuInfo.notificationsReceiver = notificationsReceiver;
emit SkuCreation(sku, totalSupply, maxQuantityPerPurchase, notificationsReceiver);
}
/**
* Updates SKU token prices.
* @dev Reverts if one of the `tokens` is the zero address.
* @dev Reverts if the update results in too many tokens for the SKU.
* @param tokenPrices Storage pointer to a mapping of SKU token prices to update.
* @param tokens The list of payment tokens to update.
* @param prices The list of prices to apply for each payment token.
* Zero price values are used to disable a payment token.
*/
function _setTokenPrices(
EnumMap.Map storage tokenPrices,
address[] memory tokens,
uint256[] memory prices
) internal virtual {
for (uint256 i = 0; i < tokens.length; ++i) {
address token = tokens[i];
require(token != address(0), "Sale: zero address token");
uint256 price = prices[i];
if (price == 0) {
tokenPrices.remove(bytes32(uint256(token)));
} else {
tokenPrices.set(bytes32(uint256(token)), bytes32(price));
}
}
require(tokenPrices.length() <= _tokensPerSkuCapacity, "Sale: too many tokens");
}
/* Internal Life Cycle Step Functions */
/**
* Lifecycle step which validates the purchase pre-conditions.
* @dev Responsibilities:
* - Ensure that the purchase pre-conditions are met and revert if not.
* @dev Reverts if `purchase.recipient` is the zero address.
* @dev Reverts if `purchase.token` is the zero address.
* @dev Reverts if `purchase.quantity` is zero.
* @dev Reverts if `purchase.quantity` is greater than the SKU's `maxQuantityPerPurchase`.
* @dev Reverts if `purchase.quantity` is greater than the available supply.
* @dev Reverts if `purchase.sku` does not exist.
* @dev Reverts if `purchase.sku` exists but does not have a price set for `purchase.token`.
* @dev If this function is overriden, the implementer SHOULD super call this before.
* @param purchase The purchase conditions.
*/
function _validation(PurchaseData memory purchase) internal view virtual override {
require(purchase.recipient != address(0), "Sale: zero address recipient");
require(purchase.token != address(0), "Sale: zero address token");
require(purchase.quantity != 0, "Sale: zero quantity purchase");
SkuInfo storage skuInfo = _skuInfos[purchase.sku];
require(skuInfo.totalSupply != 0, "Sale: non-existent sku");
require(skuInfo.maxQuantityPerPurchase >= purchase.quantity, "Sale: above max quantity");
if (skuInfo.totalSupply != SUPPLY_UNLIMITED) {
require(skuInfo.remainingSupply >= purchase.quantity, "Sale: insufficient supply");
}
bytes32 priceKey = bytes32(uint256(purchase.token));
require(skuInfo.prices.contains(priceKey), "Sale: non-existent sku token");
}
/**
* Lifecycle step which delivers the purchased SKUs to the recipient.
* @dev Responsibilities:
* - Ensure the product is delivered to the recipient, if that is the contract's responsibility.
* - Handle any internal logic related to the delivery, including the remaining supply update;
* - Add any relevant extra data related to delivery in `purchase.deliveryData` and document how to interpret it.
* @dev Reverts if there is not enough available supply.
* @dev If this function is overriden, the implementer SHOULD super call it.
* @param purchase The purchase conditions.
*/
function _delivery(PurchaseData memory purchase) internal virtual override {
SkuInfo memory skuInfo = _skuInfos[purchase.sku];
if (skuInfo.totalSupply != SUPPLY_UNLIMITED) {
_skuInfos[purchase.sku].remainingSupply = skuInfo.remainingSupply.sub(purchase.quantity);
}
}
/**
* Lifecycle step which notifies of the purchase.
* @dev Responsibilities:
* - Manage after-purchase event(s) emission.
* - Handle calls to the notifications receiver contract's `onPurchaseNotificationReceived` function, if applicable.
* @dev Reverts if `onPurchaseNotificationReceived` throws or returns an incorrect value.
* @dev Emits the `Purchase` event. The values of `purchaseData` are the concatenated values of `priceData`, `paymentData`
* and `deliveryData`. If not empty, the implementer MUST document how to interpret these values.
* @dev If this function is overriden, the implementer SHOULD super call it.
* @param purchase The purchase conditions.
*/
function _notification(PurchaseData memory purchase) internal virtual override {
emit Purchase(
purchase.purchaser,
purchase.recipient,
purchase.token,
purchase.sku,
purchase.quantity,
purchase.userData,
purchase.totalPrice,
abi.encodePacked(purchase.pricingData, purchase.paymentData, purchase.deliveryData)
);
address notificationsReceiver = _skuInfos[purchase.sku].notificationsReceiver;
if (notificationsReceiver != address(0)) {
// solhint-disable-next-line reason-string
require(
IPurchaseNotificationsReceiver(notificationsReceiver).onPurchaseNotificationReceived(
purchase.purchaser,
purchase.recipient,
purchase.token,
purchase.sku,
purchase.quantity,
purchase.userData,
purchase.totalPrice,
purchase.pricingData,
purchase.paymentData,
purchase.deliveryData
) == IPurchaseNotificationsReceiver(address(0)).onPurchaseNotificationReceived.selector, // TODO precompute return value
"Sale: wrong receiver return value"
);
}
}
}
// File contracts/sale/FixedPricesSale.sol
pragma solidity 0.6.8;
/**
* @title FixedPricesSale
* An Sale which implements a fixed prices strategy.
* The final implementer is responsible for implementing any additional pricing and/or delivery logic.
*/
contract FixedPricesSale is Sale {
/**
* Constructor.
* @dev Emits the `MagicValues` event.
* @dev Emits the `Paused` event.
* @param payoutWallet_ the payout wallet.
* @param skusCapacity the cap for the number of managed SKUs.
* @param tokensPerSkuCapacity the cap for the number of tokens managed per SKU.
*/
constructor(
address payoutWallet_,
uint256 skusCapacity,
uint256 tokensPerSkuCapacity
) internal Sale(payoutWallet_, skusCapacity, tokensPerSkuCapacity) {}
/* Internal Life Cycle Functions */
/**
* Lifecycle step which computes the purchase price.
* @dev Responsibilities:
* - Computes the pricing formula, including any discount logic and price conversion;
* - Set the value of `purchase.totalPrice`;
* - Add any relevant extra data related to pricing in `purchase.pricingData` and document how to interpret it.
* @dev Reverts if `purchase.sku` does not exist.
* @dev Reverts if `purchase.token` is not supported by the SKU.
* @dev Reverts in case of price overflow.
* @param purchase The purchase conditions.
*/
function _pricing(PurchaseData memory purchase) internal view virtual override {
SkuInfo storage skuInfo = _skuInfos[purchase.sku];
require(skuInfo.totalSupply != 0, "Sale: unsupported SKU");
EnumMap.Map storage prices = skuInfo.prices;
uint256 unitPrice = _unitPrice(purchase, prices);
purchase.totalPrice = unitPrice.mul(purchase.quantity);
}
/**
* Lifecycle step which manages the transfer of funds from the purchaser.
* @dev Responsibilities:
* - Ensure the payment reaches destination in the expected output token;
* - Handle any token swap logic;
* - Add any relevant extra data related to payment in `purchase.paymentData` and document how to interpret it.
* @dev Reverts in case of payment failure.
* @param purchase The purchase conditions.
*/
function _payment(PurchaseData memory purchase) internal virtual override {
if (purchase.token == TOKEN_ETH) {
require(msg.value >= purchase.totalPrice, "Sale: insufficient ETH provided");
payoutWallet.transfer(purchase.totalPrice);
uint256 change = msg.value.sub(purchase.totalPrice);
if (change != 0) {
purchase.purchaser.transfer(change);
}
} else {
require(IERC20(purchase.token).transferFrom(_msgSender(), payoutWallet, purchase.totalPrice), "Sale: ERC20 payment failed");
}
}
/* Internal Utility Functions */
/**
* Retrieves the unit price of a SKU for the specified payment token.
* @dev Reverts if the specified payment token is unsupported.
* @param purchase The purchase conditions specifying the payment token with which the unit price will be retrieved.
* @param prices Storage pointer to a mapping of SKU token prices to retrieve the unit price from.
* @return unitPrice The unit price of a SKU for the specified payment token.
*/
function _unitPrice(PurchaseData memory purchase, EnumMap.Map storage prices) internal view virtual returns (uint256 unitPrice) {
unitPrice = uint256(prices.get(bytes32(uint256(purchase.token))));
require(unitPrice != 0, "Sale: unsupported payment token");
}
}
// File contracts/sale/interfaces/IOracleSale.sol
pragma solidity 0.6.8;
/**
* @title IOracleSale
* An ISale which can manage token conversion rates through an oracle.
*/
/*is ISale*/
interface IOracleSale {
/**
* Returns the price magic value used to represent an oracle-based token conversion pricing.
* @dev MUST NOT be zero. SHOULD BE a prohibitively big value, so that it doesn’t collide with a possible price value.
* @return The price magic value used to represent an oracle-based token conversion pricing.
*/
// solhint-disable-next-line func-name-mixedcase
function PRICE_CONVERT_VIA_ORACLE() external pure returns (uint256);
/**
* Retrieves the token conversion rates for the `tokens`/`referenceToken` pairs via the oracle.
* @dev Reverts if the oracle does not provide a conversion rate for one of the token pairs.
* @param tokens The list of tokens to retrieve the conversion rates for.
* @param data Additional data with no specified format for deriving the conversion rates.
* @return rates The conversion rates for the `tokens`/`referenceToken` pairs, retrieved via the oracle.
*/
function conversionRates(address[] calldata tokens, bytes calldata data) external view returns (uint256[] memory rates);
}
// File contracts/sale/abstract/OracleSale.sol
pragma solidity 0.6.8;
/**
* @title OracleSale
* A FixedPricesSale which implements support for an oracle-based token conversion pricing strategy.
* The final implementer is responsible for implementing any additional pricing and/or delivery logic.
*
* PurchaseData.pricingData:
* - a zero length array for fixed pricing data.
* - a non-zero length array for oracle-based pricing data
* - [0] uint256: the uninterpolated unit price (i.e. magic value).
* - [1] uint256: the token conversion rate used for oracle-based pricing.
*/
abstract contract OracleSale is IOracleSale, FixedPricesSale {
uint256 public constant override PRICE_CONVERT_VIA_ORACLE = type(uint256).max;
address public referenceToken;
/**
* Constructor.
* @dev Emits the `MagicValues` event.
* @dev Emits the `Paused` event.
* @param payoutWallet_ the payout wallet.
* @param skusCapacity the cap for the number of managed SKUs.
* @param tokensPerSkuCapacity the cap for the number of tokens managed per SKU.
* @param referenceToken_ the token to use for oracle-based conversions.
*/
constructor(
address payoutWallet_,
uint256 skusCapacity,
uint256 tokensPerSkuCapacity,
address referenceToken_
) internal FixedPricesSale(payoutWallet_, skusCapacity, tokensPerSkuCapacity) {
referenceToken = referenceToken_;
bytes32[] memory names = new bytes32[](1);
bytes32[] memory values = new bytes32[](1);
(names[0], values[0]) = ("PRICE_CONVERT_VIA_ORACLE", bytes32(PRICE_CONVERT_VIA_ORACLE));
emit MagicValues(names, values);
}
/* Internal Life Cycle Functions */
/**
* Lifecycle step which computes the purchase price.
* @dev Responsibilities:
* - Computes the pricing formula, including any discount logic and price conversion;
* - Set the value of `purchase.totalPrice`;
* - Add any relevant extra data related to pricing in `purchase.pricingData` and document how to interpret it.
* @dev Reverts if `purchase.sku` does not exist.
* @dev Reverts if `purchase.token` is not supported by the SKU.
* @dev Reverts in case of price overflow.
* @param purchase The purchase conditions.
*/
function _pricing(PurchaseData memory purchase) internal view virtual override {
SkuInfo storage skuInfo = _skuInfos[purchase.sku];
require(skuInfo.totalSupply != 0, "Sale: unsupported SKU");
EnumMap.Map storage prices = skuInfo.prices;
uint256 unitPrice = _unitPrice(purchase, prices);
if (!_oraclePricing(purchase, prices, unitPrice)) {
purchase.totalPrice = unitPrice.mul(purchase.quantity);
}
}
/* Public IOracleSale Functions */
/**
* Retrieves the token conversion rates for the `tokens`/`referenceToken` pairs via the oracle.
* @dev Reverts if the oracle does not provide a conversion rate for one of the token pairs.
* @param tokens The list of tokens to retrieve the conversion rates for.
* @param data Additional data with no specified format for deriving the conversion rates.
* @return rates The conversion rates for the `tokens`/`referenceToken` pairs, retrieved via the oracle.
*/
function conversionRates(address[] calldata tokens, bytes calldata data) external view virtual override returns (uint256[] memory rates) {
uint256 length = tokens.length;
rates = new uint256[](length);
for (uint256 i = 0; i < length; ++i) {
rates[i] = _conversionRate(tokens[i], referenceToken, data);
}
}
/* Internal Utility Functions */
/**
* Updates SKU token prices.
* @dev Reverts if one of the `tokens` is the zero address.
* @dev Reverts if the update results in too many tokens for the SKU.
* @dev Reverts if the SKU has any supported payment tokens and one of them is not the
* reference token.
* @param tokenPrices Storage pointer to a mapping of SKU token prices to update.
* @param tokens The list of payment tokens to update.
* @param prices The list of prices to apply for each payment token.
* Zero price values are used to disable a payment token.
*/
function _setTokenPrices(
EnumMap.Map storage tokenPrices,
address[] memory tokens,
uint256[] memory prices
) internal virtual override {
super._setTokenPrices(tokenPrices, tokens, prices);
// solhint-disable-next-line reason-string
require(tokenPrices.length() == 0 || tokenPrices.contains(bytes32(uint256(referenceToken))), "OracleSale: missing reference token");
}
/**
* Computes the oracle-based purchase price.
* @dev Responsibilities:
* - Computes the oracle-based pricing formula, including any discount logic and price conversion;
* - Set the value of `purchase.totalPrice`;
* - Add any relevant extra data related to pricing in `purchase.pricingData` and document how to interpret it.
* @dev Reverts in case of price overflow.
* @param purchase The purchase conditions.
* @param tokenPrices Storage pointer to a mapping of SKU token prices.
* @param unitPrice The unit price of a SKU for the specified payment token.
* @return True if oracle pricing was handled, false otherwise.
*/
function _oraclePricing(
PurchaseData memory purchase,
EnumMap.Map storage tokenPrices,
uint256 unitPrice
) internal view virtual returns (bool) {
if (unitPrice != PRICE_CONVERT_VIA_ORACLE) {
return false;
}
uint256 referenceUnitPrice = uint256(tokenPrices.get(bytes32(uint256(referenceToken))));
uint256 conversionRate = _conversionRate(purchase.token, referenceToken, purchase.userData);
uint256 totalPrice = referenceUnitPrice.mul(10**18).div(conversionRate).mul(purchase.quantity);
purchase.pricingData = new bytes32[](2);
purchase.pricingData[0] = bytes32(unitPrice);
purchase.pricingData[1] = bytes32(conversionRate);
purchase.totalPrice = totalPrice;
return true;
}
/**
* Retrieves the token conversion rate for the `fromToken`/`toToken` pair via the oracle.
* @dev Reverts if the oracle does not provide a conversion rate for the pair.
* @param fromToken The source token from which the conversion rate is derived from.
* @param toToken the destination token from which the conversion rate is derived from.
* @param data Additional data with no specified format for deriving the conversion rate.
* @return rate The conversion rate for the `fromToken`/`toToken` pair, retrieved via the oracle.
*/
function _conversionRate(
address fromToken,
address toToken,
bytes memory data
) internal view virtual returns (uint256 rate);
}
// File contracts/sale/abstract/SwapSale.sol
pragma solidity 0.6.8;
/**
* @title SwapSale
* An OracleSale which implements support for an oracle-based token swap pricing strategy. The
* final implementer is responsible for implementing any additional pricing and/or delivery logic.
*
* PurchaseData.pricingData:
* - a zero length array for fixed pricing data.
* - a non-zero length array for oracle-based pricing data
* - [0] uint256: the uninterpolated unit price (i.e. magic value).
* - [1] uint256: the token conversion/swap rate used for oracle-based pricing.
*
* PurchaseData.paymentData:
* - [0] uint256: the actual payment price in terms of the purchase token.
*/
abstract contract SwapSale is OracleSale, ISwapSale {
uint256 public constant override PRICE_SWAP_VIA_ORACLE = PRICE_CONVERT_VIA_ORACLE - 1;
/**
* Constructor.
* @dev Emits the `MagicValues` event.
* @dev Emits the `Paused` event.
* @param payoutWallet_ The payout wallet.
* @param skusCapacity The cap for the number of managed SKUs.
* @param tokensPerSkuCapacity The cap for the number of tokens managed per SKU.
* @param referenceToken The token to use for oracle-based token swaps.
*/
constructor(
address payoutWallet_,
uint256 skusCapacity,
uint256 tokensPerSkuCapacity,
address referenceToken
) internal OracleSale(payoutWallet_, skusCapacity, tokensPerSkuCapacity, referenceToken) {
bytes32[] memory names = new bytes32[](1);
bytes32[] memory values = new bytes32[](1);
(names[0], values[0]) = ("PRICE_SWAP_VIA_ORACLE", bytes32(PRICE_SWAP_VIA_ORACLE));
emit MagicValues(names, values);
}
/* Public ISwapSale Functions */
/**
* Retrieves the token swap rates for the `tokens`/`referenceToken` pairs via the oracle.
* @dev Reverts if the oracle does not provide a swap rate for one of the token pairs.
* @param tokens The list of tokens to retrieve the swap rates for.
* @param referenceAmount The amount of `referenceToken` to retrieve the swap rates for.
* @param data Additional data with no specified format for deriving the swap rates.
* @return rates The swap rates for the `tokens`/`referenceToken` pairs, retrieved via the oracle.
*/
function swapRates(
address[] calldata tokens,
uint256 referenceAmount,
bytes calldata data
) external view virtual override returns (uint256[] memory rates) {
uint256 length = tokens.length;
rates = new uint256[](length);
for (uint256 i = 0; i < length; ++i) {
uint256 tokenAmount = _estimateSwap(tokens[i], referenceToken, referenceAmount, data);
rates[i] = referenceAmount.mul(10**18).div(tokenAmount);
}
}
/* Internal Life Cycle Functions */
/**
* Lifecycle step which manages the transfer of funds from the purchaser.
* @dev Responsibilities:
* - Ensure the payment reaches destination in the expected output token;
* - Handle any token swap logic;
* - Add any relevant extra data related to payment in `purchase.paymentData` and document how to interpret it.
* @dev Reverts in case of payment failure.
* @param purchase The purchase conditions.
*/
function _payment(PurchaseData memory purchase) internal virtual override {
if ((purchase.pricingData.length == 0) || (uint256(purchase.pricingData[0]) != PRICE_SWAP_VIA_ORACLE)) {
super._payment(purchase);
return;
}
if (purchase.token == TOKEN_ETH) {
// solhint-disable-next-line reason-string
require(msg.value >= purchase.totalPrice, "SwapSale: insufficient ETH provided");
} else {
require(IERC20(purchase.token).transferFrom(_msgSender(), address(this), purchase.totalPrice), "SwapSale: ERC20 payment failed");
}
uint256 swapRate = uint256(purchase.pricingData[1]);
uint256 referenceTotalPrice = swapRate.mul(purchase.totalPrice).div(10**18);
uint256 fromAmount = _swap(purchase.token, referenceToken, referenceTotalPrice, purchase.userData);
if (purchase.token == TOKEN_ETH) {
uint256 change = msg.value.sub(fromAmount);
if (change != 0) {
purchase.purchaser.transfer(change);
}
} else {
uint256 change = purchase.totalPrice.sub(fromAmount);
if (change != 0) {
// solhint-disable-next-line reason-string
require(IERC20(purchase.token).transfer(purchase.purchaser, change), "SwapSale: ERC20 payment change failed");
}
}
if (referenceToken == TOKEN_ETH) {
payoutWallet.transfer(fromAmount);
} else {
require(IERC20(referenceToken).transfer(payoutWallet, fromAmount), "SwapSale: ERC20 payout failed");
}
}
/* Internal Utility Functions */
/**
* Estimates the optimal amount of `fromToken` to provide in order to swap for the specified amount of
* `toToken`, via the oracle.
* @dev Reverts if the oracle cannot estimate the optimal amount of `fromToken` to provide.
* @param fromToken The source token to swap from.
* @param toToken The destination token to swap to.
* @param toAmount The amount of destination tokens to swap for.
* @param data Additional data with no specified format for deriving the swap estimate.
* @return fromAmount The estimated optimal amount of `fromToken` to provide in order to perform a swap,
* via the oracle.
*/
function _estimateSwap(
address fromToken,
address toToken,
uint256 toAmount,
bytes memory data
) internal view virtual returns (uint256 fromAmount);
/**
* Swaps `fromToken` for the specified amount of `toToken`, via the oracle.
* @dev Reverts if the oracle is unable to perform the token swap.
* @param fromToken The source token to swap from.
* @param toToken The destination token to swap to.
* @param toAmount The amount of destination tokens to swap for.
* @param data Additional data with no specified format for performing the swap.
* return fromAmount The amount of `fromToken` swapped for the specified amount of `toToken`, via the
* oracle.
*/
function _swap(
address fromToken,
address toToken,
uint256 toAmount,
bytes memory data
) internal virtual returns (uint256 fromAmount);
/**
* Computes the oracle-based purchase price.
* @dev Responsibilities:
* - Computes the oracle-based pricing formula, including any discount logic and price conversion;
* - Set the value of `purchase.totalPrice`;
* - Add any relevant extra data related to pricing in `purchase.pricingData` and document how to interpret it.
* @dev Reverts in case of price overflow.
* @param purchase The purchase conditions.
* @param tokenPrices Storage pointer to a mapping of SKU token prices.
* @param unitPrice The unit price of a SKU for the specified payment token.
* @return True if oracle pricing was handled, false otherwise.
*/
function _oraclePricing(
PurchaseData memory purchase,
EnumMap.Map storage tokenPrices,
uint256 unitPrice
) internal view virtual override returns (bool) {
if (unitPrice != PRICE_SWAP_VIA_ORACLE) {
return super._oraclePricing(purchase, tokenPrices, unitPrice);
}
uint256 referenceUnitPrice = uint256(tokenPrices.get(bytes32(uint256(referenceToken))));
uint256 referenceTotalPrice = referenceUnitPrice.mul(purchase.quantity);
uint256 totalPrice = _estimateSwap(purchase.token, referenceToken, referenceTotalPrice, purchase.userData);
uint256 swapRate = referenceTotalPrice.mul(10**18).div(totalPrice);
purchase.pricingData = new bytes32[](2);
purchase.pricingData[0] = bytes32(unitPrice);
purchase.pricingData[1] = bytes32(swapRate);
purchase.totalPrice = totalPrice;
return true;
}
}
// File contracts/sale/UniswapSwapSale.sol
pragma solidity 0.6.8;
/**
* @title UniswapSwapSale
* An SwapSale which implements a UniswapV2-based token conversion pricing strategy. The final
* implementer is responsible for implementing any additional pricing and/or delivery logic.
*
* PurchaseData.pricingData:
* - a non-zero length array indicates Uniswap-based pricing, otherwise indicates fixed pricing.
* - [0] uint256: the token conversion rate used for Uniswap-based pricing.
*
* PurchaseData.userData MUST be encoded in-place as follows:
* - uint256: the maximum amount of purchase tokens to swap for reference tokens, in payment for
* a purchase. A value of 0 will use the maximum supported amount (default: type(uint256).max).
* - uint256: the token swap deadline as a UNIX timestamp. A value of 0 will not apply any
* deadline.
* - any additional fields may be defined in-place by deriving contracts (to be documented by the
* deriving contract).
*/
contract UniswapSwapSale is SwapSale, UniswapV2Adapter {
using SafeMath for uint256;
/**
* Constructor.
* @dev Emits the `MagicValues` event.
* @dev Emits the `Paused` event.
* @param payoutWallet_ The payout wallet.
* @param skusCapacity The cap for the number of managed SKUs.
* @param tokensPerSkuCapacity The cap for the number of tokens managed per SKU.
* @param referenceToken The token to use for oracle-based conversions.
* @param uniswapV2Router The UniswapV2 router contract used to facilitate operations against the Uniswap network.
*/
constructor(
address payoutWallet_,
uint256 skusCapacity,
uint256 tokensPerSkuCapacity,
address referenceToken,
IUniswapV2Router uniswapV2Router
) public SwapSale(payoutWallet_, skusCapacity, tokensPerSkuCapacity, referenceToken) UniswapV2Adapter(uniswapV2Router) {}
/**
* Receives refunded ETH from the Uniswap token swapping operation.
* @dev Reverts if the sender of ETH isn't the Uniswap V2 router.
*/
receive() external payable {
// solhint-disable-next-line reason-string
require(_msgSender() == address(uniswapV2Router), "UniswapSwapSale: Invalid ETH sender");
}
/* Internal Life Cycle Functions */
/**
* Lifecycle step which validates the purchase pre-conditions.
* @dev Responsibilities:
* - Ensure that the purchase pre-conditions are met and revert if not.
* @param purchase The purchase conditions.
*/
function _validation(PurchaseData memory purchase) internal view virtual override {
super._validation(purchase);
// solhint-disable-next-line reason-string
require(purchase.userData.length >= 64, "UniswapSwapSale: Missing expected purchase user data");
}
/**
* Lifecycle step which manages the transfer of funds from the purchaser.
* @dev Responsibilities:
* - Ensure the payment reaches destination in the expected output token;
* - Handle any token swap logic;
* - Add any relevant extra data related to payment in `purchase.paymentData` and document how to interpret it.
* @dev Reverts in case of payment failure.
* @param purchase The purchase conditions.
*/
function _payment(PurchaseData memory purchase) internal virtual override {
if ((purchase.pricingData.length != 0) && (purchase.token != TOKEN_ETH)) {
bytes memory data = purchase.userData;
uint256 maxFromAmount;
assembly {
maxFromAmount := mload(add(data, 32))
}
if (maxFromAmount == 0) {
maxFromAmount = type(uint256).max;
}
// solhint-disable-next-line reason-string
require(IERC20(purchase.token).approve(address(uniswapV2Router), maxFromAmount), "UniswapSwapSale: ERC20 payment approval failed");
}
super._payment(purchase);
}
/* Internal Utility Functions */
/**
* Retrieves the conversion rate for the `fromToken`/`toToken` pair via the oracle.
* @dev Reverts if the oracle does not provide a conversion rate for the pair.
* @param fromToken The source token from which the conversion rate is derived from.
* @param toToken the destination token from which the conversion rate is derived from.
* @param *data* Additional data with no specified format for deriving the conversion rate.
* @return rate The conversion rate for the `fromToken`/`toToken` pair, retrieved via the oracle.
*/
function _conversionRate(
address fromToken,
address toToken,
bytes memory /*data*/
) internal view virtual override returns (uint256 rate) {
if (fromToken == TOKEN_ETH) {
fromToken = uniswapV2Router.WETH();
}
if (toToken == TOKEN_ETH) {
toToken = uniswapV2Router.WETH();
}
(uint256 fromReserve, uint256 toReserve) = _getReserves(fromToken, toToken);
rate = toReserve.mul(10**18).div(fromReserve);
}
/**
* Estimates the optimal amount of `fromToken` to provide in order to swap for the specified amount of
* `toToken`, via the oracle.
* @dev Reverts if the oracle cannot estimate the optimal amount of `fromToken` to provide.
* @param fromToken The source token to swap from.
* @param toToken The destination token to swap to.
* @param toAmount The amount of destination tokens to swap for.
* @param *data* Additional data with no specified format for deriving the swap estimate.
* @return fromAmount The estimated optimal amount of `fromToken` to provide in order to perform a swap,
* via the oracle.
*/
function _estimateSwap(
address fromToken,
address toToken,
uint256 toAmount,
bytes memory /*data*/
) internal view virtual override returns (uint256 fromAmount) {
if (fromToken == TOKEN_ETH) {
fromToken = uniswapV2Router.WETH();
}
if (toToken == TOKEN_ETH) {
toToken = uniswapV2Router.WETH();
}
fromAmount = _getAmountsIn(fromToken, toToken, toAmount);
}
/**
* Swaps `fromToken` for the specified amount of `toToken`, via the oracle.
* @dev Reverts if the oracle is unable to perform the token swap.
* @param fromToken The source token to swap from.
* @param toToken The destination token to swap to.
* @param toAmount The amount of destination tokens to swap for.
* @param data Additional data for UniswapV2 (uint256 `maxFromAmount`, uint256 `deadline`).
* @return fromAmount The amount of `fromToken` swapped for the specified amount of `toToken`, via the
* oracle.
*/
function _swap(
address fromToken,
address toToken,
uint256 toAmount,
bytes memory data
) internal virtual override returns (uint256 fromAmount) {
uint256 maxFromAmount;
uint256 deadline;
assembly {
maxFromAmount := mload(add(data, 32))
deadline := mload(add(data, 64))
}
if (maxFromAmount == 0) {
if (fromToken == TOKEN_ETH) {
maxFromAmount = msg.value;
} else {
maxFromAmount = type(uint256).max;
}
}
if (deadline == 0) {
deadline = type(uint256).max;
}
if (fromToken == TOKEN_ETH) {
fromToken = uniswapV2Router.WETH();
}
if (toToken == TOKEN_ETH) {
toToken = uniswapV2Router.WETH();
}
fromAmount = _swapTokensForExactAmount(fromToken, toToken, toAmount, maxFromAmount, address(this), deadline);
}
}
// File contracts/mocks/sale/UniswapSwapSaleMock.sol
pragma solidity 0.6.8;
contract UniswapSwapSaleMock is UniswapSwapSale {
event UnderscoreSwapResult(uint256 fromAmount);
constructor(
address payoutWallet_,
uint256 skusCapacity,
uint256 tokensPerSkuCapacity,
address referenceToken,
IUniswapV2Router uniswapV2Router
) public UniswapSwapSale(payoutWallet_, skusCapacity, tokensPerSkuCapacity, referenceToken, uniswapV2Router) {}
function createSku(
bytes32 sku,
uint256 totalSupply,
uint256 maxQuantityPerPurchase,
address notificationsReceiver
) external {
_createSku(sku, totalSupply, maxQuantityPerPurchase, notificationsReceiver);
}
function addEth() external payable {}
function callUnderscoreValidation(
address payable recipient,
address token,
bytes32 sku,
uint256 quantity,
bytes calldata userData
) external view {
PurchaseData memory purchaseData;
purchaseData.purchaser = _msgSender();
purchaseData.recipient = recipient;
purchaseData.token = token;
purchaseData.sku = sku;
purchaseData.quantity = quantity;
purchaseData.userData = userData;
_validation(purchaseData);
}
function callUnderscorePricing(
address payable recipient,
address token,
bytes32 sku,
uint256 quantity,
bytes calldata userData
) external view returns (uint256 totalPrice, bytes32[] memory pricingData) {
PurchaseData memory purchaseData;
purchaseData.purchaser = _msgSender();
purchaseData.recipient = recipient;
purchaseData.token = token;
purchaseData.sku = sku;
purchaseData.quantity = quantity;
purchaseData.userData = userData;
_pricing(purchaseData);
totalPrice = purchaseData.totalPrice;
pricingData = purchaseData.pricingData;
}
function callUnderscorePayment(
address payable recipient,
address token,
bytes32 sku,
uint256 quantity,
bytes calldata userData,
uint256 totalPrice,
bytes32[] calldata pricingData
) external payable {
PurchaseData memory purchaseData;
purchaseData.purchaser = _msgSender();
purchaseData.recipient = recipient;
purchaseData.token = token;
purchaseData.sku = sku;
purchaseData.quantity = quantity;
purchaseData.userData = userData;
purchaseData.totalPrice = totalPrice;
purchaseData.pricingData = pricingData;
_payment(purchaseData);
}
function callUnderscoreConversionRate(
address fromToken,
address toToken,
bytes calldata data
) external view returns (uint256 rate) {
rate = _conversionRate(fromToken, toToken, data);
}
function callUnderscoreEstimateSwap(
address fromToken,
address toToken,
uint256 toAmount,
bytes calldata data
) external view returns (uint256 fromAmount) {
fromAmount = _estimateSwap(fromToken, toToken, toAmount, data);
}
function callUnderscoreSwap(
address fromToken,
uint256 fromAmount,
address toToken,
uint256 toAmount,
bytes calldata data
) external payable {
if (fromToken != TOKEN_ETH) {
// solhint-disable-next-line reason-string
require(IERC20(fromToken).approve(address(uniswapV2Router), fromAmount), "UniswapSwapSaleMock: ERC20 swap approval failed");
// solhint-disable-next-line reason-string
require(IERC20(fromToken).allowance(msg.sender, address(this)) >= fromAmount, "UniswapSwapSaleMock: ERC20 allowance insufficient");
// solhint-disable-next-line reason-string
require(IERC20(fromToken).transferFrom(msg.sender, address(this), fromAmount), "UniswapSwapSaleMock: ERC20 transfer from failed");
}
fromAmount = _swap(fromToken, toToken, toAmount, data);
emit UnderscoreSwapResult(fromAmount);
}
function getReserves(address tokenA, address tokenB) external view returns (uint256 reserveA, uint256 reserveB) {
if (tokenA == TOKEN_ETH) {
tokenA = uniswapV2Router.WETH();
}
if (tokenB == TOKEN_ETH) {
tokenB = uniswapV2Router.WETH();
}
(reserveA, reserveB) = _getReserves(tokenA, tokenB);
}
}
|
Retrieves the conversion rate for the `fromToken`/`toToken` pair via the oracle. Reverts if the oracle does not provide a conversion rate for the pair. fromToken The source token from which the conversion rate is derived from. toToken the destination token from which the conversion rate is derived from. data Additional data with no specified format for deriving the conversion rate. return rate The conversion rate for the `fromToken`/`toToken` pair, retrieved via the oracle./
|
function _conversionRate(
address fromToken,
address toToken,
bytes memory /*data*/
) internal view virtual override returns (uint256 rate) {
if (fromToken == TOKEN_ETH) {
fromToken = uniswapV2Router.WETH();
}
if (toToken == TOKEN_ETH) {
toToken = uniswapV2Router.WETH();
}
(uint256 fromReserve, uint256 toReserve) = _getReserves(fromToken, toToken);
rate = toReserve.mul(10**18).div(fromReserve);
}
| 2,556,270 |
library SafeMath {
/**
* @dev Multiplies two numbers, throws on overflow.
*/
function mul(uint256 a, uint256 b) internal pure returns (uint256) {
if (a == 0) {
return 0;
}
uint256 c = a * b;
assert(c / a == b);
return c;
}
/**
* @dev Integer division of two numbers, truncating the quotient.
*/
function div(uint256 a, uint256 b) internal pure returns (uint256) {
// assert(b > 0); // Solidity automatically throws when dividing by 0
uint256 c = a / b;
// assert(a == b * c + a % b); // There is no case in which this doesn't hold
return c;
}
/**
* @dev Substracts two numbers, throws on overflow (i.e. if subtrahend is greater than minuend).
*/
function sub(uint256 a, uint256 b) internal pure returns (uint256) {
assert(b <= a);
return a - b;
}
/**
* @dev Adds two numbers, throws on overflow.
*/
function add(uint256 a, uint256 b) internal pure returns (uint256) {
uint256 c = a + b;
assert(c >= a);
return c;
}
}
/**
* @title Ownable
* @dev The Ownable contract has an owner address, and provides basic authorization control
* functions, this simplifies the implementation of "user permissions".
*/
contract Ownable {
address public owner;
event OwnershipTransferred(address indexed previousOwner, address indexed newOwner);
/**
* @dev The Ownable constructor sets the original `owner` of the contract to the sender
* account.
*/
function Ownable() public {
owner = msg.sender;
}
/**
* @dev Throws if called by any account other than the owner.
*/
modifier onlyOwner() {
require(msg.sender == owner);
_;
}
/**
* @dev Allows the current owner to transfer control of the contract to a newOwner.
* @param newOwner The address to transfer ownership to.
*/
function transferOwnership(address newOwner) public onlyOwner {
require(newOwner != address(0));
OwnershipTransferred(owner, newOwner);
owner = newOwner;
}
}
/**
* @title Pausable
* @dev Base contract which allows children to implement an emergency stop mechanism.
*/
contract Pausable is Ownable {
event Pause();
event Unpause();
bool public paused = false;
/**
* @dev Modifier to make a function callable only when the contract is not paused.
*/
modifier whenNotPaused() {
require(!paused);
_;
}
/**
* @dev Modifier to make a function callable only when the contract is paused.
*/
modifier whenPaused() {
require(paused);
_;
}
/**
* @dev called by the owner to pause, triggers stopped state
*/
function pause() onlyOwner whenNotPaused public {
paused = true;
Pause();
}
/**
* @dev called by the owner to unpause, returns to normal state
*/
function unpause() onlyOwner whenPaused public {
paused = false;
Unpause();
}
}
/**
* @title ERC20Basic
* @dev Simpler version of ERC20 interface
* @dev see https://github.com/ethereum/EIPs/issues/179
*/
contract ERC20Basic {
function totalSupply() public view returns (uint256);
function balanceOf(address who) public view returns (uint256);
function transfer(address to, uint256 value) public returns (bool);
event Transfer(address indexed from, address indexed to, uint256 value);
}
/**
* @title ERC20 interface
* @dev see https://github.com/ethereum/EIPs/issues/20
*/
contract ERC20 is ERC20Basic {
function allowance(address owner, address spender) public view returns (uint256);
function transferFrom(address from, address to, uint256 value) public returns (bool);
function approve(address spender, uint256 value) public returns (bool);
event Approval(address indexed owner, address indexed spender, uint256 value);
}
/**
* @title Basic token
* @dev Basic version of StandardToken, with no allowances.
*/
contract BasicToken is ERC20Basic {
using SafeMath for uint256;
mapping(address => uint256) balances;
uint256 totalSupply_;
/**
* @dev total number of tokens in existence
*/
function totalSupply() public view returns (uint256) {
return totalSupply_;
}
/**
* @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(_to != address(0));
require(_value <= balances[msg.sender]);
// SafeMath.sub will throw if there is not enough balance.
balances[msg.sender] = balances[msg.sender].sub(_value);
balances[_to] = balances[_to].add(_value);
Transfer(msg.sender, _to, _value);
return true;
}
/**
* @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 balance) {
return balances[_owner];
}
}
/**
* @title Standard ERC20 token
*
* @dev Implementation of the basic standard token.
* @dev https://github.com/ethereum/EIPs/issues/20
* @dev Based on code by FirstBlood: https://github.com/Firstbloodio/token/blob/master/smart_contract/FirstBloodToken.sol
*/
contract StandardToken is ERC20, BasicToken {
mapping (address => mapping (address => uint256)) internal allowed;
/**
* @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(_to != address(0));
require(_value <= balances[_from]);
require(_value <= allowed[_from][msg.sender]);
balances[_from] = balances[_from].sub(_value);
balances[_to] = balances[_to].add(_value);
allowed[_from][msg.sender] = allowed[_from][msg.sender].sub(_value);
Transfer(_from, _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) {
allowed[msg.sender][_spender] = _value;
Approval(msg.sender, _spender, _value);
return true;
}
/**
* @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 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 increaseApproval(address _spender, uint _addedValue) public returns (bool) {
allowed[msg.sender][_spender] = allowed[msg.sender][_spender].add(_addedValue);
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 decreaseApproval(address _spender, uint _subtractedValue) public returns (bool) {
uint oldValue = allowed[msg.sender][_spender];
if (_subtractedValue > oldValue) {
allowed[msg.sender][_spender] = 0;
} else {
allowed[msg.sender][_spender] = oldValue.sub(_subtractedValue);
}
Approval(msg.sender, _spender, allowed[msg.sender][_spender]);
return true;
}
}
/**
* @title Mintable token
* @dev Simple ERC20 Token example, with mintable token creation
* @dev Issue: * https://github.com/OpenZeppelin/zeppelin-solidity/issues/120
* Based on code by TokenMarketNet: https://github.com/TokenMarketNet/ico/blob/master/contracts/MintableToken.sol
*/
contract MintableToken is StandardToken, Ownable {
event Mint(address indexed to, uint256 amount);
event MintFinished();
bool public mintingFinished = false;
modifier canMint() {
require(!mintingFinished);
_;
}
/**
* @dev Function to mint tokens
* @param _to The address that will receive the minted tokens.
* @param _amount The amount of tokens to mint.
* @return A boolean that indicates if the operation was successful.
*/
function mint(address _to, uint256 _amount) onlyOwner public returns (bool) {
totalSupply_ = totalSupply_.add(_amount);
balances[_to] = balances[_to].add(_amount);
Mint(_to, _amount);
Transfer(address(0), _to, _amount);
return true;
}
/**
* @dev Function to stop minting new tokens.
* @return True if the operation was successful.
*/
function finishMinting() onlyOwner canMint public returns (bool) {
mintingFinished = true;
MintFinished();
return true;
}
}
/**
* @title Pausable token
* @dev StandardToken modified with pausable transfers.
**/
contract PausableToken is StandardToken, Pausable {
function transfer(address _to, uint256 _value) public whenNotPaused returns (bool) {
return super.transfer(_to, _value);
}
function transferFrom(address _from, address _to, uint256 _value) public whenNotPaused returns (bool) {
return super.transferFrom(_from, _to, _value);
}
function approve(address _spender, uint256 _value) public whenNotPaused returns (bool) {
return super.approve(_spender, _value);
}
function increaseApproval(address _spender, uint _addedValue) public whenNotPaused returns (bool success) {
return super.increaseApproval(_spender, _addedValue);
}
function decreaseApproval(address _spender, uint _subtractedValue) public whenNotPaused returns (bool success) {
return super.decreaseApproval(_spender, _subtractedValue);
}
}
/**
* @dev Smw token ERC20 contract
* Based on references from OpenZeppelin: https://github.com/OpenZeppelin/zeppelin-solidity
*/
contract Smw is MintableToken, PausableToken {
string public constant version = "1.1";
string public constant name = "Sameway DIGICCY";
string public constant symbol = "SMW";
uint8 public constant decimals = 18;
event MintMasterTransferred(address indexed previousMaster, address indexed newMaster);
address public mintMaster;
modifier onlyMintMasterOrOwner() {
require(msg.sender == mintMaster || msg.sender == owner);
_;
}
function Smw() public {
mintMaster = msg.sender;
}
function transferMintMaster(address newMaster) onlyOwner public {
require(newMaster != address(0));
MintMasterTransferred(mintMaster, newMaster);
mintMaster = newMaster;
}
function mintToAddresses(address[] addresses, uint256 amount) public onlyMintMasterOrOwner canMint {
for (uint i = 0; i < addresses.length; i++) {
require(mint(addresses[i], amount));
}
}
function mintToAddressesAndAmounts(address[] addresses, uint256[] amounts) public onlyMintMasterOrOwner canMint {
require(addresses.length == amounts.length);
for (uint i = 0; i < addresses.length; i++) {
require(mint(addresses[i], amounts[i]));
}
}
/**
* @dev Function to mint tokens
* @param _to The address that will receive the minted tokens.
* @param _amount The amount of tokens to mint.
* @return A boolean that indicates if the operation was successful.
*/
function mint(address _to, uint256 _amount) onlyMintMasterOrOwner canMint public returns (bool) {
address oldOwner = owner;
owner = msg.sender;
bool result = super.mint(_to, _amount);
owner = oldOwner;
return result;
}
}
|
Function to mint tokens _to The address that will receive the minted tokens. _amount The amount of tokens to mint. return A boolean that indicates if the operation was successful./
|
function mint(address _to, uint256 _amount) onlyMintMasterOrOwner canMint public returns (bool) {
address oldOwner = owner;
owner = msg.sender;
bool result = super.mint(_to, _amount);
owner = oldOwner;
return result;
}
| 461,026 |
./partial_match/4/0x7503539b4c684682CbE0C8A0746e124c6b803162/sources/UniftyMarket.sol
|
Override isApprovedForAll to whitelist user's OpenSea proxy accounts to enable gas-free listings./ Whitelist OpenSea proxy contract for easy trading.
|
function isApprovedForAll(address _owner, address _operator) public view returns (bool isOperator) {
ProxyRegistry proxyRegistry = ProxyRegistry(proxyRegistryAddress);
if (address(proxyRegistry.proxies(_owner)) == _operator) {
return true;
}
return ERC1155.isApprovedForAll(_owner, _operator);
}*/
| 8,744,705 |
./partial_match/1/0x3198EAdB777b9b6C789bfc89491774644E95eD7e/sources/contracts/interfaces/pool/ISolidlyV3PoolState.sol
|
Pool state that can change These methods compose the pool's state, and can change with any frequency including multiple times per transaction
|
interface ISolidlyV3PoolState {
function slot0() external view returns (uint160 sqrtPriceX96, int24 tick, uint24 fee, bool unlocked);
function poolFees() external view returns (uint128 token0, uint128 token1);
function liquidity() external view returns (uint128);
function ticks(int24 tick) external view returns (uint128 liquidityGross, int128 liquidityNet, bool initialized);
function tickBitmap(int16 wordPosition) external view returns (uint256);
function positions(
bytes32 key
) external view returns (uint128 _liquidity, uint128 tokensOwed0, uint128 tokensOwed1);
pragma solidity >=0.5.0;
}
| 15,989,230 |
./partial_match/1/0xc06B961D9Ef666FDdCc15F37264fbf6352cA2264/sources/BuyBack.sol
|
returns bool if the contract can send to treasury if value of USDC > MIN_SEND_TO_TREASURY
|
function canSendToTreasury() public view override returns (bool) {
if (ERC20(USDC).balanceOf(address(this)) > MIN_SEND_TO_TREASURY)
return true;
return false;
}
| 15,738,411 |
pragma solidity ^0.4.13;
//solc --bin --abi --optimize --optimize-runs 20000 -o . Testpool.sol
import "./Ethash.sol";
/**
* @title RLPReader
*
* RLPReader is used to read and parse RLP encoded data in memory.
*
* @author Andreas Olofsson ([email protected])
*
* code was taken from https://github.com/androlo/standard-contracts/blob/master/contracts/src/codec/RLP.sol
*
*/
library RLP {
uint constant DATA_SHORT_START = 0x80;
uint constant DATA_LONG_START = 0xB8;
uint constant LIST_SHORT_START = 0xC0;
uint constant LIST_LONG_START = 0xF8;
uint constant DATA_LONG_OFFSET = 0xB7;
uint constant LIST_LONG_OFFSET = 0xF7;
struct RLPItem {
uint _unsafe_memPtr; // Pointer to the RLP-encoded bytes.
uint _unsafe_length; // Number of bytes. This is the full length of the string.
}
struct Iterator {
RLPItem _unsafe_item; // Item that's being iterated over.
uint _unsafe_nextPtr; // Position of the next item in the list.
}
/* Iterator */
function next(Iterator memory self) internal constant returns (RLPItem memory subItem) {
if(hasNext(self)) {
var ptr = self._unsafe_nextPtr;
var itemLength = _itemLength(ptr);
subItem._unsafe_memPtr = ptr;
subItem._unsafe_length = itemLength;
self._unsafe_nextPtr = ptr + itemLength;
}
else
revert();
}
function next(Iterator memory self, bool strict) internal constant returns (RLPItem memory subItem) {
subItem = next(self);
if(strict && !_validate(subItem))
revert();
return;
}
function hasNext(Iterator memory self) internal constant returns (bool) {
var item = self._unsafe_item;
return self._unsafe_nextPtr < item._unsafe_memPtr + item._unsafe_length;
}
/* RLPItem */
/// @dev Creates an RLPItem from an array of RLP encoded bytes.
/// @param self The RLP encoded bytes.
/// @return An RLPItem
function toRLPItem(bytes memory self) internal constant returns (RLPItem memory) {
uint len = self.length;
if (len == 0) {
return RLPItem(0, 0);
}
uint memPtr;
assembly {
memPtr := add(self, 0x20)
}
return RLPItem(memPtr, len);
}
/// @dev Creates an RLPItem from an array of RLP encoded bytes.
/// @param self The RLP encoded bytes.
/// @param strict Will throw if the data is not RLP encoded.
/// @return An RLPItem
function toRLPItem(bytes memory self, bool strict) internal constant returns (RLPItem memory) {
var item = toRLPItem(self);
if(strict) {
uint len = self.length;
if(_payloadOffset(item) > len)
revert();
if(_itemLength(item._unsafe_memPtr) != len)
revert();
if(!_validate(item))
revert();
}
return item;
}
/// @dev Check if the RLP item is null.
/// @param self The RLP item.
/// @return 'true' if the item is null.
function isNull(RLPItem memory self) internal constant returns (bool ret) {
return self._unsafe_length == 0;
}
/// @dev Check if the RLP item is a list.
/// @param self The RLP item.
/// @return 'true' if the item is a list.
function isList(RLPItem memory self) internal constant returns (bool ret) {
if (self._unsafe_length == 0)
return false;
uint memPtr = self._unsafe_memPtr;
assembly {
ret := iszero(lt(byte(0, mload(memPtr)), 0xC0))
}
}
/// @dev Check if the RLP item is data.
/// @param self The RLP item.
/// @return 'true' if the item is data.
function isData(RLPItem memory self) internal constant returns (bool ret) {
if (self._unsafe_length == 0)
return false;
uint memPtr = self._unsafe_memPtr;
assembly {
ret := lt(byte(0, mload(memPtr)), 0xC0)
}
}
/// @dev Check if the RLP item is empty (string or list).
/// @param self The RLP item.
/// @return 'true' if the item is null.
function isEmpty(RLPItem memory self) internal constant returns (bool ret) {
if(isNull(self))
return false;
uint b0;
uint memPtr = self._unsafe_memPtr;
assembly {
b0 := byte(0, mload(memPtr))
}
return (b0 == DATA_SHORT_START || b0 == LIST_SHORT_START);
}
/// @dev Get the number of items in an RLP encoded list.
/// @param self The RLP item.
/// @return The number of items.
function items(RLPItem memory self) internal constant returns (uint) {
if (!isList(self))
return 0;
uint b0;
uint memPtr = self._unsafe_memPtr;
assembly {
b0 := byte(0, mload(memPtr))
}
uint pos = memPtr + _payloadOffset(self);
uint last = memPtr + self._unsafe_length - 1;
uint itms;
while(pos <= last) {
pos += _itemLength(pos);
itms++;
}
return itms;
}
/// @dev Create an iterator.
/// @param self The RLP item.
/// @return An 'Iterator' over the item.
function iterator(RLPItem memory self) internal constant returns (Iterator memory it) {
if (!isList(self))
revert();
uint ptr = self._unsafe_memPtr + _payloadOffset(self);
it._unsafe_item = self;
it._unsafe_nextPtr = ptr;
}
/// @dev Return the RLP encoded bytes.
/// @param self The RLPItem.
/// @return The bytes.
/*
function toBytes(RLPItem memory self) internal constant returns (bytes memory bts) {
var len = self._unsafe_length;
if (len == 0)
return;
bts = new bytes(len);
_copyToBytes(self._unsafe_memPtr, bts, len);
}*/
/// @dev Decode an RLPItem into bytes. This will not work if the
/// RLPItem is a list.
/// @param self The RLPItem.
/// @return The decoded string.
/*
function toData(RLPItem memory self) internal constant returns (bytes memory bts) {
if(!isData(self))
revert();
var (rStartPos, len) = _decode(self);
bts = new bytes(len);
_copyToBytes(rStartPos, bts, len);
}*/
/// @dev Get the list of sub-items from an RLP encoded list.
/// Warning: This is inefficient, as it requires that the list is read twice.
/// @param self The RLP item.
/// @return Array of RLPItems.
function toList(RLPItem memory self) internal constant returns (RLPItem[] memory list) {
if(!isList(self))
revert();
var numItems = items(self);
list = new RLPItem[](numItems);
var it = iterator(self);
uint idx;
while(hasNext(it)) {
list[idx] = next(it);
idx++;
}
}
/// @dev Decode an RLPItem into an ascii string. This will not work if the
/// RLPItem is a list.
/// @param self The RLPItem.
/// @return The decoded string.
/*
function toAscii(RLPItem memory self) internal constant returns (string memory str) {
if(!isData(self))
revert();
var (rStartPos, len) = _decode(self);
bytes memory bts = new bytes(len);
_copyToBytes(rStartPos, bts, len);
str = string(bts);
}*/
/// @dev Decode an RLPItem into a uint. This will not work if the
/// RLPItem is a list.
/// @param self The RLPItem.
/// @return The decoded string.
function toUint(RLPItem memory self) internal constant returns (uint data) {
if(!isData(self))
revert();
var (rStartPos, len) = _decode(self);
if (len > 32 || len == 0)
revert();
assembly {
data := div(mload(rStartPos), exp(256, sub(32, len)))
}
}
/// @dev Decode an RLPItem into a boolean. This will not work if the
/// RLPItem is a list.
/// @param self The RLPItem.
/// @return The decoded string.
function toBool(RLPItem memory self) internal constant returns (bool data) {
if(!isData(self))
revert();
var (rStartPos, len) = _decode(self);
if (len != 1)
revert();
uint temp;
assembly {
temp := byte(0, mload(rStartPos))
}
if (temp > 1)
revert();
return temp == 1 ? true : false;
}
/// @dev Decode an RLPItem into a byte. This will not work if the
/// RLPItem is a list.
/// @param self The RLPItem.
/// @return The decoded string.
function toByte(RLPItem memory self) internal constant returns (byte data) {
if(!isData(self))
revert();
var (rStartPos, len) = _decode(self);
if (len != 1)
revert();
uint temp;
assembly {
temp := byte(0, mload(rStartPos))
}
return byte(temp);
}
/// @dev Decode an RLPItem into an int. This will not work if the
/// RLPItem is a list.
/// @param self The RLPItem.
/// @return The decoded string.
function toInt(RLPItem memory self) internal constant returns (int data) {
return int(toUint(self));
}
/// @dev Decode an RLPItem into a bytes32. This will not work if the
/// RLPItem is a list.
/// @param self The RLPItem.
/// @return The decoded string.
function toBytes32(RLPItem memory self) internal constant returns (bytes32 data) {
return bytes32(toUint(self));
}
/// @dev Decode an RLPItem into an address. This will not work if the
/// RLPItem is a list.
/// @param self The RLPItem.
/// @return The decoded string.
function toAddress(RLPItem memory self) internal constant returns (address data) {
if(!isData(self))
revert();
var (rStartPos, len) = _decode(self);
if (len != 20)
revert();
assembly {
data := div(mload(rStartPos), exp(256, 12))
}
}
// Get the payload offset.
function _payloadOffset(RLPItem memory self) private constant returns (uint) {
if(self._unsafe_length == 0)
return 0;
uint b0;
uint memPtr = self._unsafe_memPtr;
assembly {
b0 := byte(0, mload(memPtr))
}
if(b0 < DATA_SHORT_START)
return 0;
if(b0 < DATA_LONG_START || (b0 >= LIST_SHORT_START && b0 < LIST_LONG_START))
return 1;
if(b0 < LIST_SHORT_START)
return b0 - DATA_LONG_OFFSET + 1;
return b0 - LIST_LONG_OFFSET + 1;
}
// Get the full length of an RLP item.
function _itemLength(uint memPtr) private constant returns (uint len) {
uint b0;
assembly {
b0 := byte(0, mload(memPtr))
}
if (b0 < DATA_SHORT_START)
len = 1;
else if (b0 < DATA_LONG_START)
len = b0 - DATA_SHORT_START + 1;
else if (b0 < LIST_SHORT_START) {
assembly {
let bLen := sub(b0, 0xB7) // bytes length (DATA_LONG_OFFSET)
let dLen := div(mload(add(memPtr, 1)), exp(256, sub(32, bLen))) // data length
len := add(1, add(bLen, dLen)) // total length
}
}
else if (b0 < LIST_LONG_START)
len = b0 - LIST_SHORT_START + 1;
else {
assembly {
let bLen := sub(b0, 0xF7) // bytes length (LIST_LONG_OFFSET)
let dLen := div(mload(add(memPtr, 1)), exp(256, sub(32, bLen))) // data length
len := add(1, add(bLen, dLen)) // total length
}
}
}
// Get start position and length of the data.
function _decode(RLPItem memory self) private constant returns (uint memPtr, uint len) {
if(!isData(self))
revert();
uint b0;
uint start = self._unsafe_memPtr;
assembly {
b0 := byte(0, mload(start))
}
if (b0 < DATA_SHORT_START) {
memPtr = start;
len = 1;
return;
}
if (b0 < DATA_LONG_START) {
len = self._unsafe_length - 1;
memPtr = start + 1;
} else {
uint bLen;
assembly {
bLen := sub(b0, 0xB7) // DATA_LONG_OFFSET
}
len = self._unsafe_length - 1 - bLen;
memPtr = start + bLen + 1;
}
return;
}
// Assumes that enough memory has been allocated to store in target.
/* this code is commented because I am too lazy to fix it to prevent jumpi warning, and since I don't use it anyway, I might as well just remove it.
function _copyToBytes(uint btsPtr, bytes memory tgt, uint btsLen) private constant {
// Exploiting the fact that 'tgt' was the last thing to be allocated,
// we can write entire words, and just overwrite any excess.
assembly {
{
let i := 0 // Start at arr + 0x20
let words := div(add(btsLen, 31), 32)
let rOffset := btsPtr
let wOffset := add(tgt, 0x20)
tag_loop:
jumpi(end, eq(i, words))
{
let offset := mul(i, 0x20)
mstore(add(wOffset, offset), mload(add(rOffset, offset)))
i := add(i, 1)
}
jump(tag_loop)
end:
mstore(add(tgt, add(0x20, mload(tgt))), 0)
}
}
}*/
// Check that an RLP item is valid.
function _validate(RLPItem memory self) private constant returns (bool ret) {
// Check that RLP is well-formed.
uint b0;
uint b1;
uint memPtr = self._unsafe_memPtr;
assembly {
b0 := byte(0, mload(memPtr))
b1 := byte(1, mload(memPtr))
}
if(b0 == DATA_SHORT_START + 1 && b1 < DATA_SHORT_START)
return false;
return true;
}
}
contract Agt {
using RLP for RLP.RLPItem;
using RLP for RLP.Iterator;
using RLP for bytes;
struct BlockHeader {
uint prevBlockHash; // 0
uint coinbase; // 1
uint blockNumber; // 8
//uint gasUsed; // 10
uint timestamp; // 11
bytes32 extraData; // 12
}
function Agt() {}
function parseBlockHeader( bytes rlpHeader ) constant internal returns(BlockHeader) {
BlockHeader memory header;
var it = rlpHeader.toRLPItem().iterator();
uint idx;
while(it.hasNext()) {
if( idx == 0 ) header.prevBlockHash = it.next().toUint();
else if ( idx == 2 ) header.coinbase = it.next().toUint();
else if ( idx == 8 ) header.blockNumber = it.next().toUint();
else if ( idx == 11 ) header.timestamp = it.next().toUint();
else if ( idx == 12 ) header.extraData = bytes32(it.next().toUint());
else it.next();
idx++;
}
return header;
}
//event VerifyAgt( string msg, uint index );
event VerifyAgt( uint error, uint index );
struct VerifyAgtData {
uint rootHash;
uint rootMin;
uint rootMax;
uint leafHash;
uint leafCounter;
}
function verifyAgt( VerifyAgtData data,
uint branchIndex,
uint[] countersBranch,
uint[] hashesBranch ) constant internal returns(bool) {
uint currentHash = data.leafHash & 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF;
uint leftCounterMin;
uint leftCounterMax;
uint leftHash;
uint rightCounterMin;
uint rightCounterMax;
uint rightHash;
uint min = data.leafCounter;
uint max = data.leafCounter;
for( uint i = 0 ; i < countersBranch.length ; i++ ) {
if( branchIndex & 0x1 > 0 ) {
leftCounterMin = countersBranch[i] & 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF;
leftCounterMax = countersBranch[i] >> 128;
leftHash = hashesBranch[i];
rightCounterMin = min;
rightCounterMax = max;
rightHash = currentHash;
}
else {
leftCounterMin = min;
leftCounterMax = max;
leftHash = currentHash;
rightCounterMin = countersBranch[i] & 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF;
rightCounterMax = countersBranch[i] >> 128;
rightHash = hashesBranch[i];
}
currentHash = uint(sha3(leftCounterMin + (leftCounterMax << 128),
leftHash,
rightCounterMin + (rightCounterMax << 128),
rightHash)) & 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF;
if( (leftCounterMin >= leftCounterMax) || (rightCounterMin >= rightCounterMax) ) {
if( i > 0 ) {
//VerifyAgt( "counters mismatch",i);
VerifyAgt( 0x80000000, i );
return false;
}
if( leftCounterMin > leftCounterMax ) {
//VerifyAgt( "counters mismatch",i);
VerifyAgt( 0x80000001, i );
return false;
}
if( rightCounterMin > rightCounterMax ) {
//VerifyAgt( "counters mismatch",i);
VerifyAgt( 0x80000002, i );
return false;
}
}
if( leftCounterMax >= rightCounterMin ) {
VerifyAgt( 0x80000009, i );
return false;
}
min = leftCounterMin;
max = rightCounterMax;
branchIndex = branchIndex / 2;
}
if( min != data.rootMin ) {
//VerifyAgt( "min does not match root min",min);
VerifyAgt( 0x80000003, min );
return false;
}
if( max != data.rootMax ) {
//VerifyAgt( "max does not match root max",max);
VerifyAgt( 0x80000004, max );
return false;
}
if( currentHash != data.rootHash ) {
//VerifyAgt( "hash does not match root hash",currentHash);
VerifyAgt( 0x80000005, currentHash );
return false;
}
return true;
}
function verifyAgtDebugForTesting( uint rootHash,
uint rootMin,
uint rootMax,
uint leafHash,
uint leafCounter,
uint branchIndex,
uint[] countersBranch,
uint[] hashesBranch ) returns(bool) {
VerifyAgtData memory data;
data.rootHash = rootHash;
data.rootMin = rootMin;
data.rootMax = rootMax;
data.leafHash = leafHash;
data.leafCounter = leafCounter;
return verifyAgt( data, branchIndex, countersBranch, hashesBranch );
}
}
contract WeightedSubmission {
function WeightedSubmission(){}
struct SingleSubmissionData {
uint128 numShares;
uint128 submissionValue;
uint128 totalPreviousSubmissionValue;
uint128 min;
uint128 max;
uint128 augRoot;
}
struct SubmissionMetaData {
uint64 numPendingSubmissions;
uint32 readyForVerification; // suppose to be bool
uint32 lastSubmissionBlockNumber;
uint128 totalSubmissionValue;
uint128 difficulty;
uint128 lastCounter;
uint submissionSeed;
}
mapping(address=>SubmissionMetaData) submissionsMetaData;
// (user, submission number)=>data
mapping(address=>mapping(uint=>SingleSubmissionData)) submissionsData;
event SubmitClaim( address indexed sender, uint error, uint errorInfo );
function submitClaim( uint numShares, uint difficulty, uint min, uint max, uint augRoot, bool lastClaimBeforeVerification ) {
SubmissionMetaData memory metaData = submissionsMetaData[msg.sender];
if( metaData.lastCounter >= min ) {
// miner cheated. min counter is too low
SubmitClaim( msg.sender, 0x81000001, metaData.lastCounter );
return;
}
if( metaData.readyForVerification > 0 ) {
// miner cheated - should go verification first
SubmitClaim( msg.sender, 0x81000002, 0 );
return;
}
if( metaData.numPendingSubmissions > 0 ) {
if( metaData.difficulty != difficulty ) {
// could not change difficulty before verification
SubmitClaim( msg.sender, 0x81000003, metaData.difficulty );
return;
}
}
SingleSubmissionData memory submissionData;
submissionData.numShares = uint64(numShares);
uint blockDifficulty;
if( block.difficulty == 0 ) {
// testrpc - fake increasing difficulty
blockDifficulty = (900000000 * (metaData.numPendingSubmissions+1));
}
else {
blockDifficulty = block.difficulty;
}
submissionData.submissionValue = uint128((uint(numShares * difficulty) * (5 ether)) / blockDifficulty);
submissionData.totalPreviousSubmissionValue = metaData.totalSubmissionValue;
submissionData.min = uint128(min);
submissionData.max = uint128(max);
submissionData.augRoot = uint128(augRoot);
(submissionsData[msg.sender])[metaData.numPendingSubmissions] = submissionData;
// update meta data
metaData.numPendingSubmissions++;
metaData.lastSubmissionBlockNumber = uint32(block.number);
metaData.difficulty = uint128(difficulty);
metaData.lastCounter = uint128(max);
metaData.readyForVerification = lastClaimBeforeVerification ? uint32(1) : uint32(0);
uint128 temp128;
temp128 = metaData.totalSubmissionValue;
metaData.totalSubmissionValue += submissionData.submissionValue;
if( temp128 > metaData.totalSubmissionValue ) {
// overflow in calculation
// note that this code is reachable if user is dishonest and give false
// report on his submission. but even without
// this validation, user cannot benifit from the overflow
SubmitClaim( msg.sender, 0x81000005, 0 );
return;
}
submissionsMetaData[msg.sender] = metaData;
// everything is ok
SubmitClaim( msg.sender, 0, numShares * difficulty );
}
function getClaimSeed(address sender) constant returns(uint){
SubmissionMetaData memory metaData = submissionsMetaData[sender];
if( metaData.readyForVerification == 0 ) return 0;
if( metaData.submissionSeed != 0 ) return metaData.submissionSeed;
uint lastBlockNumber = uint(metaData.lastSubmissionBlockNumber);
if( block.number > lastBlockNumber + 200 ) return 0;
if( block.number <= lastBlockNumber + 15 ) return 0;
return uint(block.blockhash(lastBlockNumber + 10));
}
event StoreClaimSeed( address indexed sender, uint error, uint errorInfo );
function storeClaimSeed( address miner ) {
// anyone who is willing to pay gas fees can call this function
uint seed = getClaimSeed( miner );
if( seed != 0 ) {
submissionsMetaData[miner].submissionSeed = seed;
StoreClaimSeed( msg.sender, 0, uint(miner) );
return;
}
// else
SubmissionMetaData memory metaData = submissionsMetaData[miner];
uint lastBlockNumber = uint(metaData.lastSubmissionBlockNumber);
if( metaData.readyForVerification == 0 ) {
// submission is not ready for verification
StoreClaimSeed( msg.sender, 0x8000000, uint(miner) );
}
else if( block.number > lastBlockNumber + 200 ) {
// submission is not ready for verification
StoreClaimSeed( msg.sender, 0x8000001, uint(miner) );
}
else if( block.number <= lastBlockNumber + 15 ) {
// it is too late to call store function
StoreClaimSeed( msg.sender, 0x8000002, uint(miner) );
}
else {
// unknown error
StoreClaimSeed( msg.sender, 0x8000003, uint(miner) );
}
}
function verifySubmissionIndex( address sender, uint seed, uint submissionNumber, uint shareIndex ) constant returns(bool) {
if( seed == 0 ) return false;
uint totalValue = uint(submissionsMetaData[sender].totalSubmissionValue);
uint numPendingSubmissions = uint(submissionsMetaData[sender].numPendingSubmissions);
SingleSubmissionData memory submissionData = (submissionsData[sender])[submissionNumber];
if( submissionNumber >= numPendingSubmissions ) return false;
uint seed1 = seed & 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF;
uint seed2 = seed / (2**128);
uint selectedValue = seed1 % totalValue;
if( uint(submissionData.totalPreviousSubmissionValue) >= selectedValue ) return false;
if( uint(submissionData.totalPreviousSubmissionValue + submissionData.submissionValue) < selectedValue ) return false;
uint expectedShareshareIndex = (seed2 % uint(submissionData.numShares));
if( expectedShareshareIndex != shareIndex ) return false;
return true;
}
function calculateSubmissionIndex( address sender, uint seed ) constant returns(uint[2]) {
// this function should be executed off chain - hene, it is not optimized
uint seed1 = seed & 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF;
uint seed2 = seed / (2**128);
uint totalValue = uint(submissionsMetaData[sender].totalSubmissionValue);
uint numPendingSubmissions = uint(submissionsMetaData[sender].numPendingSubmissions);
uint selectedValue = seed1 % totalValue;
SingleSubmissionData memory submissionData;
for( uint submissionInd = 0 ; submissionInd < numPendingSubmissions ; submissionInd++ ) {
submissionData = (submissionsData[sender])[submissionInd];
if( uint(submissionData.totalPreviousSubmissionValue + submissionData.submissionValue) >= selectedValue ) break;
}
// unexpected error
if( submissionInd == numPendingSubmissions ) return [uint(0xFFFFFFFFFFFFFFFF),0xFFFFFFFFFFFFFFFF];
uint shareIndex = seed2 % uint(submissionData.numShares);
return [submissionInd, shareIndex];
}
// should be called only from verify claim
function closeSubmission( address sender ) internal {
SubmissionMetaData memory metaData = submissionsMetaData[sender];
metaData.numPendingSubmissions = 0;
metaData.totalSubmissionValue = 0;
metaData.readyForVerification = 0;
metaData.submissionSeed = 0;
// last counter must not be reset
// last submission block number and difficulty are also kept, but it is not a must
// only to save some gas
submissionsMetaData[sender] = metaData;
}
struct SubmissionDataForClaimVerification {
uint lastCounter;
uint shareDifficulty;
uint totalSubmissionValue;
uint min;
uint max;
uint augMerkle;
bool indicesAreValid;
bool readyForVerification;
}
function getClaimData( address sender, uint submissionIndex, uint shareIndex, uint seed )
constant internal returns(SubmissionDataForClaimVerification){
SubmissionDataForClaimVerification memory output;
SubmissionMetaData memory metaData = submissionsMetaData[sender];
output.lastCounter = uint(metaData.lastCounter);
output.shareDifficulty = uint(metaData.difficulty);
output.totalSubmissionValue = metaData.totalSubmissionValue;
SingleSubmissionData memory submissionData = (submissionsData[sender])[submissionIndex];
output.min = uint(submissionData.min);
output.max = uint(submissionData.max);
output.augMerkle = uint(submissionData.augRoot);
output.indicesAreValid = verifySubmissionIndex( sender, seed, submissionIndex, shareIndex );
output.readyForVerification = (metaData.readyForVerification > 0);
return output;
}
function debugGetNumPendingSubmissions( address sender ) constant returns(uint) {
return uint(submissionsMetaData[sender].numPendingSubmissions);
}
event DebugResetSubmissions( address indexed sender, uint error, uint errorInfo );
function debugResetSubmissions( ) {
// should be called only in emergency
// msg.sender will loose all its pending shares
closeSubmission(msg.sender);
DebugResetSubmissions( msg.sender, 0, 0 );
}
}
contract SmartPool is Agt, WeightedSubmission {
string public version = "0.1.1";
Ethash public ethashContract;
address public withdrawalAddress;
mapping(address=>bool) public owners;
bool public newVersionReleased = false;
struct MinerData {
bytes32 minerId;
address paymentAddress;
}
mapping(address=>MinerData) minersData;
mapping(bytes32=>bool) public existingIds;
bool public whiteListEnabled;
bool public blackListEnabled;
mapping(address=>bool) whiteList;
mapping(address=>bool) blackList;
function SmartPool( address[] _owners,
Ethash _ethashContract,
address _withdrawalAddress,
bool _whiteListEnabled,
bool _blackListEnabled ) payable {
for( uint i = 0 ; i < _owners.length ; i++ ) {
owners[_owners[i]] = true;
}
ethashContract = _ethashContract;
withdrawalAddress = _withdrawalAddress;
whiteListEnabled = _whiteListEnabled;
blackListEnabled = _blackListEnabled;
}
function replaceOwner(address _newOwner) {
require( owners[msg.sender] );
owners[msg.sender] = false;
owners[_newOwner] = true;
}
function declareNewerVersion() {
require( owners[msg.sender] );
newVersionReleased = true;
//if( ! msg.sender.send(this.balance) ) throw;
}
event Withdraw( address indexed sender, uint error, uint errorInfo );
function withdraw( uint amount ) {
if( ! owners[msg.sender] ) {
// only ownder can withdraw
Withdraw( msg.sender, 0x80000000, amount );
return;
}
withdrawalAddress.transfer( amount );
Withdraw( msg.sender, 0, amount );
}
function to62Encoding( uint id, uint numChars ) constant returns(bytes32) {
require( id < (26+26+10)**numChars );
uint result = 0;
for( uint i = 0 ; i < numChars ; i++ ) {
uint b = id % (26+26+10);
uint8 char;
if( b < 10 ) {
char = uint8(b + 0x30); // 0x30 = '0'
}
else if( b < 26 + 10 ) {
char = uint8(b + 0x61 - 10); //0x61 = 'a'
}
else {
char = uint8(b + 0x41 - 26 - 10); // 0x41 = 'A'
}
result = (result * 256) + char;
id /= (26+26+10);
}
return bytes32(result);
}
event Register( address indexed sender, uint error, uint errorInfo );
function register( address paymentAddress ) {
address minerAddress = msg.sender;
// build id
uint id = uint(minerAddress) % (26+26+10)**11;
bytes32 minerId = to62Encoding(id,11);
if( existingIds[minersData[minerAddress].minerId] ) {
// miner id is already in use
Register( msg.sender, 0x80000000, uint(minerId) );
return;
}
if( paymentAddress == address(0) ) {
// payment address is 0
Register( msg.sender, 0x80000001, uint(paymentAddress) );
return;
}
if( whiteListEnabled ) {
if( ! whiteList[ msg.sender ] ) {
// miner not in white list
Register( msg.sender, 0x80000002, uint(minerId) );
return;
}
}
if( blackListEnabled ) {
if( blackList[ msg.sender ] ) {
// miner on black list
Register( msg.sender, 0x80000003, uint(minerId) );
return;
}
}
// last counter is set to 0.
// It might be safer to change it to now.
//minersData[minerAddress].lastCounter = now * (2**64);
minersData[minerAddress].paymentAddress = paymentAddress;
minersData[minerAddress].minerId = minerId;
existingIds[minersData[minerAddress].minerId] = true;
// succesful registration
Register( msg.sender, 0, 0 );
}
function canRegister(address sender) constant returns(bool) {
uint id = uint(sender) % (26+26+10)**11;
bytes32 expectedId = to62Encoding(id,11);
if( whiteListEnabled ) {
if( ! whiteList[ sender ] ) return false;
}
if( blackListEnabled ) {
if( blackList[ sender ] ) return false;
}
return ! existingIds[expectedId];
}
function isRegistered(address sender) constant returns(bool) {
return minersData[sender].paymentAddress != address(0);
}
function getMinerId(address sender) constant returns(bytes32) {
return minersData[sender].minerId;
}
event UpdateWhiteList( address indexed miner, uint error, uint errorInfo, bool add );
event UpdateBlackList( address indexed miner, uint error, uint errorInfo, bool add );
function unRegister( address miner ) internal {
minersData[miner].paymentAddress = address(0);
existingIds[minersData[miner].minerId] = false;
}
function updateWhiteList( address miner, bool add ) {
if( ! owners[ msg.sender ] ) {
// only owner can update list
UpdateWhiteList( msg.sender, 0x80000000, 0, add );
return;
}
if( ! whiteListEnabled ) {
// white list is not enabeled
UpdateWhiteList( msg.sender, 0x80000001, 0, add );
return;
}
whiteList[ miner ] = add;
if( ! add && isRegistered( miner ) ) {
// unregister
unRegister( miner );
}
UpdateWhiteList( msg.sender, 0, uint(miner), add );
}
function updateBlackList( address miner, bool add ) {
if( ! owners[ msg.sender ] ) {
// only owner can update list
UpdateBlackList( msg.sender, 0x80000000, 0, add );
return;
}
if( ! blackListEnabled ) {
// white list is not enabeled
UpdateBlackList( msg.sender, 0x80000001, 0, add );
return;
}
blackList[ miner ] = add;
if( add && isRegistered( miner ) ) {
// unregister
unRegister( miner );
}
UpdateBlackList( msg.sender, 0, uint(miner), add );
}
event DisableBlackListForever( address indexed sender, uint error, uint errorInfo );
function disableBlackListForever() {
if( ! owners[ msg.sender ] ) {
// only owner can update list
DisableBlackListForever( msg.sender, 0x80000000, 0 );
return;
}
blackListEnabled = false;
DisableBlackListForever( msg.sender, 0, 0 );
}
event DisableWhiteListForever( address indexed sender, uint error, uint errorInfo );
function disableWhiteListForever() {
if( ! owners[ msg.sender ] ) {
// only owner can update list
DisableWhiteListForever( msg.sender, 0x80000000, 0 );
return;
}
whiteListEnabled = false;
DisableWhiteListForever( msg.sender, 0, 0 );
}
event VerifyExtraData( address indexed sender, uint error, uint errorInfo );
function verifyExtraData( bytes32 extraData, bytes32 minerId, uint difficulty ) constant internal returns(bool) {
uint i;
// compare id
for( i = 0 ; i < 11 ; i++ ) {
if( extraData[10+i] != minerId[21+i] ) {
//ErrorLog( "verifyExtraData: miner id not as expected", 0 );
VerifyExtraData( msg.sender, 0x83000000, uint(minerId) );
return false;
}
}
// compare difficulty
bytes32 encodedDiff = to62Encoding(difficulty,11);
for( i = 0 ; i < 11 ; i++ ) {
if(extraData[i+21] != encodedDiff[21+i]) {
//ErrorLog( "verifyExtraData: difficulty is not as expected", uint(encodedDiff) );
VerifyExtraData( msg.sender, 0x83000001, uint(encodedDiff) );
return false;
}
}
return true;
}
event VerifyClaim( address indexed sender, uint error, uint errorInfo );
function verifyClaim( bytes rlpHeader,
uint nonce,
uint submissionIndex,
uint shareIndex,
uint[] dataSetLookup,
uint[] witnessForLookup,
uint[] augCountersBranch,
uint[] augHashesBranch ) {
if( ! isRegistered(msg.sender) ) {
// miner is not registered
VerifyClaim( msg.sender, 0x8400000c, 0 );
return;
}
SubmissionDataForClaimVerification memory submissionData = getClaimData( msg.sender,
submissionIndex, shareIndex, getClaimSeed( msg.sender ) );
if( ! submissionData.readyForVerification ) {
//ErrorLog( "there are no pending claims", 0 );
VerifyClaim( msg.sender, 0x84000003, 0 );
return;
}
BlockHeader memory header = parseBlockHeader(rlpHeader);
// check extra data
if( ! verifyExtraData( header.extraData,
minersData[ msg.sender ].minerId,
submissionData.shareDifficulty ) ) {
//ErrorLog( "extra data not as expected", uint(header.extraData) );
VerifyClaim( msg.sender, 0x84000004, uint(header.extraData) );
return;
}
// check coinbase data
if( header.coinbase != uint(this) ) {
//ErrorLog( "coinbase not as expected", uint(header.coinbase) );
VerifyClaim( msg.sender, 0x84000005, uint(header.coinbase) );
return;
}
// check counter
uint counter = header.timestamp * (2 ** 64) + nonce;
if( counter < submissionData.min ) {
//ErrorLog( "counter is smaller than min",counter);
VerifyClaim( msg.sender, 0x84000007, counter );
return;
}
if( counter > submissionData.max ) {
//ErrorLog( "counter is smaller than max",counter);
VerifyClaim( msg.sender, 0x84000008, counter );
return;
}
// verify agt
uint leafHash = uint(sha3(rlpHeader));
VerifyAgtData memory agtData;
agtData.rootHash = submissionData.augMerkle;
agtData.rootMin = submissionData.min;
agtData.rootMax = submissionData.max;
agtData.leafHash = leafHash;
agtData.leafCounter = counter;
if( ! verifyAgt( agtData,
shareIndex,
augCountersBranch,
augHashesBranch ) ) {
//ErrorLog( "verifyAgt failed",0);
VerifyClaim( msg.sender, 0x84000009, 0 );
return;
}
/*
// check epoch data - done inside hashimoto
if( ! ethashContract.isEpochDataSet( header.blockNumber / 30000 ) ) {
//ErrorLog( "epoch data was not set",header.blockNumber / 30000);
VerifyClaim( msg.sender, 0x8400000a, header.blockNumber / 30000 );
return;
}*/
// verify ethash
uint ethash = ethashContract.hashimoto( bytes32(leafHash),
bytes8(nonce),
dataSetLookup,
witnessForLookup,
header.blockNumber / 30000 );
if( ethash > ((2**256-1)/submissionData.shareDifficulty )) {
if( ethash == 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFE ) {
//ErrorLog( "epoch data was not set",header.blockNumber / 30000);
VerifyClaim( msg.sender, 0x8400000a, header.blockNumber / 30000 );
}
else {
//ErrorLog( "ethash difficulty too low",ethash);
VerifyClaim( msg.sender, 0x8400000b, ethash );
}
return;
}
if( getClaimSeed(msg.sender) == 0 ) {
//ErrorLog( "claim seed is 0", 0 );
VerifyClaim( msg.sender, 0x84000001, 0 );
return;
}
if( ! submissionData.indicesAreValid ) {
//ErrorLog( "share index or submission are not as expected. should be:", getShareIndex() );
VerifyClaim( msg.sender, 0x84000002, 0 );
return;
}
// recrusive attack is not possible as doPayment is using send and not call.
if( ! doPayment(submissionData.totalSubmissionValue,
minersData[ msg.sender ].paymentAddress) ) {
// error msg is given in doPayment function
return;
}
closeSubmission( msg.sender );
//minersData[ msg.sender ].pendingClaim = false;
VerifyClaim( msg.sender, 0, 0 );
return;
}
// 10000 = 100%
uint public uncleRate = 500; // 5%
// 10000 = 100%
uint public poolFees = 0;
event IncomingFunds( address sender, uint amountInWei );
function() payable {
require(msg.value > 0 ); // prevent, e.g., receiving ERC223 tokens.
IncomingFunds( msg.sender, msg.value );
}
event SetUnlceRateAndFees( address indexed sender, uint error, uint errorInfo );
function setUnlceRateAndFees( uint _uncleRate, uint _poolFees ) {
if( ! owners[msg.sender] ) {
// only owner should change rates
SetUnlceRateAndFees( msg.sender, 0x80000000, 0 );
return;
}
uncleRate = _uncleRate;
poolFees = _poolFees;
SetUnlceRateAndFees( msg.sender, 0, 0 );
}
event DoPayment( address indexed sender, address paymentAddress, uint valueInWei );
function doPayment( uint submissionValue,
address paymentAddress ) internal returns(bool) {
uint payment = submissionValue;
// take uncle rate into account
// payment = payment * (1-0.25*uncleRate)
// uncleRate in [0,10000]
payment = (payment * (4*10000 - uncleRate)) / (4*10000);
// fees
payment = (payment * (10000 - poolFees)) / 10000;
if( payment > this.balance ){
//ErrorLog( "cannot afford to pay", calcPayment( submissionData.numShares, submissionData.difficulty ) );
VerifyClaim( msg.sender, 0x84000000, payment );
return false;
}
paymentAddress.transfer( payment );
DoPayment( msg.sender, paymentAddress, payment );
return true;
}
function getPoolBalance( ) constant returns(uint) {
// debug function for testrpc
return this.balance;
}
event GetShareIndexDebugForTestRPCSubmissionIndex( uint index );
event GetShareIndexDebugForTestRPCShareIndex( uint index );
function getShareIndexDebugForTestRPC( address sender ) {
uint seed = getClaimSeed( sender );
uint[2] memory result = calculateSubmissionIndex( sender, seed );
GetShareIndexDebugForTestRPCSubmissionIndex( result[0] );
GetShareIndexDebugForTestRPCShareIndex( result[1] );
}
}
|
debug function for testrpc
|
function getPoolBalance( ) constant returns(uint) {
return this.balance;
}
event GetShareIndexDebugForTestRPCSubmissionIndex( uint index );
event GetShareIndexDebugForTestRPCShareIndex( uint index );
| 13,006,377 |
pragma solidity 0.5.15;
contract IAugur {
function CREATECHILDUNIVERSE712(bytes32 _parentPayoutDistributionHash, uint256[] memory _parentPayoutNumerators) public returns (IUniverse); //inject NONSTANDARD NAMING
function ISKNOWNUNIVERSE698(IUniverse _universe) public view returns (bool); //inject NONSTANDARD NAMING
function TRUSTEDCASHTRANSFER967(address _from, address _to, uint256 _amount) public returns (bool); //inject NONSTANDARD NAMING
function ISTRUSTEDSENDER635(address _address) public returns (bool); //inject NONSTANDARD NAMING
function ONCATEGORICALMARKETCREATED679(uint256 _endTime, string memory _extraInfo, IMarket _market, address _marketCreator, address _designatedReporter, uint256 _feePerCashInAttoCash, bytes32[] memory _outcomes) public returns (bool); //inject NONSTANDARD NAMING
function ONYESNOMARKETCREATED215(uint256 _endTime, string memory _extraInfo, IMarket _market, address _marketCreator, address _designatedReporter, uint256 _feePerCashInAttoCash) public returns (bool); //inject NONSTANDARD NAMING
function ONSCALARMARKETCREATED844(uint256 _endTime, string memory _extraInfo, IMarket _market, address _marketCreator, address _designatedReporter, uint256 _feePerCashInAttoCash, int256[] memory _prices, uint256 _numTicks) public returns (bool); //inject NONSTANDARD NAMING
function LOGINITIALREPORTSUBMITTED874(IUniverse _universe, address _reporter, address _market, address _initialReporter, uint256 _amountStaked, bool _isDesignatedReporter, uint256[] memory _payoutNumerators, string memory _description, uint256 _nextWindowStartTime, uint256 _nextWindowEndTime) public returns (bool); //inject NONSTANDARD NAMING
function DISPUTECROWDSOURCERCREATED646(IUniverse _universe, address _market, address _disputeCrowdsourcer, uint256[] memory _payoutNumerators, uint256 _size, uint256 _disputeRound) public returns (bool); //inject NONSTANDARD NAMING
function LOGDISPUTECROWDSOURCERCONTRIBUTION255(IUniverse _universe, address _reporter, address _market, address _disputeCrowdsourcer, uint256 _amountStaked, string memory description, uint256[] memory _payoutNumerators, uint256 _currentStake, uint256 _stakeRemaining, uint256 _disputeRound) public returns (bool); //inject NONSTANDARD NAMING
function LOGDISPUTECROWDSOURCERCOMPLETED546(IUniverse _universe, address _market, address _disputeCrowdsourcer, uint256[] memory _payoutNumerators, uint256 _nextWindowStartTime, uint256 _nextWindowEndTime, bool _pacingOn, uint256 _totalRepStakedInPayout, uint256 _totalRepStakedInMarket, uint256 _disputeRound) public returns (bool); //inject NONSTANDARD NAMING
function LOGINITIALREPORTERREDEEMED338(IUniverse _universe, address _reporter, address _market, uint256 _amountRedeemed, uint256 _repReceived, uint256[] memory _payoutNumerators) public returns (bool); //inject NONSTANDARD NAMING
function LOGDISPUTECROWDSOURCERREDEEMED9(IUniverse _universe, address _reporter, address _market, uint256 _amountRedeemed, uint256 _repReceived, uint256[] memory _payoutNumerators) public returns (bool); //inject NONSTANDARD NAMING
function LOGMARKETFINALIZED368(IUniverse _universe, uint256[] memory _winningPayoutNumerators) public returns (bool); //inject NONSTANDARD NAMING
function LOGMARKETMIGRATED444(IMarket _market, IUniverse _originalUniverse) public returns (bool); //inject NONSTANDARD NAMING
function LOGREPORTINGPARTICIPANTDISAVOWED43(IUniverse _universe, IMarket _market) public returns (bool); //inject NONSTANDARD NAMING
function LOGMARKETPARTICIPANTSDISAVOWED537(IUniverse _universe) public returns (bool); //inject NONSTANDARD NAMING
function LOGCOMPLETESETSPURCHASED486(IUniverse _universe, IMarket _market, address _account, uint256 _numCompleteSets) public returns (bool); //inject NONSTANDARD NAMING
function LOGCOMPLETESETSSOLD144(IUniverse _universe, IMarket _market, address _account, uint256 _numCompleteSets, uint256 _fees) public returns (bool); //inject NONSTANDARD NAMING
function LOGMARKETOICHANGED928(IUniverse _universe, IMarket _market) public returns (bool); //inject NONSTANDARD NAMING
function LOGTRADINGPROCEEDSCLAIMED757(IUniverse _universe, address _sender, address _market, uint256 _outcome, uint256 _numShares, uint256 _numPayoutTokens, uint256 _fees) public returns (bool); //inject NONSTANDARD NAMING
function LOGUNIVERSEFORKED116(IMarket _forkingMarket) public returns (bool); //inject NONSTANDARD NAMING
function LOGREPUTATIONTOKENSTRANSFERRED904(IUniverse _universe, address _from, address _to, uint256 _value, uint256 _fromBalance, uint256 _toBalance) public returns (bool); //inject NONSTANDARD NAMING
function LOGREPUTATIONTOKENSBURNED995(IUniverse _universe, address _target, uint256 _amount, uint256 _totalSupply, uint256 _balance) public returns (bool); //inject NONSTANDARD NAMING
function LOGREPUTATIONTOKENSMINTED985(IUniverse _universe, address _target, uint256 _amount, uint256 _totalSupply, uint256 _balance) public returns (bool); //inject NONSTANDARD NAMING
function LOGSHARETOKENSBALANCECHANGED123(address _account, IMarket _market, uint256 _outcome, uint256 _balance) public returns (bool); //inject NONSTANDARD NAMING
function LOGDISPUTECROWDSOURCERTOKENSTRANSFERRED932(IUniverse _universe, address _from, address _to, uint256 _value, uint256 _fromBalance, uint256 _toBalance) public returns (bool); //inject NONSTANDARD NAMING
function LOGDISPUTECROWDSOURCERTOKENSBURNED518(IUniverse _universe, address _target, uint256 _amount, uint256 _totalSupply, uint256 _balance) public returns (bool); //inject NONSTANDARD NAMING
function LOGDISPUTECROWDSOURCERTOKENSMINTED48(IUniverse _universe, address _target, uint256 _amount, uint256 _totalSupply, uint256 _balance) public returns (bool); //inject NONSTANDARD NAMING
function LOGDISPUTEWINDOWCREATED79(IDisputeWindow _disputeWindow, uint256 _id, bool _initial) public returns (bool); //inject NONSTANDARD NAMING
function LOGPARTICIPATIONTOKENSREDEEMED534(IUniverse universe, address _sender, uint256 _attoParticipationTokens, uint256 _feePayoutShare) public returns (bool); //inject NONSTANDARD NAMING
function LOGTIMESTAMPSET762(uint256 _newTimestamp) public returns (bool); //inject NONSTANDARD NAMING
function LOGINITIALREPORTERTRANSFERRED573(IUniverse _universe, IMarket _market, address _from, address _to) public returns (bool); //inject NONSTANDARD NAMING
function LOGMARKETTRANSFERRED247(IUniverse _universe, address _from, address _to) public returns (bool); //inject NONSTANDARD NAMING
function LOGPARTICIPATIONTOKENSTRANSFERRED386(IUniverse _universe, address _from, address _to, uint256 _value, uint256 _fromBalance, uint256 _toBalance) public returns (bool); //inject NONSTANDARD NAMING
function LOGPARTICIPATIONTOKENSBURNED957(IUniverse _universe, address _target, uint256 _amount, uint256 _totalSupply, uint256 _balance) public returns (bool); //inject NONSTANDARD NAMING
function LOGPARTICIPATIONTOKENSMINTED248(IUniverse _universe, address _target, uint256 _amount, uint256 _totalSupply, uint256 _balance) public returns (bool); //inject NONSTANDARD NAMING
function LOGMARKETREPBONDTRANSFERRED31(address _universe, address _from, address _to) public returns (bool); //inject NONSTANDARD NAMING
function LOGWARPSYNCDATAUPDATED845(address _universe, uint256 _warpSyncHash, uint256 _marketEndTime) public returns (bool); //inject NONSTANDARD NAMING
function ISKNOWNFEESENDER211(address _feeSender) public view returns (bool); //inject NONSTANDARD NAMING
function LOOKUP594(bytes32 _key) public view returns (address); //inject NONSTANDARD NAMING
function GETTIMESTAMP626() public view returns (uint256); //inject NONSTANDARD NAMING
function GETMAXIMUMMARKETENDDATE626() public returns (uint256); //inject NONSTANDARD NAMING
function ISKNOWNMARKET166(IMarket _market) public view returns (bool); //inject NONSTANDARD NAMING
function DERIVEPAYOUTDISTRIBUTIONHASH812(uint256[] memory _payoutNumerators, uint256 _numTicks, uint256 numOutcomes) public view returns (bytes32); //inject NONSTANDARD NAMING
function LOGVALIDITYBONDCHANGED992(uint256 _validityBond) public returns (bool); //inject NONSTANDARD NAMING
function LOGDESIGNATEDREPORTSTAKECHANGED748(uint256 _designatedReportStake) public returns (bool); //inject NONSTANDARD NAMING
function LOGNOSHOWBONDCHANGED254(uint256 _noShowBond) public returns (bool); //inject NONSTANDARD NAMING
function LOGREPORTINGFEECHANGED596(uint256 _reportingFee) public returns (bool); //inject NONSTANDARD NAMING
function GETUNIVERSEFORKINDEX548(IUniverse _universe) public view returns (uint256); //inject NONSTANDARD NAMING
}
contract IOwnable {
function GETOWNER826() public view returns (address); //inject NONSTANDARD NAMING
function TRANSFEROWNERSHIP284(address _newOwner) public returns (bool); //inject NONSTANDARD NAMING
}
contract ITyped {
function GETTYPENAME153() public view returns (bytes32); //inject NONSTANDARD NAMING
}
library SafeMathUint256 {
function MUL760(uint256 a, uint256 b) internal pure returns (uint256) { //inject NONSTANDARD NAMING
// Gas optimization: this is cheaper than requiring 'a' not being zero, but the
// benefit is lost if 'b' is also tested.
// See: https://github.com/OpenZeppelin/openzeppelin-solidity/pull/522
if (a == 0) {
return 0;
}
uint256 c = a * b;
require(c / a == b);
return c;
}
function DIV647(uint256 a, uint256 b) internal pure returns (uint256) { //inject NONSTANDARD NAMING
// assert(b > 0); // Solidity automatically throws when dividing by 0
uint256 c = a / b;
// assert(a == b * c + a % b); // There is no case in which this doesn't hold
return c;
}
function SUB692(uint256 a, uint256 b) internal pure returns (uint256) { //inject NONSTANDARD NAMING
require(b <= a);
return a - b;
}
function ADD571(uint256 a, uint256 b) internal pure returns (uint256) { //inject NONSTANDARD NAMING
uint256 c = a + b;
require(c >= a);
return c;
}
function MIN885(uint256 a, uint256 b) internal pure returns (uint256) { //inject NONSTANDARD NAMING
if (a <= b) {
return a;
} else {
return b;
}
}
function MAX990(uint256 a, uint256 b) internal pure returns (uint256) { //inject NONSTANDARD NAMING
if (a >= b) {
return a;
} else {
return b;
}
}
function SQRT858(uint256 y) internal pure returns (uint256 z) { //inject NONSTANDARD NAMING
if (y > 3) {
uint256 x = (y + 1) / 2;
z = y;
while (x < z) {
z = x;
x = (y / x + x) / 2;
}
} else if (y != 0) {
z = 1;
}
}
function GETUINT256MIN331() internal pure returns (uint256) { //inject NONSTANDARD NAMING
return 0;
}
function GETUINT256MAX467() internal pure returns (uint256) { //inject NONSTANDARD NAMING
// 2 ** 256 - 1
return 0xffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff;
}
function ISMULTIPLEOF540(uint256 a, uint256 b) internal pure returns (bool) { //inject NONSTANDARD NAMING
return a % b == 0;
}
// Float [fixed point] Operations
function FXPMUL102(uint256 a, uint256 b, uint256 base) internal pure returns (uint256) { //inject NONSTANDARD NAMING
return DIV647(MUL760(a, b), base);
}
function FXPDIV922(uint256 a, uint256 b, uint256 base) internal pure returns (uint256) { //inject NONSTANDARD NAMING
return DIV647(MUL760(a, base), b);
}
}
interface IERC1155 {
event TRANSFERSINGLE49( //inject NONSTANDARD NAMING
address indexed operator,
address indexed from,
address indexed to,
uint256 id,
uint256 value
);
event TRANSFERBATCH882( //inject NONSTANDARD NAMING
address indexed operator,
address indexed from,
address indexed to,
uint256[] ids,
uint256[] values
);
event APPROVALFORALL731( //inject NONSTANDARD NAMING
address indexed owner,
address indexed operator,
bool approved
);
event URI998( //inject NONSTANDARD NAMING
string value,
uint256 indexed id
);
function SAFETRANSFERFROM689( //inject NONSTANDARD NAMING
address from,
address to,
uint256 id,
uint256 value,
bytes calldata data
)
external;
function SAFEBATCHTRANSFERFROM779( //inject NONSTANDARD NAMING
address from,
address to,
uint256[] calldata ids,
uint256[] calldata values,
bytes calldata data
)
external;
function SETAPPROVALFORALL494(address operator, bool approved) external; //inject NONSTANDARD NAMING
function ISAPPROVEDFORALL901(address owner, address operator) external view returns (bool); //inject NONSTANDARD NAMING
function BALANCEOF492(address owner, uint256 id) external view returns (uint256); //inject NONSTANDARD NAMING
function TOTALSUPPLY304(uint256 id) external view returns (uint256); //inject NONSTANDARD NAMING
function BALANCEOFBATCH918( //inject NONSTANDARD NAMING
address[] calldata owners,
uint256[] calldata ids
)
external
view
returns (uint256[] memory balances_);
}
contract IERC20 {
function TOTALSUPPLY304() external view returns (uint256); //inject NONSTANDARD NAMING
function BALANCEOF492(address owner) public view returns (uint256); //inject NONSTANDARD NAMING
function TRANSFER644(address to, uint256 amount) public returns (bool); //inject NONSTANDARD NAMING
function TRANSFERFROM669(address from, address to, uint256 amount) public returns (bool); //inject NONSTANDARD NAMING
function APPROVE293(address spender, uint256 amount) public returns (bool); //inject NONSTANDARD NAMING
function ALLOWANCE377(address owner, address spender) public view returns (uint256); //inject NONSTANDARD NAMING
// solhint-disable-next-line no-simple-event-func-name
event TRANSFER723(address indexed from, address indexed to, uint256 value); //inject NONSTANDARD NAMING
event APPROVAL665(address indexed owner, address indexed spender, uint256 value); //inject NONSTANDARD NAMING
}
contract ICash is IERC20 {
}
contract ERC20 is IERC20 {
using SafeMathUint256 for uint256;
uint8 constant public decimals866 = 18; //inject NONSTANDARD NAMING
uint256 public totalSupply;
mapping (address => uint256) public balances;
mapping (address => mapping (address => uint256)) public allowances;
function BALANCEOF492(address _account) public view returns (uint256) { //inject NONSTANDARD NAMING
return balances[_account];
}
function TRANSFER644(address _recipient, uint256 _amount) public returns (bool) { //inject NONSTANDARD NAMING
_TRANSFER433(msg.sender, _recipient, _amount);
return true;
}
function ALLOWANCE377(address _owner, address _spender) public view returns (uint256) { //inject NONSTANDARD NAMING
return allowances[_owner][_spender];
}
function APPROVE293(address _spender, uint256 _amount) public returns (bool) { //inject NONSTANDARD NAMING
_APPROVE571(msg.sender, _spender, _amount);
return true;
}
function TRANSFERFROM669(address _sender, address _recipient, uint256 _amount) public returns (bool) { //inject NONSTANDARD NAMING
_TRANSFER433(_sender, _recipient, _amount);
_APPROVE571(_sender, msg.sender, allowances[_sender][msg.sender].SUB692(_amount));
return true;
}
function INCREASEALLOWANCE307(address _spender, uint256 _addedValue) public returns (bool) { //inject NONSTANDARD NAMING
_APPROVE571(msg.sender, _spender, allowances[msg.sender][_spender].ADD571(_addedValue));
return true;
}
function DECREASEALLOWANCE757(address _spender, uint256 _subtractedValue) public returns (bool) { //inject NONSTANDARD NAMING
_APPROVE571(msg.sender, _spender, allowances[msg.sender][_spender].SUB692(_subtractedValue));
return true;
}
function _TRANSFER433(address _sender, address _recipient, uint256 _amount) internal { //inject NONSTANDARD NAMING
require(_sender != address(0), "ERC20: transfer from the zero address");
require(_recipient != address(0), "ERC20: transfer to the zero address");
balances[_sender] = balances[_sender].SUB692(_amount);
balances[_recipient] = balances[_recipient].ADD571(_amount);
emit TRANSFER723(_sender, _recipient, _amount);
ONTOKENTRANSFER292(_sender, _recipient, _amount);
}
function _MINT880(address _account, uint256 _amount) internal { //inject NONSTANDARD NAMING
require(_account != address(0), "ERC20: mint to the zero address");
totalSupply = totalSupply.ADD571(_amount);
balances[_account] = balances[_account].ADD571(_amount);
emit TRANSFER723(address(0), _account, _amount);
}
function _BURN356(address _account, uint256 _amount) internal { //inject NONSTANDARD NAMING
require(_account != address(0), "ERC20: burn from the zero address");
balances[_account] = balances[_account].SUB692(_amount);
totalSupply = totalSupply.SUB692(_amount);
emit TRANSFER723(_account, address(0), _amount);
}
function _APPROVE571(address _owner, address _spender, uint256 _amount) internal { //inject NONSTANDARD NAMING
require(_owner != address(0), "ERC20: approve from the zero address");
require(_spender != address(0), "ERC20: approve to the zero address");
allowances[_owner][_spender] = _amount;
emit APPROVAL665(_owner, _spender, _amount);
}
function _BURNFROM317(address _account, uint256 _amount) internal { //inject NONSTANDARD NAMING
_BURN356(_account, _amount);
_APPROVE571(_account, msg.sender, allowances[_account][msg.sender].SUB692(_amount));
}
// Subclasses of this token generally want to send additional logs through the centralized Augur log emitter contract
function ONTOKENTRANSFER292(address _from, address _to, uint256 _value) internal; //inject NONSTANDARD NAMING
}
contract VariableSupplyToken is ERC20 {
using SafeMathUint256 for uint256;
function MINT146(address _target, uint256 _amount) internal returns (bool) { //inject NONSTANDARD NAMING
_MINT880(_target, _amount);
ONMINT315(_target, _amount);
return true;
}
function BURN234(address _target, uint256 _amount) internal returns (bool) { //inject NONSTANDARD NAMING
_BURN356(_target, _amount);
ONBURN653(_target, _amount);
return true;
}
// Subclasses of this token may want to send additional logs through the centralized Augur log emitter contract
function ONMINT315(address, uint256) internal { //inject NONSTANDARD NAMING
}
// Subclasses of this token may want to send additional logs through the centralized Augur log emitter contract
function ONBURN653(address, uint256) internal { //inject NONSTANDARD NAMING
}
}
contract IAffiliateValidator {
function VALIDATEREFERENCE609(address _account, address _referrer) external view returns (bool); //inject NONSTANDARD NAMING
}
contract IDisputeWindow is ITyped, IERC20 {
function INVALIDMARKETSTOTAL511() external view returns (uint256); //inject NONSTANDARD NAMING
function VALIDITYBONDTOTAL28() external view returns (uint256); //inject NONSTANDARD NAMING
function INCORRECTDESIGNATEDREPORTTOTAL522() external view returns (uint256); //inject NONSTANDARD NAMING
function INITIALREPORTBONDTOTAL695() external view returns (uint256); //inject NONSTANDARD NAMING
function DESIGNATEDREPORTNOSHOWSTOTAL443() external view returns (uint256); //inject NONSTANDARD NAMING
function DESIGNATEDREPORTERNOSHOWBONDTOTAL703() external view returns (uint256); //inject NONSTANDARD NAMING
function INITIALIZE90(IAugur _augur, IUniverse _universe, uint256 _disputeWindowId, bool _participationTokensEnabled, uint256 _duration, uint256 _startTime) public; //inject NONSTANDARD NAMING
function TRUSTEDBUY954(address _buyer, uint256 _attotokens) public returns (bool); //inject NONSTANDARD NAMING
function GETUNIVERSE719() public view returns (IUniverse); //inject NONSTANDARD NAMING
function GETREPUTATIONTOKEN35() public view returns (IReputationToken); //inject NONSTANDARD NAMING
function GETSTARTTIME383() public view returns (uint256); //inject NONSTANDARD NAMING
function GETENDTIME626() public view returns (uint256); //inject NONSTANDARD NAMING
function GETWINDOWID901() public view returns (uint256); //inject NONSTANDARD NAMING
function ISACTIVE720() public view returns (bool); //inject NONSTANDARD NAMING
function ISOVER108() public view returns (bool); //inject NONSTANDARD NAMING
function ONMARKETFINALIZED596() public; //inject NONSTANDARD NAMING
function REDEEM559(address _account) public returns (bool); //inject NONSTANDARD NAMING
}
contract IMarket is IOwnable {
enum MarketType {
YES_NO,
CATEGORICAL,
SCALAR
}
function INITIALIZE90(IAugur _augur, IUniverse _universe, uint256 _endTime, uint256 _feePerCashInAttoCash, IAffiliateValidator _affiliateValidator, uint256 _affiliateFeeDivisor, address _designatedReporterAddress, address _creator, uint256 _numOutcomes, uint256 _numTicks) public; //inject NONSTANDARD NAMING
function DERIVEPAYOUTDISTRIBUTIONHASH812(uint256[] memory _payoutNumerators) public view returns (bytes32); //inject NONSTANDARD NAMING
function DOINITIALREPORT448(uint256[] memory _payoutNumerators, string memory _description, uint256 _additionalStake) public returns (bool); //inject NONSTANDARD NAMING
function GETUNIVERSE719() public view returns (IUniverse); //inject NONSTANDARD NAMING
function GETDISPUTEWINDOW804() public view returns (IDisputeWindow); //inject NONSTANDARD NAMING
function GETNUMBEROFOUTCOMES636() public view returns (uint256); //inject NONSTANDARD NAMING
function GETNUMTICKS752() public view returns (uint256); //inject NONSTANDARD NAMING
function GETMARKETCREATORSETTLEMENTFEEDIVISOR51() public view returns (uint256); //inject NONSTANDARD NAMING
function GETFORKINGMARKET637() public view returns (IMarket _market); //inject NONSTANDARD NAMING
function GETENDTIME626() public view returns (uint256); //inject NONSTANDARD NAMING
function GETWINNINGPAYOUTDISTRIBUTIONHASH916() public view returns (bytes32); //inject NONSTANDARD NAMING
function GETWINNINGPAYOUTNUMERATOR375(uint256 _outcome) public view returns (uint256); //inject NONSTANDARD NAMING
function GETWINNINGREPORTINGPARTICIPANT424() public view returns (IReportingParticipant); //inject NONSTANDARD NAMING
function GETREPUTATIONTOKEN35() public view returns (IV2ReputationToken); //inject NONSTANDARD NAMING
function GETFINALIZATIONTIME347() public view returns (uint256); //inject NONSTANDARD NAMING
function GETINITIALREPORTER212() public view returns (IInitialReporter); //inject NONSTANDARD NAMING
function GETDESIGNATEDREPORTINGENDTIME834() public view returns (uint256); //inject NONSTANDARD NAMING
function GETVALIDITYBONDATTOCASH123() public view returns (uint256); //inject NONSTANDARD NAMING
function AFFILIATEFEEDIVISOR322() external view returns (uint256); //inject NONSTANDARD NAMING
function GETNUMPARTICIPANTS137() public view returns (uint256); //inject NONSTANDARD NAMING
function GETDISPUTEPACINGON415() public view returns (bool); //inject NONSTANDARD NAMING
function DERIVEMARKETCREATORFEEAMOUNT558(uint256 _amount) public view returns (uint256); //inject NONSTANDARD NAMING
function RECORDMARKETCREATORFEES738(uint256 _marketCreatorFees, address _sourceAccount, bytes32 _fingerprint) public returns (bool); //inject NONSTANDARD NAMING
function ISCONTAINERFORREPORTINGPARTICIPANT696(IReportingParticipant _reportingParticipant) public view returns (bool); //inject NONSTANDARD NAMING
function ISFINALIZEDASINVALID362() public view returns (bool); //inject NONSTANDARD NAMING
function FINALIZE310() public returns (bool); //inject NONSTANDARD NAMING
function ISFINALIZED623() public view returns (bool); //inject NONSTANDARD NAMING
function GETOPENINTEREST251() public view returns (uint256); //inject NONSTANDARD NAMING
}
contract IReportingParticipant {
function GETSTAKE932() public view returns (uint256); //inject NONSTANDARD NAMING
function GETPAYOUTDISTRIBUTIONHASH1000() public view returns (bytes32); //inject NONSTANDARD NAMING
function LIQUIDATELOSING232() public; //inject NONSTANDARD NAMING
function REDEEM559(address _redeemer) public returns (bool); //inject NONSTANDARD NAMING
function ISDISAVOWED173() public view returns (bool); //inject NONSTANDARD NAMING
function GETPAYOUTNUMERATOR512(uint256 _outcome) public view returns (uint256); //inject NONSTANDARD NAMING
function GETPAYOUTNUMERATORS444() public view returns (uint256[] memory); //inject NONSTANDARD NAMING
function GETMARKET927() public view returns (IMarket); //inject NONSTANDARD NAMING
function GETSIZE85() public view returns (uint256); //inject NONSTANDARD NAMING
}
contract IDisputeCrowdsourcer is IReportingParticipant, IERC20 {
function INITIALIZE90(IAugur _augur, IMarket market, uint256 _size, bytes32 _payoutDistributionHash, uint256[] memory _payoutNumerators, uint256 _crowdsourcerGeneration) public; //inject NONSTANDARD NAMING
function CONTRIBUTE720(address _participant, uint256 _amount, bool _overload) public returns (uint256); //inject NONSTANDARD NAMING
function SETSIZE177(uint256 _size) public; //inject NONSTANDARD NAMING
function GETREMAININGTOFILL115() public view returns (uint256); //inject NONSTANDARD NAMING
function CORRECTSIZE807() public returns (bool); //inject NONSTANDARD NAMING
function GETCROWDSOURCERGENERATION652() public view returns (uint256); //inject NONSTANDARD NAMING
}
contract IInitialReporter is IReportingParticipant, IOwnable {
function INITIALIZE90(IAugur _augur, IMarket _market, address _designatedReporter) public; //inject NONSTANDARD NAMING
function REPORT291(address _reporter, bytes32 _payoutDistributionHash, uint256[] memory _payoutNumerators, uint256 _initialReportStake) public; //inject NONSTANDARD NAMING
function DESIGNATEDREPORTERSHOWED809() public view returns (bool); //inject NONSTANDARD NAMING
function INITIALREPORTERWASCORRECT338() public view returns (bool); //inject NONSTANDARD NAMING
function GETDESIGNATEDREPORTER404() public view returns (address); //inject NONSTANDARD NAMING
function GETREPORTTIMESTAMP304() public view returns (uint256); //inject NONSTANDARD NAMING
function MIGRATETONEWUNIVERSE701(address _designatedReporter) public; //inject NONSTANDARD NAMING
function RETURNREPFROMDISAVOW512() public; //inject NONSTANDARD NAMING
}
contract IReputationToken is IERC20 {
function MIGRATEOUTBYPAYOUT436(uint256[] memory _payoutNumerators, uint256 _attotokens) public returns (bool); //inject NONSTANDARD NAMING
function MIGRATEIN692(address _reporter, uint256 _attotokens) public returns (bool); //inject NONSTANDARD NAMING
function TRUSTEDREPORTINGPARTICIPANTTRANSFER10(address _source, address _destination, uint256 _attotokens) public returns (bool); //inject NONSTANDARD NAMING
function TRUSTEDMARKETTRANSFER61(address _source, address _destination, uint256 _attotokens) public returns (bool); //inject NONSTANDARD NAMING
function TRUSTEDUNIVERSETRANSFER148(address _source, address _destination, uint256 _attotokens) public returns (bool); //inject NONSTANDARD NAMING
function TRUSTEDDISPUTEWINDOWTRANSFER53(address _source, address _destination, uint256 _attotokens) public returns (bool); //inject NONSTANDARD NAMING
function GETUNIVERSE719() public view returns (IUniverse); //inject NONSTANDARD NAMING
function GETTOTALMIGRATED220() public view returns (uint256); //inject NONSTANDARD NAMING
function GETTOTALTHEORETICALSUPPLY552() public view returns (uint256); //inject NONSTANDARD NAMING
function MINTFORREPORTINGPARTICIPANT798(uint256 _amountMigrated) public returns (bool); //inject NONSTANDARD NAMING
}
contract IShareToken is ITyped, IERC1155 {
function INITIALIZE90(IAugur _augur) external; //inject NONSTANDARD NAMING
function INITIALIZEMARKET720(IMarket _market, uint256 _numOutcomes, uint256 _numTicks) public; //inject NONSTANDARD NAMING
function UNSAFETRANSFERFROM654(address _from, address _to, uint256 _id, uint256 _value) public; //inject NONSTANDARD NAMING
function UNSAFEBATCHTRANSFERFROM211(address _from, address _to, uint256[] memory _ids, uint256[] memory _values) public; //inject NONSTANDARD NAMING
function CLAIMTRADINGPROCEEDS854(IMarket _market, address _shareHolder, bytes32 _fingerprint) external returns (uint256[] memory _outcomeFees); //inject NONSTANDARD NAMING
function GETMARKET927(uint256 _tokenId) external view returns (IMarket); //inject NONSTANDARD NAMING
function GETOUTCOME167(uint256 _tokenId) external view returns (uint256); //inject NONSTANDARD NAMING
function GETTOKENID371(IMarket _market, uint256 _outcome) public pure returns (uint256 _tokenId); //inject NONSTANDARD NAMING
function GETTOKENIDS530(IMarket _market, uint256[] memory _outcomes) public pure returns (uint256[] memory _tokenIds); //inject NONSTANDARD NAMING
function BUYCOMPLETESETS983(IMarket _market, address _account, uint256 _amount) external returns (bool); //inject NONSTANDARD NAMING
function BUYCOMPLETESETSFORTRADE277(IMarket _market, uint256 _amount, uint256 _longOutcome, address _longRecipient, address _shortRecipient) external returns (bool); //inject NONSTANDARD NAMING
function SELLCOMPLETESETS485(IMarket _market, address _holder, address _recipient, uint256 _amount, bytes32 _fingerprint) external returns (uint256 _creatorFee, uint256 _reportingFee); //inject NONSTANDARD NAMING
function SELLCOMPLETESETSFORTRADE561(IMarket _market, uint256 _outcome, uint256 _amount, address _shortParticipant, address _longParticipant, address _shortRecipient, address _longRecipient, uint256 _price, address _sourceAccount, bytes32 _fingerprint) external returns (uint256 _creatorFee, uint256 _reportingFee); //inject NONSTANDARD NAMING
function TOTALSUPPLYFORMARKETOUTCOME526(IMarket _market, uint256 _outcome) public view returns (uint256); //inject NONSTANDARD NAMING
function BALANCEOFMARKETOUTCOME21(IMarket _market, uint256 _outcome, address _account) public view returns (uint256); //inject NONSTANDARD NAMING
function LOWESTBALANCEOFMARKETOUTCOMES298(IMarket _market, uint256[] memory _outcomes, address _account) public view returns (uint256); //inject NONSTANDARD NAMING
}
contract IUniverse {
function CREATIONTIME597() external view returns (uint256); //inject NONSTANDARD NAMING
function MARKETBALANCE692(address) external view returns (uint256); //inject NONSTANDARD NAMING
function FORK341() public returns (bool); //inject NONSTANDARD NAMING
function UPDATEFORKVALUES73() public returns (bool); //inject NONSTANDARD NAMING
function GETPARENTUNIVERSE169() public view returns (IUniverse); //inject NONSTANDARD NAMING
function CREATECHILDUNIVERSE712(uint256[] memory _parentPayoutNumerators) public returns (IUniverse); //inject NONSTANDARD NAMING
function GETCHILDUNIVERSE576(bytes32 _parentPayoutDistributionHash) public view returns (IUniverse); //inject NONSTANDARD NAMING
function GETREPUTATIONTOKEN35() public view returns (IV2ReputationToken); //inject NONSTANDARD NAMING
function GETFORKINGMARKET637() public view returns (IMarket); //inject NONSTANDARD NAMING
function GETFORKENDTIME510() public view returns (uint256); //inject NONSTANDARD NAMING
function GETFORKREPUTATIONGOAL776() public view returns (uint256); //inject NONSTANDARD NAMING
function GETPARENTPAYOUTDISTRIBUTIONHASH230() public view returns (bytes32); //inject NONSTANDARD NAMING
function GETDISPUTEROUNDDURATIONINSECONDS412(bool _initial) public view returns (uint256); //inject NONSTANDARD NAMING
function GETORCREATEDISPUTEWINDOWBYTIMESTAMP65(uint256 _timestamp, bool _initial) public returns (IDisputeWindow); //inject NONSTANDARD NAMING
function GETORCREATECURRENTDISPUTEWINDOW813(bool _initial) public returns (IDisputeWindow); //inject NONSTANDARD NAMING
function GETORCREATENEXTDISPUTEWINDOW682(bool _initial) public returns (IDisputeWindow); //inject NONSTANDARD NAMING
function GETORCREATEPREVIOUSDISPUTEWINDOW575(bool _initial) public returns (IDisputeWindow); //inject NONSTANDARD NAMING
function GETOPENINTERESTINATTOCASH866() public view returns (uint256); //inject NONSTANDARD NAMING
function GETTARGETREPMARKETCAPINATTOCASH438() public view returns (uint256); //inject NONSTANDARD NAMING
function GETORCACHEVALIDITYBOND873() public returns (uint256); //inject NONSTANDARD NAMING
function GETORCACHEDESIGNATEDREPORTSTAKE630() public returns (uint256); //inject NONSTANDARD NAMING
function GETORCACHEDESIGNATEDREPORTNOSHOWBOND936() public returns (uint256); //inject NONSTANDARD NAMING
function GETORCACHEMARKETREPBOND533() public returns (uint256); //inject NONSTANDARD NAMING
function GETORCACHEREPORTINGFEEDIVISOR44() public returns (uint256); //inject NONSTANDARD NAMING
function GETDISPUTETHRESHOLDFORFORK42() public view returns (uint256); //inject NONSTANDARD NAMING
function GETDISPUTETHRESHOLDFORDISPUTEPACING311() public view returns (uint256); //inject NONSTANDARD NAMING
function GETINITIALREPORTMINVALUE947() public view returns (uint256); //inject NONSTANDARD NAMING
function GETPAYOUTNUMERATORS444() public view returns (uint256[] memory); //inject NONSTANDARD NAMING
function GETREPORTINGFEEDIVISOR13() public view returns (uint256); //inject NONSTANDARD NAMING
function GETPAYOUTNUMERATOR512(uint256 _outcome) public view returns (uint256); //inject NONSTANDARD NAMING
function GETWINNINGCHILDPAYOUTNUMERATOR599(uint256 _outcome) public view returns (uint256); //inject NONSTANDARD NAMING
function ISOPENINTERESTCASH47(address) public view returns (bool); //inject NONSTANDARD NAMING
function ISFORKINGMARKET534() public view returns (bool); //inject NONSTANDARD NAMING
function GETCURRENTDISPUTEWINDOW862(bool _initial) public view returns (IDisputeWindow); //inject NONSTANDARD NAMING
function GETDISPUTEWINDOWSTARTTIMEANDDURATION802(uint256 _timestamp, bool _initial) public view returns (uint256, uint256); //inject NONSTANDARD NAMING
function ISPARENTOF319(IUniverse _shadyChild) public view returns (bool); //inject NONSTANDARD NAMING
function UPDATETENTATIVEWINNINGCHILDUNIVERSE89(bytes32 _parentPayoutDistributionHash) public returns (bool); //inject NONSTANDARD NAMING
function ISCONTAINERFORDISPUTEWINDOW320(IDisputeWindow _shadyTarget) public view returns (bool); //inject NONSTANDARD NAMING
function ISCONTAINERFORMARKET856(IMarket _shadyTarget) public view returns (bool); //inject NONSTANDARD NAMING
function ISCONTAINERFORREPORTINGPARTICIPANT696(IReportingParticipant _reportingParticipant) public view returns (bool); //inject NONSTANDARD NAMING
function MIGRATEMARKETOUT672(IUniverse _destinationUniverse) public returns (bool); //inject NONSTANDARD NAMING
function MIGRATEMARKETIN285(IMarket _market, uint256 _cashBalance, uint256 _marketOI) public returns (bool); //inject NONSTANDARD NAMING
function DECREMENTOPENINTEREST834(uint256 _amount) public returns (bool); //inject NONSTANDARD NAMING
function DECREMENTOPENINTERESTFROMMARKET346(IMarket _market) public returns (bool); //inject NONSTANDARD NAMING
function INCREMENTOPENINTEREST645(uint256 _amount) public returns (bool); //inject NONSTANDARD NAMING
function GETWINNINGCHILDUNIVERSE709() public view returns (IUniverse); //inject NONSTANDARD NAMING
function ISFORKING853() public view returns (bool); //inject NONSTANDARD NAMING
function DEPOSIT693(address _sender, uint256 _amount, address _market) public returns (bool); //inject NONSTANDARD NAMING
function WITHDRAW474(address _recipient, uint256 _amount, address _market) public returns (bool); //inject NONSTANDARD NAMING
function CREATESCALARMARKET875(uint256 _endTime, uint256 _feePerCashInAttoCash, IAffiliateValidator _affiliateValidator, uint256 _affiliateFeeDivisor, address _designatedReporterAddress, int256[] memory _prices, uint256 _numTicks, string memory _extraInfo) public returns (IMarket _newMarket); //inject NONSTANDARD NAMING
}
contract IV2ReputationToken is IReputationToken {
function PARENTUNIVERSE976() external returns (IUniverse); //inject NONSTANDARD NAMING
function BURNFORMARKET683(uint256 _amountToBurn) public returns (bool); //inject NONSTANDARD NAMING
function MINTFORWARPSYNC909(uint256 _amountToMint, address _target) public returns (bool); //inject NONSTANDARD NAMING
}
library Reporting {
uint256 private constant designated_reporting_duration_seconds939 = 1 days; //inject NONSTANDARD NAMING
uint256 private constant dispute_round_duration_seconds351 = 7 days; //inject NONSTANDARD NAMING
uint256 private constant initial_dispute_round_duration_seconds185 = 1 days; //inject NONSTANDARD NAMING
uint256 private constant dispute_window_buffer_seconds655 = 1 hours; //inject NONSTANDARD NAMING
uint256 private constant fork_duration_seconds463 = 60 days; //inject NONSTANDARD NAMING
uint256 private constant base_market_duration_maximum20 = 30 days; // A market of 30 day length can always be created //inject NONSTANDARD NAMING
uint256 private constant upgrade_cadence254 = 365 days; //inject NONSTANDARD NAMING
uint256 private constant initial_upgrade_timestamp605 = 1627776000; // Aug 1st 2021 //inject NONSTANDARD NAMING
uint256 private constant initial_rep_supply507 = 11 * 10 ** 6 * 10 ** 18; // 11 Million REP //inject NONSTANDARD NAMING
uint256 private constant affiliate_source_cut_divisor194 = 5; // The trader gets 20% of the affiliate fee when an affiliate fee is taken //inject NONSTANDARD NAMING
uint256 private constant default_validity_bond803 = 10 ether; // 10 Cash (Dai) //inject NONSTANDARD NAMING
uint256 private constant validity_bond_floor708 = 10 ether; // 10 Cash (Dai) //inject NONSTANDARD NAMING
uint256 private constant default_reporting_fee_divisor809 = 10000; // .01% fees //inject NONSTANDARD NAMING
uint256 private constant maximum_reporting_fee_divisor548 = 10000; // Minimum .01% fees //inject NONSTANDARD NAMING
uint256 private constant minimum_reporting_fee_divisor749 = 3; // Maximum 33.3~% fees. Note than anything less than a value of 2 here will likely result in bugs such as divide by 0 cases. //inject NONSTANDARD NAMING
uint256 private constant target_invalid_markets_divisor747 = 100; // 1% of markets are expected to be invalid //inject NONSTANDARD NAMING
uint256 private constant target_incorrect_designated_report_markets_divisor83 = 100; // 1% of markets are expected to have an incorrect designate report //inject NONSTANDARD NAMING
uint256 private constant target_designated_report_no_shows_divisor678 = 20; // 5% of markets are expected to have a no show //inject NONSTANDARD NAMING
uint256 private constant target_rep_market_cap_multiplier475 = 5; // We multiply and divide by constants since we may want to multiply by a fractional amount //inject NONSTANDARD NAMING
uint256 private constant fork_threshold_divisor49 = 40; // 2.5% of the total REP supply being filled in a single dispute bond will trigger a fork //inject NONSTANDARD NAMING
uint256 private constant maximum_dispute_rounds529 = 20; // We ensure that after 20 rounds of disputes a fork will occur //inject NONSTANDARD NAMING
uint256 private constant minimum_slow_rounds438 = 8; // We ensure that at least 8 dispute rounds take DISPUTE_ROUND_DURATION_SECONDS+ seconds to complete until the next round begins //inject NONSTANDARD NAMING
function GETDESIGNATEDREPORTINGDURATIONSECONDS10() internal pure returns (uint256) { return designated_reporting_duration_seconds939; } //inject NONSTANDARD NAMING
function GETINITIALDISPUTEROUNDDURATIONSECONDS286() internal pure returns (uint256) { return initial_dispute_round_duration_seconds185; } //inject NONSTANDARD NAMING
function GETDISPUTEWINDOWBUFFERSECONDS683() internal pure returns (uint256) { return dispute_window_buffer_seconds655; } //inject NONSTANDARD NAMING
function GETDISPUTEROUNDDURATIONSECONDS187() internal pure returns (uint256) { return dispute_round_duration_seconds351; } //inject NONSTANDARD NAMING
function GETFORKDURATIONSECONDS842() internal pure returns (uint256) { return fork_duration_seconds463; } //inject NONSTANDARD NAMING
function GETBASEMARKETDURATIONMAXIMUM759() internal pure returns (uint256) { return base_market_duration_maximum20; } //inject NONSTANDARD NAMING
function GETUPGRADECADENCE338() internal pure returns (uint256) { return upgrade_cadence254; } //inject NONSTANDARD NAMING
function GETINITIALUPGRADETIMESTAMP486() internal pure returns (uint256) { return initial_upgrade_timestamp605; } //inject NONSTANDARD NAMING
function GETDEFAULTVALIDITYBOND656() internal pure returns (uint256) { return default_validity_bond803; } //inject NONSTANDARD NAMING
function GETVALIDITYBONDFLOOR634() internal pure returns (uint256) { return validity_bond_floor708; } //inject NONSTANDARD NAMING
function GETTARGETINVALIDMARKETSDIVISOR906() internal pure returns (uint256) { return target_invalid_markets_divisor747; } //inject NONSTANDARD NAMING
function GETTARGETINCORRECTDESIGNATEDREPORTMARKETSDIVISOR444() internal pure returns (uint256) { return target_incorrect_designated_report_markets_divisor83; } //inject NONSTANDARD NAMING
function GETTARGETDESIGNATEDREPORTNOSHOWSDIVISOR524() internal pure returns (uint256) { return target_designated_report_no_shows_divisor678; } //inject NONSTANDARD NAMING
function GETTARGETREPMARKETCAPMULTIPLIER935() internal pure returns (uint256) { return target_rep_market_cap_multiplier475; } //inject NONSTANDARD NAMING
function GETMAXIMUMREPORTINGFEEDIVISOR201() internal pure returns (uint256) { return maximum_reporting_fee_divisor548; } //inject NONSTANDARD NAMING
function GETMINIMUMREPORTINGFEEDIVISOR230() internal pure returns (uint256) { return minimum_reporting_fee_divisor749; } //inject NONSTANDARD NAMING
function GETDEFAULTREPORTINGFEEDIVISOR804() internal pure returns (uint256) { return default_reporting_fee_divisor809; } //inject NONSTANDARD NAMING
function GETINITIALREPSUPPLY859() internal pure returns (uint256) { return initial_rep_supply507; } //inject NONSTANDARD NAMING
function GETAFFILIATESOURCECUTDIVISOR779() internal pure returns (uint256) { return affiliate_source_cut_divisor194; } //inject NONSTANDARD NAMING
function GETFORKTHRESHOLDDIVISOR823() internal pure returns (uint256) { return fork_threshold_divisor49; } //inject NONSTANDARD NAMING
function GETMAXIMUMDISPUTEROUNDS774() internal pure returns (uint256) { return maximum_dispute_rounds529; } //inject NONSTANDARD NAMING
function GETMINIMUMSLOWROUNDS218() internal pure returns (uint256) { return minimum_slow_rounds438; } //inject NONSTANDARD NAMING
}
contract IAugurTrading {
function LOOKUP594(bytes32 _key) public view returns (address); //inject NONSTANDARD NAMING
function LOGPROFITLOSSCHANGED911(IMarket _market, address _account, uint256 _outcome, int256 _netPosition, uint256 _avgPrice, int256 _realizedProfit, int256 _frozenFunds, int256 _realizedCost) public returns (bool); //inject NONSTANDARD NAMING
function LOGORDERCREATED154(IUniverse _universe, bytes32 _orderId, bytes32 _tradeGroupId) public returns (bool); //inject NONSTANDARD NAMING
function LOGORDERCANCELED389(IUniverse _universe, IMarket _market, address _creator, uint256 _tokenRefund, uint256 _sharesRefund, bytes32 _orderId) public returns (bool); //inject NONSTANDARD NAMING
function LOGORDERFILLED166(IUniverse _universe, address _creator, address _filler, uint256 _price, uint256 _fees, uint256 _amountFilled, bytes32 _orderId, bytes32 _tradeGroupId) public returns (bool); //inject NONSTANDARD NAMING
function LOGMARKETVOLUMECHANGED635(IUniverse _universe, address _market, uint256 _volume, uint256[] memory _outcomeVolumes, uint256 _totalTrades) public returns (bool); //inject NONSTANDARD NAMING
function LOGZEROXORDERFILLED898(IUniverse _universe, IMarket _market, bytes32 _orderHash, bytes32 _tradeGroupId, uint8 _orderType, address[] memory _addressData, uint256[] memory _uint256Data) public returns (bool); //inject NONSTANDARD NAMING
function LOGZEROXORDERCANCELED137(address _universe, address _market, address _account, uint256 _outcome, uint256 _price, uint256 _amount, uint8 _type, bytes32 _orderHash) public; //inject NONSTANDARD NAMING
}
contract IOrders {
function SAVEORDER165(uint256[] calldata _uints, bytes32[] calldata _bytes32s, Order.Types _type, IMarket _market, address _sender) external returns (bytes32 _orderId); //inject NONSTANDARD NAMING
function REMOVEORDER407(bytes32 _orderId) external returns (bool); //inject NONSTANDARD NAMING
function GETMARKET927(bytes32 _orderId) public view returns (IMarket); //inject NONSTANDARD NAMING
function GETORDERTYPE39(bytes32 _orderId) public view returns (Order.Types); //inject NONSTANDARD NAMING
function GETOUTCOME167(bytes32 _orderId) public view returns (uint256); //inject NONSTANDARD NAMING
function GETAMOUNT930(bytes32 _orderId) public view returns (uint256); //inject NONSTANDARD NAMING
function GETPRICE598(bytes32 _orderId) public view returns (uint256); //inject NONSTANDARD NAMING
function GETORDERCREATOR755(bytes32 _orderId) public view returns (address); //inject NONSTANDARD NAMING
function GETORDERSHARESESCROWED20(bytes32 _orderId) public view returns (uint256); //inject NONSTANDARD NAMING
function GETORDERMONEYESCROWED161(bytes32 _orderId) public view returns (uint256); //inject NONSTANDARD NAMING
function GETORDERDATAFORCANCEL357(bytes32 _orderId) public view returns (uint256, uint256, Order.Types, IMarket, uint256, address); //inject NONSTANDARD NAMING
function GETORDERDATAFORLOGS935(bytes32 _orderId) public view returns (Order.Types, address[] memory _addressData, uint256[] memory _uint256Data); //inject NONSTANDARD NAMING
function GETBETTERORDERID822(bytes32 _orderId) public view returns (bytes32); //inject NONSTANDARD NAMING
function GETWORSEORDERID439(bytes32 _orderId) public view returns (bytes32); //inject NONSTANDARD NAMING
function GETBESTORDERID727(Order.Types _type, IMarket _market, uint256 _outcome) public view returns (bytes32); //inject NONSTANDARD NAMING
function GETWORSTORDERID835(Order.Types _type, IMarket _market, uint256 _outcome) public view returns (bytes32); //inject NONSTANDARD NAMING
function GETLASTOUTCOMEPRICE593(IMarket _market, uint256 _outcome) public view returns (uint256); //inject NONSTANDARD NAMING
function GETORDERID157(Order.Types _type, IMarket _market, uint256 _amount, uint256 _price, address _sender, uint256 _blockNumber, uint256 _outcome, uint256 _moneyEscrowed, uint256 _sharesEscrowed) public pure returns (bytes32); //inject NONSTANDARD NAMING
function GETTOTALESCROWED463(IMarket _market) public view returns (uint256); //inject NONSTANDARD NAMING
function ISBETTERPRICE274(Order.Types _type, uint256 _price, bytes32 _orderId) public view returns (bool); //inject NONSTANDARD NAMING
function ISWORSEPRICE692(Order.Types _type, uint256 _price, bytes32 _orderId) public view returns (bool); //inject NONSTANDARD NAMING
function ASSERTISNOTBETTERPRICE18(Order.Types _type, uint256 _price, bytes32 _betterOrderId) public view returns (bool); //inject NONSTANDARD NAMING
function ASSERTISNOTWORSEPRICE875(Order.Types _type, uint256 _price, bytes32 _worseOrderId) public returns (bool); //inject NONSTANDARD NAMING
function RECORDFILLORDER693(bytes32 _orderId, uint256 _sharesFilled, uint256 _tokensFilled, uint256 _fill) external returns (bool); //inject NONSTANDARD NAMING
function SETPRICE687(IMarket _market, uint256 _outcome, uint256 _price) external returns (bool); //inject NONSTANDARD NAMING
}
library Order {
using SafeMathUint256 for uint256;
enum Types {
Bid, Ask
}
enum TradeDirections {
Long, Short
}
struct Data {
// Contracts
IMarket market;
IAugur augur;
IAugurTrading augurTrading;
IShareToken shareToken;
ICash cash;
// Order
bytes32 id;
address creator;
uint256 outcome;
Order.Types orderType;
uint256 amount;
uint256 price;
uint256 sharesEscrowed;
uint256 moneyEscrowed;
bytes32 betterOrderId;
bytes32 worseOrderId;
}
function CREATE815(IAugur _augur, IAugurTrading _augurTrading, address _creator, uint256 _outcome, Order.Types _type, uint256 _attoshares, uint256 _price, IMarket _market, bytes32 _betterOrderId, bytes32 _worseOrderId) internal view returns (Data memory) { //inject NONSTANDARD NAMING
require(_outcome < _market.GETNUMBEROFOUTCOMES636(), "Order.create: Outcome is not within market range");
require(_price != 0, "Order.create: Price may not be 0");
require(_price < _market.GETNUMTICKS752(), "Order.create: Price is outside of market range");
require(_attoshares > 0, "Order.create: Cannot use amount of 0");
require(_creator != address(0), "Order.create: Creator is 0x0");
IShareToken _shareToken = IShareToken(_augur.LOOKUP594("ShareToken"));
return Data({
market: _market,
augur: _augur,
augurTrading: _augurTrading,
shareToken: _shareToken,
cash: ICash(_augur.LOOKUP594("Cash")),
id: 0,
creator: _creator,
outcome: _outcome,
orderType: _type,
amount: _attoshares,
price: _price,
sharesEscrowed: 0,
moneyEscrowed: 0,
betterOrderId: _betterOrderId,
worseOrderId: _worseOrderId
});
}
//
// "public" functions
//
function GETORDERID157(Order.Data memory _orderData, IOrders _orders) internal view returns (bytes32) { //inject NONSTANDARD NAMING
if (_orderData.id == bytes32(0)) {
bytes32 _orderId = CALCULATEORDERID856(_orderData.orderType, _orderData.market, _orderData.amount, _orderData.price, _orderData.creator, block.number, _orderData.outcome, _orderData.moneyEscrowed, _orderData.sharesEscrowed);
require(_orders.GETAMOUNT930(_orderId) == 0, "Order.getOrderId: New order had amount. This should not be possible");
_orderData.id = _orderId;
}
return _orderData.id;
}
function CALCULATEORDERID856(Order.Types _type, IMarket _market, uint256 _amount, uint256 _price, address _sender, uint256 _blockNumber, uint256 _outcome, uint256 _moneyEscrowed, uint256 _sharesEscrowed) internal pure returns (bytes32) { //inject NONSTANDARD NAMING
return sha256(abi.encodePacked(_type, _market, _amount, _price, _sender, _blockNumber, _outcome, _moneyEscrowed, _sharesEscrowed));
}
function GETORDERTRADINGTYPEFROMMAKERDIRECTION100(Order.TradeDirections _creatorDirection) internal pure returns (Order.Types) { //inject NONSTANDARD NAMING
return (_creatorDirection == Order.TradeDirections.Long) ? Order.Types.Bid : Order.Types.Ask;
}
function GETORDERTRADINGTYPEFROMFILLERDIRECTION800(Order.TradeDirections _fillerDirection) internal pure returns (Order.Types) { //inject NONSTANDARD NAMING
return (_fillerDirection == Order.TradeDirections.Long) ? Order.Types.Ask : Order.Types.Bid;
}
function SAVEORDER165(Order.Data memory _orderData, bytes32 _tradeGroupId, IOrders _orders) internal returns (bytes32) { //inject NONSTANDARD NAMING
GETORDERID157(_orderData, _orders);
uint256[] memory _uints = new uint256[](5);
_uints[0] = _orderData.amount;
_uints[1] = _orderData.price;
_uints[2] = _orderData.outcome;
_uints[3] = _orderData.moneyEscrowed;
_uints[4] = _orderData.sharesEscrowed;
bytes32[] memory _bytes32s = new bytes32[](4);
_bytes32s[0] = _orderData.betterOrderId;
_bytes32s[1] = _orderData.worseOrderId;
_bytes32s[2] = _tradeGroupId;
_bytes32s[3] = _orderData.id;
return _orders.SAVEORDER165(_uints, _bytes32s, _orderData.orderType, _orderData.market, _orderData.creator);
}
}
interface IUniswapV2Pair {
event APPROVAL665(address indexed owner, address indexed spender, uint value); //inject NONSTANDARD NAMING
event TRANSFER723(address indexed from, address indexed to, uint value); //inject NONSTANDARD NAMING
function NAME524() external pure returns (string memory); //inject NONSTANDARD NAMING
function SYMBOL582() external pure returns (string memory); //inject NONSTANDARD NAMING
function DECIMALS958() external pure returns (uint8); //inject NONSTANDARD NAMING
function TOTALSUPPLY304() external view returns (uint); //inject NONSTANDARD NAMING
function BALANCEOF492(address owner) external view returns (uint); //inject NONSTANDARD NAMING
function ALLOWANCE377(address owner, address spender) external view returns (uint); //inject NONSTANDARD NAMING
function APPROVE293(address spender, uint value) external returns (bool); //inject NONSTANDARD NAMING
function TRANSFER644(address to, uint value) external returns (bool); //inject NONSTANDARD NAMING
function TRANSFERFROM669(address from, address to, uint value) external returns (bool); //inject NONSTANDARD NAMING
function DOMAIN_SEPARATOR256() external view returns (bytes32); //inject NONSTANDARD NAMING
function PERMIT_TYPEHASH256() external pure returns (bytes32); //inject NONSTANDARD NAMING
function NONCES605(address owner) external view returns (uint); //inject NONSTANDARD NAMING
function PERMIT866(address owner, address spender, uint value, uint deadline, uint8 v, bytes32 r, bytes32 s) external; //inject NONSTANDARD NAMING
event MINT159(address indexed sender, uint amount0, uint amount1); //inject NONSTANDARD NAMING
event BURN674(address indexed sender, uint amount0, uint amount1, address indexed to); //inject NONSTANDARD NAMING
event SWAP992( //inject NONSTANDARD NAMING
address indexed sender,
uint amount0In,
uint amount1In,
uint amount0Out,
uint amount1Out,
address indexed to
);
event SYNC856(uint112 reserve0, uint112 reserve1); //inject NONSTANDARD NAMING
function MINIMUM_LIQUIDITY585() external pure returns (uint); //inject NONSTANDARD NAMING
function FACTORY704() external view returns (address); //inject NONSTANDARD NAMING
function TOKEN0151() external view returns (address); //inject NONSTANDARD NAMING
function TOKEN132() external view returns (address); //inject NONSTANDARD NAMING
function GETRESERVES901() external view returns (uint112 reserve0, uint112 reserve1, uint32 blockTimestampLast); //inject NONSTANDARD NAMING
function PRICE0CUMULATIVELAST708() external view returns (uint); //inject NONSTANDARD NAMING
function PRICE1CUMULATIVELAST245() external view returns (uint); //inject NONSTANDARD NAMING
function KLAST943() external view returns (uint); //inject NONSTANDARD NAMING
function MINT146(address to) external returns (uint liquidity); //inject NONSTANDARD NAMING
function BURN234(address to) external returns (uint amount0, uint amount1); //inject NONSTANDARD NAMING
function SWAP505(uint amount0Out, uint amount1Out, address to, bytes calldata data) external; //inject NONSTANDARD NAMING
function SKIM81(address to) external; //inject NONSTANDARD NAMING
function SYNC86() external; //inject NONSTANDARD NAMING
function INITIALIZE90(address, address) external; //inject NONSTANDARD NAMING
}
contract IRepSymbol {
function GETREPSYMBOL498(address _augur, address _universe) external view returns (string memory); //inject NONSTANDARD NAMING
}
contract ReputationToken is VariableSupplyToken, IV2ReputationToken {
using SafeMathUint256 for uint256;
string constant public name600 = "Reputation"; //inject NONSTANDARD NAMING
IUniverse internal universe;
IUniverse public parentUniverse;
uint256 internal totalMigrated;
IERC20 public legacyRepToken;
IAugur public augur;
address public warpSync;
constructor(IAugur _augur, IUniverse _universe, IUniverse _parentUniverse) public {
augur = _augur;
universe = _universe;
parentUniverse = _parentUniverse;
warpSync = _augur.LOOKUP594("WarpSync");
legacyRepToken = IERC20(_augur.LOOKUP594("LegacyReputationToken"));
require(warpSync != address(0));
require(legacyRepToken != IERC20(0));
}
function SYMBOL582() public view returns (string memory) { //inject NONSTANDARD NAMING
return IRepSymbol(augur.LOOKUP594("RepSymbol")).GETREPSYMBOL498(address(augur), address(universe));
}
function MIGRATEOUTBYPAYOUT436(uint256[] memory _payoutNumerators, uint256 _attotokens) public returns (bool) { //inject NONSTANDARD NAMING
require(_attotokens > 0);
IUniverse _destinationUniverse = universe.CREATECHILDUNIVERSE712(_payoutNumerators);
IReputationToken _destination = _destinationUniverse.GETREPUTATIONTOKEN35();
BURN234(msg.sender, _attotokens);
_destination.MIGRATEIN692(msg.sender, _attotokens);
return true;
}
function MIGRATEIN692(address _reporter, uint256 _attotokens) public returns (bool) { //inject NONSTANDARD NAMING
IUniverse _parentUniverse = parentUniverse;
require(ReputationToken(msg.sender) == _parentUniverse.GETREPUTATIONTOKEN35());
require(augur.GETTIMESTAMP626() < _parentUniverse.GETFORKENDTIME510());
MINT146(_reporter, _attotokens);
totalMigrated += _attotokens;
// Update the fork tentative winner and finalize if we can
if (!_parentUniverse.GETFORKINGMARKET637().ISFINALIZED623()) {
_parentUniverse.UPDATETENTATIVEWINNINGCHILDUNIVERSE89(universe.GETPARENTPAYOUTDISTRIBUTIONHASH230());
}
return true;
}
function MINTFORREPORTINGPARTICIPANT798(uint256 _amountMigrated) public returns (bool) { //inject NONSTANDARD NAMING
IReportingParticipant _reportingParticipant = IReportingParticipant(msg.sender);
require(parentUniverse.ISCONTAINERFORREPORTINGPARTICIPANT696(_reportingParticipant));
// simulate a 40% ROI which would have occured during a normal dispute had this participant's outcome won the dispute
uint256 _bonus = _amountMigrated.MUL760(2) / 5;
MINT146(address(_reportingParticipant), _bonus);
return true;
}
function MINTFORWARPSYNC909(uint256 _amountToMint, address _target) public returns (bool) { //inject NONSTANDARD NAMING
require(warpSync == msg.sender);
MINT146(_target, _amountToMint);
universe.UPDATEFORKVALUES73();
return true;
}
function BURNFORMARKET683(uint256 _amountToBurn) public returns (bool) { //inject NONSTANDARD NAMING
require(universe.ISCONTAINERFORMARKET856(IMarket(msg.sender)));
BURN234(msg.sender, _amountToBurn);
return true;
}
function TRUSTEDUNIVERSETRANSFER148(address _source, address _destination, uint256 _attotokens) public returns (bool) { //inject NONSTANDARD NAMING
require(IUniverse(msg.sender) == universe);
_TRANSFER433(_source, _destination, _attotokens);
return true;
}
function TRUSTEDMARKETTRANSFER61(address _source, address _destination, uint256 _attotokens) public returns (bool) { //inject NONSTANDARD NAMING
require(universe.ISCONTAINERFORMARKET856(IMarket(msg.sender)));
_TRANSFER433(_source, _destination, _attotokens);
return true;
}
function TRUSTEDREPORTINGPARTICIPANTTRANSFER10(address _source, address _destination, uint256 _attotokens) public returns (bool) { //inject NONSTANDARD NAMING
require(universe.ISCONTAINERFORREPORTINGPARTICIPANT696(IReportingParticipant(msg.sender)));
_TRANSFER433(_source, _destination, _attotokens);
return true;
}
function TRUSTEDDISPUTEWINDOWTRANSFER53(address _source, address _destination, uint256 _attotokens) public returns (bool) { //inject NONSTANDARD NAMING
require(universe.ISCONTAINERFORDISPUTEWINDOW320(IDisputeWindow(msg.sender)));
_TRANSFER433(_source, _destination, _attotokens);
return true;
}
function ASSERTREPUTATIONTOKENISLEGITCHILD164(IReputationToken _shadyReputationToken) private view { //inject NONSTANDARD NAMING
IUniverse _universe = _shadyReputationToken.GETUNIVERSE719();
require(universe.ISPARENTOF319(_universe));
require(_universe.GETREPUTATIONTOKEN35() == _shadyReputationToken);
}
function GETUNIVERSE719() public view returns (IUniverse) { //inject NONSTANDARD NAMING
return universe;
}
function GETTOTALMIGRATED220() public view returns (uint256) { //inject NONSTANDARD NAMING
return totalMigrated;
}
function GETLEGACYREPTOKEN110() public view returns (IERC20) { //inject NONSTANDARD NAMING
return legacyRepToken;
}
function GETTOTALTHEORETICALSUPPLY552() public view returns (uint256) { //inject NONSTANDARD NAMING
uint256 _totalSupply = totalSupply;
if (parentUniverse == IUniverse(0)) {
return _totalSupply.ADD571(legacyRepToken.TOTALSUPPLY304()).SUB692(legacyRepToken.BALANCEOF492(address(1))).SUB692(legacyRepToken.BALANCEOF492(address(0)));
} else if (augur.GETTIMESTAMP626() >= parentUniverse.GETFORKENDTIME510()) {
return _totalSupply;
} else {
return _totalSupply + parentUniverse.GETREPUTATIONTOKEN35().GETTOTALTHEORETICALSUPPLY552();
}
}
function ONTOKENTRANSFER292(address _from, address _to, uint256 _value) internal { //inject NONSTANDARD NAMING
augur.LOGREPUTATIONTOKENSTRANSFERRED904(universe, _from, _to, _value, balances[_from], balances[_to]);
}
function ONMINT315(address _target, uint256 _amount) internal { //inject NONSTANDARD NAMING
augur.LOGREPUTATIONTOKENSMINTED985(universe, _target, _amount, totalSupply, balances[_target]);
}
function ONBURN653(address _target, uint256 _amount) internal { //inject NONSTANDARD NAMING
augur.LOGREPUTATIONTOKENSBURNED995(universe, _target, _amount, totalSupply, balances[_target]);
}
function MIGRATEFROMLEGACYREPUTATIONTOKEN918() public returns (bool) { //inject NONSTANDARD NAMING
require(parentUniverse == IUniverse(0));
uint256 _legacyBalance = legacyRepToken.BALANCEOF492(msg.sender);
require(legacyRepToken.TRANSFERFROM669(msg.sender, address(1), _legacyBalance));
MINT146(msg.sender, _legacyBalance);
return true;
}
}
|
inject NONSTANDARD NAMING
|
function SYMBOL582() external pure returns (string memory);
| 2,554,122 |
./full_match/137/0x2Ff03681804437E39fB40D7AEd54D70A200AD363/sources/contracts/dragginator/legends.sol
|
calculates the next token ID based on value of _currentTokenId return uint256 for the next token ID/
|
function _getNextTokenId() private view returns (uint256) {
return _currentTokenId.add(1);
}*/
| 4,736,902 |
pragma solidity ^0.5.2;
import "openzeppelin-solidity/contracts/math/SafeMath.sol";
import "openzeppelin-solidity/contracts/token/ERC20/IERC20.sol";
interface AddressRegistry {
function getAddr(string calldata name) external view returns (address);
}
// Kyber's contract Interface
interface KyberExchange {
// Kyber's trade function
function trade(
address src,
uint srcAmount,
address dest,
address destAddress,
uint maxDestAmount,
uint minConversionRate,
address walletId
) external payable returns (uint);
// Kyber's Get expected Rate function
function getExpectedRate(address src, address dest, uint srcQty) external view returns (uint, uint);
}
// Uniswap's factory Interface
interface UniswapFactory {
// get exchange from token's address
function getExchange(address token) external view returns (address exchange);
}
// Uniswap's exchange Interface
interface UniswapExchange {
// Get Prices
function getEthToTokenInputPrice(uint256 eth_sold) external view returns (uint256 tokens_bought);
function getEthToTokenOutputPrice(uint256 tokens_bought) external view returns (uint256 eth_sold);
function getTokenToEthInputPrice(uint256 tokens_sold) external view returns (uint256 eth_bought);
function getTokenToEthOutputPrice(uint256 eth_bought) external view returns (uint256 tokens_sold);
// Trade ETH to ERC20
function ethToTokenTransferInput(uint256 min_tokens, uint256 deadline, address recipient)
external
payable
returns (uint256 tokens_bought);
function ethToTokenTransferOutput(uint256 tokens_bought, uint256 deadline, address recipient)
external
payable
returns (uint256 eth_sold);
// Trade ERC20 to ETH
function tokenToEthTransferInput(uint256 tokens_sold, uint256 min_eth, uint256 deadline, address recipient)
external
returns (uint256 eth_bought);
function tokenToEthTransferOutput(uint256 eth_bought, uint256 max_tokens, uint256 deadline, address recipient)
external
returns (uint256 tokens_sold);
// Trade ERC20 to ERC20
function tokenToTokenTransferInput(
uint256 tokens_sold,
uint256 min_tokens_bought,
uint256 min_eth_bought,
uint256 deadline,
address recipient,
address token_addr
) external returns (uint256 tokens_bought);
function tokenToTokenTransferOutput(
uint256 tokens_bought,
uint256 max_tokens_sold,
uint256 max_eth_sold,
uint256 deadline,
address recipient,
address token_addr
) external returns (uint256 tokens_sold);
}
contract Registry {
address public addressRegistry;
modifier onlyAdmin() {
require(msg.sender == _getAddress("admin"), "Permission Denied");
_;
}
function _getAddress(string memory name) internal view returns (address) {
AddressRegistry addrReg = AddressRegistry(addressRegistry);
return addrReg.getAddr(name);
}
}
// common stuffs in Kyber and Uniswap's trade
contract CommonStuffs {
using SafeMath for uint;
// Check required ETH Quantity to execute code
function _getToken(address trader, address src, uint srcAmt, address eth) internal returns (uint ethQty) {
if (src == eth) {
require(msg.value == srcAmt, "Invalid Operation");
ethQty = srcAmt;
} else {
IERC20 tokenFunctions = IERC20(src);
tokenFunctions.transferFrom(trader, address(this), srcAmt);
ethQty = 0;
}
}
function _approveDexes(address token, address dexToApprove) internal returns (bool) {
IERC20 tokenFunctions = IERC20(token);
return tokenFunctions.approve(dexToApprove, uint(0 - 1));
}
function _allowance(address token, address spender) internal view returns (uint) {
IERC20 tokenFunctions = IERC20(token);
return tokenFunctions.allowance(address(this), spender);
}
}
// Kyber's dex functions
contract Kyber is Registry, CommonStuffs {
function getExpectedRateKyber(address src, address dest, uint srcAmt) internal view returns (uint) {
KyberExchange kyberFunctions = KyberExchange(_getAddress("kyber"));
uint expectedRate;
(expectedRate, ) = kyberFunctions.getExpectedRate(src, dest, srcAmt);
uint kyberRate = expectedRate.mul(srcAmt);
return kyberRate;
}
// approve to Kyber Proxy contract
function _approveKyber(address token) internal returns (bool) {
address kyberProxy = _getAddress("kyber");
return _approveDexes(token, kyberProxy);
}
// Check Allowance to Kyber Proxy contract
function _allowanceKyber(address token) internal view returns (uint) {
address kyberProxy = _getAddress("kyber");
return _allowance(token, kyberProxy);
}
function _allowanceApproveKyber(address token) internal returns (bool) {
uint allowanceGiven = _allowanceKyber(token);
if (allowanceGiven == 0) {
return _approveKyber(token);
} else {
return true;
}
}
/**
* @dev Kyber's trade when token to sell Amount fixed
* @param src - Token address to sell (for ETH it's "0xeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeee")
* @param srcAmt - amount of token for sell
* @param dest - Token address to buy (for ETH it's "0xeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeee")
* @param minDestAmt - min amount of token to buy (slippage)
*/
function tradeSrcKyber(
address src, // token to sell
uint srcAmt, // amount of token for sell
address dest, // token to buy
uint minDestAmt // minimum slippage rate
) public payable returns (uint tokensBought) {
address eth = _getAddress("eth");
uint ethQty = _getToken(msg.sender, src, srcAmt, eth);
// Interacting with Kyber Proxy Contract
KyberExchange kyberFunctions = KyberExchange(_getAddress("kyber"));
tokensBought = kyberFunctions.trade.value(ethQty)(src, srcAmt, dest, msg.sender, uint(0 - 1), minDestAmt, _getAddress("admin"));
}
function tradeDestKyber(
address src, // token to sell
uint maxSrcAmt, // amount of token for sell
address dest, // token to buy
uint destAmt // minimum slippage rate
) public payable returns (uint tokensBought) {
address eth = _getAddress("eth");
uint ethQty = _getToken(msg.sender, src, maxSrcAmt, eth);
// Interacting with Kyber Proxy Contract
KyberExchange kyberFunctions = KyberExchange(_getAddress("kyber"));
tokensBought = kyberFunctions.trade.value(ethQty)(src, maxSrcAmt, dest, msg.sender, destAmt, destAmt, _getAddress("admin"));
// maxDestAmt usecase implementated
if (src == eth && address(this).balance > 0) {
msg.sender.transfer(address(this).balance);
} else if (src != eth) {
// as there is no balanceOf of eth
IERC20 srcTkn = IERC20(src);
uint srcBal = srcTkn.balanceOf(address(this));
if (srcBal > 0) {
srcTkn.transfer(msg.sender, srcBal);
}
}
}
}
// Uinswap's dex functions
contract Uniswap is Registry, CommonStuffs {
// Get Uniswap's Exchange address from Factory Contract
function _getExchangeAddress(address _token) internal view returns (address) {
UniswapFactory uniswapMain = UniswapFactory(_getAddress("uniswap"));
return uniswapMain.getExchange(_token);
}
// Approve Uniswap's Exchanges
function _approveUniswapExchange(address token) internal returns (bool) {
address uniswapExchange = _getExchangeAddress(token);
return _approveDexes(token, uniswapExchange);
}
// Check Allowance to Uniswap's Exchanges
function _allowanceUniswapExchange(address token) internal view returns (uint) {
address uniswapExchange = _getExchangeAddress(token);
return _allowance(token, uniswapExchange);
}
function _allowanceApproveUniswap(address token) internal returns (bool) {
uint allowanceGiven = _allowanceUniswapExchange(token);
if (allowanceGiven == 0) {
return _approveUniswapExchange(token);
} else {
return true;
}
}
/**
* @dev Uniswap's get expected rate from source
* @param src - Token address to sell (for ETH it's "0xeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeee")
* @param dest - Token address to buy (for ETH it's "0xeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeee")
* @param srcAmt - source token amount
*/
function getExpectedRateSrcUniswap(address src, address dest, uint srcAmt) internal view returns (uint256) {
address eth = _getAddress("eth");
if (src == eth) {
// define uniswap exchange with dest address
UniswapExchange exchangeContract = UniswapExchange(_getExchangeAddress(dest));
return exchangeContract.getEthToTokenInputPrice(srcAmt);
} else if (dest == eth) {
// define uniswap exchange with src address
UniswapExchange exchangeContract = UniswapExchange(_getExchangeAddress(src));
return exchangeContract.getTokenToEthInputPrice(srcAmt);
} else {
UniswapExchange exchangeContractSrc = UniswapExchange(_getExchangeAddress(src));
UniswapExchange exchangeContractDest = UniswapExchange(_getExchangeAddress(dest));
uint ethQty = exchangeContractSrc.getTokenToEthInputPrice(srcAmt);
return exchangeContractDest.getEthToTokenInputPrice(ethQty);
}
}
/**
* @dev Uniswap's get expected rate from dest
* @param src - Token address to sell (for ETH it's "0xeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeee")
* @param dest - Token address to buy (for ETH it's "0xeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeee")
* @param destAmt - dest token amount
*/
function getExpectedRateDestUniswap(address src, address dest, uint destAmt) internal view returns (uint256) {
address eth = _getAddress("eth");
if (src == eth) {
// define uniswap exchange with dest address
UniswapExchange exchangeContract = UniswapExchange(_getExchangeAddress(dest));
return exchangeContract.getEthToTokenOutputPrice(destAmt);
} else if (dest == eth) {
// define uniswap exchange with src address
UniswapExchange exchangeContract = UniswapExchange(_getExchangeAddress(src));
return exchangeContract.getTokenToEthOutputPrice(destAmt);
} else {
UniswapExchange exchangeContractSrc = UniswapExchange(_getExchangeAddress(src));
UniswapExchange exchangeContractDest = UniswapExchange(_getExchangeAddress(dest));
uint ethQty = exchangeContractDest.getTokenToEthInputPrice(destAmt);
return exchangeContractSrc.getEthToTokenInputPrice(ethQty);
}
}
/**
* @dev Uniswap's trade when token to sell Amount fixed
* @param src - Token address to sell (for ETH it's "0xeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeee")
* @param srcAmt - amount of token for sell
* @param dest - Token address to buy (for ETH it's "0xeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeee")
* @param minDestAmt - min amount of token to buy (slippage)
* @param deadline - time for this transaction to be valid
*/
function tradeSrcUniswap(address src, uint srcAmt, address dest, uint minDestAmt, uint deadline) public payable returns (uint) {
address eth = _getAddress("eth");
uint ethQty = _getToken(msg.sender, src, srcAmt, eth);
if (src == eth) {
UniswapExchange exchangeContract = UniswapExchange(_getExchangeAddress(dest));
uint tokensBought = exchangeContract.ethToTokenTransferInput.value(ethQty)(minDestAmt, deadline, msg.sender);
return tokensBought;
} else if (dest == eth) {
UniswapExchange exchangeContract = UniswapExchange(_getExchangeAddress(src));
uint ethBought = exchangeContract.tokenToEthTransferInput(srcAmt, minDestAmt, deadline, msg.sender);
return ethBought;
} else {
UniswapExchange exchangeContract = UniswapExchange(_getExchangeAddress(src));
uint tokensBought = exchangeContract.tokenToTokenTransferInput(srcAmt, minDestAmt, uint(0), deadline, msg.sender, dest);
return tokensBought;
}
}
/**
* @dev Uniswap's trade when token to buy Amount fixed
* @param src - Token address to sell (for ETH it's "0xeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeee")
* @param maxSrcAmt - max amount of token for sell (slippage)
* @param dest - Token address to buy (for ETH it's "0xeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeee")
* @param destAmt - amount of token to buy
* @param deadline - time for this transaction to be valid
*/
function tradeDestUniswap(address src, uint maxSrcAmt, address dest, uint destAmt, uint deadline) public payable returns (uint) {
address eth = _getAddress("eth");
uint ethQty = _getToken(msg.sender, src, maxSrcAmt, eth);
if (src == eth) {
UniswapExchange exchangeContract = UniswapExchange(_getExchangeAddress(dest));
uint ethSold = exchangeContract.ethToTokenTransferOutput.value(ethQty)(destAmt, deadline, msg.sender);
if (ethSold < ethQty) {
uint srcToReturn = ethQty - ethSold;
msg.sender.transfer(srcToReturn);
}
return ethSold;
} else if (dest == eth) {
UniswapExchange exchangeContract = UniswapExchange(_getExchangeAddress(src));
uint tokensSold = exchangeContract.tokenToEthTransferOutput(destAmt, maxSrcAmt, deadline, msg.sender);
if (tokensSold < maxSrcAmt) {
IERC20 srcTkn = IERC20(src);
uint srcToReturn = maxSrcAmt - tokensSold;
srcTkn.transfer(msg.sender, srcToReturn);
}
return tokensSold;
} else {
UniswapExchange exchangeContractSrc = UniswapExchange(_getExchangeAddress(src));
uint tokensSold = exchangeContractSrc.tokenToTokenTransferOutput(destAmt, maxSrcAmt, uint(0 - 1), deadline, msg.sender, dest);
if (tokensSold < maxSrcAmt) {
IERC20 srcTkn = IERC20(src);
uint srcToReturn = maxSrcAmt - tokensSold;
srcTkn.transfer(msg.sender, srcToReturn);
}
return tokensSold;
}
}
}
contract Trade is Kyber, Uniswap {
function getRateFromSrc(address src, address dest, uint srcAmt) public view returns (uint, uint) {
uint uniswapRate = getExpectedRateSrcUniswap(src, dest, srcAmt);
uint kyberRate = getExpectedRateKyber(src, dest, srcAmt);
if (uniswapRate > kyberRate) {
return (uniswapRate, 1);
} else {
return (kyberRate, 2);
}
}
function tradeFromSrc(address src, uint srcAmt, address dest, uint minDestAmt, uint dexNum) public payable returns (uint) {
address eth = _getAddress("eth");
if (dexNum == 1) {
if (src == eth) {
return tradeSrcUniswap(src, srcAmt, dest, minDestAmt, now + 10000000);
} else {
_allowanceApproveUniswap(src);
return tradeSrcUniswap(src, srcAmt, dest, minDestAmt, now + 10000000);
}
} else {
if (src == eth) {
return tradeSrcKyber(src, srcAmt, dest, minDestAmt);
} else {
_allowanceApproveKyber(src);
return tradeSrcKyber(src, srcAmt, dest, minDestAmt);
}
}
}
function tradeFromDest(address src, uint maxSrcAmt, address dest, uint destAmt, uint dexNum) public payable returns (uint) {
address eth = _getAddress("eth");
if (dexNum == 1) {
if (src == eth) {
return tradeDestUniswap(src, maxSrcAmt, dest, destAmt, now + 10000000);
} else {
_allowanceApproveUniswap(src);
return tradeDestUniswap(src, maxSrcAmt, dest, destAmt, now + 10000000);
}
} else {
if (src == eth) {
return tradeDestKyber(src, maxSrcAmt, dest, destAmt);
} else {
_allowanceApproveKyber(src);
return tradeDestKyber(src, maxSrcAmt, dest, destAmt);
}
}
}
}
|
approve to Kyber Proxy contract
|
function _approveKyber(address token) internal returns (bool) {
address kyberProxy = _getAddress("kyber");
return _approveDexes(token, kyberProxy);
}
| 12,644,952 |
pragma solidity 0.4.15;
/**
* @title SafeMath
* @dev Math operations with safety checks that throw on error
*/
library SafeMath {
function mul(uint256 a, uint256 b) internal constant returns (uint256) {
uint256 c = a * b;
assert(a == 0 || c / a == b);
return c;
}
function div(uint256 a, uint256 b) internal constant returns (uint256) {
// assert(b > 0); // Solidity automatically throws when dividing by 0
uint256 c = a / b;
// assert(a == b * c + a % b); // There is no case in which this doesn't hold
return c;
}
function sub(uint256 a, uint256 b) internal constant returns (uint256) {
assert(b <= a);
return a - b;
}
function add(uint256 a, uint256 b) internal constant returns (uint256) {
uint256 c = a + b;
assert(c >= a);
return c;
}
}
contract Controlled {
/// @notice The address of the controller is the only address that can call
/// a function with this modifier
modifier onlyController { require(msg.sender == controller); _; }
address public controller;
function Controlled() public { controller = msg.sender;}
/// @notice Changes the controller of the contract
/// @param _newController The new controller of the contract
function changeController(address _newController) public onlyController {
controller = _newController;
}
}
/*
Copyright 2016, Jordi Baylina
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
/// @title MiniMeToken Contract
/// @author Jordi Baylina
/// @dev This token contract's goal is to make it easy for anyone to clone this
/// token using the token distribution at a given block, this will allow DAO's
/// and DApps to upgrade their features in a decentralized manner without
/// affecting the original token
/// @dev It is ERC20 compliant, but still needs to under go further testing.
contract ApproveAndCallFallBack {
function receiveApproval(address from, uint256 _amount, address _token, bytes _data) public;
}
/// @dev The actual token contract, the default controller is the msg.sender
/// that deploys the contract, so usually this token will be deployed by a
/// token controller contract, which Giveth will call a "Campaign"
contract MiniMeToken is Controlled {
string public name; //The Token's name: e.g. DigixDAO Tokens
uint8 public decimals; //Number of decimals of the smallest unit
string public symbol; //An identifier: e.g. REP
string public version = 'MMT_0.2'; //An arbitrary versioning scheme
/// @dev `Checkpoint` is the structure that attaches a block number to a
/// given value, the block number attached is the one that last changed the
/// value
struct Checkpoint {
// `fromBlock` is the block number that the value was generated from
uint128 fromBlock;
// `value` is the amount of tokens at a specific block number
uint128 value;
}
// `parentToken` is the Token address that was cloned to produce this token;
// it will be 0x0 for a token that was not cloned
MiniMeToken public parentToken;
// `parentSnapShotBlock` is the block number from the Parent Token that was
// used to determine the initial distribution of the Clone Token
uint public parentSnapShotBlock;
// `creationBlock` is the block number that the Clone Token was created
uint public creationBlock;
// `balances` is the map that tracks the balance of each address, in this
// contract when the balance changes the block number that the change
// occurred is also included in the map
mapping (address => Checkpoint[]) balances;
// `allowed` tracks any extra transfer rights as in all ERC20 tokens
mapping (address => mapping (address => uint256)) allowed;
// Tracks the history of the `totalSupply` of the token
Checkpoint[] totalSupplyHistory;
// Flag that determines if the token is transferable or not.
bool public transfersEnabled;
// The factory used to create new clone tokens
MiniMeTokenFactory public tokenFactory;
////////////////
// Constructor
////////////////
/// @notice Constructor to create a MiniMeToken
/// @param _tokenFactory The address of the MiniMeTokenFactory contract that
/// will create the Clone token contracts, the token factory needs to be
/// deployed first
/// @param _parentToken Address of the parent token, set to 0x0 if it is a
/// new token
/// @param _parentSnapShotBlock Block of the parent token that will
/// determine the initial distribution of the clone token, set to 0 if it
/// is a new token
/// @param _tokenName Name of the new token
/// @param _decimalUnits Number of decimals of the new token
/// @param _tokenSymbol Token Symbol for the new token
/// @param _transfersEnabled If true, tokens will be able to be transferred
function MiniMeToken(
address _tokenFactory,
address _parentToken,
uint _parentSnapShotBlock,
string _tokenName,
uint8 _decimalUnits,
string _tokenSymbol,
bool _transfersEnabled
) public {
tokenFactory = MiniMeTokenFactory(_tokenFactory);
name = _tokenName; // Set the name
decimals = _decimalUnits; // Set the decimals
symbol = _tokenSymbol; // Set the symbol
parentToken = MiniMeToken(_parentToken);
parentSnapShotBlock = _parentSnapShotBlock;
transfersEnabled = _transfersEnabled;
creationBlock = block.number;
}
///////////////////
// ERC20 Methods
///////////////////
/// @notice Send `_amount` tokens to `_to` from `msg.sender`
/// @param _to The address of the recipient
/// @param _amount The amount of tokens to be transferred
/// @return Whether the transfer was successful or not
function transfer(address _to, uint256 _amount) public returns (bool success) {
require(transfersEnabled);
return doTransfer(msg.sender, _to, _amount);
}
/// @notice Send `_amount` tokens to `_to` from `_from` on the condition it
/// is approved by `_from`
/// @param _from The address holding the tokens being transferred
/// @param _to The address of the recipient
/// @param _amount The amount of tokens to be transferred
/// @return True if the transfer was successful
function transferFrom(address _from, address _to, uint256 _amount
) public returns (bool success) {
// The controller of this contract can move tokens around at will,
// this is important to recognize! Confirm that you trust the
// controller of this contract, which in most situations should be
// another open source smart contract or 0x0
if (msg.sender != controller) {
require(transfersEnabled);
// The standard ERC 20 transferFrom functionality
if (allowed[_from][msg.sender] < _amount) return false;
allowed[_from][msg.sender] -= _amount;
}
return doTransfer(_from, _to, _amount);
}
/// @dev This is the actual transfer function in the token contract, it can
/// only be called by other functions in this contract.
/// @param _from The address holding the tokens being transferred
/// @param _to The address of the recipient
/// @param _amount The amount of tokens to be transferred
/// @return True if the transfer was successful
function doTransfer(address _from, address _to, uint _amount
) internal returns(bool) {
if (_amount == 0) {
return true;
}
require(parentSnapShotBlock < block.number);
// Do not allow transfer to 0x0 or the token contract itself
require((_to != 0) && (_to != address(this)));
// If the amount being transfered is more than the balance of the
// account the transfer returns false
var previousBalanceFrom = balanceOfAt(_from, block.number);
if (previousBalanceFrom < _amount) {
return false;
}
// First update the balance array with the new value for the address
// sending the tokens
updateValueAtNow(balances[_from], previousBalanceFrom - _amount);
// Then update the balance array with the new value for the address
// receiving the tokens
var previousBalanceTo = balanceOfAt(_to, block.number);
require(previousBalanceTo + _amount >= previousBalanceTo); // Check for overflow
updateValueAtNow(balances[_to], previousBalanceTo + _amount);
// An event to make the transfer easy to find on the blockchain
Transfer(_from, _to, _amount);
return true;
}
/// @param _owner The address that's balance is being requested
/// @return The balance of `_owner` at the current block
function balanceOf(address _owner) public constant returns (uint256 balance) {
return balanceOfAt(_owner, block.number);
}
/// @notice `msg.sender` approves `_spender` to spend `_amount` tokens on
/// its behalf. This is a modified version of the ERC20 approve function
/// to be a little bit safer
/// @param _spender The address of the account able to transfer the tokens
/// @param _amount The amount of tokens to be approved for transfer
/// @return True if the approval was successful
function approve(address _spender, uint256 _amount) public returns (bool success) {
require(transfersEnabled);
// To change the approve amount you first have to reduce the addresses`
// allowance to zero by calling `approve(_spender,0)` if it is not
// already 0 to mitigate the race condition described here:
// https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729
require((_amount == 0) || (allowed[msg.sender][_spender] == 0));
allowed[msg.sender][_spender] = _amount;
Approval(msg.sender, _spender, _amount);
return true;
}
/// @dev This function makes it easy to read the `allowed[]` map
/// @param _owner The address of the account that owns the token
/// @param _spender The address of the account able to transfer the tokens
/// @return Amount of remaining tokens of _owner that _spender is allowed
/// to spend
function allowance(address _owner, address _spender
) public constant returns (uint256 remaining) {
return allowed[_owner][_spender];
}
/// @notice `msg.sender` approves `_spender` to send `_amount` tokens on
/// its behalf, and then a function is triggered in the contract that is
/// being approved, `_spender`. This allows users to use their tokens to
/// interact with contracts in one function call instead of two
/// @param _spender The address of the contract able to transfer the tokens
/// @param _amount The amount of tokens to be approved for transfer
/// @return True if the function call was successful
function approveAndCall(address _spender, uint256 _amount, bytes _extraData
) public returns (bool success) {
require(approve(_spender, _amount));
ApproveAndCallFallBack(_spender).receiveApproval(
msg.sender,
_amount,
this,
_extraData
);
return true;
}
/// @dev This function makes it easy to get the total number of tokens
/// @return The total number of tokens
function totalSupply() public constant returns (uint) {
return totalSupplyAt(block.number);
}
////////////////
// Query balance and totalSupply in History
////////////////
/// @dev Queries the balance of `_owner` at a specific `_blockNumber`
/// @param _owner The address from which the balance will be retrieved
/// @param _blockNumber The block number when the balance is queried
/// @return The balance at `_blockNumber`
function balanceOfAt(address _owner, uint _blockNumber) public constant
returns (uint) {
// These next few lines are used when the balance of the token is
// requested before a check point was ever created for this token, it
// requires that the `parentToken.balanceOfAt` be queried at the
// genesis block for that token as this contains initial balance of
// this token
if ((balances[_owner].length == 0)
|| (balances[_owner][0].fromBlock > _blockNumber)) {
if (address(parentToken) != 0) {
return parentToken.balanceOfAt(_owner, min(_blockNumber, parentSnapShotBlock));
} else {
// Has no parent
return 0;
}
// This will return the expected balance during normal situations
} else {
return getValueAt(balances[_owner], _blockNumber);
}
}
/// @notice Total amount of tokens at a specific `_blockNumber`.
/// @param _blockNumber The block number when the totalSupply is queried
/// @return The total amount of tokens at `_blockNumber`
function totalSupplyAt(uint _blockNumber) public constant returns(uint) {
// These next few lines are used when the totalSupply of the token is
// requested before a check point was ever created for this token, it
// requires that the `parentToken.totalSupplyAt` be queried at the
// genesis block for this token as that contains totalSupply of this
// token at this block number.
if ((totalSupplyHistory.length == 0)
|| (totalSupplyHistory[0].fromBlock > _blockNumber)) {
if (address(parentToken) != 0) {
return parentToken.totalSupplyAt(min(_blockNumber, parentSnapShotBlock));
} else {
return 0;
}
// This will return the expected totalSupply during normal situations
} else {
return getValueAt(totalSupplyHistory, _blockNumber);
}
}
////////////////
// Clone Token Method
////////////////
/// @notice Creates a new clone token with the initial distribution being
/// this token at `_snapshotBlock`
/// @param _cloneTokenName Name of the clone token
/// @param _cloneDecimalUnits Number of decimals of the smallest unit
/// @param _cloneTokenSymbol Symbol of the clone token
/// @param _snapshotBlock Block when the distribution of the parent token is
/// copied to set the initial distribution of the new clone token;
/// if the block is zero than the actual block, the current block is used
/// @param _transfersEnabled True if transfers are allowed in the clone
/// @return The address of the new MiniMeToken Contract
function createCloneToken(
string _cloneTokenName,
uint8 _cloneDecimalUnits,
string _cloneTokenSymbol,
uint _snapshotBlock,
bool _transfersEnabled
) public returns(address) {
if (_snapshotBlock == 0) _snapshotBlock = block.number;
MiniMeToken cloneToken = tokenFactory.createCloneToken(
this,
_snapshotBlock,
_cloneTokenName,
_cloneDecimalUnits,
_cloneTokenSymbol,
_transfersEnabled
);
cloneToken.changeController(msg.sender);
// An event to make the token easy to find on the blockchain
NewCloneToken(address(cloneToken), _snapshotBlock);
return address(cloneToken);
}
////////////////
// Generate and destroy tokens
////////////////
/// @notice Generates `_amount` tokens that are assigned to `_owner`
/// @param _owner The address that will be assigned the new tokens
/// @param _amount The quantity of tokens generated
/// @return True if the tokens are generated correctly
function generateTokens(address _owner, uint _amount
) public onlyController returns (bool) {
uint curTotalSupply = totalSupply();
require(curTotalSupply + _amount >= curTotalSupply); // Check for overflow
uint previousBalanceTo = balanceOf(_owner);
require(previousBalanceTo + _amount >= previousBalanceTo); // Check for overflow
updateValueAtNow(totalSupplyHistory, curTotalSupply + _amount);
updateValueAtNow(balances[_owner], previousBalanceTo + _amount);
Transfer(0, _owner, _amount);
return true;
}
/// @notice Burns `_amount` tokens from `_owner`
/// @param _owner The address that will lose the tokens
/// @param _amount The quantity of tokens to burn
/// @return True if the tokens are burned correctly
function destroyTokens(address _owner, uint _amount
) onlyController public returns (bool) {
uint curTotalSupply = totalSupply();
require(curTotalSupply >= _amount);
uint previousBalanceFrom = balanceOf(_owner);
require(previousBalanceFrom >= _amount);
updateValueAtNow(totalSupplyHistory, curTotalSupply - _amount);
updateValueAtNow(balances[_owner], previousBalanceFrom - _amount);
Transfer(_owner, 0, _amount);
return true;
}
////////////////
// Enable tokens transfers
////////////////
/// @notice Enables token holders to transfer their tokens freely if true
/// @param _transfersEnabled True if transfers are allowed in the clone
function enableTransfers(bool _transfersEnabled) public onlyController {
transfersEnabled = _transfersEnabled;
}
////////////////
// Internal helper functions to query and set a value in a snapshot array
////////////////
/// @dev `getValueAt` retrieves the number of tokens at a given block number
/// @param checkpoints The history of values being queried
/// @param _block The block number to retrieve the value at
/// @return The number of tokens being queried
function getValueAt(Checkpoint[] storage checkpoints, uint _block
) constant internal returns (uint) {
if (checkpoints.length == 0) return 0;
// Shortcut for the actual value
if (_block >= checkpoints[checkpoints.length-1].fromBlock)
return checkpoints[checkpoints.length-1].value;
if (_block < checkpoints[0].fromBlock) return 0;
// Binary search of the value in the array
uint min = 0;
uint max = checkpoints.length-1;
while (max > min) {
uint mid = (max + min + 1)/ 2;
if (checkpoints[mid].fromBlock<=_block) {
min = mid;
} else {
max = mid-1;
}
}
return checkpoints[min].value;
}
/// @dev `updateValueAtNow` used to update the `balances` map and the
/// `totalSupplyHistory`
/// @param checkpoints The history of data being updated
/// @param _value The new number of tokens
function updateValueAtNow(Checkpoint[] storage checkpoints, uint _value
) internal {
if ((checkpoints.length == 0)
|| (checkpoints[checkpoints.length -1].fromBlock < block.number)) {
Checkpoint storage newCheckPoint = checkpoints[ checkpoints.length++ ];
newCheckPoint.fromBlock = uint128(block.number);
newCheckPoint.value = uint128(_value);
} else {
Checkpoint storage oldCheckPoint = checkpoints[checkpoints.length-1];
oldCheckPoint.value = uint128(_value);
}
}
/// @dev Internal function to determine if an address is a contract
/// @param _addr The address being queried
/// @return True if `_addr` is a contract
function isContract(address _addr) constant internal returns(bool) {
uint size;
if (_addr == 0) return false;
assembly {
size := extcodesize(_addr)
}
return size>0;
}
/// @dev Helper function to return a min betwen the two uints
/// PURE function
function min(uint a, uint b) internal constant returns (uint) {
return a < b ? a : b;
}
/// @notice The fallback function: If the contract's controller has not been
/// set to 0, then the `proxyPayment` method is called which relays the
/// ether and creates tokens as described in the token controller contract
function () public payable {
}
//////////
// Safety Methods
//////////
/// @notice This method can be used by the controller to extract mistakenly
/// sent tokens to this contract.
/// @param _token The address of the token contract that you want to recover
/// set to 0 in case you want to extract ether.
function claimTokens(address _token) public onlyController {
if (_token == 0x0) {
controller.transfer(this.balance);
return;
}
MiniMeToken token = MiniMeToken(_token);
uint balance = token.balanceOf(this);
token.transfer(controller, balance);
ClaimedTokens(_token, controller, balance);
}
////////////////
// Events
////////////////
event ClaimedTokens(address indexed _token, address indexed _controller, uint _amount);
event Transfer(address indexed _from, address indexed _to, uint256 _amount);
event NewCloneToken(address indexed _cloneToken, uint _snapshotBlock);
event Approval(
address indexed _owner,
address indexed _spender,
uint256 _amount
);
}
////////////////
// MiniMeTokenFactory
////////////////
/// @dev This contract is used to generate clone contracts from a contract.
/// In solidity this is the way to create a contract from a contract of the
/// same class
contract MiniMeTokenFactory {
/// @notice Update the DApp by creating a new token with new functionalities
/// the msg.sender becomes the controller of this clone token
/// @param _parentToken Address of the token being cloned
/// @param _snapshotBlock Block of the parent token that will
/// determine the initial distribution of the clone token
/// @param _tokenName Name of the new token
/// @param _decimalUnits Number of decimals of the new token
/// @param _tokenSymbol Token Symbol for the new token
/// @param _transfersEnabled If true, tokens will be able to be transferred
/// @return The address of the new token contract
function createCloneToken(
address _parentToken,
uint _snapshotBlock,
string _tokenName,
uint8 _decimalUnits,
string _tokenSymbol,
bool _transfersEnabled
) public returns (MiniMeToken) {
MiniMeToken newToken = new MiniMeToken(
this,
_parentToken,
_snapshotBlock,
_tokenName,
_decimalUnits,
_tokenSymbol,
_transfersEnabled
);
newToken.changeController(msg.sender);
return newToken;
}
}
contract StakeTreeWithTokenization {
using SafeMath for uint256;
uint public version = 2;
struct Funder {
bool exists;
uint balance;
uint withdrawalEntry;
uint contribution;
uint contributionClaimed;
}
mapping(address => Funder) public funders;
bool public live = true; // For sunsetting contract
uint public totalCurrentFunders = 0; // Keeps track of total funders
uint public withdrawalCounter = 0; // Keeps track of how many withdrawals have taken place
uint public sunsetWithdrawDate;
MiniMeToken public tokenContract;
MiniMeTokenFactory public tokenFactory;
bool public tokenized = false;
bool public canClaimTokens = false;
address public beneficiary; // Address for beneficiary
uint public sunsetWithdrawalPeriod; // How long it takes for beneficiary to swipe contract when put into sunset mode
uint public withdrawalPeriod; // How long the beneficiary has to wait withdraw
uint public minimumFundingAmount; // Setting used for setting minimum amounts to fund contract with
uint public lastWithdrawal; // Last withdrawal time
uint public nextWithdrawal; // Next withdrawal time
uint public contractStartTime; // For accounting purposes
event Payment(address indexed funder, uint amount);
event Refund(address indexed funder, uint amount);
event Withdrawal(uint amount);
event TokensClaimed(address indexed funder, uint amount);
event Sunset(bool hasSunset);
function StakeTreeWithTokenization(
address beneficiaryAddress,
uint withdrawalPeriodInit,
uint withdrawalStart,
uint sunsetWithdrawPeriodInit,
uint minimumFundingAmountInit) {
beneficiary = beneficiaryAddress;
withdrawalPeriod = withdrawalPeriodInit;
sunsetWithdrawalPeriod = sunsetWithdrawPeriodInit;
lastWithdrawal = withdrawalStart;
nextWithdrawal = lastWithdrawal + withdrawalPeriod;
minimumFundingAmount = minimumFundingAmountInit;
contractStartTime = now;
}
// Modifiers
modifier onlyByBeneficiary() {
require(msg.sender == beneficiary);
_;
}
modifier onlyWhenTokenized() {
require(isTokenized());
_;
}
modifier onlyByFunder() {
require(isFunder(msg.sender));
_;
}
modifier onlyAfterNextWithdrawalDate() {
require(now >= nextWithdrawal);
_;
}
modifier onlyWhenLive() {
require(live);
_;
}
modifier onlyWhenSunset() {
require(!live);
_;
}
/*
* External accounts can pay directly to contract to fund it.
*/
function () payable {
fund();
}
/*
* Additional api for contracts to use as well
* Can only happen when live and over a minimum amount set by the beneficiary
*/
function fund() public payable onlyWhenLive {
require(msg.value >= minimumFundingAmount);
// Only increase total funders when we have a new funder
if(!isFunder(msg.sender)) {
totalCurrentFunders = totalCurrentFunders.add(1); // Increase total funder count
funders[msg.sender] = Funder({
exists: true,
balance: msg.value,
withdrawalEntry: withdrawalCounter, // Set the withdrawal counter. Ie at which withdrawal the funder "entered" the patronage contract
contribution: 0,
contributionClaimed: 0
});
}
else {
consolidateFunder(msg.sender, msg.value);
}
Payment(msg.sender, msg.value);
}
// Pure functions
/*
* This function calculates how much the beneficiary can withdraw.
* Due to no floating points in Solidity, we will lose some fidelity
* if there's wei on the last digit. The beneficiary loses a neglibible amount
* to withdraw but this benefits the beneficiary again on later withdrawals.
* We multiply by 10 (which corresponds to the 10%)
* then divide by 100 to get the actual part.
*/
function calculateWithdrawalAmount(uint startAmount) public returns (uint){
return startAmount.mul(10).div(100); // 10%
}
/*
* This function calculates the refund amount for the funder.
* Due to no floating points in Solidity, we will lose some fidelity.
* The funder loses a neglibible amount to refund.
* The left over wei gets pooled to the fund.
*/
function calculateRefundAmount(uint amount, uint withdrawalTimes) public returns (uint) {
for(uint i=0; i<withdrawalTimes; i++){
amount = amount.mul(9).div(10);
}
return amount;
}
// Getter functions
/*
* To calculate the refund amount we look at how many times the beneficiary
* has withdrawn since the funder added their funds.
* We use that deduct 10% for each withdrawal.
*/
function getRefundAmountForFunder(address addr) public constant returns (uint) {
// Only calculate on-the-fly if funder has not been updated
if(shouldUpdateFunder(addr)) {
uint amount = funders[addr].balance;
uint withdrawalTimes = getHowManyWithdrawalsForFunder(addr);
return calculateRefundAmount(amount, withdrawalTimes);
}
else {
return funders[addr].balance;
}
}
function getFunderContribution(address funder) public constant returns (uint) {
// Only calculate on-the-fly if funder has not been updated
if(shouldUpdateFunder(funder)) {
uint oldBalance = funders[funder].balance;
uint newBalance = getRefundAmountForFunder(funder);
uint contribution = oldBalance.sub(newBalance);
return funders[funder].contribution.add(contribution);
}
else {
return funders[funder].contribution;
}
}
function getBeneficiary() public constant returns (address) {
return beneficiary;
}
function getCurrentTotalFunders() public constant returns (uint) {
return totalCurrentFunders;
}
function getWithdrawalCounter() public constant returns (uint) {
return withdrawalCounter;
}
function getWithdrawalEntryForFunder(address addr) public constant returns (uint) {
return funders[addr].withdrawalEntry;
}
function getContractBalance() public constant returns (uint256 balance) {
balance = this.balance;
}
function getFunderBalance(address funder) public constant returns (uint256) {
return getRefundAmountForFunder(funder);
}
function getFunderContributionClaimed(address addr) public constant returns (uint) {
return funders[addr].contributionClaimed;
}
function isFunder(address addr) public constant returns (bool) {
return funders[addr].exists;
}
function isTokenized() public constant returns (bool) {
return tokenized;
}
function shouldUpdateFunder(address funder) public constant returns (bool) {
return getWithdrawalEntryForFunder(funder) < withdrawalCounter;
}
function getHowManyWithdrawalsForFunder(address addr) private constant returns (uint) {
return withdrawalCounter.sub(getWithdrawalEntryForFunder(addr));
}
// State changing functions
function setMinimumFundingAmount(uint amount) external onlyByBeneficiary {
require(amount > 0);
minimumFundingAmount = amount;
}
function withdraw() external onlyByBeneficiary onlyAfterNextWithdrawalDate onlyWhenLive {
// Check
uint amount = calculateWithdrawalAmount(this.balance);
// Effects
withdrawalCounter = withdrawalCounter.add(1);
lastWithdrawal = now; // For tracking purposes
nextWithdrawal = nextWithdrawal + withdrawalPeriod; // Fixed period increase
// Interaction
beneficiary.transfer(amount);
Withdrawal(amount);
}
// Refunding by funder
// Only funders can refund their own funding
// Can only be sent back to the same address it was funded with
// We also remove the funder if they succesfully exit with their funds
function refund() external onlyByFunder {
// Check
uint walletBalance = this.balance;
uint amount = getRefundAmountForFunder(msg.sender);
require(amount > 0);
// Effects
removeFunder();
// Interaction
msg.sender.transfer(amount);
Refund(msg.sender, amount);
// Make sure this worked as intended
assert(this.balance == walletBalance-amount);
}
// Used when the funder wants to remove themselves as a funder
// without refunding. Their eth stays in the pool
function removeFunder() public onlyByFunder {
delete funders[msg.sender];
totalCurrentFunders = totalCurrentFunders.sub(1);
}
/*
* This is a bookkeeping function which updates the state for the funder
* when top up their funds.
*/
function consolidateFunder(address funder, uint newPayment) private {
// Update contribution
funders[funder].contribution = getFunderContribution(funder);
// Update balance
funders[funder].balance = getRefundAmountForFunder(funder).add(newPayment);
// Update withdrawal entry
funders[funder].withdrawalEntry = withdrawalCounter;
}
function addTokenization(string tokenName, string tokenSymbol, uint8 tokenDecimals ) external onlyByBeneficiary {
require(!isTokenized());
tokenFactory = new MiniMeTokenFactory();
tokenContract = tokenFactory.createCloneToken(0x0, 0, tokenName, tokenDecimals, tokenSymbol, true);
tokenized = true;
canClaimTokens = true;
}
function claimTokens() external onlyByFunder onlyWhenTokenized {
require(canClaimTokens);
uint contributionAmount = getFunderContribution(msg.sender);
uint contributionClaimedAmount = getFunderContributionClaimed(msg.sender);
// Only claim tokens if they have some left to claim
uint claimAmount = contributionAmount.sub(contributionClaimedAmount);
require(claimAmount > 0);
// Claim tokens
funders[msg.sender].contributionClaimed = contributionAmount;
tokenContract.generateTokens(msg.sender, claimAmount);
TokensClaimed(msg.sender, claimAmount);
}
/*
* The beneficiary can stop/enable funders from claiming more tokens.
* This opens up opportunities for tokenizing only happening for a set periods.
*/
function enableTokenClaiming(bool _enabled) external onlyWhenTokenized onlyByBeneficiary {
canClaimTokens = _enabled;
}
/* --- Sunsetting --- */
/*
* The beneficiary can decide to stop using this contract.
* They use this sunset function to put it into sunset mode.
* The beneficiary can then swipe rest of the funds after a set time
* if funders have not withdrawn their funds.
*/
function sunset() external onlyByBeneficiary onlyWhenLive {
sunsetWithdrawDate = now.add(sunsetWithdrawalPeriod);
live = false;
Sunset(true);
}
function swipe(address recipient) external onlyWhenSunset onlyByBeneficiary {
require(now >= sunsetWithdrawDate);
recipient.transfer(this.balance);
}
/* --- Token Contract Forwarding Controller Functions --- */
/*
* Allows beneficiary to call two additional functions on the token contract:
* claimTokens
* enabledTransfers
*
*/
function tokenContractClaimTokens(address _token) onlyByBeneficiary onlyWhenTokenized {
tokenContract.claimTokens(_token);
}
function tokenContractEnableTransfers(bool _transfersEnabled) onlyByBeneficiary onlyWhenTokenized {
tokenContract.enableTransfers(_transfersEnabled);
}
}
|
Used when the funder wants to remove themselves as a funder without refunding. Their eth stays in the pool
|
function removeFunder() public onlyByFunder {
delete funders[msg.sender];
totalCurrentFunders = totalCurrentFunders.sub(1);
}
| 7,211,578 |
pragma solidity ^0.4.11;
import "./DAOLib.sol";
import "./CrowdsaleDAOFields.sol";
import "../Common.sol";
import "./Owned.sol";
import "./DAOProxy.sol";
contract CrowdsaleDAO is CrowdsaleDAOFields, Owned {
address public stateModule;
address public paymentModule;
address public votingDecisionModule;
address public crowdsaleModule;
function CrowdsaleDAO(string _name, string _description, address _serviceContractAddress, address _votingFactoryContractAddress)
Owned(msg.sender) {
(name, description, serviceContract, votingFactory) = (_name, _description, _serviceContractAddress, VotingFactoryInterface(_votingFactoryContractAddress));
}
/*
* @dev Receives ether and forwards to the crowdsale module via a delegatecall with commission flag equal to false
*/
function() payable {
DAOProxy.delegatedHandlePayment(crowdsaleModule, msg.sender, false);
}
/*
* @dev Receives ether from commission contract and forwards to the crowdsale module
* via a delegatecall with commission flag equal to true
* @param _sender Address which sent ether to commission contract
*/
function handleCommissionPayment(address _sender) payable {
DAOProxy.delegatedHandlePayment(crowdsaleModule, _sender, true);
}
/*
* @dev Receives info about address which sent DXC tokens to current contract and about amount of sent tokens from
* DXC token contract and then forwards this data to the crowdsale module
* @param _from Address which sent DXC tokens
* @param _amount Amount of tokens which were sent
*/
function handleDXCPayment(address _from, uint _amount) {
DAOProxy.delegatedHandleDXCPayment(crowdsaleModule, _from, _amount);
}
/*
* @dev Receives decision from withdrawal voting and forwards it to the voting decisions module
* @param _address Address for withdrawal
* @param _withdrawalSum Amount of ether/DXC tokens which must be sent to withdrawal address
* @param _dxc boolean indicating whether withdrawal should be made through DXC tokens or not
*/
function withdrawal(address _address, uint _withdrawalSum, bool _dxc) external {
DAOProxy.delegatedWithdrawal(votingDecisionModule, _address, _withdrawalSum, _dxc);
}
/*
* @dev Receives decision from refund voting and forwards it to the voting decisions module
*/
function makeRefundableByVotingDecision() external {
DAOProxy.delegatedMakeRefundableByVotingDecision(votingDecisionModule);
}
/*
* @dev Called by voting contract to hold tokens of voted address.
* It is needed to prevent multiple votes with same tokens
* @param _address Voted address
* @param _duration Amount of time left for voting to be finished
*/
function holdTokens(address _address, uint _duration) external {
DAOProxy.delegatedHoldTokens(votingDecisionModule, _address, _duration);
}
function setStateModule(address _stateModule) external canSetAddress(stateModule) {
stateModule = _stateModule;
}
function setPaymentModule(address _paymentModule) external canSetAddress(paymentModule) {
paymentModule = _paymentModule;
}
function setVotingDecisionModule(address _votingDecisionModule) external canSetAddress(votingDecisionModule) {
votingDecisionModule = _votingDecisionModule;
}
function setCrowdsaleModule(address _crowdsaleModule) external canSetAddress(crowdsaleModule) {
crowdsaleModule = _crowdsaleModule;
}
function setVotingFactoryAddress(address _votingFactory) external canSetAddress(votingFactory) {
votingFactory = VotingFactoryInterface(_votingFactory);
}
/*
* @dev Checks if provided address has tokens of current DAO
* @param _participantAddress Address of potential participant
* @return boolean indicating if the address has at least one token
*/
function isParticipant(address _participantAddress) external constant returns (bool) {
return token.balanceOf(_participantAddress) > 0;
}
/*
* @dev Function which is used to set address of token which will be distributed by DAO during the crowdsale and
* address of DXC token contract to use it for handling payment operations with DXC. Delegates call to state module
* @param _tokenAddress Address of token which will be distributed during the crowdsale
* @param _DXC Address of DXC contract
*/
function initState(address _tokenAddress, address _DXC) public {
DAOProxy.delegatedInitState(stateModule, _tokenAddress, _DXC);
}
/*
* @dev Delegates parameters which describe conditions of crowdsale to the crowdsale module.
* @param _softCap The minimal amount of funds that must be collected by DAO for crowdsale to be considered successful
* @param _hardCap The maximal amount of funds that can be raised during the crowdsale
* @param _etherRate Amount of tokens that will be minted per one ether
* @param _DXCRate Amount of tokens that will be minted per one DXC
* @param _startTime Unix timestamp that indicates the moment when crowdsale will start
* @param _endTime Unix timestamp that indicates the moment when crowdsale will end
* @param _dxcPayments Boolean indicating whether it is possible to invest via DXC token or not
*/
function initCrowdsaleParameters(uint _softCap, uint _hardCap, uint _etherRate, uint _DXCRate, uint _startTime, uint _endTime, bool _dxcPayments, uint _lockup) public {
DAOProxy.delegatedInitCrowdsaleParameters(crowdsaleModule, _softCap, _hardCap, _etherRate, _DXCRate, _startTime, _endTime, _dxcPayments, _lockup);
}
/*
* @dev Delegates request of creating "regular" voting and saves the address of created voting contract to votings list
* @param _name Name for voting
* @param _description Description for voting that will be created
* @param _duration Time in seconds from current moment until voting will be finished
* @param _options List of options
*/
function addRegular(string _name, string _description, uint _duration, bytes32[] _options) public {
votings[DAOLib.delegatedCreateRegular(votingFactory, _name, _description, _duration, _options, this)] = true;
}
/*
* @dev Delegates request of creating "withdrawal" voting and saves the address of created voting contract to votings list
* @param _name Name for voting
* @param _description Description for voting that will be created
* @param _duration Time in seconds from current moment until voting will be finished
* @param _sum Amount of funds that is supposed to be withdrawn
* @param _withdrawalWallet Address for withdrawal
* @param _dxc Boolean indicating whether withdrawal must be in DXC tokens or in ether
*/
function addWithdrawal(string _name, string _description, uint _duration, uint _sum, address _withdrawalWallet, bool _dxc) public {
votings[DAOLib.delegatedCreateWithdrawal(votingFactory, _name, _description, _duration, _sum, _withdrawalWallet, _dxc, this)] = true;
}
/*
* @dev Delegates request of creating "refund" voting and saves the address of created voting contract to votings list
* @param _name Name for voting
* @param _description Description for voting that will be created
* @param _duration Time in seconds from current moment until voting will be finished
*/
function addRefund(string _name, string _description, uint _duration) public {
votings[DAOLib.delegatedCreateRefund(votingFactory, _name, _description, _duration, this)] = true;
}
/*
* @dev Delegates request of creating "module" voting and saves the address of created voting contract to votings list
* @param _name Name for voting
* @param _description Description for voting that will be created
* @param _duration Time in seconds from current moment until voting will be finished
* @param _module Number of module which must be replaced
* @param _newAddress Address of new module
*/
function addModule(string _name, string _description, uint _duration, uint _module, address _newAddress) public {
votings[DAOLib.delegatedCreateModule(votingFactory, _name, _description, _duration, _module, _newAddress, this)] = true;
}
/*
* @dev Delegates request for going into refundable state to voting decisions module
*/
function makeRefundableByUser() public {
DAOProxy.delegatedMakeRefundableByUser(votingDecisionModule);
}
/*
* @dev Delegates request for refund to payment module
*/
function refund() public {
DAOProxy.delegatedRefund(paymentModule);
}
/*
* @dev Delegates request for refund of soft cap to payment module
*/
function refundSoftCap() public {
DAOProxy.delegatedRefundSoftCap(paymentModule);
}
/*
* @dev Delegates request for finish of crowdsale to crowdsale module
*/
function finish() public {
DAOProxy.delegatedFinish(crowdsaleModule);
}
/*
* @dev Sets team addresses and bonuses for crowdsale
* @param _team The addresses that will be defined as team members
* @param _tokenPercents Array of bonuses in percents which will go te every member in case of successful crowdsale
* @param _bonusPeriods Array of timestamps which show when tokens will be minted with higher rate
* @param _bonusEtherRates Array of ether rates for every bonus period
* @param _bonusDXCRates Array of DXC rates for every bonus period
* @param _teamHold Array of timestamps which show the hold duration of tokens for every team member
* @param service Array of booleans which show whether member is a service address or not
*/
function initBonuses(address[] _team, uint[] _tokenPercents, uint[] _bonusPeriods, uint[] _bonusEtherRates, uint[] _bonusDXCRates, uint[] _teamHold, bool[] _service) public onlyOwner(msg.sender) {
require(
_team.length == _tokenPercents.length &&
_team.length == _teamHold.length &&
_team.length == _service.length &&
_bonusPeriods.length == _bonusEtherRates.length &&
(_bonusDXCRates.length == 0 || _bonusPeriods.length == _bonusDXCRates.length) &&
canInitBonuses &&
(block.timestamp < startTime || canInitCrowdsaleParameters)
);
team = _team;
teamHold = _teamHold;
teamBonusesArr = _tokenPercents;
teamServiceMember = _service;
for(uint i = 0; i < _team.length; i++) {
teamMap[_team[i]] = true;
teamBonuses[_team[i]] = _tokenPercents[i];
}
bonusPeriods = _bonusPeriods;
bonusEtherRates = _bonusEtherRates;
bonusDXCRates = _bonusDXCRates;
canInitBonuses = false;
}
/*
* @dev Sets addresses which can be used to get funds via withdrawal votings
* @param _addresses Array of addresses which will be used for withdrawals
*/
function setWhiteList(address[] _addresses) public onlyOwner(msg.sender) {
require(canSetWhiteList);
whiteListArr = _addresses;
for(uint i = 0; i < _addresses.length; i++) {
whiteList[_addresses[i]] = true;
}
canSetWhiteList = false;
}
/*
Modifiers
*/
modifier canSetAddress(address module) {
require(votings[msg.sender] || (module == 0x0 && msg.sender == owner));
_;
}
}
|
Delegates request of creating "module" voting and saves the address of created voting contract to votings list _name Name for voting _description Description for voting that will be created _duration Time in seconds from current moment until voting will be finished _module Number of module which must be replaced _newAddress Address of new module/
|
function addModule(string _name, string _description, uint _duration, uint _module, address _newAddress) public {
votings[DAOLib.delegatedCreateModule(votingFactory, _name, _description, _duration, _module, _newAddress, this)] = true;
}
| 946,558 |
./full_match/1/0x1722C9882A64f5D901C5A905caBcE5012CF06Ed5/sources/browser/appletoken.sol
|
Determine the prior number of votes for an account as of a block number Block number must be a finalized block or else this function will revert to prevent misinformation. account The address of the account to check blockNumber The block number to get the vote balance at return The number of votes the account had as of the given block/ First check most recent balance Next check implicit zero balance
|
function getPriorVotes(address account, uint blockNumber)
external
view
returns (uint256)
{
require(blockNumber < block.number, "APPLE::getPriorVotes: not yet determined");
uint32 nCheckpoints = numCheckpoints[account];
if (nCheckpoints == 0) {
return 0;
}
if (checkpoints[account][nCheckpoints - 1].fromBlock <= blockNumber) {
return checkpoints[account][nCheckpoints - 1].votes;
}
if (checkpoints[account][0].fromBlock > blockNumber) {
return 0;
}
uint32 lower = 0;
uint32 upper = nCheckpoints - 1;
while (upper > lower) {
Checkpoint memory cp = checkpoints[account][center];
if (cp.fromBlock == blockNumber) {
return cp.votes;
lower = center;
upper = center - 1;
}
}
return checkpoints[account][lower].votes;
}
| 3,132,570 |
// SPDX-License-Identifier: MIT
pragma solidity >=0.4.25 <0.8.0;
import { IAlphaWhiteList } from "./IAlphaWhiteList.sol";
import { Ownable } from "@openzeppelin/contracts/access/Ownable.sol";
import { SafeMath } from "@openzeppelin/contracts/math/SafeMath.sol";
import { IFujiERC1155 } from "./FujiERC1155/IFujiERC1155.sol";
contract AlphaWhitelist is IAlphaWhiteList, Ownable {
using SafeMath for uint256;
uint256 public ethCapValue;
uint256 public limitUsers;
uint256 public counter;
// Log Limit Users Changed
event UserLimitUpdated(uint256 _newUserLimit);
// Log Cap Value Changed
event CapValueUpdated(uint256 _newCapValue);
constructor(uint256 _limitUsers, uint256 _capValue) public {
limitUsers = _limitUsers;
ethCapValue = _capValue;
}
/**
* @dev Does Whitelist Routine to check if:
* - limit of users got reached
* - first deposit is less than ethCapValue
* - subsequent total deposits are less than 2*ethCapValue
* @param _usrAddr: Address of the User to check
* @return letgo a boolean that allows a function to continue in "require" context
*/
function whiteListRoutine(
address _usrAddr,
uint64 _assetID,
uint256 _amount,
address _erc1155
) external override returns (bool letgo) {
uint256 currentBalance = IFujiERC1155(_erc1155).balanceOf(_usrAddr, _assetID);
if (currentBalance == 0) {
counter = counter.add(1);
letgo = _amount <= ethCapValue && counter <= limitUsers;
} else {
letgo = currentBalance.add(_amount) <= ethCapValue.mul(2);
}
}
// Administrative Functions
/**
* @dev Modifies the limitUsers
* @param _newUserLimit: New User Limit number
*/
function updateLimitUser(uint256 _newUserLimit) public onlyOwner {
limitUsers = _newUserLimit;
emit UserLimitUpdated(_newUserLimit);
}
/**
* @dev Modifies the ethCapValue
* @param _newEthCapValue: New ethCapValue
*/
function updateCap(uint256 _newEthCapValue) public onlyOwner {
ethCapValue = _newEthCapValue;
emit CapValueUpdated(_newEthCapValue);
}
}
// SPDX-License-Identifier: MIT
pragma solidity >=0.6.12 <0.8.0;
interface IAlphaWhiteList {
function whiteListRoutine(
address _usrAddrs,
uint64 _assetId,
uint256 _amount,
address _erc1155
) external returns(bool);
}
// SPDX-License-Identifier: MIT
pragma solidity >=0.6.0 <0.8.0;
import "../utils/Context.sol";
/**
* @dev Contract module which provides a basic access control mechanism, where
* there is an account (an owner) that can be granted exclusive access to
* specific functions.
*
* By default, the owner account will be the one that deploys the contract. This
* can later be changed with {transferOwnership}.
*
* This module is used through inheritance. It will make available the modifier
* `onlyOwner`, which can be applied to your functions to restrict their use to
* the owner.
*/
abstract contract Ownable is Context {
address private _owner;
event OwnershipTransferred(address indexed previousOwner, address indexed newOwner);
/**
* @dev Initializes the contract setting the deployer as the initial owner.
*/
constructor () internal {
address msgSender = _msgSender();
_owner = msgSender;
emit OwnershipTransferred(address(0), msgSender);
}
/**
* @dev Returns the address of the current owner.
*/
function owner() public view virtual returns (address) {
return _owner;
}
/**
* @dev Throws if called by any account other than the owner.
*/
modifier onlyOwner() {
require(owner() == _msgSender(), "Ownable: caller is not the owner");
_;
}
/**
* @dev Leaves the contract without owner. It will not be possible to call
* `onlyOwner` functions anymore. Can only be called by the current owner.
*
* NOTE: Renouncing ownership will leave the contract without an owner,
* thereby removing any functionality that is only available to the owner.
*/
function renounceOwnership() public virtual onlyOwner {
emit OwnershipTransferred(_owner, address(0));
_owner = address(0);
}
/**
* @dev Transfers ownership of the contract to a new account (`newOwner`).
* Can only be called by the current owner.
*/
function transferOwnership(address newOwner) public virtual onlyOwner {
require(newOwner != address(0), "Ownable: new owner is the zero address");
emit OwnershipTransferred(_owner, newOwner);
_owner = newOwner;
}
}
// SPDX-License-Identifier: MIT
pragma solidity >=0.6.0 <0.8.0;
/**
* @dev Wrappers over Solidity's arithmetic operations with added overflow
* checks.
*
* Arithmetic operations in Solidity wrap on overflow. This can easily result
* in bugs, because programmers usually assume that an overflow raises an
* error, which is the standard behavior in high level programming languages.
* `SafeMath` restores this intuition by reverting the transaction when an
* operation overflows.
*
* Using this library instead of the unchecked operations eliminates an entire
* class of bugs, so it's recommended to use it always.
*/
library SafeMath {
/**
* @dev Returns the addition of two unsigned integers, with an overflow flag.
*
* _Available since v3.4._
*/
function tryAdd(uint256 a, uint256 b) internal pure returns (bool, uint256) {
uint256 c = a + b;
if (c < a) return (false, 0);
return (true, c);
}
/**
* @dev Returns the substraction of two unsigned integers, with an overflow flag.
*
* _Available since v3.4._
*/
function trySub(uint256 a, uint256 b) internal pure returns (bool, uint256) {
if (b > a) return (false, 0);
return (true, a - b);
}
/**
* @dev Returns the multiplication of two unsigned integers, with an overflow flag.
*
* _Available since v3.4._
*/
function tryMul(uint256 a, uint256 b) internal pure returns (bool, uint256) {
// Gas optimization: this is cheaper than requiring 'a' not being zero, but the
// benefit is lost if 'b' is also tested.
// See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522
if (a == 0) return (true, 0);
uint256 c = a * b;
if (c / a != b) return (false, 0);
return (true, c);
}
/**
* @dev Returns the division of two unsigned integers, with a division by zero flag.
*
* _Available since v3.4._
*/
function tryDiv(uint256 a, uint256 b) internal pure returns (bool, uint256) {
if (b == 0) return (false, 0);
return (true, a / b);
}
/**
* @dev Returns the remainder of dividing two unsigned integers, with a division by zero flag.
*
* _Available since v3.4._
*/
function tryMod(uint256 a, uint256 b) internal pure returns (bool, uint256) {
if (b == 0) return (false, 0);
return (true, a % b);
}
/**
* @dev Returns the addition of two unsigned integers, reverting on
* overflow.
*
* Counterpart to Solidity's `+` operator.
*
* Requirements:
*
* - Addition cannot overflow.
*/
function add(uint256 a, uint256 b) internal pure returns (uint256) {
uint256 c = a + b;
require(c >= a, "SafeMath: addition overflow");
return c;
}
/**
* @dev Returns the subtraction of two unsigned integers, reverting on
* overflow (when the result is negative).
*
* Counterpart to Solidity's `-` operator.
*
* Requirements:
*
* - Subtraction cannot overflow.
*/
function sub(uint256 a, uint256 b) internal pure returns (uint256) {
require(b <= a, "SafeMath: subtraction overflow");
return a - b;
}
/**
* @dev Returns the multiplication of two unsigned integers, reverting on
* overflow.
*
* Counterpart to Solidity's `*` operator.
*
* Requirements:
*
* - Multiplication cannot overflow.
*/
function mul(uint256 a, uint256 b) internal pure returns (uint256) {
if (a == 0) return 0;
uint256 c = a * b;
require(c / a == b, "SafeMath: multiplication overflow");
return c;
}
/**
* @dev Returns the integer division of two unsigned integers, reverting on
* division by zero. The result is rounded towards zero.
*
* Counterpart to Solidity's `/` operator. Note: this function uses a
* `revert` opcode (which leaves remaining gas untouched) while Solidity
* uses an invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function div(uint256 a, uint256 b) internal pure returns (uint256) {
require(b > 0, "SafeMath: division by zero");
return a / b;
}
/**
* @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo),
* reverting when dividing by zero.
*
* Counterpart to Solidity's `%` operator. This function uses a `revert`
* opcode (which leaves remaining gas untouched) while Solidity uses an
* invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function mod(uint256 a, uint256 b) internal pure returns (uint256) {
require(b > 0, "SafeMath: modulo by zero");
return a % b;
}
/**
* @dev Returns the subtraction of two unsigned integers, reverting with custom message on
* overflow (when the result is negative).
*
* CAUTION: This function is deprecated because it requires allocating memory for the error
* message unnecessarily. For custom revert reasons use {trySub}.
*
* Counterpart to Solidity's `-` operator.
*
* Requirements:
*
* - Subtraction cannot overflow.
*/
function sub(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
require(b <= a, errorMessage);
return a - b;
}
/**
* @dev Returns the integer division of two unsigned integers, reverting with custom message on
* division by zero. The result is rounded towards zero.
*
* CAUTION: This function is deprecated because it requires allocating memory for the error
* message unnecessarily. For custom revert reasons use {tryDiv}.
*
* Counterpart to Solidity's `/` operator. Note: this function uses a
* `revert` opcode (which leaves remaining gas untouched) while Solidity
* uses an invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function div(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
require(b > 0, errorMessage);
return a / b;
}
/**
* @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo),
* reverting with custom message when dividing by zero.
*
* CAUTION: This function is deprecated because it requires allocating memory for the error
* message unnecessarily. For custom revert reasons use {tryMod}.
*
* Counterpart to Solidity's `%` operator. This function uses a `revert`
* opcode (which leaves remaining gas untouched) while Solidity uses an
* invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function mod(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
require(b > 0, errorMessage);
return a % b;
}
}
// SPDX-License-Identifier: MIT
pragma solidity >=0.6.12;
pragma experimental ABIEncoderV2;
interface IFujiERC1155 {
//Asset Types
enum AssetType {
//uint8 = 0
collateralToken,
//uint8 = 1
debtToken
}
//General Getter Functions
function getAssetID(AssetType _type, address _assetAddr) external view returns (uint256);
function qtyOfManagedAssets() external view returns (uint64);
function balanceOf(address _account, uint256 _id) external view returns (uint256);
//function splitBalanceOf(address account,uint256 _AssetID) external view returns (uint256,uint256);
//function balanceOfBatchType(address account, AssetType _Type) external view returns (uint256);
//Permit Controlled Functions
function mint(
address _account,
uint256 _id,
uint256 _amount,
bytes memory _data
) external;
function burn(
address _account,
uint256 _id,
uint256 _amount
) external;
function updateState(uint256 _assetID, uint256 _newBalance) external;
function addInitializeAsset(AssetType _type, address _addr) external returns (uint64);
}
// SPDX-License-Identifier: MIT
pragma solidity >=0.6.0 <0.8.0;
/*
* @dev Provides information about the current execution context, including the
* sender of the transaction and its data. While these are generally available
* via msg.sender and msg.data, they should not be accessed in such a direct
* manner, since when dealing with GSN meta-transactions the account sending and
* paying for execution may not be the actual sender (as far as an application
* is concerned).
*
* This contract is only required for intermediate, library-like contracts.
*/
abstract contract Context {
function _msgSender() internal view virtual returns (address payable) {
return msg.sender;
}
function _msgData() internal view virtual returns (bytes memory) {
this; // silence state mutability warning without generating bytecode - see https://github.com/ethereum/solidity/issues/2691
return msg.data;
}
}
|
Does Whitelist Routine to check if: - limit of users got reached - first deposit is less than ethCapValue - subsequent total deposits are less than 2ethCapValue _usrAddr: Address of the User to check return letgo a boolean that allows a function to continue in "require" context/
|
function whiteListRoutine(
address _usrAddr,
uint64 _assetID,
uint256 _amount,
address _erc1155
) external override returns (bool letgo) {
uint256 currentBalance = IFujiERC1155(_erc1155).balanceOf(_usrAddr, _assetID);
if (currentBalance == 0) {
counter = counter.add(1);
letgo = _amount <= ethCapValue && counter <= limitUsers;
letgo = currentBalance.add(_amount) <= ethCapValue.mul(2);
}
}
| 13,505,930 |
pragma solidity >=0.5.3 < 0.6.0;
import { IERC20 } from "../../_resources/openzeppelin-solidity/token/ERC20/IERC20.sol";
import { SafeMath } from "../../_resources/openzeppelin-solidity/math/SafeMath.sol";
import { Roles } from "../../_resources/openzeppelin-solidity/access/Roles.sol";
import { ITokenManager } from "../../tokenManager/basicLinearV1/ITokenManagerV1.sol";
import { AdminManaged } from "../../shared/modules/AdminManaged.sol";
// Use Library for Roles: https://openzeppelin.org/api/docs/learn-about-access-control.html
/// @author Ryan @ Protea
/// @title V1 Membership Manager
contract MembershipManagerV1 is AdminManaged {
using SafeMath for uint256;
using Roles for Roles.Role;
address internal tokenManager_;
uint8 internal membershipTypeTotal_;
bool internal disabled = false;
Roles.Role internal systemAdmins_;
mapping(address => RegisteredUtility) internal registeredUtility_;
mapping(address => mapping (uint8 => uint256)) internal reputationRewards_;
mapping(address => Membership) internal membershipState_;
struct RegisteredUtility{
bool active;
mapping(uint256 => uint256) lockedStakePool; // Total Stake withheld by the utility
mapping(uint256 => mapping(address => uint256)) contributions; // Traking individual token values sent in
}
struct Membership{
uint256 currentDate;
uint256 availableStake;
uint256 reputation;
}
event UtilityAdded(address issuer);
event UtilityRemoved(address issuer);
event ReputationRewardSet(address indexed issuer, uint8 id, uint256 amount);
event StakeLocked(address indexed member, address indexed utility, uint256 tokenAmount);
event StakeUnlocked(address indexed member, address indexed utility, uint256 tokenAmount);
event MembershipStaked(address indexed member, uint256 tokensStaked);
event MembershipWithdrawn(address indexed member, uint256 tokensWithdrawn);
/// @param _communityManager The first admin and publisher of the community
constructor(address _communityManager)
public
AdminManaged(_communityManager)
{
systemAdmins_.add(_communityManager);
systemAdmins_.add(msg.sender); // This allows the deployer to set the membership manager
admins_.add(msg.sender);
}
modifier onlySystemAdmin() {
require(systemAdmins_.has(msg.sender), "User not authorised");
_;
}
modifier onlyUtility(address _utilityAddress){
require(registeredUtility_[_utilityAddress].active, "Address is not a registered utility");
_;
}
modifier notDisabled() {
require(disabled == false, "Membership manager locked for migration");
_;
}
/// @dev Used to initalise the contract after the token manager is deployed
/// @param _tokenManager :address The address of the new token manager
/// @return bool Returns a bool for requires to validate
function initialize(address _tokenManager) external onlySystemAdmin returns(bool) {
require(tokenManager_ == address(0), "Contracts initalised");
tokenManager_ = _tokenManager;
systemAdmins_.remove(msg.sender);
admins_.remove(msg.sender);
return true;
}
/// @dev Used to lock all incomming token functions & reputation for migrating to a new manager
/// @return bool Returns a bool for requires to validate
function disableForMigration() external onlySystemAdmin returns(bool) {
disabled = true;
return disabled;
}
/// @dev Used to register a utility for access to the membership manager
/// @param _utility :address The utility in question
// Rough gas usage 44,950
function addUtility(address _utility) external onlyAdmin{
registeredUtility_[_utility].active = true;
emit UtilityAdded(_utility);
}
/// @dev Used to remove a utility's access from the membership manager
/// @param _utility :address The utility in question
function removeUtility(address _utility) external onlyAdmin {
registeredUtility_[_utility].active = false;
emit UtilityRemoved(_utility);
}
/// @dev Used to add an admin
/// @param _newAdmin :address The address of the new admin
function addAdmin(address _newAdmin) external onlyAdmin {
admins_.add(_newAdmin);
}
/// @dev Used to add a system admin
/// @param _newAdmin :address The address of the new admin
function addSystemAdmin(address _newAdmin) external onlySystemAdmin {
systemAdmins_.add(_newAdmin);
}
/// @dev Used to remove admins
/// @param _oldAdmin :address The address of the previous admin
function removeAdmin(address _oldAdmin) external onlyAdmin {
admins_.remove(_oldAdmin);
}
/// @dev Used to remove system admins
/// @param _oldAdmin :address The address of the previous admin
function removeSystemAdmin(address _oldAdmin) external onlySystemAdmin {
systemAdmins_.remove(_oldAdmin);
}
/// @dev Registers a reputation incrementing event for a utility to use
/// @param _utility :address The utility in question
/// @param _id :uint8 The registered reputation increment
/// @param _rewardAmount :uint256 The amount that the event adds to a users reputation
// Rough gas usage 45,824
function setReputationRewardEvent(address _utility, uint8 _id, uint256 _rewardAmount) external onlySystemAdmin{
reputationRewards_[_utility][_id] = _rewardAmount;
emit ReputationRewardSet(_utility, _id, _rewardAmount);
}
/// @dev Used by utilities to increment a users reputation values
/// @param _member :address The member address
/// @param _rewardId :uint8 The registered reputation increment
/// @return bool Returns a bool for requires to validate
function issueReputationReward(address _member, uint8 _rewardId) public notDisabled() onlyUtility(msg.sender) returns (bool) {
membershipState_[_member].reputation = membershipState_[_member].reputation.add(reputationRewards_[msg.sender][_rewardId]);
return true;
}
/// @dev Used to inject tokens for utility access into a users membership account
/// @param _daiValue :uint256 The value in DAI of tokens to extract
/// @param _member :address The member address
/// @return bool Returns a bool for requires to validate
// Rough gas usage 102,245
function stakeMembership(uint256 _daiValue, address _member) external notDisabled() returns(bool) {
uint256 requiredTokens = ITokenManager(tokenManager_).colateralToTokenSelling(_daiValue);
require(ITokenManager(tokenManager_).transferFrom(_member, address(this), requiredTokens), "Transfer was not complete");
if(membershipState_[_member].currentDate == 0){
membershipState_[_member].currentDate = now;
}
membershipState_[_member].availableStake = membershipState_[_member].availableStake.add(requiredTokens);
emit MembershipStaked(_member, requiredTokens);
return true;
}
/// @dev Used to manually send tokens sitting in a utility pool, either unclaimed or requiring distribution by the utility
/// @param _tokenAmount :uint256 The amount of community tokens to send
/// @param _index :uint256 The utility activity index
/// @param _member :address The member address
/// @return bool Returns a bool for requires to validate
function manualTransfer(uint256 _tokenAmount, uint256 _index, address _member) external onlyUtility(msg.sender) returns (bool) {
require(registeredUtility_[msg.sender].lockedStakePool[_index] >= _tokenAmount, "Insufficient tokens available");
registeredUtility_[msg.sender].lockedStakePool[_index] = registeredUtility_[msg.sender].lockedStakePool[_index].sub(_tokenAmount);
membershipState_[_member].availableStake = membershipState_[_member].availableStake.add(_tokenAmount);
return true;
}
/// @dev Used to extract tokens from the membership manager to the users account
/// @param _daiValue :uint256 The value in DAI of tokens to extract
/// @param _member :address The member address
/// @return bool Returns a bool for requires to validate
function withdrawMembership(uint256 _daiValue, address _member) external returns(bool) {
uint256 withdrawAmount = ITokenManager(tokenManager_).colateralToTokenSelling(_daiValue);
require(membershipState_[_member].availableStake >= withdrawAmount, "Not enough stake to fulfil request");
membershipState_[_member].availableStake = membershipState_[_member].availableStake.sub(withdrawAmount);
require(ITokenManager(tokenManager_).transfer(_member, withdrawAmount), "Transfer was not complete");
emit MembershipWithdrawn(_member, withdrawAmount);
}
/// @dev Used to lock up tokens for access to a utilities features
/// @param _member :address The member address
/// @param _index :uint256 The utility activity index
/// @param _daiValue :uint256 The value in DAI of tokens needed to use the utility
/// @return bool Returns a bool for requires to validate
function lockCommitment(address _member, uint256 _index, uint256 _daiValue) external notDisabled() onlyUtility(msg.sender) returns (bool) {
uint256 requiredTokens = ITokenManager(tokenManager_).colateralToTokenSelling(_daiValue);
require(membershipState_[_member].availableStake >= requiredTokens, "Not enough available commitment");
require(msg.sender != _member, "Address invalid");
membershipState_[_member].availableStake = membershipState_[_member].availableStake.sub(requiredTokens);
registeredUtility_[msg.sender].contributions[_index][_member] = registeredUtility_[msg.sender].contributions[_index][_member].add(requiredTokens);
registeredUtility_[msg.sender].lockedStakePool[_index] = registeredUtility_[msg.sender].lockedStakePool[_index].add(requiredTokens);
emit StakeLocked(_member, msg.sender, requiredTokens);
return true;
}
/// @dev Used to return stake to a user having previously been locked up in a utility for use
/// @param _member :address The member address
/// @param _index :uint256 The utility activity index
/// @return bool Returns a bool for requires to validate
function unlockCommitment(address _member, uint256 _index, uint8 _reputationEvent) external onlyUtility(msg.sender) returns (bool) {
uint256 returnAmount = registeredUtility_[msg.sender].contributions[_index][_member];
require(registeredUtility_[msg.sender].lockedStakePool[_index] >= returnAmount, "Insufficient tokens available");
registeredUtility_[msg.sender].contributions[_index][_member] = 0;
registeredUtility_[msg.sender].lockedStakePool[_index] = registeredUtility_[msg.sender].lockedStakePool[_index].sub(returnAmount);
membershipState_[_member].availableStake = membershipState_[_member].availableStake.add(returnAmount);
require(issueReputationReward(_member, _reputationEvent), "Reputation not increased");
emit StakeUnlocked(_member, msg.sender, returnAmount);
return true;
}
/// @dev Returns the details on a members contributions, reputation and date data
/// @param _member :address The member address
/// @return (uint256, uint256, uint256) The date field, reputation and current available stake
function getMembershipStatus(address _member)
public
view
returns(uint256, uint256, uint256)
{
return (
membershipState_[_member].currentDate,
membershipState_[_member].reputation,
membershipState_[_member].availableStake
);
}
/// @dev Checks if an address is a registered or active utility
/// @param _utility :address Address to check if is a registered utility
/// @return bool Bool stating if valid
function isRegistered(address _utility) external view returns(bool) {
return registeredUtility_[_utility].active;
}
/// @dev Used to see the total amount of contributions sitting in a utility's activity
/// @param _utility :address The utility in question
/// @param _index :uint256 The utility activity index
/// @return uint256 Total active contributions locked up but the activity
function getUtilityStake(address _utility, uint256 _index) external view returns(uint256) {
return registeredUtility_[_utility].lockedStakePool[_index];
}
/// @dev Used to track the contribution of tokens a user has sent to the utility's activity
/// @param _utility :address The utility in question
/// @param _member :address The member contributing
/// @param _index :uint256 The utility activity index
/// @return uint256 Current contribution for that member on the utility activty
function getMemberUtilityStake(address _utility, address _member, uint256 _index) external view returns(uint256) {
return registeredUtility_[_utility].contributions[_index][_member];
}
/// @dev Used to check the current reward amount for the utilities reputation increasing event
/// @param _utility :address The utility in question
/// @param _id :uint8 The registered reputation increment
/// @return uint256 The amount that the event adds to a users reputation
function getReputationRewardEvent(address _utility, uint8 _id) external view returns(uint256){
return reputationRewards_[_utility][_id];
}
/// @dev Used to return the registered token manager, works like an initialisation check
/// @return :address Token manager address
function tokenManager() external view returns(address) {
return tokenManager_;
}
}
|
Used to register a utility for access to the membership manager _utility :address The utility in question Rough gas usage 44,950
|
function addUtility(address _utility) external onlyAdmin{
registeredUtility_[_utility].active = true;
emit UtilityAdded(_utility);
}
| 14,053,106 |
/**
*Submitted for verification at Etherscan.io on 2020-06-08
*/
/*
Copyright 2020 dYdX Trading Inc.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
// File: @openzeppelin/contracts/token/ERC20/IERC20.sol
pragma solidity 0.5.16;
pragma experimental ABIEncoderV2;
/**
* @dev Interface of the ERC20 standard as defined in the EIP. Does not include
* the optional functions; to access them see {ERC20Detailed}.
*/
interface IERC20 {
/**
* @dev Returns the amount of tokens in existence.
*/
function totalSupply() external view returns (uint256);
/**
* @dev Returns the amount of tokens owned by `account`.
*/
function balanceOf(address account) external view returns (uint256);
/**
* @dev Moves `amount` tokens from the caller's account to `recipient`.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/
function transfer(address recipient, uint256 amount) external returns (bool);
/**
* @dev Returns the remaining number of tokens that `spender` will be
* allowed to spend on behalf of `owner` through {transferFrom}. This is
* zero by default.
*
* This value changes when {approve} or {transferFrom} are called.
*/
function allowance(address owner, address spender) external view returns (uint256);
/**
* @dev Sets `amount` as the allowance of `spender` over the caller's tokens.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* IMPORTANT: 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
*
* Emits an {Approval} event.
*/
function approve(address spender, uint256 amount) external returns (bool);
/**
* @dev Moves `amount` tokens from `sender` to `recipient` using the
* allowance mechanism. `amount` is then deducted from the caller's
* allowance.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/
function transferFrom(address sender, address recipient, uint256 amount) external returns (bool);
/**
* @dev Emitted when `value` tokens are moved from one account (`from`) to
* another (`to`).
*
* Note that `value` may be zero.
*/
event Transfer(address indexed from, address indexed to, uint256 value);
/**
* @dev Emitted when the allowance of a `spender` for an `owner` is set by
* a call to {approve}. `value` is the new allowance.
*/
event Approval(address indexed owner, address indexed spender, uint256 value);
}
// File: @openzeppelin/contracts/math/SafeMath.sol
/**
* @dev Wrappers over Solidity's arithmetic operations with added overflow
* checks.
*
* Arithmetic operations in Solidity wrap on overflow. This can easily result
* in bugs, because programmers usually assume that an overflow raises an
* error, which is the standard behavior in high level programming languages.
* `SafeMath` restores this intuition by reverting the transaction when an
* operation overflows.
*
* Using this library instead of the unchecked operations eliminates an entire
* class of bugs, so it's recommended to use it always.
*/
library SafeMath {
/**
* @dev Returns the addition of two unsigned integers, reverting on
* overflow.
*
* Counterpart to Solidity's `+` operator.
*
* Requirements:
* - Addition cannot overflow.
*/
function add(uint256 a, uint256 b) internal pure returns (uint256) {
uint256 c = a + b;
require(c >= a, "SafeMath: addition overflow");
return c;
}
/**
* @dev Returns the subtraction of two unsigned integers, reverting on
* overflow (when the result is negative).
*
* Counterpart to Solidity's `-` operator.
*
* Requirements:
* - Subtraction cannot overflow.
*/
function sub(uint256 a, uint256 b) internal pure returns (uint256) {
return sub(a, b, "SafeMath: subtraction overflow");
}
/**
* @dev Returns the subtraction of two unsigned integers, reverting with custom message on
* overflow (when the result is negative).
*
* Counterpart to Solidity's `-` operator.
*
* Requirements:
* - Subtraction cannot overflow.
*
* _Available since v2.4.0._
*/
function sub(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
require(b <= a, errorMessage);
uint256 c = a - b;
return c;
}
/**
* @dev Returns the multiplication of two unsigned integers, reverting on
* overflow.
*
* Counterpart to Solidity's `*` operator.
*
* Requirements:
* - Multiplication cannot overflow.
*/
function mul(uint256 a, uint256 b) internal pure returns (uint256) {
// Gas optimization: this is cheaper than requiring 'a' not being zero, but the
// benefit is lost if 'b' is also tested.
// See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522
if (a == 0) {
return 0;
}
uint256 c = a * b;
require(c / a == b, "SafeMath: multiplication overflow");
return c;
}
/**
* @dev Returns the integer division of two unsigned integers. Reverts on
* division by zero. The result is rounded towards zero.
*
* Counterpart to Solidity's `/` operator. Note: this function uses a
* `revert` opcode (which leaves remaining gas untouched) while Solidity
* uses an invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
* - The divisor cannot be zero.
*/
function div(uint256 a, uint256 b) internal pure returns (uint256) {
return div(a, b, "SafeMath: division by zero");
}
/**
* @dev Returns the integer division of two unsigned integers. Reverts with custom message on
* division by zero. The result is rounded towards zero.
*
* Counterpart to Solidity's `/` operator. Note: this function uses a
* `revert` opcode (which leaves remaining gas untouched) while Solidity
* uses an invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
* - The divisor cannot be zero.
*
* _Available since v2.4.0._
*/
function div(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
// Solidity only automatically asserts when dividing by 0
require(b > 0, errorMessage);
uint256 c = a / b;
// assert(a == b * c + a % b); // There is no case in which this doesn't hold
return c;
}
/**
* @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo),
* Reverts when dividing by zero.
*
* Counterpart to Solidity's `%` operator. This function uses a `revert`
* opcode (which leaves remaining gas untouched) while Solidity uses an
* invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
* - The divisor cannot be zero.
*/
function mod(uint256 a, uint256 b) internal pure returns (uint256) {
return mod(a, b, "SafeMath: modulo by zero");
}
/**
* @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo),
* Reverts with custom message when dividing by zero.
*
* Counterpart to Solidity's `%` operator. This function uses a `revert`
* opcode (which leaves remaining gas untouched) while Solidity uses an
* invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
* - The divisor cannot be zero.
*
* _Available since v2.4.0._
*/
function mod(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
require(b != 0, errorMessage);
return a % b;
}
}
// File: @openzeppelin/contracts/utils/Address.sol
/**
* @dev Collection of functions related to the address type
*/
library Address {
/**
* @dev Returns true if `account` is a contract.
*
* [IMPORTANT]
* ====
* It is unsafe to assume that an address for which this function returns
* false is an externally-owned account (EOA) and not a contract.
*
* Among others, `isContract` will return false for the following
* types of addresses:
*
* - an externally-owned account
* - a contract in construction
* - an address where a contract will be created
* - an address where a contract lived, but was destroyed
* ====
*/
function isContract(address account) internal view returns (bool) {
// According to EIP-1052, 0x0 is the value returned for not-yet created accounts
// and 0xc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470 is returned
// for accounts without code, i.e. `keccak256('')`
bytes32 codehash;
bytes32 accountHash = 0xc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470;
// solhint-disable-next-line no-inline-assembly
assembly { codehash := extcodehash(account) }
return (codehash != accountHash && codehash != 0x0);
}
/**
* @dev Converts an `address` into `address payable`. Note that this is
* simply a type cast: the actual underlying value is not changed.
*
* _Available since v2.4.0._
*/
function toPayable(address account) internal pure returns (address payable) {
return address(uint160(account));
}
/**
* @dev Replacement for Solidity's `transfer`: sends `amount` wei to
* `recipient`, forwarding all available gas and reverting on errors.
*
* https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost
* of certain opcodes, possibly making contracts go over the 2300 gas limit
* imposed by `transfer`, making them unable to receive funds via
* `transfer`. {sendValue} removes this limitation.
*
* https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more].
*
* IMPORTANT: because control is transferred to `recipient`, care must be
* taken to not create reentrancy vulnerabilities. Consider using
* {ReentrancyGuard} or the
* https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern].
*
* _Available since v2.4.0._
*/
function sendValue(address payable recipient, uint256 amount) internal {
require(address(this).balance >= amount, "Address: insufficient balance");
// solhint-disable-next-line avoid-call-value
(bool success, ) = recipient.call.value(amount)("");
require(success, "Address: unable to send value, recipient may have reverted");
}
}
// File: @openzeppelin/contracts/token/ERC20/SafeERC20.sol
/**
* @title SafeERC20
* @dev Wrappers around ERC20 operations that throw on failure (when the token
* contract returns false). Tokens that return no value (and instead revert or
* throw on failure) are also supported, non-reverting calls are assumed to be
* successful.
* To use this library you can add a `using SafeERC20 for ERC20;` statement to your contract,
* which allows you to call the safe operations as `token.safeTransfer(...)`, etc.
*/
library SafeERC20 {
using SafeMath for uint256;
using Address for address;
function safeTransfer(IERC20 token, address to, uint256 value) internal {
callOptionalReturn(token, abi.encodeWithSelector(token.transfer.selector, to, value));
}
function safeTransferFrom(IERC20 token, address from, address to, uint256 value) internal {
callOptionalReturn(token, abi.encodeWithSelector(token.transferFrom.selector, from, to, value));
}
function safeApprove(IERC20 token, address spender, uint256 value) internal {
// safeApprove should only be called when setting an initial allowance,
// or when resetting it to zero. To increase and decrease it, use
// 'safeIncreaseAllowance' and 'safeDecreaseAllowance'
// solhint-disable-next-line max-line-length
require((value == 0) || (token.allowance(address(this), spender) == 0),
"SafeERC20: approve from non-zero to non-zero allowance"
);
callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, value));
}
function safeIncreaseAllowance(IERC20 token, address spender, uint256 value) internal {
uint256 newAllowance = token.allowance(address(this), spender).add(value);
callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance));
}
function safeDecreaseAllowance(IERC20 token, address spender, uint256 value) internal {
uint256 newAllowance = token.allowance(address(this), spender).sub(value, "SafeERC20: decreased allowance below zero");
callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance));
}
/**
* @dev Imitates a Solidity high-level call (i.e. a regular function call to a contract), relaxing the requirement
* on the return value: the return value is optional (but if data is returned, it must not be false).
* @param token The token targeted by the call.
* @param data The call data (encoded using abi.encode or one of its variants).
*/
function callOptionalReturn(IERC20 token, bytes memory data) private {
// We need to perform a low level call here, to bypass Solidity's return data size checking mechanism, since
// we're implementing it ourselves.
// A Solidity high level call has three parts:
// 1. The target address is checked to verify it contains contract code
// 2. The call itself is made, and success asserted
// 3. The return value is decoded, which in turn checks the size of the returned data.
// solhint-disable-next-line max-line-length
require(address(token).isContract(), "SafeERC20: call to non-contract");
// solhint-disable-next-line avoid-low-level-calls
(bool success, bytes memory returndata) = address(token).call(data);
require(success, "SafeERC20: low-level call failed");
if (block.number > 0) { // Return data is optional //injected CONTRACT AFFECTED BY MINERS
// solhint-disable-next-line max-line-length
require(abi.decode(returndata, (bool)), "SafeERC20: ERC20 operation did not succeed");
}
}
}
// File: contracts/external/I_ExchangeWrapper.sol
/**
* @title I_ExchangeWrapper
* @author dYdX
*
* @notice Interface for exchange wrappers, used to trade ERC20 tokens.
*/
interface I_ExchangeWrapper {
// ============ Public Functions ============
/**
* Exchange some amount of takerToken for makerToken.
*
* @param tradeOriginator Address of the initiator of the trade (however, this value
* cannot always be trusted as it is set at the discretion of the
* msg.sender)
* @param receiver Address to set allowance on once the trade has completed
* @param makerToken Address of makerToken, the token to receive
* @param takerToken Address of takerToken, the token to pay
* @param requestedFillAmount Amount of takerToken being paid
* @param orderData Arbitrary bytes data for any information to pass to the exchange
* @return The amount of makerToken received
*/
function exchange(
address tradeOriginator,
address receiver,
address makerToken,
address takerToken,
uint256 requestedFillAmount,
bytes calldata orderData
)
external
returns (uint256);
/**
* Get amount of takerToken required to buy a certain amount of makerToken for a given trade.
* Should match the takerToken amount used in exchangeForAmount. If the order cannot provide
* exactly desiredMakerToken, then it must return the price to buy the minimum amount greater
* than desiredMakerToken
*
* @param makerToken Address of makerToken, the token to receive
* @param takerToken Address of takerToken, the token to pay
* @param desiredMakerToken Amount of makerToken requested
* @param orderData Arbitrary bytes data for any information to pass to the exchange
* @return Amount of takerToken the needed to complete the exchange
*/
function getExchangeCost(
address makerToken,
address takerToken,
uint256 desiredMakerToken,
bytes calldata orderData
)
external
view
returns (uint256);
}
// File: contracts/protocol/v1/lib/P1Types.sol
/**
* @title P1Types
* @author dYdX
*
* @dev Library for common types used in PerpetualV1 contracts.
*/
library P1Types {
// ============ Structs ============
/**
* @dev Used to represent the global index and each account's cached index.
* Used to settle funding paymennts on a per-account basis.
*/
struct Index {
uint32 timestamp;
bool isPositive;
uint128 value;
}
/**
* @dev Used to track the signed margin balance and position balance values for each account.
*/
struct Balance {
bool marginIsPositive;
bool positionIsPositive;
uint120 margin;
uint120 position;
}
/**
* @dev Used to cache commonly-used variables that are relatively gas-intensive to obtain.
*/
struct Context {
uint256 price;
uint256 minCollateral;
Index index;
}
/**
* @dev Used by contracts implementing the I_P1Trader interface to return the result of a trade.
*/
struct TradeResult {
uint256 marginAmount;
uint256 positionAmount;
bool isBuy; // From taker's perspective.
bytes32 traderFlags;
}
}
// File: contracts/protocol/v1/intf/I_PerpetualV1.sol
/**
* @title I_PerpetualV1
* @author dYdX
*
* @notice Interface for PerpetualV1.
*/
interface I_PerpetualV1 {
// ============ Structs ============
struct TradeArg {
uint256 takerIndex;
uint256 makerIndex;
address trader;
bytes data;
}
// ============ State-Changing Functions ============
/**
* @notice Submits one or more trades between any number of accounts.
*
* @param accounts The sorted list of accounts that are involved in trades.
* @param trades The list of trades to execute in-order.
*/
function trade(
address[] calldata accounts,
TradeArg[] calldata trades
)
external;
/**
* @notice Withdraw the number of margin tokens equal to the value of the account at the time
* that final settlement occurred.
*/
function withdrawFinalSettlement()
external;
/**
* @notice Deposit some amount of margin tokens from the msg.sender into an account.
*
* @param account The account for which to credit the deposit.
* @param amount the amount of tokens to deposit.
*/
function deposit(
address account,
uint256 amount
)
external;
/**
* @notice Withdraw some amount of margin tokens from an account to a destination address.
*
* @param account The account for which to debit the withdrawal.
* @param destination The address to which the tokens are transferred.
* @param amount The amount of tokens to withdraw.
*/
function withdraw(
address account,
address destination,
uint256 amount
)
external;
/**
* @notice Grants or revokes permission for another account to perform certain actions on behalf
* of the sender.
*
* @param operator The account that is approved or disapproved.
* @param approved True for approval, false for disapproval.
*/
function setLocalOperator(
address operator,
bool approved
)
external;
// ============ Account Getters ============
/**
* @notice Get the balance of an account, without accounting for changes in the index.
*
* @param account The address of the account to query the balances of.
* @return The balances of the account.
*/
function getAccountBalance(
address account
)
external
view
returns (P1Types.Balance memory);
/**
* @notice Gets the most recently cached index of an account.
*
* @param account The address of the account to query the index of.
* @return The index of the account.
*/
function getAccountIndex(
address account
)
external
view
returns (P1Types.Index memory);
/**
* @notice Gets the local operator status of an operator for a particular account.
*
* @param account The account to query the operator for.
* @param operator The address of the operator to query the status of.
* @return True if the operator is a local operator of the account, false otherwise.
*/
function getIsLocalOperator(
address account,
address operator
)
external
view
returns (bool);
// ============ Global Getters ============
/**
* @notice Gets the global operator status of an address.
*
* @param operator The address of the operator to query the status of.
* @return True if the address is a global operator, false otherwise.
*/
function getIsGlobalOperator(
address operator
)
external
view
returns (bool);
/**
* @notice Gets the address of the ERC20 margin contract used for margin deposits.
*
* @return The address of the ERC20 token.
*/
function getTokenContract()
external
view
returns (address);
/**
* @notice Gets the current address of the price oracle contract.
*
* @return The address of the price oracle contract.
*/
function getOracleContract()
external
view
returns (address);
/**
* @notice Gets the current address of the funder contract.
*
* @return The address of the funder contract.
*/
function getFunderContract()
external
view
returns (address);
/**
* @notice Gets the most recently cached global index.
*
* @return The most recently cached global index.
*/
function getGlobalIndex()
external
view
returns (P1Types.Index memory);
/**
* @notice Gets minimum collateralization ratio of the protocol.
*
* @return The minimum-acceptable collateralization ratio, returned as a fixed-point number with
* 18 decimals of precision.
*/
function getMinCollateral()
external
view
returns (uint256);
/**
* @notice Gets the status of whether final-settlement was initiated by the Admin.
*
* @return True if final-settlement was enabled, false otherwise.
*/
function getFinalSettlementEnabled()
external
view
returns (bool);
// ============ Public Getters ============
/**
* @notice Gets whether an address has permissions to operate an account.
*
* @param account The account to query.
* @param operator The address to query.
* @return True if the operator has permission to operate the account,
* and false otherwise.
*/
function hasAccountPermissions(
address account,
address operator
)
external
view
returns (bool);
// ============ Authorized Getters ============
/**
* @notice Gets the price returned by the oracle.
* @dev Only able to be called by global operators.
*
* @return The price returned by the current price oracle.
*/
function getOraclePrice()
external
view
returns (uint256);
}
// File: contracts/protocol/v1/proxies/P1CurrencyConverterProxy.sol
/**
* @title P1CurrencyConverterProxy
* @author dYdX
*
* @notice Proxy contract which executes a trade via an ExchangeWrapper before making a deposit
* or after making a withdrawal.
*/
contract P1CurrencyConverterProxy {
using SafeERC20 for IERC20;
// ============ Events ============
event LogConvertedDeposit(
address indexed account,
address source,
address perpetual,
address exchangeWrapper,
address tokenFrom,
address tokenTo,
uint256 tokenFromAmount,
uint256 tokenToAmount
);
event LogConvertedWithdrawal(
address indexed account,
address destination,
address perpetual,
address exchangeWrapper,
address tokenFrom,
address tokenTo,
uint256 tokenFromAmount,
uint256 tokenToAmount
);
// ============ State-Changing Functions ============
/**
* @notice Sets the maximum allowance on the Perpetual contract. Must be called at least once
* on a given Perpetual before deposits can be made.
* @dev Cannot be run in the constructor due to technical restrictions in Solidity.
*/
function approveMaximumOnPerpetual(
address perpetual
)
external
{
IERC20 tokenContract = IERC20(I_PerpetualV1(perpetual).getTokenContract());
// safeApprove requires unsetting the allowance first.
tokenContract.safeApprove(perpetual, 0);
// Set the allowance to the highest possible value.
tokenContract.safeApprove(perpetual, uint256(-1));
}
/**
* @notice Make a margin deposit to a Perpetual, after converting funds to the margin currency.
* Funds will be withdrawn from the sender and deposited into the specified account.
* @dev Emits LogConvertedDeposit event.
*
* @param account The account for which to credit the deposit.
* @param perpetual The PerpetualV1 contract to deposit to.
* @param exchangeWrapper The ExchangeWrapper contract to trade with.
* @param tokenFrom The token to convert from.
* @param tokenFromAmount The amount of `tokenFrom` tokens to deposit.
* @param data Trade parameters for the ExchangeWrapper.
*/
function deposit(
address account,
address perpetual,
address exchangeWrapper,
address tokenFrom,
uint256 tokenFromAmount,
bytes calldata data
)
external
returns (uint256)
{
I_PerpetualV1 perpetualContract = I_PerpetualV1(perpetual);
address tokenTo = perpetualContract.getTokenContract();
address self = address(this);
// Send fromToken to the ExchangeWrapper.
//
// TODO: Take possible ERC20 fee into account.
IERC20(tokenFrom).safeTransferFrom(
msg.sender,
exchangeWrapper,
tokenFromAmount
);
// Convert fromToken to toToken on the ExchangeWrapper.
I_ExchangeWrapper exchangeWrapperContract = I_ExchangeWrapper(exchangeWrapper);
uint256 tokenToAmount = exchangeWrapperContract.exchange(
msg.sender,
self,
tokenTo,
tokenFrom,
tokenFromAmount,
data
);
// Receive toToken from the ExchangeWrapper.
IERC20(tokenTo).safeTransferFrom(
exchangeWrapper,
self,
tokenToAmount
);
// Deposit toToken to the Perpetual.
perpetualContract.deposit(
account,
tokenToAmount
);
// Log the result.
emit LogConvertedDeposit(
account,
msg.sender,
perpetual,
exchangeWrapper,
tokenFrom,
tokenTo,
tokenFromAmount,
tokenToAmount
);
return tokenToAmount;
}
/**
* @notice Withdraw margin from a Perpetual, then convert the funds to another currency. Funds
* will be withdrawn from the specified account and transfered to the specified destination.
* @dev Emits LogConvertedWithdrawal event.
*
* @param account The account to withdraw from.
* @param destination The address to send the withdrawn funds to.
* @param perpetual The PerpetualV1 contract to withdraw from to.
* @param exchangeWrapper The ExchangeWrapper contract to trade with.
* @param tokenTo The token to convert to.
* @param tokenFromAmount The amount of `tokenFrom` tokens to withdraw.
* @param data Trade parameters for the ExchangeWrapper.
*/
function withdraw(
address account,
address destination,
address perpetual,
address exchangeWrapper,
address tokenTo,
uint256 tokenFromAmount,
bytes calldata data
)
external
returns (uint256)
{
I_PerpetualV1 perpetualContract = I_PerpetualV1(perpetual);
address tokenFrom = perpetualContract.getTokenContract();
address self = address(this);
// Verify that the sender has permission to withdraw from the account.
require(
account == msg.sender || perpetualContract.hasAccountPermissions(account, msg.sender),
"msg.sender cannot operate the account"
);
// Withdraw fromToken from the Perpetual.
perpetualContract.withdraw(
account,
exchangeWrapper,
tokenFromAmount
);
// Convert fromToken to toToken on the ExchangeWrapper.
I_ExchangeWrapper exchangeWrapperContract = I_ExchangeWrapper(exchangeWrapper);
uint256 tokenToAmount = exchangeWrapperContract.exchange(
msg.sender,
self,
tokenTo,
tokenFrom,
tokenFromAmount,
data
);
// Transfer toToken from the ExchangeWrapper to the destination address.
IERC20(tokenTo).safeTransferFrom(
exchangeWrapper,
destination,
tokenToAmount
);
// Log the result.
emit LogConvertedWithdrawal(
account,
destination,
perpetual,
exchangeWrapper,
tokenFrom,
tokenTo,
tokenFromAmount,
tokenToAmount
);
return tokenToAmount;
}
}
|
I_ExchangeWrapper dYdX Interface for exchange wrappers, used to trade ERC20 tokens./ ============ Public Functions ============
|
interface I_ExchangeWrapper {
function exchange(
address tradeOriginator,
address receiver,
address makerToken,
address takerToken,
uint256 requestedFillAmount,
bytes calldata orderData
)
external
returns (uint256);
function getExchangeCost(
address makerToken,
address takerToken,
uint256 desiredMakerToken,
bytes calldata orderData
)
external
view
returns (uint256);
}
| 6,387,268 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.