file_name
stringlengths 71
779k
| comments
stringlengths 20
182k
| code_string
stringlengths 20
36.9M
| __index_level_0__
int64 0
17.2M
| input_ids
sequence | attention_mask
sequence | labels
sequence |
---|---|---|---|---|---|---|
./full_match/137/0x7d802CB99477ef10d0c6D329da01D2540807E4b8/sources/ERC721/ERC721.sol | * @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./ Check that tokenId was not minted by `_beforeTokenTransfer` hook Will not overflow unless all 2**256 token ids are minted to the same owner. Given that tokens are minted one by one, it is impossible in practice that this ever happens. Might change if we allow batch minting. The ERC fails to describe this case. | 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, 1);
require(!_exists(tokenId), "ERC721: token already minted");
unchecked {
_balances[to] += 1;
}
_owners[tokenId] = to;
emit Transfer(address(0), to, tokenId);
_afterTokenTransfer(address(0), to, tokenId, 1);
}
| 4,773,792 | [
1,
49,
28142,
1375,
2316,
548,
68,
471,
29375,
518,
358,
1375,
869,
8338,
9744,
30,
10858,
434,
333,
707,
353,
19169,
477,
11349,
16,
999,
288,
67,
4626,
49,
474,
97,
17334,
3323,
29076,
30,
300,
1375,
2316,
548,
68,
1297,
486,
1005,
18,
300,
1375,
869,
68,
2780,
506,
326,
3634,
1758,
18,
7377,
1282,
279,
288,
5912,
97,
871,
18,
19,
2073,
716,
1147,
548,
1703,
486,
312,
474,
329,
635,
1375,
67,
5771,
1345,
5912,
68,
3953,
9980,
486,
9391,
3308,
777,
576,
5034,
1147,
3258,
854,
312,
474,
329,
358,
326,
1967,
3410,
18,
16803,
716,
2430,
854,
312,
474,
329,
1245,
635,
1245,
16,
518,
353,
23343,
316,
27164,
716,
333,
14103,
10555,
18,
490,
750,
2549,
309,
732,
1699,
2581,
312,
474,
310,
18,
1021,
4232,
39,
6684,
358,
6401,
333,
648,
18,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
565,
445,
389,
81,
474,
12,
2867,
358,
16,
2254,
5034,
1147,
548,
13,
2713,
5024,
288,
203,
3639,
2583,
12,
869,
480,
1758,
12,
20,
3631,
315,
654,
39,
27,
5340,
30,
312,
474,
358,
326,
3634,
1758,
8863,
203,
3639,
2583,
12,
5,
67,
1808,
12,
2316,
548,
3631,
315,
654,
39,
27,
5340,
30,
1147,
1818,
312,
474,
329,
8863,
203,
203,
3639,
389,
5771,
1345,
5912,
12,
2867,
12,
20,
3631,
358,
16,
1147,
548,
16,
404,
1769,
203,
203,
3639,
2583,
12,
5,
67,
1808,
12,
2316,
548,
3631,
315,
654,
39,
27,
5340,
30,
1147,
1818,
312,
474,
329,
8863,
203,
203,
3639,
22893,
288,
203,
5411,
389,
70,
26488,
63,
869,
65,
1011,
404,
31,
203,
3639,
289,
203,
203,
3639,
389,
995,
414,
63,
2316,
548,
65,
273,
358,
31,
203,
203,
203,
3639,
3626,
12279,
12,
2867,
12,
20,
3631,
358,
16,
1147,
548,
1769,
203,
203,
203,
203,
3639,
389,
5205,
1345,
5912,
12,
2867,
12,
20,
3631,
358,
16,
1147,
548,
16,
404,
1769,
203,
565,
289,
203,
203,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
] |
pragma solidity ^0.5.0;
import "../interfaces/ClientRaindropInterface.sol";
import "../interfaces/HydroInterface.sol";
import "../interfaces/IdentityRegistryInterface.sol";
import "../zeppelin/math/SafeMath.sol";
import "../zeppelin/ownership/Ownable.sol";
import "./interfaces/SnowflakeResolverInterface.sol";
import "./interfaces/SnowflakeViaInterface.sol";
contract Snowflake is Ownable {
using SafeMath for uint;
// mapping of EIN to hydro token deposits
mapping (uint => uint) public deposits;
// mapping from EIN to resolver to allowance
mapping (uint => mapping (address => uint)) public resolverAllowances;
// SC variables
address public identityRegistryAddress;
IdentityRegistryInterface private identityRegistry;
address public hydroTokenAddress;
HydroInterface private hydroToken;
address public clientRaindropAddress;
ClientRaindropInterface private clientRaindrop;
// signature variables
uint public signatureTimeout = 1 days;
mapping (uint => uint) public signatureNonce;
constructor (address _identityRegistryAddress, address _hydroTokenAddress) public {
setAddresses(_identityRegistryAddress, _hydroTokenAddress);
}
// enforces that a particular EIN exists
modifier identityExists(uint ein, bool check) {
require(identityRegistry.identityExists(ein) == check, "The EIN does not exist.");
_;
}
// enforces signature timeouts
modifier ensureSignatureTimeValid(uint timestamp) {
require(
// solium-disable-next-line security/no-block-members
block.timestamp >= timestamp && block.timestamp < timestamp + signatureTimeout, "Timestamp is not valid."
);
_;
}
// set the hydro token and identity registry addresses
function setAddresses(address _identityRegistryAddress, address _hydroTokenAddress) public onlyOwner {
identityRegistryAddress = _identityRegistryAddress;
identityRegistry = IdentityRegistryInterface(identityRegistryAddress);
hydroTokenAddress = _hydroTokenAddress;
hydroToken = HydroInterface(hydroTokenAddress);
}
function setClientRaindropAddress(address _clientRaindropAddress) public onlyOwner {
clientRaindropAddress = _clientRaindropAddress;
clientRaindrop = ClientRaindropInterface(clientRaindropAddress);
}
// wrap createIdentityDelegated and initialize the client raindrop resolver
function createIdentityDelegated(
address recoveryAddress, address associatedAddress, address[] memory providers, string memory casedHydroId,
uint8 v, bytes32 r, bytes32 s, uint timestamp
)
public returns (uint ein)
{
address[] memory _providers = new address[](providers.length + 1);
_providers[0] = address(this);
for (uint i; i < providers.length; i++) {
_providers[i + 1] = providers[i];
}
uint _ein = identityRegistry.createIdentityDelegated(
recoveryAddress, associatedAddress, _providers, new address[](0), v, r, s, timestamp
);
_addResolver(_ein, clientRaindropAddress, true, 0, abi.encode(associatedAddress, casedHydroId));
return _ein;
}
// permission addProvidersFor by signature
function addProvidersFor(
address approvingAddress, address[] memory providers, uint8 v, bytes32 r, bytes32 s, uint timestamp
)
public ensureSignatureTimeValid(timestamp)
{
uint ein = identityRegistry.getEIN(approvingAddress);
require(
identityRegistry.isSigned(
approvingAddress,
keccak256(
abi.encodePacked(
byte(0x19), byte(0), address(this),
"I authorize that these Providers be added to my Identity.",
ein, providers, timestamp
)
),
v, r, s
),
"Permission denied."
);
identityRegistry.addProvidersFor(ein, providers);
}
// permission removeProvidersFor by signature
function removeProvidersFor(
address approvingAddress, address[] memory providers, uint8 v, bytes32 r, bytes32 s, uint timestamp
)
public ensureSignatureTimeValid(timestamp)
{
uint ein = identityRegistry.getEIN(approvingAddress);
require(
identityRegistry.isSigned(
approvingAddress,
keccak256(
abi.encodePacked(
byte(0x19), byte(0), address(this),
"I authorize that these Providers be removed from my Identity.",
ein, providers, timestamp
)
),
v, r, s
),
"Permission denied."
);
identityRegistry.removeProvidersFor(ein, providers);
}
// permissioned addProvidersFor and removeProvidersFor by signature
function upgradeProvidersFor(
address approvingAddress, address[] memory newProviders, address[] memory oldProviders,
uint8[2] memory v, bytes32[2] memory r, bytes32[2] memory s, uint[2] memory timestamp
)
public
{
addProvidersFor(approvingAddress, newProviders, v[0], r[0], s[0], timestamp[0]);
removeProvidersFor(approvingAddress, oldProviders, v[1], r[1], s[1], timestamp[1]);
uint ein = identityRegistry.getEIN(approvingAddress);
emit SnowflakeProvidersUpgraded(ein, newProviders, oldProviders, approvingAddress);
}
// permission adding a resolver for identity of msg.sender
function addResolver(address resolver, bool isSnowflake, uint withdrawAllowance, bytes memory extraData) public {
_addResolver(identityRegistry.getEIN(msg.sender), resolver, isSnowflake, withdrawAllowance, extraData);
}
// permission adding a resolver for identity passed by a provider
function addResolverAsProvider(
uint ein, address resolver, bool isSnowflake, uint withdrawAllowance, bytes memory extraData
)
public
{
require(identityRegistry.isProviderFor(ein, msg.sender), "The msg.sender is not a Provider for the passed EIN");
_addResolver(ein, resolver, isSnowflake, withdrawAllowance, extraData);
}
// permission addResolversFor by signature
function addResolverFor(
address approvingAddress, address resolver, bool isSnowflake, uint withdrawAllowance, bytes memory extraData,
uint8 v, bytes32 r, bytes32 s, uint timestamp
)
public
{
uint ein = identityRegistry.getEIN(approvingAddress);
validateAddResolverForSignature(
approvingAddress, ein, resolver, isSnowflake, withdrawAllowance, extraData, v, r, s, timestamp
);
_addResolver(ein, resolver, isSnowflake, withdrawAllowance, extraData);
}
function validateAddResolverForSignature(
address approvingAddress, uint ein,
address resolver, bool isSnowflake, uint withdrawAllowance, bytes memory extraData,
uint8 v, bytes32 r, bytes32 s, uint timestamp
)
private view ensureSignatureTimeValid(timestamp)
{
require(
identityRegistry.isSigned(
approvingAddress,
keccak256(
abi.encodePacked(
byte(0x19), byte(0), address(this),
"I authorize that this resolver be added to my Identity.",
ein, resolver, isSnowflake, withdrawAllowance, extraData, timestamp
)
),
v, r, s
),
"Permission denied."
);
}
// common logic for adding resolvers
function _addResolver(uint ein, address resolver, bool isSnowflake, uint withdrawAllowance, bytes memory extraData)
private
{
require(!identityRegistry.isResolverFor(ein, resolver), "Identity has already set this resolver.");
address[] memory resolvers = new address[](1);
resolvers[0] = resolver;
identityRegistry.addResolversFor(ein, resolvers);
if (isSnowflake) {
resolverAllowances[ein][resolver] = withdrawAllowance;
SnowflakeResolverInterface snowflakeResolver = SnowflakeResolverInterface(resolver);
if (snowflakeResolver.callOnAddition())
require(snowflakeResolver.onAddition(ein, withdrawAllowance, extraData), "Sign up failure.");
emit SnowflakeResolverAdded(ein, resolver, withdrawAllowance);
}
}
// permission changing resolver allowances for identity of msg.sender
function changeResolverAllowances(address[] memory resolvers, uint[] memory withdrawAllowances) public {
changeResolverAllowances(identityRegistry.getEIN(msg.sender), resolvers, withdrawAllowances);
}
// change resolver allowances delegated
function changeResolverAllowancesDelegated(
address approvingAddress, address[] memory resolvers, uint[] memory withdrawAllowances,
uint8 v, bytes32 r, bytes32 s
)
public
{
uint ein = identityRegistry.getEIN(approvingAddress);
uint nonce = signatureNonce[ein]++;
require(
identityRegistry.isSigned(
approvingAddress,
keccak256(
abi.encodePacked(
byte(0x19), byte(0), address(this),
"I authorize this change in Resolver allowances.",
ein, resolvers, withdrawAllowances, nonce
)
),
v, r, s
),
"Permission denied."
);
changeResolverAllowances(ein, resolvers, withdrawAllowances);
}
// common logic to change resolver allowances
function changeResolverAllowances(uint ein, address[] memory resolvers, uint[] memory withdrawAllowances) private {
require(resolvers.length == withdrawAllowances.length, "Malformed inputs.");
for (uint i; i < resolvers.length; i++) {
require(identityRegistry.isResolverFor(ein, resolvers[i]), "Identity has not set this resolver.");
resolverAllowances[ein][resolvers[i]] = withdrawAllowances[i];
emit SnowflakeResolverAllowanceChanged(ein, resolvers[i], withdrawAllowances[i]);
}
}
// permission removing a resolver for identity of msg.sender
function removeResolver(address resolver, bool isSnowflake, bytes memory extraData) public {
removeResolver(identityRegistry.getEIN(msg.sender), resolver, isSnowflake, extraData);
}
// permission removeResolverFor by signature
function removeResolverFor(
address approvingAddress, address resolver, bool isSnowflake, bytes memory extraData,
uint8 v, bytes32 r, bytes32 s, uint timestamp
)
public ensureSignatureTimeValid(timestamp)
{
uint ein = identityRegistry.getEIN(approvingAddress);
validateRemoveResolverForSignature(approvingAddress, ein, resolver, isSnowflake, extraData, v, r, s, timestamp);
removeResolver(ein, resolver, isSnowflake, extraData);
}
function validateRemoveResolverForSignature(
address approvingAddress, uint ein, address resolver, bool isSnowflake, bytes memory extraData,
uint8 v, bytes32 r, bytes32 s, uint timestamp
)
private view
{
require(
identityRegistry.isSigned(
approvingAddress,
keccak256(
abi.encodePacked(
byte(0x19), byte(0), address(this),
"I authorize that these Resolvers be removed from my Identity.",
ein, resolver, isSnowflake, extraData, timestamp
)
),
v, r, s
),
"Permission denied."
);
}
// common logic to remove resolvers
function removeResolver(uint ein, address resolver, bool isSnowflake, bytes memory extraData) private {
require(identityRegistry.isResolverFor(ein, resolver), "Identity has not yet set this resolver.");
delete resolverAllowances[ein][resolver];
if (isSnowflake) {
SnowflakeResolverInterface snowflakeResolver = SnowflakeResolverInterface(resolver);
if (snowflakeResolver.callOnRemoval())
require(snowflakeResolver.onRemoval(ein, extraData), "Removal failure.");
emit SnowflakeResolverRemoved(ein, resolver);
}
address[] memory resolvers = new address[](1);
resolvers[0] = resolver;
identityRegistry.removeResolversFor(ein, resolvers);
}
function triggerRecoveryAddressChangeFor(
address approvingAddress, address newRecoveryAddress, uint8 v, bytes32 r, bytes32 s
)
public
{
uint ein = identityRegistry.getEIN(approvingAddress);
uint nonce = signatureNonce[ein]++;
require(
identityRegistry.isSigned(
approvingAddress,
keccak256(
abi.encodePacked(
byte(0x19), byte(0), address(this),
"I authorize this change of Recovery Address.",
ein, newRecoveryAddress, nonce
)
),
v, r, s
),
"Permission denied."
);
identityRegistry.triggerRecoveryAddressChangeFor(ein, newRecoveryAddress);
}
// allow contract to receive HYDRO tokens
function receiveApproval(address sender, uint amount, address _tokenAddress, bytes memory _bytes) public {
require(msg.sender == _tokenAddress, "Malformed inputs.");
require(_tokenAddress == hydroTokenAddress, "Sender is not the HYDRO token smart contract.");
// depositing to an EIN
if (_bytes.length <= 32) {
require(hydroToken.transferFrom(sender, address(this), amount), "Unable to transfer token ownership.");
uint recipient;
if (_bytes.length < 32) {
recipient = identityRegistry.getEIN(sender);
}
else {
recipient = abi.decode(_bytes, (uint));
require(identityRegistry.identityExists(recipient), "The recipient EIN does not exist.");
}
deposits[recipient] = deposits[recipient].add(amount);
emit SnowflakeDeposit(sender, recipient, amount);
}
// transferring to a via
else {
(
bool isTransfer, address resolver, address via, uint to, bytes memory snowflakeCallBytes
) = abi.decode(_bytes, (bool, address, address, uint, bytes));
require(hydroToken.transferFrom(sender, via, amount), "Unable to transfer token ownership.");
SnowflakeViaInterface viaContract = SnowflakeViaInterface(via);
if (isTransfer) {
viaContract.snowflakeCall(resolver, to, amount, snowflakeCallBytes);
emit SnowflakeTransferToVia(resolver, via, to, amount);
} else {
address payable payableTo = address(to);
viaContract.snowflakeCall(resolver, payableTo, amount, snowflakeCallBytes);
emit SnowflakeWithdrawToVia(resolver, via, address(to), amount);
}
}
}
// transfer snowflake balance from one snowflake holder to another
function transferSnowflakeBalance(uint einTo, uint amount) public {
_transfer(identityRegistry.getEIN(msg.sender), einTo, amount);
}
// withdraw Snowflake balance to an external address
function withdrawSnowflakeBalance(address to, uint amount) public {
_withdraw(identityRegistry.getEIN(msg.sender), to, amount);
}
// allows resolvers to transfer allowance amounts to other snowflakes (throws if unsuccessful)
function transferSnowflakeBalanceFrom(uint einFrom, uint einTo, uint amount) public {
handleAllowance(einFrom, amount);
_transfer(einFrom, einTo, amount);
emit SnowflakeTransferFrom(msg.sender);
}
// allows resolvers to withdraw allowance amounts to external addresses (throws if unsuccessful)
function withdrawSnowflakeBalanceFrom(uint einFrom, address to, uint amount) public {
handleAllowance(einFrom, amount);
_withdraw(einFrom, to, amount);
emit SnowflakeWithdrawFrom(msg.sender);
}
// allows resolvers to send withdrawal amounts to arbitrary smart contracts 'to' identities (throws if unsuccessful)
function transferSnowflakeBalanceFromVia(uint einFrom, address via, uint einTo, uint amount, bytes memory _bytes)
public
{
handleAllowance(einFrom, amount);
_withdraw(einFrom, via, amount);
SnowflakeViaInterface viaContract = SnowflakeViaInterface(via);
viaContract.snowflakeCall(msg.sender, einFrom, einTo, amount, _bytes);
emit SnowflakeTransferFromVia(msg.sender, einTo);
}
// allows resolvers to send withdrawal amounts 'to' addresses via arbitrary smart contracts
function withdrawSnowflakeBalanceFromVia(
uint einFrom, address via, address payable to, uint amount, bytes memory _bytes
)
public
{
handleAllowance(einFrom, amount);
_withdraw(einFrom, via, amount);
SnowflakeViaInterface viaContract = SnowflakeViaInterface(via);
viaContract.snowflakeCall(msg.sender, einFrom, to, amount, _bytes);
emit SnowflakeWithdrawFromVia(msg.sender, to);
}
function _transfer(uint einFrom, uint einTo, uint amount) private identityExists(einTo, true) returns (bool) {
require(deposits[einFrom] >= amount, "Cannot withdraw more than the current deposit balance.");
deposits[einFrom] = deposits[einFrom].sub(amount);
deposits[einTo] = deposits[einTo].add(amount);
emit SnowflakeTransfer(einFrom, einTo, amount);
}
function _withdraw(uint einFrom, address to, uint amount) internal {
require(to != address(this), "Cannot transfer to the Snowflake smart contract itself.");
require(deposits[einFrom] >= amount, "Cannot withdraw more than the current deposit balance.");
deposits[einFrom] = deposits[einFrom].sub(amount);
require(hydroToken.transfer(to, amount), "Transfer was unsuccessful");
emit SnowflakeWithdraw(einFrom, to, amount);
}
function handleAllowance(uint einFrom, uint amount) internal {
// check that resolver-related details are correct
require(identityRegistry.isResolverFor(einFrom, msg.sender), "Resolver has not been set by from tokenholder.");
if (resolverAllowances[einFrom][msg.sender] < amount) {
emit SnowflakeInsufficientAllowance(einFrom, msg.sender, resolverAllowances[einFrom][msg.sender], amount);
revert("Insufficient Allowance");
}
resolverAllowances[einFrom][msg.sender] = resolverAllowances[einFrom][msg.sender].sub(amount);
}
// allowAndCall from msg.sender
function allowAndCall(address destination, uint amount, bytes memory data)
public returns (bytes memory returnData)
{
return allowAndCall(identityRegistry.getEIN(msg.sender), amount, destination, data);
}
// allowAndCall from approvingAddress with meta-transaction
function allowAndCallDelegated(
address destination, uint amount, bytes memory data, address approvingAddress, uint8 v, bytes32 r, bytes32 s
)
public returns (bytes memory returnData)
{
uint ein = identityRegistry.getEIN(approvingAddress);
uint nonce = signatureNonce[ein]++;
validateAllowAndCallDelegatedSignature(approvingAddress, ein, destination, amount, data, nonce, v, r, s);
return allowAndCall(ein, amount, destination, data);
}
function validateAllowAndCallDelegatedSignature(
address approvingAddress, uint ein, address destination, uint amount, bytes memory data, uint nonce,
uint8 v, bytes32 r, bytes32 s
)
private view
{
require(
identityRegistry.isSigned(
approvingAddress,
keccak256(
abi.encodePacked(
byte(0x19), byte(0), address(this),
"I authorize this allow and call.", ein, destination, amount, data, nonce
)
),
v, r, s
),
"Permission denied."
);
}
// internal logic for allowAndCall
function allowAndCall(uint ein, uint amount, address destination, bytes memory data)
private returns (bytes memory returnData)
{
// check that resolver-related details are correct
require(identityRegistry.isResolverFor(ein, destination), "Destination has not been set by from tokenholder.");
if (amount != 0) {
resolverAllowances[ein][destination] = resolverAllowances[ein][destination].add(amount);
}
// solium-disable-next-line security/no-low-level-calls
(bool success, bytes memory _returnData) = destination.call(data);
require(success, "Call was not successful.");
return _returnData;
}
// events
event SnowflakeProvidersUpgraded(uint indexed ein, address[] newProviders, address[] oldProviders, address approvingAddress);
event SnowflakeResolverAdded(uint indexed ein, address indexed resolver, uint withdrawAllowance);
event SnowflakeResolverAllowanceChanged(uint indexed ein, address indexed resolver, uint withdrawAllowance);
event SnowflakeResolverRemoved(uint indexed ein, address indexed resolver);
event SnowflakeDeposit(address indexed from, uint indexed einTo, uint amount);
event SnowflakeTransfer(uint indexed einFrom, uint indexed einTo, uint amount);
event SnowflakeWithdraw(uint indexed einFrom, address indexed to, uint amount);
event SnowflakeTransferFrom(address indexed resolverFrom);
event SnowflakeWithdrawFrom(address indexed resolverFrom);
event SnowflakeTransferFromVia(address indexed resolverFrom, uint indexed einTo);
event SnowflakeWithdrawFromVia(address indexed resolverFrom, address indexed to);
event SnowflakeTransferToVia(address indexed resolverFrom, address indexed via, uint indexed einTo, uint amount);
event SnowflakeWithdrawToVia(address indexed resolverFrom, address indexed via, address indexed to, uint amount);
event SnowflakeInsufficientAllowance(
uint indexed ein, address indexed resolver, uint currentAllowance, uint requestedWithdraw
);
}
| mapping of EIN to hydro token deposits mapping from EIN to resolver to allowance SC variables signature variables | contract Snowflake is Ownable {
using SafeMath for uint;
mapping (uint => uint) public deposits;
mapping (uint => mapping (address => uint)) public resolverAllowances;
address public identityRegistryAddress;
IdentityRegistryInterface private identityRegistry;
address public hydroTokenAddress;
HydroInterface private hydroToken;
address public clientRaindropAddress;
ClientRaindropInterface private clientRaindrop;
uint public signatureTimeout = 1 days;
mapping (uint => uint) public signatureNonce;
constructor (address _identityRegistryAddress, address _hydroTokenAddress) public {
setAddresses(_identityRegistryAddress, _hydroTokenAddress);
}
modifier identityExists(uint ein, bool check) {
require(identityRegistry.identityExists(ein) == check, "The EIN does not exist.");
_;
}
modifier ensureSignatureTimeValid(uint timestamp) {
require(
block.timestamp >= timestamp && block.timestamp < timestamp + signatureTimeout, "Timestamp is not valid."
);
_;
}
function setAddresses(address _identityRegistryAddress, address _hydroTokenAddress) public onlyOwner {
identityRegistryAddress = _identityRegistryAddress;
identityRegistry = IdentityRegistryInterface(identityRegistryAddress);
hydroTokenAddress = _hydroTokenAddress;
hydroToken = HydroInterface(hydroTokenAddress);
}
function setClientRaindropAddress(address _clientRaindropAddress) public onlyOwner {
clientRaindropAddress = _clientRaindropAddress;
clientRaindrop = ClientRaindropInterface(clientRaindropAddress);
}
function createIdentityDelegated(
address recoveryAddress, address associatedAddress, address[] memory providers, string memory casedHydroId,
uint8 v, bytes32 r, bytes32 s, uint timestamp
)
public returns (uint ein)
{
address[] memory _providers = new address[](providers.length + 1);
_providers[0] = address(this);
for (uint i; i < providers.length; i++) {
_providers[i + 1] = providers[i];
}
uint _ein = identityRegistry.createIdentityDelegated(
recoveryAddress, associatedAddress, _providers, new address[](0), v, r, s, timestamp
);
_addResolver(_ein, clientRaindropAddress, true, 0, abi.encode(associatedAddress, casedHydroId));
return _ein;
}
function createIdentityDelegated(
address recoveryAddress, address associatedAddress, address[] memory providers, string memory casedHydroId,
uint8 v, bytes32 r, bytes32 s, uint timestamp
)
public returns (uint ein)
{
address[] memory _providers = new address[](providers.length + 1);
_providers[0] = address(this);
for (uint i; i < providers.length; i++) {
_providers[i + 1] = providers[i];
}
uint _ein = identityRegistry.createIdentityDelegated(
recoveryAddress, associatedAddress, _providers, new address[](0), v, r, s, timestamp
);
_addResolver(_ein, clientRaindropAddress, true, 0, abi.encode(associatedAddress, casedHydroId));
return _ein;
}
function addProvidersFor(
address approvingAddress, address[] memory providers, uint8 v, bytes32 r, bytes32 s, uint timestamp
)
public ensureSignatureTimeValid(timestamp)
{
uint ein = identityRegistry.getEIN(approvingAddress);
require(
identityRegistry.isSigned(
approvingAddress,
keccak256(
abi.encodePacked(
byte(0x19), byte(0), address(this),
"I authorize that these Providers be added to my Identity.",
ein, providers, timestamp
)
),
v, r, s
),
"Permission denied."
);
identityRegistry.addProvidersFor(ein, providers);
}
function removeProvidersFor(
address approvingAddress, address[] memory providers, uint8 v, bytes32 r, bytes32 s, uint timestamp
)
public ensureSignatureTimeValid(timestamp)
{
uint ein = identityRegistry.getEIN(approvingAddress);
require(
identityRegistry.isSigned(
approvingAddress,
keccak256(
abi.encodePacked(
byte(0x19), byte(0), address(this),
"I authorize that these Providers be removed from my Identity.",
ein, providers, timestamp
)
),
v, r, s
),
"Permission denied."
);
identityRegistry.removeProvidersFor(ein, providers);
}
function upgradeProvidersFor(
address approvingAddress, address[] memory newProviders, address[] memory oldProviders,
uint8[2] memory v, bytes32[2] memory r, bytes32[2] memory s, uint[2] memory timestamp
)
public
{
addProvidersFor(approvingAddress, newProviders, v[0], r[0], s[0], timestamp[0]);
removeProvidersFor(approvingAddress, oldProviders, v[1], r[1], s[1], timestamp[1]);
uint ein = identityRegistry.getEIN(approvingAddress);
emit SnowflakeProvidersUpgraded(ein, newProviders, oldProviders, approvingAddress);
}
function addResolver(address resolver, bool isSnowflake, uint withdrawAllowance, bytes memory extraData) public {
_addResolver(identityRegistry.getEIN(msg.sender), resolver, isSnowflake, withdrawAllowance, extraData);
}
function addResolverAsProvider(
uint ein, address resolver, bool isSnowflake, uint withdrawAllowance, bytes memory extraData
)
public
{
require(identityRegistry.isProviderFor(ein, msg.sender), "The msg.sender is not a Provider for the passed EIN");
_addResolver(ein, resolver, isSnowflake, withdrawAllowance, extraData);
}
function addResolverFor(
address approvingAddress, address resolver, bool isSnowflake, uint withdrawAllowance, bytes memory extraData,
uint8 v, bytes32 r, bytes32 s, uint timestamp
)
public
{
uint ein = identityRegistry.getEIN(approvingAddress);
validateAddResolverForSignature(
approvingAddress, ein, resolver, isSnowflake, withdrawAllowance, extraData, v, r, s, timestamp
);
_addResolver(ein, resolver, isSnowflake, withdrawAllowance, extraData);
}
function validateAddResolverForSignature(
address approvingAddress, uint ein,
address resolver, bool isSnowflake, uint withdrawAllowance, bytes memory extraData,
uint8 v, bytes32 r, bytes32 s, uint timestamp
)
private view ensureSignatureTimeValid(timestamp)
{
require(
identityRegistry.isSigned(
approvingAddress,
keccak256(
abi.encodePacked(
byte(0x19), byte(0), address(this),
"I authorize that this resolver be added to my Identity.",
ein, resolver, isSnowflake, withdrawAllowance, extraData, timestamp
)
),
v, r, s
),
"Permission denied."
);
}
function _addResolver(uint ein, address resolver, bool isSnowflake, uint withdrawAllowance, bytes memory extraData)
private
{
require(!identityRegistry.isResolverFor(ein, resolver), "Identity has already set this resolver.");
address[] memory resolvers = new address[](1);
resolvers[0] = resolver;
identityRegistry.addResolversFor(ein, resolvers);
if (isSnowflake) {
resolverAllowances[ein][resolver] = withdrawAllowance;
SnowflakeResolverInterface snowflakeResolver = SnowflakeResolverInterface(resolver);
if (snowflakeResolver.callOnAddition())
require(snowflakeResolver.onAddition(ein, withdrawAllowance, extraData), "Sign up failure.");
emit SnowflakeResolverAdded(ein, resolver, withdrawAllowance);
}
}
function _addResolver(uint ein, address resolver, bool isSnowflake, uint withdrawAllowance, bytes memory extraData)
private
{
require(!identityRegistry.isResolverFor(ein, resolver), "Identity has already set this resolver.");
address[] memory resolvers = new address[](1);
resolvers[0] = resolver;
identityRegistry.addResolversFor(ein, resolvers);
if (isSnowflake) {
resolverAllowances[ein][resolver] = withdrawAllowance;
SnowflakeResolverInterface snowflakeResolver = SnowflakeResolverInterface(resolver);
if (snowflakeResolver.callOnAddition())
require(snowflakeResolver.onAddition(ein, withdrawAllowance, extraData), "Sign up failure.");
emit SnowflakeResolverAdded(ein, resolver, withdrawAllowance);
}
}
function changeResolverAllowances(address[] memory resolvers, uint[] memory withdrawAllowances) public {
changeResolverAllowances(identityRegistry.getEIN(msg.sender), resolvers, withdrawAllowances);
}
function changeResolverAllowancesDelegated(
address approvingAddress, address[] memory resolvers, uint[] memory withdrawAllowances,
uint8 v, bytes32 r, bytes32 s
)
public
{
uint ein = identityRegistry.getEIN(approvingAddress);
uint nonce = signatureNonce[ein]++;
require(
identityRegistry.isSigned(
approvingAddress,
keccak256(
abi.encodePacked(
byte(0x19), byte(0), address(this),
"I authorize this change in Resolver allowances.",
ein, resolvers, withdrawAllowances, nonce
)
),
v, r, s
),
"Permission denied."
);
changeResolverAllowances(ein, resolvers, withdrawAllowances);
}
function changeResolverAllowances(uint ein, address[] memory resolvers, uint[] memory withdrawAllowances) private {
require(resolvers.length == withdrawAllowances.length, "Malformed inputs.");
for (uint i; i < resolvers.length; i++) {
require(identityRegistry.isResolverFor(ein, resolvers[i]), "Identity has not set this resolver.");
resolverAllowances[ein][resolvers[i]] = withdrawAllowances[i];
emit SnowflakeResolverAllowanceChanged(ein, resolvers[i], withdrawAllowances[i]);
}
}
function changeResolverAllowances(uint ein, address[] memory resolvers, uint[] memory withdrawAllowances) private {
require(resolvers.length == withdrawAllowances.length, "Malformed inputs.");
for (uint i; i < resolvers.length; i++) {
require(identityRegistry.isResolverFor(ein, resolvers[i]), "Identity has not set this resolver.");
resolverAllowances[ein][resolvers[i]] = withdrawAllowances[i];
emit SnowflakeResolverAllowanceChanged(ein, resolvers[i], withdrawAllowances[i]);
}
}
function removeResolver(address resolver, bool isSnowflake, bytes memory extraData) public {
removeResolver(identityRegistry.getEIN(msg.sender), resolver, isSnowflake, extraData);
}
function removeResolverFor(
address approvingAddress, address resolver, bool isSnowflake, bytes memory extraData,
uint8 v, bytes32 r, bytes32 s, uint timestamp
)
public ensureSignatureTimeValid(timestamp)
{
uint ein = identityRegistry.getEIN(approvingAddress);
validateRemoveResolverForSignature(approvingAddress, ein, resolver, isSnowflake, extraData, v, r, s, timestamp);
removeResolver(ein, resolver, isSnowflake, extraData);
}
function validateRemoveResolverForSignature(
address approvingAddress, uint ein, address resolver, bool isSnowflake, bytes memory extraData,
uint8 v, bytes32 r, bytes32 s, uint timestamp
)
private view
{
require(
identityRegistry.isSigned(
approvingAddress,
keccak256(
abi.encodePacked(
byte(0x19), byte(0), address(this),
"I authorize that these Resolvers be removed from my Identity.",
ein, resolver, isSnowflake, extraData, timestamp
)
),
v, r, s
),
"Permission denied."
);
}
function removeResolver(uint ein, address resolver, bool isSnowflake, bytes memory extraData) private {
require(identityRegistry.isResolverFor(ein, resolver), "Identity has not yet set this resolver.");
delete resolverAllowances[ein][resolver];
if (isSnowflake) {
SnowflakeResolverInterface snowflakeResolver = SnowflakeResolverInterface(resolver);
if (snowflakeResolver.callOnRemoval())
require(snowflakeResolver.onRemoval(ein, extraData), "Removal failure.");
emit SnowflakeResolverRemoved(ein, resolver);
}
address[] memory resolvers = new address[](1);
resolvers[0] = resolver;
identityRegistry.removeResolversFor(ein, resolvers);
}
function removeResolver(uint ein, address resolver, bool isSnowflake, bytes memory extraData) private {
require(identityRegistry.isResolverFor(ein, resolver), "Identity has not yet set this resolver.");
delete resolverAllowances[ein][resolver];
if (isSnowflake) {
SnowflakeResolverInterface snowflakeResolver = SnowflakeResolverInterface(resolver);
if (snowflakeResolver.callOnRemoval())
require(snowflakeResolver.onRemoval(ein, extraData), "Removal failure.");
emit SnowflakeResolverRemoved(ein, resolver);
}
address[] memory resolvers = new address[](1);
resolvers[0] = resolver;
identityRegistry.removeResolversFor(ein, resolvers);
}
function triggerRecoveryAddressChangeFor(
address approvingAddress, address newRecoveryAddress, uint8 v, bytes32 r, bytes32 s
)
public
{
uint ein = identityRegistry.getEIN(approvingAddress);
uint nonce = signatureNonce[ein]++;
require(
identityRegistry.isSigned(
approvingAddress,
keccak256(
abi.encodePacked(
byte(0x19), byte(0), address(this),
"I authorize this change of Recovery Address.",
ein, newRecoveryAddress, nonce
)
),
v, r, s
),
"Permission denied."
);
identityRegistry.triggerRecoveryAddressChangeFor(ein, newRecoveryAddress);
}
function receiveApproval(address sender, uint amount, address _tokenAddress, bytes memory _bytes) public {
require(msg.sender == _tokenAddress, "Malformed inputs.");
require(_tokenAddress == hydroTokenAddress, "Sender is not the HYDRO token smart contract.");
if (_bytes.length <= 32) {
require(hydroToken.transferFrom(sender, address(this), amount), "Unable to transfer token ownership.");
uint recipient;
if (_bytes.length < 32) {
recipient = identityRegistry.getEIN(sender);
}
else {
recipient = abi.decode(_bytes, (uint));
require(identityRegistry.identityExists(recipient), "The recipient EIN does not exist.");
}
deposits[recipient] = deposits[recipient].add(amount);
emit SnowflakeDeposit(sender, recipient, amount);
}
else {
(
bool isTransfer, address resolver, address via, uint to, bytes memory snowflakeCallBytes
) = abi.decode(_bytes, (bool, address, address, uint, bytes));
require(hydroToken.transferFrom(sender, via, amount), "Unable to transfer token ownership.");
SnowflakeViaInterface viaContract = SnowflakeViaInterface(via);
if (isTransfer) {
viaContract.snowflakeCall(resolver, to, amount, snowflakeCallBytes);
emit SnowflakeTransferToVia(resolver, via, to, amount);
address payable payableTo = address(to);
viaContract.snowflakeCall(resolver, payableTo, amount, snowflakeCallBytes);
emit SnowflakeWithdrawToVia(resolver, via, address(to), amount);
}
}
}
function receiveApproval(address sender, uint amount, address _tokenAddress, bytes memory _bytes) public {
require(msg.sender == _tokenAddress, "Malformed inputs.");
require(_tokenAddress == hydroTokenAddress, "Sender is not the HYDRO token smart contract.");
if (_bytes.length <= 32) {
require(hydroToken.transferFrom(sender, address(this), amount), "Unable to transfer token ownership.");
uint recipient;
if (_bytes.length < 32) {
recipient = identityRegistry.getEIN(sender);
}
else {
recipient = abi.decode(_bytes, (uint));
require(identityRegistry.identityExists(recipient), "The recipient EIN does not exist.");
}
deposits[recipient] = deposits[recipient].add(amount);
emit SnowflakeDeposit(sender, recipient, amount);
}
else {
(
bool isTransfer, address resolver, address via, uint to, bytes memory snowflakeCallBytes
) = abi.decode(_bytes, (bool, address, address, uint, bytes));
require(hydroToken.transferFrom(sender, via, amount), "Unable to transfer token ownership.");
SnowflakeViaInterface viaContract = SnowflakeViaInterface(via);
if (isTransfer) {
viaContract.snowflakeCall(resolver, to, amount, snowflakeCallBytes);
emit SnowflakeTransferToVia(resolver, via, to, amount);
address payable payableTo = address(to);
viaContract.snowflakeCall(resolver, payableTo, amount, snowflakeCallBytes);
emit SnowflakeWithdrawToVia(resolver, via, address(to), amount);
}
}
}
function receiveApproval(address sender, uint amount, address _tokenAddress, bytes memory _bytes) public {
require(msg.sender == _tokenAddress, "Malformed inputs.");
require(_tokenAddress == hydroTokenAddress, "Sender is not the HYDRO token smart contract.");
if (_bytes.length <= 32) {
require(hydroToken.transferFrom(sender, address(this), amount), "Unable to transfer token ownership.");
uint recipient;
if (_bytes.length < 32) {
recipient = identityRegistry.getEIN(sender);
}
else {
recipient = abi.decode(_bytes, (uint));
require(identityRegistry.identityExists(recipient), "The recipient EIN does not exist.");
}
deposits[recipient] = deposits[recipient].add(amount);
emit SnowflakeDeposit(sender, recipient, amount);
}
else {
(
bool isTransfer, address resolver, address via, uint to, bytes memory snowflakeCallBytes
) = abi.decode(_bytes, (bool, address, address, uint, bytes));
require(hydroToken.transferFrom(sender, via, amount), "Unable to transfer token ownership.");
SnowflakeViaInterface viaContract = SnowflakeViaInterface(via);
if (isTransfer) {
viaContract.snowflakeCall(resolver, to, amount, snowflakeCallBytes);
emit SnowflakeTransferToVia(resolver, via, to, amount);
address payable payableTo = address(to);
viaContract.snowflakeCall(resolver, payableTo, amount, snowflakeCallBytes);
emit SnowflakeWithdrawToVia(resolver, via, address(to), amount);
}
}
}
function receiveApproval(address sender, uint amount, address _tokenAddress, bytes memory _bytes) public {
require(msg.sender == _tokenAddress, "Malformed inputs.");
require(_tokenAddress == hydroTokenAddress, "Sender is not the HYDRO token smart contract.");
if (_bytes.length <= 32) {
require(hydroToken.transferFrom(sender, address(this), amount), "Unable to transfer token ownership.");
uint recipient;
if (_bytes.length < 32) {
recipient = identityRegistry.getEIN(sender);
}
else {
recipient = abi.decode(_bytes, (uint));
require(identityRegistry.identityExists(recipient), "The recipient EIN does not exist.");
}
deposits[recipient] = deposits[recipient].add(amount);
emit SnowflakeDeposit(sender, recipient, amount);
}
else {
(
bool isTransfer, address resolver, address via, uint to, bytes memory snowflakeCallBytes
) = abi.decode(_bytes, (bool, address, address, uint, bytes));
require(hydroToken.transferFrom(sender, via, amount), "Unable to transfer token ownership.");
SnowflakeViaInterface viaContract = SnowflakeViaInterface(via);
if (isTransfer) {
viaContract.snowflakeCall(resolver, to, amount, snowflakeCallBytes);
emit SnowflakeTransferToVia(resolver, via, to, amount);
address payable payableTo = address(to);
viaContract.snowflakeCall(resolver, payableTo, amount, snowflakeCallBytes);
emit SnowflakeWithdrawToVia(resolver, via, address(to), amount);
}
}
}
function receiveApproval(address sender, uint amount, address _tokenAddress, bytes memory _bytes) public {
require(msg.sender == _tokenAddress, "Malformed inputs.");
require(_tokenAddress == hydroTokenAddress, "Sender is not the HYDRO token smart contract.");
if (_bytes.length <= 32) {
require(hydroToken.transferFrom(sender, address(this), amount), "Unable to transfer token ownership.");
uint recipient;
if (_bytes.length < 32) {
recipient = identityRegistry.getEIN(sender);
}
else {
recipient = abi.decode(_bytes, (uint));
require(identityRegistry.identityExists(recipient), "The recipient EIN does not exist.");
}
deposits[recipient] = deposits[recipient].add(amount);
emit SnowflakeDeposit(sender, recipient, amount);
}
else {
(
bool isTransfer, address resolver, address via, uint to, bytes memory snowflakeCallBytes
) = abi.decode(_bytes, (bool, address, address, uint, bytes));
require(hydroToken.transferFrom(sender, via, amount), "Unable to transfer token ownership.");
SnowflakeViaInterface viaContract = SnowflakeViaInterface(via);
if (isTransfer) {
viaContract.snowflakeCall(resolver, to, amount, snowflakeCallBytes);
emit SnowflakeTransferToVia(resolver, via, to, amount);
address payable payableTo = address(to);
viaContract.snowflakeCall(resolver, payableTo, amount, snowflakeCallBytes);
emit SnowflakeWithdrawToVia(resolver, via, address(to), amount);
}
}
}
function receiveApproval(address sender, uint amount, address _tokenAddress, bytes memory _bytes) public {
require(msg.sender == _tokenAddress, "Malformed inputs.");
require(_tokenAddress == hydroTokenAddress, "Sender is not the HYDRO token smart contract.");
if (_bytes.length <= 32) {
require(hydroToken.transferFrom(sender, address(this), amount), "Unable to transfer token ownership.");
uint recipient;
if (_bytes.length < 32) {
recipient = identityRegistry.getEIN(sender);
}
else {
recipient = abi.decode(_bytes, (uint));
require(identityRegistry.identityExists(recipient), "The recipient EIN does not exist.");
}
deposits[recipient] = deposits[recipient].add(amount);
emit SnowflakeDeposit(sender, recipient, amount);
}
else {
(
bool isTransfer, address resolver, address via, uint to, bytes memory snowflakeCallBytes
) = abi.decode(_bytes, (bool, address, address, uint, bytes));
require(hydroToken.transferFrom(sender, via, amount), "Unable to transfer token ownership.");
SnowflakeViaInterface viaContract = SnowflakeViaInterface(via);
if (isTransfer) {
viaContract.snowflakeCall(resolver, to, amount, snowflakeCallBytes);
emit SnowflakeTransferToVia(resolver, via, to, amount);
address payable payableTo = address(to);
viaContract.snowflakeCall(resolver, payableTo, amount, snowflakeCallBytes);
emit SnowflakeWithdrawToVia(resolver, via, address(to), amount);
}
}
}
} else {
function transferSnowflakeBalance(uint einTo, uint amount) public {
_transfer(identityRegistry.getEIN(msg.sender), einTo, amount);
}
function withdrawSnowflakeBalance(address to, uint amount) public {
_withdraw(identityRegistry.getEIN(msg.sender), to, amount);
}
function transferSnowflakeBalanceFrom(uint einFrom, uint einTo, uint amount) public {
handleAllowance(einFrom, amount);
_transfer(einFrom, einTo, amount);
emit SnowflakeTransferFrom(msg.sender);
}
function withdrawSnowflakeBalanceFrom(uint einFrom, address to, uint amount) public {
handleAllowance(einFrom, amount);
_withdraw(einFrom, to, amount);
emit SnowflakeWithdrawFrom(msg.sender);
}
function transferSnowflakeBalanceFromVia(uint einFrom, address via, uint einTo, uint amount, bytes memory _bytes)
public
{
handleAllowance(einFrom, amount);
_withdraw(einFrom, via, amount);
SnowflakeViaInterface viaContract = SnowflakeViaInterface(via);
viaContract.snowflakeCall(msg.sender, einFrom, einTo, amount, _bytes);
emit SnowflakeTransferFromVia(msg.sender, einTo);
}
function withdrawSnowflakeBalanceFromVia(
uint einFrom, address via, address payable to, uint amount, bytes memory _bytes
)
public
{
handleAllowance(einFrom, amount);
_withdraw(einFrom, via, amount);
SnowflakeViaInterface viaContract = SnowflakeViaInterface(via);
viaContract.snowflakeCall(msg.sender, einFrom, to, amount, _bytes);
emit SnowflakeWithdrawFromVia(msg.sender, to);
}
function _transfer(uint einFrom, uint einTo, uint amount) private identityExists(einTo, true) returns (bool) {
require(deposits[einFrom] >= amount, "Cannot withdraw more than the current deposit balance.");
deposits[einFrom] = deposits[einFrom].sub(amount);
deposits[einTo] = deposits[einTo].add(amount);
emit SnowflakeTransfer(einFrom, einTo, amount);
}
function _withdraw(uint einFrom, address to, uint amount) internal {
require(to != address(this), "Cannot transfer to the Snowflake smart contract itself.");
require(deposits[einFrom] >= amount, "Cannot withdraw more than the current deposit balance.");
deposits[einFrom] = deposits[einFrom].sub(amount);
require(hydroToken.transfer(to, amount), "Transfer was unsuccessful");
emit SnowflakeWithdraw(einFrom, to, amount);
}
function handleAllowance(uint einFrom, uint amount) internal {
require(identityRegistry.isResolverFor(einFrom, msg.sender), "Resolver has not been set by from tokenholder.");
if (resolverAllowances[einFrom][msg.sender] < amount) {
emit SnowflakeInsufficientAllowance(einFrom, msg.sender, resolverAllowances[einFrom][msg.sender], amount);
revert("Insufficient Allowance");
}
resolverAllowances[einFrom][msg.sender] = resolverAllowances[einFrom][msg.sender].sub(amount);
}
function handleAllowance(uint einFrom, uint amount) internal {
require(identityRegistry.isResolverFor(einFrom, msg.sender), "Resolver has not been set by from tokenholder.");
if (resolverAllowances[einFrom][msg.sender] < amount) {
emit SnowflakeInsufficientAllowance(einFrom, msg.sender, resolverAllowances[einFrom][msg.sender], amount);
revert("Insufficient Allowance");
}
resolverAllowances[einFrom][msg.sender] = resolverAllowances[einFrom][msg.sender].sub(amount);
}
function allowAndCall(address destination, uint amount, bytes memory data)
public returns (bytes memory returnData)
{
return allowAndCall(identityRegistry.getEIN(msg.sender), amount, destination, data);
}
function allowAndCallDelegated(
address destination, uint amount, bytes memory data, address approvingAddress, uint8 v, bytes32 r, bytes32 s
)
public returns (bytes memory returnData)
{
uint ein = identityRegistry.getEIN(approvingAddress);
uint nonce = signatureNonce[ein]++;
validateAllowAndCallDelegatedSignature(approvingAddress, ein, destination, amount, data, nonce, v, r, s);
return allowAndCall(ein, amount, destination, data);
}
function validateAllowAndCallDelegatedSignature(
address approvingAddress, uint ein, address destination, uint amount, bytes memory data, uint nonce,
uint8 v, bytes32 r, bytes32 s
)
private view
{
require(
identityRegistry.isSigned(
approvingAddress,
keccak256(
abi.encodePacked(
byte(0x19), byte(0), address(this),
"I authorize this allow and call.", ein, destination, amount, data, nonce
)
),
v, r, s
),
"Permission denied."
);
}
function allowAndCall(uint ein, uint amount, address destination, bytes memory data)
private returns (bytes memory returnData)
{
require(identityRegistry.isResolverFor(ein, destination), "Destination has not been set by from tokenholder.");
if (amount != 0) {
resolverAllowances[ein][destination] = resolverAllowances[ein][destination].add(amount);
}
require(success, "Call was not successful.");
return _returnData;
}
event SnowflakeResolverAdded(uint indexed ein, address indexed resolver, uint withdrawAllowance);
event SnowflakeResolverAllowanceChanged(uint indexed ein, address indexed resolver, uint withdrawAllowance);
event SnowflakeResolverRemoved(uint indexed ein, address indexed resolver);
event SnowflakeDeposit(address indexed from, uint indexed einTo, uint amount);
event SnowflakeTransfer(uint indexed einFrom, uint indexed einTo, uint amount);
event SnowflakeWithdraw(uint indexed einFrom, address indexed to, uint amount);
event SnowflakeTransferFrom(address indexed resolverFrom);
event SnowflakeWithdrawFrom(address indexed resolverFrom);
event SnowflakeTransferFromVia(address indexed resolverFrom, uint indexed einTo);
event SnowflakeWithdrawFromVia(address indexed resolverFrom, address indexed to);
event SnowflakeTransferToVia(address indexed resolverFrom, address indexed via, uint indexed einTo, uint amount);
event SnowflakeWithdrawToVia(address indexed resolverFrom, address indexed via, address indexed to, uint amount);
event SnowflakeInsufficientAllowance(
uint indexed ein, address indexed resolver, uint currentAllowance, uint requestedWithdraw
);
function allowAndCall(uint ein, uint amount, address destination, bytes memory data)
private returns (bytes memory returnData)
{
require(identityRegistry.isResolverFor(ein, destination), "Destination has not been set by from tokenholder.");
if (amount != 0) {
resolverAllowances[ein][destination] = resolverAllowances[ein][destination].add(amount);
}
require(success, "Call was not successful.");
return _returnData;
}
event SnowflakeResolverAdded(uint indexed ein, address indexed resolver, uint withdrawAllowance);
event SnowflakeResolverAllowanceChanged(uint indexed ein, address indexed resolver, uint withdrawAllowance);
event SnowflakeResolverRemoved(uint indexed ein, address indexed resolver);
event SnowflakeDeposit(address indexed from, uint indexed einTo, uint amount);
event SnowflakeTransfer(uint indexed einFrom, uint indexed einTo, uint amount);
event SnowflakeWithdraw(uint indexed einFrom, address indexed to, uint amount);
event SnowflakeTransferFrom(address indexed resolverFrom);
event SnowflakeWithdrawFrom(address indexed resolverFrom);
event SnowflakeTransferFromVia(address indexed resolverFrom, uint indexed einTo);
event SnowflakeWithdrawFromVia(address indexed resolverFrom, address indexed to);
event SnowflakeTransferToVia(address indexed resolverFrom, address indexed via, uint indexed einTo, uint amount);
event SnowflakeWithdrawToVia(address indexed resolverFrom, address indexed via, address indexed to, uint amount);
event SnowflakeInsufficientAllowance(
uint indexed ein, address indexed resolver, uint currentAllowance, uint requestedWithdraw
);
(bool success, bytes memory _returnData) = destination.call(data);
event SnowflakeProvidersUpgraded(uint indexed ein, address[] newProviders, address[] oldProviders, address approvingAddress);
}
| 12,556,755 | [
1,
6770,
434,
512,
706,
358,
4855,
9005,
1147,
443,
917,
1282,
2874,
628,
512,
706,
358,
5039,
358,
1699,
1359,
8795,
3152,
3372,
3152,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
16351,
31040,
30451,
353,
14223,
6914,
288,
203,
565,
1450,
14060,
10477,
364,
2254,
31,
203,
203,
565,
2874,
261,
11890,
516,
2254,
13,
1071,
443,
917,
1282,
31,
203,
565,
2874,
261,
11890,
516,
2874,
261,
2867,
516,
2254,
3719,
1071,
5039,
7009,
6872,
31,
203,
203,
565,
1758,
1071,
4215,
4243,
1887,
31,
203,
565,
7808,
4243,
1358,
3238,
4215,
4243,
31,
203,
565,
1758,
1071,
4855,
9005,
1345,
1887,
31,
203,
565,
14881,
9005,
1358,
3238,
4855,
9005,
1345,
31,
203,
565,
1758,
1071,
1004,
54,
530,
7285,
1887,
31,
203,
565,
2445,
54,
530,
7285,
1358,
3238,
1004,
54,
530,
7285,
31,
203,
203,
565,
2254,
1071,
3372,
2694,
273,
404,
4681,
31,
203,
565,
2874,
261,
11890,
516,
2254,
13,
1071,
3372,
13611,
31,
203,
203,
565,
3885,
261,
2867,
389,
10781,
4243,
1887,
16,
1758,
389,
18112,
9005,
1345,
1887,
13,
1071,
288,
203,
3639,
444,
7148,
24899,
10781,
4243,
1887,
16,
389,
18112,
9005,
1345,
1887,
1769,
203,
565,
289,
203,
203,
565,
9606,
4215,
4002,
12,
11890,
16315,
16,
1426,
866,
13,
288,
203,
3639,
2583,
12,
10781,
4243,
18,
10781,
4002,
12,
13685,
13,
422,
866,
16,
315,
1986,
512,
706,
1552,
486,
1005,
1199,
1769,
203,
3639,
389,
31,
203,
565,
289,
203,
203,
565,
9606,
3387,
5374,
950,
1556,
12,
11890,
2858,
13,
288,
203,
3639,
2583,
12,
203,
5411,
1203,
18,
5508,
1545,
2858,
597,
1203,
18,
5508,
411,
2858,
397,
3372,
2694,
16,
315,
4921,
353,
486,
923,
1199,
203,
3639,
2
] |
// Dependency file: @openzeppelin/contracts/GSN/Context.sol
// pragma solidity ^0.5.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 Context {
// Empty internal constructor, to prevent people from mistakenly deploying
// an instance of this contract, which should be used via inheritance.
constructor () internal { }
// solhint-disable-previous-line no-empty-blocks
function _msgSender() internal view returns (address payable) {
return msg.sender;
}
function _msgData() internal view returns (bytes memory) {
this; // silence state mutability warning without generating bytecode - see https://github.com/ethereum/solidity/issues/2691
return msg.data;
}
}
// Dependency file: contracts/interfaces/IKULAPDex.sol
// pragma solidity 0.5.17;
// import "../helper/ERC20Interface.sol";
// import "./IKULAPTradingProxy.sol";
interface IKULAPDex {
// /**
// * @dev when new trade occure (and success), this event will be boardcast.
// * @param _src Source token
// * @param _srcAmount amount of source tokens
// * @param _dest Destination token
// * @return _destAmount: amount of actual destination tokens
// */
// event Trade(ERC20 _src, uint256 _srcAmount, ERC20 _dest, uint256 _destAmount);
/**
* @notice use token address 0xeee...eee for ether
* @dev makes a trade between src and dest token by tradingProxyIndex
* Ex1: trade 0.5 ETH -> EOS
* 0, "0xeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeee", "500000000000000000", "0xd3c64BbA75859Eb808ACE6F2A6048ecdb2d70817", "21003850000000000000"
* Ex2: trade 30 EOS -> ETH
* 0, "0xd3c64BbA75859Eb808ACE6F2A6048ecdb2d70817", "30000000000000000000", "0xeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeee", "740825000000000000"
* @param tradingProxyIndex index of trading proxy
* @param src Source token
* @param srcAmount amount of source tokens
* @param dest Destination token
* @param minDestAmount minimun destination amount
* @param partnerIndex index of partnership for revenue sharing
* @return amount of actual destination tokens
*/
function trade(
uint256 tradingProxyIndex,
ERC20 src,
uint256 srcAmount,
ERC20 dest,
uint256 minDestAmount,
uint256 partnerIndex
)
external
payable
returns(uint256);
/**
* @notice use token address 0xeee...eee for ether
* @dev makes a trade with multiple routes ex. UNI -> ETH -> DAI
* Ex: trade 50 UNI -> ETH -> DAI
* Step1: trade 50 UNI -> ETH
* Step2: trade xx ETH -> DAI
* srcAmount: 50 * 1e18
* routes: [0, 1]
* srcTokens: [0x1f9840a85d5aF5bf1D1762F925BDADdC4201F984, 0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE]
* destTokens: [0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE, 0x6B175474E89094C44Da98b954EedeAC495271d0F]
* @param srcAmount amount of source tokens
* @param minDestAmount minimun destination amount
* @param routes Trading paths
* @param srcTokens all source of token pairs
* @param destTokens all destination of token pairs
* @param partnerIndex index of partnership for revenue sharing
* @return amount of actual destination tokens
*/
function tradeRoutes(
uint256 srcAmount,
uint256 minDestAmount,
uint256[] calldata routes,
ERC20[] calldata srcTokens,
ERC20[] calldata destTokens,
uint256 partnerIndex
)
external
payable
returns(uint256);
/**
* @notice use token address 0xeee...eee for ether
* @dev makes a trade with split volumes to multiple-routes ex. UNI -> ETH (5%, 15% and 80%)
* @param routes Trading paths
* @param src Source token
* @param srcAmounts amount of source tokens
* @param dest Destination token
* @param minDestAmount minimun destination amount
* @param partnerIndex index of partnership for revenue sharing
* @return amount of actual destination tokens
*/
function splitTrades(
uint256[] calldata routes,
ERC20 src,
uint256[] calldata srcAmounts,
ERC20 dest,
uint256 minDestAmount,
uint256 partnerIndex
)
external
payable
returns(uint256);
/**
* @notice use token address 0xeee...eee for ether
* @dev get amount of destination token for given source token amount
* @param tradingProxyIndex index of trading proxy
* @param src Source token
* @param dest Destination token
* @param srcAmount amount of source tokens
* @return amount of actual destination tokens
*/
function getDestinationReturnAmount(
uint256 tradingProxyIndex,
ERC20 src,
ERC20 dest,
uint256 srcAmount,
uint256 partnerIndex
)
external
view
returns(uint256);
function getDestinationReturnAmountForSplitTrades(
uint256[] calldata routes,
ERC20 src,
uint256[] calldata srcAmounts,
ERC20 dest,
uint256 partnerIndex
)
external
view
returns(uint256);
function getDestinationReturnAmountForTradeRoutes(
ERC20 src,
uint256 srcAmount,
ERC20 dest,
address[] calldata _tradingPaths,
uint256 partnerIndex
)
external
view
returns(uint256);
}
// Dependency file: contracts/interfaces/IKULAPTradingProxy.sol
// pragma solidity 0.5.17;
// import "../helper/ERC20Interface.sol";
/**
* @title KULAP Trading Proxy
* @dev The KULAP trading proxy interface has an standard functions and event
* for other smart contract to implement to join KULAP Dex as Market Maker.
*/
interface IKULAPTradingProxy {
/**
* @dev when new trade occure (and success), this event will be boardcast.
* @param _src Source token
* @param _srcAmount amount of source tokens
* @param _dest Destination token
* @return _destAmount: amount of actual destination tokens
*/
event Trade(ERC20 _src, uint256 _srcAmount, ERC20 _dest, uint256 _destAmount);
/**
* @notice use token address 0xeee...eee for ether
* @dev makes a trade between src and dest token
* @param _src Source token
* @param _dest Destination token
* @param _srcAmount amount of source tokens
* @return _destAmount: amount of actual destination tokens
*/
function trade(
ERC20 _src,
ERC20 _dest,
uint256 _srcAmount
)
external
payable
returns(uint256 _destAmount);
/**
* @dev provide destinationm token amount for given source amount
* @param _src Source token
* @param _dest Destination token
* @param _srcAmount Amount of source tokens
* @return _destAmount: amount of expected destination tokens
*/
function getDestinationReturnAmount(
ERC20 _src,
ERC20 _dest,
uint256 _srcAmount
)
external
view
returns(uint256 _destAmount);
/**
* @dev provide source token amount for given destination amount
* @param _src Source token
* @param _dest Destination token
* @param _destAmount Amount of destination tokens
* @return _srcAmount: amount of expected source tokens
*/
// function getSourceReturnAmount(
// ERC20 _src,
// ERC20 _dest,
// uint256 _destAmount
// )
// external
// view
// returns(uint256 _srcAmount);
}
// Dependency file: contracts/helper/ERC20Interface.sol
// pragma solidity 0.5.17;
/**
* @title ERC20
* @dev The ERC20 interface has an standard functions and event
* for erc20 compatible token on Ethereum blockchain.
*/
interface ERC20 {
function totalSupply() external view returns (uint supply);
function balanceOf(address _owner) external view returns (uint balance);
function transfer(address _to, uint _value) external; // Some ERC20 doesn't have return
function transferFrom(address _from, address _to, uint _value) external; // Some ERC20 doesn't have return
function approve(address _spender, uint _value) external; // Some ERC20 doesn't have return
function allowance(address _owner, address _spender) external view returns (uint remaining);
function decimals() external view returns(uint digits);
event Approval(address indexed _owner, address indexed _spender, uint _value);
}
// Dependency file: @openzeppelin/contracts/ownership/Ownable.sol
// pragma solidity ^0.5.0;
// import "../GSN/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.
*
* 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(isOwner(), "Ownable: caller is not the owner");
_;
}
/**
* @dev Returns true if the caller is the current owner.
*/
function isOwner() public view returns (bool) {
return _msgSender() == _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 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 onlyOwner {
_transferOwnership(newOwner);
}
/**
* @dev Transfers ownership of the contract to a new account (`newOwner`).
*/
function _transferOwnership(address newOwner) internal {
require(newOwner != address(0), "Ownable: new owner is the zero address");
emit OwnershipTransferred(_owner, newOwner);
_owner = newOwner;
}
}
// Dependency file: @openzeppelin/contracts/math/SafeMath.sol
// pragma solidity ^0.5.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.
*
* _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;
}
}
// Dependency file: @openzeppelin/contracts/utils/ReentrancyGuard.sol
// pragma solidity ^0.5.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].
*
* _Since v2.5.0:_ this module is now much more gas efficient, given net gas
* metering changes introduced in the Istanbul hardfork.
*/
contract ReentrancyGuard {
bool private _notEntered;
constructor () internal {
// 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;
}
}
pragma solidity 0.5.17;
// import '@openzeppelin/contracts/utils/ReentrancyGuard.sol';
// import "@openzeppelin/contracts/math/SafeMath.sol";
// import "@openzeppelin/contracts/ownership/Ownable.sol";
// import "./helper/ERC20Interface.sol";
// import "./interfaces/IKULAPTradingProxy.sol";
// import "./interfaces/IKULAPDex.sol";
contract ProxyManagement is Ownable {
/**
* @dev Struct of trading proxy
* @param name Name of trading proxy.
* @param enable The flag of trading proxy to check is trading proxy enable.
* @param proxy The address of trading proxy.
*/
struct Proxy {
string name;
bool enable;
IKULAPTradingProxy proxy;
}
event AddedTradingProxy(
address indexed addedBy,
string name,
IKULAPTradingProxy indexed proxyAddress,
uint256 indexed index
);
event EnabledTradingProxy(
address indexed enabledBy,
string name,
IKULAPTradingProxy proxyAddress,
uint256 indexed index
);
event DisabledTradingProxy(
address indexed disabledBy,
string name,
IKULAPTradingProxy indexed proxyAddress,
uint256 indexed index
);
Proxy[] public tradingProxies; // list of trading proxies
modifier onlyTradingProxyEnabled(uint _index) {
require(tradingProxies[_index].enable == true, "This trading proxy is disabled");
_;
}
modifier onlyTradingProxyDisabled(uint _index) {
require(tradingProxies[_index].enable == false, "This trading proxy is enabled");
_;
}
/**
* @dev Function for adding new trading proxy
* @param _name Name of trading proxy.
* @param _proxyAddress The address of trading proxy.
* @return length of trading proxies.
*/
function addTradingProxy(
string memory _name,
IKULAPTradingProxy _proxyAddress
)
public
onlyOwner
{
tradingProxies.push(Proxy({
name: _name,
enable: true,
proxy: _proxyAddress
}));
emit AddedTradingProxy(msg.sender, _name, _proxyAddress, tradingProxies.length - 1);
}
/**
* @dev Function for disable trading proxy by index
* @param _index The uint256 of trading proxy index.
* @return length of trading proxies.
*/
function disableTradingProxy(
uint256 _index
)
public
onlyOwner
onlyTradingProxyEnabled(_index)
{
tradingProxies[_index].enable = false;
emit DisabledTradingProxy(msg.sender, tradingProxies[_index].name, tradingProxies[_index].proxy, _index);
}
/**
* @dev Function for enale trading proxy by index
* @param _index The uint256 of trading proxy index.
* @return length of trading proxies.
*/
function enableTradingProxy(
uint256 _index
)
public
onlyOwner
onlyTradingProxyDisabled(_index)
{
tradingProxies[_index].enable = true;
emit EnabledTradingProxy(msg.sender, tradingProxies[_index].name, tradingProxies[_index].proxy, _index);
}
/**
* @dev Function for get amount of trading proxy
* @return Amount of trading proxies.
*/
function getProxyCount() public view returns (uint256) {
return tradingProxies.length;
}
/**
* @dev Function for get enable status of trading proxy
* @param _index The uint256 of trading proxy index.
* @return enable status of trading proxy.
*/
function isTradingProxyEnable(uint256 _index) public view returns (bool) {
return tradingProxies[_index].enable;
}
}
/*
* Fee collection by partner reference
*/
contract Partnership is ProxyManagement {
using SafeMath for uint256;
struct Partner {
address wallet; // To receive fee on the KULAP Dex network
uint16 fee; // fee in bps
bytes16 name; // Partner reference
}
mapping(uint256 => Partner) public partners;
constructor() public {
Partner memory partner = Partner(msg.sender, 0, "KULAP");
partners[0] = partner;
}
function updatePartner(uint256 index, address wallet, uint16 fee, bytes16 name)
external
onlyOwner
{
Partner memory partner = Partner(wallet, fee, name);
partners[index] = partner;
}
function amountWithFee(uint256 amount, uint256 partnerIndex)
internal
view
returns(uint256 remainingAmount)
{
Partner storage partner = partners[partnerIndex];
if (partner.fee == 0) {
return amount;
}
uint256 fee = amount.mul(partner.fee).div(10000);
return amount.sub(fee);
}
function collectFee(uint256 partnerIndex, uint256 amount, ERC20 token)
internal
returns(uint256 remainingAmount)
{
Partner storage partner = partners[partnerIndex];
if (partner.fee == 0) {
return amount;
}
uint256 fee = amount.mul(partner.fee).div(10000);
require(fee < amount, "fee exceeds return amount!");
token.transfer(partner.wallet, fee);
return amount.sub(fee);
}
}
contract KULAPDex is IKULAPDex, Partnership, ReentrancyGuard {
event Trade(
address indexed srcAsset, // Source
uint256 srcAmount,
address indexed destAsset, // Destination
uint256 destAmount,
address indexed trader, // User
uint256 fee // System fee
);
using SafeMath for uint256;
ERC20 public etherERC20 = ERC20(0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE);
/**
* @notice use token address 0xeee...eee for ether
* @dev makes a trade between Ether to token by tradingProxyIndex
* @param tradingProxyIndex index of trading proxy
* @param srcAmount amount of source tokens
* @param dest Destination token
* @return amount of actual destination tokens
*/
function _tradeEtherToToken(
uint256 tradingProxyIndex,
uint256 srcAmount,
ERC20 dest
)
private
returns(uint256)
{
// Load trading proxy
IKULAPTradingProxy tradingProxy = tradingProxies[tradingProxyIndex].proxy;
// Trade to proxy
uint256 destAmount = tradingProxy.trade.value(srcAmount)(
etherERC20,
dest,
srcAmount
);
return destAmount;
}
// Receive ETH in case of trade Token -> ETH, will get ETH back from trading proxy
function () external payable {}
/**
* @notice use token address 0xeee...eee for ether
* @dev makes a trade between token to Ether by tradingProxyIndex
* @param tradingProxyIndex index of trading proxy
* @param src Source token
* @param srcAmount amount of source tokens
* @return amount of actual destination tokens
*/
function _tradeTokenToEther(
uint256 tradingProxyIndex,
ERC20 src,
uint256 srcAmount
)
private
returns(uint256)
{
// Load trading proxy
IKULAPTradingProxy tradingProxy = tradingProxies[tradingProxyIndex].proxy;
// Approve to TradingProxy
src.approve(address(tradingProxy), srcAmount);
// Trande to proxy
uint256 destAmount = tradingProxy.trade(
src,
etherERC20,
srcAmount
);
return destAmount;
}
/**
* @dev makes a trade between token to token by tradingProxyIndex
* @param tradingProxyIndex index of trading proxy
* @param src Source token
* @param srcAmount amount of source tokens
* @param dest Destination token
* @return amount of actual destination tokens
*/
function _tradeTokenToToken(
uint256 tradingProxyIndex,
ERC20 src,
uint256 srcAmount,
ERC20 dest
)
private
returns(uint256)
{
// Load trading proxy
IKULAPTradingProxy tradingProxy = tradingProxies[tradingProxyIndex].proxy;
// Approve to TradingProxy
src.approve(address(tradingProxy), srcAmount);
// Trande to proxy
uint256 destAmount = tradingProxy.trade(
src,
dest,
srcAmount
);
return destAmount;
}
/**
* @notice use token address 0xeee...eee for ether
* @dev makes a trade between src and dest token by tradingProxyIndex
* Ex1: trade 0.5 ETH -> DAI
* 0, "0xeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeee", "500000000000000000", "0xd3c64BbA75859Eb808ACE6F2A6048ecdb2d70817", "21003850000000000000"
* Ex2: trade 30 DAI -> ETH
* 0, "0xd3c64BbA75859Eb808ACE6F2A6048ecdb2d70817", "30000000000000000000", "0xeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeee", "740825000000000000"
* @param _tradingProxyIndex index of trading proxy
* @param _src Source token
* @param _srcAmount amount of source tokens
* @param _dest Destination token
* @return amount of actual destination tokens
*/
function _trade(
uint256 _tradingProxyIndex,
ERC20 _src,
uint256 _srcAmount,
ERC20 _dest
)
private
onlyTradingProxyEnabled(_tradingProxyIndex)
returns(uint256)
{
// Destination amount
uint256 destAmount;
// Record src/dest asset for later consistency check.
uint256 srcAmountBefore;
uint256 destAmountBefore;
if (etherERC20 == _src) { // Source
srcAmountBefore = address(this).balance;
} else {
srcAmountBefore = _src.balanceOf(address(this));
}
if (etherERC20 == _dest) { // Dest
destAmountBefore = address(this).balance;
} else {
destAmountBefore = _dest.balanceOf(address(this));
}
if (etherERC20 == _src) { // Trade ETH -> Token
destAmount = _tradeEtherToToken(_tradingProxyIndex, _srcAmount, _dest);
} else if (etherERC20 == _dest) { // Trade Token -> ETH
destAmount = _tradeTokenToEther(_tradingProxyIndex, _src, _srcAmount);
} else { // Trade Token -> Token
destAmount = _tradeTokenToToken(_tradingProxyIndex, _src, _srcAmount, _dest);
}
// Recheck if src/dest amount correct
if (etherERC20 == _src) { // Source
require(address(this).balance == srcAmountBefore.sub(_srcAmount), "source amount mismatch after trade");
} else {
require(_src.balanceOf(address(this)) == srcAmountBefore.sub(_srcAmount), "source amount mismatch after trade");
}
if (etherERC20 == _dest) { // Dest
require(address(this).balance == destAmountBefore.add(destAmount), "destination amount mismatch after trade");
} else {
require(_dest.balanceOf(address(this)) == destAmountBefore.add(destAmount), "destination amount mismatch after trade");
}
return destAmount;
}
/**
* @notice use token address 0xeee...eee for ether
* @dev makes a trade between src and dest token by tradingProxyIndex
* Ex1: trade 0.5 ETH -> DAI
* 0, "0xeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeee", "500000000000000000", "0xd3c64BbA75859Eb808ACE6F2A6048ecdb2d70817", "21003850000000000000"
* Ex2: trade 30 DAI -> ETH
* 0, "0xd3c64BbA75859Eb808ACE6F2A6048ecdb2d70817", "30000000000000000000", "0xeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeee", "740825000000000000"
* @param tradingProxyIndex index of trading proxy
* @param src Source token
* @param srcAmount amount of source tokens
* @param dest Destination token
* @param minDestAmount minimun destination amount
* @param partnerIndex index of partnership for revenue sharing
* @return amount of actual destination tokens
*/
function trade(
uint256 tradingProxyIndex,
ERC20 src,
uint256 srcAmount,
ERC20 dest,
uint256 minDestAmount,
uint256 partnerIndex
)
external
payable
nonReentrant
returns(uint256)
{
uint256 destAmount;
// Prepare source's asset
if (etherERC20 != src) {
src.transferFrom(msg.sender, address(this), srcAmount); // Transfer token to this address
}
// Trade with proxy
destAmount = _trade(tradingProxyIndex, src, srcAmount, dest);
// Throw exception if destination amount doesn't meet user requirement.
require(destAmount >= minDestAmount, "destination amount is too low.");
if (etherERC20 == dest) {
(bool success, ) = msg.sender.call.value(destAmount)(""); // Send back ether to sender
require(success, "Transfer ether back to caller failed.");
} else { // Send back token to sender
// Some ERC20 Smart contract not return Bool, so we can't use require(dest.transfer(x, y)); here
dest.transfer(msg.sender, destAmount);
}
// Collect fee
uint256 remainingAmount = collectFee(partnerIndex, destAmount, dest);
emit Trade(address(src), srcAmount, address(dest), remainingAmount, msg.sender, 0);
return remainingAmount;
}
/**
* @notice use token address 0xeee...eee for ether
* @dev makes a trade with multiple routes ex. UNI -> ETH -> DAI
* Ex: trade 50 UNI -> ETH -> DAI
* Step1: trade 50 UNI -> ETH
* Step2: trade xx ETH -> DAI
* srcAmount: 50 * 1e18
* routes: [0, 1]
* srcTokens: [0x1f9840a85d5aF5bf1D1762F925BDADdC4201F984, 0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE]
* destTokens: [0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE, 0x6B175474E89094C44Da98b954EedeAC495271d0F]
* @param srcAmount amount of source tokens
* @param minDestAmount minimun destination amount
* @param routes Trading paths
* @param srcTokens all source of token pairs
* @param destTokens all destination of token pairs
* @param partnerIndex index of partnership for revenue sharing
* @return amount of actual destination tokens
*/
function tradeRoutes(
uint256 srcAmount,
uint256 minDestAmount,
uint256[] calldata routes,
ERC20[] calldata srcTokens,
ERC20[] calldata destTokens,
uint256 partnerIndex
)
external
payable
nonReentrant
returns(uint256)
{
require(routes.length > 0, "routes can not be empty");
require(routes.length == srcTokens.length && routes.length == destTokens.length, "Parameter value lengths mismatch");
uint256 remainingAmount;
{
uint256 destAmount;
if (etherERC20 != srcTokens[0]) {
srcTokens[0].transferFrom(msg.sender, address(this), srcAmount); // Transfer token to This address
}
uint256 pathSrcAmount = srcAmount;
for (uint i = 0; i < routes.length; i++) {
uint256 tradingProxyIndex = routes[i];
ERC20 pathSrc = srcTokens[i];
ERC20 pathDest = destTokens[i];
destAmount = _trade(tradingProxyIndex, pathSrc, pathSrcAmount, pathDest);
pathSrcAmount = destAmount;
}
// Throw exception if destination amount doesn't meet user requirement.
require(destAmount >= minDestAmount, "destination amount is too low.");
if (etherERC20 == destTokens[destTokens.length - 1]) { // Trade Any -> ETH
// Send back ether to sender
(bool success,) = msg.sender.call.value(destAmount)("");
require(success, "Transfer ether back to caller failed.");
} else { // Trade Any -> Token
// Send back token to sender
// Some ERC20 Smart contract not return Bool, so we can't use require(dest.transfer(x, y)) here
destTokens[destTokens.length - 1].transfer(msg.sender, destAmount);
}
// Collect fee
remainingAmount = collectFee(partnerIndex, destAmount, destTokens[destTokens.length - 1]);
}
emit Trade(address(srcTokens[0]), srcAmount, address(destTokens[destTokens.length - 1]), remainingAmount, msg.sender, 0);
return remainingAmount;
}
/**
* @notice use token address 0xeee...eee for ether
* @dev makes a trade with split volumes to multiple-routes ex. UNI -> ETH (5%, 15% and 80%)
* @param routes Trading paths
* @param src Source token
* @param srcAmounts amount of source tokens
* @param dest Destination token
* @param minDestAmount minimun destination amount
* @param partnerIndex index of partnership for revenue sharing
* @return amount of actual destination tokens
*/
function splitTrades(
uint256[] calldata routes,
ERC20 src,
uint256[] calldata srcAmounts,
ERC20 dest,
uint256 minDestAmount,
uint256 partnerIndex
)
external
payable
nonReentrant
returns(uint256)
{
require(routes.length > 0, "routes can not be empty");
require(routes.length == srcAmounts.length, "routes and srcAmounts lengths mismatch");
uint256 srcAmount = srcAmounts[0];
uint256 destAmount = 0;
// Prepare source's asset
if (etherERC20 != src) {
src.transferFrom(msg.sender, address(this), srcAmount); // Transfer token to this address
}
// Trade with proxies
for (uint i = 0; i < routes.length; i++) {
uint256 tradingProxyIndex = routes[i];
uint256 amount = srcAmounts[i];
destAmount = destAmount.add(_trade(tradingProxyIndex, src, amount, dest));
}
// Throw exception if destination amount doesn't meet user requirement.
require(destAmount >= minDestAmount, "destination amount is too low.");
if (etherERC20 == dest) {
(bool success, ) = msg.sender.call.value(destAmount)(""); // Send back ether to sender
require(success, "Transfer ether back to caller failed.");
} else { // Send back token to sender
// Some ERC20 Smart contract not return Bool, so we can't use require(dest.transfer(x, y)); here
dest.transfer(msg.sender, destAmount);
}
// Collect fee
uint256 remainingAmount = collectFee(partnerIndex, destAmount, dest);
emit Trade(address(src), srcAmount, address(dest), remainingAmount, msg.sender, 0);
return remainingAmount;
}
/**
* @notice use token address 0xeee...eee for ether
* @dev get amount of destination token for given source token amount
* @param tradingProxyIndex index of trading proxy
* @param src Source token
* @param dest Destination token
* @param srcAmount amount of source tokens
* @return amount of actual destination tokens
*/
function getDestinationReturnAmount(
uint256 tradingProxyIndex,
ERC20 src,
ERC20 dest,
uint256 srcAmount,
uint256 partnerIndex
)
external
view
returns(uint256)
{
// Load trading proxy
IKULAPTradingProxy tradingProxy = tradingProxies[tradingProxyIndex].proxy;
uint256 destAmount = tradingProxy.getDestinationReturnAmount(src, dest, srcAmount);
return amountWithFee(destAmount, partnerIndex);
}
function getDestinationReturnAmountForSplitTrades(
uint256[] calldata routes,
ERC20 src,
uint256[] calldata srcAmounts,
ERC20 dest,
uint256 partnerIndex
)
external
view
returns(uint256)
{
require(routes.length > 0, "routes can not be empty");
require(routes.length == srcAmounts.length, "routes and srcAmounts lengths mismatch");
uint256 destAmount = 0;
for (uint i = 0; i < routes.length; i++) {
uint256 tradingProxyIndex = routes[i];
uint256 amount = srcAmounts[i];
// Load trading proxy
IKULAPTradingProxy tradingProxy = tradingProxies[tradingProxyIndex].proxy;
destAmount = destAmount.add(tradingProxy.getDestinationReturnAmount(src, dest, amount));
}
return amountWithFee(destAmount, partnerIndex);
}
function getDestinationReturnAmountForTradeRoutes(
ERC20 src,
uint256 srcAmount,
ERC20 dest,
address[] calldata _tradingPaths,
uint256 partnerIndex
)
external
view
returns(uint256)
{
src;
dest;
uint256 destAmount;
uint256 pathSrcAmount = srcAmount;
for (uint i = 0; i < _tradingPaths.length; i += 3) {
uint256 tradingProxyIndex = uint256(_tradingPaths[i]);
ERC20 pathSrc = ERC20(_tradingPaths[i+1]);
ERC20 pathDest = ERC20(_tradingPaths[i+2]);
// Load trading proxy
IKULAPTradingProxy tradingProxy = tradingProxies[tradingProxyIndex].proxy;
destAmount = tradingProxy.getDestinationReturnAmount(pathSrc, pathDest, pathSrcAmount);
pathSrcAmount = destAmount;
}
return amountWithFee(destAmount, partnerIndex);
}
// In case of expected and unexpected event that have some token amounts remain in this contract, owner can call to collect them.
function collectRemainingToken(
ERC20 token,
uint256 amount
)
public
onlyOwner
{
token.transfer(msg.sender, amount);
}
// In case of expected and unexpected event that have some ether amounts remain in this contract, owner can call to collect them.
function collectRemainingEther(
uint256 amount
)
public
onlyOwner
{
(bool success, ) = msg.sender.call.value(amount)(""); // Send back ether to sender
require(success, "Transfer ether back to caller failed.");
}
} | * @dev Function for adding new trading proxy @param _name Name of trading proxy. @param _proxyAddress The address of trading proxy. @return length of trading proxies./ | function addTradingProxy(
string memory _name,
IKULAPTradingProxy _proxyAddress
)
public
onlyOwner
{
tradingProxies.push(Proxy({
name: _name,
enable: true,
proxy: _proxyAddress
}));
emit AddedTradingProxy(msg.sender, _name, _proxyAddress, tradingProxies.length - 1);
}
| 10,518,629 | [
1,
2083,
364,
6534,
394,
1284,
7459,
2889,
225,
389,
529,
1770,
434,
1284,
7459,
2889,
18,
225,
389,
5656,
1887,
1021,
1758,
434,
1284,
7459,
2889,
18,
327,
769,
434,
1284,
7459,
13263,
18,
19,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
565,
445,
527,
1609,
7459,
3886,
12,
203,
3639,
533,
3778,
389,
529,
16,
203,
3639,
467,
47,
1506,
2203,
1609,
7459,
3886,
389,
5656,
1887,
203,
565,
262,
203,
1377,
1071,
203,
1377,
1338,
5541,
203,
565,
288,
203,
3639,
1284,
7459,
21488,
18,
6206,
12,
3886,
12590,
203,
5411,
508,
30,
389,
529,
16,
203,
5411,
4237,
30,
638,
16,
203,
5411,
2889,
30,
389,
5656,
1887,
203,
3639,
289,
10019,
203,
3639,
3626,
25808,
1609,
7459,
3886,
12,
3576,
18,
15330,
16,
389,
529,
16,
389,
5656,
1887,
16,
1284,
7459,
21488,
18,
2469,
300,
404,
1769,
203,
565,
289,
203,
203,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
] |
./full_match/1/0x440502f4843Ba5d942CFcFFDA0f0eEE1c84fA1Ac/sources/contracts/MemeCoin.sol | * @notice Updates the ability to enable or disable token swapping on Uniswap. @param _enabled A boolean value indicating whether token swapping is enabled or disabled. @dev Only the contract owner with the DEFAULT_ADMIN_ROLE can call this function to control token swapping. Emits a SwapEnabled event to signal the change in token swapping status./ | function updateSwapEnabled(
bool _enabled
) external onlyRole(DEFAULT_ADMIN_ROLE) {
swapEnabled = _enabled;
emit SwapEnabled(_enabled);
}
| 3,178,121 | [
1,
5121,
326,
7123,
358,
4237,
578,
4056,
1147,
7720,
1382,
603,
1351,
291,
91,
438,
18,
225,
389,
5745,
432,
1250,
460,
11193,
2856,
1147,
7720,
1382,
353,
3696,
578,
5673,
18,
225,
5098,
326,
6835,
3410,
598,
326,
3331,
67,
15468,
67,
16256,
848,
745,
333,
445,
358,
3325,
1147,
7720,
1382,
18,
7377,
1282,
279,
12738,
1526,
871,
358,
4277,
326,
2549,
316,
1147,
7720,
1382,
1267,
18,
19,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
565,
445,
1089,
12521,
1526,
12,
203,
3639,
1426,
389,
5745,
203,
565,
262,
3903,
1338,
2996,
12,
5280,
67,
15468,
67,
16256,
13,
288,
203,
3639,
7720,
1526,
273,
389,
5745,
31,
203,
203,
3639,
3626,
12738,
1526,
24899,
5745,
1769,
203,
565,
289,
203,
203,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
] |
pragma solidity >=0.4.21 <0.7.0;
contract Marketplace {
string public name;
address deployer;
uint public productCount = 0;
mapping(uint => Product) public products;
struct Product {
uint id;
string name;
string description;
string category;
uint rentalDeposit;
uint rentalFee;
address payable owner;
address payable custodian;
uint rentalStart;
bool rented;
}
event ProductCreated(
uint id,
string name,
string description,
string category,
uint rentalDeposit,
uint rentalFee,
address payable owner,
bool rented
);
event ProductRented(
uint id,
string name,
uint rentalDeposit,
uint rentalFee,
address owner,
address custodian,
uint rentalStart,
bool rented
);
event ProductReturned(
uint id,
string name,
uint rentalDeposit,
uint rentalCost,
uint returnedDeposit,
address payable owner,
address payable borrower,
address custodian,
uint rentalDays,
bool rented
);
event ProductDeleted(
uint id,
string name,
address owner,
address custodian,
bool rented
);
event ProductEdited(
uint id,
string name,
string description,
string category,
uint rentalDeposit,
uint rentalFee,
address payable owner,
bool rented
);
constructor() public {
name = "ETHRent Dapp";
deployer = msg.sender;
}
function createProduct(string memory _name, string memory _description, string memory _category, uint _rentalDeposit, uint _rentalFee) public {
// Require a valid name
require(bytes(_name).length > 0);
// Require a valid description
require(bytes(_description).length > 0);
// Require a valid rental deposit
require(_rentalDeposit > 0);
// Require a valid rental fee
require(_rentalFee > 0);
// Increment product count
productCount ++;
// Create the product
products[productCount] = Product(productCount, _name, _description, _category, _rentalDeposit, _rentalFee, msg.sender, msg.sender, 0, false);
// Trigger an event
emit ProductCreated(
productCount,
_name,
_description,
_category,
_rentalDeposit,
_rentalFee,
msg.sender,
false);
}
function rentProduct(uint _id) public payable {
// Fetch the product
Product memory _product = products[_id];
// Fetch the owner
address payable _owner = _product.owner;
// Make sure the product has a valid id
require(_product.id > 0 && _product.id <= productCount);
// Require that there is enough Ether in the transaction
require(msg.value >= _product.rentalDeposit);
// Require that the product has not been rented already
require(!_product.rented);
// Require that the borrower is not the owner
require(_owner != msg.sender);
// Transfer responsibility to the borrower
_product.custodian = msg.sender;
// Set time when rental starts
_product.rentalStart = now;
// Mark as rented
_product.rented = true;
// Update the product
products[_id] = _product;
// Trigger an event
emit ProductRented(
productCount,
_product.name,
_product.rentalDeposit,
_product.rentalFee,
_product.owner,
msg.sender,
_product.rentalStart,
true);
}
function returnProduct(uint _id, uint _rentalDays) public payable {
// Fetch the product
Product memory _product = products[_id];
// Fetch the owner
address payable _owner = _product.owner;
// Fetch the borrower
address payable _borrower = _product.custodian;
// Make sure the product has a valid id
require(_product.id > 0 && _product.id <= productCount);
// Require that the product is currently rented
require(_product.rented);
// Require that the borrower is not the owner
require(_owner != _borrower);
// Determine rental period, and associated rental cost
uint endTime;
endTime = now;
uint rentalCost;
rentalCost = _rentalDays * _product.rentalFee;
rentalCost = _product.rentalDeposit <= rentalCost ? _product.rentalDeposit : rentalCost; // x <= y ? x : y
// Transfer responsibility back to owner
_product.custodian = _product.owner;
// Mark as rented
_product.rented = false;
// Update the product
products[_id] = _product;
// Pay the owner by sending them Ether
address(_owner).transfer(rentalCost);
// Return remaining deposit to the borrower
uint returnedDeposit;
returnedDeposit = _product.rentalDeposit - rentalCost;
address(_borrower).transfer(returnedDeposit);
// Trigger an event
emit ProductReturned(
productCount,
_product.name,
_product.rentalDeposit,
rentalCost,
returnedDeposit,
_product.owner,
_borrower,
_product.custodian,
_rentalDays,
_product.rented);
}
function deleteProduct(uint _id) public {
// Fetch the product
Product memory _product = products[_id];
// Make sure the product has a valid id
require(_product.id > 0 && _product.id <= productCount);
// Make sure only the product owner can delete a product
require(_product.owner == msg.sender);
// Make sure the owner is currently the custodian of the product
require(_product.custodian == _product.owner);
// Mark as rented (i.e. unavailable to rent)
_product.rented = true;
// Update the product
products[_id] = _product;
// Trigger an event
emit ProductDeleted(
productCount,
_product.name,
_product.owner,
_product.custodian,
_product.rented);
}
function editProduct(uint _id, string memory _name, string memory _description, string memory _category, uint _rentalDeposit, uint _rentalFee) public {
// Fetch the product
Product memory _product = products[_id];
// Make sure the product has a valid id
require(_product.id > 0 && _product.id <= productCount);
// Make sure only the product owner can edit a product
require(_product.owner == msg.sender);
// Make sure the owner is currently the custodian of the product
require(_product.custodian == _product.owner);
// Edit the product
_product.name = _name;
_product.description = _description;
_product.category = _category;
_product.rentalDeposit = _rentalDeposit;
_product.rentalFee = _rentalFee;
products[_id] = _product;
emit ProductEdited(
productCount,
_name,
_description,
_category,
_rentalDeposit,
_rentalFee,
msg.sender,
false);
}
function destroy() public {
// Make sure the function is being called by the contract deployer
require(msg.sender == deployer);
// Remove the contract from the blockchain, return any ether to the deployer
selfdestruct(msg.sender);
}
} | Require a valid name Require a valid description Require a valid rental deposit Require a valid rental fee Increment product count Create the product Trigger an event | function createProduct(string memory _name, string memory _description, string memory _category, uint _rentalDeposit, uint _rentalFee) public {
require(bytes(_name).length > 0);
require(bytes(_description).length > 0);
require(_rentalDeposit > 0);
require(_rentalFee > 0);
productCount ++;
products[productCount] = Product(productCount, _name, _description, _category, _rentalDeposit, _rentalFee, msg.sender, msg.sender, 0, false);
emit ProductCreated(
productCount,
_name,
_description,
_category,
_rentalDeposit,
_rentalFee,
msg.sender,
false);
}
| 12,936,702 | [
1,
8115,
279,
923,
508,
12981,
279,
923,
2477,
12981,
279,
923,
283,
496,
287,
443,
1724,
12981,
279,
923,
283,
496,
287,
14036,
17883,
3017,
1056,
1788,
326,
3017,
11321,
392,
871,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
225,
445,
752,
4133,
12,
1080,
3778,
389,
529,
16,
533,
3778,
389,
3384,
16,
533,
3778,
389,
4743,
16,
2254,
389,
547,
287,
758,
1724,
16,
2254,
389,
547,
287,
14667,
13,
1071,
288,
203,
565,
2583,
12,
3890,
24899,
529,
2934,
2469,
405,
374,
1769,
203,
565,
2583,
12,
3890,
24899,
3384,
2934,
2469,
405,
374,
1769,
203,
565,
2583,
24899,
547,
287,
758,
1724,
405,
374,
1769,
203,
565,
2583,
24899,
547,
287,
14667,
405,
374,
1769,
203,
565,
3017,
1380,
965,
31,
203,
565,
10406,
63,
5896,
1380,
65,
273,
8094,
12,
5896,
1380,
16,
389,
529,
16,
389,
3384,
16,
389,
4743,
16,
389,
547,
287,
758,
1724,
16,
389,
547,
287,
14667,
16,
1234,
18,
15330,
16,
1234,
18,
15330,
16,
374,
16,
629,
1769,
203,
565,
3626,
8094,
6119,
12,
203,
1377,
3017,
1380,
16,
203,
1377,
389,
529,
16,
203,
1377,
389,
3384,
16,
203,
1377,
389,
4743,
16,
203,
1377,
389,
547,
287,
758,
1724,
16,
203,
1377,
389,
547,
287,
14667,
16,
203,
1377,
1234,
18,
15330,
16,
203,
1377,
629,
1769,
203,
225,
289,
203,
203,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
] |
// 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);
}
/**
* @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;
}
/**
* @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);
}
/**
* @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);
}
/**
* @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);
}
}
}
}
/**
* @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;
}
}
/**
* @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);
}
}
/**
* @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;
}
}
/**
* @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 {
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.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 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() {
_setOwner(_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 {
_setOwner(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");
_setOwner(newOwner);
}
function _setOwner(address newOwner) private {
address oldOwner = _owner;
_owner = newOwner;
emit OwnershipTransferred(oldOwner, newOwner);
}
}
// 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 no longer needed starting with Solidity 0.8. 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;
}
}
}
/**
* @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;
}
}
/*
* Interface for the $COLORWASTE erc20 token contract
*/
interface ICW {
function burn(address _from, uint256 _amount) external;
function updateBalance(address _from, address _to) external;
}
/*
* Interface for the $SOS erc20 token contract
*/
interface ISOS {
function approve(address from, uint256 amount) external returns(bool);
function transferFrom(address from, address to, uint256 amount) external;
function balanceOf(address owner) external view returns(uint256);
}
/*
* Interface for the Doodles contract
*/
interface IDoodles {
function balanceOf(address owner) external view returns(uint256);
function ownerOf(uint256 tokenId) external view returns(address);
function tokenOfOwnerByIndex(address owner, uint256 index) external view returns(uint256);
}
/*
* Interface for the KaijuKingz contract
*/
interface IKaijuKingz {
function walletOfOwner(address owner) external view returns(uint256[] memory);
function ownerOf(uint256 tokenId) external view returns(address);
}
/*
* DAIJUKINGZ
*/
contract DaijuKingz is ERC721, Ownable {
using SafeMath for uint256;
using Address for address;
using Counters for Counters.Counter;
Counters.Counter private TotalSupplyFix;
ICW public CW;
IDoodles public Doodles;
IKaijuKingz public KaijuKingz;
ISOS public SOS;
string private baseURI;
uint256 constant public reserveMax = 50; // the amount of daijus the team will reserve for community events, staff, etc.
uint256 public maxSupply = 11110; // max genesis + max bred daijus
uint256 public maxGenCount = 5555; // the max genesis count. if theres remaining supply after sale ends, the genesis daijukingz will be less then this number
uint256 public maxFreeMints = 124; // the max free mints that can be claimed for kaiju and doodle holders
uint256 public maxGivewayMint = 676; // the max free mints that are from the whitelisted users
// counters
uint256 public reserveCount = 0;
uint256 public freeMintCount = 0;
uint256 public giveawayMintCount = 0;
uint256 public genCount = 0;
uint256 public babyCount = 0;
// settings for breeding & sales
uint256 public price = 0.05 ether;
uint256 public breedPrice = 7500 ether;
uint256 public increasePerBreed = 0 ether;
uint256 public saleStartTimestamp;
uint256 public freeEndTimestamp;
address public sosWallet;
uint256 public sosPrice = 0.05 ether;
bool public transfersEnabled = false;
bool public breedingEnabled = false;
// tracks all of the wallets that interact with the contract
mapping(address => uint256) public balanceGenesis;
mapping(address => uint256) public balanceBaby;
mapping(address => uint256) public freeMintList;
mapping(address => uint256) public giveawayMintList;
/*
* DaijuOwner
* checks if the token IDs provided are owned by the user interacting with the contract (used for breeding)
*/
modifier DaijuOwner(uint256 DaijuId) {
require(ownerOf(DaijuId) == msg.sender, "Cannot interact with a DaijuKingz you do not own");
_;
}
/*
* IsSaleActive
* checks if the mint is ready to begin
*/
modifier IsSaleActive() {
require(saleStartTimestamp != 0 && block.timestamp > saleStartTimestamp, "Cannot interact because sale has not started");
_;
}
/*
* IsFreeMintActive
* checks if the free mint end timestamp isn't met
*/
modifier IsFreeMintActive {
require(block.timestamp < freeEndTimestamp, "Free Minting period has ended!");
_;
}
/*
* AreTransfersEnabled
* checks if we want to allow opensea to transfer any tokens
*/
modifier AreTransfersEnabled() {
require(transfersEnabled, "Transfers aren't allowed yet!");
_;
}
constructor() ERC721("DaijuKingz", "Daiju") {}
/*
* mintFreeKaijuList
* checks the walelt for a list of kaijukingz they hold, used for checking if they
* can claim a free daijuking
*/
function mintFreeKaijuList(address _address) external view returns(uint256[] memory) {
return KaijuKingz.walletOfOwner(_address);
}
/*
* mintFreeDoodleList
* gets the amount of doodles a wallet holds, used for checking if they are elligble
* for claiming a free daijuking
*/
function mintFreeDoodleList(address _address) public view returns(uint256) {
uint256 count = Doodles.balanceOf(_address);
return count;
}
/*
* checkIfFreeMintClaimed
* checks if the address passed claimed a free mint already
*/
function checkIfFreeMintClaimed(address _address) public view returns(uint256) {
return freeMintList[_address];
}
/*
* checkIfGiveawayMintClaimed
* checks if they claimed their giveaway mint
*/
function checkIfGiveawayMintClaimed(address _address) public view returns(uint256) {
return giveawayMintList[_address];
}
/*
* addGiveawayWinners
* adds the wallets to the giveaway list so they can call mintFreeGiveaway()
*/
function addGiveawayWinners(address[] calldata giveawayAddresses) external onlyOwner {
for (uint256 i; i < giveawayAddresses.length; i++) {
giveawayMintList[giveawayAddresses[i]] = 1;
}
}
/*
* mintFreeDoodle
* mints a free daijuking using a Doodles token - can only be claimed once per wallet
*/
function mintFreeDoodle() public payable IsSaleActive IsFreeMintActive {
uint256 supply = TotalSupplyFix.current();
require(supply <= maxGenCount, "All Genesis Daijukingz were claimed!");
require(mintFreeDoodleList(msg.sender) >= 1, "You don't own any Doodles!");
require((supply + 1) <= maxFreeMints, "All the free mints have been claimed!");
require(freeMintList[msg.sender] < 1, "You already claimed your free daijuking!");
require(!breedingEnabled, "Minting genesis has been disabled!");
_safeMint(msg.sender, supply);
TotalSupplyFix.increment();
freeMintList[msg.sender] = 1;
balanceGenesis[msg.sender]++;
genCount++;
freeMintCount += 1;
}
/*
* mintFreeKaiju
* mints a free daijuking using a KaijuKingz token - can only be claimed once per wallet
*/
function mintFreeKaiju() public payable IsSaleActive IsFreeMintActive {
uint256 supply = TotalSupplyFix.current();
uint256[] memory list = KaijuKingz.walletOfOwner(msg.sender);
require(supply <= maxGenCount, "All Genesis Daijukingz were claimed!");
require((supply + 1) <= maxFreeMints, "All the free mints have been claimed!");
require(freeMintList[msg.sender] < 1, "You already claimed your free daijuking!");
require(list.length >= 1, "You don't own any KaijuKingz!");
require(!breedingEnabled, "Minting genesis has been disabled!");
_safeMint(msg.sender, supply);
TotalSupplyFix.increment();
freeMintList[msg.sender] = 1;
balanceGenesis[msg.sender]++;
genCount++;
freeMintCount += 1;
}
/*
* mintFreeGiveaway
* this is for the giveaway winners - allows you to mint a free daijuking
*/
function mintFreeGiveaway() public payable IsSaleActive IsFreeMintActive {
uint256 supply = TotalSupplyFix.current();
require(supply <= maxGenCount, "All Genesis Daijukingz were claimed!");
require((supply + 1) <= maxGivewayMint, "All giveaway mints were claimed!");
require(giveawayMintList[msg.sender] >= 1, "You don't have any free mints left!");
require(!breedingEnabled, "Minting genesis has been disabled!");
_safeMint(msg.sender, supply);
TotalSupplyFix.increment();
giveawayMintList[msg.sender] = 0;
balanceGenesis[msg.sender]++;
genCount++;
giveawayMintCount += 1;
}
/*
* mint
* mints the daijuking using ETH as the payment token
*/
function mint(uint256 numberOfMints) public payable IsSaleActive {
uint256 supply = TotalSupplyFix.current();
require(numberOfMints > 0 && numberOfMints < 11, "Invalid purchase amount");
if (block.timestamp <= freeEndTimestamp) {
require(supply.add(numberOfMints) <= (maxGenCount - (maxFreeMints + maxGivewayMint)), "Purchase would exceed max supply");
} else {
require(supply.add(numberOfMints) <= maxGenCount, "Purchase would exceed max supply");
}
require(price.mul(numberOfMints) == msg.value, "Ether value sent is not correct");
require(!breedingEnabled, "Minting genesis has been disabled!");
for (uint256 i; i < numberOfMints; i++) {
_safeMint(msg.sender, supply + i);
balanceGenesis[msg.sender]++;
genCount++;
TotalSupplyFix.increment();
}
}
/*
* mintWithSOS
* allows the user to mint a daijuking using the $SOS token
* note: user must approve it before this can be called
*/
function mintWithSOS(uint256 numberOfMints) public payable IsSaleActive {
uint256 supply = TotalSupplyFix.current();
require(numberOfMints > 0 && numberOfMints < 11, "Invalid purchase amount");
require(supply.add(numberOfMints) <= maxGenCount, "Purchase would exceed max supply");
require(sosPrice.mul(numberOfMints) < SOS.balanceOf(msg.sender), "Not enough SOS to mint!");
require(!breedingEnabled, "Minting genesis has been disabled!");
SOS.transferFrom(msg.sender, sosWallet, sosPrice.mul(numberOfMints));
for (uint256 i; i < numberOfMints; i++) {
_safeMint(msg.sender, supply + i);
balanceGenesis[msg.sender]++;
genCount++;
TotalSupplyFix.increment();
}
}
/*
* breed
* allows you to create a daijuking using 2 parents and some $COLORWASTE, 18+ only
* note: selecting is automatic from the DAPP, but if you use the contract make sure they are two unique token id's that aren't children...
*/
function breed(uint256 parent1, uint256 parent2) public DaijuOwner(parent1) DaijuOwner(parent2) {
uint256 supply = TotalSupplyFix.current();
require(breedingEnabled, "Breeding isn't enabled yet!");
require(supply < maxSupply, "Cannot breed any more baby Daijus");
require(parent1 < genCount && parent2 < genCount, "Cannot breed with baby Daijus (thats sick bro)");
require(parent1 != parent2, "Must select two unique parents");
// burns the tokens for the breeding cost
CW.burn(msg.sender, breedPrice + increasePerBreed * babyCount);
// adds the baby to the total supply and counter
babyCount++;
TotalSupplyFix.increment();
// mints the baby daijuking and adds it to the balance for the wallet
_safeMint(msg.sender, supply);
balanceBaby[msg.sender]++;
}
/*
* reserve
* mints the reserved amount
*/
function reserve(uint256 count) public onlyOwner {
uint256 supply = TotalSupplyFix.current();
require(reserveCount + count < reserveMax, "cannot reserve more");
for (uint256 i = 0; i < count; i++) {
_safeMint(msg.sender, supply + i);
balanceGenesis[msg.sender]++;
genCount++;
TotalSupplyFix.increment();
reserveCount++;
}
}
/*
* totalSupply
* returns the current amount of tokens, called by DAPPs
*/
function totalSupply() external view returns(uint256) {
return TotalSupplyFix.current();
}
/*
* getTypes
* gets the tokens provided and returns the genesis and baby daijukingz
*
* genesis is 0
* baby is 1
*/
function getTypes(uint256[] memory list) external view returns(uint256[] memory) {
uint256[] memory typeList = new uint256[](list.length);
for (uint256 i; i < list.length; i++){
if (list[i] >= genCount) {
typeList[i] = 1;
} else {
typeList[i] = 0;
}
}
return typeList;
}
/*
* walletOfOwner
* returns the tokens that the user owns
*/
function walletOfOwner(address owner) public view returns(uint256[] memory) {
uint256 tokenCount = balanceOf(owner);
uint256 supply = TotalSupplyFix.current();
uint256 index = 0;
uint256[] memory tokensId = new uint256[](tokenCount);
for (uint256 i; i < supply; i++) {
if (ownerOf(i) == owner) {
tokensId[index] = i;
index++;
}
}
return tokensId;
}
/*
* withdraw
* takes out the eth from the contract to the deployer
*/
function withdraw() public onlyOwner {
uint256 balance = address(this).balance;
payable(msg.sender).transfer(balance);
}
/*
* updateSaleTimestamp
* set once we're ready release
*/
function updateSaleTimestamp(uint256 _saleStartTimestamp) public onlyOwner {
saleStartTimestamp = _saleStartTimestamp;
}
/*
* updateFreeEndTimestamp
* set once saleStartTimestamp is set for release
*/
function updateFreeEndTimestamp(uint256 _freeEndTimestamp) public onlyOwner {
freeEndTimestamp = _freeEndTimestamp;
}
/*
* setBreedingCost
* sets the breeding cost to the new
*/
function setBreedingCost(uint256 _breedPrice) public onlyOwner {
breedPrice = _breedPrice;
}
/*
* setBreedingCostIncrease
* change the rate based on the breeding cost for each new baby mint
*/
function setBreedingCostIncrease(uint256 _increasePerBreed) public onlyOwner {
increasePerBreed = _increasePerBreed;
}
/*
* setBreedingState
* changes whether breeding is enabled or not, by default its disabled
*/
function setBreedingState(bool _state) public onlyOwner {
breedingEnabled = _state;
}
/*
* setPrice
* sets the eth mint price (shouldn't ever be called but who knows)
*/
function setPrice(uint256 _price) public onlyOwner {
price = _price;
}
/*
* setSOSPrice
* sets the price for $SOS mint, most likely will only be set once before the release
*/
function setSOSPrice(uint256 _sosPrice) public onlyOwner {
sosPrice = _sosPrice;
}
// 46524939000000000000000000
// 4652493900000000000000000
/*
* setSOSWallet
* sets the deposit wallet for $SOS mints
*/
function setSOSWallet(address _address) public onlyOwner {
sosWallet = _address;
}
/*
* setBaseURI
* sets the metadata url once its live
*/
function setBaseURI(string memory _newURI) public onlyOwner {
baseURI = _newURI;
}
/*
* _baseURI
* returns the metadata url to any DAPPs that use it (opensea for instance)
*/
function _baseURI() internal view override returns (string memory) {
return baseURI;
}
/*
* setTransfersEnabled
* enables opensea transfers - can only be called once
*/
function setTransfersEnabled() external onlyOwner {
transfersEnabled = true;
}
/*
* setCWInterface
* links the interface to the $COLORWASTE smart contract once it's deployed
*/
function setCWInterface(address _address) external onlyOwner {
CW = ICW(_address);
}
/*
* setKaijuInterface
* links the interface to the KaijuKingz contract
*/
function setKaijuInterface(address _address) public onlyOwner {
KaijuKingz = IKaijuKingz(_address);
}
/*
* setDoodleInterface
* links the interface to the Doodles contract
*/
function setDoodleInterface(address _address) public onlyOwner {
Doodles = IDoodles(_address);
}
/*
* setSOSInterface
* links the interface to the $SOS contract
*/
function setSOSInterface(address target) public onlyOwner {
SOS = ISOS(target);
}
/*
* Opensea methods for transfering the tokens
*/
function transferFrom(address from, address to, uint256 tokenId) public override AreTransfersEnabled {
CW.updateBalance(from, to);
if (tokenId >= maxGenCount) {
balanceBaby[from]--;
balanceBaby[to]++;
} else {
balanceGenesis[from]--;
balanceGenesis[to]++;
}
ERC721.transferFrom(from, to, tokenId);
}
function safeTransferFrom(address from, address to, uint256 tokenId) public override AreTransfersEnabled {
safeTransferFrom(from, to, tokenId, "");
}
function safeTransferFrom(address from, address to, uint256 tokenId, bytes memory data) public override AreTransfersEnabled {
CW.updateBalance(from, to);
if (tokenId >= maxGenCount) {
balanceBaby[from]--;
balanceBaby[to]++;
} else {
balanceGenesis[from]--;
balanceGenesis[to]++;
}
ERC721.safeTransferFrom(from, to, tokenId, data);
}
} | the max free mints that can be claimed for kaiju and doodle holders
| uint256 public maxFreeMints = 124; | 6,906,499 | [
1,
5787,
943,
4843,
312,
28142,
716,
848,
506,
7516,
329,
364,
22258,
8302,
89,
471,
741,
369,
298,
366,
4665,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
565,
2254,
5034,
1071,
943,
9194,
49,
28142,
273,
2593,
24,
31,
225,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
] |
// SPDX-License-Identifier: MIT
/**
MMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMM
MMMMMMMMMMMMMMMMMMMMMMMMMMMMWWWWWWWWWWWWWWWMMMMMMMMMMMMMMMMMMMMMMMMMMM
MMMMMMMMMMMMMMMMMMMMMMWWNXXKKKKKKKXXXXKKKKKKXXNWWMMMMMMMMMMMMMMMMMMMMM
MMMMMMMMMMMMMMMMMMWNXKKKKXXNWWWWMMWWWWMWWWWNXXXKKKXNWMMMMMMMMMMMMMMMMM
MMMMMMMMMMMMMMMWNXKKKXNWMMMMMMMMMNOdxKWMMMMMMMMWNXKKKXNWMMMMMMMMMMMMMM
MMMMMMMMMMMMMWXKKKNWMMMMMMMMMMMMNx:;;l0WMMMMMMMMMMMWNK0KXWMMMMMMMMMMMM
MMMMMMMMMMMWXKKXWMMMMMMMMMMMMMMXd:;;;;cOWMMMMMMMMMMMMMWXKKXWMMMMMMMMMM
MMMMMMMMMWNKKXWMMMMMMMMMMMMMMWKo;;col:;:kNMMMMMMMMMMMMMMWX0KNWMMMMMMMM
MMMMMMMMWX0XWMMMMMMMMMMMMMMMWOl;;oKWXkc;:dXMMMMMMMMMMMMMMMWX0XWMMMMMMM
MMMMMMMNKKNWMMMMMMMMMMMMMMMNkc;:dXMMMWOc;;oKWMMMMMMMMMMMMMMWNKKNMMMMMM
MMMMMMNKKNMMMMMMMMMMMMMMMMNx:;:xNMMMMMW0l;;l0WMMMMMMMWMMMMMMMNKKNMMMMM
MMMMMNKKNMMMMMMMMMMMMMMMMXd:;ckNMMMMMMMMKo:;cOWMMMMXkxkXWMMMMMNKKNMMMM
MMMMWK0NMMMMMMMMMMMMMMMWKo;;l0WMMMMMMMMMMXx:;:xNMMW0lccxXMMMMMMN0KWMMM
MMMMX0XWMMMMMMWWMMMMMMWOl;;oKWMMMMMMMMMMMMNkc;:dXMMNklcoKMMMMMMMX0XMMM
MMMWKKNMMWK0OkkkkkkKWNkc;:dXMMMMMMMMMMMMMMMWOl;;oKWMXdcxNMMMMMMMNKKWMM
MMMN0XWMMWNXX0OdlccdKOc;:xNMMMWXKKXNWNNNNWWMW0o;;l0WNkdKWMMMMMMMWX0NMM
MMMX0XMMMMMMMMMN0dlcdOxoONMMMMW0xdddddodxk0KNWXd:;l0Kx0WMMMMMMMMMX0XMM
MMMX0NMMMMMMMMMMWXxlcoOXWMMMMWKkolclodkKNNNNWWMNxcxOkKWMMMMMMMMMMX0XMM
MMMX0XMMMMMMMMMMMMNklclkNMMWXklccodxdodKWMMMMMMMNKOkKWMMMMMMMMMMMX0XMM
MMMN0XWMMMMMMMMMMMMNOoclxXN0occcdKX0xlco0WMMMMMMNOOXMMMMMMMMMMMMMX0NMM
MMMWKKWMMMMMMMMMMMMMW0dccoxocccdKWMWNklclONMMMMXOONMMMMMMMMMMMMMWKKWMM
MMMMX0XMMMMMMMMMMMMMMWKdcccccco0WMMMMNOoclkNWWKk0NMMMMMMMMMMMMMMX0XWMM
MMMMWKKNMMMMMMMMMMMMMMMXxlcccckNMMMMMMW0oclxK0kKWMMMMMMMMMMMMMMNKKWMMM
MMMMMN0KWMMMMMMMMMMMMMMMNklccoKWMMMMMMMWKdlcoxKWMMMMMMMMMMMMMMWK0NMMMM
MMMMMMN0KWMMMMMMMMMMMMMMMNOod0KXWMMMMMMNK0xoxXWMMMMMMMMMMMMMMWK0NMMMMM
MMMMMMMN0KNMMMMMMMMMMMMMMMWXKkll0WMMMMXdcoOKNMMMMMMMMMMMMMMMNK0NMMMMMM
MMMMMMMMNK0XWMMMMMMMMMMMMMMMNd:;cOWMWKo:;c0WMMMMMMMMMMMMMMWX0KNMMMMMMM
MMMMMMMMMWXKKNWMMMMMMMMMMMMMMXd:;cx0kl;;l0WMMMMMMMMMMMMMWNKKXWMMMMMMMM
MMMMMMMMMMMWX0KNWMMMMMMMMMMMMMNkc;;::;:oKWMMMMMMMMMMMMWNK0XWMMMMMMMMMM
MMMMMMMMMMMMMNXKKXNWMMMMMMMMMMMWOc;;;:dXMMMMMMMMMMMWNXKKXWMMMMMMMMMMMM
MMMMMMMMMMMMMMMWNKKKXNWMMMMMMMMMW0l:ckNMMMMMMMMMWNXKKKNWMMMMMMMMMMMMMM
MMMMMMMMMMMMMMMMMMWNXKKKXXNWWWMMMMX0KWMMMWWWNXXKKKXNWMMMMMMMMMMMMMMMMM
MMMMMMMMMMMMMMMMMMMMMWWNXXKKKKKXXXXXXXXXXKKKKXXNWWMMMMMMMMMMMMMMMMMMMM
MMMMMMMMMMMMMMMMMMMMMMMMMMMWWNNNNNNNNNNNNWWWMMMMMMMMMMMMMMMMMMMMMMMMMM
MMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMM
---------------------- [ WPSmartContracts.com ] ----------------------
[ Blockchain Made Easy ]
|
| ERC-721 NFT Token Marketplace
|
|----------------------------
|
| Flavors
|
| > Suika v.2: Standard ERC-721 Token with Marketplace
| Supports Payment with Tokens, and royalties
|
*/
pragma solidity ^0.8.2;
/**
* @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);
}
/**
* @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;
}
/**
* @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);
}
/**
* @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);
}
/**
* @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);
}
}
}
}
/**
* @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;
}
}
/**
* @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);
}
}
/**
* @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;
}
}
/**
* @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 {
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.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 {}
}
/**
* @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);
}
/**
* @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();
}
}
/**
* @dev ERC721 token with storage based token URI management.
*/
abstract contract ERC721URIStorage is ERC721 {
using Strings for uint256;
// Optional mapping for token URIs
mapping(uint256 => string) private _tokenURIs;
/**
* @dev See {IERC721Metadata-tokenURI}.
*/
function tokenURI(uint256 tokenId) public view virtual override returns (string memory) {
require(_exists(tokenId), "ERC721URIStorage: URI query for nonexistent token");
string memory _tokenURI = _tokenURIs[tokenId];
string memory base = _baseURI();
// If there is no base URI, return the token URI.
if (bytes(base).length == 0) {
return _tokenURI;
}
// If both are set, concatenate the baseURI and tokenURI (via abi.encodePacked).
if (bytes(_tokenURI).length > 0) {
return string(abi.encodePacked(base, _tokenURI));
}
return super.tokenURI(tokenId);
}
/**
* @dev Sets `_tokenURI` as the tokenURI of `tokenId`.
*
* Requirements:
*
* - `tokenId` must exist.
*/
function _setTokenURI(uint256 tokenId, string memory _tokenURI) internal virtual {
require(_exists(tokenId), "ERC721URIStorage: URI set of nonexistent token");
_tokenURIs[tokenId] = _tokenURI;
}
/**
* @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 override {
super._burn(tokenId);
if (bytes(_tokenURIs[tokenId]).length != 0) {
delete _tokenURIs[tokenId];
}
}
}
/**
* @title ERC721 Burnable Token
* @dev ERC721 Token that can be irreversibly burned (destroyed).
*/
abstract contract ERC721Burnable is Context, ERC721 {
/**
* @dev Burns `tokenId`. See {ERC721-_burn}.
*
* Requirements:
*
* - The caller must own `tokenId` or be an approved operator.
*/
function burn(uint256 tokenId) public virtual {
//solhint-disable-next-line max-line-length
require(_isApprovedOrOwner(_msgSender(), tokenId), "ERC721Burnable: caller is not owner nor approved");
_burn(tokenId);
}
}
/**
* @dev External interface of AccessControl declared to support ERC165 detection.
*/
interface IAccessControl {
/**
* @dev Emitted when `newAdminRole` is set as ``role``'s admin role, replacing `previousAdminRole`
*
* `DEFAULT_ADMIN_ROLE` is the starting admin for all roles, despite
* {RoleAdminChanged} not being emitted signaling this.
*
* _Available since v3.1._
*/
event RoleAdminChanged(bytes32 indexed role, bytes32 indexed previousAdminRole, bytes32 indexed newAdminRole);
/**
* @dev Emitted when `account` is granted `role`.
*
* `sender` is the account that originated the contract call, an admin role
* bearer except when using {AccessControl-_setupRole}.
*/
event RoleGranted(bytes32 indexed role, address indexed account, address indexed sender);
/**
* @dev Emitted when `account` is revoked `role`.
*
* `sender` is the account that originated the contract call:
* - if using `revokeRole`, it is the admin role bearer
* - if using `renounceRole`, it is the role bearer (i.e. `account`)
*/
event RoleRevoked(bytes32 indexed role, address indexed account, address indexed sender);
/**
* @dev Returns `true` if `account` has been granted `role`.
*/
function hasRole(bytes32 role, address account) external view returns (bool);
/**
* @dev Returns the admin role that controls `role`. See {grantRole} and
* {revokeRole}.
*
* To change a role's admin, use {AccessControl-_setRoleAdmin}.
*/
function getRoleAdmin(bytes32 role) external view returns (bytes32);
/**
* @dev Grants `role` to `account`.
*
* If `account` had not been already granted `role`, emits a {RoleGranted}
* event.
*
* Requirements:
*
* - the caller must have ``role``'s admin role.
*/
function grantRole(bytes32 role, address account) external;
/**
* @dev Revokes `role` from `account`.
*
* If `account` had been granted `role`, emits a {RoleRevoked} event.
*
* Requirements:
*
* - the caller must have ``role``'s admin role.
*/
function revokeRole(bytes32 role, address account) external;
/**
* @dev Revokes `role` from the calling account.
*
* Roles are often managed via {grantRole} and {revokeRole}: this function's
* purpose is to provide a mechanism for accounts to lose their privileges
* if they are compromised (such as when a trusted device is misplaced).
*
* If the calling account had been granted `role`, emits a {RoleRevoked}
* event.
*
* Requirements:
*
* - the caller must be `account`.
*/
function renounceRole(bytes32 role, address account) external;
}
/**
* @dev External interface of AccessControlEnumerable declared to support ERC165 detection.
*/
interface IAccessControlEnumerable is IAccessControl {
/**
* @dev Returns one of the accounts that have `role`. `index` must be a
* value between 0 and {getRoleMemberCount}, non-inclusive.
*
* Role bearers are not sorted in any particular way, and their ordering may
* change at any point.
*
* WARNING: When using {getRoleMember} and {getRoleMemberCount}, make sure
* you perform all queries on the same block. See the following
* https://forum.openzeppelin.com/t/iterating-over-elements-on-enumerableset-in-openzeppelin-contracts/2296[forum post]
* for more information.
*/
function getRoleMember(bytes32 role, uint256 index) external view returns (address);
/**
* @dev Returns the number of accounts that have `role`. Can be used
* together with {getRoleMember} to enumerate all bearers of a role.
*/
function getRoleMemberCount(bytes32 role) external view returns (uint256);
}
/**
* @dev Contract module that allows children to implement role-based access
* control mechanisms. This is a lightweight version that doesn't allow enumerating role
* members except through off-chain means by accessing the contract event logs. Some
* applications may benefit from on-chain enumerability, for those cases see
* {AccessControlEnumerable}.
*
* Roles are referred to by their `bytes32` identifier. These should be exposed
* in the external API and be unique. The best way to achieve this is by
* using `public constant` hash digests:
*
* ```
* bytes32 public constant MY_ROLE = keccak256("MY_ROLE");
* ```
*
* Roles can be used to represent a set of permissions. To restrict access to a
* function call, use {hasRole}:
*
* ```
* function foo() public {
* require(hasRole(MY_ROLE, msg.sender));
* ...
* }
* ```
*
* Roles can be granted and revoked dynamically via the {grantRole} and
* {revokeRole} functions. Each role has an associated admin role, and only
* accounts that have a role's admin role can call {grantRole} and {revokeRole}.
*
* By default, the admin role for all roles is `DEFAULT_ADMIN_ROLE`, which means
* that only accounts with this role will be able to grant or revoke other
* roles. More complex role relationships can be created by using
* {_setRoleAdmin}.
*
* WARNING: The `DEFAULT_ADMIN_ROLE` is also its own admin: it has permission to
* grant and revoke this role. Extra precautions should be taken to secure
* accounts that have been granted it.
*/
abstract contract AccessControl is Context, IAccessControl, ERC165 {
struct RoleData {
mapping(address => bool) members;
bytes32 adminRole;
}
mapping(bytes32 => RoleData) private _roles;
bytes32 public constant DEFAULT_ADMIN_ROLE = 0x00;
/**
* @dev Modifier that checks that an account has a specific role. Reverts
* with a standardized message including the required role.
*
* The format of the revert reason is given by the following regular expression:
*
* /^AccessControl: account (0x[0-9a-f]{40}) is missing role (0x[0-9a-f]{64})$/
*
* _Available since v4.1._
*/
modifier onlyRole(bytes32 role) {
_checkRole(role, _msgSender());
_;
}
/**
* @dev See {IERC165-supportsInterface}.
*/
function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) {
return interfaceId == type(IAccessControl).interfaceId || super.supportsInterface(interfaceId);
}
/**
* @dev Returns `true` if `account` has been granted `role`.
*/
function hasRole(bytes32 role, address account) public view override returns (bool) {
return _roles[role].members[account];
}
/**
* @dev Revert with a standard message if `account` is missing `role`.
*
* The format of the revert reason is given by the following regular expression:
*
* /^AccessControl: account (0x[0-9a-f]{40}) is missing role (0x[0-9a-f]{64})$/
*/
function _checkRole(bytes32 role, address account) internal view {
if (!hasRole(role, account)) {
revert(
string(
abi.encodePacked(
"AccessControl: account ",
Strings.toHexString(uint160(account), 20),
" is missing role ",
Strings.toHexString(uint256(role), 32)
)
)
);
}
}
/**
* @dev Returns the admin role that controls `role`. See {grantRole} and
* {revokeRole}.
*
* To change a role's admin, use {_setRoleAdmin}.
*/
function getRoleAdmin(bytes32 role) public view override returns (bytes32) {
return _roles[role].adminRole;
}
/**
* @dev Grants `role` to `account`.
*
* If `account` had not been already granted `role`, emits a {RoleGranted}
* event.
*
* Requirements:
*
* - the caller must have ``role``'s admin role.
*/
function grantRole(bytes32 role, address account) public virtual override onlyRole(getRoleAdmin(role)) {
_grantRole(role, account);
}
/**
* @dev Revokes `role` from `account`.
*
* If `account` had been granted `role`, emits a {RoleRevoked} event.
*
* Requirements:
*
* - the caller must have ``role``'s admin role.
*/
function revokeRole(bytes32 role, address account) public virtual override onlyRole(getRoleAdmin(role)) {
_revokeRole(role, account);
}
/**
* @dev Revokes `role` from the calling account.
*
* Roles are often managed via {grantRole} and {revokeRole}: this function's
* purpose is to provide a mechanism for accounts to lose their privileges
* if they are compromised (such as when a trusted device is misplaced).
*
* If the calling account had been granted `role`, emits a {RoleRevoked}
* event.
*
* Requirements:
*
* - the caller must be `account`.
*/
function renounceRole(bytes32 role, address account) public virtual override {
require(account == _msgSender(), "AccessControl: can only renounce roles for self");
_revokeRole(role, account);
}
/**
* @dev Grants `role` to `account`.
*
* If `account` had not been already granted `role`, emits a {RoleGranted}
* event. Note that unlike {grantRole}, this function doesn't perform any
* checks on the calling account.
*
* [WARNING]
* ====
* This function should only be called from the constructor when setting
* up the initial roles for the system.
*
* Using this function in any other way is effectively circumventing the admin
* system imposed by {AccessControl}.
* ====
*/
function _setupRole(bytes32 role, address account) internal virtual {
_grantRole(role, account);
}
/**
* @dev Sets `adminRole` as ``role``'s admin role.
*
* Emits a {RoleAdminChanged} event.
*/
function _setRoleAdmin(bytes32 role, bytes32 adminRole) internal virtual {
bytes32 previousAdminRole = getRoleAdmin(role);
_roles[role].adminRole = adminRole;
emit RoleAdminChanged(role, previousAdminRole, adminRole);
}
function _grantRole(bytes32 role, address account) private {
if (!hasRole(role, account)) {
_roles[role].members[account] = true;
emit RoleGranted(role, account, _msgSender());
}
}
function _revokeRole(bytes32 role, address account) private {
if (hasRole(role, account)) {
_roles[role].members[account] = false;
emit RoleRevoked(role, account, _msgSender());
}
}
}
/**
* @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.3.0, sets of type `bytes32` (`Bytes32Set`), `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;
if (lastIndex != toDeleteIndex) {
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] = valueIndex; // Replace lastvalue's index to valueIndex
}
// 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) {
return set._values[index];
}
/**
* @dev Return the entire set in an array
*
* WARNING: This operation will copy the entire storage to memory, which can be quite expensive. This is designed
* to mostly be used by view accessors that are queried without any gas fees. Developers should keep in mind that
* this function has an unbounded cost, and using it as part of a state-changing function may render the function
* uncallable if the set grows to a point where copying to memory consumes too much gas to fit in a block.
*/
function _values(Set storage set) private view returns (bytes32[] memory) {
return set._values;
}
// Bytes32Set
struct Bytes32Set {
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(Bytes32Set storage set, bytes32 value) internal returns (bool) {
return _add(set._inner, 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(Bytes32Set storage set, bytes32 value) internal returns (bool) {
return _remove(set._inner, value);
}
/**
* @dev Returns true if the value is in the set. O(1).
*/
function contains(Bytes32Set storage set, bytes32 value) internal view returns (bool) {
return _contains(set._inner, value);
}
/**
* @dev Returns the number of values in the set. O(1).
*/
function length(Bytes32Set 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(Bytes32Set storage set, uint256 index) internal view returns (bytes32) {
return _at(set._inner, index);
}
/**
* @dev Return the entire set in an array
*
* WARNING: This operation will copy the entire storage to memory, which can be quite expensive. This is designed
* to mostly be used by view accessors that are queried without any gas fees. Developers should keep in mind that
* this function has an unbounded cost, and using it as part of a state-changing function may render the function
* uncallable if the set grows to a point where copying to memory consumes too much gas to fit in a block.
*/
function values(Bytes32Set storage set) internal view returns (bytes32[] memory) {
return _values(set._inner);
}
// 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(uint160(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(uint160(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(uint160(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(uint160(uint256(_at(set._inner, index))));
}
/**
* @dev Return the entire set in an array
*
* WARNING: This operation will copy the entire storage to memory, which can be quite expensive. This is designed
* to mostly be used by view accessors that are queried without any gas fees. Developers should keep in mind that
* this function has an unbounded cost, and using it as part of a state-changing function may render the function
* uncallable if the set grows to a point where copying to memory consumes too much gas to fit in a block.
*/
function values(AddressSet storage set) internal view returns (address[] memory) {
bytes32[] memory store = _values(set._inner);
address[] memory result;
assembly {
result := store
}
return result;
}
// 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));
}
/**
* @dev Return the entire set in an array
*
* WARNING: This operation will copy the entire storage to memory, which can be quite expensive. This is designed
* to mostly be used by view accessors that are queried without any gas fees. Developers should keep in mind that
* this function has an unbounded cost, and using it as part of a state-changing function may render the function
* uncallable if the set grows to a point where copying to memory consumes too much gas to fit in a block.
*/
function values(UintSet storage set) internal view returns (uint256[] memory) {
bytes32[] memory store = _values(set._inner);
uint256[] memory result;
assembly {
result := store
}
return result;
}
}
/**
* @dev Extension of {AccessControl} that allows enumerating the members of each role.
*/
abstract contract AccessControlEnumerable is IAccessControlEnumerable, AccessControl {
using EnumerableSet for EnumerableSet.AddressSet;
mapping(bytes32 => EnumerableSet.AddressSet) private _roleMembers;
/**
* @dev See {IERC165-supportsInterface}.
*/
function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) {
return interfaceId == type(IAccessControlEnumerable).interfaceId || super.supportsInterface(interfaceId);
}
/**
* @dev Returns one of the accounts that have `role`. `index` must be a
* value between 0 and {getRoleMemberCount}, non-inclusive.
*
* Role bearers are not sorted in any particular way, and their ordering may
* change at any point.
*
* WARNING: When using {getRoleMember} and {getRoleMemberCount}, make sure
* you perform all queries on the same block. See the following
* https://forum.openzeppelin.com/t/iterating-over-elements-on-enumerableset-in-openzeppelin-contracts/2296[forum post]
* for more information.
*/
function getRoleMember(bytes32 role, uint256 index) public view override returns (address) {
return _roleMembers[role].at(index);
}
/**
* @dev Returns the number of accounts that have `role`. Can be used
* together with {getRoleMember} to enumerate all bearers of a role.
*/
function getRoleMemberCount(bytes32 role) public view override returns (uint256) {
return _roleMembers[role].length();
}
/**
* @dev Overload {grantRole} to track enumerable memberships
*/
function grantRole(bytes32 role, address account) public virtual override(AccessControl, IAccessControl) {
super.grantRole(role, account);
_roleMembers[role].add(account);
}
/**
* @dev Overload {revokeRole} to track enumerable memberships
*/
function revokeRole(bytes32 role, address account) public virtual override(AccessControl, IAccessControl) {
super.revokeRole(role, account);
_roleMembers[role].remove(account);
}
/**
* @dev Overload {renounceRole} to track enumerable memberships
*/
function renounceRole(bytes32 role, address account) public virtual override(AccessControl, IAccessControl) {
super.renounceRole(role, account);
_roleMembers[role].remove(account);
}
/**
* @dev Overload {_setupRole} to track enumerable memberships
*/
function _setupRole(bytes32 role, address account) internal virtual override {
super._setupRole(role, account);
_roleMembers[role].add(account);
}
}
/**
* @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;
}
}
contract ERC721Mochi is ERC721, ERC721Enumerable, ERC721URIStorage, AccessControlEnumerable, ERC721Burnable {
using Counters for Counters.Counter;
bytes32 public constant MINTER_ROLE = keccak256("MINTER_ROLE");
Counters.Counter private _tokenIdCounter;
bool public anyoneCanMint;
constructor(address owner, string memory name, string memory symbol, bool _anyoneCanMint) ERC721(name, symbol) {
_setupRole(DEFAULT_ADMIN_ROLE, owner);
_setupRole(MINTER_ROLE, owner);
anyoneCanMint = _anyoneCanMint;
}
function autoMint(string memory _tokenURI, address to) public onlyMinter {
uint id;
do {
_tokenIdCounter.increment();
id = _tokenIdCounter.current();
} while(_exists(id));
_mint(to, id);
_setTokenURI(id, _tokenURI);
}
function mint(address to, uint256 tokenId) public onlyMinter {
_mint(to, tokenId);
}
function safeMint(address to, uint256 tokenId) public onlyMinter {
_safeMint(to, tokenId);
}
function isMinter(address account) public view returns (bool) {
return hasRole(MINTER_ROLE, account);
}
function safeMint(address to, uint256 tokenId, bytes memory _data) public onlyMinter {
_safeMint(to, tokenId, _data);
}
function _burn(uint256 tokenId) internal virtual override(ERC721, ERC721URIStorage) {
ERC721URIStorage._burn(tokenId);
}
function _beforeTokenTransfer(address from, address to, uint256 tokenId)
internal
override(ERC721, ERC721Enumerable)
{
super._beforeTokenTransfer(from, to, tokenId);
}
function tokenURI(uint256 tokenId)
public
view
override(ERC721, ERC721URIStorage)
returns (string memory)
{
return super.tokenURI(tokenId);
}
function supportsInterface(bytes4 interfaceId)
public
view
override(ERC721, ERC721Enumerable, AccessControlEnumerable)
returns (bool)
{
return super.supportsInterface(interfaceId);
}
function addMinter(address account) public onlyRole(MINTER_ROLE) {
grantRole(MINTER_ROLE, account);
}
function canIMint() public view returns (bool) {
return anyoneCanMint || isMinter(msg.sender);
}
/**
* Open modifier to anyone can mint possibility
*/
modifier onlyMinter() {
string memory mensaje;
require(
canIMint(),
"MinterRole: caller does not have the Minter role"
);
_;
}
}
/**
* @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;
}
}
// 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 no longer needed starting with Solidity 0.8. 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;
}
}
}
contract EIP20 {
uint256 public totalSupply;
uint256 constant private MAX_UINT256 = 2**256 - 1;
mapping (address => uint256) public balances;
mapping (address => mapping (address => uint256)) public allowed;
/*
NOTE:
The following variables are OPTIONAL vanities. One does not have to include them.
They allow one to customise the token contract & in no way influences the core functionality.
Some wallets/interfaces might not even bother to look at this information.
*/
string public name; //fancy name: eg Simon Bucks
uint8 public decimals; //How many decimals to show.
string public symbol; //An identifier: eg SBX
event Transfer(address indexed _from, address indexed _to, uint256 _value);
event Approval(address indexed _owner, address indexed _spender, uint256 _value);
constructor(
uint256 _initialAmount,
string memory _tokenName,
uint8 _decimalUnits,
string memory _tokenSymbol
) {
balances[msg.sender] = _initialAmount; // Give the creator all initial tokens
totalSupply = _initialAmount; // Update total supply
name = _tokenName; // Set the name for display purposes
decimals = _decimalUnits; // Amount of decimals for display purposes
symbol = _tokenSymbol; // Set the symbol for display purposes
}
function transfer(address _to, uint256 _value) public returns (bool success) {
require(balances[msg.sender] >= _value);
balances[msg.sender] -= _value;
balances[_to] += _value;
emit Transfer(msg.sender, _to, _value); //solhint-disable-line indent, no-unused-vars
return true;
}
function transferFrom(address _from, address _to, uint256 _value) public returns (bool success) {
uint256 _allowance = allowed[_from][msg.sender];
require(balances[_from] >= _value && _allowance >= _value);
balances[_to] += _value;
balances[_from] -= _value;
if (_allowance < MAX_UINT256) {
allowed[_from][msg.sender] -= _value;
}
emit Transfer(_from, _to, _value); //solhint-disable-line indent, no-unused-vars
return true;
}
function balanceOf(address _owner) public view returns (uint256 balance) {
return balances[_owner];
}
function approve(address _spender, uint256 _value) public returns (bool success) {
allowed[msg.sender][_spender] = _value;
emit Approval(msg.sender, _spender, _value); //solhint-disable-line indent, no-unused-vars
return true;
}
function allowance(address _owner, address _spender) public view returns (uint256 remaining) {
return allowed[_owner][_spender];
}
}
/**
* @title ERC721Suika
* ERC-721 Marketplace with tokens and royalties support
*/
contract ERC721Suika is ERC721Mochi, ReentrancyGuard {
using SafeMath for uint256;
using Address for address payable;
using Address for address;
// admin address, the owner of the marketplace
address payable admin;
address public contract_owner;
// ERC20 token to be used for payments
EIP20 public payment_token;
// commission rate is a value from 0 to 100
uint256 commissionRate;
// royalties commission rate is a value from 0 to 100
uint256 royaltiesCommissionRate;
// nft item creators list, used to pay royalties
mapping(uint256 => address) public creators;
// last price sold or auctioned
mapping(uint256 => uint256) public soldFor;
// Mapping from token ID to sell price in Ether or to bid price, depending if it is an auction or not
mapping(uint256 => uint256) public sellBidPrice;
// Mapping payment address for tokenId
mapping(uint256 => address payable) private _wallets;
event Sale(uint256 indexed tokenId, address indexed from, address indexed to, uint256 value);
event Commission(uint256 indexed tokenId, address indexed to, uint256 value, uint256 rate, uint256 total);
event Royalty(uint256 indexed tokenId, address indexed to, uint256 value, uint256 rate, uint256 total);
// Auction data
struct Auction {
// Parameters of the auction. Times are either
// absolute unix timestamps (seconds since 1970-01-01)
// or time periods in seconds.
address payable beneficiary;
uint auctionEnd;
// Current state of the auction.
address payable highestBidder;
uint highestBid;
// Set to true at the end, disallows any change
bool open;
// minimum reserve price in wei
uint256 reserve;
}
// mapping auctions for each tokenId
mapping(uint256 => Auction) public auctions;
// Events that will be fired on changes.
event Refund(address bidder, uint amount);
event HighestBidIncreased(address indexed bidder, uint amount, uint256 tokenId);
event AuctionEnded(address winner, uint amount);
event LimitSell(address indexed from, address indexed to, uint256 amount);
event LimitBuy(address indexed from, address indexed to, uint256 amount);
event MarketSell(address indexed from, address indexed to, uint256 amount);
event MarketBuy(address indexed from, address indexed to, uint256 amount);
constructor(
EIP20 _payment_token, address _owner, address payable _admin,
uint256 _commissionRate, uint256 _royaltiesCommissionRate, string memory name, string memory symbol, bool _anyoneCanMint)
ERC721Mochi(_owner, name, symbol, _anyoneCanMint)
{
admin = _admin;
contract_owner = _owner;
require(_commissionRate<=100, "ERC721Suika: Commission rate has to be between 0 and 100");
commissionRate = _commissionRate;
royaltiesCommissionRate = _royaltiesCommissionRate;
payment_token = _payment_token;
}
function canSell(uint256 tokenId) public view returns (bool) {
return (ownerOf(tokenId)==msg.sender && !auctions[tokenId].open);
}
// Sell option for a fixed price
function sell(uint256 tokenId, uint256 price, address payable wallet) public {
// onlyOwner
require(ownerOf(tokenId)==msg.sender, "ERC721Suika: Only owner can sell this item");
// cannot set a price if auction is activated
require(!auctions[tokenId].open, "ERC721Suika: Cannot sell an item which has an active auction");
// set sell price for index
sellBidPrice[tokenId] = price;
// If price is zero, means not for sale
if (price>0) {
// approve the Index to the current contract
approve(address(this), tokenId);
// set wallet payment
_wallets[tokenId] = wallet;
}
}
// simple function to return the price of a tokenId
// returns: sell price, bid price, sold price, only one can be non zero
function getPrice(uint256 tokenId) public view returns (uint256, uint256, uint256) {
if (sellBidPrice[tokenId]>0) return (sellBidPrice[tokenId], 0, 0);
if (auctions[tokenId].highestBid>0) return (0, auctions[tokenId].highestBid, 0);
return (0, 0, soldFor[tokenId]);
}
function canBuy(uint256 tokenId) public view returns (uint256) {
if (!auctions[tokenId].open && sellBidPrice[tokenId]>0 && sellBidPrice[tokenId]>0 && getApproved(tokenId) == address(this)) {
return sellBidPrice[tokenId];
} else {
return 0;
}
}
// Buy option
function buy(uint256 tokenId) public nonReentrant {
// is on sale
require(!auctions[tokenId].open && sellBidPrice[tokenId]>0, "ERC721Suika: The collectible is not for sale");
// transfer ownership
address owner = ownerOf(tokenId);
require(msg.sender!=owner, "ERC721Suika: The seller cannot buy his own collectible");
// we need to call a transferFrom from this contract, which is the one with permission to sell the NFT
callOptionalReturn(this, abi.encodeWithSelector(this.transferFrom.selector, owner, msg.sender, tokenId));
// calculate amounts
uint256 amount4admin = sellBidPrice[tokenId].mul(commissionRate).div(100);
uint256 amount4creator = sellBidPrice[tokenId].mul(royaltiesCommissionRate).div(100);
uint256 amount4owner = sellBidPrice[tokenId].sub(amount4admin).sub(amount4creator);
// to owner
require(payment_token.transferFrom(msg.sender, _wallets[tokenId], amount4owner), "Transfer failed.");
// to creator
if (amount4creator>0) {
require(payment_token.transferFrom(msg.sender, creators[tokenId], amount4creator), "Transfer failed.");
}
// to admin
if (amount4admin>0) {
require(payment_token.transferFrom(msg.sender, admin, amount4admin), "Transfer failed.");
}
emit Sale(tokenId, owner, msg.sender, sellBidPrice[tokenId]);
emit Commission(tokenId, owner, sellBidPrice[tokenId], commissionRate, amount4admin);
emit Royalty(tokenId, owner, sellBidPrice[tokenId], royaltiesCommissionRate, amount4creator);
soldFor[tokenId] = sellBidPrice[tokenId];
// close the sell
sellBidPrice[tokenId] = 0;
delete _wallets[tokenId];
}
function canAuction(uint256 tokenId) public view returns (bool) {
return (ownerOf(tokenId)==msg.sender && !auctions[tokenId].open && sellBidPrice[tokenId]==0);
}
// Instantiate an auction contract for a tokenId
function createAuction(uint256 tokenId, uint _closingTime, address payable _beneficiary, uint256 _reservePrice) public {
require(sellBidPrice[tokenId]==0, "ERC721Suika: The selected NFT is open for sale, cannot be auctioned");
require(!auctions[tokenId].open, "ERC721Suika: The selected NFT already has an auction");
require(ownerOf(tokenId)==msg.sender, "ERC721Suika: Only owner can auction this item");
auctions[tokenId].beneficiary = _beneficiary;
auctions[tokenId].auctionEnd = _closingTime;
auctions[tokenId].reserve = _reservePrice;
auctions[tokenId].open = true;
// approve the Index to the current contract
approve(address(this), tokenId);
}
function canBid(uint256 tokenId) public view returns (bool) {
if (!msg.sender.isContract() &&
auctions[tokenId].open &&
block.timestamp <= auctions[tokenId].auctionEnd &&
msg.sender != ownerOf(tokenId) &&
getApproved(tokenId) == address(this)
) {
return true;
} else {
return false;
}
}
/// Overrides minting function to keep track of item creators
function _mint(address to, uint256 tokenId) override internal {
creators[tokenId] = msg.sender;
super._mint(to, tokenId);
}
/// Bid on the auction with the value sent
/// together with this transaction.
/// The value will only be refunded if the
/// auction is not won.
function bid(uint256 tokenId, uint256 bid_value) public nonReentrant {
// Contracts cannot bid, because they can block the auction with a reentrant attack
require(!msg.sender.isContract(), "No script kiddies");
// auction has to be opened
require(auctions[tokenId].open, "No opened auction found");
// approve was lost
require(getApproved(tokenId) == address(this), "Cannot complete the auction");
// Revert the call if the bidding
// period is over.
require(
block.timestamp <= auctions[tokenId].auctionEnd,
"Auction already ended."
);
// If the bid is not higher, send the
// money back.
require(
bid_value > auctions[tokenId].highestBid,
"There already is a higher bid."
);
address owner = ownerOf(tokenId);
require(msg.sender!=owner, "ERC721Suika: The owner cannot bid his own collectible");
// return the funds to the previous bidder, if there is one
if (auctions[tokenId].highestBid>0) {
require(payment_token.transfer(auctions[tokenId].highestBidder, auctions[tokenId].highestBid), "Transfer failed.");
emit Refund(auctions[tokenId].highestBidder, auctions[tokenId].highestBid);
}
// now store the bid data
auctions[tokenId].highestBidder = payable(msg.sender);
// transfer tokens to contract
require(payment_token.transferFrom(msg.sender, address(this), bid_value), "Transfer failed.");
// register the highest bid value
auctions[tokenId].highestBid = bid_value;
emit HighestBidIncreased(msg.sender, bid_value, tokenId);
}
// anyone can execute withdraw if auction is opened and
// the bid time expired and the reserve was not met
// or
// the auction is openen but the contract is unable to transfer
function canWithdraw(uint256 tokenId) public view returns (bool) {
if (auctions[tokenId].open &&
(
(
block.timestamp >= auctions[tokenId].auctionEnd &&
auctions[tokenId].highestBid > 0 &&
auctions[tokenId].highestBid<auctions[tokenId].reserve
) ||
getApproved(tokenId) != address(this)
)
) {
return true;
} else {
return false;
}
}
/// Withdraw a bid when the auction is not finalized
function withdraw(uint256 tokenId) public nonReentrant {
require(canWithdraw(tokenId), "Conditions to withdraw are not met");
// transfer funds to highest bidder always
if (auctions[tokenId].highestBid > 0) {
require(payment_token.transfer(auctions[tokenId].highestBidder, auctions[tokenId].highestBid), "Transfer failed.");
}
// finalize the auction
delete auctions[tokenId];
}
function canFinalize(uint256 tokenId) public view returns (bool) {
if (auctions[tokenId].open &&
block.timestamp >= auctions[tokenId].auctionEnd &&
(
auctions[tokenId].highestBid>=auctions[tokenId].reserve ||
auctions[tokenId].highestBid==0
)
) {
return true;
} else {
return false;
}
}
// implement the auctionFinalize including the NFT transfer logic
function auctionFinalize(uint256 tokenId) public nonReentrant {
require(canFinalize(tokenId), "Cannot finalize");
if (auctions[tokenId].highestBid>0) {
// transfer the ownership of token to the highest bidder
address payable _highestBidder = auctions[tokenId].highestBidder;
// calculate payment amounts
uint256 amount4admin = auctions[tokenId].highestBid.mul(commissionRate).div(100);
uint256 amount4creator = auctions[tokenId].highestBid.mul(royaltiesCommissionRate).div(100);
uint256 amount4owner = auctions[tokenId].highestBid.sub(amount4admin).sub(amount4creator);
// to owner
require(payment_token.transfer(auctions[tokenId].beneficiary, amount4owner), "Transfer failed.");
// to creator
if (amount4creator>0) {
require(payment_token.transfer(creators[tokenId], amount4creator), "Transfer failed.");
}
// to admin
if (amount4admin>0) {
require(payment_token.transfer(admin, amount4admin), "Transfer failed.");
}
emit Sale(tokenId, auctions[tokenId].beneficiary, _highestBidder, auctions[tokenId].highestBid);
emit Royalty(tokenId, auctions[tokenId].beneficiary, auctions[tokenId].highestBid, royaltiesCommissionRate, amount4creator);
emit Commission(tokenId, auctions[tokenId].beneficiary, auctions[tokenId].highestBid, commissionRate, amount4admin);
// transfer ownership
address owner = ownerOf(tokenId);
// we need to call a transferFrom from this contract, which is the one with permission to sell the NFT
// transfer the NFT to the auction's highest bidder
callOptionalReturn(this, abi.encodeWithSelector(this.transferFrom.selector, owner, _highestBidder, tokenId));
soldFor[tokenId] = auctions[tokenId].highestBid;
}
emit AuctionEnded(auctions[tokenId].highestBidder, auctions[tokenId].highestBid);
// finalize the auction
delete auctions[tokenId];
}
// Bid query functions
function highestBidder(uint256 tokenId) public view returns (address payable) {
return auctions[tokenId].highestBidder;
}
function highestBid(uint256 tokenId) public view returns (uint256) {
return auctions[tokenId].highestBid;
}
/**
* @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(IERC721 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(), "SafeERC721: call to non-contract");
// solhint-disable-next-line avoid-low-level-calls
(bool success, bytes memory returndata) = address(token).call(data);
require(success, "SafeERC721: low-level call failed");
if (returndata.length > 0) { // Return data is optional
// solhint-disable-next-line max-line-length
require(abi.decode(returndata, (bool)), "SafeERC721: ERC20 operation did not succeed");
}
}
// update contract fields
function updateAdmin(address payable _admin, uint256 _commissionRate, uint256 _royaltiesCommissionRate, bool _anyoneCanMint, EIP20 _payment_token) public {
require(msg.sender==contract_owner, "Only contract owner can do this");
admin = _admin;
commissionRate = _commissionRate;
royaltiesCommissionRate = _royaltiesCommissionRate;
anyoneCanMint = _anyoneCanMint;
payment_token = _payment_token;
}
// update owner
function updateOwner(address _contract_owner) public {
require(msg.sender==contract_owner, "Only contract owner can do this");
// grant roles to new owner
_setupRole(DEFAULT_ADMIN_ROLE, _contract_owner);
_setupRole(MINTER_ROLE, _contract_owner);
// revoke roles of old owner
revokeRole(MINTER_ROLE, contract_owner);
_setupRole(DEFAULT_ADMIN_ROLE, contract_owner);
// change ownership
contract_owner = _contract_owner;
}
} | Bid on the auction with the value sent together with this transaction. The value will only be refunded if the auction is not won. Contracts cannot bid, because they can block the auction with a reentrant attack auction has to be opened approve was lost Revert the call if the bidding period is over. If the bid is not higher, send the money back. return the funds to the previous bidder, if there is one | function bid(uint256 tokenId, uint256 bid_value) public nonReentrant {
require(!msg.sender.isContract(), "No script kiddies");
require(auctions[tokenId].open, "No opened auction found");
require(getApproved(tokenId) == address(this), "Cannot complete the auction");
require(
block.timestamp <= auctions[tokenId].auctionEnd,
"Auction already ended."
);
require(
bid_value > auctions[tokenId].highestBid,
"There already is a higher bid."
);
address owner = ownerOf(tokenId);
require(msg.sender!=owner, "ERC721Suika: The owner cannot bid his own collectible");
if (auctions[tokenId].highestBid>0) {
require(payment_token.transfer(auctions[tokenId].highestBidder, auctions[tokenId].highestBid), "Transfer failed.");
emit Refund(auctions[tokenId].highestBidder, auctions[tokenId].highestBid);
}
emit HighestBidIncreased(msg.sender, bid_value, tokenId);
}
| 1,140,422 | [
1,
17763,
603,
326,
279,
4062,
598,
326,
460,
3271,
9475,
598,
333,
2492,
18,
1021,
460,
903,
1338,
506,
1278,
12254,
309,
326,
279,
4062,
353,
486,
8462,
18,
30131,
2780,
9949,
16,
2724,
2898,
848,
1203,
326,
279,
4062,
598,
279,
283,
8230,
970,
13843,
279,
4062,
711,
358,
506,
10191,
6617,
537,
1703,
13557,
868,
1097,
326,
745,
309,
326,
324,
1873,
310,
3879,
353,
1879,
18,
971,
326,
9949,
353,
486,
10478,
16,
1366,
326,
15601,
1473,
18,
327,
326,
284,
19156,
358,
326,
2416,
9949,
765,
16,
309,
1915,
353,
1245,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
565,
445,
9949,
12,
11890,
5034,
1147,
548,
16,
2254,
5034,
9949,
67,
1132,
13,
1071,
1661,
426,
8230,
970,
288,
203,
203,
3639,
2583,
12,
5,
3576,
18,
15330,
18,
291,
8924,
9334,
315,
2279,
2728,
417,
1873,
606,
8863,
203,
203,
3639,
2583,
12,
69,
4062,
87,
63,
2316,
548,
8009,
3190,
16,
315,
2279,
10191,
279,
4062,
1392,
8863,
203,
203,
3639,
2583,
12,
588,
31639,
12,
2316,
548,
13,
422,
1758,
12,
2211,
3631,
315,
4515,
3912,
326,
279,
4062,
8863,
203,
203,
3639,
2583,
12,
203,
5411,
1203,
18,
5508,
1648,
279,
4062,
87,
63,
2316,
548,
8009,
69,
4062,
1638,
16,
203,
5411,
315,
37,
4062,
1818,
16926,
1199,
203,
3639,
11272,
203,
203,
3639,
2583,
12,
203,
5411,
9949,
67,
1132,
405,
279,
4062,
87,
63,
2316,
548,
8009,
8766,
395,
17763,
16,
203,
5411,
315,
9828,
1818,
353,
279,
10478,
9949,
1199,
203,
3639,
11272,
203,
203,
3639,
1758,
3410,
273,
3410,
951,
12,
2316,
548,
1769,
203,
3639,
2583,
12,
3576,
18,
15330,
5,
33,
8443,
16,
315,
654,
39,
27,
5340,
17072,
21256,
30,
1021,
3410,
2780,
9949,
18423,
4953,
3274,
1523,
8863,
203,
203,
3639,
309,
261,
69,
4062,
87,
63,
2316,
548,
8009,
8766,
395,
17763,
34,
20,
13,
288,
203,
5411,
2583,
12,
9261,
67,
2316,
18,
13866,
12,
69,
4062,
87,
63,
2316,
548,
8009,
8766,
395,
17763,
765,
16,
279,
4062,
87,
63,
2316,
548,
8009,
8766,
395,
17763,
3631,
315,
5912,
2535,
1199,
1769,
203,
5411,
3626,
3941,
2
] |
// 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;
}
}
/**
* @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);
}
/*
* @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 returns (address payable) {
return msg.sender;
}
function _msgData() internal view returns (bytes memory) {
this; // silence state mutability warning without generating bytecode - see https://github.com/ethereum/solidity/issues/2691
return msg.data;
}
}
/**
* @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;
address private _newOwner;
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 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 Accept the ownership transfer. This is to make sure that the contract is
* transferred to a working address
*
* Can only be called by the newly transfered owner.
*/
function acceptOwnership() public {
require(_msgSender() == _newOwner, "Ownable: only new owner can accept ownership");
address oldOwner = _owner;
_owner = _newOwner;
_newOwner = address(0);
emit OwnershipTransferred(oldOwner, _owner);
}
/**
* @dev Transfers ownership of the contract to a new account (`newOwner`).
*
* Can only be called by the current owner.
*/
function transferOwnership(address newOwner) public onlyOwner {
require(newOwner != address(0), "Ownable: new owner is the zero address");
_newOwner = newOwner;
}
}
/**
* @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 `whenNotFrozen` and `whenFrozen`, 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, Ownable {
/**
* @dev Emitted when the freeze is triggered by `account`.
*/
event Frozen(address account);
/**
* @dev Emitted when the freeze is lifted by `account`.
*/
event Unfrozen(address account);
bool private _frozen;
/**
* @dev Initializes the contract in unfrozen state.
*/
constructor () {
_frozen = false;
}
/**
* @dev Returns true if the contract is frozen, and false otherwise.
*/
function frozen() public view returns (bool) {
return _frozen;
}
/**
* @dev Modifier to make a function callable only when the contract is not frozen.
*
* Requirements:
*
* - The contract must not be frozen.
*/
modifier whenNotFrozen() {
require(!frozen(), "Freezable: frozen");
_;
}
/**
* @dev Modifier to make a function callable only when the contract is frozen.
*
* Requirements:
*
* - The contract must be frozen.
*/
modifier whenFrozen() {
require(frozen(), "Freezable: frozen");
_;
}
/**
* @dev Triggers stopped state.
*
* Requirements:
*
* - The contract must not be frozen.
*/
function _freeze() internal whenNotFrozen {
_frozen = true;
emit Frozen(_msgSender());
}
/**
* @dev Returns to normal state.
*
* Requirements:
*
* - Can only be called by the current owner.
* - The contract must be frozen.
*/
function _unfreeze() internal whenFrozen {
_frozen = false;
emit Unfrozen(_msgSender());
}
}
/**
* @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 Coin98 is Context, Ownable, Pausable, IERC20 {
using SafeMath for uint256;
mapping (address => uint256) private _balances;
mapping (address => mapping (address => uint256)) private _allowances;
uint256 private _maxSupply;
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() {
uint256 fractions = 10 ** uint256(18);
_name = "Coin98";
_symbol = "C98";
_decimals = 18;
_maxSupply = 1000000000 * fractions;
}
/**
* @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 override returns (bool) {
_transfer(_msgSender(), recipient, amount);
return true;
}
/**
* @dev See {IERC20-allowance}.
*/
function allowance(address owner, address spender) public view 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 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 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 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 returns (bool) {
_approve(_msgSender(), spender, _allowances[_msgSender()][spender].sub(subtractedValue, "ERC20: decreased allowance below zero"));
return true;
}
/**
* @dev Issues `amount` tokens to the designated `address`.
*
* Can only be called by the current owner.
* See {ERC20-_mint}.
*/
function mint(address account, uint256 amount) public onlyOwner {
_mint(account, amount);
}
/**
* @dev Destroys `amount` tokens from the caller.
*
* See {ERC20-_burn}.
*/
function burn(uint256 amount) public {
_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 {
uint256 decreasedAllowance = allowance(account, _msgSender()).sub(amount, "ERC20: burn amount exceeds allowance");
_approve(account, _msgSender(), decreasedAllowance);
_burn(account, amount);
}
/**
* @dev Disable the {transfer}, {mint} and {burn} functions of contract.
*
* Can only be called by the current owner.
* The contract must not be frozen.
*/
function freeze() public onlyOwner {
_freeze();
}
/**
* @dev Enable the {transfer}, {mint} and {burn} functions of contract.
*
* Can only be called by the current owner.
* The contract must be frozen.
*/
function unfreeze() public onlyOwner {
_unfreeze();
}
/**
* @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 {
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 {
require(account != address(0), "ERC20: mint to the zero address");
require(_totalSupply + amount <= _maxSupply, "ERC20: mint amount exceeds max supply");
_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 {
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 {
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 {
require(!frozen(), "ERC20: token transfer while frozen");
}
function _afterTokenTransfer(
address from,
address to,
uint256 amount
) internal {}
} | * @dev Emitted when the freeze is triggered by `account`./* @dev Emitted when the freeze is lifted by `account`./* @dev Initializes the contract in unfrozen state./ | constructor () {
_frozen = false;
}
| 186,151 | [
1,
1514,
11541,
1347,
326,
16684,
353,
10861,
635,
1375,
4631,
8338,
19,
225,
512,
7948,
1347,
326,
16684,
353,
28080,
329,
635,
1375,
4631,
8338,
19,
225,
10188,
3128,
326,
6835,
316,
640,
28138,
919,
18,
19,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
225,
3885,
1832,
288,
203,
565,
389,
28138,
273,
629,
31,
203,
225,
289,
203,
203,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
] |
/**
*Submitted for verification at Etherscan.io on 2022-02-27
*/
// File: contracts/LampsPaymentSplitter.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;
// 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);
}
}
}
}
/**
* @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);
}
library SafeERC20Upgradeable {
using Address for address;
function safeTransfer(IERC20Upgradeable token, address to, uint256 value) internal {
_callOptionalReturn(token, abi.encodeWithSelector(token.transfer.selector, to, value));
}
function safeTransferFrom(IERC20Upgradeable 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(IERC20Upgradeable 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(IERC20Upgradeable 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(IERC20Upgradeable 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(IERC20Upgradeable 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");
}
}
}
contract PaymentSplitter {
using SafeERC20Upgradeable for IERC20Upgradeable;
address payable constant TREASURY = payable(0x0bA6585009c2E275CdE3Ede4Ab086d2c8b71b155);
address payable constant UWULABS = payable(0x354A70969F0b4a4C994403051A81C2ca45db3615);
address payable constant CM = payable(0xD80b6996C73BA77FF96FF2ADA982eBA1cb73d387);
address payable constant CA = payable(0xFeB95163E713ADa2594Fe50CA0462a89db32cCa8);
address payable constant MOD = payable(0xfd45CD3ACa3c21e1600f07eA60CAA96B2d6d3D05);
address payable constant WEBDEV = payable(0x06046310B5483d4c185D9d87933D944405Ceb981);
address payable constant WRITER = payable(0x118B91e2F362D5B3ecb7a6bebce08Ea617c659E9);
address payable constant ARTIST = payable(0x8C0dd928691113D5C91D678aE7c7818F6a036E04);
address payable constant NIKHIMA = payable(0xb304b3205862dF57e1718FFE0A1E7165c89c1482);
/**
* @dev The Ether received will be logged with {PaymentReceived} events. Note that these events are not fully
* reliable: it's possible for a contract to receive Ether without triggering this function. This only affects the
* reliability of the events, and not the actual splitting of Ether.
*
* To learn more about this see the Solidity documentation for
* https://solidity.readthedocs.io/en/latest/contracts.html#fallback-function[fallback
* functions].
*/
receive() external payable virtual {
uint256 totalBalance = address(this).balance;
sendValue(TREASURY, percentOfTotal(totalBalance, 0.30 gwei)); // 1.5%/5% - 30% of royalties
sendValue(UWULABS, percentOfTotal(totalBalance, 0.10 gwei)); // 0.5%/5% - 10% of royalties
sendValue(CM, percentOfTotal(totalBalance, 0.03 gwei)); // 0.15%/5% - 3% of royalties
sendValue(CA, percentOfTotal(totalBalance, 0.03 gwei)); // 0.15%/5% - 3% of royalties
sendValue(MOD, percentOfTotal(totalBalance, 0.03 gwei)); // 0.15%/5% - 3% of royalties
sendValue(WEBDEV, percentOfTotal(totalBalance, 0.03 gwei)); // 0.15%/5% - 3% of royalties
sendValue(WRITER, percentOfTotal(totalBalance, 0.03 gwei)); // 0.15%/5% - 3% of royalties
sendValue(ARTIST, percentOfTotal(totalBalance, 0.15 gwei)); // 0.75%/5% - 15% of royalties
sendValue(NIKHIMA, address(this).balance); // 1.5%/5% - 30% of royalties
}
function percentOfTotal(uint256 total, uint256 percentInGwei) internal pure returns (uint256) {
return (total * percentInGwei) / 1 gwei;
}
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");
}
function rescue(address token) external {
if (token == address(0)) {
uint256 totalBalance = address(this).balance;
sendValue(TREASURY, percentOfTotal(totalBalance, 0.30 gwei)); // 1.5%/5% - 30% of royalties
sendValue(UWULABS, percentOfTotal(totalBalance, 0.10 gwei)); // 0.5%/5% - 10% of royalties
sendValue(CM, percentOfTotal(totalBalance, 0.03 gwei)); // 0.15%/5% - 3% of royalties
sendValue(CA, percentOfTotal(totalBalance, 0.03 gwei)); // 0.15%/5% - 3% of royalties
sendValue(MOD, percentOfTotal(totalBalance, 0.03 gwei)); // 0.15%/5% - 3% of royalties
sendValue(WEBDEV, percentOfTotal(totalBalance, 0.03 gwei)); // 0.15%/5% - 3% of royalties
sendValue(WRITER, percentOfTotal(totalBalance, 0.03 gwei)); // 0.15%/5% - 3% of royalties
sendValue(ARTIST, percentOfTotal(totalBalance, 0.15 gwei)); // 0.75%/5% - 15% of royalties
sendValue(NIKHIMA, address(this).balance); // 1.5%/5% - 30% of royalties
} else {
uint256 totalBalance = IERC20Upgradeable(token).balanceOf(address(this));
IERC20Upgradeable(token).safeTransfer(TREASURY, percentOfTotal(totalBalance, 0.30 gwei)); // 1.5%/5% - 30% of royalties
IERC20Upgradeable(token).safeTransfer(UWULABS, percentOfTotal(totalBalance, 0.10 gwei)); // 0.5%/5% - 10% of royalties
IERC20Upgradeable(token).safeTransfer(CM, percentOfTotal(totalBalance, 0.03 gwei)); // 0.15%/5% - 3% of royalties
IERC20Upgradeable(token).safeTransfer(CA, percentOfTotal(totalBalance, 0.03 gwei)); // 0.15%/5% - 3% of royalties
IERC20Upgradeable(token).safeTransfer(MOD, percentOfTotal(totalBalance, 0.03 gwei)); // 0.15%/5% - 3% of royalties
IERC20Upgradeable(token).safeTransfer(WEBDEV, percentOfTotal(totalBalance, 0.03 gwei)); // 0.15%/5% - 3% of royalties
IERC20Upgradeable(token).safeTransfer(WRITER, percentOfTotal(totalBalance, 0.03 gwei)); // 0.15%/5% - 3% of royalties
IERC20Upgradeable(token).safeTransfer(ARTIST, percentOfTotal(totalBalance, 0.15 gwei)); // 0.75%/5% - 15% of royalties
IERC20Upgradeable(token).safeTransfer(NIKHIMA, IERC20Upgradeable(token).balanceOf(address(this))); // 1.5%/5% - 30% of royalties
}
}
} | 0.15%/5% - 3% of royalties
| IERC20Upgradeable(token).safeTransfer(WEBDEV, percentOfTotal(totalBalance, 0.03 gwei)); | 2,113,185 | [
1,
20,
18,
3600,
9,
19,
25,
9,
300,
890,
9,
434,
721,
93,
2390,
606,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
5411,
467,
654,
39,
3462,
10784,
429,
12,
2316,
2934,
4626,
5912,
12,
14778,
15301,
16,
5551,
951,
5269,
12,
4963,
13937,
16,
374,
18,
4630,
314,
1814,
77,
10019,
225,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
] |
// SPDX-License-Identifier: MIT
pragma solidity 0.7.6;
/// Any contracts that want to recieve a trigger from Flare keeper should
/// implement IFlareKeep
interface IFlareKeep {
/// implement this function for recieving a trigger from FlareKeeper
function keep() external returns(bool);
}
| Any contracts that want to recieve a trigger from Flare keeper should implement IFlareKeep | interface IFlareKeep {
function keep() external returns(bool);
pragma solidity 0.7.6;
}
| 928,612 | [
1,
2961,
20092,
716,
2545,
358,
1950,
21271,
279,
3080,
628,
3857,
834,
417,
9868,
1410,
377,
2348,
467,
2340,
834,
11523,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
5831,
467,
2340,
834,
11523,
288,
203,
203,
565,
445,
3455,
1435,
3903,
1135,
12,
6430,
1769,
203,
683,
9454,
18035,
560,
374,
18,
27,
18,
26,
31,
203,
97,
203,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
] |
pragma solidity ^0.4.16;
contract owned {
address public owner;
function owned() public {
owner = msg.sender;
}
modifier onlyOwner {
require(msg.sender == owner);
_;
}
function transferOwnership(address newOwner) onlyOwner public {
owner = newOwner;
}
}
interface tokenRecipient {
function receiveApproval(address _from, uint256 _value, address _token, bytes _extraData) public;
}
contract TokenERC20 {
// Public variables of the token
string public name;
string public symbol;
uint8 public decimals = 18;
// 18 decimals is the strongly suggested default, avoid changing it
uint256 public totalSupply;
// This creates an array with all balances
mapping (address => uint256) public balanceOf;
mapping (address => mapping (address => uint256)) public allowance;
// This generates a public event on the blockchain that will notify clients
event Transfer(address indexed from, address indexed to, uint256 value);
// This notifies clients about the amount burnt
event Burn(address indexed from, uint256 value);
/**
* Constrctor function
*
* Initializes contract with initial supply tokens to the creator of the contract
*/
function TokenERC20(
uint256 initialSupply,
string tokenName,
string tokenSymbol
) public {
totalSupply = initialSupply * 10 ** uint256(decimals); // Update total supply with the decimal amount
balanceOf[msg.sender] = totalSupply; // Give the creator all initial tokens
name = tokenName; // Set the name for display purposes
symbol = tokenSymbol; // Set the symbol for display purposes
}
/**
* Internal transfer, only can be called by this contract
*/
function _transfer(address _from, address _to, uint _value) {
// Prevent transfer to 0x0 address. Use burn() instead
require(_to != 0x0);
// Check if the sender has enough
require(balanceOf[_from] >= _value);
// Check for overflows
require(balanceOf[_to] + _value > balanceOf[_to]);
// Save this for an assertion in the future
uint previousBalances = balanceOf[_from] + balanceOf[_to];
// Subtract from the sender
balanceOf[_from] -= _value;
// Add the same to the recipient
balanceOf[_to] += _value;
Transfer(_from, _to, _value);
// Asserts are used to use static analysis to find bugs in your code. They should never fail
assert(balanceOf[_from] + balanceOf[_to] == previousBalances);
}
/**
* Transfer tokens
*
* Send `_value` tokens to `_to` from your account
*
* @param _to The address of the recipient
* @param _value the amount to send
*/
function transfer(address _to, uint256 _value) public returns (bool success)
{
_transfer(msg.sender, _to, _value);
return true;
}
/**
* Transfer tokens from other address
*
* Send `_value` tokens to `_to` in behalf of `_from`
*
* @param _from The address of the sender
* @param _to The address of the recipient
* @param _value the amount to send
*/
function transferFrom(address _from, address _to, uint256 _value) public returns (bool success) {
require(_value <= allowance[_from][msg.sender]); // Check allowance
allowance[_from][msg.sender] -= _value;
_transfer(_from, _to, _value);
return true;
}
/**
* Set allowance for other address
*
* Allows `_spender` to spend no more than `_value` tokens in your behalf
*
* @param _spender The address authorized to spend
* @param _value the max amount they can spend
*/
function approve(address _spender, uint256 _value) public
returns (bool success) {
allowance[msg.sender][_spender] = _value;
return true;
}
/**
* Set allowance for other address and notify
*
* Allows `_spender` to spend no more than `_value` tokens in your behalf, and then ping the contract about it
*
* @param _spender The address authorized to spend
* @param _value the max amount they can spend
* @param _extraData some extra information to send to the approved contract
*/
function approveAndCall(address _spender, uint256 _value, bytes _extraData)
public
returns (bool success) {
tokenRecipient spender = tokenRecipient(_spender);
if (approve(_spender, _value)) {
spender.receiveApproval(msg.sender, _value, this, _extraData);
return true;
}
}
function burn(uint256 _value) public returns (bool success) {
require(balanceOf[msg.sender] >= _value); // Check if the sender has enough
balanceOf[msg.sender] -= _value; // Subtract from the sender
totalSupply -= _value; // Updates totalSupply
Burn(msg.sender, _value);
return true;
}
function burnFrom(address _from, uint256 _value) public returns (bool success) {
require(balanceOf[_from] >= _value); // Check if the targeted balance is enough
require(_value <= allowance[_from][msg.sender]); // Check allowance
balanceOf[_from] -= _value; // Subtract from the targeted balance
allowance[_from][msg.sender] -= _value; // Subtract from the sender's allowance
totalSupply -= _value; // Update totalSupply
Burn(_from, _value);
return true;
}
}
contract WorldTrade is owned, TokenERC20 {
uint256 public sellPrice;
uint256 public buyPrice;
mapping (address => bool) public frozenAccount;
/* This generates a public event on the blockchain that will notify clients */
event FrozenFunds(address target, bool frozen);
/* Initializes contract with initial supply tokens to the creator of the contract */
function WorldTrade(
uint256 initialSupply,
string tokenName,
string tokenSymbol
) TokenERC20(initialSupply, tokenName, tokenSymbol) public {}
/// @notice Create `mintedAmount` tokens and send it to `target`
/// @param target Address to receive the tokens
/// @param mintedAmount the amount of tokens it will receive
function mintToken(address target, uint256 mintedAmount) onlyOwner public {
balanceOf[target] += mintedAmount;
totalSupply += mintedAmount;
Transfer(0, this, mintedAmount);
Transfer(this, target, mintedAmount);
}
/// @notice `freeze? Prevent | Allow` `target` from sending & receiving tokens
/// @param target Address to be frozen
/// @param freeze either to freeze it or not
function freezeAccount(address target, bool freeze) onlyOwner public {
frozenAccount[target] = freeze;
FrozenFunds(target, freeze);
}
/// @notice Allow users to buy tokens for `newBuyPrice` eth and sell tokens for `newSellPrice` eth
/// @param newSellPrice Price the users can sell to the contract
/// @param newBuyPrice Price users can buy from the contract
function setPrices(uint256 newSellPrice, uint256 newBuyPrice) onlyOwner public {
sellPrice = newSellPrice;
buyPrice = newBuyPrice;
}
/// @notice Buy tokens from contract by sending ether
function buy() payable public {
uint amount = msg.value / buyPrice; // calculates the amount
_transfer(this, msg.sender, amount); // makes the transfers
}
/// @notice Sell `amount` tokens to contract
/// @param amount amount of tokens to be sold
function sell(uint256 amount) public {
require(this.balance >= amount * sellPrice); // checks if the contract has enough ether to buy
_transfer(msg.sender, this, amount); // makes the transfers
msg.sender.transfer(amount * sellPrice); // sends ether to the seller. It's important to do this last to avoid recursion attacks
}
} | * Set allowance for other address and notify Allows `_spender` to spend no more than `_value` tokens in your behalf, and then ping the contract about it @param _spender The address authorized to spend @param _value the max amount they can spend @param _extraData some extra information to send to the approved contract/ | function approveAndCall(address _spender, uint256 _value, bytes _extraData)
public
returns (bool success) {
tokenRecipient spender = tokenRecipient(_spender);
if (approve(_spender, _value)) {
spender.receiveApproval(msg.sender, _value, this, _extraData);
return true;
}
}
| 15,447,814 | [
1,
694,
1699,
1359,
364,
1308,
1758,
471,
5066,
25619,
1375,
67,
87,
1302,
264,
68,
358,
17571,
1158,
1898,
2353,
1375,
67,
1132,
68,
2430,
316,
3433,
12433,
6186,
16,
471,
1508,
10087,
326,
6835,
2973,
518,
225,
389,
87,
1302,
264,
1021,
1758,
10799,
358,
17571,
225,
389,
1132,
326,
943,
3844,
2898,
848,
17571,
225,
389,
7763,
751,
2690,
2870,
1779,
358,
1366,
358,
326,
20412,
6835,
19,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
565,
445,
6617,
537,
1876,
1477,
12,
2867,
389,
87,
1302,
264,
16,
2254,
5034,
389,
1132,
16,
1731,
389,
7763,
751,
13,
203,
3639,
1071,
203,
3639,
1135,
261,
6430,
2216,
13,
288,
203,
3639,
1147,
18241,
17571,
264,
273,
1147,
18241,
24899,
87,
1302,
264,
1769,
203,
3639,
309,
261,
12908,
537,
24899,
87,
1302,
264,
16,
389,
1132,
3719,
288,
203,
5411,
17571,
264,
18,
18149,
23461,
12,
3576,
18,
15330,
16,
389,
1132,
16,
333,
16,
389,
7763,
751,
1769,
203,
5411,
327,
638,
31,
203,
3639,
289,
203,
565,
289,
203,
203,
377,
203,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
] |
//Address: 0x74cedA99C44DA280F2fd8EA8b5dd43f8b66912a8
//Contract name: DetherSale
//Balance: 0 Ether
//Verification Date: 2/7/2018
//Transacion Count: 10248
// CODE STARTS HERE
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;
}
}
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);
}
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);
}
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;
}
}
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];
}
}
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;
}
}
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);
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;
}
}
contract Whitelistable is Ownable {
event LogUserRegistered(address indexed sender, address indexed userAddress);
event LogUserUnregistered(address indexed sender, address indexed userAddress);
mapping(address => bool) public whitelisted;
function registerUser(address userAddress)
public
onlyOwner
{
require(userAddress != 0);
whitelisted[userAddress] = true;
LogUserRegistered(msg.sender, userAddress);
}
function unregisterUser(address userAddress)
public
onlyOwner
{
require(whitelisted[userAddress] == true);
whitelisted[userAddress] = false;
LogUserUnregistered(msg.sender, userAddress);
}
}
contract DisbursementHandler is Ownable {
struct Disbursement {
uint256 timestamp;
uint256 tokens;
}
event LogSetup(address indexed vestor, uint256 tokens, uint256 timestamp);
event LogChangeTimestamp(address indexed vestor, uint256 index, uint256 timestamp);
event LogWithdraw(address indexed to, uint256 value);
ERC20 public token;
mapping(address => Disbursement[]) public disbursements;
mapping(address => uint256) public withdrawnTokens;
function DisbursementHandler(address _token) public {
token = ERC20(_token);
}
/// @dev Called by the sale contract to create a disbursement.
/// @param vestor The address of the beneficiary.
/// @param tokens Amount of tokens to be locked.
/// @param timestamp Funds will be locked until this timestamp.
function setupDisbursement(
address vestor,
uint256 tokens,
uint256 timestamp
)
public
onlyOwner
{
require(block.timestamp < timestamp);
disbursements[vestor].push(Disbursement(timestamp, tokens));
LogSetup(vestor, timestamp, tokens);
}
/// @dev Change an existing disbursement.
/// @param vestor The address of the beneficiary.
/// @param timestamp Funds will be locked until this timestamp.
/// @param index Index of the DisbursementVesting in the vesting array.
function changeTimestamp(
address vestor,
uint256 index,
uint256 timestamp
)
public
onlyOwner
{
require(block.timestamp < timestamp);
require(index < disbursements[vestor].length);
disbursements[vestor][index].timestamp = timestamp;
LogChangeTimestamp(vestor, index, timestamp);
}
/// @dev Transfers tokens to a given address
/// @param to Address of token receiver
/// @param value Number of tokens to transfer
function withdraw(address to, uint256 value)
public
{
uint256 maxTokens = calcMaxWithdraw();
uint256 withdrawAmount = value < maxTokens ? value : maxTokens;
withdrawnTokens[msg.sender] = SafeMath.add(withdrawnTokens[msg.sender], withdrawAmount);
token.transfer(to, withdrawAmount);
LogWithdraw(to, value);
}
/// @dev Calculates the maximum amount of vested tokens
/// @return Number of vested tokens to withdraw
function calcMaxWithdraw()
public
constant
returns (uint256)
{
uint256 maxTokens = 0;
Disbursement[] storage temp = disbursements[msg.sender];
for (uint256 i = 0; i < temp.length; i++) {
if (block.timestamp > temp[i].timestamp) {
maxTokens = SafeMath.add(maxTokens, temp[i].tokens);
}
}
maxTokens = SafeMath.sub(maxTokens, withdrawnTokens[msg.sender]);
return maxTokens;
}
}
library StateMachineLib {
struct Stage {
// The id of the next stage
bytes32 nextId;
// The identifiers for the available functions in each stage
mapping(bytes4 => bool) allowedFunctions;
}
struct State {
// The current stage id
bytes32 currentStageId;
// A callback that is called when entering this stage
function(bytes32) internal onTransition;
// Checks if a stage id is valid
mapping(bytes32 => bool) validStage;
// Maps stage ids to their Stage structs
mapping(bytes32 => Stage) stages;
}
/// @dev Creates and sets the initial stage. It has to be called before creating any transitions.
/// @param stageId The id of the (new) stage to set as initial stage.
function setInitialStage(State storage self, bytes32 stageId) internal {
self.validStage[stageId] = true;
self.currentStageId = stageId;
}
/// @dev Creates a transition from 'fromId' to 'toId'. If fromId already had a nextId, it deletes the now unreachable stage.
/// @param fromId The id of the stage from which the transition begins.
/// @param toId The id of the stage that will be reachable from "fromId".
function createTransition(State storage self, bytes32 fromId, bytes32 toId) internal {
require(self.validStage[fromId]);
Stage storage from = self.stages[fromId];
// Invalidate the stage that won't be reachable any more
if (from.nextId != 0) {
self.validStage[from.nextId] = false;
delete self.stages[from.nextId];
}
from.nextId = toId;
self.validStage[toId] = true;
}
/// @dev Goes to the next stage if posible (if the next stage is valid)
function goToNextStage(State storage self) internal {
Stage storage current = self.stages[self.currentStageId];
require(self.validStage[current.nextId]);
self.currentStageId = current.nextId;
self.onTransition(current.nextId);
}
/// @dev Checks if the a function is allowed in the current stage.
/// @param selector A function selector (bytes4[keccak256(functionSignature)])
/// @return true If the function is allowed in the current stage
function checkAllowedFunction(State storage self, bytes4 selector) internal constant returns(bool) {
return self.stages[self.currentStageId].allowedFunctions[selector];
}
/// @dev Allow a function in the given stage.
/// @param stageId The id of the stage
/// @param selector A function selector (bytes4[keccak256(functionSignature)])
function allowFunction(State storage self, bytes32 stageId, bytes4 selector) internal {
require(self.validStage[stageId]);
self.stages[stageId].allowedFunctions[selector] = true;
}
}
contract StateMachine {
using StateMachineLib for StateMachineLib.State;
event LogTransition(bytes32 indexed stageId, uint256 blockNumber);
StateMachineLib.State internal state;
/* This modifier performs the conditional transitions and checks that the function
* to be executed is allowed in the current stage
*/
modifier checkAllowed {
conditionalTransitions();
require(state.checkAllowedFunction(msg.sig));
_;
}
function StateMachine() public {
// Register the startConditions function and the onTransition callback
state.onTransition = onTransition;
}
/// @dev Gets the current stage id.
/// @return The current stage id.
function getCurrentStageId() public view returns(bytes32) {
return state.currentStageId;
}
/// @dev Performs conditional transitions. Can be called by anyone.
function conditionalTransitions() public {
bytes32 nextId = state.stages[state.currentStageId].nextId;
while (state.validStage[nextId]) {
StateMachineLib.Stage storage next = state.stages[nextId];
// If the next stage's condition is true, go to next stage and continue
if (startConditions(nextId)) {
state.goToNextStage();
nextId = next.nextId;
} else {
break;
}
}
}
/// @dev Determines whether the conditions for transitioning to the given stage are met.
/// @return true if the conditions are met for the given stageId. False by default (must override in child contracts).
function startConditions(bytes32) internal constant returns(bool) {
return false;
}
/// @dev Callback called when there is a stage transition. It should be overridden for additional functionality.
function onTransition(bytes32 stageId) internal {
LogTransition(stageId, block.number);
}
}
contract TimedStateMachine is StateMachine {
event LogSetStageStartTime(bytes32 indexed stageId, uint256 startTime);
// Stores the start timestamp for each stage (the value is 0 if the stage doesn't have a start timestamp).
mapping(bytes32 => uint256) internal startTime;
/// @dev This function overrides the startConditions function in the parent contract in order to enable automatic transitions that depend on the timestamp.
function startConditions(bytes32 stageId) internal constant returns(bool) {
// Get the startTime for stage
uint256 start = startTime[stageId];
// If the startTime is set and has already passed, return true.
return start != 0 && block.timestamp > start;
}
/// @dev Sets the starting timestamp for a stage.
/// @param stageId The id of the stage for which we want to set the start timestamp.
/// @param timestamp The start timestamp for the given stage. It should be bigger than the current one.
function setStageStartTime(bytes32 stageId, uint256 timestamp) internal {
require(state.validStage[stageId]);
require(timestamp > block.timestamp);
startTime[stageId] = timestamp;
LogSetStageStartTime(stageId, timestamp);
}
/// @dev Returns the timestamp for the given stage id.
/// @param stageId The id of the stage for which we want to set the start timestamp.
function getStageStartTime(bytes32 stageId) public view returns(uint256) {
return startTime[stageId];
}
}
contract Sale is Ownable, TimedStateMachine {
using SafeMath for uint256;
event LogContribution(address indexed contributor, uint256 amountSent, uint256 excessRefunded);
event LogTokenAllocation(address indexed contributor, uint256 contribution, uint256 tokens);
event LogDisbursement(address indexed beneficiary, uint256 tokens);
// Stages for the state machine
bytes32 public constant SETUP = "setup";
bytes32 public constant SETUP_DONE = "setupDone";
bytes32 public constant SALE_IN_PROGRESS = "saleInProgress";
bytes32 public constant SALE_ENDED = "saleEnded";
mapping(address => uint256) public contributions;
uint256 public weiContributed = 0;
uint256 public contributionCap;
// Wallet where funds will be sent
address public wallet;
MintableToken public token;
DisbursementHandler public disbursementHandler;
function Sale(
address _wallet,
uint256 _contributionCap
)
public
{
require(_wallet != 0);
require(_contributionCap != 0);
wallet = _wallet;
token = createTokenContract();
disbursementHandler = new DisbursementHandler(token);
contributionCap = _contributionCap;
setupStages();
}
function() external payable {
contribute();
}
/// @dev Sets the start timestamp for the SALE_IN_PROGRESS stage.
/// @param timestamp The start timestamp.
function setSaleStartTime(uint256 timestamp)
external
onlyOwner
checkAllowed
{
// require(_startTime < getStageStartTime(SALE_ENDED));
setStageStartTime(SALE_IN_PROGRESS, timestamp);
}
/// @dev Sets the start timestamp for the SALE_ENDED stage.
/// @param timestamp The start timestamp.
function setSaleEndTime(uint256 timestamp)
external
onlyOwner
checkAllowed
{
require(getStageStartTime(SALE_IN_PROGRESS) < timestamp);
setStageStartTime(SALE_ENDED, timestamp);
}
/// @dev Called in the SETUP stage, check configurations and to go to the SETUP_DONE stage.
function setupDone()
public
onlyOwner
checkAllowed
{
uint256 _startTime = getStageStartTime(SALE_IN_PROGRESS);
uint256 _endTime = getStageStartTime(SALE_ENDED);
require(block.timestamp < _startTime);
require(_startTime < _endTime);
state.goToNextStage();
}
/// @dev Called by users to contribute ETH to the sale.
function contribute()
public
payable
checkAllowed
{
require(msg.value > 0);
uint256 contributionLimit = getContributionLimit(msg.sender);
require(contributionLimit > 0);
// Check that the user is allowed to contribute
uint256 totalContribution = contributions[msg.sender].add(msg.value);
uint256 excess = 0;
// Check if it goes over the eth cap for the sale.
if (weiContributed.add(msg.value) > contributionCap) {
// Subtract the excess
excess = weiContributed.add(msg.value).sub(contributionCap);
totalContribution = totalContribution.sub(excess);
}
// Check if it goes over the contribution limit of the user.
if (totalContribution > contributionLimit) {
excess = excess.add(totalContribution).sub(contributionLimit);
contributions[msg.sender] = contributionLimit;
} else {
contributions[msg.sender] = totalContribution;
}
// We are only able to refund up to msg.value because the contract will not contain ether
// excess = excess < msg.value ? excess : msg.value;
require(excess <= msg.value);
weiContributed = weiContributed.add(msg.value).sub(excess);
if (excess > 0) {
msg.sender.transfer(excess);
}
wallet.transfer(this.balance);
assert(contributions[msg.sender] <= contributionLimit);
LogContribution(msg.sender, msg.value, excess);
}
/// @dev Create a disbursement of tokens.
/// @param beneficiary The beneficiary of the disbursement.
/// @param tokenAmount Amount of tokens to be locked.
/// @param timestamp Tokens will be locked until this timestamp.
function distributeTimelockedTokens(
address beneficiary,
uint256 tokenAmount,
uint256 timestamp
)
public
onlyOwner
checkAllowed
{
disbursementHandler.setupDisbursement(
beneficiary,
tokenAmount,
timestamp
);
token.mint(disbursementHandler, tokenAmount);
LogDisbursement(beneficiary, tokenAmount);
}
function setupStages() internal {
// Set the stages
state.setInitialStage(SETUP);
state.createTransition(SETUP, SETUP_DONE);
state.createTransition(SETUP_DONE, SALE_IN_PROGRESS);
state.createTransition(SALE_IN_PROGRESS, SALE_ENDED);
state.allowFunction(SETUP, this.distributeTimelockedTokens.selector);
state.allowFunction(SETUP, this.setSaleStartTime.selector);
state.allowFunction(SETUP, this.setSaleEndTime.selector);
state.allowFunction(SETUP, this.setupDone.selector);
state.allowFunction(SALE_IN_PROGRESS, this.contribute.selector);
state.allowFunction(SALE_IN_PROGRESS, 0); // fallback
}
// Override in the child sales
function createTokenContract() internal returns (MintableToken);
function getContributionLimit(address userAddress) public view returns (uint256);
/// @dev Stage start conditions.
function startConditions(bytes32 stageId) internal constant returns (bool) {
// If the cap has been reached, end the sale.
if (stageId == SALE_ENDED && contributionCap <= weiContributed) {
return true;
}
return super.startConditions(stageId);
}
/// @dev State transitions callbacks.
function onTransition(bytes32 stageId) internal {
if (stageId == SALE_ENDED) {
onSaleEnded();
}
super.onTransition(stageId);
}
/// @dev Callback that gets called when entering the SALE_ENDED stage.
function onSaleEnded() internal {}
}
contract ERC223ReceivingContract {
/// @dev Standard ERC223 function that will handle incoming token transfers.
/// @param _from Token sender address.
/// @param _value Amount of tokens.
/// @param _data Transaction metadata.
function tokenFallback(address _from, uint _value, bytes _data) public;
}
contract ERC223Basic is ERC20Basic {
/**
* @dev Transfer the specified amount of tokens to the specified address.
* Now with a new parameter _data.
*
* @param _to Receiver address.
* @param _value Amount of tokens that will be transferred.
* @param _data Transaction metadata.
*/
function transfer(address _to, uint _value, bytes _data) public returns (bool);
/**
* @dev triggered when transfer is successfully called.
*
* @param _from Sender address.
* @param _to Receiver address.
* @param _value Amount of tokens that will be transferred.
* @param _data Transaction metadata.
*/
event Transfer(address indexed _from, address indexed _to, uint256 indexed _value, bytes _data);
}
contract ERC223BasicToken is ERC223Basic, BasicToken {
/**
* @dev Transfer the specified amount of tokens to the specified address.
* Invokes the `tokenFallback` function if the recipient is a contract.
* The token transfer fails if the recipient is a contract
* but does not implement the `tokenFallback` function
* or the fallback function to receive funds.
*
* @param _to Receiver address.
* @param _value Amount of tokens that will be transferred.
* @param _data Transaction metadata.
*/
function transfer(address _to, uint _value, bytes _data) public returns (bool) {
// Standard function transfer similar to ERC20 transfer with no _data .
// Added due to backwards compatibility reasons .
uint codeLength;
assembly {
// Retrieve the size of the code on target address, this needs assembly .
codeLength := extcodesize(_to)
}
require(super.transfer(_to, _value));
if(codeLength>0) {
ERC223ReceivingContract receiver = ERC223ReceivingContract(_to);
receiver.tokenFallback(msg.sender, _value, _data);
}
Transfer(msg.sender, _to, _value, _data);
return true;
}
/**
* @dev Transfer the specified amount of tokens to the specified address.
* Invokes the `tokenFallback` function if the recipient is a contract.
* The token transfer fails if the recipient is a contract
* but does not implement the `tokenFallback` function
* or the fallback function to receive funds.
*
* @param _to Receiver address.
* @param _value Amount of tokens that will be transferred.
*/
function transfer(address _to, uint256 _value) public returns (bool) {
bytes memory empty;
require(transfer(_to, _value, empty));
return true;
}
}
contract DetailedERC20 is ERC20 {
string public name;
string public symbol;
uint8 public decimals;
function DetailedERC20(string _name, string _symbol, uint8 _decimals) public {
name = _name;
symbol = _symbol;
decimals = _decimals;
}
}
contract DetherToken is DetailedERC20, MintableToken, ERC223BasicToken {
string constant NAME = "Dether";
string constant SYMBOL = "DTH";
uint8 constant DECIMALS = 18;
/**
*@dev Constructor that set Detailed of the ERC20 token.
*/
function DetherToken()
DetailedERC20(NAME, SYMBOL, DECIMALS)
public
{}
}
contract DetherSale is Sale, Whitelistable {
uint256 public constant PRESALE_WEI = 3956 ether * 1.15 + 490 ether; // Amount raised in the presale including bonus
uint256 public constant DECIMALS_MULTIPLIER = 1000000000000000000;
uint256 public constant MAX_DTH = 100000000 * DECIMALS_MULTIPLIER;
// MAX_WEI - PRESALE_WEI
// TODO: change to actual amount
uint256 public constant WEI_CAP = 10554 ether;
// Duration of the whitelisting phase
uint256 public constant WHITELISTING_DURATION = 2 days;
// Contribution limit for the whitelisting phase
uint256 public constant WHITELISTING_MAX_CONTRIBUTION = 5 ether;
// Contribution limit for the public sale
uint256 public constant PUBLIC_MAX_CONTRIBUTION = 2**256 - 1;
// Minimum contribution allowed
uint256 public constant MIN_CONTRIBUTION = 0.1 ether;
// wei per DTH
uint256 public weiPerDTH;
// true if the locked tokens have been distributed
bool private lockedTokensDistributed;
// true if the presale tokens have been allocated
bool private presaleAllocated;
// Address for the presale buyers (Dether team will distribute manually)
address public presaleAddress;
uint256 private weiAllocated;
// Contribution limits specified for the presale
mapping(address => uint256) public presaleMaxContribution;
function DetherSale(address _wallet, address _presaleAddress) Sale(_wallet, WEI_CAP) public {
presaleAddress = _presaleAddress;
}
/// @dev Distributes timed locked tokens
function performInitialAllocations() external onlyOwner checkAllowed {
require(lockedTokensDistributed == false);
lockedTokensDistributed = true;
// Advisors
distributeTimelockedTokens(0x4dc976cEd66d1B87C099B338E1F1388AE657377d, MAX_DTH.mul(3).div(100), now + 6 * 4 weeks);
// Bounty
distributeTimelockedTokens(0xfEF675cC3068Ee798f2312e82B12c841157A0A0E, MAX_DTH.mul(3).div(100), now + 1 weeks);
// Early Contributors
distributeTimelockedTokens(0x8F38C4ddFE09Bd22545262FE160cf441D43d2489, MAX_DTH.mul(25).div(1000), now + 6 * 4 weeks);
distributeTimelockedTokens(0x87a4eb1c9fdef835DC9197FAff3E09b8007ADe5b, MAX_DTH.mul(25).div(1000), now + 6 * 4 weeks);
// Strategic Partnerships
distributeTimelockedTokens(0x6f63D5DF2D8644851cBb5F8607C845704C008284, MAX_DTH.mul(11).div(100), now + 1 weeks);
// Team (locked 3 years, 6 months release)
distributeTimelockedTokens(0x24c14796f401D77fc401F9c2FA1dF42A136EbF83, MAX_DTH.mul(3).div(100), now + 6 * 4 weeks);
distributeTimelockedTokens(0x24c14796f401D77fc401F9c2FA1dF42A136EbF83, MAX_DTH.mul(3).div(100), now + 2 * 6 * 4 weeks);
distributeTimelockedTokens(0x24c14796f401D77fc401F9c2FA1dF42A136EbF83, MAX_DTH.mul(3).div(100), now + 3 * 6 * 4 weeks);
distributeTimelockedTokens(0x24c14796f401D77fc401F9c2FA1dF42A136EbF83, MAX_DTH.mul(3).div(100), now + 4 * 6 * 4 weeks);
distributeTimelockedTokens(0x24c14796f401D77fc401F9c2FA1dF42A136EbF83, MAX_DTH.mul(3).div(100), now + 5 * 6 * 4 weeks);
distributeTimelockedTokens(0x24c14796f401D77fc401F9c2FA1dF42A136EbF83, MAX_DTH.mul(3).div(100), now + 6 * 6 * 4 weeks);
}
/// @dev Registers a user and sets the maximum contribution amount for the whitelisting period
function registerPresaleContributor(address userAddress, uint256 maxContribution)
external
onlyOwner
{
// Specified contribution has to be lower than the max
require(maxContribution <= WHITELISTING_MAX_CONTRIBUTION);
// Register user (Whitelistable contract)
registerUser(userAddress);
// Set contribution
presaleMaxContribution[userAddress] = maxContribution;
}
/// @dev Called to allocate the tokens depending on eth contributed.
/// @param contributor The address of the contributor.
function allocateTokens(address contributor)
external
checkAllowed
{
require(presaleAllocated);
require(contributions[contributor] != 0);
// We keep a record of how much wei contributed has already been used for allocations
weiAllocated = weiAllocated.add(contributions[contributor]);
// Mint the respective tokens to the contributor
token.mint(contributor, contributions[contributor].mul(DECIMALS_MULTIPLIER).div(weiPerDTH));
// Set contributions to 0
contributions[contributor] = 0;
// If all tokens were allocated, stop minting functionality
// and send the remaining (rounding errors) tokens to the owner
if (weiAllocated == weiContributed) {
uint256 remaining = MAX_DTH.sub(token.totalSupply());
token.mint(owner, remaining);
token.finishMinting();
}
}
/// @dev Called to allocate the tokens for presale address.
function presaleAllocateTokens()
external
checkAllowed
{
require(!presaleAllocated);
presaleAllocated = true;
// Mint the respective tokens to the contributor
token.mint(presaleAddress, PRESALE_WEI.mul(DECIMALS_MULTIPLIER).div(weiPerDTH));
}
function contribute()
public
payable
checkAllowed
{
require(msg.value >= MIN_CONTRIBUTION);
super.contribute();
}
/// @dev The limit will be different for every address during the whitelist period, and after that phase there is no limit for contributions.
function getContributionLimit(address userAddress) public view returns (uint256) {
uint256 saleStartTime = getStageStartTime(SALE_IN_PROGRESS);
// If not whitelisted or sale has not started, return 0
if (!whitelisted[userAddress] || block.timestamp < saleStartTime) {
return 0;
}
// Are we in the first two days?
bool whitelistingPeriod = block.timestamp - saleStartTime <= WHITELISTING_DURATION;
// If we are in the whitelisting period, return the contribution limit for the user
// If not, return the public max contribution
return whitelistingPeriod ? presaleMaxContribution[userAddress] : PUBLIC_MAX_CONTRIBUTION;
}
function createTokenContract() internal returns(MintableToken) {
return new DetherToken();
}
function setupStages() internal {
super.setupStages();
state.allowFunction(SETUP, this.performInitialAllocations.selector);
state.allowFunction(SALE_ENDED, this.allocateTokens.selector);
state.allowFunction(SALE_ENDED, this.presaleAllocateTokens.selector);
}
/// @dev The price will be the total wei contributed divided by the amount of tokens to be allocated to contributors.
function calculatePrice() public view returns(uint256) {
return weiContributed.add(PRESALE_WEI).div(60000000).add(1);
}
function onSaleEnded() internal {
// Calculate DTH per Wei
weiPerDTH = calculatePrice();
}
}
| Amount raised in the presale including bonus
| uint256 public constant PRESALE_WEI = 3956 ether * 1.15 + 490 ether; | 13,011,631 | [
1,
6275,
11531,
316,
326,
4075,
5349,
6508,
324,
22889,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
565,
2254,
5034,
1071,
5381,
7071,
5233,
900,
67,
6950,
45,
273,
16977,
4313,
225,
2437,
380,
404,
18,
3600,
397,
1059,
9349,
225,
2437,
31,
225,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
] |
pragma solidity ^0.5.0;
contract IERC725
{
// 1: MANAGEMENT keys, which can manage the identity
uint256 public constant MANAGEMENT_KEY = 1;
// 2: ACTION keys, which perform actions in this identities name (signing, logins, transactions, etc.)
uint256 public constant ACTION_KEY = 2;
// 3: CLAIM signer keys, used to sign claims on other identities which need to be revokable.
uint256 public constant CLAIM_SIGNER_KEY = 3;
// 4: ENCRYPTION keys, used to encrypt data e.g. hold in claims.
uint256 public constant ENCRYPTION_KEY = 4;
// KeyType
uint256 public constant ECDSA_TYPE = 1;
// https://medium.com/@alexberegszaszi/lets-bring-the-70s-to-ethereum-48daa16a4b51
uint256 public constant RSA_TYPE = 2;
// Events
event KeyAdded (bytes32 indexed key, uint256 indexed purpose, uint256 indexed keyType);
event KeyRemoved (bytes32 indexed key, uint256 indexed purpose, uint256 indexed keyType);
event ExecutionRequested(uint256 indexed executionId, address indexed to, uint256 indexed value, bytes data);
event Executed (uint256 indexed executionId, address indexed to, uint256 indexed value, bytes data);
event ExecutionFailed (uint256 indexed executionId, address indexed to, uint256 indexed value, bytes data);
event Approved (uint256 indexed executionId, bool approved);
// Functions
function getKey (bytes32 _key ) external view returns (uint256[] memory purposes, uint256 keyType, bytes32 key);
function keyHasPurpose (bytes32 _key, uint256 purpose ) external view returns (bool exists);
function getKeysByPurpose(uint256 _purpose ) external view returns (bytes32[] memory keys);
function addKey (bytes32 _key, uint256 _purpose, uint256 _keyType ) external returns (bool success);
function removeKey (bytes32 _key, uint256 _purpose ) external returns (bool success);
function execute (address _to, uint256 _value, bytes calldata _data) external returns (uint256 executionId);
function approve (uint256 _id, bool _approve ) external returns (bool success);
}
/**
* @title SafeMath
* @dev Unsigned math operations with safety checks that revert on error
*/
library SafeMath
{
/**
* @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 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 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 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;
}
/**
* @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 Multiplies the a by the fraction b/c
*/
function mulByFraction(uint256 a, uint256 b, uint256 c) internal pure returns (uint256)
{
return div(mul(a, b), c);
}
/**
* @dev Return b percents of a (equivalent to a percents of b)
*/
function percentage(uint256 a, uint256 b) internal pure returns (uint256)
{
return mulByFraction(a, b, 100);
}
/**
* @dev Returns the base 2 log of x
* @notice Source : https://ethereum.stackexchange.com/questions/8086/logarithm-math-operation-in-solidity
*/
function log(uint x) internal pure returns (uint y)
{
assembly
{
let arg := x
x := sub(x,1)
x := or(x, div(x, 0x02))
x := or(x, div(x, 0x04))
x := or(x, div(x, 0x10))
x := or(x, div(x, 0x100))
x := or(x, div(x, 0x10000))
x := or(x, div(x, 0x100000000))
x := or(x, div(x, 0x10000000000000000))
x := or(x, div(x, 0x100000000000000000000000000000000))
x := add(x, 1)
let m := mload(0x40)
mstore(m, 0xf8f9cbfae6cc78fbefe7cdc3a1793dfcf4f0e8bbd8cec470b6a28a7a5a3e1efd)
mstore(add(m,0x20), 0xf5ecf1b3e9debc68e1d9cfabc5997135bfb7a7a3938b7b606b5b4b3f2f1f0ffe)
mstore(add(m,0x40), 0xf6e4ed9ff2d6b458eadcdf97bd91692de2d4da8fd2d0ac50c6ae9a8272523616)
mstore(add(m,0x60), 0xc8c0b887b0a8a4489c948c7f847c6125746c645c544c444038302820181008ff)
mstore(add(m,0x80), 0xf7cae577eec2a03cf3bad76fb589591debb2dd67e0aa9834bea6925f6a4a2e0e)
mstore(add(m,0xa0), 0xe39ed557db96902cd38ed14fad815115c786af479b7e83247363534337271707)
mstore(add(m,0xc0), 0xc976c13bb96e881cb166a933a55e490d9d56952b8d4e801485467d2362422606)
mstore(add(m,0xe0), 0x753a6d1b65325d0c552a4d1345224105391a310b29122104190a110309020100)
mstore(0x40, add(m, 0x100))
let magic := 0x818283848586878898a8b8c8d8e8f929395969799a9b9d9e9faaeb6bedeeff
let shift := 0x100000000000000000000000000000000000000000000000000000000000000
let a := div(mul(x, magic), shift)
y := div(mload(add(m,sub(255,a))), shift)
y := add(y, mul(256, gt(arg, 0x8000000000000000000000000000000000000000000000000000000000000000)))
}
}
}
pragma experimental ABIEncoderV2;
contract ECDSA
{
struct signature
{
uint8 v;
bytes32 r;
bytes32 s;
}
function recover(bytes32 hash, signature memory sign)
internal pure returns (address)
{
require(sign.v == 27 || sign.v == 28);
return ecrecover(hash, sign.v, sign.r, sign.s);
}
function recover(bytes32 hash, bytes memory sign)
internal pure returns (address)
{
bytes32 r;
bytes32 s;
uint8 v;
require(sign.length == 65);
assembly
{
r := mload(add(sign, 0x20))
s := mload(add(sign, 0x40))
v := byte(0, mload(add(sign, 0x60)))
}
if (v < 27) v += 27;
require(v == 27 || v == 28);
return ecrecover(hash, v, r, s);
}
function toEthSignedMessageHash(bytes32 hash)
internal pure returns (bytes32)
{
return keccak256(abi.encodePacked("\x19Ethereum Signed Message:\n32", hash));
}
function toEthTypedStructHash(bytes32 struct_hash, bytes32 domain_separator)
internal pure returns (bytes32)
{
return keccak256(abi.encodePacked("\x19\x01", domain_separator, struct_hash));
}
}
pragma experimental ABIEncoderV2;
library IexecODBLibCore
{
/**
* Tools
*/
struct Account
{
uint256 stake;
uint256 locked;
}
struct Category
{
string name;
string description;
uint256 workClockTimeRef;
}
/**
* Clerk - Deals
*/
struct Resource
{
address pointer;
address owner;
uint256 price;
}
struct Deal
{
// Ressources
Resource app;
Resource dataset;
Resource workerpool;
uint256 trust;
uint256 category;
bytes32 tag;
// execution details
address requester;
address beneficiary;
address callback;
string params;
// execution settings
uint256 startTime;
uint256 botFirst;
uint256 botSize;
// consistency
uint256 workerStake;
uint256 schedulerRewardRatio;
}
/**
* Tasks
// TODO: rename Workorder → Task
*/
enum TaskStatusEnum
{
UNSET, // Work order not yet initialized (invalid address)
ACTIVE, // Marketed → constributions are open
REVEALING, // Starting consensus reveal
COMPLETED, // Concensus achieved
FAILLED // Failled consensus
}
struct Task
{
TaskStatusEnum status;
bytes32 dealid;
uint256 idx;
uint256 timeref;
uint256 contributionDeadline;
uint256 revealDeadline;
uint256 finalDeadline;
bytes32 consensusValue;
uint256 revealCounter;
uint256 winnerCounter;
address[] contributors;
bytes results;
}
/**
* Consensus
*/
enum ContributionStatusEnum
{
UNSET,
CONTRIBUTED,
PROVED,
REJECTED
}
struct Contribution
{
ContributionStatusEnum status;
bytes32 resultHash;
bytes32 resultSeal;
address enclaveChallenge;
}
}
pragma experimental ABIEncoderV2;
library IexecODBLibOrders
{
// bytes32 public constant EIP712DOMAIN_TYPEHASH = keccak256("EIP712Domain(string name,string version,uint256 chainId,address verifyingContract)");
// bytes32 public constant APPORDER_TYPEHASH = keccak256("AppOrder(address app,uint256 appprice,uint256 volume,bytes32 tag,address datasetrestrict,address workerpoolrestrict,address requesterrestrict,bytes32 salt)");
// bytes32 public constant DATASETORDER_TYPEHASH = keccak256("DatasetOrder(address dataset,uint256 datasetprice,uint256 volume,bytes32 tag,address apprestrict,address workerpoolrestrict,address requesterrestrict,bytes32 salt)");
// bytes32 public constant WORKERPOOLORDER_TYPEHASH = keccak256("WorkerpoolOrder(address workerpool,uint256 workerpoolprice,uint256 volume,bytes32 tag,uint256 category,uint256 trust,address apprestrict,address datasetrestrict,address requesterrestrict,bytes32 salt)");
// bytes32 public constant REQUESTORDER_TYPEHASH = keccak256("RequestOrder(address app,uint256 appmaxprice,address dataset,uint256 datasetmaxprice,address workerpool,uint256 workerpoolmaxprice,address requester,uint256 volume,bytes32 tag,uint256 category,uint256 trust,address beneficiary,address callback,string params,bytes32 salt)");
bytes32 public constant EIP712DOMAIN_TYPEHASH = 0x8b73c3c69bb8fe3d512ecc4cf759cc79239f7b179b0ffacaa9a75d522b39400f;
bytes32 public constant APPORDER_TYPEHASH = 0x60815a0eeec47dddf1615fe53b31d016c31444e01b9d796db365443a6445d008;
bytes32 public constant DATASETORDER_TYPEHASH = 0x6cfc932a5a3d22c4359295b9f433edff52b60703fa47690a04a83e40933dd47c;
bytes32 public constant WORKERPOOLORDER_TYPEHASH = 0xaa3429fb281b34691803133d3d978a75bb77c617ed6bc9aa162b9b30920022bb;
bytes32 public constant REQUESTORDER_TYPEHASH = 0xf24e853034a3a450aba845a82914fbb564ad85accca6cf62be112a154520fae0;
struct EIP712Domain
{
string name;
string version;
uint256 chainId;
address verifyingContract;
}
struct AppOrder
{
address app;
uint256 appprice;
uint256 volume;
bytes32 tag;
address datasetrestrict;
address workerpoolrestrict;
address requesterrestrict;
bytes32 salt;
ECDSA.signature sign;
}
struct DatasetOrder
{
address dataset;
uint256 datasetprice;
uint256 volume;
bytes32 tag;
address apprestrict;
address workerpoolrestrict;
address requesterrestrict;
bytes32 salt;
ECDSA.signature sign;
}
struct WorkerpoolOrder
{
address workerpool;
uint256 workerpoolprice;
uint256 volume;
bytes32 tag;
uint256 category;
uint256 trust;
address apprestrict;
address datasetrestrict;
address requesterrestrict;
bytes32 salt;
ECDSA.signature sign;
}
struct RequestOrder
{
address app;
uint256 appmaxprice;
address dataset;
uint256 datasetmaxprice;
address workerpool;
uint256 workerpoolmaxprice;
address requester;
uint256 volume;
bytes32 tag;
uint256 category;
uint256 trust;
address beneficiary;
address callback;
string params;
bytes32 salt;
ECDSA.signature sign;
}
function hash(EIP712Domain memory _domain)
public pure returns (bytes32 domainhash)
{
/**
* Readeable but expensive
*/
// return keccak256(abi.encode(
// EIP712DOMAIN_TYPEHASH
// , keccak256(bytes(_domain.name))
// , keccak256(bytes(_domain.version))
// , _domain.chainId
// , _domain.verifyingContract
// ));
// Compute sub-hashes
bytes32 typeHash = EIP712DOMAIN_TYPEHASH;
bytes32 nameHash = keccak256(bytes(_domain.name));
bytes32 versionHash = keccak256(bytes(_domain.version));
assembly {
// Back up select memory
let temp1 := mload(sub(_domain, 32))
let temp2 := mload(add(_domain, 0))
let temp3 := mload(add(_domain, 32))
// Write typeHash and sub-hashes
mstore(sub(_domain, 32), typeHash)
mstore(add(_domain, 0), nameHash)
mstore(add(_domain, 32), versionHash)
// Compute hash
domainhash := keccak256(sub(_domain, 32), 160) // 160 = 32 + 128
// Restore memory
mstore(sub(_domain, 32), temp1)
mstore(add(_domain, 0), temp2)
mstore(add(_domain, 32), temp3)
}
}
function hash(AppOrder memory _apporder)
public pure returns (bytes32 apphash)
{
/**
* Readeable but expensive
*/
// return keccak256(abi.encode(
// APPORDER_TYPEHASH
// , _apporder.app
// , _apporder.appprice
// , _apporder.volume
// , _apporder.tag
// , _apporder.datasetrestrict
// , _apporder.workerpoolrestrict
// , _apporder.requesterrestrict
// , _apporder.salt
// ));
// Compute sub-hashes
bytes32 typeHash = APPORDER_TYPEHASH;
assembly {
// Back up select memory
let temp1 := mload(sub(_apporder, 32))
// Write typeHash and sub-hashes
mstore(sub(_apporder, 32), typeHash)
// Compute hash
apphash := keccak256(sub(_apporder, 32), 288) // 288 = 32 + 256
// Restore memory
mstore(sub(_apporder, 32), temp1)
}
}
function hash(DatasetOrder memory _datasetorder)
public pure returns (bytes32 datasethash)
{
/**
* Readeable but expensive
*/
// return keccak256(abi.encode(
// DATASETORDER_TYPEHASH
// , _datasetorder.dataset
// , _datasetorder.datasetprice
// , _datasetorder.volume
// , _datasetorder.tag
// , _datasetorder.apprestrict
// , _datasetorder.workerpoolrestrict
// , _datasetorder.requesterrestrict
// , _datasetorder.salt
// ));
// Compute sub-hashes
bytes32 typeHash = DATASETORDER_TYPEHASH;
assembly {
// Back up select memory
let temp1 := mload(sub(_datasetorder, 32))
// Write typeHash and sub-hashes
mstore(sub(_datasetorder, 32), typeHash)
// Compute hash
datasethash := keccak256(sub(_datasetorder, 32), 288) // 288 = 32 + 256
// Restore memory
mstore(sub(_datasetorder, 32), temp1)
}
}
function hash(WorkerpoolOrder memory _workerpoolorder)
public pure returns (bytes32 workerpoolhash)
{
/**
* Readeable but expensive
*/
// return keccak256(abi.encode(
// WORKERPOOLORDER_TYPEHASH
// , _workerpoolorder.workerpool
// , _workerpoolorder.workerpoolprice
// , _workerpoolorder.volume
// , _workerpoolorder.tag
// , _workerpoolorder.category
// , _workerpoolorder.trust
// , _workerpoolorder.apprestrict
// , _workerpoolorder.datasetrestrict
// , _workerpoolorder.requesterrestrict
// , _workerpoolorder.salt
// ));
// Compute sub-hashes
bytes32 typeHash = WORKERPOOLORDER_TYPEHASH;
assembly {
// Back up select memory
let temp1 := mload(sub(_workerpoolorder, 32))
// Write typeHash and sub-hashes
mstore(sub(_workerpoolorder, 32), typeHash)
// Compute hash
workerpoolhash := keccak256(sub(_workerpoolorder, 32), 352) // 352 = 32 + 320
// Restore memory
mstore(sub(_workerpoolorder, 32), temp1)
}
}
function hash(RequestOrder memory _requestorder)
public pure returns (bytes32 requesthash)
{
/**
* Readeable but expensive
*/
//return keccak256(abi.encodePacked(
// abi.encode(
// REQUESTORDER_TYPEHASH
// , _requestorder.app
// , _requestorder.appmaxprice
// , _requestorder.dataset
// , _requestorder.datasetmaxprice
// , _requestorder.workerpool
// , _requestorder.workerpoolmaxprice
// , _requestorder.requester
// , _requestorder.volume
// , _requestorder.tag
// , _requestorder.category
// , _requestorder.trust
// , _requestorder.beneficiary
// , _requestorder.callback
// , keccak256(bytes(_requestorder.params))
// , _requestorder.salt
// )
//));
// Compute sub-hashes
bytes32 typeHash = REQUESTORDER_TYPEHASH;
bytes32 paramsHash = keccak256(bytes(_requestorder.params));
assembly {
// Back up select memory
let temp1 := mload(sub(_requestorder, 32))
let temp2 := mload(add(_requestorder, 416))
// Write typeHash and sub-hashes
mstore(sub(_requestorder, 32), typeHash)
mstore(add(_requestorder, 416), paramsHash)
// Compute hash
requesthash := keccak256(sub(_requestorder, 32), 512) // 512 = 32 + 480
// Restore memory
mstore(sub(_requestorder, 32), temp1)
mstore(add(_requestorder, 416), temp2)
}
}
}
contract OwnableImmutable
{
address public m_owner;
/**
* @dev Throws if called by any account other than the owner.
*/
modifier onlyOwner()
{
require(msg.sender == m_owner);
_;
}
/**
* @dev The Ownable constructor sets the original `owner` of the contract to the sender
* account.
*/
constructor(address _owner) public
{
m_owner = _owner;
}
}
contract OwnableMutable is OwnableImmutable
{
event OwnershipTransferred(address previousOwner, address newOwner);
/**
* @dev The Ownable constructor sets the original `owner` of the contract to the sender
* account.
*/
constructor() public
OwnableImmutable(msg.sender)
{
}
/**
* @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(m_owner, _newOwner);
m_owner = _newOwner;
}
}
pragma experimental ABIEncoderV2;
contract App is OwnableImmutable
{
/**
* Members
*/
string public m_appName;
string public m_appType;
bytes public m_appMultiaddr;
bytes32 public m_appChecksum;
bytes public m_appMREnclave;
/**
* Constructor
*/
constructor(
address _appOwner,
string memory _appName,
string memory _appType,
bytes memory _appMultiaddr,
bytes32 _appChecksum,
bytes memory _appMREnclave)
public
OwnableImmutable(_appOwner)
{
m_appName = _appName;
m_appType = _appType;
m_appMultiaddr = _appMultiaddr;
m_appChecksum = _appChecksum;
m_appMREnclave = _appMREnclave;
}
}
pragma experimental ABIEncoderV2;
contract Dataset is OwnableImmutable
{
/**
* Members
*/
string public m_datasetName;
bytes public m_datasetMultiaddr;
bytes32 public m_datasetChecksum;
/**
* Constructor
*/
constructor(
address _datasetOwner,
string memory _datasetName,
bytes memory _datasetMultiaddr,
bytes32 _datasetChecksum)
public
OwnableImmutable(_datasetOwner)
{
m_datasetName = _datasetName;
m_datasetMultiaddr = _datasetMultiaddr;
m_datasetChecksum = _datasetChecksum;
}
}
pragma experimental ABIEncoderV2;
contract Workerpool is OwnableImmutable
{
/**
* Parameters
*/
string public m_workerpoolDescription;
uint256 public m_workerStakeRatioPolicy; // % of reward to stake
uint256 public m_schedulerRewardRatioPolicy; // % of reward given to scheduler
/**
* Events
*/
event PolicyUpdate(
uint256 oldWorkerStakeRatioPolicy, uint256 newWorkerStakeRatioPolicy,
uint256 oldSchedulerRewardRatioPolicy, uint256 newSchedulerRewardRatioPolicy);
/**
* Constructor
*/
constructor(
address _workerpoolOwner,
string memory _workerpoolDescription)
public
OwnableImmutable(_workerpoolOwner)
{
m_workerpoolDescription = _workerpoolDescription;
m_workerStakeRatioPolicy = 30; // mutable
m_schedulerRewardRatioPolicy = 1; // mutable
}
function changePolicy(
uint256 _newWorkerStakeRatioPolicy,
uint256 _newSchedulerRewardRatioPolicy)
public onlyOwner
{
require(_newSchedulerRewardRatioPolicy <= 100);
emit PolicyUpdate(
m_workerStakeRatioPolicy, _newWorkerStakeRatioPolicy,
m_schedulerRewardRatioPolicy, _newSchedulerRewardRatioPolicy
);
m_workerStakeRatioPolicy = _newWorkerStakeRatioPolicy;
m_schedulerRewardRatioPolicy = _newSchedulerRewardRatioPolicy;
}
}
/**
* @title ERC20 interface
* @dev see https://github.com/ethereum/EIPs/blob/master/EIPS/eip-20.md
*/
interface IERC20
{
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);
event Transfer(
address indexed from,
address indexed to,
uint256 value
);
event Approval(
address indexed owner,
address indexed spender,
uint256 value
);
}
pragma experimental ABIEncoderV2;
contract Escrow
{
using SafeMath for uint256;
/**
* token contract for transfers.
*/
IERC20 public token;
/**
* Escrow content
*/
mapping(address => IexecODBLibCore.Account) m_accounts;
/**
* Events
*/
event Deposit (address owner, uint256 amount);
event DepositFor(address owner, uint256 amount, address target);
event Withdraw (address owner, uint256 amount);
event Reward (address user, uint256 amount);
event Seize (address user, uint256 amount);
event Lock (address user, uint256 amount);
event Unlock (address user, uint256 amount);
/**
* Constructor
*/
constructor(address _token)
public
{
token = IERC20(_token);
}
/**
* Accessor
*/
function viewAccount(address _user)
external view returns (IexecODBLibCore.Account memory account)
{
return m_accounts[_user];
}
/**
* Wallet methods: public
*/
function deposit(uint256 _amount)
external returns (bool)
{
require(token.transferFrom(msg.sender, address(this), _amount));
m_accounts[msg.sender].stake = m_accounts[msg.sender].stake.add(_amount);
emit Deposit(msg.sender, _amount);
return true;
}
function depositFor(uint256 _amount, address _target)
external returns (bool)
{
require(_target != address(0));
require(token.transferFrom(msg.sender, address(this), _amount));
m_accounts[_target].stake = m_accounts[_target].stake.add(_amount);
emit DepositFor(msg.sender, _amount, _target);
return true;
}
function withdraw(uint256 _amount)
external returns (bool)
{
m_accounts[msg.sender].stake = m_accounts[msg.sender].stake.sub(_amount);
require(token.transfer(msg.sender, _amount));
emit Withdraw(msg.sender, _amount);
return true;
}
/**
* Wallet methods: Internal
*/
function reward(address _user, uint256 _amount) internal /* returns (bool) */
{
m_accounts[_user].stake = m_accounts[_user].stake.add(_amount);
emit Reward(_user, _amount);
/* return true; */
}
function seize(address _user, uint256 _amount) internal /* returns (bool) */
{
m_accounts[_user].locked = m_accounts[_user].locked.sub(_amount);
emit Seize(_user, _amount);
/* return true; */
}
function lock(address _user, uint256 _amount) internal /* returns (bool) */
{
m_accounts[_user].stake = m_accounts[_user].stake.sub(_amount);
m_accounts[_user].locked = m_accounts[_user].locked.add(_amount);
emit Lock(_user, _amount);
/* return true; */
}
function unlock(address _user, uint256 _amount) internal /* returns (bool) */
{
m_accounts[_user].locked = m_accounts[_user].locked.sub(_amount);
m_accounts[_user].stake = m_accounts[_user].stake.add(_amount);
emit Unlock(_user, _amount);
/* return true; */
}
}
pragma experimental ABIEncoderV2;
interface IexecHubInterface
{
function checkResources(address, address, address)
external view returns (bool);
}
pragma experimental ABIEncoderV2;
contract IexecHubAccessor
{
IexecHubInterface public iexechub;
modifier onlyIexecHub()
{
require(msg.sender == address(iexechub));
_;
}
constructor(address _iexechub)
public
{
require(_iexechub != address(0));
iexechub = IexecHubInterface(_iexechub);
}
}
pragma experimental ABIEncoderV2;
contract IexecClerk is Escrow, IexecHubAccessor, ECDSA
{
using SafeMath for uint256;
using IexecODBLibOrders for IexecODBLibOrders.EIP712Domain;
using IexecODBLibOrders for IexecODBLibOrders.AppOrder;
using IexecODBLibOrders for IexecODBLibOrders.DatasetOrder;
using IexecODBLibOrders for IexecODBLibOrders.WorkerpoolOrder;
using IexecODBLibOrders for IexecODBLibOrders.RequestOrder;
/***************************************************************************
* Constants *
***************************************************************************/
uint256 public constant WORKERPOOL_STAKE_RATIO = 30;
uint256 public constant KITTY_RATIO = 10;
uint256 public constant KITTY_MIN = 1000000000; // TODO: 1RLC ?
/***************************************************************************
* EIP712 signature *
***************************************************************************/
bytes32 public /* immutable */ EIP712DOMAIN_SEPARATOR;
/***************************************************************************
* Clerk data *
***************************************************************************/
mapping(bytes32 => bytes32[] ) m_requestdeals;
mapping(bytes32 => IexecODBLibCore.Deal) m_deals;
mapping(bytes32 => uint256 ) m_consumed;
mapping(bytes32 => bool ) m_presigned;
/***************************************************************************
* Events *
***************************************************************************/
event OrdersMatched (bytes32 dealid, bytes32 appHash, bytes32 datasetHash, bytes32 workerpoolHash, bytes32 requestHash, uint256 volume);
event ClosedAppOrder (bytes32 appHash);
event ClosedDatasetOrder (bytes32 datasetHash);
event ClosedWorkerpoolOrder(bytes32 workerpoolHash);
event ClosedRequestOrder (bytes32 requestHash);
event SchedulerNotice (address indexed workerpool, bytes32 dealid);
/***************************************************************************
* Constructor *
***************************************************************************/
constructor(
address _token,
address _iexechub,
uint256 _chainid)
public
Escrow(_token)
IexecHubAccessor(_iexechub)
{
EIP712DOMAIN_SEPARATOR = IexecODBLibOrders.EIP712Domain({
name: "iExecODB"
, version: "3.0-alpha"
, chainId: _chainid
, verifyingContract: address(this)
}).hash();
}
/***************************************************************************
* Accessor *
***************************************************************************/
function viewRequestDeals(bytes32 _id)
external view returns (bytes32[] memory requestdeals)
{
return m_requestdeals[_id];
}
function viewDeal(bytes32 _id)
external view returns (IexecODBLibCore.Deal memory deal)
{
return m_deals[_id];
}
function viewConsumed(bytes32 _id)
external view returns (uint256 consumed)
{
return m_consumed[_id];
}
function viewPresigned(bytes32 _id)
external view returns (bool presigned)
{
return m_presigned[_id];
}
/***************************************************************************
* Hashing and signature tools *
***************************************************************************/
function checkIdentity(address _identity, address _candidate, uint256 _purpose)
internal view returns (bool valid)
{
return _identity == _candidate || IERC725(_identity).keyHasPurpose(keccak256(abi.encode(_candidate)), _purpose); // Simple address || Identity contract
}
// internal ?
function verifySignature(
address _identity,
bytes32 _hash,
ECDSA.signature memory _signature)
public view returns (bool)
{
return checkIdentity(
_identity,
recover(toEthTypedStructHash(_hash, EIP712DOMAIN_SEPARATOR), _signature),
2 // canceling an order requires ACTION (2) from the owning identity, signature with 2 or 4?
);
}
/***************************************************************************
* pre-signing tools *
***************************************************************************/
// should be external
function signAppOrder(IexecODBLibOrders.AppOrder memory _apporder)
public returns (bool)
{
require(msg.sender == App(_apporder.app).m_owner());
m_presigned[_apporder.hash()] = true;
return true;
}
// should be external
function signDatasetOrder(IexecODBLibOrders.DatasetOrder memory _datasetorder)
public returns (bool)
{
require(msg.sender == Dataset(_datasetorder.dataset).m_owner());
m_presigned[_datasetorder.hash()] = true;
return true;
}
// should be external
function signWorkerpoolOrder(IexecODBLibOrders.WorkerpoolOrder memory _workerpoolorder)
public returns (bool)
{
require(msg.sender == Workerpool(_workerpoolorder.workerpool).m_owner());
m_presigned[_workerpoolorder.hash()] = true;
return true;
}
// should be external
function signRequestOrder(IexecODBLibOrders.RequestOrder memory _requestorder)
public returns (bool)
{
require(msg.sender == _requestorder.requester);
m_presigned[_requestorder.hash()] = true;
return true;
}
/***************************************************************************
* Clerk methods *
***************************************************************************/
struct Identities
{
bytes32 appHash;
address appOwner;
bytes32 datasetHash;
address datasetOwner;
bytes32 workerpoolHash;
address workerpoolOwner;
bytes32 requestHash;
bool hasDataset;
}
// should be external
function matchOrders(
IexecODBLibOrders.AppOrder memory _apporder,
IexecODBLibOrders.DatasetOrder memory _datasetorder,
IexecODBLibOrders.WorkerpoolOrder memory _workerpoolorder,
IexecODBLibOrders.RequestOrder memory _requestorder)
public returns (bytes32)
{
/**
* Check orders compatibility
*/
// computation environment & allowed enough funds
require(_requestorder.category == _workerpoolorder.category );
require(_requestorder.trust <= _workerpoolorder.trust );
require(_requestorder.appmaxprice >= _apporder.appprice );
require(_requestorder.datasetmaxprice >= _datasetorder.datasetprice );
require(_requestorder.workerpoolmaxprice >= _workerpoolorder.workerpoolprice);
require((_apporder.tag | _datasetorder.tag | _requestorder.tag) & ~_workerpoolorder.tag == 0x0);
// Check matching and restrictions
require(_requestorder.app == _apporder.app );
require(_requestorder.dataset == _datasetorder.dataset);
require(_requestorder.workerpool == address(0) || checkIdentity(_requestorder.workerpool, _workerpoolorder.workerpool, 4)); // requestorder.workerpool is a restriction
require(_apporder.datasetrestrict == address(0) || checkIdentity(_apporder.datasetrestrict, _datasetorder.dataset, 4));
require(_apporder.workerpoolrestrict == address(0) || checkIdentity(_apporder.workerpoolrestrict, _workerpoolorder.workerpool, 4));
require(_apporder.requesterrestrict == address(0) || checkIdentity(_apporder.requesterrestrict, _requestorder.requester, 4));
require(_datasetorder.apprestrict == address(0) || checkIdentity(_datasetorder.apprestrict, _apporder.app, 4));
require(_datasetorder.workerpoolrestrict == address(0) || checkIdentity(_datasetorder.workerpoolrestrict, _workerpoolorder.workerpool, 4));
require(_datasetorder.requesterrestrict == address(0) || checkIdentity(_datasetorder.requesterrestrict, _requestorder.requester, 4));
require(_workerpoolorder.apprestrict == address(0) || checkIdentity(_workerpoolorder.apprestrict, _apporder.app, 4));
require(_workerpoolorder.datasetrestrict == address(0) || checkIdentity(_workerpoolorder.datasetrestrict, _datasetorder.dataset, 4));
require(_workerpoolorder.requesterrestrict == address(0) || checkIdentity(_workerpoolorder.requesterrestrict, _requestorder.requester, 4));
require(iexechub.checkResources(_apporder.app, _datasetorder.dataset, _workerpoolorder.workerpool));
/**
* Check orders authenticity
*/
Identities memory ids;
ids.hasDataset = _datasetorder.dataset != address(0);
// app
ids.appHash = _apporder.hash();
ids.appOwner = App(_apporder.app).m_owner();
require(m_presigned[ids.appHash] || verifySignature(ids.appOwner, ids.appHash, _apporder.sign));
// dataset
if (ids.hasDataset) // only check if dataset is enabled
{
ids.datasetHash = _datasetorder.hash();
ids.datasetOwner = Dataset(_datasetorder.dataset).m_owner();
require(m_presigned[ids.datasetHash] || verifySignature(ids.datasetOwner, ids.datasetHash, _datasetorder.sign));
}
// workerpool
ids.workerpoolHash = _workerpoolorder.hash();
ids.workerpoolOwner = Workerpool(_workerpoolorder.workerpool).m_owner();
require(m_presigned[ids.workerpoolHash] || verifySignature(ids.workerpoolOwner, ids.workerpoolHash, _workerpoolorder.sign));
// request
ids.requestHash = _requestorder.hash();
require(m_presigned[ids.requestHash] || verifySignature(_requestorder.requester, ids.requestHash, _requestorder.sign));
/**
* Check availability
*/
uint256 volume;
volume = _apporder.volume.sub (m_consumed[ids.appHash ]);
volume = ids.hasDataset ? volume.min(_datasetorder.volume.sub (m_consumed[ids.datasetHash ])) : volume;
volume = volume.min(_workerpoolorder.volume.sub(m_consumed[ids.workerpoolHash]));
volume = volume.min(_requestorder.volume.sub (m_consumed[ids.requestHash ]));
require(volume > 0);
/**
* Record
*/
bytes32 dealid = keccak256(abi.encodePacked(
ids.requestHash, // requestHash
m_consumed[ids.requestHash] // idx of first subtask
));
IexecODBLibCore.Deal storage deal = m_deals[dealid];
deal.app.pointer = _apporder.app;
deal.app.owner = ids.appOwner;
deal.app.price = _apporder.appprice;
deal.dataset.owner = ids.datasetOwner;
deal.dataset.pointer = _datasetorder.dataset;
deal.dataset.price = ids.hasDataset ? _datasetorder.datasetprice : 0;
deal.workerpool.pointer = _workerpoolorder.workerpool;
deal.workerpool.owner = ids.workerpoolOwner;
deal.workerpool.price = _workerpoolorder.workerpoolprice;
deal.trust = _requestorder.trust.max(1);
deal.category = _requestorder.category;
deal.tag = _apporder.tag | _datasetorder.tag | _requestorder.tag;
deal.requester = _requestorder.requester;
deal.beneficiary = _requestorder.beneficiary;
deal.callback = _requestorder.callback;
deal.params = _requestorder.params;
deal.startTime = now;
deal.botFirst = m_consumed[ids.requestHash];
deal.botSize = volume;
deal.workerStake = _workerpoolorder.workerpoolprice.percentage(Workerpool(_workerpoolorder.workerpool).m_workerStakeRatioPolicy());
deal.schedulerRewardRatio = Workerpool(_workerpoolorder.workerpool).m_schedulerRewardRatioPolicy();
m_requestdeals[ids.requestHash].push(dealid);
/**
* Update consumed
*/
m_consumed[ids.appHash ] = m_consumed[ids.appHash ].add( volume );
m_consumed[ids.datasetHash ] = m_consumed[ids.datasetHash ].add(ids.hasDataset ? volume : 0);
m_consumed[ids.workerpoolHash] = m_consumed[ids.workerpoolHash].add( volume );
m_consumed[ids.requestHash ] = m_consumed[ids.requestHash ].add( volume );
/**
* Lock
*/
lock(
deal.requester,
deal.app.price
.add(deal.dataset.price)
.add(deal.workerpool.price)
.mul(volume)
);
lock(
deal.workerpool.owner,
deal.workerpool.price
.percentage(WORKERPOOL_STAKE_RATIO) // ORDER IS IMPORTANT HERE!
.mul(volume) // ORDER IS IMPORTANT HERE!
);
/**
* Advertize deal
*/
emit SchedulerNotice(deal.workerpool.pointer, dealid);
/**
* Advertize consumption
*/
emit OrdersMatched(
dealid,
ids.appHash,
ids.datasetHash,
ids.workerpoolHash,
ids.requestHash,
volume
);
return dealid;
}
// should be external
function cancelAppOrder(IexecODBLibOrders.AppOrder memory _apporder)
public returns (bool)
{
bytes32 dapporderHash = _apporder.hash();
require(msg.sender == App(_apporder.app).m_owner());
// require(verify(msg.sender, dapporderHash, _apporder.sign));
m_consumed[dapporderHash] = _apporder.volume;
emit ClosedAppOrder(dapporderHash);
return true;
}
// should be external
function cancelDatasetOrder(IexecODBLibOrders.DatasetOrder memory _datasetorder)
public returns (bool)
{
bytes32 dataorderHash = _datasetorder.hash();
require(msg.sender == Dataset(_datasetorder.dataset).m_owner());
// require(verify(msg.sender, dataorderHash, _datasetorder.sign));
m_consumed[dataorderHash] = _datasetorder.volume;
emit ClosedDatasetOrder(dataorderHash);
return true;
}
// should be external
function cancelWorkerpoolOrder(IexecODBLibOrders.WorkerpoolOrder memory _workerpoolorder)
public returns (bool)
{
bytes32 poolorderHash = _workerpoolorder.hash();
require(msg.sender == Workerpool(_workerpoolorder.workerpool).m_owner());
// require(verify(msg.sender, poolorderHash, _workerpoolorder.sign));
m_consumed[poolorderHash] = _workerpoolorder.volume;
emit ClosedWorkerpoolOrder(poolorderHash);
return true;
}
// should be external
function cancelRequestOrder(IexecODBLibOrders.RequestOrder memory _requestorder)
public returns (bool)
{
bytes32 requestorderHash = _requestorder.hash();
require(msg.sender == _requestorder.requester);
// require(verify(msg.sender, requestorderHash, _requestorder.sign));
m_consumed[requestorderHash] = _requestorder.volume;
emit ClosedRequestOrder(requestorderHash);
return true;
}
/***************************************************************************
* Escrow overhead for contribution *
***************************************************************************/
function lockContribution(bytes32 _dealid, address _worker)
external onlyIexecHub
{
lock(_worker, m_deals[_dealid].workerStake);
}
function unlockContribution(bytes32 _dealid, address _worker)
external onlyIexecHub
{
unlock(_worker, m_deals[_dealid].workerStake);
}
function unlockAndRewardForContribution(bytes32 _dealid, address _worker, uint256 _amount)
external onlyIexecHub
{
unlock(_worker, m_deals[_dealid].workerStake);
reward(_worker, _amount);
}
function seizeContribution(bytes32 _dealid, address _worker)
external onlyIexecHub
{
seize(_worker, m_deals[_dealid].workerStake);
}
function rewardForScheduling(bytes32 _dealid, uint256 _amount)
external onlyIexecHub
{
reward(m_deals[_dealid].workerpool.owner, _amount);
}
function successWork(bytes32 _dealid)
external onlyIexecHub
{
IexecODBLibCore.Deal storage deal = m_deals[_dealid];
uint256 requesterstake = deal.app.price
.add(deal.dataset.price)
.add(deal.workerpool.price);
uint256 poolstake = deal.workerpool.price
.percentage(WORKERPOOL_STAKE_RATIO);
// seize requester funds
seize (deal.requester, requesterstake);
// unlock pool stake
unlock(deal.workerpool.owner, poolstake);
// dapp reward
reward(deal.app.owner, deal.app.price);
// data reward
if (deal.dataset.pointer != address(0))
{
reward(deal.dataset.owner, deal.dataset.price);
}
// pool reward performed by consensus manager
/**
* Retrieve part of the kitty
* TODO: remove / keep ?
*/
uint256 kitty = m_accounts[address(0)].locked;
if (kitty > 0)
{
kitty = kitty
.percentage(KITTY_RATIO) // fraction
.max(KITTY_MIN) // at least this
.min(kitty); // but not more than available
seize (address(0), kitty);
reward(deal.workerpool.owner, kitty);
}
}
function failedWork(bytes32 _dealid)
external onlyIexecHub
{
IexecODBLibCore.Deal storage deal = m_deals[_dealid];
uint256 requesterstake = deal.app.price
.add(deal.dataset.price)
.add(deal.workerpool.price);
uint256 poolstake = deal.workerpool.price
.percentage(WORKERPOOL_STAKE_RATIO);
unlock(deal.requester, requesterstake);
seize (deal.workerpool.owner, poolstake );
reward(address(0), poolstake ); // → Kitty / Burn
lock (address(0), poolstake ); // → Kitty / Burn
}
} | bytes32 public constant EIP712DOMAIN_TYPEHASH = keccak256("EIP712Domain(string name,string version,uint256 chainId,address verifyingContract)"); bytes32 public constant APPORDER_TYPEHASH = keccak256("AppOrder(address app,uint256 appprice,uint256 volume,bytes32 tag,address datasetrestrict,address workerpoolrestrict,address requesterrestrict,bytes32 salt)"); bytes32 public constant DATASETORDER_TYPEHASH = keccak256("DatasetOrder(address dataset,uint256 datasetprice,uint256 volume,bytes32 tag,address apprestrict,address workerpoolrestrict,address requesterrestrict,bytes32 salt)"); bytes32 public constant WORKERPOOLORDER_TYPEHASH = keccak256("WorkerpoolOrder(address workerpool,uint256 workerpoolprice,uint256 volume,bytes32 tag,uint256 category,uint256 trust,address apprestrict,address datasetrestrict,address requesterrestrict,bytes32 salt)"); bytes32 public constant REQUESTORDER_TYPEHASH = keccak256("RequestOrder(address app,uint256 appmaxprice,address dataset,uint256 datasetmaxprice,address workerpool,uint256 workerpoolmaxprice,address requester,uint256 volume,bytes32 tag,uint256 category,uint256 trust,address beneficiary,address callback,string params,bytes32 salt)"); | {
bytes32 public constant EIP712DOMAIN_TYPEHASH = 0x8b73c3c69bb8fe3d512ecc4cf759cc79239f7b179b0ffacaa9a75d522b39400f;
bytes32 public constant APPORDER_TYPEHASH = 0x60815a0eeec47dddf1615fe53b31d016c31444e01b9d796db365443a6445d008;
bytes32 public constant DATASETORDER_TYPEHASH = 0x6cfc932a5a3d22c4359295b9f433edff52b60703fa47690a04a83e40933dd47c;
bytes32 public constant WORKERPOOLORDER_TYPEHASH = 0xaa3429fb281b34691803133d3d978a75bb77c617ed6bc9aa162b9b30920022bb;
bytes32 public constant REQUESTORDER_TYPEHASH = 0xf24e853034a3a450aba845a82914fbb564ad85accca6cf62be112a154520fae0;
struct EIP712Domain
{
string name;
string version;
uint256 chainId;
address verifyingContract;
}
struct AppOrder
{
address app;
uint256 appprice;
uint256 volume;
bytes32 tag;
address datasetrestrict;
address workerpoolrestrict;
address requesterrestrict;
bytes32 salt;
ECDSA.signature sign;
}
struct DatasetOrder
{
address dataset;
uint256 datasetprice;
uint256 volume;
bytes32 tag;
address apprestrict;
address workerpoolrestrict;
address requesterrestrict;
bytes32 salt;
ECDSA.signature sign;
}
struct WorkerpoolOrder
{
address workerpool;
uint256 workerpoolprice;
uint256 volume;
bytes32 tag;
uint256 category;
uint256 trust;
address apprestrict;
address datasetrestrict;
address requesterrestrict;
bytes32 salt;
ECDSA.signature sign;
}
struct RequestOrder
{
address app;
uint256 appmaxprice;
address dataset;
uint256 datasetmaxprice;
address workerpool;
uint256 workerpoolmaxprice;
address requester;
uint256 volume;
bytes32 tag;
uint256 category;
uint256 trust;
address beneficiary;
address callback;
string params;
bytes32 salt;
ECDSA.signature sign;
}
function hash(EIP712Domain memory _domain)
public pure returns (bytes32 domainhash)
{
bytes32 typeHash = EIP712DOMAIN_TYPEHASH;
bytes32 nameHash = keccak256(bytes(_domain.name));
bytes32 versionHash = keccak256(bytes(_domain.version));
assembly {
let temp1 := mload(sub(_domain, 32))
let temp2 := mload(add(_domain, 0))
let temp3 := mload(add(_domain, 32))
mstore(sub(_domain, 32), typeHash)
mstore(add(_domain, 0), nameHash)
mstore(add(_domain, 32), versionHash)
mstore(sub(_domain, 32), temp1)
mstore(add(_domain, 0), temp2)
mstore(add(_domain, 32), temp3)
}
}
function hash(EIP712Domain memory _domain)
public pure returns (bytes32 domainhash)
{
bytes32 typeHash = EIP712DOMAIN_TYPEHASH;
bytes32 nameHash = keccak256(bytes(_domain.name));
bytes32 versionHash = keccak256(bytes(_domain.version));
assembly {
let temp1 := mload(sub(_domain, 32))
let temp2 := mload(add(_domain, 0))
let temp3 := mload(add(_domain, 32))
mstore(sub(_domain, 32), typeHash)
mstore(add(_domain, 0), nameHash)
mstore(add(_domain, 32), versionHash)
mstore(sub(_domain, 32), temp1)
mstore(add(_domain, 0), temp2)
mstore(add(_domain, 32), temp3)
}
}
function hash(AppOrder memory _apporder)
public pure returns (bytes32 apphash)
{
bytes32 typeHash = APPORDER_TYPEHASH;
assembly {
let temp1 := mload(sub(_apporder, 32))
mstore(sub(_apporder, 32), typeHash)
mstore(sub(_apporder, 32), temp1)
}
}
function hash(AppOrder memory _apporder)
public pure returns (bytes32 apphash)
{
bytes32 typeHash = APPORDER_TYPEHASH;
assembly {
let temp1 := mload(sub(_apporder, 32))
mstore(sub(_apporder, 32), typeHash)
mstore(sub(_apporder, 32), temp1)
}
}
function hash(DatasetOrder memory _datasetorder)
public pure returns (bytes32 datasethash)
{
bytes32 typeHash = DATASETORDER_TYPEHASH;
assembly {
let temp1 := mload(sub(_datasetorder, 32))
mstore(sub(_datasetorder, 32), typeHash)
mstore(sub(_datasetorder, 32), temp1)
}
}
function hash(DatasetOrder memory _datasetorder)
public pure returns (bytes32 datasethash)
{
bytes32 typeHash = DATASETORDER_TYPEHASH;
assembly {
let temp1 := mload(sub(_datasetorder, 32))
mstore(sub(_datasetorder, 32), typeHash)
mstore(sub(_datasetorder, 32), temp1)
}
}
function hash(WorkerpoolOrder memory _workerpoolorder)
public pure returns (bytes32 workerpoolhash)
{
bytes32 typeHash = WORKERPOOLORDER_TYPEHASH;
assembly {
let temp1 := mload(sub(_workerpoolorder, 32))
mstore(sub(_workerpoolorder, 32), typeHash)
mstore(sub(_workerpoolorder, 32), temp1)
}
}
function hash(WorkerpoolOrder memory _workerpoolorder)
public pure returns (bytes32 workerpoolhash)
{
bytes32 typeHash = WORKERPOOLORDER_TYPEHASH;
assembly {
let temp1 := mload(sub(_workerpoolorder, 32))
mstore(sub(_workerpoolorder, 32), typeHash)
mstore(sub(_workerpoolorder, 32), temp1)
}
}
function hash(RequestOrder memory _requestorder)
public pure returns (bytes32 requesthash)
{
bytes32 typeHash = REQUESTORDER_TYPEHASH;
bytes32 paramsHash = keccak256(bytes(_requestorder.params));
assembly {
let temp1 := mload(sub(_requestorder, 32))
let temp2 := mload(add(_requestorder, 416))
mstore(sub(_requestorder, 32), typeHash)
mstore(add(_requestorder, 416), paramsHash)
mstore(sub(_requestorder, 32), temp1)
mstore(add(_requestorder, 416), temp2)
}
}
function hash(RequestOrder memory _requestorder)
public pure returns (bytes32 requesthash)
{
bytes32 typeHash = REQUESTORDER_TYPEHASH;
bytes32 paramsHash = keccak256(bytes(_requestorder.params));
assembly {
let temp1 := mload(sub(_requestorder, 32))
let temp2 := mload(add(_requestorder, 416))
mstore(sub(_requestorder, 32), typeHash)
mstore(add(_requestorder, 416), paramsHash)
mstore(sub(_requestorder, 32), temp1)
mstore(add(_requestorder, 416), temp2)
}
}
}
| 12,917,851 | [
1,
3890,
1578,
1071,
5381,
565,
512,
2579,
27,
2138,
18192,
67,
2399,
15920,
273,
417,
24410,
581,
5034,
2932,
41,
2579,
27,
2138,
3748,
12,
1080,
508,
16,
1080,
1177,
16,
11890,
5034,
2687,
548,
16,
2867,
3929,
310,
8924,
2225,
1769,
1731,
1578,
1071,
5381,
3639,
9146,
7954,
67,
2399,
15920,
273,
417,
24410,
581,
5034,
2932,
3371,
2448,
12,
2867,
595,
16,
11890,
5034,
595,
8694,
16,
11890,
5034,
3940,
16,
3890,
1578,
1047,
16,
2867,
3709,
30604,
16,
2867,
4322,
6011,
30604,
16,
2867,
19961,
30604,
16,
3890,
1578,
4286,
2225,
1769,
1731,
1578,
1071,
5381,
565,
8730,
4043,
7954,
67,
2399,
15920,
273,
417,
24410,
581,
5034,
2932,
10656,
2448,
12,
2867,
3709,
16,
11890,
5034,
3709,
8694,
16,
11890,
5034,
3940,
16,
3890,
1578,
1047,
16,
2867,
595,
30604,
16,
2867,
4322,
6011,
30604,
16,
2867,
19961,
30604,
16,
3890,
1578,
4286,
2225,
2
] | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1
] | [
1,
95,
203,
202,
3890,
1578,
1071,
5381,
565,
512,
2579,
27,
2138,
18192,
67,
2399,
15920,
273,
374,
92,
28,
70,
9036,
71,
23,
71,
8148,
9897,
28,
3030,
23,
72,
13757,
24410,
24,
8522,
5877,
29,
952,
7235,
4366,
29,
74,
27,
70,
28814,
70,
20,
74,
507,
5353,
69,
29,
69,
5877,
72,
25,
3787,
70,
5520,
16010,
74,
31,
203,
202,
3890,
1578,
1071,
5381,
3639,
9146,
7954,
67,
2399,
15920,
273,
374,
92,
4848,
28,
3600,
69,
20,
1340,
557,
9462,
449,
2180,
2313,
3600,
3030,
8643,
70,
6938,
72,
24171,
71,
23,
3461,
6334,
73,
1611,
70,
29,
72,
7235,
26,
1966,
5718,
25,
6334,
23,
69,
1105,
7950,
72,
713,
28,
31,
203,
202,
3890,
1578,
1071,
5381,
565,
8730,
4043,
7954,
67,
2399,
15920,
273,
374,
92,
26,
71,
7142,
29,
1578,
69,
25,
69,
23,
72,
3787,
71,
24,
4763,
29,
29286,
70,
29,
74,
24,
3707,
329,
1403,
9401,
70,
4848,
27,
4630,
507,
24,
6669,
9349,
69,
3028,
69,
10261,
73,
24,
5908,
3707,
449,
9462,
71,
31,
203,
202,
3890,
1578,
1071,
5381,
17062,
654,
20339,
7954,
67,
2399,
15920,
273,
374,
6995,
69,
5026,
5540,
19192,
6030,
21,
70,
5026,
8148,
2643,
4630,
28615,
72,
23,
72,
29,
8285,
69,
5877,
9897,
4700,
71,
26,
4033,
329,
26,
13459,
29,
7598,
30042,
70,
29,
70,
5082,
29,
6976,
3787,
9897,
31,
203,
202,
3890,
1578,
1071,
5381,
565,
12492,
7954,
67,
2399,
15920,
273,
374,
5841,
3247,
73,
7140,
23,
4630,
24,
2
] |
// SPDX-License-Identifier: MIT
pragma solidity >=0.6.0 <0.8.0;
import "@openzeppelin/contracts/GSN/Context.sol";
/**
* @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 PausedDeposit(address account);
/**
* @dev Emitted when the pause is lifted by `account`.
*/
event UnpausedDeposit(address account);
/**
* @dev Emitted when the pause is triggered by `account`.
*/
event PausedWithdraw(address account);
/**
* @dev Emitted when the pause is lifted by `account`.
*/
event UnpausedWithdraw(address account);
bool private _depositPaused;
bool private _withdrawPaused;
/**
* @dev Initializes the contract in unpaused state.
*/
constructor () internal {
_depositPaused = false;
_withdrawPaused = false;
}
/**
* @dev Returns true if the contract is paused, and false otherwise.
*/
function pausedDeposit() public view returns (bool) {
return _depositPaused;
}
/**
* @dev Returns true if the contract is paused, and false otherwise.
*/
function pausedWithdraw() public view returns (bool) {
return _withdrawPaused;
}
/**
* @dev Modifier to make a function callable only when the contract is not paused.
*
* Requirements:
*
* - The contract must not be paused.
*/
modifier whenDepositNotPaused() {
require(!_depositPaused, "Pausable: Deposit paused");
_;
}
/**
* @dev Modifier to make a function callable only when the contract is paused.
*
* Requirements:
*
* - The contract must be paused.
*/
modifier whenDepositPaused() {
require(_depositPaused, "Pausable: Deposit not paused");
_;
}
/**
* @dev Modifier to make a function callable only when the contract is not paused.
*
* Requirements:
*
* - The contract must not be paused.
*/
modifier whenWithdrawNotPaused() {
require(!_withdrawPaused, "Pausable: paused");
_;
}
/**
* @dev Modifier to make a function callable only when the contract is paused.
*
* Requirements:
*
* - The contract must be paused.
*/
modifier whenWithdrawPaused() {
require(_withdrawPaused, "Pausable: not paused");
_;
}
/**
* @dev Triggers stopped state.
*
* Requirements:
*
* - The contract Deposits must not be paused.
*/
function pauseDeposit() internal virtual whenDepositNotPaused(){
_depositPaused = true ;
emit PausedDeposit(_msgSender());
}
function unpauseDeposit() internal virtual whenDepositPaused() {
_depositPaused = false;
emit UnpausedDeposit(_msgSender());
}
/**
* @dev Triggers stopped state.
*
* Requirements:
*
* - The contract Deposits must not be paused.
*/
function pauseWithdraw() internal virtual whenWithdrawNotPaused(){
_depositPaused = true ;
emit PausedWithdraw(_msgSender());
}
function unpauseWithdraw() internal virtual whenWithdrawPaused() {
_withdrawPaused = false;
emit UnpausedWithdraw(_msgSender());
}
}
| * @dev Modifier to make a function callable only when the contract is paused. Requirements: - The contract must be paused./ | modifier whenDepositPaused() {
require(_depositPaused, "Pausable: Deposit not paused");
_;
}
| 1,814,859 | [
1,
9829,
358,
1221,
279,
445,
4140,
1338,
1347,
326,
6835,
353,
17781,
18,
29076,
30,
300,
1021,
6835,
1297,
506,
17781,
18,
19,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
565,
9606,
1347,
758,
1724,
28590,
1435,
288,
203,
3639,
2583,
24899,
323,
1724,
28590,
16,
315,
16507,
16665,
30,
4019,
538,
305,
486,
17781,
8863,
203,
3639,
389,
31,
203,
565,
289,
203,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
] |
./full_match/1/0x2B19466eE159DE81c0393b933472BbA4EbD8E0BE/sources/contracts/ERC1155.sol | * @dev See {IERC1155-balanceOf}. Requirements: - `account` cannot be the zero address./ | function balanceOf(address account, uint256 id) public view virtual override returns (uint256) {
require(account != address(0), "ERC1155: balance query for the zero address");
return _balances[id][account].amount;
}
| 9,801,780 | [
1,
9704,
288,
45,
654,
39,
2499,
2539,
17,
12296,
951,
5496,
29076,
30,
300,
1375,
4631,
68,
2780,
506,
326,
3634,
1758,
18,
19,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
565,
445,
11013,
951,
12,
2867,
2236,
16,
2254,
5034,
612,
13,
1071,
1476,
5024,
3849,
1135,
261,
11890,
5034,
13,
288,
203,
3639,
2583,
12,
4631,
480,
1758,
12,
20,
3631,
315,
654,
39,
2499,
2539,
30,
11013,
843,
364,
326,
3634,
1758,
8863,
203,
3639,
327,
389,
70,
26488,
63,
350,
6362,
4631,
8009,
8949,
31,
203,
565,
289,
203,
203,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
] |
//Address: 0x1418e621e5be75f2f79b7add3322ce8481f073b4
//Contract name: DataeumToken
//Balance: 0 Ether
//Verification Date: 5/23/2018
//Transacion Count: 3
// CODE STARTS HERE
pragma solidity ^0.4.13;
contract ApproveAndCallFallBack {
function receiveApproval(address from, uint256 tokens, address token, bytes data) public;
}
contract ERC20Interface {
function totalSupply() public view returns (uint);
function balanceOf(address tokenOwner) public view returns (uint balance);
function allowance(address tokenOwner, address spender) public view 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);
}
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);
}
}
contract DataeumToken is Owned, ERC20Interface {
// Adding safe calculation methods to uint256
using SafeMath for uint256;
// Defining balances mapping (ERC20)
mapping(address => uint256) balances;
// Defining allowances mapping (ERC20)
mapping(address => mapping(address => uint256)) allowed;
// Defining addresses allowed to bypass global freeze
mapping(address => bool) public freezeBypassing;
// Defining addresses that have custom lockups periods
mapping(address => uint256) public lockupExpirations;
// Token Symbol
string public constant symbol = "XDT";
// Token Name
string public constant name = "Dataeum Token";
// Token Decimals
uint8 public constant decimals = 18;
// Current distributed supply
uint256 public circulatingSupply = 0;
// global freeze one-way toggle
bool public tradingLive = false;
// Total supply of token
uint256 public totalSupply;
/**
* @notice Event for Lockup period applied to address
* @param owner Specific lockup address target
* @param until Timestamp when lockup end (seconds since epoch)
*/
event LockupApplied(
address indexed owner,
uint256 until
);
/**
* @notice Contract constructor
* @param _totalSupply Total supply of token wanted
*/
constructor(uint256 _totalSupply) public {
totalSupply = _totalSupply;
}
/**
* @notice distribute tokens to an address
* @param to Who will receive the token
* @param tokens How much token will be sent
*/
function distribute(
address to,
uint256 tokens
)
public onlyOwner
{
uint newCirculatingSupply = circulatingSupply.add(tokens);
require(newCirculatingSupply <= totalSupply);
circulatingSupply = newCirculatingSupply;
balances[to] = balances[to].add(tokens);
emit Transfer(address(this), to, tokens);
}
/**
* @notice Prevents the given wallet to transfer its token for the given duration.
* This methods resets the lock duration if one is already in place.
* @param wallet The wallet address to lock
* @param duration How much time is the token locked from now (in sec)
*/
function lockup(
address wallet,
uint256 duration
)
public onlyOwner
{
uint256 lockupExpiration = duration.add(now);
lockupExpirations[wallet] = lockupExpiration;
emit LockupApplied(wallet, lockupExpiration);
}
/**
* @notice choose if an address is allowed to bypass the global freeze
* @param to Target of the freeze bypass status update
* @param status New status (if true will bypass)
*/
function setBypassStatus(
address to,
bool status
)
public onlyOwner
{
freezeBypassing[to] = status;
}
/**
* @notice One-way toggle to allow trading (remove global freeze)
*/
function setTradingLive() public onlyOwner {
tradingLive = true;
}
/**
* @notice Modifier that checks if the conditions are met for a token to be
* tradable. To be so, it must :
* - Global Freeze must be removed, or, "from" must be allowed to bypass it
* - "from" must not be in a custom lockup period
* @param from Who to check the status
*/
modifier tradable(address from) {
require(
(tradingLive || freezeBypassing[from]) && //solium-disable-line indentation
(lockupExpirations[from] <= now)
);
_;
}
/**
* @notice Return the total supply of the token
* @dev This function is part of the ERC20 standard
* @return {"supply": "The token supply"}
*/
function totalSupply() public view returns (uint256 supply) {
return totalSupply;
}
/**
* @notice Get the token balance of `owner`
* @dev This function is part of the ERC20 standard
* @param owner The wallet to get the balance of
* @return {"balance": "The balance of `owner`"}
*/
function balanceOf(
address owner
)
public view returns (uint256 balance)
{
return balances[owner];
}
/**
* @notice Transfers `amount` from msg.sender to `destination`
* @dev This function is part of the ERC20 standard
* @param destination The address that receives the tokens
* @param amount Token amount to transfer
* @return {"success": "If the operation completed successfuly"}
*/
function transfer(
address destination,
uint256 amount
)
public tradable(msg.sender) returns (bool success)
{
balances[msg.sender] = balances[msg.sender].sub(amount);
balances[destination] = balances[destination].add(amount);
emit Transfer(msg.sender, destination, amount);
return true;
}
/**
* @notice Transfer tokens from an address to another one
* through an allowance made before
* @dev This function is part of the ERC20 standard
* @param from The address that sends the tokens
* @param to The address that receives the tokens
* @param tokenAmount Token amount to transfer
* @return {"success": "If the operation completed successfuly"}
*/
function transferFrom(
address from,
address to,
uint256 tokenAmount
)
public tradable(from) returns (bool success)
{
balances[from] = balances[from].sub(tokenAmount);
allowed[from][msg.sender] = allowed[from][msg.sender].sub(tokenAmount);
balances[to] = balances[to].add(tokenAmount);
emit Transfer(from, to, tokenAmount);
return true;
}
/**
* @notice Approve an address to send `tokenAmount` tokens to `msg.sender` (make an allowance)
* @dev This function is part of the ERC20 standard
* @param spender The allowed address
* @param tokenAmount The maximum amount allowed to spend
* @return {"success": "If the operation completed successfuly"}
*/
function approve(
address spender,
uint256 tokenAmount
)
public returns (bool success)
{
allowed[msg.sender][spender] = tokenAmount;
emit Approval(msg.sender, spender, tokenAmount);
return true;
}
/**
* @notice Get the remaining allowance for a spender on a given address
* @dev This function is part of the ERC20 standard
* @param tokenOwner The address that owns the tokens
* @param spender The spender
* @return {"remaining": "The amount of tokens remaining in the allowance"}
*/
function allowance(
address tokenOwner,
address spender
)
public view returns (uint256 remaining)
{
return allowed[tokenOwner][spender];
}
/**
* @notice Permits to create an approval on a contract and then call a method
* on the approved contract right away.
* @param spender The allowed address
* @param tokenAmount The maximum amount allowed to spend
* @param data The data sent back as parameter to the contract (bytes array)
* @return {"success": "If the operation completed successfuly"}
*/
function approveAndCall(
address spender,
uint256 tokenAmount,
bytes data
)
public tradable(spender) returns (bool success)
{
allowed[msg.sender][spender] = tokenAmount;
emit Approval(msg.sender, spender, tokenAmount);
ApproveAndCallFallBack(spender)
.receiveApproval(msg.sender, tokenAmount, this, data);
return true;
}
/**
* @notice Permits to withdraw any ERC20 tokens that have been mistakingly sent to this contract
* @param tokenAddress The received ERC20 token address
* @param tokenAmount The amount of ERC20 tokens to withdraw from this contract
* @return {"success": "If the operation completed successfuly"}
*/
function withdrawERC20Token(
address tokenAddress,
uint256 tokenAmount
)
public onlyOwner returns (bool success)
{
return ERC20Interface(tokenAddress).transfer(owner, tokenAmount);
}
}
library SafeMath {
/**
* @notice 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;
}
/**
* @notice 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;
}
/**
* @notice 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;
}
}
| * @notice Get the remaining allowance for a spender on a given address @dev This function is part of the ERC20 standard @param tokenOwner The address that owns the tokens @param spender The spender @return {"remaining": "The amount of tokens remaining in the allowance"}/ | function allowance(
address tokenOwner,
address spender
)
public view returns (uint256 remaining)
{
return allowed[tokenOwner][spender];
}
| 12,716,064 | [
1,
967,
326,
4463,
1699,
1359,
364,
279,
17571,
264,
603,
279,
864,
1758,
225,
1220,
445,
353,
1087,
434,
326,
4232,
39,
3462,
4529,
225,
1147,
5541,
1021,
1758,
716,
29065,
326,
2430,
225,
17571,
264,
1021,
17571,
264,
327,
12528,
17956,
6877,
315,
1986,
3844,
434,
2430,
4463,
316,
326,
1699,
1359,
6,
4004,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
565,
445,
1699,
1359,
12,
203,
3639,
1758,
1147,
5541,
16,
203,
3639,
1758,
17571,
264,
203,
565,
262,
203,
3639,
1071,
1476,
1135,
261,
11890,
5034,
4463,
13,
203,
565,
288,
203,
3639,
327,
2935,
63,
2316,
5541,
6362,
87,
1302,
264,
15533,
203,
565,
289,
203,
203,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
] |
./full_match/43113/0x20cb630B2d9F4D31b1c024ec78018C451bD398Fe/sources/contracts/Vesting.sol | * @dev Check whether a particular vesting index has elapsed and claimable @return - Bool: Claimable, uint256: If started and not claimable, returns the time needed to be claimable. @notice - Access control: Public./ | function isVestingClaimable(ERC20 _token, uint256 _index) public view returns(bool, uint256) {
if (!vestInfos[_token].vestingTimerStarted) {
return (false, 0);
}
uint256 period = vestInfos[_token].periods[_index];
uint256 releaseTime = vestInfos[_token].startTime + period;
bool claimable = (block.timestamp > releaseTime);
uint256 remainTime;
if (!claimable) {
remainTime = releaseTime - block.timestamp;
}
return (claimable, remainTime);
}
| 13,212,227 | [
1,
1564,
2856,
279,
6826,
331,
10100,
770,
711,
9613,
471,
7516,
429,
327,
300,
9166,
30,
18381,
429,
16,
2254,
5034,
30,
971,
5746,
471,
486,
7516,
429,
16,
1135,
326,
813,
3577,
358,
506,
7516,
429,
18,
225,
300,
5016,
3325,
30,
7224,
18,
19,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
565,
445,
353,
58,
10100,
9762,
429,
12,
654,
39,
3462,
389,
2316,
16,
2254,
5034,
389,
1615,
13,
1071,
1476,
1135,
12,
6430,
16,
2254,
5034,
13,
288,
203,
203,
3639,
309,
16051,
26923,
7655,
63,
67,
2316,
8009,
90,
10100,
6777,
9217,
13,
288,
203,
5411,
327,
261,
5743,
16,
374,
1769,
203,
3639,
289,
203,
3639,
2254,
5034,
3879,
273,
331,
395,
7655,
63,
67,
2316,
8009,
20659,
63,
67,
1615,
15533,
203,
3639,
2254,
5034,
3992,
950,
273,
331,
395,
7655,
63,
67,
2316,
8009,
1937,
950,
397,
3879,
31,
203,
3639,
1426,
7516,
429,
273,
261,
2629,
18,
5508,
405,
3992,
950,
1769,
203,
3639,
2254,
5034,
7232,
950,
31,
203,
3639,
309,
16051,
14784,
429,
13,
288,
203,
5411,
7232,
950,
273,
3992,
950,
300,
1203,
18,
5508,
31,
203,
3639,
289,
203,
3639,
327,
261,
14784,
429,
16,
7232,
950,
1769,
203,
565,
289,
203,
203,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
] |
./full_match/3/0x6CcEE702A4fad4239Ec763F8EFF338Db96E50819/sources/Tarot.sol | * Hack to get things to work automatically on OpenSea. Use isApprovedForAll so the frontend doesn't have to worry about different method names./ | function isApprovedForAll(address _owner, address _operator)
public
view
returns (bool)
{
if (owner() == _owner && _owner == _operator) {
return true;
}
ProxyRegistry proxyRegistry = ProxyRegistry(proxyRegistryAddress);
return
owner() == _owner &&
address(proxyRegistry.proxies(_owner)) == _operator;
}
| 14,175,143 | [
1,
44,
484,
358,
336,
9198,
358,
1440,
6635,
603,
3502,
1761,
69,
18,
2672,
353,
31639,
1290,
1595,
1427,
326,
15442,
3302,
1404,
1240,
358,
26784,
2973,
3775,
707,
1257,
18,
19,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
565,
445,
353,
31639,
1290,
1595,
12,
2867,
389,
8443,
16,
1758,
389,
9497,
13,
203,
3639,
1071,
203,
3639,
1476,
203,
3639,
1135,
261,
6430,
13,
203,
565,
288,
203,
3639,
309,
261,
8443,
1435,
422,
389,
8443,
597,
389,
8443,
422,
389,
9497,
13,
288,
203,
5411,
327,
638,
31,
203,
3639,
289,
203,
203,
3639,
7659,
4243,
2889,
4243,
273,
7659,
4243,
12,
5656,
4243,
1887,
1769,
203,
3639,
327,
203,
5411,
3410,
1435,
422,
389,
8443,
597,
203,
5411,
1758,
12,
5656,
4243,
18,
20314,
606,
24899,
8443,
3719,
422,
389,
9497,
31,
203,
565,
289,
203,
203,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
] |
// SPDX-License-Identifier: GPL-3.0
pragma solidity ^0.8.0;
import { ERC20 } from "@openzeppelin/contracts/token/ERC20/ERC20.sol";
contract ERC20Mock is ERC20 {
// solhint-disable-next-line no-empty-blocks
constructor(string memory name, string memory symbol) ERC20(name, symbol) {}
function mint(address account, uint256 amount) external {
_mint(account, amount);
}
function burn(address account, uint256 amount) external {
_burn(account, amount);
}
function setBalance(address to, uint256 amount) public {
uint256 old = balanceOf(to);
if (old < amount) {
_mint(to, amount - old);
} else if (old > amount) {
_burn(to, old - amount);
}
}
}
| solhint-disable-next-line no-empty-blocks | contract ERC20Mock is ERC20 {
pragma solidity ^0.8.0;
import { ERC20 } from "@openzeppelin/contracts/token/ERC20/ERC20.sol";
constructor(string memory name, string memory symbol) ERC20(name, symbol) {}
function mint(address account, uint256 amount) external {
_mint(account, amount);
}
function burn(address account, uint256 amount) external {
_burn(account, amount);
}
function setBalance(address to, uint256 amount) public {
uint256 old = balanceOf(to);
if (old < amount) {
_mint(to, amount - old);
_burn(to, old - amount);
}
}
function setBalance(address to, uint256 amount) public {
uint256 old = balanceOf(to);
if (old < amount) {
_mint(to, amount - old);
_burn(to, old - amount);
}
}
} else if (old > amount) {
}
| 15,843,749 | [
1,
18281,
11317,
17,
8394,
17,
4285,
17,
1369,
1158,
17,
5531,
17,
7996,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
16351,
4232,
39,
3462,
9865,
353,
4232,
39,
3462,
288,
203,
203,
683,
9454,
18035,
560,
3602,
20,
18,
28,
18,
20,
31,
203,
5666,
288,
4232,
39,
3462,
289,
628,
8787,
3190,
94,
881,
84,
292,
267,
19,
16351,
87,
19,
2316,
19,
654,
39,
3462,
19,
654,
39,
3462,
18,
18281,
14432,
203,
565,
3885,
12,
1080,
3778,
508,
16,
533,
3778,
3273,
13,
4232,
39,
3462,
12,
529,
16,
3273,
13,
2618,
203,
565,
445,
312,
474,
12,
2867,
2236,
16,
2254,
5034,
3844,
13,
3903,
288,
203,
3639,
389,
81,
474,
12,
4631,
16,
3844,
1769,
203,
565,
289,
203,
203,
565,
445,
18305,
12,
2867,
2236,
16,
2254,
5034,
3844,
13,
3903,
288,
203,
3639,
389,
70,
321,
12,
4631,
16,
3844,
1769,
203,
565,
289,
203,
203,
565,
445,
444,
13937,
12,
2867,
358,
16,
2254,
5034,
3844,
13,
1071,
288,
203,
3639,
2254,
5034,
1592,
273,
11013,
951,
12,
869,
1769,
203,
3639,
309,
261,
1673,
411,
3844,
13,
288,
203,
5411,
389,
81,
474,
12,
869,
16,
3844,
300,
1592,
1769,
203,
5411,
389,
70,
321,
12,
869,
16,
1592,
300,
3844,
1769,
203,
3639,
289,
203,
565,
289,
203,
565,
445,
444,
13937,
12,
2867,
358,
16,
2254,
5034,
3844,
13,
1071,
288,
203,
3639,
2254,
5034,
1592,
273,
11013,
951,
12,
869,
1769,
203,
3639,
309,
261,
1673,
411,
3844,
13,
288,
203,
5411,
389,
81,
474,
12,
869,
16,
3844,
300,
1592,
1769,
203,
5411,
389,
70,
321,
12,
869,
16,
1592,
300,
2
] |
pragma solidity ^0.4.18;
interface ExpectedRateInterface {
function getExpectedRate(ERC20 source, ERC20 dest, uint srcQty) public view
returns (uint expectedPrice, uint slippagePrice);
}
interface ERC20 {
function totalSupply() public view returns (uint supply);
function balanceOf(address _owner) public view returns (uint balance);
function transfer(address _to, uint _value) public returns (bool success);
function transferFrom(address _from, address _to, uint _value) public returns (bool success);
function approve(address _spender, uint _value) public returns (bool success);
function allowance(address _owner, address _spender) public view returns (uint remaining);
function decimals() public view returns(uint digits);
event Transfer(address indexed _from, address indexed _to, uint _value);
event Approval(address indexed _owner, address indexed _spender, uint _value);
}
interface SanityPricingInterface {
function getSanityPrice(ERC20 src, ERC20 dest) view public returns(uint);
}
contract KyberConstants {
ERC20 constant ETH_TOKEN_ADDRESS = ERC20(0x00eeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeee);
uint constant PRECISION = (10**18);
uint constant MAX_QTY = (10**28); // 1B tokens
uint constant MAX_RATE = (PRECISION * 10**6); // up to 1M tokens per ETH
uint constant MAX_DECIMALS = 18;
}
interface FeeBurnerInterface {
function handleFees (uint tradeWeiAmount, address reserve, address wallet) public returns(bool);
}
contract PermissionGroups {
address public admin;
address public pendingAdmin;
mapping(address=>bool) operators;
mapping(address=>bool) alerters;
address[] operatorsGroup;
address[] alertersGroup;
function PermissionGroups() public {
admin = msg.sender;
}
modifier onlyAdmin() {
require (msg.sender == admin);
_;
}
modifier onlyOperator() {
require (operators[msg.sender]);
_;
}
modifier onlyAlerter() {
require (alerters[msg.sender]);
_;
}
event TransferAdmin(address pendingAdmin);
/**
* @dev Allows the current admin to set the pendingAdmin address.
* @param newAdmin The address to transfer ownership to.
*/
function transferAdmin(address newAdmin) public onlyAdmin {
require(newAdmin != address(0));
TransferAdmin(pendingAdmin);
pendingAdmin = newAdmin;
}
event ClaimAdmin( address newAdmin, address previousAdmin);
/**
* @dev Allows the pendingAdmin address to finalize the change admin process.
*/
function claimAdmin() public {
require(pendingAdmin == msg.sender);
ClaimAdmin(pendingAdmin, admin);
admin = pendingAdmin;
pendingAdmin = address(0);
}
event AddAlerter (address newAlerter, bool isAdd);
function addAlerter(address newAlerter) public onlyAdmin {
require(!alerters[newAlerter]); // prevent duplicates.
AddAlerter(newAlerter, true);
alerters[newAlerter] = true;
alertersGroup.push(newAlerter);
}
function removeAlerter (address alerter) public onlyAdmin {
require(alerters[alerter]);
alerters[alerter] = false;
for (uint i = 0; i < alertersGroup.length; ++i)
{
if (alertersGroup[i] == alerter)
{
alertersGroup[i] = alertersGroup[alertersGroup.length - 1];
alertersGroup.length--;
AddAlerter(alerter, false);
break;
}
}
}
event AddOperator(address newOperator, bool isAdd);
function addOperator(address newOperator) public onlyAdmin {
require(!operators[newOperator]); // prevent duplicates.
AddOperator(newOperator, true);
operators[newOperator] = true;
operatorsGroup.push(newOperator);
}
function removeOperator (address operator) public onlyAdmin {
require (operators[operator]);
operators[operator] = false;
for (uint i = 0; i < operatorsGroup.length; ++i)
{
if (operatorsGroup[i] == operator)
{
operatorsGroup[i] = operatorsGroup[operatorsGroup.length - 1];
operatorsGroup.length -= 1;
AddOperator(operator, false);
break;
}
}
}
function getOperators () external view returns(address []) {
return operatorsGroup;
}
function getAlerters () external view returns(address []) {
return alertersGroup;
}
}
contract Withdrawable is PermissionGroups {
event WithdrawToken(ERC20 token, uint amount, address sendTo);
/**
* @dev Withdraw all ERC20 compatible tokens
* @param token ERC20 The address of the token contract
*/
function withdrawToken(ERC20 token, uint amount, address sendTo) external onlyAdmin {
assert(token.transfer(sendTo, amount));
WithdrawToken(token, amount, sendTo);
}
event WithdrawEther(uint amount, address sendTo);
/**
* @dev Withdraw Ethers
*/
function withdrawEther(uint amount, address sendTo) external onlyAdmin {
sendTo.transfer(amount);
WithdrawEther(amount, sendTo);
}
}
contract KyberNetwork is Withdrawable, KyberConstants {
uint public negligiblePriceDiff = 10; // basic price steps will be in 0.01%
KyberReserve[] public reserves;
mapping(address=>bool) public isReserve;
KyberWhiteList public kyberWhiteList;
ExpectedRateInterface public expectedRateContract;
FeeBurnerInterface public feeBurnerContract;
uint public maxGasPrice = 50 * 1000 * 1000 * 1000; // 50 gwei
bool public enable = true; // network is enabled
mapping(address=>mapping(bytes32=>bool)) perReserveListedPairs;
function KyberNetwork(address _admin) public {
admin = _admin;
}
event Trade(address indexed sender, ERC20 source, ERC20 dest, uint actualSrcAmount, uint actualDestAmount);
/// @notice use token address ETH_TOKEN_ADDRESS for ether
/// @dev makes a trade between source and dest token and send dest token to
/// destAddress and record wallet id for later payment
/// @param source Source token
/// @param srcAmount amount of source tokens
/// @param dest Destination token
/// @param destAddress Address to send tokens to
/// @param maxDestAmount A limit on the amount of dest tokens
/// @param minConversionRate The minimal conversion rate. If actual rate is lower, trade is canceled.
/// @return amount of actual dest tokens
function walletTrade(
ERC20 source,
uint srcAmount,
ERC20 dest,
address destAddress,
uint maxDestAmount,
uint minConversionRate,
address walletId
)
public
payable
returns(uint)
{
return trade(source, srcAmount, dest, destAddress, maxDestAmount, minConversionRate, walletId);
}
/// @notice use token address ETH_TOKEN_ADDRESS for ether
/// @dev makes a trade between source and dest token and send dest token to destAddress
/// @param source Source token
/// @param srcAmount amount of source tokens
/// @param dest Destination token
/// @param destAddress Address to send tokens to
/// @param maxDestAmount A limit on the amount of dest tokens
/// @param minConversionRate The minimal conversion rate. If actual rate is lower, trade is canceled.
/// @return amount of actual dest tokens
function trade(
ERC20 source,
uint srcAmount,
ERC20 dest,
address destAddress,
uint maxDestAmount,
uint minConversionRate,
address walletId
)
public
payable
returns(uint)
{
require(enable);
uint userSrcBalanceBefore;
uint userSrcBalanceAfter;
uint userDestBalanceBefore;
uint userDestBalanceAfter;
userSrcBalanceBefore = getBalance(source, msg.sender);
userDestBalanceBefore = getBalance(dest,destAddress);
assert(doTrade(source,srcAmount,dest,destAddress,maxDestAmount,minConversionRate,walletId) > 0);
userSrcBalanceAfter = getBalance(source, msg.sender);
userDestBalanceAfter = getBalance(dest,destAddress);
require(userSrcBalanceAfter <= userSrcBalanceBefore);
require(userDestBalanceAfter >= userDestBalanceBefore);
uint srcDecimals;
uint destDecimals;
if(source == ETH_TOKEN_ADDRESS) {
srcDecimals = 18;
} else {
srcDecimals = source.decimals();
}
if(dest == ETH_TOKEN_ADDRESS) {
destDecimals = 18;
} else {
destDecimals = dest.decimals();
}
// TODO - mitigate potential overflow
require(((userSrcBalanceBefore - userSrcBalanceAfter) * minConversionRate) * (10 ** destDecimals) <=
(userDestBalanceAfter - userDestBalanceBefore) * (10 ** srcDecimals) * PRECISION );
}
function doTrade(
ERC20 source,
uint srcAmount,
ERC20 dest,
address destAddress,
uint maxDestAmount,
uint minConversionRate,
address walletId
)
internal
returns(uint)
{
require(tx.gasprice <= maxGasPrice);
require(kyberWhiteList != address(0));
require(feeBurnerContract != address(0));
require(validateTradeInput(source, srcAmount));
uint reserveInd;
uint rate;
(reserveInd,rate) = findBestRate(source, dest, srcAmount);
KyberReserve theReserve = reserves[reserveInd];
assert(rate > 0);
assert(rate < MAX_RATE);
assert(rate >= minConversionRate);
uint actualSourceAmount = srcAmount;
uint actualDestAmount = theReserve.getDestQty(source, dest, actualSourceAmount, rate);
if(actualDestAmount > maxDestAmount) {
actualDestAmount = maxDestAmount;
actualSourceAmount = theReserve.getSrcQty(source, dest, actualDestAmount, rate);
}
// do the trade
// verify trade size is smaller then user cap
uint ethAmount;
if (source == ETH_TOKEN_ADDRESS) {
ethAmount = actualSourceAmount;
}
else {
ethAmount = actualDestAmount;
}
require(ethAmount <= getUserCapInWei(msg.sender));
assert(doReserveTrade(
source,
actualSourceAmount,
dest,
destAddress,
actualDestAmount,
theReserve,
rate,
true)
);
assert(feeBurnerContract.handleFees(ethAmount,theReserve,walletId));
Trade(msg.sender, source, dest, actualSourceAmount, actualDestAmount);
return actualDestAmount;
}
event AddReserve(KyberReserve reserve, bool add);
/// @notice can be called only by admin
/// @dev add or deletes a reserve to/from the network.
/// @param reserve The reserve address.
/// @param add If true, the add reserve. Otherwise delete reserve.
function addReserve(KyberReserve reserve, bool add) public onlyAdmin {
if(add) {
reserves.push(reserve);
isReserve[reserve] = true;
AddReserve(reserve, true);
} else {
isReserve[reserve] = false;
// will have trouble if more than 50k reserves...
for(uint i = 0; i < reserves.length; i++) {
if(reserves[i] == reserve) {
if(reserves.length == 0) return;
reserves[i] = reserves[--reserves.length];
AddReserve(reserve, false);
break;
}
}
}
}
event ListPairsForReserve(address reserve, ERC20 source, ERC20 dest, bool add);
/// @notice can be called only by admin
/// @dev allow or prevent a specific reserve to trade a pair of tokens
/// @param reserve The reserve address.
/// @param source Source token
/// @param dest Destination token
/// @param add If true then enable trade, otherwise delist pair.
function listPairForReserve(address reserve, ERC20 source, ERC20 dest, bool add) public onlyAdmin {
(perReserveListedPairs[reserve])[keccak256(source, dest)] = add;
if(source != ETH_TOKEN_ADDRESS) {
if(add) {
source.approve(reserve, 2**255); // approve infinity
} else {
source.approve(reserve, 0);
}
}
ListPairsForReserve(reserve, source, dest, add);
}
function setParams(
KyberWhiteList _whiteList,
ExpectedRateInterface _expectedRate,
FeeBurnerInterface _feeBurner,
uint _maxGasPrice,
uint _negligibleDiff
)
public
onlyAdmin
{
kyberWhiteList = _whiteList;
expectedRateContract = _expectedRate;
feeBurnerContract = _feeBurner;
maxGasPrice = _maxGasPrice;
negligiblePriceDiff = _negligibleDiff;
}
function setEnable(bool _enable) public onlyAdmin {
enable = _enable;
}
event EtherRecival(address indexed sender, uint amount);
function() payable public {
require(isReserve[msg.sender]);
EtherRecival(msg.sender,msg.value);
}
/// @dev returns number of reserves
/// @return number of reserves
function getNumReserves() public view returns(uint) {
return reserves.length;
}
/// @notice should be called off chain with as much gas as needed
/// @dev get an array of all reserves
/// @return An array of all reserves
function getReserves() public view returns(KyberReserve[]) {
return reserves;
}
/// @dev get the balance of a user.
/// @param token The token type
/// @return The balance
function getBalance(ERC20 token, address user) public view returns(uint){
if(token == ETH_TOKEN_ADDRESS) return user.balance;
else return token.balanceOf(user);
}
/// @notice use token address ETH_TOKEN_ADDRESS for ether
/// @dev best conversion rate for a pair of tokens, if number of reserves have small differences. randomize
/// @param source Source token
/// @param dest Destination token
function findBestRate(ERC20 source, ERC20 dest, uint srcQty) public view returns(uint, uint) {
uint bestRate = 0;
uint bestReserve = 0;
uint numRelevantReserves = 0;
uint numReserves = reserves.length;
uint[] memory rates = new uint[](numReserves);
uint[] memory reserveCandidates = new uint[](numReserves);
for(uint i = 0; i < numReserves; i++) {
//list all reserves that have this token.
if(!(perReserveListedPairs[reserves[i]])[keccak256(source, dest)]) continue;
rates[i] = reserves[i].getConversionRate(source, dest, srcQty, block.number);
if(rates[i] > bestRate) {
//best rate is highest rate
bestRate = rates[i];
}
}
if (bestRate > 0) {
uint random = 0;
uint smallestRelevantRate = (bestRate * 10000) / (10000 + negligiblePriceDiff);
for (i = 0; i < numReserves; i++) {
if (rates[i] >= smallestRelevantRate) {
reserveCandidates[numRelevantReserves++] = i;
}
}
if (numRelevantReserves > 1) {
//when encountering small price diff from bestRate. draw from relevant reserves
random = uint(block.blockhash(block.number-1)) % numRelevantReserves;
}
bestReserve = reserveCandidates[random];
bestRate = rates[bestReserve];
}
return (bestReserve, bestRate);
}
function getExpectedRate(ERC20 source, ERC20 dest, uint srcQuantity)
public view
returns (uint expectedPrice, uint slippagePrice)
{
require(expectedRateContract != address(0));
return expectedRateContract.getExpectedRate(source, dest, srcQuantity);
}
function getUserCapInWei(address user) public view returns(uint) {
return kyberWhiteList.getUserCapInWei(user);
}
/// @notice use token address ETH_TOKEN_ADDRESS for ether
/// @dev do one trade with a reserve
/// @param source Source token
/// @param amount amount of source tokens
/// @param dest Destination token
/// @param destAddress Address to send tokens to
/// @param reserve Reserve to use
/// @param validate If true, additional validations are applicable
/// @return true if trade is successful
function doReserveTrade(
ERC20 source,
uint amount,
ERC20 dest,
address destAddress,
uint expectedDestAmount,
KyberReserve reserve,
uint conversionRate,
bool validate
)
internal
returns(bool)
{
uint callValue = 0;
if(source == ETH_TOKEN_ADDRESS) {
callValue = amount;
} else {
// take source tokens to this contract
source.transferFrom(msg.sender, this, amount);
}
// reserve send tokens/eth to network. network sends it to destination
assert(reserve.trade.value(callValue)(source, amount, dest, this, conversionRate, validate));
if(dest == ETH_TOKEN_ADDRESS) {
destAddress.transfer(expectedDestAmount);
} else {
assert(dest.transfer(destAddress,expectedDestAmount));
}
return true;
}
/// @notice use token address ETH_TOKEN_ADDRESS for ether
/// @dev checks that user sent ether/tokens to contract before trade
/// @param source Source token
/// @param srcAmount amount of source tokens
/// @return true if input is valid
function validateTradeInput(ERC20 source, uint srcAmount) internal view returns(bool) {
require(srcAmount < MAX_QTY );
if(source == ETH_TOKEN_ADDRESS) {
require (msg.value == srcAmount);
} else {
require (msg.value == 0);
require (source.allowance(msg.sender,this) >= srcAmount);
}
return true;
}
}
contract FeeBurner is Withdrawable, FeeBurnerInterface {
mapping(address=>uint) public reserveFeesInBps;
mapping(address=>address) public reserveKNCWallet;
mapping(address=>uint) public walletFeesInBps;
mapping(address=>uint) public reserveFeeToBurn;
mapping(address=>mapping(address=>uint)) public reserveFeeToWallet;
BurnableToken public KNC;
address public kyberNetwork;
uint public KNCPerETHRate = 300;
function FeeBurner(address _admin, BurnableToken KNCToken) public {
admin = _admin;
KNC = KNCToken;
}
function setReserveData(address reserve, uint feesInBps, address kncWallet) public onlyAdmin {
require(feesInBps < 100); // make sure it is always < 1%
reserveFeesInBps[reserve] = feesInBps;
reserveKNCWallet[reserve] = kncWallet;
}
function setWalletFees(address wallet, uint feesInBps) public onlyAdmin {
require(feesInBps < 10000); // under 100%
walletFeesInBps[wallet] = feesInBps;
}
function setKyberNetwork(address network) public onlyAdmin {
kyberNetwork = network;
}
function setKNCRate(uint rate) public onlyAdmin {
KNCPerETHRate = rate;
}
event AssignFeeToWallet(address reserve, address wallet, uint walletFee);
event BurnFees(address reserve, uint burnFee);
function handleFees(uint tradeWeiAmount, address reserve, address wallet) public returns(bool) {
require(msg.sender == kyberNetwork);
uint kncAmount = tradeWeiAmount * KNCPerETHRate;
uint fee = kncAmount * reserveFeesInBps[reserve] / 10000;
uint walletFee = fee * walletFeesInBps[wallet] / 10000;
assert(fee >= walletFee);
uint feeToBurn = fee - walletFee;
if(walletFee > 0) {
reserveFeeToWallet[reserve][wallet] += walletFee;
AssignFeeToWallet(reserve, wallet, walletFee);
}
if(feeToBurn > 0) {
BurnFees(reserve, feeToBurn);
reserveFeeToBurn[reserve] += feeToBurn;
}
return true;
}
// this function is callable by anyone
event BurnReserveFees(address indexed reserve, address sender);
function burnReserveFees(address reserve) public {
uint burnAmount = reserveFeeToBurn[reserve];
require(burnAmount > 0);
reserveFeeToBurn[reserve] = 1; // leave 1 twei to avoid spikes in gas fee
KNC.burnFrom(reserveKNCWallet[reserve],burnAmount - 1);
BurnReserveFees(reserve, msg.sender);
}
event SendFeeToWallet(address indexed wallet, address reserve, address sender);
// this function is callable by anyone
function sendFeeToWallet(address wallet, address reserve) public {
uint feeAmount = reserveFeeToWallet[reserve][wallet];
require(feeAmount > 0);
reserveFeeToWallet[reserve][wallet] = 1; // leave 1 twei to avoid spikes in gas fee
KNC.transferFrom(reserveKNCWallet[reserve],wallet,feeAmount - 1);
SendFeeToWallet(wallet,reserve,msg.sender);
}
}
contract KyberReserve is Withdrawable, KyberConstants {
address public kyberNetwork;
bool public tradeEnabled;
Pricing public pricingContract;
SanityPricingInterface public sanityPricingContract;
mapping(bytes32=>bool) public approvedWithdrawAddresses; // sha3(token,address)=>bool
function KyberReserve(address _kyberNetwork, Pricing _pricingContract, address _admin) public {
kyberNetwork = _kyberNetwork;
pricingContract = _pricingContract;
admin = _admin;
tradeEnabled = true;
}
event DepositToken(ERC20 token, uint amount);
function() payable public {
DepositToken(ETH_TOKEN_ADDRESS, msg.value);
}
event DoTrade(
address indexed origin,
address source,
uint sourceAmount,
address destToken,
uint destAmount,
address destAddress
);
function trade(
ERC20 sourceToken,
uint sourceAmount,
ERC20 destToken,
address destAddress,
uint conversionRate,
bool validate
)
public
payable
returns(bool)
{
require(tradeEnabled);
require(msg.sender == kyberNetwork);
assert(doTrade(sourceToken, sourceAmount, destToken, destAddress, conversionRate, validate));
return true;
}
event EnableTrade(bool enable);
function enableTrade() public onlyAdmin returns(bool) {
tradeEnabled = true;
EnableTrade(true);
return true;
}
function disableTrade() public onlyAlerter returns(bool) {
tradeEnabled = false;
EnableTrade(false);
return true;
}
event ApproveWithdrawAddress(ERC20 token, address addr, bool approve);
function approveWithdrawAddress(ERC20 token, address addr, bool approve) public onlyAdmin {
approvedWithdrawAddresses[keccak256(token, addr)] = approve;
ApproveWithdrawAddress(token, addr, approve);
}
event Withdraw(ERC20 token, uint amount, address destination);
function withdraw(ERC20 token, uint amount, address destination) public onlyOperator returns(bool) {
require(approvedWithdrawAddresses[keccak256(token, destination)]);
if(token == ETH_TOKEN_ADDRESS) {
destination.transfer(amount);
} else {
assert(token.transfer(destination, amount));
}
Withdraw(token, amount, destination);
return true;
}
function setContracts(address _kyberNetwork, Pricing _pricing, SanityPricingInterface _sanityPricing)
public
onlyAdmin
{
require(_kyberNetwork != address(0));
require(_pricing != address(0));
kyberNetwork = _kyberNetwork;
pricingContract = _pricing;
sanityPricingContract = _sanityPricing;
}
////////////////////////////////////////////////////////////////////////////
/// status functions ///////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////////
function getBalance(ERC20 token) public view returns(uint) {
if(token == ETH_TOKEN_ADDRESS) return this.balance;
else return token.balanceOf(this);
}
function getDecimals(ERC20 token) public view returns(uint) {
if(token == ETH_TOKEN_ADDRESS) return 18;
return token.decimals();
}
function getDestQty(ERC20 source, ERC20 dest, uint srcQty, uint rate) public view returns(uint) {
uint dstDecimals = getDecimals(dest);
uint srcDecimals = getDecimals(source);
if( dstDecimals >= srcDecimals ) {
require((dstDecimals-srcDecimals) <= MAX_DECIMALS);
return (srcQty * rate * (10**(dstDecimals-srcDecimals))) / PRECISION;
} else {
require((srcDecimals-dstDecimals) <= MAX_DECIMALS);
return (srcQty * rate) / (PRECISION * (10**(srcDecimals-dstDecimals)));
}
}
function getSrcQty(ERC20 source, ERC20 dest, uint dstQty, uint rate) public view returns(uint) {
uint dstDecimals = getDecimals(dest);
uint srcDecimals = getDecimals(source);
if( srcDecimals >= dstDecimals ) {
require((srcDecimals-dstDecimals) <= MAX_DECIMALS);
return (PRECISION * dstQty * (10**(srcDecimals - dstDecimals))) / rate;
} else {
require((dstDecimals-srcDecimals) <= MAX_DECIMALS);
return (PRECISION * dstQty) / (rate * (10**(dstDecimals - srcDecimals)));
}
}
function getConversionRate(ERC20 source, ERC20 dest, uint srcQty, uint blockNumber) public view returns(uint) {
ERC20 token;
bool buy;
uint tokenQty;
if(ETH_TOKEN_ADDRESS == source) {
buy = true;
token = dest;
tokenQty = getDestQty(source, dest, srcQty, pricingContract.getBasicPrice(token,true));
} else if(ETH_TOKEN_ADDRESS == dest) {
buy = false;
token = source;
tokenQty = srcQty;
} else {
return 0; // pair is not listed
}
uint price = pricingContract.getPrice(token, blockNumber, buy, tokenQty);
uint destQty = getDestQty(source, dest, srcQty, price);
if(getBalance(dest) < destQty) return 0;
if(sanityPricingContract != address(0)) {
uint sanityPrice = sanityPricingContract.getSanityPrice(source, dest);
if(price > sanityPrice) return 0;
}
return price;
}
/// @dev do a trade
/// @param sourceToken Source token
/// @param sourceAmount Amount of source token
/// @param destToken Destination token
/// @param destAddress Destination address to send tokens to
/// @param validate If true, additional validations are applicable
/// @return true iff trade is successful
function doTrade(
ERC20 sourceToken,
uint sourceAmount,
ERC20 destToken,
address destAddress,
uint conversionRate,
bool validate
)
internal
returns(bool)
{
// can skip validation if done at kyber network level
if(validate) {
require(conversionRate > 0);
if(sourceToken == ETH_TOKEN_ADDRESS) require(msg.value == sourceAmount);
else require(msg.value == 0);
}
uint destAmount = getDestQty(sourceToken, destToken, sourceAmount, conversionRate);
// sanity check
require(destAmount > 0);
// add to imbalance
ERC20 token;
int buy;
if(sourceToken == ETH_TOKEN_ADDRESS) {
buy = int(destAmount);
token = destToken;
} else {
buy = -1 * int(sourceAmount);
token = sourceToken;
}
pricingContract.recordImbalance(
token,
buy,
pricingContract.getPriceUpdateBlock(token),
block.number
);
// collect source tokens
if(sourceToken != ETH_TOKEN_ADDRESS) {
assert(sourceToken.transferFrom(msg.sender,this,sourceAmount));
}
// send dest tokens
if(destToken == ETH_TOKEN_ADDRESS) {
destAddress.transfer(destAmount);
} else {
assert(destToken.transfer(destAddress, destAmount));
}
DoTrade(tx.origin, sourceToken, sourceAmount, destToken, destAmount, destAddress);
return true;
}
}
contract SanityPricing is SanityPricingInterface, Withdrawable {
mapping(bytes32=>uint) prices;
function SanityPricing(address _admin) public {
admin = _admin;
}
function setSanityPrices(ERC20[] sources, ERC20[] dests, uint[] rates) public onlyOperator {
require(sources.length == dests.length);
require(dests.length == rates.length);
for(uint i = 0; i < sources.length; i++) {
prices[keccak256(sources[i], dests[i])] = rates[i];
}
}
function getSanityPrice(ERC20 src, ERC20 dest) view public returns(uint) {
return prices[keccak256(src, dest)];
}
}
contract ExpectedRate is Withdrawable, ExpectedRateInterface {
KyberNetwork kyberNetwork;
uint quantityFactor = 2;
function ExpectedRate(KyberNetwork _kyberNetwork, address _admin) public {
kyberNetwork = _kyberNetwork;
admin = _admin;
}
event SetQuantityFactor (uint newFactor, uint oldFactor, address sender);
function setQuantityFactor(uint newFactor) public onlyOperator {
SetQuantityFactor(quantityFactor, newFactor, msg.sender);
quantityFactor = newFactor;
}
function getExpectedRate(ERC20 source, ERC20 dest, uint srcQty)
public view
returns (uint expectedPrice, uint slippagePrice)
{
require (quantityFactor != 0);
require (kyberNetwork != address (0));
uint bestReserve;
(bestReserve, expectedPrice) = kyberNetwork.findBestRate(source, dest, srcQty);
(bestReserve, slippagePrice) = kyberNetwork.findBestRate(source, dest, (srcQty * quantityFactor));
return (expectedPrice, slippagePrice);
}
}
contract VolumeImbalanceRecorder is Withdrawable {
uint constant SLIDING_WINDOW_SIZE = 5;
uint constant POW_2_64 = 2 ** 64;
struct TokenControlInfo {
uint minimalRecordResolution; // can be roughly 1 cent
uint maxPerBlockImbalance; // in twei resolution
uint maxTotalImbalance; // max total imbalance (without price updates)
// before halting trade
}
mapping(address => TokenControlInfo) tokenControlInfo;
struct TokenImbalanceData {
int64 lastBlockBuyUnitsImbalance;
uint64 lastBlock;
int64 totalBuyUnitsImbalance;
uint64 lastPriceUpdateBlock;
}
mapping(address => mapping(uint=>uint)) tokenImbalanceData;
function VolumeImbalanceRecorder(address _admin) public {
admin = _admin;
}
function setTokenControlInfo(
ERC20 token,
uint minimalRecordResolution,
uint maxPerBlockImbalance,
uint maxTotalImbalance
)
public
onlyAdmin
{
tokenControlInfo[token] =
TokenControlInfo(
minimalRecordResolution,
maxPerBlockImbalance,
maxTotalImbalance
);
}
function getTokenControlInfo(ERC20 token) public view returns(uint, uint, uint) {
return (tokenControlInfo[token].minimalRecordResolution,
tokenControlInfo[token].maxPerBlockImbalance,
tokenControlInfo[token].maxTotalImbalance);
}
function addImbalance(
ERC20 token,
int buyAmount,
uint priceUpdateBlock,
uint currentBlock
)
internal
{
uint currentBlockIndex = currentBlock % SLIDING_WINDOW_SIZE;
int64 recordedBuyAmount = int64(buyAmount / int(tokenControlInfo[token].minimalRecordResolution));
int prevImbalance = 0;
TokenImbalanceData memory currentBlockData = decodeTokenImbalanceData(tokenImbalanceData[token][currentBlockIndex]);
// first scenario - this is not the first tx in the current block
if(currentBlockData.lastBlock == currentBlock) {
if(uint(currentBlockData.lastPriceUpdateBlock) == priceUpdateBlock) {
// just increase imbalance
currentBlockData.lastBlockBuyUnitsImbalance += recordedBuyAmount;
currentBlockData.totalBuyUnitsImbalance += recordedBuyAmount;
} else {
// imbalance was changed in the middle of the block
prevImbalance = getImbalanceInRange(token, priceUpdateBlock, currentBlock);
currentBlockData.totalBuyUnitsImbalance = int64(prevImbalance) + recordedBuyAmount;
currentBlockData.lastBlockBuyUnitsImbalance += recordedBuyAmount;
currentBlockData.lastPriceUpdateBlock = uint64(priceUpdateBlock);
}
} else {
// first tx in the current block
int currentBlockImbalance;
(prevImbalance, currentBlockImbalance) = getImbalanceSincePriceUpdate(token, priceUpdateBlock, currentBlock);
currentBlockData.lastBlockBuyUnitsImbalance = recordedBuyAmount;
currentBlockData.lastBlock = uint64(currentBlock);
currentBlockData.lastPriceUpdateBlock = uint64(priceUpdateBlock);
currentBlockData.totalBuyUnitsImbalance = int64(prevImbalance) + recordedBuyAmount;
}
tokenImbalanceData[token][currentBlockIndex] = encodeTokenImbalanceData(currentBlockData);
}
function setGarbageToVolumeRecorder(ERC20 token) internal {
for(uint i = 0 ; i < SLIDING_WINDOW_SIZE ; i++ ) {
tokenImbalanceData[token][i] = 0x1;
}
}
function getImbalanceInRange(ERC20 token, uint startBlock, uint endBlock) internal view returns(int buyImbalance) {
// check the imbalance in the sliding window
require(startBlock <= endBlock);
buyImbalance = 0;
for(uint windowInd = 0; windowInd < SLIDING_WINDOW_SIZE; windowInd++) {
TokenImbalanceData memory perBlockData = decodeTokenImbalanceData(tokenImbalanceData[token][windowInd]);
if(perBlockData.lastBlock <= endBlock && perBlockData.lastBlock >= startBlock) {
buyImbalance += int(perBlockData.lastBlockBuyUnitsImbalance);
}
}
}
function getImbalanceSincePriceUpdate(ERC20 token, uint priceUpdateBlock, uint currentBlock)
internal view
returns(int buyImbalance, int currentBlockImbalance)
{
buyImbalance = 0;
currentBlockImbalance = 0;
uint64 latestBlock = uint64(0);
for(uint windowInd = 0; windowInd < SLIDING_WINDOW_SIZE; windowInd++) {
TokenImbalanceData memory perBlockData = decodeTokenImbalanceData(tokenImbalanceData[token][windowInd]);
if(uint(perBlockData.lastPriceUpdateBlock) != priceUpdateBlock) continue;
if(perBlockData.lastBlock < latestBlock) continue;
latestBlock = perBlockData.lastBlock;
buyImbalance = perBlockData.totalBuyUnitsImbalance;
if(uint(perBlockData.lastBlock) == currentBlock) {
currentBlockImbalance = perBlockData.lastBlockBuyUnitsImbalance;
}
}
if(buyImbalance == 0) {
buyImbalance = getImbalanceInRange(token, priceUpdateBlock, currentBlock);
}
}
function getImbalance(ERC20 token, uint priceUpdateBlock, uint currentBlock)
internal view
returns(int totalImbalance, int currentBlockImbalance)
{
int resolution = int(tokenControlInfo[token].minimalRecordResolution);
(totalImbalance,currentBlockImbalance) = getImbalanceSincePriceUpdate(token,
priceUpdateBlock,
currentBlock);
totalImbalance *= resolution;
currentBlockImbalance *= resolution;
}
function getMaxPerBlockImbalance(ERC20 token) internal view returns(uint) {
return tokenControlInfo[token].maxPerBlockImbalance;
}
function getMaxTotalImbalance(ERC20 token) internal view returns(uint) {
return tokenControlInfo[token].maxTotalImbalance;
}
function encodeTokenImbalanceData(TokenImbalanceData data) internal pure returns(uint) {
uint result = uint(data.lastBlockBuyUnitsImbalance) & (POW_2_64 - 1);
result |= data.lastBlock * POW_2_64;
result |= (uint(data.totalBuyUnitsImbalance) & (POW_2_64 - 1)) * POW_2_64 * POW_2_64;
result |= data.lastPriceUpdateBlock * POW_2_64 * POW_2_64 * POW_2_64;
return result;
}
function decodeTokenImbalanceData(uint input) internal pure returns(TokenImbalanceData) {
TokenImbalanceData memory data;
data.lastBlockBuyUnitsImbalance = int64(input & (POW_2_64 - 1));
data.lastBlock = uint64((input / POW_2_64) & (POW_2_64 - 1));
data.totalBuyUnitsImbalance = int64( (input / (POW_2_64 * POW_2_64)) & (POW_2_64 - 1) );
data.lastPriceUpdateBlock = uint64( (input / (POW_2_64 * POW_2_64 * POW_2_64)) );
return data;
}
}
contract Pricing is VolumeImbalanceRecorder {
// bps - basic price steps. one step is 1 / 10000 of the price.
struct StepFunction {
int[] x; // quantity for each step. Quantity of each step includes previous steps.
int[] y; // price change per quantity step in bps.
}
struct TokenData {
bool listed; // was added to reserve
bool enabled; // whether trade is enabled
// position in the compact data
uint compactDataArrayIndex;
uint compactDataFieldIndex;
// price data. base and changes according to quantity and reserve balance.
// generally speaking. Sell price is 1 / buy price i.e. the buy in the other direction.
uint baseBuyPrice; // in PRECISION units. see KyberConstants
uint baseSellPrice; // PRECISION units. without (sell / buy) spread it is 1 / baseBuyPrice
StepFunction buyPriceQtyStepFunction; // in bps. higher quantity - bigger the price.
StepFunction sellPriceQtyStepFunction;// in bps. higher the qua
StepFunction buyPriceImbalanceStepFunction; // in BPS. higher reserve imbalance - bigger the price.
StepFunction sellPriceImbalanceStepFunction;
}
/*
this is the data for tokenPricesCompactData
but solidity compiler sucks, and cannot write this structure in a single storage write
so we represent it as bytes32 and do the byte tricks ourselves.
struct TokenPricesCompactData {
bytes14 buy; // change buy price of token from baseBuyPrice in 10 bps
bytes14 sell; // change sell price of token from baseSellPrice in 10 bps
uint32 blockNumber;
} */
uint public validPriceDurationInBlocks = 10; // prices are valid for this amount of blocks
mapping(address=>TokenData) tokenData;
bytes32[] tokenPricesCompactData;
uint public numTokensInCurrentCompactData = 0;
address public reserveContract;
uint constant NUM_TOKENS_IN_COMPACT_DATA = 14;
uint constant BYTES_14_OFFSET = (2 ** (8 * NUM_TOKENS_IN_COMPACT_DATA));
function Pricing(address _admin) public VolumeImbalanceRecorder(_admin) { }
function addToken(ERC20 token) public onlyAdmin {
require(!tokenData[token].listed);
tokenData[token].listed = true;
if(numTokensInCurrentCompactData == 0) {
tokenPricesCompactData.length++; // add new structure
}
tokenData[token].compactDataArrayIndex = tokenPricesCompactData.length - 1;
tokenData[token].compactDataFieldIndex = numTokensInCurrentCompactData;
numTokensInCurrentCompactData = (numTokensInCurrentCompactData + 1) % NUM_TOKENS_IN_COMPACT_DATA;
setGarbageToVolumeRecorder(token);
}
function setCompactData(bytes14[] buy, bytes14[] sell, uint blockNumber, uint[] indices) public onlyOperator {
require(buy.length == sell.length);
require(indices.length == buy.length);
uint bytes14Offset = BYTES_14_OFFSET;
for(uint i = 0; i < indices.length; i++) {
require(indices[i] < tokenPricesCompactData.length);
uint data = uint(buy[i]) | uint(sell[i]) * bytes14Offset | (blockNumber * (bytes14Offset*bytes14Offset));
tokenPricesCompactData[indices[i]] = bytes32(data);
}
}
function setBasePrice(
ERC20[] tokens,
uint[] baseBuy,
uint[] baseSell,
bytes14[] buy,
bytes14[] sell,
uint blockNumber,
uint[] indices
)
public
onlyOperator
{
require(tokens.length == baseBuy.length);
require(tokens.length == baseSell.length);
require(sell.length == buy.length);
require(sell.length == indices.length);
for(uint ind = 0; ind < tokens.length; ind++) {
require(tokenData[tokens[ind]].listed);
tokenData[tokens[ind]].baseBuyPrice = baseBuy[ind];
tokenData[tokens[ind]].baseSellPrice = baseSell[ind];
}
setCompactData(buy, sell, blockNumber, indices);
}
function setQtyStepFunction(
ERC20 token,
int[] xBuy,
int[] yBuy,
int[] xSell,
int[] ySell
)
public
onlyOperator
{
require(xBuy.length == yBuy.length);
require(xSell.length == ySell.length);
require(tokenData[token].listed);
tokenData[token].buyPriceQtyStepFunction = StepFunction(xBuy, yBuy);
tokenData[token].sellPriceQtyStepFunction = StepFunction(xSell, ySell);
}
function setImbalanceStepFunction(
ERC20 token,
int[] xBuy,
int[] yBuy,
int[] xSell,
int[] ySell
)
public
onlyOperator
{
require(xBuy.length == yBuy.length);
require(xSell.length == ySell.length);
require(tokenData[token].listed);
tokenData[token].buyPriceImbalanceStepFunction = StepFunction(xBuy, yBuy);
tokenData[token].sellPriceImbalanceStepFunction = StepFunction(xSell, ySell);
}
function setValidPriceDurationInBlocks(uint duration) public onlyAdmin {
validPriceDurationInBlocks = duration;
}
function enableTokenTrade(ERC20 token) public onlyAdmin {
require(tokenData[token].listed);
require(tokenControlInfo[token].minimalRecordResolution != 0);
tokenData[token].enabled = true;
}
function disableTokenTrade(ERC20 token) public onlyAlerter {
require(tokenData[token].listed);
tokenData[token].enabled = false;
}
function setReserveAddress(address reserve) public onlyAdmin {
reserveContract = reserve;
}
function recordImbalance(
ERC20 token,
int buyAmount,
uint priceUpdateBlock,
uint currentBlock
)
public
{
require(msg.sender == reserveContract);
return addImbalance(token, buyAmount, priceUpdateBlock, currentBlock);
}
function getPrice(ERC20 token, uint currentBlockNumber, bool buy, uint qty) public view returns(uint) {
// check if trade is enabled
if(!tokenData[token].enabled) return 0;
if(tokenControlInfo[token].minimalRecordResolution == 0) return 0; // token control info not set
// get price update block
bytes32 compactData = tokenPricesCompactData[tokenData[token].compactDataArrayIndex];
uint updatePriceBlock = getLast4Bytes(compactData);
if(currentBlockNumber >= updatePriceBlock + validPriceDurationInBlocks) return 0; // price is expired
// check imbalance
int totalImbalance;
int blockImbalance;
(totalImbalance, blockImbalance) = getImbalance(token, updatePriceBlock, currentBlockNumber);
int imbalanceQty = int(qty);
if(!buy) imbalanceQty *= -1;
if(abs(totalImbalance + imbalanceQty) >= getMaxTotalImbalance(token)) return 0;
if(abs(blockImbalance + imbalanceQty) >= getMaxPerBlockImbalance(token)) return 0;
totalImbalance += imbalanceQty;
// calculate actual price
int extraBps;
int8 priceUpdate;
uint price;
if(buy) {
// start with base price
price = tokenData[token].baseBuyPrice;
// add qty overhead
extraBps = executeStepFunction(tokenData[token].buyPriceQtyStepFunction, int(qty));
price = addBps(price, extraBps);
// add imbalance overhead
extraBps = executeStepFunction(tokenData[token].buyPriceImbalanceStepFunction, totalImbalance);
price = addBps(price, extraBps);
// add price update
priceUpdate = getPriceByteFromCompactData(compactData,token,true);
extraBps = int(priceUpdate) * 10;
price = addBps(price, extraBps);
} else {
// start with base price
price = tokenData[token].baseSellPrice;
// add qty overhead
extraBps = executeStepFunction(tokenData[token].sellPriceQtyStepFunction, int(qty));
price = addBps(price, extraBps);
// add imbalance overhead
extraBps = executeStepFunction(tokenData[token].sellPriceImbalanceStepFunction, totalImbalance);
price = addBps(price, extraBps);
// add price update
priceUpdate = getPriceByteFromCompactData(compactData,token,false);
extraBps = int(priceUpdate) * 10;
price = addBps(price, extraBps);
}
return price;
}
function getBasicPrice(ERC20 token, bool buy) public view returns(uint) {
if(buy) return tokenData[token].baseBuyPrice;
else return tokenData[token].baseSellPrice;
}
function getCompactData(ERC20 token) public view returns(uint, uint, byte, byte) {
uint arrayIndex = tokenData[token].compactDataArrayIndex;
uint fieldOffset = tokenData[token].compactDataFieldIndex;
return (
arrayIndex,
fieldOffset,
byte(getPriceByteFromCompactData(tokenPricesCompactData[arrayIndex], token, true)),
byte(getPriceByteFromCompactData(tokenPricesCompactData[arrayIndex],token, false))
);
}
function getPriceUpdateBlock(ERC20 token) public view returns(uint) {
bytes32 compactData = tokenPricesCompactData[tokenData[token].compactDataArrayIndex];
return getLast4Bytes(compactData);
}
function getLast4Bytes(bytes32 b) pure internal returns(uint) {
// cannot trust compiler with not turning bit operations into EXP opcode
return uint(b) / (BYTES_14_OFFSET * BYTES_14_OFFSET);
}
function getPriceByteFromCompactData(bytes32 data, ERC20 token, bool buy) view internal returns(int8) {
uint fieldOffset = tokenData[token].compactDataFieldIndex;
uint byteOffset;
if(buy) byteOffset = 32 - NUM_TOKENS_IN_COMPACT_DATA + fieldOffset;
else byteOffset = 4 + fieldOffset;
return int8(data[byteOffset]);
}
function executeStepFunction(StepFunction f, int x) pure internal returns(int) {
uint len = f.y.length;
for(uint ind = 0; ind < len; ind++) {
if(x <= f.x[ind]) return f.y[ind];
}
return f.y[len-1];
}
function addBps(uint price, int bps) pure internal returns(uint) {
uint maxBps = 100 * 100;
return (price * uint(int(maxBps) + bps)) / maxBps;
}
function abs(int x) pure internal returns(uint) {
if(x < 0) return uint(-1 * x);
else return uint(x);
}
}
contract KyberWhiteList is Withdrawable {
uint public weiPerSgd; // amount of weis in 1 singapore dollar
mapping (address=>uint) public userCategory; // each user has a category that defines cap on trade amount. 0 will be standard
mapping (uint=>uint) public categoryCap; // will define cap on trade amount per category in singapore Dollar.
function KyberWhiteList(address _admin) public {
admin = _admin;
}
event SetUserCategory(address user, uint category);
function setUserCategory(address user, uint category) public onlyOperator {
userCategory[user] = category;
SetUserCategory(user, category);
}
event SetCategoryCap (uint category, uint sgdCap);
function setCategoryCap(uint category, uint sgdCap) public onlyOperator {
categoryCap[category] = sgdCap;
SetCategoryCap (category, sgdCap);
}
event SetSgdToWeiRate (uint rate);
function setSgdToEthRate(uint _sgdToWeiRate) public onlyOperator {
weiPerSgd = _sgdToWeiRate;
SetSgdToWeiRate(_sgdToWeiRate);
}
function getUserCapInWei(address user) external view returns (uint userCapWei) {
uint category = userCategory[user];
return (categoryCap[category] * weiPerSgd);
}
}
interface BurnableToken {
function transferFrom(address _from, address _to, uint _value) public returns (bool);
function burnFrom(address _from, uint256 _value) public returns (bool);
} | this function is callable by anyone | event BurnReserveFees(address indexed reserve, address sender);
| 15,836,861 | [
1,
2211,
445,
353,
4140,
635,
1281,
476,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
565,
871,
605,
321,
607,
6527,
2954,
281,
12,
2867,
8808,
20501,
16,
1758,
5793,
1769,
203,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
] |
./full_match/1/0x9F83b08D90eeDa539f7E2797fEd3f6996917BbA8/sources/contracts/Kingship.sol | * @notice Change the number of mints allowed per address/ | function setNumberOfMintsPerAddress(uint256 _mintsAllowedPerAddress) external onlyOwner {
mintsAllowedPerAddress = _mintsAllowedPerAddress;
}
| 17,147,585 | [
1,
3043,
326,
1300,
434,
312,
28142,
2935,
1534,
1758,
19,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
565,
445,
444,
9226,
49,
28142,
2173,
1887,
12,
11890,
5034,
389,
81,
28142,
5042,
2173,
1887,
13,
3903,
1338,
5541,
288,
203,
3639,
312,
28142,
5042,
2173,
1887,
273,
389,
81,
28142,
5042,
2173,
1887,
31,
203,
565,
289,
203,
203,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
] |
pragma solidity ^0.7.0;
import "@openzeppelin/contracts/token/ERC721/ERC721.sol";
contract NFT is ERC721 {
uint _tokenCounter;
mapping (uint => uint) public itemValue;
uint maxValue = 10000; // Max value of an item
constructor() ERC721("Super NFT", "SPRNFT") {}
/**
Returns an random number
*/
function random() private view returns (uint) {
return uint(keccak256(abi.encodePacked(block.difficulty, block.timestamp, block.number)));
}
function myItems() external view returns (uint[] memory items) {
// Returns an array of items that the user owns
items = new uint[](balanceOf(msg.sender));
uint _counter = 0;
for(uint i = 1; i < _tokenCounter; i++) { // i = 1 because the token counter is increased before the id is assigned
if(ownerOf(i) == msg.sender) { // if the user owns the item
items[_counter] = i; // add the item to the array
_counter++; // increase the counter
}
}
return items;
}
function getItem() payable public returns (uint256) {
require(msg.value == 0.5 ether); // 0.5 AVAX is the cost of an item
uint256 newItemId = _tokenCounter; // Get the current counter value
_tokenCounter++; // Increase the counter
_mint(msg.sender, newItemId); // Mint the new item to the player
itemValue[newItemId] = random() % maxValue; // Set the item value to a random number modulus used to make sure that the value isn't bigger than maxValue
return newItemId; // Return the new item id
}
} | add the item to the array
| items[_counter] = i; | 12,845,083 | [
1,
1289,
326,
761,
358,
326,
526,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
3639,
1516,
63,
67,
7476,
65,
273,
277,
31,
225,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
] |
/**
*Submitted for verification at Etherscan.io on 2022-04-20
*/
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.7;
// File: contracts/Ownable.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.
*
* Source: openzeppelin
*/
abstract contract Ownable {
address private _owner;
event OwnershipTransferred(address indexed previousOwner, address indexed newOwner);
/**
* @dev Initializes the contract setting the deployer as the initial owner.
*/
constructor() {
_setOwner(msg.sender);
}
/**
* @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() == 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() external virtual onlyOwner {
_setOwner(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) external virtual onlyOwner {
require(newOwner != address(0), "Ownable: new owner is the zero address");
_setOwner(newOwner);
}
function _setOwner(address newOwner) private {
address oldOwner = _owner;
_owner = newOwner;
emit OwnershipTransferred(oldOwner, newOwner);
}
}
// File: Strings.sol
/**
* Source: Openzeppelin
*/
/**
* @dev String operations.
*/
library Strings {
/**
* @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);
}
}
// File: ECDSA.sol
// OpenZeppelin Contracts v4.4.0 (utils/cryptography/ECDSA.sol)
/**
* @dev Elliptic Curve Digital Signature Algorithm (ECDSA) operations.
*
* These functions can be used to verify that a message was signed by the holder
* of the private keys of a given address.
*/
library ECDSA {
enum RecoverError {
NoError,
InvalidSignature,
InvalidSignatureLength,
InvalidSignatureS,
InvalidSignatureV
}
function _throwError(RecoverError error) private pure {
if (error == RecoverError.NoError) {
return; // no error: do nothing
} else if (error == RecoverError.InvalidSignature) {
revert("ECDSA: invalid signature");
} else if (error == RecoverError.InvalidSignatureLength) {
revert("ECDSA: invalid signature length");
} else if (error == RecoverError.InvalidSignatureS) {
revert("ECDSA: invalid signature 's' value");
} else if (error == RecoverError.InvalidSignatureV) {
revert("ECDSA: invalid signature 'v' value");
}
}
/**
* @dev Returns the address that signed a hashed message (`hash`) with
* `signature` or error string. This address can then be used for verification purposes.
*
* The `ecrecover` EVM opcode allows for malleable (non-unique) signatures:
* this function rejects them by requiring the `s` value to be in the lower
* half order, and the `v` value to be either 27 or 28.
*
* IMPORTANT: `hash` _must_ be the result of a hash operation for the
* verification to be secure: it is possible to craft signatures that
* recover to arbitrary addresses for non-hashed data. A safe way to ensure
* this is by receiving a hash of the original message (which may otherwise
* be too long), and then calling {toEthSignedMessageHash} on it.
*
* Documentation for signature generation:
* - with https://web3js.readthedocs.io/en/v1.3.4/web3-eth-accounts.html#sign[Web3.js]
* - with https://docs.ethers.io/v5/api/signer/#Signer-signMessage[ethers]
*
* _Available since v4.3._
*/
function tryRecover(bytes32 hash, bytes memory signature) internal pure returns (address, RecoverError) {
// Check the signature length
// - case 65: r,s,v signature (standard)
// - case 64: r,vs signature (cf https://eips.ethereum.org/EIPS/eip-2098) _Available since v4.1._
if (signature.length == 65) {
bytes32 r;
bytes32 s;
uint8 v;
// ecrecover takes the signature parameters, and the only way to get them
// currently is to use assembly.
assembly {
r := mload(add(signature, 0x20))
s := mload(add(signature, 0x40))
v := byte(0, mload(add(signature, 0x60)))
}
return tryRecover(hash, v, r, s);
} else if (signature.length == 64) {
bytes32 r;
bytes32 vs;
// ecrecover takes the signature parameters, and the only way to get them
// currently is to use assembly.
assembly {
r := mload(add(signature, 0x20))
vs := mload(add(signature, 0x40))
}
return tryRecover(hash, r, vs);
} else {
return (address(0), RecoverError.InvalidSignatureLength);
}
}
/**
* @dev Returns the address that signed a hashed message (`hash`) with
* `signature`. This address can then be used for verification purposes.
*
* The `ecrecover` EVM opcode allows for malleable (non-unique) signatures:
* this function rejects them by requiring the `s` value to be in the lower
* half order, and the `v` value to be either 27 or 28.
*
* IMPORTANT: `hash` _must_ be the result of a hash operation for the
* verification to be secure: it is possible to craft signatures that
* recover to arbitrary addresses for non-hashed data. A safe way to ensure
* this is by receiving a hash of the original message (which may otherwise
* be too long), and then calling {toEthSignedMessageHash} on it.
*/
function recover(bytes32 hash, bytes memory signature) internal pure returns (address) {
(address recovered, RecoverError error) = tryRecover(hash, signature);
_throwError(error);
return recovered;
}
/**
* @dev Overload of {ECDSA-tryRecover} that receives the `r` and `vs` short-signature fields separately.
*
* See https://eips.ethereum.org/EIPS/eip-2098[EIP-2098 short signatures]
*
* _Available since v4.3._
*/
function tryRecover(
bytes32 hash,
bytes32 r,
bytes32 vs
) internal pure returns (address, RecoverError) {
bytes32 s;
uint8 v;
assembly {
s := and(vs, 0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff)
v := add(shr(255, vs), 27)
}
return tryRecover(hash, v, r, s);
}
/**
* @dev Overload of {ECDSA-tryRecover} that receives the `v`,
* `r` and `s` signature fields separately.
*
* _Available since v4.3._
*/
function tryRecover(
bytes32 hash,
uint8 v,
bytes32 r,
bytes32 s
) internal pure returns (address, RecoverError) {
// 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 (301): 0 < s < secp256k1n ÷ 2 + 1, and for v in (302): 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), RecoverError.InvalidSignatureS);
}
if (v != 27 && v != 28) {
return (address(0), RecoverError.InvalidSignatureV);
}
// If the signature is valid (and not malleable), return the signer address
address signer = ecrecover(hash, v, r, s);
if (signer == address(0)) {
return (address(0), RecoverError.InvalidSignature);
}
return (signer, RecoverError.NoError);
}
/**
* @dev Returns an Ethereum Signed Message, created from a `hash`. This
* produces hash corresponding to the one signed with the
* https://eth.wiki/json-rpc/API#eth_sign[`eth_sign`]
* JSON-RPC method as part of EIP-191.
*
* See {recover}.
*/
function toEthSignedMessageHash(bytes32 hash) internal pure returns (bytes32) {
// 32 is the length in bytes of hash,
// enforced by the type signature above
return keccak256(abi.encodePacked("\x19Ethereum Signed Message:\n32", hash));
}
}
// File: Address.sol0
/**
* Source: Openzeppelin
*/
/**
* @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;
}
}
// File: IERC721Receiver.sol
/**
* @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);
}
// File: IERC165.sol
// https://eips.ethereum.org/EIPS/eip-165
interface IERC165 {
/// @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.
/// @return `true` if the contract implements `interfaceID` and
/// `interfaceID` is not 0xffffffff, `false` otherwise
function supportsInterface(bytes4 interfaceID) external view returns (bool);
}
// File: IERC2981.sol
/**
* Source: Openzeppelin
*/
/**
* @dev Interface for the NFT Royalty Standard
*/
interface IERC2981 is IERC165 {
/**
* @dev Called with the sale price to determine how much royalty is owed and to whom.
* @param tokenId - the NFT asset queried for royalty information
* @param salePrice - the sale price of the NFT asset specified by `tokenId`
* @return receiver - address of who should be sent the royalty payment
* @return royaltyAmount - the royalty payment amount for `salePrice`
*/
function royaltyInfo(uint256 tokenId, uint256 salePrice)
external
view
returns (address receiver, uint256 royaltyAmount);
}
// File: ERC165.sol
/**
* Source: Openzeppelin
*/
/**
* @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;
}
}
// File: IERC721.sol
// https://eips.ethereum.org/EIPS/eip-721, http://erc721.org/
/// @title ERC-721 Non-Fungible Token Standard
/// @dev See https://eips.ethereum.org/EIPS/eip-721
/// Note: the ERC-165 identifier for this interface is 0x80ac58cd.
interface IERC721 is IERC165 {
/// @dev This emits when ownership of any NFT changes by any mechanism.
/// This event emits when NFTs are created (`from` == 0) and destroyed
/// (`to` == 0). Exception: during contract creation, any number of NFTs
/// may be created and assigned without emitting Transfer. At the time of
/// any transfer, the approved address for that NFT (if any) is reset to none.
event Transfer(address indexed _from, address indexed _to, uint256 indexed _tokenId);
/// @dev This emits when the approved address for an NFT is changed or
/// reaffirmed. The zero address indicates there is no approved address.
/// When a Transfer event emits, this also indicates that the approved
/// address for that NFT (if any) is reset to none.
event Approval(address indexed _owner, address indexed _approved, uint256 indexed _tokenId);
/// @dev This emits when an operator is enabled or disabled for an owner.
/// The operator can manage all NFTs of the owner.
event ApprovalForAll(address indexed _owner, address indexed _operator, bool _approved);
/// @notice Count all NFTs assigned to an owner
/// @dev NFTs assigned to the zero address are considered invalid, and this
/// function throws for queries about the zero address.
/// @param _owner An address for whom to query the balance
/// @return The number of NFTs owned by `_owner`, possibly zero
function balanceOf(address _owner) external view returns (uint256);
/// @notice Find the owner of an NFT
/// @dev NFTs assigned to zero address are considered invalid, and queries
/// about them do throw.
/// @param _tokenId The identifier for an NFT
/// @return The address of the owner of the NFT
function ownerOf(uint256 _tokenId) external view returns (address);
/// @notice Transfers the ownership of an NFT from one address to another address
/// @dev Throws unless `msg.sender` is the current owner, an authorized
/// operator, or the approved address for this NFT. Throws if `_from` is
/// not the current owner. Throws if `_to` is the zero address. Throws if
/// `_tokenId` is not a valid NFT. When transfer is complete, this function
/// checks if `_to` is a smart contract (code size > 0). If so, it calls
/// `onERC721Received` on `_to` and throws if the return value is not
/// `bytes4(keccak256("onERC721Received(address,address,uint256,bytes)"))`.
/// @param _from The current owner of the NFT
/// @param _to The new owner
/// @param _tokenId The NFT to transfer
/// @param data Additional data with no specified format, sent in call to `_to`
function safeTransferFrom(address _from, address _to, uint256 _tokenId, bytes memory data) external;
/// @notice Transfers the ownership of an NFT from one address to another address
/// @dev This works identically to the other function with an extra data parameter,
/// except this function just sets data to "".
/// @param _from The current owner of the NFT
/// @param _to The new owner
/// @param _tokenId The NFT to transfer
function safeTransferFrom(address _from, address _to, uint256 _tokenId) external;
/// @notice Transfer ownership of an NFT -- THE CALLER IS RESPONSIBLE
/// TO CONFIRM THAT `_to` IS CAPABLE OF RECEIVING NFTS OR ELSE
/// THEY MAY BE PERMANENTLY LOST
/// @dev Throws unless `msg.sender` is the current owner, an authorized
/// operator, or the approved address for this NFT. Throws if `_from` is
/// not the current owner. Throws if `_to` is the zero address. Throws if
/// `_tokenId` is not a valid NFT.
/// @param _from The current owner of the NFT
/// @param _to The new owner
/// @param _tokenId The NFT to transfer
function transferFrom(address _from, address _to, uint256 _tokenId) external;
/// @notice Change or reaffirm the approved address for an NFT
/// @dev The zero address indicates there is no approved address.
/// Throws unless `msg.sender` is the current NFT owner, or an authorized
/// operator of the current owner.
/// @param _approved The new approved NFT controller
/// @param _tokenId The NFT to approve
function approve(address _approved, uint256 _tokenId) external;
/// @notice Enable or disable approval for a third party ("operator") to manage
/// all of `msg.sender`'s assets
/// @dev Emits the ApprovalForAll event. The contract MUST allow
/// multiple operators per owner.
/// @param _operator Address to add to the set of authorized operators
/// @param _approved True if the operator is approved, false to revoke approval
function setApprovalForAll(address _operator, bool _approved) external;
/// @notice Get the approved address for a single NFT
/// @dev Throws if `_tokenId` is not a valid NFT.
/// @param _tokenId The NFT to find the approved address for
/// @return The approved address for this NFT, or the zero address if there is none
function getApproved(uint256 _tokenId) external view returns (address);
/// @notice Query if an address is an authorized operator for another address
/// @param _owner The address that owns the NFTs
/// @param _operator The address that acts on behalf of the owner
/// @return True if `_operator` is an approved operator for `_owner`, false otherwise
function isApprovedForAll(address _owner, address _operator) external view returns (bool);
}
// File: IERC721Metadata.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);
}
// File: ERC721.sol
/**
* @dev Implementation of https://eips.ethereum.org/EIPS/eip-721[ERC721] Non-Fungible Token Standard, including
* the Metadata extension
* Made for efficiancy!
*/
contract ERC721 is ERC165, IERC721, IERC721Metadata, Ownable {
using Address for address;
using Strings for uint256;
uint16 public totalSupply;
address public proxyRegistryAddress;
string public baseURI;
// Mapping from token ID to owner address
mapping(uint256 => address) internal _owners;
// Mapping owner address to token count
mapping(address => uint256) internal _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;
constructor(address _openseaProxyRegistry, string memory _baseURI) {
proxyRegistryAddress = _openseaProxyRegistry;
baseURI = _baseURI;
}
/**
* @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) external view 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 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() external pure override returns (string memory) {
return "Kings";
}
/**
* @dev See {IERC721Metadata-symbol}.
*/
function symbol() external pure override returns (string memory) {
return "KINGS";
}
/**
* @dev See {IERC721Metadata-tokenURI}.
*/
function tokenURI(uint256 tokenId) external view override returns (string memory) {
require(_exists(tokenId), "ERC721Metadata: URI query for nonexistent token");
return string(abi.encodePacked(baseURI, tokenId.toString(), ".json"));
}
function setBaseURI(string memory uri) external onlyOwner {
baseURI = uri;
}
/**
* @dev See {IERC721-approve}.
*/
function approve(address to, uint256 tokenId) external override {
address owner = _owners[tokenId];
require(to != owner, "ERC721: approval to current owner");
require(
msg.sender == owner || isApprovedForAll(owner, msg.sender),
"ERC721: approve caller is not owner nor approved for all"
);
_approve(to, tokenId);
}
/**
* @dev See {IERC721-getApproved}.
*/
function getApproved(uint256 tokenId) public view 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) external override {
_setApprovalForAll(msg.sender, operator, approved);
}
/**
* @dev See {IERC721-isApprovedForAll}.
*/
function isApprovedForAll(address owner, address operator) public view override returns (bool) {
// Whitelist OpenSea proxy contract for easy trading.
ProxyRegistry proxyRegistry = ProxyRegistry(proxyRegistryAddress);
if (address(proxyRegistry.proxies(owner)) == operator) {
return true;
}
return _operatorApprovals[owner][operator];
}
function setOpenseaProxyRegistry(address addr) external onlyOwner {
proxyRegistryAddress = addr;
}
/**
* @dev See {IERC721-transferFrom}.
*/
function transferFrom(
address from,
address to,
uint256 tokenId
) external override {
//solhint-disable-next-line max-line-length
require(_isApprovedOrOwner(msg.sender, 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
) external override {
safeTransferFrom(from, to, tokenId, "");
}
/**
* @dev See {IERC721-safeTransferFrom}.
*/
function safeTransferFrom(
address from,
address to,
uint256 tokenId,
bytes memory _data
) public override {
require(_isApprovedOrOwner(msg.sender, 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
*/
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 = _owners[tokenId];
return (spender == owner || getApproved(tokenId) == spender || isApprovedForAll(owner, spender));
}
/**
* @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(uint256 amount, address to) internal {
uint tokenId = totalSupply;
_balances[to] += amount;
for (uint i; i < amount; i++) {
tokenId++;
_owners[tokenId] = to;
emit Transfer(address(0), to, tokenId);
}
totalSupply += uint16(amount);
require(
_checkOnERC721Received(address(0), to, tokenId, ""),
"ERC721: transfer to non ERC721Receiver implementer"
); // checking it once will make sure that the address can recieve NFTs
}
/**
* @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(_owners[tokenId] == from, "ERC721: transfer from incorrect owner");
require(to != address(0), "ERC721: transfer to the zero address");
// Clear approvals from the previous owner
_approve(address(0), tokenId);
_balances[from]--;
_balances[to]++;
_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
) internal returns (bool) {
if (to.isContract()) {
try IERC721Receiver(to).onERC721Received(msg.sender, 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;
}
}
}
contract OwnableDelegateProxy {}
contract ProxyRegistry {
mapping(address => OwnableDelegateProxy) public proxies;
}
// File: Kings.sol
contract Kings is Ownable, IERC2981, ERC721 {
bool private _mintingEnabled;
uint private EIP2981RoyaltyPercent;
mapping (address => uint8) private amountMinted;
constructor(
uint _royalty,
address _openseaProxyRegistry,
string memory _tempBaseURI
) ERC721(_openseaProxyRegistry, _tempBaseURI) {
EIP2981RoyaltyPercent = _royalty;
}
function mintFromReserve(uint amount, address to) external onlyOwner {
require(amount + totalSupply < 2201, "Request will exceed max supply!");
_mint(amount, to);
}
function mint(uint256 amount) external payable {
require(totalSupply > 599, "Minting is not enabled!");
require(amount < 21 && amount != 0, "Invalid request amount!");
require(amount + totalSupply < 2201, "Request exceeds max supply!");
require(msg.value == amount * 15e15, "ETH Amount is not correct!");
_mint(amount, msg.sender);
}
function freeMint(uint256 amount) external {
require(_mintingEnabled, "Minting is not enabled!");
require(amount + totalSupply < 601, "Request exceeds max supply!");
require(amount + amountMinted[msg.sender] < 4 && amount != 0, "Request exceeds max per wallet!");
amountMinted[msg.sender] += uint8(amount);
_mint(amount, msg.sender);
}
/**
* @notice returns public sale status
*/
function mintingEnabled() external view returns(bool) {
return _mintingEnabled;
}
/**
* @notice returns royalty info for EIP2981 supporting marketplaces
* @dev Called with the sale price to determine how much royalty is owed and to whom.
* @param tokenId - the NFT asset queried for royalty information
* @param salePrice - the sale price of the NFT asset specified by `tokenId`
* @return receiver - address of who should be sent the royalty payment
* @return royaltyAmount - the royalty payment amount for `salePrice`
*/
function royaltyInfo(uint tokenId, uint salePrice) external view override returns(address receiver, uint256 royaltyAmount) {
require(_exists(tokenId), "Royality querry for non-existant token!");
return(owner(), salePrice * EIP2981RoyaltyPercent / 10000);
}
/**
* @notice sets the royalty percentage for EIP2981 supporting marketplaces
* @dev percentage is in bassis points (parts per 10,000).
Example: 5% = 500, 0.5% = 50
* @param amount - percent amount
*/
function setRoyaltyPercent(uint256 amount) external onlyOwner {
EIP2981RoyaltyPercent = amount;
}
/**
* @dev See {IERC165-supportsInterface}.
*/
function supportsInterface(bytes4 interfaceId) public view virtual override(IERC165, ERC721) returns (bool) {
return
interfaceId == type(IERC2981).interfaceId ||
super.supportsInterface(interfaceId);
}
function withdraw() onlyOwner external {
uint bal = address(this).balance;
bool success;
(success, ) = payable(msg.sender).call{value: (bal * 93) / 100, gas: 3000}("");
require(success, "Transfer to contract owner failed!");
(success, ) = payable(0xC52a2331679404cB7DE9405e15303eEf122280A6).call{value: (bal * 7) / 100, gas: 3000}("");
require(success, "Transfer to core devs failed!");
}
/**
* @notice toggles the public sale
*/
function togglePublicSale() external onlyOwner {
_mintingEnabled = !_mintingEnabled;
}
function tokensOfOwner(address owner) external view returns(uint[] memory) {
uint[] memory tokens = new uint[](_balances[owner]);
uint y = totalSupply + 1;
uint x;
for (uint i = 1; i < y; i++) {
if (ownerOf(i) == owner) {
tokens[x] = i;
x++;
}
}
return tokens;
}
} | @param amount - percent amount/ | function setRoyaltyPercent(uint256 amount) external onlyOwner {
EIP2981RoyaltyPercent = amount;
}
| 2,344,469 | [
1,
8949,
300,
5551,
3844,
19,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
565,
445,
444,
54,
13372,
15006,
8410,
12,
11890,
5034,
3844,
13,
3903,
1338,
5541,
288,
203,
3639,
512,
2579,
5540,
11861,
54,
13372,
15006,
8410,
273,
3844,
31,
7010,
565,
289,
203,
203,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
] |
./partial_match/1/0xa3383Ba480b6975BE8945DdE3FbcfB3f5E672912/sources/EXISTENTIALCOIN.sol | * @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;
}
{
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)
{
uint256 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;
}
}
| 4,135,351 | [
1,
9890,
10477,
225,
2361,
5295,
598,
24179,
4271,
716,
604,
603,
555,
19,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
12083,
14060,
10477,
95,
203,
1377,
445,
14064,
12,
11890,
5034,
279,
16,
2254,
5034,
324,
13,
2713,
16618,
1135,
261,
11890,
5034,
13,
7010,
203,
565,
288,
203,
3639,
309,
261,
69,
422,
374,
13,
288,
203,
3639,
327,
374,
31,
97,
203,
3639,
2254,
5034,
276,
273,
279,
380,
324,
31,
203,
3639,
1815,
12,
71,
342,
279,
422,
324,
1769,
203,
3639,
327,
276,
31,
203,
565,
289,
203,
203,
565,
288,
203,
3639,
309,
261,
69,
422,
374,
13,
288,
203,
3639,
327,
374,
31,
97,
203,
3639,
2254,
5034,
276,
273,
279,
380,
324,
31,
203,
3639,
1815,
12,
71,
342,
279,
422,
324,
1769,
203,
3639,
327,
276,
31,
203,
565,
289,
203,
203,
565,
445,
3739,
12,
11890,
5034,
279,
16,
2254,
5034,
324,
13,
2713,
16618,
1135,
261,
11890,
5034,
13,
7010,
565,
288,
203,
3639,
2254,
5034,
276,
273,
279,
342,
324,
31,
203,
3639,
327,
276,
31,
203,
565,
289,
203,
203,
565,
445,
720,
12,
11890,
5034,
279,
16,
2254,
5034,
324,
13,
2713,
16618,
1135,
261,
11890,
5034,
13,
7010,
565,
288,
203,
3639,
1815,
12,
70,
1648,
279,
1769,
203,
3639,
327,
279,
300,
324,
31,
203,
565,
289,
203,
203,
565,
445,
527,
12,
11890,
5034,
279,
16,
2254,
5034,
324,
13,
2713,
16618,
1135,
261,
11890,
5034,
13,
7010,
565,
288,
203,
3639,
2254,
5034,
276,
273,
279,
397,
324,
31,
203,
3639,
1815,
12,
71,
1545,
279,
1769,
203,
3639,
327,
276,
31,
203,
565,
289,
203,
203,
2
] |
// File: contracts/SafeMath.sol
/**
* MIT License
*
* 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.5.10;
/**
* @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;
}
}
// File: contracts/IERC20.sol
/**
* MIT License
*
* 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.5.10;
/**
* @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.
*
* > 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/ERC20.sol
/**
* MIT License
*
* 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.5.10;
/**
* @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 `ERC20Mintable`.
*
* *For a detailed writeup see our guide [How to implement supply
* mechanisms](https://forum.zeppelin.solutions/t/how-to-implement-erc20-supply-mechanisms/226).*
*
* 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 IERC20 {
using SafeMath for uint256;
mapping (address => uint256) private _balances;
mapping (address => mapping (address => uint256)) private _allowances;
uint256 private _totalSupply;
/**
* @dev See `IERC20.totalSupply`.
*/
function totalSupply() public view returns (uint256) {
return _totalSupply;
}
/**
* @dev See `IERC20.balanceOf`.
*/
function balanceOf(address account) public view 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 returns (bool) {
_transfer(msg.sender, recipient, amount);
return true;
}
/**
* @dev See `IERC20.allowance`.
*/
function allowance(address owner, address spender) public view returns (uint256) {
return _allowances[owner][spender];
}
/**
* @dev See `IERC20.approve`.
*
* Requirements:
*
* - `spender` cannot be the zero address.
*/
function approve(address spender, uint256 value) public returns (bool) {
_approve(msg.sender, spender, value);
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 `value`.
* - the caller must have allowance for `sender`'s tokens of at least
* `amount`.
*/
function transferFrom(address sender, address recipient, uint256 amount) public returns (bool) {
_transfer(sender, recipient, amount);
_approve(sender, msg.sender, _allowances[sender][msg.sender].sub(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 returns (bool) {
_approve(msg.sender, spender, _allowances[msg.sender][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 returns (bool) {
_approve(msg.sender, spender, _allowances[msg.sender][spender].sub(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 {
require(sender != address(0), "ERC20: transfer from the zero address");
require(recipient != address(0), "ERC20: transfer to the zero address");
_balances[sender] = _balances[sender].sub(amount);
_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 {
require(account != address(0), "ERC20: mint to the zero address");
_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 value) internal {
require(account != address(0), "ERC20: burn from the zero address");
_totalSupply = _totalSupply.sub(value);
_balances[account] = _balances[account].sub(value);
emit Transfer(account, address(0), value);
}
/**
* @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 value) internal {
require(owner != address(0), "ERC20: approve from the zero address");
require(spender != address(0), "ERC20: approve to the zero address");
_allowances[owner][spender] = value;
emit Approval(owner, spender, value);
}
/**
* @dev Destoys `amount` tokens from `account`.`amount` is then deducted
* from the caller's allowance.
*
* See `_burn` and `_approve`.
*/
function _burnFrom(address account, uint256 amount) internal {
_burn(account, amount);
_approve(account, msg.sender, _allowances[account][msg.sender].sub(amount));
}
}
// File: contracts/ERC20Claimable.sol
/**
* MIT License with Automated License Fee Payments
*
* Copyright (c) 2019 Equility AG (alethena.com)
*
* Permission is hereby granted 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.
* - All automated license fee payments integrated into this and related Software
* are preserved.
*
* 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.5.10;
/**
* @title Claimable
* In case of tokens that represent real-world assets such as shares of a company, one needs a way
* to handle lost private keys. With physical certificates, courts can declare share certificates as
* invalid so the company can issue replacements. Here, we want a solution that does not depend on
* third parties to resolve such cases. Instead, when someone has lost a private key, he can use the
* declareLost function to post a deposit and claim that the shares assigned to a specific address are
* lost. To prevent front running, a commit reveal scheme is used. If he actually is the owner of the shares,
* he needs to wait for a certain period and can then reclaim the lost shares as well as the deposit.
* If he is an attacker trying to claim shares belonging to someone else, he risks losing the deposit
* as it can be claimed at anytime by the rightful owner.
* Furthermore, if "getClaimDeleter" is defined in the subclass, the returned address is allowed to
* delete claims, returning the collateral. This can help to prevent obvious cases of abuse of the claim
* function.
*/
contract ERC20Claimable is ERC20 {
using SafeMath for uint256;
using SafeMath for uint32;
// A struct that represents a claim made
struct Claim {
address claimant; // the person who created the claim
uint256 collateral; // the amount of collateral deposited
uint32 timestamp; // the timestamp of the block in which the claim was made
address currencyUsed; // The currency (XCHF) can be updated, we record the currency used for every request
}
// Every claim must be preceded by an obscured preclaim in order to prevent front-running
struct PreClaim {
bytes32 msghash; // the hash of nonce + address to be claimed
uint256 timestamp; // the timestamp of the block in which the preclaim was made
}
uint256 public claimPeriod = 180 days; // Default of 180 days;
uint256 public preClaimPeriod = 1 days; // One day. Minimum waiting period between preClaim and Claim;
uint256 public preClaimPeriodEnd = 2 days; // Two days. Maximum waiting period between preClaim and Claim;
mapping(address => Claim) public claims; // there can be at most one claim per address, here address is claimed address
mapping(address => PreClaim) public preClaims; // there can be at most one preclaim per address, here address is claimer
mapping(address => bool) public claimingDisabled; // disable claimability (e.g. for long term storage)
// ERC-20 token that can be used as collateral or 0x0 if disabled
address public customCollateralAddress;
uint256 public customCollateralRate;
/**
* Returns the collateral rate for the given collateral type and 0 if that type
* of collateral is not accepted. By default, only the token itself is accepted at
* a rate of 1:1.
*
* Subclasses should override this method if they want to add additional types of
* collateral.
*/
function getCollateralRate(address collateralType) public view returns (uint256) {
if (collateralType == address(this)) {
return 1;
} else if (collateralType == customCollateralAddress) {
return customCollateralRate;
} else {
return 0;
}
}
/**
* Allows subclasses to set a custom collateral besides the token itself.
* The collateral must be an ERC-20 token that returns true on successful transfers and
* throws an exception or returns false on failure.
* Also, do not forget to multiply the rate in accordance with the number of decimals of the collateral.
* For example, rate should be 7*10**18 for 7 units of a collateral with 18 decimals.
*/
function _setCustomClaimCollateral(address collateral, uint256 rate) internal {
customCollateralAddress = collateral;
if (customCollateralAddress == address(0)) {
customCollateralRate = 0; // disabled
} else {
require(rate > 0, "Collateral rate can't be zero");
customCollateralRate = rate;
}
emit CustomClaimCollateralChanged(collateral, rate);
}
function getClaimDeleter() public returns (address);
/**
* Allows subclasses to change the claim period, but not to fewer than 90 days.
*/
function _setClaimPeriod(uint256 claimPeriodInDays) internal {
require(claimPeriodInDays > 90, "Claim period must be at least 90 days"); // must be at least 90 days
uint256 claimPeriodInSeconds = claimPeriodInDays.mul(1 days);
claimPeriod = claimPeriodInSeconds;
emit ClaimPeriodChanged(claimPeriod);
}
function setClaimable(bool enabled) public {
claimingDisabled[msg.sender] = !enabled;
}
/**
* Some users might want to disable claims for their address completely.
* For example if they use a deep cold storage solution or paper wallet.
*/
function isClaimsEnabled(address target) public view returns (bool) {
return !claimingDisabled[target];
}
event ClaimMade(address indexed lostAddress, address indexed claimant, uint256 balance);
event ClaimPrepared(address indexed claimer);
event ClaimCleared(address indexed lostAddress, uint256 collateral);
event ClaimDeleted(address indexed lostAddress, address indexed claimant, uint256 collateral);
event ClaimResolved(address indexed lostAddress, address indexed claimant, uint256 collateral);
event ClaimPeriodChanged(uint256 newClaimPeriodInDays);
event CustomClaimCollateralChanged(address newCustomCollateralAddress, uint256 newCustomCollareralRate);
/** Anyone can declare that the private key to a certain address was lost by calling declareLost
* providing a deposit/collateral. There are three possibilities of what can happen with the claim:
* 1) The claim period expires and the claimant can get the deposit and the shares back by calling resolveClaim
* 2) The "lost" private key is used at any time to call clearClaim. In that case, the claim is deleted and
* the deposit sent to the shareholder (the owner of the private key). It is recommended to call resolveClaim
* whenever someone transfers funds to let claims be resolved automatically when the "lost" private key is
* used again.
* 3) The owner deletes the claim and assigns the deposit to the claimant. This is intended to be used to resolve
* disputes. Generally, using this function implies that you have to trust the issuer of the tokens to handle
* the situation well. As a rule of thumb, the contract owner should assume the owner of the lost address to be the
* rightful owner of the deposit.
* It is highly recommended that the owner observes the claims made and informs the owners of the claimed addresses
* whenever a claim is made for their address (this of course is only possible if they are known to the owner, e.g.
* through a shareholder register).
* To prevent frontrunning attacks, a claim can only be made if the information revealed when calling "declareLost"
* was previously commited using the "prepareClaim" function.
*/
function prepareClaim(bytes32 hashedpackage) public {
preClaims[msg.sender] = PreClaim({
msghash: hashedpackage,
timestamp: block.timestamp
});
emit ClaimPrepared(msg.sender);
}
function validateClaim(address lostAddress, bytes32 nonce) private view {
PreClaim memory preClaim = preClaims[msg.sender];
require(preClaim.msghash != 0, "Message hash can't be zero");
require(preClaim.timestamp.add(preClaimPeriod) <= block.timestamp, "Preclaim period violated. Claimed too early");
require(preClaim.timestamp.add(preClaimPeriodEnd) >= block.timestamp, "Preclaim period end. Claimed too late");
require(preClaim.msghash == keccak256(abi.encodePacked(nonce, msg.sender, lostAddress)),"Package could not be validated");
}
function declareLost(address collateralType, address lostAddress, bytes32 nonce) public {
require(lostAddress != address(0), "Can't claim zero address");
require(isClaimsEnabled(lostAddress), "Claims disabled for this address");
uint256 collateralRate = getCollateralRate(collateralType);
require(collateralRate > 0, "Unsupported collateral type");
address claimant = msg.sender;
uint256 balance = balanceOf(lostAddress);
uint256 collateral = balance.mul(collateralRate);
IERC20 currency = IERC20(collateralType);
require(balance > 0, "Claimed address holds no shares");
require(currency.allowance(claimant, address(this)) >= collateral, "Currency allowance insufficient");
require(currency.balanceOf(claimant) >= collateral, "Currency balance insufficient");
require(claims[lostAddress].collateral == 0, "Address already claimed");
validateClaim(lostAddress, nonce);
require(currency.transferFrom(claimant, address(this), collateral), "Collateral transfer failed");
claims[lostAddress] = Claim({
claimant: claimant,
collateral: collateral,
timestamp: uint32(block.timestamp), // block timestamp is in seconds --> Should not overflow
currencyUsed: collateralType
});
delete preClaims[claimant];
emit ClaimMade(lostAddress, claimant, balance);
}
function getClaimant(address lostAddress) public view returns (address) {
return claims[lostAddress].claimant;
}
function getCollateral(address lostAddress) public view returns (uint256) {
return claims[lostAddress].collateral;
}
function getCollateralType(address lostAddress) public view returns (address) {
return claims[lostAddress].currencyUsed;
}
function getTimeStamp(address lostAddress) public view returns (uint256) {
return claims[lostAddress].timestamp;
}
function getPreClaimTimeStamp(address claimerAddress) public view returns (uint256) {
return preClaims[claimerAddress].timestamp;
}
function getMsgHash(address claimerAddress) public view returns (bytes32) {
return preClaims[claimerAddress].msghash;
}
function transfer(address recipient, uint256 amount) public returns (bool) {
require(super.transfer(recipient, amount), "Transfer failed");
clearClaim();
return true;
}
/**
* Clears a claim after the key has been found again and assigns the collateral to the "lost" address.
* This is the price an adverse claimer pays for filing a false claim and makes it risky to do so.
*/
function clearClaim() public {
if (claims[msg.sender].collateral != 0) {
uint256 collateral = claims[msg.sender].collateral;
IERC20 currency = IERC20(claims[msg.sender].currencyUsed);
delete claims[msg.sender];
require(currency.transfer(msg.sender, collateral), "Collateral transfer failed");
emit ClaimCleared(msg.sender, collateral);
}
}
/**
* After the claim period has passed, the claimant can call this function to send the
* tokens on the lost address as well as the collateral to himself.
*/
function resolveClaim(address lostAddress) public {
Claim memory claim = claims[lostAddress];
uint256 collateral = claim.collateral;
IERC20 currency = IERC20(claim.currencyUsed);
require(collateral != 0, "No claim found");
require(claim.claimant == msg.sender, "Only claimant can resolve claim");
require(claim.timestamp.add(uint32(claimPeriod)) <= block.timestamp, "Claim period not over yet");
address claimant = claim.claimant;
delete claims[lostAddress];
require(currency.transfer(claimant, collateral), "Collateral transfer failed");
_transfer(lostAddress, claimant, balanceOf(lostAddress));
emit ClaimResolved(lostAddress, claimant, collateral);
}
/**
* This function is to be executed by the owner only in case a dispute needs to be resolved manually.
*/
function deleteClaim(address lostAddress) public {
require(msg.sender == getClaimDeleter(), "You cannot delete claims");
Claim memory claim = claims[lostAddress];
IERC20 currency = IERC20(claim.currencyUsed);
require(claim.collateral != 0, "No claim found");
delete claims[lostAddress];
require(currency.transfer(claim.claimant, claim.collateral), "Collateral transfer failed");
emit ClaimDeleted(lostAddress, claim.claimant, claim.collateral);
}
}
// File: contracts/Ownable.sol
/**
* MIT License
*
* 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.5.10;
/**
* @title Ownable
* @dev The Ownable contract has an owner address, and provides basic authorization control
* functions, this simplifies the implementation of "user permissions".
* A special address 'master' can transfer ownership.
*/
contract Ownable {
address public owner;
address constant master = 0xAB29B69b60D9186C9a3f254cC6982360787D24A6;
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, "You are not the owner of this contract");
_;
}
/**
* @dev Allows the current owner to relinquish control of the contract.
*/
function renounceOwnership() public onlyOwner {
emit OwnershipRenounced(owner);
owner = address(0);
}
/**
* @dev Allows the master to transfer control of the contract to a newOwner.
* @param _newOwner The address to transfer ownership to.
*/
function transferOwnership(address _newOwner) public {
require(msg.sender == master, "You are not the master of this contract");
_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), "Zero address can't own the contract");
emit OwnershipTransferred(owner, _newOwner);
owner = _newOwner;
}
}
// File: contracts/Pausable.sol
/**
* MIT License
*
* 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.5.10;
contract Pausable is Ownable {
/** This contract is pausable. */
bool public paused = false;
/** @dev Function to set pause.
* This could for example be used in case of a fork of the network, in which case all
* "wrong" forked contracts should be paused in their respective fork. Deciding which
* fork is the "right" one is up to the owner of the contract.
*/
function pause(bool _pause, string calldata _message, address _newAddress, uint256 _fromBlock) external onlyOwner() {
paused = _pause;
emit Pause(_pause, _message, _newAddress, _fromBlock);
}
event Pause(bool paused, string message, address newAddress, uint256 fromBlock);
}
// File: contracts/AlethenaShares.sol
/**
* MIT License with Automated License Fee Payments
*
* Copyright (c) 2019 Equility AG (alethena.com)
*
* Permission is hereby granted 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.
* - All automated license fee payments integrated into this and related Software
* are preserved.
*
* 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.5.10;
/**
* @title LEXR Shares
* @author Benjamin Rickenbacher, [email protected]
* @author Luzius Meisser, [email protected]
* @dev These tokens are based on the ERC20 standard and the open-zeppelin library.
*
* These tokens are uncertified shares (Wertrechte according to the Swiss code of obligations),
* with this smart contract serving as onwership registry (Wertrechtebuch), but not as shareholder
* registry, which is kept separate and run by the company. This is equivalent to the traditional system
* of having physical share certificates kept at home by the shareholders and a shareholder registry run by
* the company. Just like with physical certificates, the owners of the tokens are the owners of the shares.
* However, in order to exercise their rights (for example receive a dividend), shareholders must register
* with the company. For example, in case the company pays out a dividend to a previous shareholder because
* the current shareholder did not register, the company cannot be held liable for paying the dividend to
* the "wrong" shareholder. In relation to the company, only the registered shareholders count as such.
* Registration requires setting up an account with ledgy.com providing your name and address and proving
* ownership over your addresses.
* @notice The main addition is a functionality that allows the user to claim that the key for a certain address is lost.
* @notice In order to prevent malicious attempts, a collateral needs to be posted.
* @notice The contract owner can delete claims in case of disputes.
*
* https://github.com/ethereum/EIPs/issues/20
* Based on code by FirstBlood: https://github.com/Firstbloodio/token/blob/master/smart_contract/FirstBloodToken.sol
*/
contract AlethenaShares is ERC20Claimable, Pausable {
using SafeMath for uint256;
string public constant symbol = "LXR";
string public constant name = "LEXR Equity";
string public constant terms = "shares.lexr.ch";
uint8 public constant decimals = 0; // legally, shares are not divisible
uint256 public totalShares = 13 * 10 ** 6; // total number of shares, maybe not all tokenized
uint256 public invalidTokens = 0;
address[] public subregisters;
event Announcement(string message);
event TokensDeclaredInvalid(address holder, uint256 amount, string message);
event ShareNumberingEvent(address holder, uint256 firstInclusive, uint256 lastInclusive);
event SubRegisterAdded(address contractAddress);
event SubRegisterRemoved(address contractAddress);
/**
* Declares the number of total shares, including those that have not been tokenized and those
* that are held by the company itself. This number can be substiantially higher than totalSupply()
* in case not all shares have been tokenized. Also, it can be lower than totalSupply() in case some
* tokens have become invalid.
*/
function setTotalShares(uint256 _newTotalShares) public onlyOwner() {
require(_newTotalShares >= totalValidSupply(), "There can't be fewer tokens than shares");
totalShares = _newTotalShares;
}
/**
* Under some use-cases, tokens are held by smart contracts that are ERC20 contracts themselves.
* A popular example are Uniswap contracts that hold traded coins and that are owned by various
* liquidity providers. For such cases, having a list of recognized such subregisters might
* be helpful with the automated registration and tracking of shareholders.
* We assume that the number of sub registers stays limited, such that they are safe to iterate.
* Subregisters should always have the same number of decimals as the main register.
* To add subregisters with a different number of decimals, adapter contracts are needed.
*/
function recognizeSubRegister(address contractAddress) public onlyOwner () {
subregisters.push(contractAddress);
emit SubRegisterAdded(contractAddress);
}
function removeSubRegister(address contractAddress) public onlyOwner() {
for (uint256 i = 0; i<subregisters.length; i++) {
if (subregisters[i] == contractAddress) {
subregisters[i] = subregisters[subregisters.length - 1];
subregisters.pop();
emit SubRegisterRemoved(contractAddress);
}
}
}
/**
* A deep balanceOf operator that also considers indirectly held tokens in
* recognized sub registers.
*/
function balanceOfDeep(address holder) public view returns (uint256) {
uint256 balance = balanceOf(holder);
for (uint256 i = 0; i<subregisters.length; i++) {
IERC20 subERC = IERC20(subregisters[i]);
balance = balance.add(subERC.balanceOf(holder));
}
return balance;
}
/**
* Allows the issuer to make public announcements that are visible on the blockchain.
*/
function announcement(string calldata message) external onlyOwner() {
emit Announcement(message);
}
function setClaimPeriod(uint256 claimPeriodInDays) public onlyOwner() {
super._setClaimPeriod(claimPeriodInDays);
}
/**
* See parent method for collateral requirements.
*/
function setCustomClaimCollateral(address collateral, uint256 rate) public onlyOwner() {
super._setCustomClaimCollateral(collateral, rate);
}
function getClaimDeleter() public returns (address) {
return owner;
}
/**
* Signals that the indicated tokens have been declared invalid (e.g. by a court ruling in accordance
* with article 973g of the planned adjustments to the Swiss Code of Obligations) and got detached from
* the underlying shares. Invalid tokens do not carry any shareholder rights any more.
*/
function declareInvalid(address holder, uint256 amount, string calldata message) external onlyOwner() {
uint256 holderBalance = balanceOf(holder);
require(amount <= holderBalance, "Cannot invalidate more tokens than held by address");
invalidTokens = invalidTokens.add(amount);
emit TokensDeclaredInvalid(holder, amount, message);
}
/**
* The total number of valid tokens in circulation. In case some tokens have been declared invalid, this
* number might be lower than totalSupply(). Also, it will always be lower than or equal to totalShares().
*/
function totalValidSupply() public view returns (uint256) {
return totalSupply().sub(invalidTokens);
}
/**
* Allows the company to tokenize shares. If these shares are newly created, setTotalShares must be
* called first in order to adjust the total number of shares.
*/
function mint(address shareholder, uint256 _amount) public onlyOwner() {
require(totalValidSupply().add(_amount) <= totalShares, "There can't be fewer shares than valid tokens");
_mint(shareholder, _amount);
}
/**
* Some companies like to number their shares so they can refer to them more explicitely in legal contracts.
* A minority of Swiss lawyers even believes that numbering shares is compulsory (which is not true).
* Nonetheless, this function allows to signal the numbers of freshly tokenized shares.
* In case the shares ever get de-tokenized again, this information might help in deducing their
* numbers again - although there might be some room for interpretation of what went where.
* By convention, transfers should be considered FIFO (first in, first out) and transactions in
* recognized subregisters be taken into account.
*/
function mintNumbered(address shareholder, uint256 firstShareNumber, uint256 lastShareNumber) public onlyOwner() {
mint(shareholder, lastShareNumber.sub(firstShareNumber).add(1));
emit ShareNumberingEvent(shareholder, firstShareNumber, lastShareNumber);
}
/**
* Transfers _amount tokens to the company and burns them.
* The meaning of this operation depends on the circumstances and the fate of the shares does
* not necessarily follow the fate of the tokens. For example, the company itself might call
* this function to implement a formal decision to destroy some of the outstanding shares.
* Also, this function might be called by an owner to return the shares to the company and
* get them back in another form under an according agreement (e.g. printed certificates or
* tokens on a different blockchain). It is not recommended to call this function without
* having agreed with the company on the further fate of the shares in question.
*/
function burn(uint256 _amount) public {
require(_amount <= balanceOf(msg.sender), "Not enough shares available");
_transfer(msg.sender, address(this), _amount);
_burn(address(this), _amount);
}
function _transfer(address from, address _to, uint256 _value) internal {
require(!paused, "Contract is paused");
super._transfer(from, _to, _value);
}
} | * Some users might want to disable claims for their address completely. For example if they use a deep cold storage solution or paper wallet./ | function isClaimsEnabled(address target) public view returns (bool) {
return !claimingDisabled[target];
}
event ClaimMade(address indexed lostAddress, address indexed claimant, uint256 balance);
event ClaimPrepared(address indexed claimer);
event ClaimCleared(address indexed lostAddress, uint256 collateral);
event ClaimDeleted(address indexed lostAddress, address indexed claimant, uint256 collateral);
event ClaimResolved(address indexed lostAddress, address indexed claimant, uint256 collateral);
event ClaimPeriodChanged(uint256 newClaimPeriodInDays);
event CustomClaimCollateralChanged(address newCustomCollateralAddress, uint256 newCustomCollareralRate);
| 926,071 | [
1,
17358,
3677,
4825,
2545,
358,
4056,
11955,
364,
3675,
1758,
14416,
18,
2457,
3454,
309,
2898,
999,
279,
4608,
645,
72,
2502,
6959,
578,
15181,
9230,
18,
19,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
565,
445,
353,
15925,
1526,
12,
2867,
1018,
13,
1071,
1476,
1135,
261,
6430,
13,
288,
203,
3639,
327,
401,
14784,
310,
8853,
63,
3299,
15533,
203,
565,
289,
203,
203,
565,
871,
18381,
49,
2486,
12,
2867,
8808,
13557,
1887,
16,
1758,
8808,
7516,
970,
16,
2254,
5034,
11013,
1769,
203,
565,
871,
18381,
15464,
12,
2867,
8808,
927,
69,
4417,
1769,
203,
565,
871,
18381,
4756,
2258,
12,
2867,
8808,
13557,
1887,
16,
2254,
5034,
4508,
2045,
287,
1769,
203,
565,
871,
18381,
7977,
12,
2867,
8808,
13557,
1887,
16,
1758,
8808,
7516,
970,
16,
2254,
5034,
4508,
2045,
287,
1769,
203,
565,
871,
18381,
12793,
12,
2867,
8808,
13557,
1887,
16,
1758,
8808,
7516,
970,
16,
2254,
5034,
4508,
2045,
287,
1769,
203,
565,
871,
18381,
5027,
5033,
12,
11890,
5034,
394,
9762,
5027,
382,
9384,
1769,
203,
565,
871,
6082,
9762,
13535,
2045,
287,
5033,
12,
2867,
394,
3802,
13535,
2045,
287,
1887,
16,
2254,
5034,
394,
3802,
914,
7901,
11612,
4727,
1769,
203,
203,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
] |
./full_match/5/0x61c082d1a24804997FE283edCF0a4de6b6B2aB63/sources/project_/contracts/CMemberSystem.sol | 函數:傳回會員陣列的地址陣列 1.建立地址陣列 2.將會員陣列的地址填入地址陣列 | function getMembersAddress()
public
view
onlyMember
returns (address[] memory)
{
address[] memory _membersAddress = new address[](members.length);
for (uint256 i = 0; i < members.length; i++) {
_membersAddress[i] = members[i]._memberAddress;
}
return _membersAddress;
}
| 1,858,566 | [
1,
166,
234,
126,
167,
248,
121,
176,
125,
253,
166,
229,
116,
166,
254,
257,
167,
255,
230,
166,
246,
99,
170,
252,
101,
166,
235,
250,
168,
253,
231,
166,
255,
113,
166,
256,
227,
170,
252,
101,
166,
235,
250,
404,
18,
166,
124,
123,
168,
109,
238,
166,
255,
113,
166,
256,
227,
170,
252,
101,
166,
235,
250,
576,
18,
166,
113,
234,
167,
255,
230,
166,
246,
99,
170,
252,
101,
166,
235,
250,
168,
253,
231,
166,
255,
113,
166,
256,
227,
166,
99,
109,
166,
232,
103,
166,
255,
113,
166,
256,
227,
170,
252,
101,
166,
235,
250,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
565,
445,
29106,
1887,
1435,
203,
3639,
1071,
203,
3639,
1476,
203,
3639,
1338,
4419,
203,
3639,
1135,
261,
2867,
8526,
3778,
13,
203,
565,
288,
203,
3639,
1758,
8526,
3778,
389,
7640,
1887,
273,
394,
1758,
8526,
12,
7640,
18,
2469,
1769,
203,
3639,
364,
261,
11890,
5034,
277,
273,
374,
31,
277,
411,
4833,
18,
2469,
31,
277,
27245,
288,
203,
5411,
389,
7640,
1887,
63,
77,
65,
273,
4833,
63,
77,
65,
6315,
5990,
1887,
31,
203,
3639,
289,
203,
3639,
327,
389,
7640,
1887,
31,
203,
565,
289,
203,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
] |
./full_match/100/0x97D3b0F2bEa3e823Aed4243c87EE475f112AfeCA/sources/contracts/CoreBase.sol | * @notice Calculate the odds of bet with amount `amount` for outcome `outcome` of condition `conditionId`. @param conditionId the match or condition ID @param amount amount of tokens to bet @param outcome predicted outcome @return odds betting odds/ | function calcOdds(
uint256 conditionId,
uint128 amount,
uint64 outcome
) external view override returns (uint64 odds) {
Condition storage condition = _getCondition(conditionId);
odds = CoreTools
.calcOdds(
condition.virtualFunds,
amount,
_getOutcomeIndex(condition, outcome),
condition.margin
)
.toUint64();
}
| 14,276,993 | [
1,
8695,
326,
14800,
87,
434,
2701,
598,
3844,
1375,
8949,
68,
364,
12884,
1375,
21672,
68,
434,
2269,
1375,
4175,
548,
8338,
282,
2269,
548,
326,
845,
578,
2269,
1599,
282,
3844,
3844,
434,
2430,
358,
2701,
282,
12884,
15071,
12884,
327,
14800,
87,
2701,
1787,
14800,
87,
19,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
565,
445,
7029,
51,
449,
87,
12,
203,
3639,
2254,
5034,
2269,
548,
16,
203,
3639,
2254,
10392,
3844,
16,
203,
3639,
2254,
1105,
12884,
203,
565,
262,
3903,
1476,
3849,
1135,
261,
11890,
1105,
14800,
87,
13,
288,
203,
3639,
7949,
2502,
2269,
273,
389,
588,
3418,
12,
4175,
548,
1769,
203,
3639,
14800,
87,
273,
4586,
10348,
203,
5411,
263,
12448,
51,
449,
87,
12,
203,
7734,
2269,
18,
12384,
42,
19156,
16,
203,
7734,
3844,
16,
203,
7734,
389,
588,
19758,
1016,
12,
4175,
16,
12884,
3631,
203,
7734,
2269,
18,
10107,
203,
5411,
262,
203,
5411,
263,
869,
5487,
1105,
5621,
203,
565,
289,
203,
203,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
] |
./partial_match/4/0xC8be655fBE8750beF55fe1896dbDF5aEA8dfCAcA/sources/DeBase.sol | * @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);
}
| 8,559,720 | [
1,
9378,
28599,
1375,
8949,
68,
2430,
628,
1375,
4631,
9191,
9299,
2822,
326,
2078,
14467,
18,
7377,
1282,
279,
288,
5912,
97,
871,
598,
1375,
869,
68,
444,
358,
326,
3634,
1758,
18,
29076,
300,
1375,
4631,
68,
2780,
506,
326,
3634,
1758,
18,
300,
1375,
4631,
68,
1297,
1240,
622,
4520,
1375,
8949,
68,
2430,
18,
19,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
565,
445,
389,
70,
321,
12,
2867,
2236,
16,
2254,
5034,
3844,
13,
2713,
5024,
288,
203,
3639,
2583,
12,
4631,
480,
1758,
12,
20,
3631,
315,
654,
39,
3462,
30,
18305,
628,
326,
3634,
1758,
8863,
203,
203,
3639,
389,
5771,
1345,
5912,
12,
4631,
16,
1758,
12,
20,
3631,
3844,
1769,
203,
203,
3639,
389,
70,
26488,
63,
4631,
65,
273,
389,
70,
26488,
63,
4631,
8009,
1717,
12,
8949,
16,
315,
654,
39,
3462,
30,
18305,
3844,
14399,
11013,
8863,
203,
3639,
389,
4963,
3088,
1283,
273,
389,
4963,
3088,
1283,
18,
1717,
12,
8949,
1769,
203,
3639,
3626,
12279,
12,
4631,
16,
1758,
12,
20,
3631,
3844,
1769,
203,
565,
289,
203,
203,
1377,
203,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
] |
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.4;
import "@openzeppelin/contracts/governance/Governor.sol";
import "@openzeppelin/contracts/governance/extensions/GovernorSettings.sol";
import "@openzeppelin/contracts/governance/extensions/GovernorCountingSimple.sol";
import "@openzeppelin/contracts/governance/extensions/GovernorVotes.sol";
import "@openzeppelin/contracts/governance/extensions/GovernorVotesQuorumFraction.sol";
import "@openzeppelin/contracts/token/ERC721/IERC721Receiver.sol";
/// @custom:security-contact [email protected]
contract PridePunkGovernor is
Governor,
GovernorSettings,
GovernorCountingSimple,
GovernorVotes,
GovernorVotesQuorumFraction,
IERC721Receiver
{
constructor(IVotes _token)
Governor("Pride Punk Governor")
GovernorSettings(
1, /* 1 block */
19636, /* 3 days */
1e18
)
GovernorVotes(_token)
GovernorVotesQuorumFraction(4)
{}
// Enable reciving ERC721s
function onERC721Received(
address,
address,
uint256,
bytes memory
) public virtual override returns (bytes4) {
return this.onERC721Received.selector;
}
// The following functions are overrides required by Solidity.
function votingDelay() public view override(IGovernor, GovernorSettings) returns (uint256) {
return super.votingDelay();
}
function votingPeriod() public view override(IGovernor, GovernorSettings) returns (uint256) {
return super.votingPeriod();
}
function quorum(uint256 blockNumber)
public
view
override(IGovernor, GovernorVotesQuorumFraction)
returns (uint256)
{
return super.quorum(blockNumber);
}
function getVotes(address account, uint256 blockNumber)
public
view
override(IGovernor, GovernorVotes)
returns (uint256)
{
return super.getVotes(account, blockNumber);
}
function proposalThreshold() public view override(Governor, GovernorSettings) returns (uint256) {
return super.proposalThreshold();
}
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v4.5.0) (governance/Governor.sol)
pragma solidity ^0.8.0;
import "../utils/cryptography/ECDSA.sol";
import "../utils/cryptography/draft-EIP712.sol";
import "../utils/introspection/ERC165.sol";
import "../utils/math/SafeCast.sol";
import "../utils/Address.sol";
import "../utils/Context.sol";
import "../utils/Timers.sol";
import "./IGovernor.sol";
/**
* @dev Core of the governance system, designed to be extended though various modules.
*
* This contract is abstract and requires several function to be implemented in various modules:
*
* - A counting module must implement {quorum}, {_quorumReached}, {_voteSucceeded} and {_countVote}
* - A voting module must implement {getVotes}
* - Additionanly, the {votingPeriod} must also be implemented
*
* _Available since v4.3._
*/
abstract contract Governor is Context, ERC165, EIP712, IGovernor {
using SafeCast for uint256;
using Timers for Timers.BlockNumber;
bytes32 public constant BALLOT_TYPEHASH = keccak256("Ballot(uint256 proposalId,uint8 support)");
struct ProposalCore {
Timers.BlockNumber voteStart;
Timers.BlockNumber voteEnd;
bool executed;
bool canceled;
}
string private _name;
mapping(uint256 => ProposalCore) private _proposals;
/**
* @dev Restrict access of functions to the governance executor, which may be the Governor itself or a timelock
* contract, as specified by {_executor}. This generally means that function with this modifier must be voted on and
* executed through the governance protocol.
*/
modifier onlyGovernance() {
require(_msgSender() == _executor(), "Governor: onlyGovernance");
_;
}
/**
* @dev Sets the value for {name} and {version}
*/
constructor(string memory name_) EIP712(name_, version()) {
_name = name_;
}
/**
* @dev Function to receive ETH that will be handled by the governor (disabled if executor is a third party contract)
*/
receive() external payable virtual {
require(_executor() == address(this));
}
/**
* @dev See {IERC165-supportsInterface}.
*/
function supportsInterface(bytes4 interfaceId) public view virtual override(IERC165, ERC165) returns (bool) {
return interfaceId == type(IGovernor).interfaceId || super.supportsInterface(interfaceId);
}
/**
* @dev See {IGovernor-name}.
*/
function name() public view virtual override returns (string memory) {
return _name;
}
/**
* @dev See {IGovernor-version}.
*/
function version() public view virtual override returns (string memory) {
return "1";
}
/**
* @dev See {IGovernor-hashProposal}.
*
* The proposal id is produced by hashing the RLC encoded `targets` array, the `values` array, the `calldatas` array
* and the descriptionHash (bytes32 which itself is the keccak256 hash of the description string). This proposal id
* can be produced from the proposal data which is part of the {ProposalCreated} event. It can even be computed in
* advance, before the proposal is submitted.
*
* Note that the chainId and the governor address are not part of the proposal id computation. Consequently, the
* same proposal (with same operation and same description) will have the same id if submitted on multiple governors
* accross multiple networks. This also means that in order to execute the same operation twice (on the same
* governor) the proposer will have to change the description in order to avoid proposal id conflicts.
*/
function hashProposal(
address[] memory targets,
uint256[] memory values,
bytes[] memory calldatas,
bytes32 descriptionHash
) public pure virtual override returns (uint256) {
return uint256(keccak256(abi.encode(targets, values, calldatas, descriptionHash)));
}
/**
* @dev See {IGovernor-state}.
*/
function state(uint256 proposalId) public view virtual override returns (ProposalState) {
ProposalCore storage proposal = _proposals[proposalId];
if (proposal.executed) {
return ProposalState.Executed;
}
if (proposal.canceled) {
return ProposalState.Canceled;
}
uint256 snapshot = proposalSnapshot(proposalId);
if (snapshot == 0) {
revert("Governor: unknown proposal id");
}
if (snapshot >= block.number) {
return ProposalState.Pending;
}
uint256 deadline = proposalDeadline(proposalId);
if (deadline >= block.number) {
return ProposalState.Active;
}
if (_quorumReached(proposalId) && _voteSucceeded(proposalId)) {
return ProposalState.Succeeded;
} else {
return ProposalState.Defeated;
}
}
/**
* @dev See {IGovernor-proposalSnapshot}.
*/
function proposalSnapshot(uint256 proposalId) public view virtual override returns (uint256) {
return _proposals[proposalId].voteStart.getDeadline();
}
/**
* @dev See {IGovernor-proposalDeadline}.
*/
function proposalDeadline(uint256 proposalId) public view virtual override returns (uint256) {
return _proposals[proposalId].voteEnd.getDeadline();
}
/**
* @dev Part of the Governor Bravo's interface: _"The number of votes required in order for a voter to become a proposer"_.
*/
function proposalThreshold() public view virtual returns (uint256) {
return 0;
}
/**
* @dev Amount of votes already cast passes the threshold limit.
*/
function _quorumReached(uint256 proposalId) internal view virtual returns (bool);
/**
* @dev Is the proposal successful or not.
*/
function _voteSucceeded(uint256 proposalId) internal view virtual returns (bool);
/**
* @dev Register a vote with a given support and voting weight.
*
* Note: Support is generic and can represent various things depending on the voting system used.
*/
function _countVote(
uint256 proposalId,
address account,
uint8 support,
uint256 weight
) internal virtual;
/**
* @dev See {IGovernor-propose}.
*/
function propose(
address[] memory targets,
uint256[] memory values,
bytes[] memory calldatas,
string memory description
) public virtual override returns (uint256) {
require(
getVotes(msg.sender, block.number - 1) >= proposalThreshold(),
"GovernorCompatibilityBravo: proposer votes below proposal threshold"
);
uint256 proposalId = hashProposal(targets, values, calldatas, keccak256(bytes(description)));
require(targets.length == values.length, "Governor: invalid proposal length");
require(targets.length == calldatas.length, "Governor: invalid proposal length");
require(targets.length > 0, "Governor: empty proposal");
ProposalCore storage proposal = _proposals[proposalId];
require(proposal.voteStart.isUnset(), "Governor: proposal already exists");
uint64 snapshot = block.number.toUint64() + votingDelay().toUint64();
uint64 deadline = snapshot + votingPeriod().toUint64();
proposal.voteStart.setDeadline(snapshot);
proposal.voteEnd.setDeadline(deadline);
emit ProposalCreated(
proposalId,
_msgSender(),
targets,
values,
new string[](targets.length),
calldatas,
snapshot,
deadline,
description
);
return proposalId;
}
/**
* @dev See {IGovernor-execute}.
*/
function execute(
address[] memory targets,
uint256[] memory values,
bytes[] memory calldatas,
bytes32 descriptionHash
) public payable virtual override returns (uint256) {
uint256 proposalId = hashProposal(targets, values, calldatas, descriptionHash);
ProposalState status = state(proposalId);
require(
status == ProposalState.Succeeded || status == ProposalState.Queued,
"Governor: proposal not successful"
);
_proposals[proposalId].executed = true;
emit ProposalExecuted(proposalId);
_execute(proposalId, targets, values, calldatas, descriptionHash);
return proposalId;
}
/**
* @dev Internal execution mechanism. Can be overriden to implement different execution mechanism
*/
function _execute(
uint256, /* proposalId */
address[] memory targets,
uint256[] memory values,
bytes[] memory calldatas,
bytes32 /*descriptionHash*/
) internal virtual {
string memory errorMessage = "Governor: call reverted without message";
for (uint256 i = 0; i < targets.length; ++i) {
(bool success, bytes memory returndata) = targets[i].call{value: values[i]}(calldatas[i]);
Address.verifyCallResult(success, returndata, errorMessage);
}
}
/**
* @dev Internal cancel mechanism: locks up the proposal timer, preventing it from being re-submitted. Marks it as
* canceled to allow distinguishing it from executed proposals.
*
* Emits a {IGovernor-ProposalCanceled} event.
*/
function _cancel(
address[] memory targets,
uint256[] memory values,
bytes[] memory calldatas,
bytes32 descriptionHash
) internal virtual returns (uint256) {
uint256 proposalId = hashProposal(targets, values, calldatas, descriptionHash);
ProposalState status = state(proposalId);
require(
status != ProposalState.Canceled && status != ProposalState.Expired && status != ProposalState.Executed,
"Governor: proposal not active"
);
_proposals[proposalId].canceled = true;
emit ProposalCanceled(proposalId);
return proposalId;
}
/**
* @dev See {IGovernor-castVote}.
*/
function castVote(uint256 proposalId, uint8 support) public virtual override returns (uint256) {
address voter = _msgSender();
return _castVote(proposalId, voter, support, "");
}
/**
* @dev See {IGovernor-castVoteWithReason}.
*/
function castVoteWithReason(
uint256 proposalId,
uint8 support,
string calldata reason
) public virtual override returns (uint256) {
address voter = _msgSender();
return _castVote(proposalId, voter, support, reason);
}
/**
* @dev See {IGovernor-castVoteBySig}.
*/
function castVoteBySig(
uint256 proposalId,
uint8 support,
uint8 v,
bytes32 r,
bytes32 s
) public virtual override returns (uint256) {
address voter = ECDSA.recover(
_hashTypedDataV4(keccak256(abi.encode(BALLOT_TYPEHASH, proposalId, support))),
v,
r,
s
);
return _castVote(proposalId, voter, support, "");
}
/**
* @dev Internal vote casting mechanism: Check that the vote is pending, that it has not been cast yet, retrieve
* voting weight using {IGovernor-getVotes} and call the {_countVote} internal function.
*
* Emits a {IGovernor-VoteCast} event.
*/
function _castVote(
uint256 proposalId,
address account,
uint8 support,
string memory reason
) internal virtual returns (uint256) {
ProposalCore storage proposal = _proposals[proposalId];
require(state(proposalId) == ProposalState.Active, "Governor: vote not currently active");
uint256 weight = getVotes(account, proposal.voteStart.getDeadline());
_countVote(proposalId, account, support, weight);
emit VoteCast(account, proposalId, support, weight, reason);
return weight;
}
/**
* @dev Relays a transaction or function call to an arbitrary target. In cases where the governance executor
* is some contract other than the governor itself, like when using a timelock, this function can be invoked
* in a governance proposal to recover tokens or Ether that was sent to the governor contract by mistake.
* Note that if the executor is simply the governor itself, use of `relay` is redundant.
*/
function relay(
address target,
uint256 value,
bytes calldata data
) external virtual onlyGovernance {
Address.functionCallWithValue(target, data, value);
}
/**
* @dev Address through which the governor executes action. Will be overloaded by module that execute actions
* through another contract such as a timelock.
*/
function _executor() internal view virtual returns (address) {
return address(this);
}
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (governance/extensions/GovernorSettings.sol)
pragma solidity ^0.8.0;
import "../Governor.sol";
/**
* @dev Extension of {Governor} for settings updatable through governance.
*
* _Available since v4.4._
*/
abstract contract GovernorSettings is Governor {
uint256 private _votingDelay;
uint256 private _votingPeriod;
uint256 private _proposalThreshold;
event VotingDelaySet(uint256 oldVotingDelay, uint256 newVotingDelay);
event VotingPeriodSet(uint256 oldVotingPeriod, uint256 newVotingPeriod);
event ProposalThresholdSet(uint256 oldProposalThreshold, uint256 newProposalThreshold);
/**
* @dev Initialize the governance parameters.
*/
constructor(
uint256 initialVotingDelay,
uint256 initialVotingPeriod,
uint256 initialProposalThreshold
) {
_setVotingDelay(initialVotingDelay);
_setVotingPeriod(initialVotingPeriod);
_setProposalThreshold(initialProposalThreshold);
}
/**
* @dev See {IGovernor-votingDelay}.
*/
function votingDelay() public view virtual override returns (uint256) {
return _votingDelay;
}
/**
* @dev See {IGovernor-votingPeriod}.
*/
function votingPeriod() public view virtual override returns (uint256) {
return _votingPeriod;
}
/**
* @dev See {Governor-proposalThreshold}.
*/
function proposalThreshold() public view virtual override returns (uint256) {
return _proposalThreshold;
}
/**
* @dev Update the voting delay. This operation can only be performed through a governance proposal.
*
* Emits a {VotingDelaySet} event.
*/
function setVotingDelay(uint256 newVotingDelay) public virtual onlyGovernance {
_setVotingDelay(newVotingDelay);
}
/**
* @dev Update the voting period. This operation can only be performed through a governance proposal.
*
* Emits a {VotingPeriodSet} event.
*/
function setVotingPeriod(uint256 newVotingPeriod) public virtual onlyGovernance {
_setVotingPeriod(newVotingPeriod);
}
/**
* @dev Update the proposal threshold. This operation can only be performed through a governance proposal.
*
* Emits a {ProposalThresholdSet} event.
*/
function setProposalThreshold(uint256 newProposalThreshold) public virtual onlyGovernance {
_setProposalThreshold(newProposalThreshold);
}
/**
* @dev Internal setter for the voting delay.
*
* Emits a {VotingDelaySet} event.
*/
function _setVotingDelay(uint256 newVotingDelay) internal virtual {
emit VotingDelaySet(_votingDelay, newVotingDelay);
_votingDelay = newVotingDelay;
}
/**
* @dev Internal setter for the voting period.
*
* Emits a {VotingPeriodSet} event.
*/
function _setVotingPeriod(uint256 newVotingPeriod) internal virtual {
// voting period must be at least one block long
require(newVotingPeriod > 0, "GovernorSettings: voting period too low");
emit VotingPeriodSet(_votingPeriod, newVotingPeriod);
_votingPeriod = newVotingPeriod;
}
/**
* @dev Internal setter for the proposal threshold.
*
* Emits a {ProposalThresholdSet} event.
*/
function _setProposalThreshold(uint256 newProposalThreshold) internal virtual {
emit ProposalThresholdSet(_proposalThreshold, newProposalThreshold);
_proposalThreshold = newProposalThreshold;
}
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (governance/extensions/GovernorCountingSimple.sol)
pragma solidity ^0.8.0;
import "../Governor.sol";
/**
* @dev Extension of {Governor} for simple, 3 options, vote counting.
*
* _Available since v4.3._
*/
abstract contract GovernorCountingSimple is Governor {
/**
* @dev Supported vote types. Matches Governor Bravo ordering.
*/
enum VoteType {
Against,
For,
Abstain
}
struct ProposalVote {
uint256 againstVotes;
uint256 forVotes;
uint256 abstainVotes;
mapping(address => bool) hasVoted;
}
mapping(uint256 => ProposalVote) private _proposalVotes;
/**
* @dev See {IGovernor-COUNTING_MODE}.
*/
// solhint-disable-next-line func-name-mixedcase
function COUNTING_MODE() public pure virtual override returns (string memory) {
return "support=bravo&quorum=for,abstain";
}
/**
* @dev See {IGovernor-hasVoted}.
*/
function hasVoted(uint256 proposalId, address account) public view virtual override returns (bool) {
return _proposalVotes[proposalId].hasVoted[account];
}
/**
* @dev Accessor to the internal vote counts.
*/
function proposalVotes(uint256 proposalId)
public
view
virtual
returns (
uint256 againstVotes,
uint256 forVotes,
uint256 abstainVotes
)
{
ProposalVote storage proposalvote = _proposalVotes[proposalId];
return (proposalvote.againstVotes, proposalvote.forVotes, proposalvote.abstainVotes);
}
/**
* @dev See {Governor-_quorumReached}.
*/
function _quorumReached(uint256 proposalId) internal view virtual override returns (bool) {
ProposalVote storage proposalvote = _proposalVotes[proposalId];
return quorum(proposalSnapshot(proposalId)) <= proposalvote.forVotes + proposalvote.abstainVotes;
}
/**
* @dev See {Governor-_voteSucceeded}. In this module, the forVotes must be strictly over the againstVotes.
*/
function _voteSucceeded(uint256 proposalId) internal view virtual override returns (bool) {
ProposalVote storage proposalvote = _proposalVotes[proposalId];
return proposalvote.forVotes > proposalvote.againstVotes;
}
/**
* @dev See {Governor-_countVote}. In this module, the support follows the `VoteType` enum (from Governor Bravo).
*/
function _countVote(
uint256 proposalId,
address account,
uint8 support,
uint256 weight
) internal virtual override {
ProposalVote storage proposalvote = _proposalVotes[proposalId];
require(!proposalvote.hasVoted[account], "GovernorVotingSimple: vote already cast");
proposalvote.hasVoted[account] = true;
if (support == uint8(VoteType.Against)) {
proposalvote.againstVotes += weight;
} else if (support == uint8(VoteType.For)) {
proposalvote.forVotes += weight;
} else if (support == uint8(VoteType.Abstain)) {
proposalvote.abstainVotes += weight;
} else {
revert("GovernorVotingSimple: invalid value for enum VoteType");
}
}
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v4.5.0) (governance/extensions/GovernorVotes.sol)
pragma solidity ^0.8.0;
import "../Governor.sol";
import "../utils/IVotes.sol";
/**
* @dev Extension of {Governor} for voting weight extraction from an {ERC20Votes} token, or since v4.5 an {ERC721Votes} token.
*
* _Available since v4.3._
*/
abstract contract GovernorVotes is Governor {
IVotes public immutable token;
constructor(IVotes tokenAddress) {
token = tokenAddress;
}
/**
* Read the voting weight from the token's built in snapshot mechanism (see {IGovernor-getVotes}).
*/
function getVotes(address account, uint256 blockNumber) public view virtual override returns (uint256) {
return token.getPastVotes(account, blockNumber);
}
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v4.5.0) (governance/extensions/GovernorVotesQuorumFraction.sol)
pragma solidity ^0.8.0;
import "./GovernorVotes.sol";
/**
* @dev Extension of {Governor} for voting weight extraction from an {ERC20Votes} token and a quorum expressed as a
* fraction of the total supply.
*
* _Available since v4.3._
*/
abstract contract GovernorVotesQuorumFraction is GovernorVotes {
uint256 private _quorumNumerator;
event QuorumNumeratorUpdated(uint256 oldQuorumNumerator, uint256 newQuorumNumerator);
/**
* @dev Initialize quorum as a fraction of the token's total supply.
*
* The fraction is specified as `numerator / denominator`. By default the denominator is 100, so quorum is
* specified as a percent: a numerator of 10 corresponds to quorum being 10% of total supply. The denominator can be
* customized by overriding {quorumDenominator}.
*/
constructor(uint256 quorumNumeratorValue) {
_updateQuorumNumerator(quorumNumeratorValue);
}
/**
* @dev Returns the current quorum numerator. See {quorumDenominator}.
*/
function quorumNumerator() public view virtual returns (uint256) {
return _quorumNumerator;
}
/**
* @dev Returns the quorum denominator. Defaults to 100, but may be overridden.
*/
function quorumDenominator() public view virtual returns (uint256) {
return 100;
}
/**
* @dev Returns the quorum for a block number, in terms of number of votes: `supply * numerator / denominator`.
*/
function quorum(uint256 blockNumber) public view virtual override returns (uint256) {
return (token.getPastTotalSupply(blockNumber) * quorumNumerator()) / quorumDenominator();
}
/**
* @dev Changes the quorum numerator.
*
* Emits a {QuorumNumeratorUpdated} event.
*
* Requirements:
*
* - Must be called through a governance proposal.
* - New numerator must be smaller or equal to the denominator.
*/
function updateQuorumNumerator(uint256 newQuorumNumerator) external virtual onlyGovernance {
_updateQuorumNumerator(newQuorumNumerator);
}
/**
* @dev Changes the quorum numerator.
*
* Emits a {QuorumNumeratorUpdated} event.
*
* Requirements:
*
* - New numerator must be smaller or equal to the denominator.
*/
function _updateQuorumNumerator(uint256 newQuorumNumerator) internal virtual {
require(
newQuorumNumerator <= quorumDenominator(),
"GovernorVotesQuorumFraction: quorumNumerator over quorumDenominator"
);
uint256 oldQuorumNumerator = _quorumNumerator;
_quorumNumerator = newQuorumNumerator;
emit QuorumNumeratorUpdated(oldQuorumNumerator, newQuorumNumerator);
}
}
// 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 (last updated v4.5.0) (utils/cryptography/ECDSA.sol)
pragma solidity ^0.8.0;
import "../Strings.sol";
/**
* @dev Elliptic Curve Digital Signature Algorithm (ECDSA) operations.
*
* These functions can be used to verify that a message was signed by the holder
* of the private keys of a given address.
*/
library ECDSA {
enum RecoverError {
NoError,
InvalidSignature,
InvalidSignatureLength,
InvalidSignatureS,
InvalidSignatureV
}
function _throwError(RecoverError error) private pure {
if (error == RecoverError.NoError) {
return; // no error: do nothing
} else if (error == RecoverError.InvalidSignature) {
revert("ECDSA: invalid signature");
} else if (error == RecoverError.InvalidSignatureLength) {
revert("ECDSA: invalid signature length");
} else if (error == RecoverError.InvalidSignatureS) {
revert("ECDSA: invalid signature 's' value");
} else if (error == RecoverError.InvalidSignatureV) {
revert("ECDSA: invalid signature 'v' value");
}
}
/**
* @dev Returns the address that signed a hashed message (`hash`) with
* `signature` or error string. This address can then be used for verification purposes.
*
* The `ecrecover` EVM opcode allows for malleable (non-unique) signatures:
* this function rejects them by requiring the `s` value to be in the lower
* half order, and the `v` value to be either 27 or 28.
*
* IMPORTANT: `hash` _must_ be the result of a hash operation for the
* verification to be secure: it is possible to craft signatures that
* recover to arbitrary addresses for non-hashed data. A safe way to ensure
* this is by receiving a hash of the original message (which may otherwise
* be too long), and then calling {toEthSignedMessageHash} on it.
*
* Documentation for signature generation:
* - with https://web3js.readthedocs.io/en/v1.3.4/web3-eth-accounts.html#sign[Web3.js]
* - with https://docs.ethers.io/v5/api/signer/#Signer-signMessage[ethers]
*
* _Available since v4.3._
*/
function tryRecover(bytes32 hash, bytes memory signature) internal pure returns (address, RecoverError) {
// Check the signature length
// - case 65: r,s,v signature (standard)
// - case 64: r,vs signature (cf https://eips.ethereum.org/EIPS/eip-2098) _Available since v4.1._
if (signature.length == 65) {
bytes32 r;
bytes32 s;
uint8 v;
// ecrecover takes the signature parameters, and the only way to get them
// currently is to use assembly.
assembly {
r := mload(add(signature, 0x20))
s := mload(add(signature, 0x40))
v := byte(0, mload(add(signature, 0x60)))
}
return tryRecover(hash, v, r, s);
} else if (signature.length == 64) {
bytes32 r;
bytes32 vs;
// ecrecover takes the signature parameters, and the only way to get them
// currently is to use assembly.
assembly {
r := mload(add(signature, 0x20))
vs := mload(add(signature, 0x40))
}
return tryRecover(hash, r, vs);
} else {
return (address(0), RecoverError.InvalidSignatureLength);
}
}
/**
* @dev Returns the address that signed a hashed message (`hash`) with
* `signature`. This address can then be used for verification purposes.
*
* The `ecrecover` EVM opcode allows for malleable (non-unique) signatures:
* this function rejects them by requiring the `s` value to be in the lower
* half order, and the `v` value to be either 27 or 28.
*
* IMPORTANT: `hash` _must_ be the result of a hash operation for the
* verification to be secure: it is possible to craft signatures that
* recover to arbitrary addresses for non-hashed data. A safe way to ensure
* this is by receiving a hash of the original message (which may otherwise
* be too long), and then calling {toEthSignedMessageHash} on it.
*/
function recover(bytes32 hash, bytes memory signature) internal pure returns (address) {
(address recovered, RecoverError error) = tryRecover(hash, signature);
_throwError(error);
return recovered;
}
/**
* @dev Overload of {ECDSA-tryRecover} that receives the `r` and `vs` short-signature fields separately.
*
* See https://eips.ethereum.org/EIPS/eip-2098[EIP-2098 short signatures]
*
* _Available since v4.3._
*/
function tryRecover(
bytes32 hash,
bytes32 r,
bytes32 vs
) internal pure returns (address, RecoverError) {
bytes32 s = vs & bytes32(0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff);
uint8 v = uint8((uint256(vs) >> 255) + 27);
return tryRecover(hash, v, r, s);
}
/**
* @dev Overload of {ECDSA-recover} that receives the `r and `vs` short-signature fields separately.
*
* _Available since v4.2._
*/
function recover(
bytes32 hash,
bytes32 r,
bytes32 vs
) internal pure returns (address) {
(address recovered, RecoverError error) = tryRecover(hash, r, vs);
_throwError(error);
return recovered;
}
/**
* @dev Overload of {ECDSA-tryRecover} that receives the `v`,
* `r` and `s` signature fields separately.
*
* _Available since v4.3._
*/
function tryRecover(
bytes32 hash,
uint8 v,
bytes32 r,
bytes32 s
) internal pure returns (address, RecoverError) {
// 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 (301): 0 < s < secp256k1n ÷ 2 + 1, and for v in (302): 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), RecoverError.InvalidSignatureS);
}
if (v != 27 && v != 28) {
return (address(0), RecoverError.InvalidSignatureV);
}
// If the signature is valid (and not malleable), return the signer address
address signer = ecrecover(hash, v, r, s);
if (signer == address(0)) {
return (address(0), RecoverError.InvalidSignature);
}
return (signer, RecoverError.NoError);
}
/**
* @dev Overload of {ECDSA-recover} that receives the `v`,
* `r` and `s` signature fields separately.
*/
function recover(
bytes32 hash,
uint8 v,
bytes32 r,
bytes32 s
) internal pure returns (address) {
(address recovered, RecoverError error) = tryRecover(hash, v, r, s);
_throwError(error);
return recovered;
}
/**
* @dev Returns an Ethereum Signed Message, created from a `hash`. This
* produces hash corresponding to the one signed with the
* https://eth.wiki/json-rpc/API#eth_sign[`eth_sign`]
* JSON-RPC method as part of EIP-191.
*
* See {recover}.
*/
function toEthSignedMessageHash(bytes32 hash) internal pure returns (bytes32) {
// 32 is the length in bytes of hash,
// enforced by the type signature above
return keccak256(abi.encodePacked("\x19Ethereum Signed Message:\n32", hash));
}
/**
* @dev Returns an Ethereum Signed Message, created from `s`. This
* produces hash corresponding to the one signed with the
* https://eth.wiki/json-rpc/API#eth_sign[`eth_sign`]
* JSON-RPC method as part of EIP-191.
*
* See {recover}.
*/
function toEthSignedMessageHash(bytes memory s) internal pure returns (bytes32) {
return keccak256(abi.encodePacked("\x19Ethereum Signed Message:\n", Strings.toString(s.length), s));
}
/**
* @dev Returns an Ethereum Signed Typed Data, created from a
* `domainSeparator` and a `structHash`. This produces hash corresponding
* to the one signed with the
* https://eips.ethereum.org/EIPS/eip-712[`eth_signTypedData`]
* JSON-RPC method as part of EIP-712.
*
* See {recover}.
*/
function toTypedDataHash(bytes32 domainSeparator, bytes32 structHash) internal pure returns (bytes32) {
return keccak256(abi.encodePacked("\x19\x01", domainSeparator, structHash));
}
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (utils/cryptography/draft-EIP712.sol)
pragma solidity ^0.8.0;
import "./ECDSA.sol";
/**
* @dev https://eips.ethereum.org/EIPS/eip-712[EIP 712] is a standard for hashing and signing of typed structured data.
*
* The encoding specified in the EIP is very generic, and such a generic implementation in Solidity is not feasible,
* thus this contract does not implement the encoding itself. Protocols need to implement the type-specific encoding
* they need in their contracts using a combination of `abi.encode` and `keccak256`.
*
* This contract implements the EIP 712 domain separator ({_domainSeparatorV4}) that is used as part of the encoding
* scheme, and the final step of the encoding to obtain the message digest that is then signed via ECDSA
* ({_hashTypedDataV4}).
*
* The implementation of the domain separator was designed to be as efficient as possible while still properly updating
* the chain id to protect against replay attacks on an eventual fork of the chain.
*
* NOTE: This contract implements the version of the encoding known as "v4", as implemented by the JSON RPC method
* https://docs.metamask.io/guide/signing-data.html[`eth_signTypedDataV4` in MetaMask].
*
* _Available since v3.4._
*/
abstract contract EIP712 {
/* solhint-disable var-name-mixedcase */
// Cache the domain separator as an immutable value, but also store the chain id that it corresponds to, in order to
// invalidate the cached domain separator if the chain id changes.
bytes32 private immutable _CACHED_DOMAIN_SEPARATOR;
uint256 private immutable _CACHED_CHAIN_ID;
address private immutable _CACHED_THIS;
bytes32 private immutable _HASHED_NAME;
bytes32 private immutable _HASHED_VERSION;
bytes32 private immutable _TYPE_HASH;
/* solhint-enable var-name-mixedcase */
/**
* @dev Initializes the domain separator and parameter caches.
*
* The meaning of `name` and `version` is specified in
* https://eips.ethereum.org/EIPS/eip-712#definition-of-domainseparator[EIP 712]:
*
* - `name`: the user readable name of the signing domain, i.e. the name of the DApp or the protocol.
* - `version`: the current major version of the signing domain.
*
* NOTE: These parameters cannot be changed except through a xref:learn::upgrading-smart-contracts.adoc[smart
* contract upgrade].
*/
constructor(string memory name, string memory version) {
bytes32 hashedName = keccak256(bytes(name));
bytes32 hashedVersion = keccak256(bytes(version));
bytes32 typeHash = keccak256(
"EIP712Domain(string name,string version,uint256 chainId,address verifyingContract)"
);
_HASHED_NAME = hashedName;
_HASHED_VERSION = hashedVersion;
_CACHED_CHAIN_ID = block.chainid;
_CACHED_DOMAIN_SEPARATOR = _buildDomainSeparator(typeHash, hashedName, hashedVersion);
_CACHED_THIS = address(this);
_TYPE_HASH = typeHash;
}
/**
* @dev Returns the domain separator for the current chain.
*/
function _domainSeparatorV4() internal view returns (bytes32) {
if (address(this) == _CACHED_THIS && block.chainid == _CACHED_CHAIN_ID) {
return _CACHED_DOMAIN_SEPARATOR;
} else {
return _buildDomainSeparator(_TYPE_HASH, _HASHED_NAME, _HASHED_VERSION);
}
}
function _buildDomainSeparator(
bytes32 typeHash,
bytes32 nameHash,
bytes32 versionHash
) private view returns (bytes32) {
return keccak256(abi.encode(typeHash, nameHash, versionHash, block.chainid, address(this)));
}
/**
* @dev Given an already https://eips.ethereum.org/EIPS/eip-712#definition-of-hashstruct[hashed struct], this
* function returns the hash of the fully encoded EIP712 message for this domain.
*
* This hash can be used together with {ECDSA-recover} to obtain the signer of a message. For example:
*
* ```solidity
* bytes32 digest = _hashTypedDataV4(keccak256(abi.encode(
* keccak256("Mail(address to,string contents)"),
* mailTo,
* keccak256(bytes(mailContents))
* )));
* address signer = ECDSA.recover(digest, signature);
* ```
*/
function _hashTypedDataV4(bytes32 structHash) internal view virtual returns (bytes32) {
return ECDSA.toTypedDataHash(_domainSeparatorV4(), structHash);
}
}
// 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/math/SafeCast.sol)
pragma solidity ^0.8.0;
/**
* @dev Wrappers over Solidity's uintXX/intXX casting operators with added overflow
* checks.
*
* Downcasting from uint256/int256 in Solidity does not revert on overflow. This can
* easily result in undesired exploitation or bugs, since developers usually
* assume that overflows raise errors. `SafeCast` restores this intuition by
* reverting the transaction when such 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.
*
* Can be combined with {SafeMath} and {SignedSafeMath} to extend it to smaller types, by performing
* all math on `uint256` and `int256` and then downcasting.
*/
library SafeCast {
/**
* @dev Returns the downcasted uint224 from uint256, reverting on
* overflow (when the input is greater than largest uint224).
*
* Counterpart to Solidity's `uint224` operator.
*
* Requirements:
*
* - input must fit into 224 bits
*/
function toUint224(uint256 value) internal pure returns (uint224) {
require(value <= type(uint224).max, "SafeCast: value doesn't fit in 224 bits");
return uint224(value);
}
/**
* @dev Returns the downcasted uint128 from uint256, reverting on
* overflow (when the input is greater than largest uint128).
*
* Counterpart to Solidity's `uint128` operator.
*
* Requirements:
*
* - input must fit into 128 bits
*/
function toUint128(uint256 value) internal pure returns (uint128) {
require(value <= type(uint128).max, "SafeCast: value doesn't fit in 128 bits");
return uint128(value);
}
/**
* @dev Returns the downcasted uint96 from uint256, reverting on
* overflow (when the input is greater than largest uint96).
*
* Counterpart to Solidity's `uint96` operator.
*
* Requirements:
*
* - input must fit into 96 bits
*/
function toUint96(uint256 value) internal pure returns (uint96) {
require(value <= type(uint96).max, "SafeCast: value doesn't fit in 96 bits");
return uint96(value);
}
/**
* @dev Returns the downcasted uint64 from uint256, reverting on
* overflow (when the input is greater than largest uint64).
*
* Counterpart to Solidity's `uint64` operator.
*
* Requirements:
*
* - input must fit into 64 bits
*/
function toUint64(uint256 value) internal pure returns (uint64) {
require(value <= type(uint64).max, "SafeCast: value doesn't fit in 64 bits");
return uint64(value);
}
/**
* @dev Returns the downcasted uint32 from uint256, reverting on
* overflow (when the input is greater than largest uint32).
*
* Counterpart to Solidity's `uint32` operator.
*
* Requirements:
*
* - input must fit into 32 bits
*/
function toUint32(uint256 value) internal pure returns (uint32) {
require(value <= type(uint32).max, "SafeCast: value doesn't fit in 32 bits");
return uint32(value);
}
/**
* @dev Returns the downcasted uint16 from uint256, reverting on
* overflow (when the input is greater than largest uint16).
*
* Counterpart to Solidity's `uint16` operator.
*
* Requirements:
*
* - input must fit into 16 bits
*/
function toUint16(uint256 value) internal pure returns (uint16) {
require(value <= type(uint16).max, "SafeCast: value doesn't fit in 16 bits");
return uint16(value);
}
/**
* @dev Returns the downcasted uint8 from uint256, reverting on
* overflow (when the input is greater than largest uint8).
*
* Counterpart to Solidity's `uint8` operator.
*
* Requirements:
*
* - input must fit into 8 bits.
*/
function toUint8(uint256 value) internal pure returns (uint8) {
require(value <= type(uint8).max, "SafeCast: value doesn't fit in 8 bits");
return uint8(value);
}
/**
* @dev Converts a signed int256 into an unsigned uint256.
*
* Requirements:
*
* - input must be greater than or equal to 0.
*/
function toUint256(int256 value) internal pure returns (uint256) {
require(value >= 0, "SafeCast: value must be positive");
return uint256(value);
}
/**
* @dev Returns the downcasted int128 from int256, reverting on
* overflow (when the input is less than smallest int128 or
* greater than largest int128).
*
* Counterpart to Solidity's `int128` operator.
*
* Requirements:
*
* - input must fit into 128 bits
*
* _Available since v3.1._
*/
function toInt128(int256 value) internal pure returns (int128) {
require(value >= type(int128).min && value <= type(int128).max, "SafeCast: value doesn't fit in 128 bits");
return int128(value);
}
/**
* @dev Returns the downcasted int64 from int256, reverting on
* overflow (when the input is less than smallest int64 or
* greater than largest int64).
*
* Counterpart to Solidity's `int64` operator.
*
* Requirements:
*
* - input must fit into 64 bits
*
* _Available since v3.1._
*/
function toInt64(int256 value) internal pure returns (int64) {
require(value >= type(int64).min && value <= type(int64).max, "SafeCast: value doesn't fit in 64 bits");
return int64(value);
}
/**
* @dev Returns the downcasted int32 from int256, reverting on
* overflow (when the input is less than smallest int32 or
* greater than largest int32).
*
* Counterpart to Solidity's `int32` operator.
*
* Requirements:
*
* - input must fit into 32 bits
*
* _Available since v3.1._
*/
function toInt32(int256 value) internal pure returns (int32) {
require(value >= type(int32).min && value <= type(int32).max, "SafeCast: value doesn't fit in 32 bits");
return int32(value);
}
/**
* @dev Returns the downcasted int16 from int256, reverting on
* overflow (when the input is less than smallest int16 or
* greater than largest int16).
*
* Counterpart to Solidity's `int16` operator.
*
* Requirements:
*
* - input must fit into 16 bits
*
* _Available since v3.1._
*/
function toInt16(int256 value) internal pure returns (int16) {
require(value >= type(int16).min && value <= type(int16).max, "SafeCast: value doesn't fit in 16 bits");
return int16(value);
}
/**
* @dev Returns the downcasted int8 from int256, reverting on
* overflow (when the input is less than smallest int8 or
* greater than largest int8).
*
* Counterpart to Solidity's `int8` operator.
*
* Requirements:
*
* - input must fit into 8 bits.
*
* _Available since v3.1._
*/
function toInt8(int256 value) internal pure returns (int8) {
require(value >= type(int8).min && value <= type(int8).max, "SafeCast: value doesn't fit in 8 bits");
return int8(value);
}
/**
* @dev Converts an unsigned uint256 into a signed int256.
*
* Requirements:
*
* - input must be less than or equal to maxInt256.
*/
function toInt256(uint256 value) internal pure returns (int256) {
// Note: Unsafe cast below is okay because `type(int256).max` is guaranteed to be positive
require(value <= uint256(type(int256).max), "SafeCast: value doesn't fit in an int256");
return int256(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/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/Timers.sol)
pragma solidity ^0.8.0;
/**
* @dev Tooling for timepoints, timers and delays
*/
library Timers {
struct Timestamp {
uint64 _deadline;
}
function getDeadline(Timestamp memory timer) internal pure returns (uint64) {
return timer._deadline;
}
function setDeadline(Timestamp storage timer, uint64 timestamp) internal {
timer._deadline = timestamp;
}
function reset(Timestamp storage timer) internal {
timer._deadline = 0;
}
function isUnset(Timestamp memory timer) internal pure returns (bool) {
return timer._deadline == 0;
}
function isStarted(Timestamp memory timer) internal pure returns (bool) {
return timer._deadline > 0;
}
function isPending(Timestamp memory timer) internal view returns (bool) {
return timer._deadline > block.timestamp;
}
function isExpired(Timestamp memory timer) internal view returns (bool) {
return isStarted(timer) && timer._deadline <= block.timestamp;
}
struct BlockNumber {
uint64 _deadline;
}
function getDeadline(BlockNumber memory timer) internal pure returns (uint64) {
return timer._deadline;
}
function setDeadline(BlockNumber storage timer, uint64 timestamp) internal {
timer._deadline = timestamp;
}
function reset(BlockNumber storage timer) internal {
timer._deadline = 0;
}
function isUnset(BlockNumber memory timer) internal pure returns (bool) {
return timer._deadline == 0;
}
function isStarted(BlockNumber memory timer) internal pure returns (bool) {
return timer._deadline > 0;
}
function isPending(BlockNumber memory timer) internal view returns (bool) {
return timer._deadline > block.number;
}
function isExpired(BlockNumber memory timer) internal view returns (bool) {
return isStarted(timer) && timer._deadline <= block.number;
}
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v4.5.0) (governance/IGovernor.sol)
pragma solidity ^0.8.0;
import "../utils/introspection/ERC165.sol";
/**
* @dev Interface of the {Governor} core.
*
* _Available since v4.3._
*/
abstract contract IGovernor is IERC165 {
enum ProposalState {
Pending,
Active,
Canceled,
Defeated,
Succeeded,
Queued,
Expired,
Executed
}
/**
* @dev Emitted when a proposal is created.
*/
event ProposalCreated(
uint256 proposalId,
address proposer,
address[] targets,
uint256[] values,
string[] signatures,
bytes[] calldatas,
uint256 startBlock,
uint256 endBlock,
string description
);
/**
* @dev Emitted when a proposal is canceled.
*/
event ProposalCanceled(uint256 proposalId);
/**
* @dev Emitted when a proposal is executed.
*/
event ProposalExecuted(uint256 proposalId);
/**
* @dev Emitted when a vote is cast.
*
* Note: `support` values should be seen as buckets. There interpretation depends on the voting module used.
*/
event VoteCast(address indexed voter, uint256 proposalId, uint8 support, uint256 weight, string reason);
/**
* @notice module:core
* @dev Name of the governor instance (used in building the ERC712 domain separator).
*/
function name() public view virtual returns (string memory);
/**
* @notice module:core
* @dev Version of the governor instance (used in building the ERC712 domain separator). Default: "1"
*/
function version() public view virtual returns (string memory);
/**
* @notice module:voting
* @dev A description of the possible `support` values for {castVote} and the way these votes are counted, meant to
* be consumed by UIs to show correct vote options and interpret the results. The string is a URL-encoded sequence of
* key-value pairs that each describe one aspect, for example `support=bravo&quorum=for,abstain`.
*
* There are 2 standard keys: `support` and `quorum`.
*
* - `support=bravo` refers to the vote options 0 = Against, 1 = For, 2 = Abstain, as in `GovernorBravo`.
* - `quorum=bravo` means that only For votes are counted towards quorum.
* - `quorum=for,abstain` means that both For and Abstain votes are counted towards quorum.
*
* NOTE: The string can be decoded by the standard
* https://developer.mozilla.org/en-US/docs/Web/API/URLSearchParams[`URLSearchParams`]
* JavaScript class.
*/
// solhint-disable-next-line func-name-mixedcase
function COUNTING_MODE() public pure virtual returns (string memory);
/**
* @notice module:core
* @dev Hashing function used to (re)build the proposal id from the proposal details..
*/
function hashProposal(
address[] calldata targets,
uint256[] calldata values,
bytes[] calldata calldatas,
bytes32 descriptionHash
) public pure virtual returns (uint256);
/**
* @notice module:core
* @dev Current state of a proposal, following Compound's convention
*/
function state(uint256 proposalId) public view virtual returns (ProposalState);
/**
* @notice module:core
* @dev Block number used to retrieve user's votes and quorum. As per Compound's Comp and OpenZeppelin's
* ERC20Votes, the snapshot is performed at the end of this block. Hence, voting for this proposal starts at the
* beginning of the following block.
*/
function proposalSnapshot(uint256 proposalId) public view virtual returns (uint256);
/**
* @notice module:core
* @dev Block number at which votes close. Votes close at the end of this block, so it is possible to cast a vote
* during this block.
*/
function proposalDeadline(uint256 proposalId) public view virtual returns (uint256);
/**
* @notice module:user-config
* @dev Delay, in number of block, between the proposal is created and the vote starts. This can be increassed to
* leave time for users to buy voting power, of delegate it, before the voting of a proposal starts.
*/
function votingDelay() public view virtual returns (uint256);
/**
* @notice module:user-config
* @dev Delay, in number of blocks, between the vote start and vote ends.
*
* NOTE: The {votingDelay} can delay the start of the vote. This must be considered when setting the voting
* duration compared to the voting delay.
*/
function votingPeriod() public view virtual returns (uint256);
/**
* @notice module:user-config
* @dev Minimum number of cast voted required for a proposal to be successful.
*
* Note: The `blockNumber` parameter corresponds to the snaphot used for counting vote. This allows to scale the
* quroum depending on values such as the totalSupply of a token at this block (see {ERC20Votes}).
*/
function quorum(uint256 blockNumber) public view virtual returns (uint256);
/**
* @notice module:reputation
* @dev Voting power of an `account` at a specific `blockNumber`.
*
* Note: this can be implemented in a number of ways, for example by reading the delegated balance from one (or
* multiple), {ERC20Votes} tokens.
*/
function getVotes(address account, uint256 blockNumber) public view virtual returns (uint256);
/**
* @notice module:voting
* @dev Returns weither `account` has cast a vote on `proposalId`.
*/
function hasVoted(uint256 proposalId, address account) public view virtual returns (bool);
/**
* @dev Create a new proposal. Vote start {IGovernor-votingDelay} blocks after the proposal is created and ends
* {IGovernor-votingPeriod} blocks after the voting starts.
*
* Emits a {ProposalCreated} event.
*/
function propose(
address[] memory targets,
uint256[] memory values,
bytes[] memory calldatas,
string memory description
) public virtual returns (uint256 proposalId);
/**
* @dev Execute a successful proposal. This requires the quorum to be reached, the vote to be successful, and the
* deadline to be reached.
*
* Emits a {ProposalExecuted} event.
*
* Note: some module can modify the requirements for execution, for example by adding an additional timelock.
*/
function execute(
address[] memory targets,
uint256[] memory values,
bytes[] memory calldatas,
bytes32 descriptionHash
) public payable virtual returns (uint256 proposalId);
/**
* @dev Cast a vote
*
* Emits a {VoteCast} event.
*/
function castVote(uint256 proposalId, uint8 support) public virtual returns (uint256 balance);
/**
* @dev Cast a vote with a reason
*
* Emits a {VoteCast} event.
*/
function castVoteWithReason(
uint256 proposalId,
uint8 support,
string calldata reason
) public virtual returns (uint256 balance);
/**
* @dev Cast a vote using the user cryptographic signature.
*
* Emits a {VoteCast} event.
*/
function castVoteBySig(
uint256 proposalId,
uint8 support,
uint8 v,
bytes32 r,
bytes32 s
) public virtual returns (uint256 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 (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 (last updated v4.5.0) (governance/utils/IVotes.sol)
pragma solidity ^0.8.0;
/**
* @dev Common interface for {ERC20Votes}, {ERC721Votes}, and other {Votes}-enabled contracts.
*
* _Available since v4.5._
*/
interface IVotes {
/**
* @dev Emitted when an account changes their delegate.
*/
event DelegateChanged(address indexed delegator, address indexed fromDelegate, address indexed toDelegate);
/**
* @dev Emitted when a token transfer or delegate change results in changes to a delegate's number of votes.
*/
event DelegateVotesChanged(address indexed delegate, uint256 previousBalance, uint256 newBalance);
/**
* @dev Returns the current amount of votes that `account` has.
*/
function getVotes(address account) external view returns (uint256);
/**
* @dev Returns the amount of votes that `account` had at the end of a past block (`blockNumber`).
*/
function getPastVotes(address account, uint256 blockNumber) external view returns (uint256);
/**
* @dev Returns the total supply of votes available at the end of a past block (`blockNumber`).
*
* NOTE: This value is the sum of all available votes, which is not necessarily the sum of all delegated votes.
* Votes that have not been delegated are still part of total supply, even though they would not participate in a
* vote.
*/
function getPastTotalSupply(uint256 blockNumber) external view returns (uint256);
/**
* @dev Returns the delegate that `account` has chosen.
*/
function delegates(address account) external view returns (address);
/**
* @dev Delegates votes from the sender to `delegatee`.
*/
function delegate(address delegatee) external;
/**
* @dev Delegates votes from signer to `delegatee`.
*/
function delegateBySig(
address delegatee,
uint256 nonce,
uint256 expiry,
uint8 v,
bytes32 r,
bytes32 s
) external;
} | * @dev Update the voting period. This operation can only be performed through a governance proposal. Emits a {VotingPeriodSet} event./ | function setVotingPeriod(uint256 newVotingPeriod) public virtual onlyGovernance {
_setVotingPeriod(newVotingPeriod);
}
| 42,136 | [
1,
1891,
326,
331,
17128,
3879,
18,
1220,
1674,
848,
1338,
506,
9591,
3059,
279,
314,
1643,
82,
1359,
14708,
18,
7377,
1282,
279,
288,
58,
17128,
5027,
694,
97,
871,
18,
19,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
565,
445,
444,
58,
17128,
5027,
12,
11890,
5034,
394,
58,
17128,
5027,
13,
1071,
5024,
1338,
43,
1643,
82,
1359,
288,
203,
3639,
389,
542,
58,
17128,
5027,
12,
2704,
58,
17128,
5027,
1769,
203,
565,
289,
203,
203,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
] |
/*
* Abstract Continuous Sale Smart Contract.
* Copyright © 2017 by ABDK Consulting.
* Author: Mikhail Vladimirov <[email protected]>
*/
pragma solidity ^0.4.11;
import "./SafeMath.sol";
/**
* Abstract base class for Ethereum smart contracts that implement continuous
* sale auction for some assets.
*/
contract AbstractContinuousSale is SafeMath {
/**
* Place buy-side order at given price. Value sent within transaction should
* be factor of given price and order amount is calculated as msg.value/price.
*
* @param _price order price
* @return true on success, false on error
*/
function placeOrder (uint256 _price) payable returns (bool success) {
if (msg.sender == 0) revert ();
if (msg.value == 0) revert ();
if (_price == 0) revert ();
uint256 amount = msg.value / _price;
if (msg.value != safeMul (amount, _price)) revert ();
Order storage newOrder = orders [msg.sender];
if (newOrder.amount != 0) revert ();
executeSale ();
newOrder.amount = amount;
newOrder.price = _price;
newOrder.totalRemainingAmount = amount;
newOrder.totalRemainingValue = msg.value;
newOrder.height = 1;
if (rootOrder == 0) rootOrder = msg.sender;
else {
address node = rootOrder;
while (true) {
Order storage order = orders [node];
if (order.price >= _price) {
address left = order.left;
if (left == 0) {
order.left = msg.sender;
break;
} else node = left;
} else {
address right = order.right;
if (right == 0) {
order.right = msg.sender;
break;
} else node = right;
}
}
newOrder.parent = node;
updateAndRebalance (node, amount, msg.value);
}
OrderPlacement (msg.sender, amount, _price);
return true;
}
/**
* Terminate order previously placed by msg.sender.
*
* @return true on success, false on error
*/
function terminateOrder () returns (bool success) {
if (msg.sender == 0) return false;
Order storage order = orders [msg.sender];
uint256 amount = order.amount;
if (amount == 0) return false; // No such order
executeSale ();
bool wasInTree = isInTree (msg.sender);
uint256 filledAmount;
if (wasInTree) {// Our order is still in tree
removeNode (msg.sender, order);
filledAmount = order.filledAmount;
OrderTermination (msg.sender, filledAmount);
} else if (order.height > 0) {// Our order is not yet terminated
order.filledAmount = amount;
filledAmount = amount;
OrderTermination (msg.sender, filledAmount);
} else { // Order already terminated
filledAmount = order.filledAmount;
}
order.parent = 0;
order.left = 0;
order.right = 0;
order.totalRemainingAmount = 0;
order.totalRemainingValue = 0;
order.height = 0;
success = true;
if (filledAmount > 0) { // Somewhat filled
if (sendAssets (msg.sender, filledAmount)) {
amount = safeSub (amount, filledAmount);
order.amount = amount;
filledAmount = 0;
order.filledAmount = 0;
} else success = false;
}
if (filledAmount < amount) { // Not fully filled
uint256 refund = safeMul (order.price, safeSub (amount, filledAmount));
if (msg.sender.send (refund)) {
order.amount = filledAmount;
order.price = 0;
if (!wasInTree)
pendingRefund = safeSub (pendingRefund, refund);
} else {
success = false;
if (wasInTree)
pendingRefund = safeAdd (pendingRefund, refund);
}
} else order.price = 0;
}
/**
* Get outstanding sale revenue.
*
* @param _currentTime current time
* @return outstanding sale revenue
*/
function outstandingRevenue (uint256 _currentTime)
constant returns (uint256 result) {
address node = rootOrder;
if (node == 0) result = this.balance; // No orders
else {
Order storage nodeOrder = orders [node];
uint256 toSell = safeSub (amountToSellBy (_currentTime), soldAmount);
if (nodeOrder.totalRemainingAmount <= toSell)
result = this.balance; // All orders are actually filled
else {
result = safeSub (this.balance, nodeOrder.totalRemainingValue);
if (toSell > 0) {
while (true) {
address right = nodeOrder.right;
if (right != 0) {
Order storage rightOrder = orders [right];
uint256 rightTotalRemainingAmount = rightOrder.totalRemainingAmount;
if (rightTotalRemainingAmount <= toSell) {
// Right subtree is actually filled
result = safeAdd (result, rightOrder.totalRemainingValue);
toSell = safeSub (toSell, rightTotalRemainingAmount);
} else {
node = right;
nodeOrder = rightOrder;
continue;
}
}
uint256 remainingAmount = safeSub (
nodeOrder.amount, nodeOrder.filledAmount);
if (remainingAmount <= toSell) {
// Order is actually filled
result = safeAdd (
result, safeMul (nodeOrder.price, remainingAmount));
toSell = safeSub (toSell, remainingAmount);
} else {
// Order is partially filled
result = safeAdd (result, safeMul (nodeOrder.price, toSell));
break;
}
node = nodeOrder.left;
nodeOrder = orders [node];
}
}
}
}
result = safeSub (result, pendingRefund);
}
/**
* Get status of order.
*
* @param _orderCreator address of the created of the order to get status for
* @param _currentTime current time
* @return order status
*/
function orderStatus (address _orderCreator, uint256 _currentTime)
constant returns (
bool active, uint256 amount, uint256 price, uint256 filledAmount) {
if (_orderCreator == 0) {
active = false;
return;
}
Order storage order = orders [_orderCreator];
if (order.amount == 0) { // No such order
active = false;
return;
}
if (isInTree (_orderCreator)) {
uint256 toSell = safeSub (amountToSellBy (_currentTime), soldAmount);
if (toSell > 0) {
uint256 rightAmount = 0;
address right = order.right;
if (right != 0)
rightAmount = safeAdd (
rightAmount, orders [right].totalRemainingAmount);
address node = _orderCreator;
Order storage nodeOrder = order;
bool leftChild = false;
while (true) {
if (leftChild) {
rightAmount = safeAdd (
rightAmount, safeSub (nodeOrder.amount, nodeOrder.filledAmount));
right = nodeOrder.right;
if (right != 0)
rightAmount = safeAdd (
rightAmount, orders [right].totalRemainingAmount);
}
address parent = nodeOrder.parent;
if (parent == 0) break;
nodeOrder = orders [parent];
leftChild = nodeOrder.left == node;
node = parent;
}
if (rightAmount >= toSell) toSell = 0;
else toSell = safeSub (toSell, rightAmount);
}
active = true;
amount = order.amount;
price = order.price;
filledAmount = order.filledAmount;
if (safeSub (amount, filledAmount) > toSell)
filledAmount = safeAdd (filledAmount, toSell);
else filledAmount = amount;
return;
} else if (order.height == 0) { // Order already terminated
active = false;
amount = order.amount;
price = order.price;
filledAmount = order.filledAmount;
return;
} else { // Order is not yet terminated, but is fully filled
active = true;
amount = order.amount;
price = order.price;
filledAmount = amount; // Ignore order.filledAmount
return;
}
}
/**
* Get total remaining amount of all active orders with price greater or
* equal to given price.
*
* @param _price price to return total remaining amount of all active orders
* with price greater or equal to
* @param _currentTime current time
* @return total remaining amount of all active orders with price greater or
* equal to given price
*/
function totalAmountForPrice (uint256 _price, uint256 _currentTime)
constant returns (uint256 result) {
result = 0;
address node = rootOrder;
while (node != 0) {
Order storage nodeOrder = orders [node];
if (_price <= nodeOrder.price) {
address right = nodeOrder.right;
if (right != 0)
result = safeAdd (result, orders [right].totalRemainingAmount);
result = safeAdd (
result, safeSub (nodeOrder.amount, nodeOrder.filledAmount));
node = nodeOrder.left;
} else node = nodeOrder.right;
}
uint256 toSell = safeSub (amountToSellBy (_currentTime), soldAmount);
if (result <= toSell) return 0;
else result = safeSub (result, toSell);
}
/**
* Get total amount of assets sold so far.
*
* @param _currentTime current time
* @return total amount of assets sold so far
*/
function totalSold (uint256 _currentTime)
constant returns (uint256 result) {
result = soldAmount;
uint256 toSell = safeSub (amountToSellBy (_currentTime), result);
if (toSell > 0 && rootOrder != 0) {
uint256 totalRemainingAmount = orders [rootOrder].totalRemainingAmount;
if (toSell <= totalRemainingAmount)
result = safeAdd (result, toSell);
else
result = safeAdd (result, totalRemainingAmount);
}
}
/**
* Calculate maximum amount of assets to be sold by given time.
*
* @param _time time to calculate maximum amount of assets to be sole by
* @return maximum amount of assets to be sold by given time
*/
function amountToSellBy (uint256 _time)
public constant returns (uint256 amount);
/**
* Send given amount of assets to the owner of given address.
*
* @param _to address to send assets to the owner of
* @param _amount amount of assets to send
* @return true on success, false on error
*/
function sendAssets (address _to, uint256 _amount)
internal returns (bool success);
/**
* Remove given node from order tree.
*
* @param _node node to be removed
*/
function removeNode (address _node, Order storage _nodeOrder) private {
if (_node == 0) throw;
address right = _nodeOrder.right;
address left = _nodeOrder.left;
if (right == 0) { // No right subtree
replaceNode (_node, left);
updateAfterExecute (_nodeOrder.parent);
} else if (left == 0) { // No left subtree
replaceNode (_node, right);
updateAfterExecute (_nodeOrder.parent);
} else { // Both subtrees present
// Lets find next node
Order storage nextOrder = orders [right];
address p = right;
while (true) {
address l = nextOrder.left;
if (l == 0) break;
else {
p = l;
nextOrder = orders [l];
}
}
address nextOrderParent = nextOrder.parent;
replaceNode (p, nextOrder.right);
replaceNode (_node, p);
left = _nodeOrder.left;
if (left != 0)
orders [left].parent = p;
right = _nodeOrder.right;
if (right != 0)
orders [right].parent = p;
nextOrder.left = left;
nextOrder.right = right;
if (nextOrderParent == _node)
updateAfterExecute (p);
else
updateAfterExecute (nextOrderParent);
}
}
/**
* Checks whether given node is currently in order tree.
*
* @param _node node to check
* @return true is given node is in order tree, false otherwise
*/
function isInTree (address _node) private constant returns (bool result) {
if (_node == 0) return false;
if (rootOrder == 0) return false; // There is no orders
if (_node == rootOrder) return true;
Order storage nodeOrder = orders [_node];
while (true) {
address parent = nodeOrder.parent;
if (parent == 0) return false;
nodeOrder = orders [parent];
if (nodeOrder.left != _node && nodeOrder.right != _node) return false;
if (parent == rootOrder) return true;
_node = parent;
}
}
/**
* Replace node A with node B.
*
* | => |
* A B B A
*
* @param _a node A
* @param _b node B (may be zero)
*/
function replaceNode (address _a, address _b) private {
Order storage orderA = orders [_a];
address parent = orderA.parent;
if (parent == 0) rootOrder = _b;
else {
Order storage parentOrder = orders [parent];
if (parentOrder.left == _a) parentOrder.left = _b;
else if (parentOrder.right == _a) parentOrder.right = _b;
else throw;
}
if (_b != 0) orders [_b].parent = parent;
}
/**
* Execute orders that could be executed.
*/
function executeSale () private {
address node = rootOrder;
if (node == 0) return; // No orders
else {
uint256 toSell = safeSub (amountToSellBy (now), soldAmount);
if (toSell == 0) return; // Nothing to sell
Order storage nodeOrder = orders [node];
uint256 totalRemainingAmount = nodeOrder.totalRemainingAmount;
if (totalRemainingAmount <= toSell) {
// Execute all orders
soldAmount = safeAdd (soldAmount, totalRemainingAmount);
rootOrder = 0;
return;
} else {
while (true) {
address left = nodeOrder.left;
if (left != 0) {
Order storage leftOrder = orders [left];
uint256 leftTotalRemainingAmount = leftOrder.totalRemainingAmount;
uint256 nonLeftTotalRemainingAmount =
safeSub (totalRemainingAmount, leftTotalRemainingAmount);
if (nonLeftTotalRemainingAmount < toSell) {
toSell = safeSub (toSell, nonLeftTotalRemainingAmount);
soldAmount = safeAdd (soldAmount, nonLeftTotalRemainingAmount);
address right1 = nodeOrder.right;
if (right1 != 0) nodeOrder.right = 0;
nodeOrder.filledAmount = nodeOrder.amount;
node = left;
nodeOrder = leftOrder;
totalRemainingAmount = leftTotalRemainingAmount;
continue;
}
}
address right2 = nodeOrder.right;
if (right2 != 0) {
Order storage rightOrder = orders [right2];
uint256 rightTotalRemainingAmount = rightOrder.totalRemainingAmount;
if (rightTotalRemainingAmount >= toSell) {
node = right2;
nodeOrder = rightOrder;
totalRemainingAmount = rightTotalRemainingAmount;
continue;
} else {
toSell = safeSub (toSell, rightTotalRemainingAmount);
soldAmount = safeAdd (soldAmount, rightTotalRemainingAmount);
nodeOrder.right = 0;
}
}
nodeOrder.filledAmount = safeAdd (nodeOrder.filledAmount, toSell);
soldAmount = safeAdd (soldAmount, toSell);
break;
}
updateAfterExecute (node);
}
}
}
/**
* Update aggregates on given node and all its ancestors.
*
* @param _node node to update along with its ancestors
*/
function updateAfterExecute (address _node) private {
while (_node != 0) {
Order storage nodeOrder = orders [_node];
uint256 height;
uint256 totalRemainingAmount =
safeSub (nodeOrder.amount, nodeOrder.filledAmount);
uint256 totalRemainingValue = totalRemainingAmount * nodeOrder.price;
address left = nodeOrder.left;
if (left != 0) {
Order storage leftOrder = orders [left];
height = safeAdd (leftOrder.height, 1);
totalRemainingAmount =
safeAdd (totalRemainingAmount, leftOrder.totalRemainingAmount);
totalRemainingValue =
safeAdd (totalRemainingValue, leftOrder.totalRemainingValue);
} else height = 1;
address right = nodeOrder.right;
if (right != 0) {
Order storage rightOrder = orders [right];
height = max (height, safeAdd (rightOrder.height, 1));
totalRemainingAmount =
safeAdd (totalRemainingAmount, rightOrder.totalRemainingAmount);
totalRemainingValue =
safeAdd (totalRemainingValue, rightOrder.totalRemainingValue);
}
nodeOrder.height = height;
nodeOrder.totalRemainingAmount = totalRemainingAmount;
nodeOrder.totalRemainingValue = totalRemainingValue;
_node = nodeOrder.parent;
}
}
/**
* Update aggregated values in given tree node and all its ancestors and
* rebalance tree if necessary.
*
* @param _node node to be updated along with its ancestors
* @param _extraAmount amount to add to this node and all its ancestors
* @param _extraValue value to add to this node and all its ancestors
*/
function updateAndRebalance (
address _node, uint256 _extraAmount, uint256 _extraValue)
private {
if (_node == 0) throw;
Order storage nodeOrder = orders [_node];
while (true) {
address left = nodeOrder.left;
address right = nodeOrder.right;
nodeOrder.height = safeAdd (
max (getHeight (left), getHeight (right)), 1);
nodeOrder.totalRemainingAmount = safeAdd (
nodeOrder.totalRemainingAmount, _extraAmount);
nodeOrder.totalRemainingValue = safeAdd (
nodeOrder.totalRemainingValue, _extraValue);
address parent = nodeOrder.parent;
address rebalanced = rebalance (_node);
if (parent != 0) {
nodeOrder = orders [parent];
if (_node != rebalanced) {
if (_node == nodeOrder.left)
nodeOrder.left = rebalanced;
else if (_node == nodeOrder.right)
nodeOrder.right = rebalanced;
}
_node = parent;
} else {
if (_node != rebalanced) rootOrder = rebalanced;
break;
}
}
}
/**
* Rebalance given tree node if necessary.
*
* @param _node tree node to rebalance
* @return rebalanced tree node
*/
function rebalance (address _node) private returns (address rebalanced) {
if (_node == 0) throw;
Order storage nodeOrder = orders [_node];
address left = nodeOrder.left;
address right = nodeOrder.right;
if (left == 0) {
if (right == 0) return _node;
else {
Order storage rightOrder1 = orders [right];
uint256 rightHeight1 = rightOrder1.height;
if (rightHeight1 > 1)
return chooseRotate (
true,
_node, nodeOrder,
right, rightOrder1,
0);
else return _node;
}
} else {
Order storage leftOrder = orders [left];
uint256 leftHeight = leftOrder.height;
if (right == 0) {
if (leftHeight > 1)
return chooseRotate (
false,
_node, nodeOrder,
left, leftOrder,
0);
else return _node;
}
else {
Order storage rightOrder2 = orders [right];
uint256 rightHeight2 = rightOrder2.height;
if (safeAdd (leftHeight, 1) < rightHeight2)
return chooseRotate (
true,
_node, nodeOrder,
right, rightOrder2,
leftHeight);
else if (leftHeight > safeAdd (rightHeight2, 1))
return chooseRotate (
false,
_node, nodeOrder,
left, leftOrder,
rightHeight2);
else return _node;
}
}
}
/**
* Choose appropriate rotation type, either ordinary or big rotation.
*
* Left
*
* A
* / \
* 1 B
*
* Right
*
* A
* / \
* B 1
*
* @param _left true to choose left rotation type, false to choose right
* rotation type
* @param _a node A
* @param _orderA order A
* @param _b node B
* @param _orderB order B
* @param _height1 height of subtree 1
* @return rotated node
*/
function chooseRotate (
bool _left,
address _a, Order storage _orderA,
address _b, Order storage _orderB,
uint256 _height1) private returns (address rotated) {
address c = _left ? _orderB.left : _orderB.right;
if (c == 0) {
rotate (
_left,
_a, _orderA,
_b, _orderB,
0, _orderA, // Order C parameter is not used anyway
_height1);
return _b;
} else {
Order storage orderC = orders [c];
if (_height1 < orderC.height) {
bigRotate (
_left,
_a, _orderA,
_b, _orderB,
c, orderC,
_height1);
return c;
} else {
rotate (
_left,
_a, _orderA,
_b, _orderB,
c, orderC,
_height1);
return _b;
}
}
}
/**
* Rotate tree either left or right:
*
* Left
* A B
* / \ / \
* 1 B ==> A 2
* / \ / \
* C 2 1 C
*
* Right
* A B
* / \ / \
* B 1 ==> 2 A
* / \ / \
* 2 C C 1
*
* @param _left true to rotate left, false to rotate right
* @param _a node A
* @param _orderA order A
* @param _b node B
* @param _orderB order B
* @param _c node C (may be zero)
* @param _orderC order C (undefined is _c is zero)
* @param _height1 height of subtree 1
*/
function rotate (
bool _left,
address _a, Order storage _orderA,
address _b, Order storage _orderB,
address _c, Order storage _orderC,
uint256 _height1) private {
// Adjust parents
_orderB.parent = _orderA.parent;
_orderA.parent = _b;
if (_c != 0)
_orderC.parent = _a;
// Adjust links
if (_left) {
_orderA.right = _c;
_orderB.left = _a;
} else {
_orderA.left = _c;
_orderB.right = _a;
}
// Adjust aggregates
uint256 _totalRemainingAmountA = _orderA.totalRemainingAmount;
uint256 _totalRemainingValueA = _orderA.totalRemainingValue;
_orderA.totalRemainingAmount = safeAdd (
safeSub (_totalRemainingAmountA, _orderB.totalRemainingAmount),
_c == 0 ? 0 : _orderC.totalRemainingAmount);
_orderA.totalRemainingValue = safeAdd (
safeSub (_totalRemainingValueA, _orderB.totalRemainingValue),
_c == 0 ? 0 : _orderC.totalRemainingValue);
_orderB.totalRemainingAmount = _totalRemainingAmountA;
_orderB.totalRemainingValue = _totalRemainingValueA;
// Adjust heights
_orderA.height = safeAdd (_height1, 1);
}
/**
* Perform big tree rotation either left or right.
*
* Left
* A
* / \ C
* 1 B / \
* / \ ==> A B
* C 4 / \ / \
* / \ 1 2 3 4
* 2 3
*
* Right
* A
* / \ C
* B 1 / \
* / \ ==> B A
* 4 C / \ / \
* / \ 4 3 2 1
* 3 2
*
* @param _left true to rotate left, false to rotate right
* @param _a node A
* @param _orderA order A
* @param _b node B
* @param _orderB order B
* @param _c node C
* @param _orderC order C
* @param _height1 height of subtree 1
*/
function bigRotate (
bool _left,
address _a, Order storage _orderA,
address _b, Order storage _orderB,
address _c, Order storage _orderC,
uint256 _height1) private {
address subtree2 = _left ? _orderC.left : _orderC.right;
Order storage subtree2Order;
if (subtree2 != 0) subtree2Order = orders [subtree2];
address subtree3 = _left ? _orderC.right : _orderC.left;
Order storage subtree3Order;
if (subtree3 != 0) subtree3Order = orders [subtree3];
address subtree4 = _left ? _orderB.right: _orderB.left;
// Adjust parents
_orderC.parent = _orderA.parent;
_orderA.parent = _c;
_orderB.parent = _c;
if (subtree2 != 0) subtree2Order.parent = _a;
if (subtree3 != 0) subtree3Order.parent = _b;
// Adjust links
if (_left) {
_orderC.left = _a;
_orderC.right = _b;
_orderA.right = subtree2;
_orderB.left = subtree3;
} else {
_orderC.right = _a;
_orderC.left = _b;
_orderA.left = subtree2;
_orderB.right = subtree3;
}
adjustAggregates (
_orderA, _orderB, _orderC,
subtree2 == 0 ? 0 : subtree2Order.totalRemainingAmount,
subtree2 == 0 ? 0 : subtree2Order.totalRemainingValue,
subtree3 == 0 ? 0 : subtree3Order.totalRemainingAmount,
subtree3 == 0 ? 0 : subtree3Order.totalRemainingValue);
adjustHeights (
_orderA, _orderB, _orderC,
_height1,
subtree2 == 0 ? 0 : subtree2Order.height,
subtree3 == 0 ? 0 : subtree3Order.height,
subtree4 == 0 ? 0 : orders [subtree4].height);
}
/**
* Adjust aggregates for orders A, B and C.after big rotation.
*
* A
* / \ C
* 1 B / \
* / \ ==> A B
* C 4 / \ / \
* / \ 1 2 3 4
* 2 3
*
* or
*
* A
* / \ C
* B 1 / \
* / \ ==> B A
* 4 C / \ / \
* / \ 4 3 2 1
* 3 2
*
* @param _orderA order A
* @param _orderB order B
* @param _orderC order C
* @param _totalRemainingAmount2 total remaining amount of subtree 2
* @param _totalRemainingValue2 total remaining value of subtree 2
* @param _totalRemainingAmount3 total remaining amount of subtree 3
* @param _totalRemainingValue3 total remaining value of subtree 3
*/
function adjustAggregates (
Order storage _orderA, Order storage _orderB, Order storage _orderC,
uint256 _totalRemainingAmount2, uint256 _totalRemainingValue2,
uint256 _totalRemainingAmount3, uint256 _totalRemainingValue3)
private {
uint256 _totalRemainingAmountA = _orderA.totalRemainingAmount;
uint256 _totalRemainingValueA = _orderA.totalRemainingValue;
_orderA.totalRemainingAmount = safeAdd (
safeSub (_orderA.totalRemainingAmount, _orderB.totalRemainingAmount),
_totalRemainingAmount2);
_orderA.totalRemainingValue = safeAdd (
safeSub (_orderA.totalRemainingValue, _orderB.totalRemainingValue),
_totalRemainingValue2);
_orderB.totalRemainingAmount = safeAdd (
safeSub (_orderB.totalRemainingAmount, _orderC.totalRemainingAmount),
_totalRemainingAmount3);
_orderB.totalRemainingValue = safeAdd (
safeSub (_orderB.totalRemainingValue, _orderC.totalRemainingValue),
_totalRemainingValue3);
_orderC.totalRemainingAmount = _totalRemainingAmountA;
_orderC.totalRemainingValue = _totalRemainingValueA;
}
/**
* Adjust heights or orders A, B and C after big rotation.
*
* C C
* / \ or / \
* A B B A
* / \ / \ / \ / \
* 1 2 3 4 4 3 2 1
*
* @param _orderA order A to adjust height of
* @param _orderB order B to adjust height of
* @param _orderC order C to adjust height of
* @param _height1 height of subtree 1
* @param _height2 height of subtree 2
* @param _height3 height of subtree 3
* @param _height4 height of subtree 4
*/
function adjustHeights (
Order storage _orderA, Order storage _orderB, Order storage _orderC,
uint256 _height1, uint256 _height2, uint256 _height3, uint256 _height4)
private {
_orderC.height = safeAdd (
max (
(_orderA.height = safeAdd (max (_height1, _height2), 1)),
(_orderB.height = safeAdd (max (_height3, _height4), 1))),
1);
}
/**
* Calculate maximum of two values.
*
* @param _x first value
* @param _y second value
* @return maximum of two values
*/
function max (uint256 _x, uint256 _y)
private constant returns (uint256 result) {
return _x > _y ? _x : _y;
}
/**
* Get height of tree node.
*
* @param _node tree node to get height of
* @return height of the given tree node
*
*/
function getHeight (address _node) private constant returns (uint256 height) {
return _node == 0 ? 0 : orders [_node].height;
}
/**
* Reference to a root order or zero is there are no orders.
*/
address rootOrder;
/**
* Mapping from address of order creator to current order from this creator.
*/
mapping (address => Order) orders;
/**
* Amount of assets sold so far.
*/
uint256 soldAmount;
/**
* Pending refund (in Wei) for inactive orders.
*/
uint256 pendingRefund = 0;
/**
* Encapsulates information about buy-side order.
*/
struct Order {
/**
* Amount of assets to buy.
*/
uint256 amount;
/**
* Price per asset unit (in Wei).
*/
uint256 price;
/**
* Amount of assets already bought.
*/
uint256 filledAmount;
/**
* Reference to parent order.
*/
address parent;
/**
* Reference to left subtree.
*/
address left;
/**
* Reference to right subtree.
*/
address right;
/**
* Total remaining amount in a subtree whose root is this order.
*/
uint256 totalRemainingAmount;
/**
* Total remaining value in a subtree whose root is this order.
*/
uint256 totalRemainingValue;
/**
* Height of the subtree whose root is this order.
*/
uint256 height;
}
/**
* Logged when new order was placed.
*
* @param creator address of the creator of the new order
* @param amount amount of the new order
* @param price price of the new order
*/
event OrderPlacement (
address indexed creator, uint256 amount, uint256 price);
/**
* Logged when order was terminated.
*
* @param creator address of the creator of terminated order
* @param filledAmount filled amount of the order
*/
event OrderTermination (
address indexed creator, uint256 filledAmount);
}
| * Abstract base class for Ethereum smart contracts that implement continuous sale auction for some assets./ | contract AbstractContinuousSale is SafeMath {
pragma solidity ^0.4.11;
function placeOrder (uint256 _price) payable returns (bool success) {
if (msg.sender == 0) revert ();
if (msg.value == 0) revert ();
if (_price == 0) revert ();
uint256 amount = msg.value / _price;
if (msg.value != safeMul (amount, _price)) revert ();
Order storage newOrder = orders [msg.sender];
if (newOrder.amount != 0) revert ();
executeSale ();
newOrder.amount = amount;
newOrder.price = _price;
newOrder.totalRemainingAmount = amount;
newOrder.totalRemainingValue = msg.value;
newOrder.height = 1;
if (rootOrder == 0) rootOrder = msg.sender;
else {
address node = rootOrder;
while (true) {
Order storage order = orders [node];
if (order.price >= _price) {
address left = order.left;
if (left == 0) {
order.left = msg.sender;
break;
} else node = left;
address right = order.right;
if (right == 0) {
order.right = msg.sender;
break;
} else node = right;
}
}
newOrder.parent = node;
updateAndRebalance (node, amount, msg.value);
}
OrderPlacement (msg.sender, amount, _price);
return true;
}
function placeOrder (uint256 _price) payable returns (bool success) {
if (msg.sender == 0) revert ();
if (msg.value == 0) revert ();
if (_price == 0) revert ();
uint256 amount = msg.value / _price;
if (msg.value != safeMul (amount, _price)) revert ();
Order storage newOrder = orders [msg.sender];
if (newOrder.amount != 0) revert ();
executeSale ();
newOrder.amount = amount;
newOrder.price = _price;
newOrder.totalRemainingAmount = amount;
newOrder.totalRemainingValue = msg.value;
newOrder.height = 1;
if (rootOrder == 0) rootOrder = msg.sender;
else {
address node = rootOrder;
while (true) {
Order storage order = orders [node];
if (order.price >= _price) {
address left = order.left;
if (left == 0) {
order.left = msg.sender;
break;
} else node = left;
address right = order.right;
if (right == 0) {
order.right = msg.sender;
break;
} else node = right;
}
}
newOrder.parent = node;
updateAndRebalance (node, amount, msg.value);
}
OrderPlacement (msg.sender, amount, _price);
return true;
}
function placeOrder (uint256 _price) payable returns (bool success) {
if (msg.sender == 0) revert ();
if (msg.value == 0) revert ();
if (_price == 0) revert ();
uint256 amount = msg.value / _price;
if (msg.value != safeMul (amount, _price)) revert ();
Order storage newOrder = orders [msg.sender];
if (newOrder.amount != 0) revert ();
executeSale ();
newOrder.amount = amount;
newOrder.price = _price;
newOrder.totalRemainingAmount = amount;
newOrder.totalRemainingValue = msg.value;
newOrder.height = 1;
if (rootOrder == 0) rootOrder = msg.sender;
else {
address node = rootOrder;
while (true) {
Order storage order = orders [node];
if (order.price >= _price) {
address left = order.left;
if (left == 0) {
order.left = msg.sender;
break;
} else node = left;
address right = order.right;
if (right == 0) {
order.right = msg.sender;
break;
} else node = right;
}
}
newOrder.parent = node;
updateAndRebalance (node, amount, msg.value);
}
OrderPlacement (msg.sender, amount, _price);
return true;
}
function placeOrder (uint256 _price) payable returns (bool success) {
if (msg.sender == 0) revert ();
if (msg.value == 0) revert ();
if (_price == 0) revert ();
uint256 amount = msg.value / _price;
if (msg.value != safeMul (amount, _price)) revert ();
Order storage newOrder = orders [msg.sender];
if (newOrder.amount != 0) revert ();
executeSale ();
newOrder.amount = amount;
newOrder.price = _price;
newOrder.totalRemainingAmount = amount;
newOrder.totalRemainingValue = msg.value;
newOrder.height = 1;
if (rootOrder == 0) rootOrder = msg.sender;
else {
address node = rootOrder;
while (true) {
Order storage order = orders [node];
if (order.price >= _price) {
address left = order.left;
if (left == 0) {
order.left = msg.sender;
break;
} else node = left;
address right = order.right;
if (right == 0) {
order.right = msg.sender;
break;
} else node = right;
}
}
newOrder.parent = node;
updateAndRebalance (node, amount, msg.value);
}
OrderPlacement (msg.sender, amount, _price);
return true;
}
function placeOrder (uint256 _price) payable returns (bool success) {
if (msg.sender == 0) revert ();
if (msg.value == 0) revert ();
if (_price == 0) revert ();
uint256 amount = msg.value / _price;
if (msg.value != safeMul (amount, _price)) revert ();
Order storage newOrder = orders [msg.sender];
if (newOrder.amount != 0) revert ();
executeSale ();
newOrder.amount = amount;
newOrder.price = _price;
newOrder.totalRemainingAmount = amount;
newOrder.totalRemainingValue = msg.value;
newOrder.height = 1;
if (rootOrder == 0) rootOrder = msg.sender;
else {
address node = rootOrder;
while (true) {
Order storage order = orders [node];
if (order.price >= _price) {
address left = order.left;
if (left == 0) {
order.left = msg.sender;
break;
} else node = left;
address right = order.right;
if (right == 0) {
order.right = msg.sender;
break;
} else node = right;
}
}
newOrder.parent = node;
updateAndRebalance (node, amount, msg.value);
}
OrderPlacement (msg.sender, amount, _price);
return true;
}
} else {
function placeOrder (uint256 _price) payable returns (bool success) {
if (msg.sender == 0) revert ();
if (msg.value == 0) revert ();
if (_price == 0) revert ();
uint256 amount = msg.value / _price;
if (msg.value != safeMul (amount, _price)) revert ();
Order storage newOrder = orders [msg.sender];
if (newOrder.amount != 0) revert ();
executeSale ();
newOrder.amount = amount;
newOrder.price = _price;
newOrder.totalRemainingAmount = amount;
newOrder.totalRemainingValue = msg.value;
newOrder.height = 1;
if (rootOrder == 0) rootOrder = msg.sender;
else {
address node = rootOrder;
while (true) {
Order storage order = orders [node];
if (order.price >= _price) {
address left = order.left;
if (left == 0) {
order.left = msg.sender;
break;
} else node = left;
address right = order.right;
if (right == 0) {
order.right = msg.sender;
break;
} else node = right;
}
}
newOrder.parent = node;
updateAndRebalance (node, amount, msg.value);
}
OrderPlacement (msg.sender, amount, _price);
return true;
}
function terminateOrder () returns (bool success) {
if (msg.sender == 0) return false;
Order storage order = orders [msg.sender];
uint256 amount = order.amount;
executeSale ();
bool wasInTree = isInTree (msg.sender);
uint256 filledAmount;
removeNode (msg.sender, order);
filledAmount = order.filledAmount;
OrderTermination (msg.sender, filledAmount);
order.filledAmount = amount;
filledAmount = amount;
OrderTermination (msg.sender, filledAmount);
filledAmount = order.filledAmount;
}
order.parent = 0;
order.left = 0;
order.right = 0;
order.totalRemainingAmount = 0;
order.totalRemainingValue = 0;
order.height = 0;
success = true;
if (sendAssets (msg.sender, filledAmount)) {
amount = safeSub (amount, filledAmount);
order.amount = amount;
filledAmount = 0;
order.filledAmount = 0;
} else success = false;
}
| 6,437,803 | [
1,
7469,
1026,
667,
364,
512,
18664,
379,
13706,
20092,
716,
2348,
17235,
272,
5349,
279,
4062,
364,
2690,
7176,
18,
19,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
16351,
4115,
26509,
30746,
353,
14060,
10477,
288,
203,
683,
9454,
18035,
560,
3602,
20,
18,
24,
18,
2499,
31,
203,
225,
445,
3166,
2448,
261,
11890,
5034,
389,
8694,
13,
8843,
429,
1135,
261,
6430,
2216,
13,
288,
203,
565,
309,
261,
3576,
18,
15330,
422,
374,
13,
15226,
261,
1769,
203,
565,
309,
261,
3576,
18,
1132,
422,
374,
13,
15226,
261,
1769,
203,
565,
309,
261,
67,
8694,
422,
374,
13,
15226,
261,
1769,
203,
203,
565,
2254,
5034,
3844,
273,
1234,
18,
1132,
342,
389,
8694,
31,
203,
565,
309,
261,
3576,
18,
1132,
480,
4183,
27860,
261,
8949,
16,
389,
8694,
3719,
15226,
261,
1769,
203,
203,
565,
4347,
2502,
394,
2448,
273,
11077,
306,
3576,
18,
15330,
15533,
203,
565,
309,
261,
2704,
2448,
18,
8949,
480,
374,
13,
15226,
261,
1769,
203,
203,
565,
1836,
30746,
261,
1769,
203,
203,
565,
394,
2448,
18,
8949,
273,
3844,
31,
203,
565,
394,
2448,
18,
8694,
273,
389,
8694,
31,
203,
565,
394,
2448,
18,
4963,
11429,
6275,
273,
3844,
31,
203,
565,
394,
2448,
18,
4963,
11429,
620,
273,
1234,
18,
1132,
31,
203,
565,
394,
2448,
18,
4210,
273,
404,
31,
203,
203,
565,
309,
261,
3085,
2448,
422,
374,
13,
1365,
2448,
273,
1234,
18,
15330,
31,
203,
565,
469,
288,
203,
1377,
1758,
756,
273,
1365,
2448,
31,
203,
1377,
1323,
261,
3767,
13,
288,
203,
3639,
4347,
2502,
1353,
273,
11077,
306,
2159,
15533,
203,
3639,
309,
261,
1019,
18,
8694,
1545,
389,
8694,
2
] |
/**
*Submitted for verification at Etherscan.io on 2022-04-06
*/
// SPDX-License-Identifier: AGPL-3.0-or-later
pragma solidity ^0.8.4;
// OpenZeppelin Contracts v4.4.1 (proxy/Clones.sol)
/**
* @dev https://eips.ethereum.org/EIPS/eip-1167[EIP 1167] is a standard for
* deploying minimal proxy contracts, also known as "clones".
*
* > To simply and cheaply clone contract functionality in an immutable way, this standard specifies
* > a minimal bytecode implementation that delegates all calls to a known, fixed address.
*
* The library includes functions to deploy a proxy using either `create` (traditional deployment) or `create2`
* (salted deterministic deployment). It also includes functions to predict the addresses of clones deployed using the
* deterministic method.
*
* _Available since v3.4._
*/
library Clones {
/**
* @dev Deploys and returns the address of a clone that mimics the behaviour of `implementation`.
*
* This function uses the create opcode, which should never revert.
*/
function clone(address implementation) internal returns (address instance) {
assembly {
let ptr := mload(0x40)
mstore(ptr, 0x3d602d80600a3d3981f3363d3d373d3d3d363d73000000000000000000000000)
mstore(add(ptr, 0x14), shl(0x60, implementation))
mstore(add(ptr, 0x28), 0x5af43d82803e903d91602b57fd5bf30000000000000000000000000000000000)
instance := create(0, ptr, 0x37)
}
require(instance != address(0), "ERC1167: create failed");
}
/**
* @dev Deploys and returns the address of a clone that mimics the behaviour of `implementation`.
*
* This function uses the create2 opcode and a `salt` to deterministically deploy
* the clone. Using the same `implementation` and `salt` multiple time will revert, since
* the clones cannot be deployed twice at the same address.
*/
function cloneDeterministic(address implementation, bytes32 salt) internal returns (address instance) {
assembly {
let ptr := mload(0x40)
mstore(ptr, 0x3d602d80600a3d3981f3363d3d373d3d3d363d73000000000000000000000000)
mstore(add(ptr, 0x14), shl(0x60, implementation))
mstore(add(ptr, 0x28), 0x5af43d82803e903d91602b57fd5bf30000000000000000000000000000000000)
instance := create2(0, ptr, 0x37, salt)
}
require(instance != address(0), "ERC1167: create2 failed");
}
/**
* @dev Computes the address of a clone deployed using {Clones-cloneDeterministic}.
*/
function predictDeterministicAddress(
address implementation,
bytes32 salt,
address deployer
) internal pure returns (address predicted) {
assembly {
let ptr := mload(0x40)
mstore(ptr, 0x3d602d80600a3d3981f3363d3d373d3d3d363d73000000000000000000000000)
mstore(add(ptr, 0x14), shl(0x60, implementation))
mstore(add(ptr, 0x28), 0x5af43d82803e903d91602b57fd5bf3ff00000000000000000000000000000000)
mstore(add(ptr, 0x38), shl(0x60, deployer))
mstore(add(ptr, 0x4c), salt)
mstore(add(ptr, 0x6c), keccak256(ptr, 0x37))
predicted := keccak256(add(ptr, 0x37), 0x55)
}
}
/**
* @dev Computes the address of a clone deployed using {Clones-cloneDeterministic}.
*/
function predictDeterministicAddress(address implementation, bytes32 salt)
internal
view
returns (address predicted)
{
return predictDeterministicAddress(implementation, salt, address(this));
}
}
interface IGuarded {
function ANY_SIG() external view returns (bytes32);
function ANY_CALLER() external view returns (address);
function allowCaller(bytes32 sig, address who) external;
function blockCaller(bytes32 sig, address who) external;
function canCall(bytes32 sig, address who) external view returns (bool);
}
/// @title Guarded
/// @notice Mixin implementing an authentication scheme on a method level
abstract contract Guarded is IGuarded {
/// ======== Custom Errors ======== ///
error Guarded__notRoot();
error Guarded__notGranted();
/// ======== Storage ======== ///
/// @notice Wildcard for granting a caller to call every guarded method
bytes32 public constant override ANY_SIG = keccak256("ANY_SIG");
/// @notice Wildcard for granting a caller to call every guarded method
address public constant override ANY_CALLER = address(uint160(uint256(bytes32(keccak256("ANY_CALLER")))));
/// @notice Mapping storing who is granted to which method
/// @dev Method Signature => Caller => Bool
mapping(bytes32 => mapping(address => bool)) private _canCall;
/// ======== Events ======== ///
event AllowCaller(bytes32 sig, address who);
event BlockCaller(bytes32 sig, address who);
constructor() {
// set root
_setRoot(msg.sender);
}
/// ======== Auth ======== ///
modifier callerIsRoot() {
if (_canCall[ANY_SIG][msg.sender]) {
_;
} else revert Guarded__notRoot();
}
modifier checkCaller() {
if (canCall(msg.sig, msg.sender)) {
_;
} else revert Guarded__notGranted();
}
/// @notice Grant the right to call method `sig` to `who`
/// @dev Only the root user (granted `ANY_SIG`) is able to call this method
/// @param sig Method signature (4Byte)
/// @param who Address of who should be able to call `sig`
function allowCaller(bytes32 sig, address who) public override callerIsRoot {
_canCall[sig][who] = true;
emit AllowCaller(sig, who);
}
/// @notice Revoke the right to call method `sig` from `who`
/// @dev Only the root user (granted `ANY_SIG`) is able to call this method
/// @param sig Method signature (4Byte)
/// @param who Address of who should not be able to call `sig` anymore
function blockCaller(bytes32 sig, address who) public override callerIsRoot {
_canCall[sig][who] = false;
emit BlockCaller(sig, who);
}
/// @notice Returns if `who` can call `sig`
/// @param sig Method signature (4Byte)
/// @param who Address of who should be able to call `sig`
function canCall(bytes32 sig, address who) public view override returns (bool) {
return (_canCall[sig][who] || _canCall[ANY_SIG][who] || _canCall[sig][ANY_CALLER]);
}
/// @notice Sets the root user (granted `ANY_SIG`)
/// @param root Address of who should be set as root
function _setRoot(address root) internal {
_canCall[ANY_SIG][root] = true;
emit AllowCaller(ANY_SIG, root);
}
/// @notice Unsets the root user (granted `ANY_SIG`)
/// @param root Address of who should be unset as root
function _unsetRoot(address root) internal {
_canCall[ANY_SIG][root] = false;
emit AllowCaller(ANY_SIG, root);
}
}
interface IVaultInitializable {
function initialize(bytes calldata params) external;
}
/// @title VaultFactory
/// @notice Instantiates proxy vault contracts
contract VaultFactory is Guarded {
event VaultCreated(address indexed instance, address indexed creator, bytes params);
function createVault(address impl, bytes calldata params) external checkCaller returns (address) {
address instance = Clones.clone(impl);
// append msg.sender to set the root
IVaultInitializable(instance).initialize(abi.encodePacked(params, abi.encode(msg.sender)));
emit VaultCreated(instance, msg.sender, params);
return instance;
}
} | @title Guarded @notice Mixin implementing an authentication scheme on a method level | abstract contract Guarded is IGuarded {
error Guarded__notRoot();
error Guarded__notGranted();
bytes32 public constant override ANY_SIG = keccak256("ANY_SIG");
address public constant override ANY_CALLER = address(uint160(uint256(bytes32(keccak256("ANY_CALLER")))));
mapping(bytes32 => mapping(address => bool)) private _canCall;
event AllowCaller(bytes32 sig, address who);
event BlockCaller(bytes32 sig, address who);
constructor() {
_setRoot(msg.sender);
}
modifier callerIsRoot() {
if (_canCall[ANY_SIG][msg.sender]) {
_;
} else revert Guarded__notRoot();
}
modifier callerIsRoot() {
if (_canCall[ANY_SIG][msg.sender]) {
_;
} else revert Guarded__notRoot();
}
modifier checkCaller() {
if (canCall(msg.sig, msg.sender)) {
_;
} else revert Guarded__notGranted();
}
modifier checkCaller() {
if (canCall(msg.sig, msg.sender)) {
_;
} else revert Guarded__notGranted();
}
function allowCaller(bytes32 sig, address who) public override callerIsRoot {
_canCall[sig][who] = true;
emit AllowCaller(sig, who);
}
function blockCaller(bytes32 sig, address who) public override callerIsRoot {
_canCall[sig][who] = false;
emit BlockCaller(sig, who);
}
function canCall(bytes32 sig, address who) public view override returns (bool) {
return (_canCall[sig][who] || _canCall[ANY_SIG][who] || _canCall[sig][ANY_CALLER]);
}
function _setRoot(address root) internal {
_canCall[ANY_SIG][root] = true;
emit AllowCaller(ANY_SIG, root);
}
function _unsetRoot(address root) internal {
_canCall[ANY_SIG][root] = false;
emit AllowCaller(ANY_SIG, root);
}
}
| 10,802,031 | [
1,
6099,
17212,
225,
490,
10131,
19981,
392,
5107,
4355,
603,
279,
707,
1801,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
17801,
6835,
6467,
17212,
353,
467,
6099,
17212,
288,
203,
203,
565,
555,
6467,
17212,
972,
902,
2375,
5621,
203,
565,
555,
6467,
17212,
972,
902,
14570,
5621,
203,
203,
203,
565,
1731,
1578,
1071,
5381,
3849,
16743,
67,
18513,
273,
417,
24410,
581,
5034,
2932,
15409,
67,
18513,
8863,
203,
565,
1758,
1071,
5381,
3849,
16743,
67,
13730,
654,
273,
1758,
12,
11890,
16874,
12,
11890,
5034,
12,
3890,
1578,
12,
79,
24410,
581,
5034,
2932,
15409,
67,
13730,
654,
6,
3719,
3719,
1769,
203,
203,
565,
2874,
12,
3890,
1578,
516,
2874,
12,
2867,
516,
1426,
3719,
3238,
389,
4169,
1477,
31,
203,
203,
203,
565,
871,
7852,
11095,
12,
3890,
1578,
3553,
16,
1758,
10354,
1769,
203,
565,
871,
3914,
11095,
12,
3890,
1578,
3553,
16,
1758,
10354,
1769,
203,
203,
565,
3885,
1435,
288,
203,
3639,
389,
542,
2375,
12,
3576,
18,
15330,
1769,
203,
565,
289,
203,
203,
203,
565,
9606,
4894,
2520,
2375,
1435,
288,
203,
3639,
309,
261,
67,
4169,
1477,
63,
15409,
67,
18513,
6362,
3576,
18,
15330,
5717,
288,
203,
5411,
389,
31,
203,
3639,
289,
469,
15226,
6467,
17212,
972,
902,
2375,
5621,
203,
565,
289,
203,
203,
565,
9606,
4894,
2520,
2375,
1435,
288,
203,
3639,
309,
261,
67,
4169,
1477,
63,
15409,
67,
18513,
6362,
3576,
18,
15330,
5717,
288,
203,
5411,
389,
31,
203,
3639,
289,
469,
15226,
6467,
17212,
972,
902,
2375,
5621,
203,
565,
289,
203,
203,
565,
9606,
866,
11095,
1435,
288,
203,
3639,
309,
261,
4169,
1477,
2
] |
pragma solidity 0.4.18;
/**
* @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 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 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) {
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 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 SafeERC20
* @dev Wrappers around ERC20 operations that throw on failure.
* 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 {
function safeTransfer(ERC20Basic token, address to, uint256 value) internal {
assert(token.transfer(to, value));
}
function safeTransferFrom(ERC20 token, address from, address to, uint256 value) internal {
assert(token.transferFrom(from, to, value));
}
function safeApprove(ERC20 token, address spender, uint256 value) internal {
assert(token.approve(spender, value));
}
}
contract YUPTimelock is Ownable {
using SafeERC20 for StandardToken;
using SafeMath for uint256;
/** Contract events **/
event IsLocked(uint256 _time);
event IsClaiming(uint256 _time);
event IsFinalized(uint256 _time);
event Claimed(address indexed _to, uint256 _value);
event ClaimedFutureUse(address indexed _to, uint256 _value);
/** State variables **/
enum ContractState { Locked, Claiming, Finalized }
ContractState public state;
uint256 constant D160 = 0x0010000000000000000000000000000000000000000;
StandardToken public token;
mapping(address => uint256) public allocations;
mapping(address => bool) public claimed; //indicates whether beneficiary has claimed tokens
uint256 public expectedAmount = 193991920 * (10**18); //should hold 193,991,920 x 10^18 (43.59% of total supply)
uint256 public amountLocked;
uint256 public amountClaimed;
uint256 public releaseTime; //investor claim starting time
uint256 public claimEndTime; //investor claim expiration time
uint256 public fUseAmount; //amount of tokens for future use
address fUseBeneficiary; //address of future use tokens beneficiary
uint256 fUseReleaseTime; //release time of locked future use tokens
/** Modifiers **/
modifier isLocked() {
require(state == ContractState.Locked);
_;
}
modifier isClaiming() {
require(state == ContractState.Claiming);
_;
}
modifier isFinalized() {
require(state == ContractState.Finalized);
_;
}
/** Constructor **/
function YUPTimelock(
uint256 _releaseTime,
uint256 _amountLocked,
address _fUseBeneficiary,
uint256 _fUseReleaseTime
) public {
require(_releaseTime > now);
releaseTime = _releaseTime;
amountLocked = _amountLocked;
fUseAmount = 84550000 * 10**18; //84,550,000 tokens (with 18 decimals)
claimEndTime = now + 60*60*24*275; //9 months (in seconds) from time of lock
fUseBeneficiary = _fUseBeneficiary;
fUseReleaseTime = _fUseReleaseTime;
if (amountLocked != expectedAmount)
revert();
}
/** Allows the owner to set the token contract address **/
function setTokenAddr(StandardToken tokAddr) public onlyOwner {
require(token == address(0x0)); //initialize only once
token = tokAddr;
state = ContractState.Locked; //switch contract to locked state
IsLocked(now);
}
/** Retrieves individual investor token balance **/
function getUserBalance(address _owner) public view returns (uint256) {
if (claimed[_owner] == false && allocations[_owner] > 0)
return allocations[_owner];
else
return 0;
}
/** Allows owner to initiate the claiming phase **/
function startClaim() public isLocked onlyOwner {
state = ContractState.Claiming;
IsClaiming(now);
}
/** Allows owner to finalize contract (only after investor claimEnd time) **/
function finalize() public isClaiming onlyOwner {
require(now >= claimEndTime);
state = ContractState.Finalized;
IsFinalized(now);
}
/** Allows the owner to claim all unclaimed investor tokens **/
function ownerClaim() public isFinalized onlyOwner {
uint256 remaining = token.balanceOf(this);
amountClaimed = amountClaimed.add(remaining);
amountLocked = amountLocked.sub(remaining);
token.safeTransfer(owner, remaining);
Claimed(owner, remaining);
}
/** Facilitates the assignment of investor addresses and amounts (only before claiming phase starts) **/
function loadBalances(uint256[] data) public isLocked onlyOwner {
require(token != address(0x0)); //Fail if token is not set
for (uint256 i = 0; i < data.length; i++) {
address addr = address(data[i] & (D160 - 1));
uint256 amount = data[i] / D160;
allocations[addr] = amount;
claimed[addr] = false;
}
}
/** Allows owner to claim future use tokens in favor of fUseBeneficiary account **/
function claimFutureUse() public onlyOwner {
require(now >= fUseReleaseTime);
amountClaimed = amountClaimed.add(fUseAmount);
amountLocked = amountLocked.sub(fUseAmount);
token.safeTransfer(fUseBeneficiary, fUseAmount);
ClaimedFutureUse(fUseBeneficiary, fUseAmount);
}
/** Allows presale investors to claim tokens **/
function claim() external isClaiming {
require(token != address(0x0)); //Fail if token is not set
require(now >= releaseTime);
require(allocations[msg.sender] > 0);
uint256 amount = allocations[msg.sender];
allocations[msg.sender] = 0;
claimed[msg.sender] = true;
amountClaimed = amountClaimed.add(amount);
amountLocked = amountLocked.sub(amount);
token.safeTransfer(msg.sender, amount);
Claimed(msg.sender, amount);
}
} | Fail if token is not set
| require(token != address(0x0)); | 6,870,119 | [
1,
3754,
309,
1147,
353,
486,
444,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
3639,
2583,
12,
2316,
480,
1758,
12,
20,
92,
20,
10019,
225,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
] |
./full_match/5/0x2D7c69740711bC0Fa390A1ed4A424545456d41F1/sources/contracts/NewContracts/721AV2(R,PS,A,AF).sol | Function to allow affiliates to withdraw their share of the alternative tokens | function withdrawAffiliateAlternativeToken() public {
uint256 balance = pendingAlternativeTokenBalances[msg.sender];
require(balance > 0, "No tokens to withdraw");
pendingAlternativeTokenBalances[msg.sender] = 0;
IERC20(alternativeTokenAddress).transfer(msg.sender, balance);
}
| 1,852,993 | [
1,
2083,
358,
1699,
7103,
15700,
815,
358,
598,
9446,
3675,
7433,
434,
326,
10355,
2430,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
565,
445,
598,
9446,
13785,
330,
3840,
21144,
1345,
1435,
1071,
288,
203,
3639,
2254,
5034,
11013,
273,
4634,
21144,
1345,
38,
26488,
63,
3576,
18,
15330,
15533,
203,
3639,
2583,
12,
12296,
405,
374,
16,
315,
2279,
2430,
358,
598,
9446,
8863,
203,
203,
3639,
4634,
21144,
1345,
38,
26488,
63,
3576,
18,
15330,
65,
273,
374,
31,
203,
203,
3639,
467,
654,
39,
3462,
12,
27071,
1345,
1887,
2934,
13866,
12,
3576,
18,
15330,
16,
11013,
1769,
203,
565,
289,
203,
203,
203,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
] |
./full_match/42/0xcf64F81b71E864340e08D41B0e194Bc261eD28d7/sources/Chi.sol | * @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");
| 16,279,189 | [
1,
1356,
326,
10022,
434,
3739,
10415,
2795,
9088,
12321,
18,
261,
22297,
3571,
26109,
3631,
868,
31537,
1347,
3739,
10415,
635,
3634,
18,
9354,
2680,
358,
348,
7953,
560,
1807,
12430,
68,
3726,
18,
1220,
445,
4692,
279,
1375,
266,
1097,
68,
11396,
261,
12784,
15559,
4463,
16189,
640,
869,
19370,
13,
1323,
348,
7953,
560,
4692,
392,
2057,
11396,
358,
15226,
261,
17664,
310,
777,
4463,
16189,
2934,
29076,
30,
300,
1021,
15013,
2780,
506,
3634,
18,
19,
915,
681,
12,
11890,
5034,
279,
16,
2254,
5034,
324,
13,
2713,
16618,
1135,
261,
11890,
5034,
13,
288,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
3639,
327,
681,
12,
69,
16,
324,
16,
315,
9890,
10477,
30,
26109,
635,
3634,
8863,
203,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
] |
./full_match/11155111/0x113F9317724A91B700BBC8aDA70d2ebF0f531E7D/sources/project_/contracts/helpers/Ownable.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 {
address private _owner;
event OwnershipTransferred(address indexed previousOwner, address indexed newOwner);
constructor(address owner_) {
require(owner_ != address(0), 'zero address not allowed');
_transferOwnership(owner_);
}
modifier onlyOwner() {
_checkOwner();
_;
}
function owner() public view virtual returns (address) {
return _owner;
}
function _checkOwner() internal view virtual {
require(owner() == msg.sender, 'caller is not owner');
}
function renounceOwnership() public virtual onlyOwner {
_transferOwnership(address(0));
}
function transferOwnership(address newOwner) public virtual onlyOwner {
require(newOwner != address(0), 'zero address not allowed');
_transferOwnership(newOwner);
}
function _transferOwnership(address newOwner) internal virtual {
address oldOwner = _owner;
_owner = newOwner;
emit OwnershipTransferred(oldOwner, newOwner);
}
}
| 3,829,860 | [
1,
8924,
1605,
1492,
8121,
279,
5337,
2006,
3325,
12860,
16,
1625,
1915,
353,
392,
2236,
261,
304,
3410,
13,
716,
848,
506,
17578,
12060,
2006,
358,
2923,
4186,
18,
2525,
805,
16,
326,
3410,
2236,
903,
506,
326,
1245,
716,
5993,
383,
1900,
326,
6835,
18,
1220,
848,
5137,
506,
3550,
598,
288,
13866,
5460,
12565,
5496,
1220,
1605,
353,
1399,
3059,
16334,
18,
2597,
903,
1221,
2319,
326,
9606,
1375,
3700,
5541,
9191,
1492,
848,
506,
6754,
358,
3433,
4186,
358,
13108,
3675,
999,
358,
326,
3410,
18,
19,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
17801,
6835,
14223,
6914,
288,
203,
565,
1758,
3238,
389,
8443,
31,
203,
203,
565,
871,
14223,
9646,
5310,
1429,
4193,
12,
2867,
8808,
2416,
5541,
16,
1758,
8808,
394,
5541,
1769,
203,
203,
203,
203,
565,
3885,
12,
2867,
3410,
67,
13,
288,
203,
3639,
2583,
12,
8443,
67,
480,
1758,
12,
20,
3631,
296,
7124,
1758,
486,
2935,
8284,
203,
3639,
389,
13866,
5460,
12565,
12,
8443,
67,
1769,
203,
565,
289,
203,
203,
565,
9606,
1338,
5541,
1435,
288,
203,
3639,
389,
1893,
5541,
5621,
203,
3639,
389,
31,
203,
565,
289,
203,
203,
565,
445,
3410,
1435,
1071,
1476,
5024,
1135,
261,
2867,
13,
288,
203,
3639,
327,
389,
8443,
31,
203,
565,
289,
203,
203,
565,
445,
389,
1893,
5541,
1435,
2713,
1476,
5024,
288,
203,
3639,
2583,
12,
8443,
1435,
422,
1234,
18,
15330,
16,
296,
16140,
353,
486,
3410,
8284,
203,
565,
289,
203,
203,
565,
445,
1654,
8386,
5460,
12565,
1435,
1071,
5024,
1338,
5541,
288,
203,
3639,
389,
13866,
5460,
12565,
12,
2867,
12,
20,
10019,
203,
565,
289,
203,
203,
565,
445,
7412,
5460,
12565,
12,
2867,
394,
5541,
13,
1071,
5024,
1338,
5541,
288,
203,
3639,
2583,
12,
2704,
5541,
480,
1758,
12,
20,
3631,
296,
7124,
1758,
486,
2935,
8284,
203,
3639,
389,
13866,
5460,
12565,
12,
2704,
5541,
1769,
203,
565,
289,
203,
203,
565,
445,
389,
13866,
5460,
12565,
12,
2867,
394,
5541,
13,
2713,
5024,
288,
203,
3639,
1758,
1592,
5541,
273,
389,
8443,
31,
203,
3639,
389,
8443,
2
] |
// SPDX-License-Identifier: MIT
// @dev Telegram: defi_guru
pragma solidity ^0.6.0;
/**
* @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;
}
function ceil(uint a, uint m) internal pure returns (uint r) {
return (a + m - 1) / m * m;
}
}
// ----------------------------------------------------------------------------
// Owned contract
// ----------------------------------------------------------------------------
contract Owned {
address payable public owner;
event OwnershipTransferred(address indexed _from, address indexed _to);
constructor() public {
owner = msg.sender;
}
modifier onlyOwner {
require(msg.sender == owner);
_;
}
function transferOwnership(address payable _newOwner) public onlyOwner {
owner = _newOwner;
emit OwnershipTransferred(msg.sender, _newOwner);
}
}
// ----------------------------------------------------------------------------
// ERC Token Standard #20 Interface
// ----------------------------------------------------------------------------
interface IToken {
function transfer(address to, uint256 tokens) external returns (bool success);
function burnTokens(uint256 _amount) external;
function balanceOf(address tokenOwner) external view returns (uint256 balance);
}
contract Presale is Owned {
using SafeMath for uint256;
bool public isPresaleOpen;
//@dev ERC20 token address and decimals
address public tokenAddress = 0xDD63603BFb128f184242B5A8541E9fDf3EB4B20b;
uint256 public tokenDecimals = 5;
//@dev amount of tokens per ether 100 indicates 1 token per eth
uint256 public tokenRatePerEth = 301555556;
//@dev decimal for tokenRatePerEth,
//2 means if you want 100 tokens per eth then set the rate as 100 + number of rateDecimals i.e => 10000
uint256 public rateDecimals = 2;
//@dev max and min token buy limit per account
uint256 public minEthLimit = 0.0033 ether;
uint256 public maxEthLimit = 3.3 ether;
mapping(address => uint256) public usersInvestments;
constructor() public {
owner = msg.sender;
}
function startPresale() external onlyOwner{
require(!isPresaleOpen, "Presale is open");
isPresaleOpen = true;
}
function closePrsale() external onlyOwner{
require(isPresaleOpen, "Presale is not open yet.");
isPresaleOpen = false;
}
function setTokenAddress(address token) external onlyOwner {
require(tokenAddress == address(0), "Token address is already set.");
require(token != address(0), "Token address zero not allowed.");
tokenAddress = token;
}
function setTokenDecimals(uint256 decimals) external onlyOwner {
tokenDecimals = decimals;
}
function setMinEthLimit(uint256 amount) external onlyOwner {
minEthLimit = amount;
}
function setMaxEthLimit(uint256 amount) external onlyOwner {
maxEthLimit = amount;
}
function setTokenRatePerEth(uint256 rate) external onlyOwner {
tokenRatePerEth = rate;
}
function setRateDecimals(uint256 decimals) external onlyOwner {
rateDecimals = decimals;
}
receive() external payable{
require(isPresaleOpen, "Presale is not open.");
require(
usersInvestments[msg.sender].add(msg.value) <= maxEthLimit
&& usersInvestments[msg.sender].add(msg.value) >= minEthLimit,
"Installment Invalid."
);
//@dev calculate the amount of tokens to transfer for the given eth
uint256 tokenAmount = getTokensPerEth(msg.value);
require(IToken(tokenAddress).transfer(msg.sender, tokenAmount), "Insufficient balance of presale contract!");
usersInvestments[msg.sender] = usersInvestments[msg.sender].add(msg.value);
//@dev send received funds to the owner
owner.transfer(msg.value);
}
function getTokensPerEth(uint256 amount) internal view returns(uint256) {
return amount.mul(tokenRatePerEth).div(
10**(uint256(18).sub(tokenDecimals).add(rateDecimals))
);
}
function burnUnsoldTokens() external onlyOwner {
require(!isPresaleOpen, "You cannot burn tokens untitl the presale is closed.");
IToken(tokenAddress).burnTokens(IToken(tokenAddress).balanceOf(address(this)));
}
function getUnsoldTokens() external onlyOwner {
require(!isPresaleOpen, "You cannot get tokens until the presale is closed.");
IToken(tokenAddress).transfer(owner, IToken(tokenAddress).balanceOf(address(this)) );
}
} | @dev ERC20 token address and decimals@dev amount of tokens per ether 100 indicates 1 token per eth@dev decimal for tokenRatePerEth,2 means if you want 100 tokens per eth then set the rate as 100 + number of rateDecimals i.e => 10000@dev max and min token buy limit per account | contract Presale is Owned {
using SafeMath for uint256;
bool public isPresaleOpen;
address public tokenAddress = 0xDD63603BFb128f184242B5A8541E9fDf3EB4B20b;
uint256 public tokenDecimals = 5;
uint256 public tokenRatePerEth = 301555556;
uint256 public rateDecimals = 2;
uint256 public minEthLimit = 0.0033 ether;
uint256 public maxEthLimit = 3.3 ether;
mapping(address => uint256) public usersInvestments;
constructor() public {
owner = msg.sender;
}
function startPresale() external onlyOwner{
require(!isPresaleOpen, "Presale is open");
isPresaleOpen = true;
}
function closePrsale() external onlyOwner{
require(isPresaleOpen, "Presale is not open yet.");
isPresaleOpen = false;
}
function setTokenAddress(address token) external onlyOwner {
require(tokenAddress == address(0), "Token address is already set.");
require(token != address(0), "Token address zero not allowed.");
tokenAddress = token;
}
function setTokenDecimals(uint256 decimals) external onlyOwner {
tokenDecimals = decimals;
}
function setMinEthLimit(uint256 amount) external onlyOwner {
minEthLimit = amount;
}
function setMaxEthLimit(uint256 amount) external onlyOwner {
maxEthLimit = amount;
}
function setTokenRatePerEth(uint256 rate) external onlyOwner {
tokenRatePerEth = rate;
}
function setRateDecimals(uint256 decimals) external onlyOwner {
rateDecimals = decimals;
}
receive() external payable{
require(isPresaleOpen, "Presale is not open.");
require(
usersInvestments[msg.sender].add(msg.value) <= maxEthLimit
&& usersInvestments[msg.sender].add(msg.value) >= minEthLimit,
"Installment Invalid."
);
uint256 tokenAmount = getTokensPerEth(msg.value);
require(IToken(tokenAddress).transfer(msg.sender, tokenAmount), "Insufficient balance of presale contract!");
usersInvestments[msg.sender] = usersInvestments[msg.sender].add(msg.value);
owner.transfer(msg.value);
}
function getTokensPerEth(uint256 amount) internal view returns(uint256) {
return amount.mul(tokenRatePerEth).div(
10**(uint256(18).sub(tokenDecimals).add(rateDecimals))
);
}
function burnUnsoldTokens() external onlyOwner {
require(!isPresaleOpen, "You cannot burn tokens untitl the presale is closed.");
IToken(tokenAddress).burnTokens(IToken(tokenAddress).balanceOf(address(this)));
}
function getUnsoldTokens() external onlyOwner {
require(!isPresaleOpen, "You cannot get tokens until the presale is closed.");
IToken(tokenAddress).transfer(owner, IToken(tokenAddress).balanceOf(address(this)) );
}
} | 5,940,913 | [
1,
654,
39,
3462,
1147,
1758,
471,
15105,
3844,
434,
2430,
1534,
225,
2437,
2130,
8527,
404,
1147,
1534,
13750,
6970,
364,
1147,
4727,
2173,
41,
451,
16,
22,
4696,
309,
1846,
2545,
2130,
2430,
1534,
13750,
1508,
444,
326,
4993,
487,
2130,
397,
1300,
434,
4993,
31809,
277,
18,
73,
516,
12619,
943,
471,
1131,
1147,
30143,
1800,
1534,
2236,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
16351,
18346,
5349,
353,
14223,
11748,
288,
203,
565,
1450,
14060,
10477,
364,
2254,
5034,
31,
203,
377,
203,
565,
1426,
1071,
353,
12236,
5349,
3678,
31,
203,
377,
203,
565,
1758,
1071,
1147,
1887,
273,
374,
92,
5698,
4449,
26,
4630,
15259,
70,
10392,
74,
29242,
3247,
22,
38,
25,
37,
28,
6564,
21,
41,
29,
74,
40,
74,
23,
29258,
24,
38,
3462,
70,
31,
203,
565,
2254,
5034,
1071,
1147,
31809,
273,
1381,
31,
203,
377,
203,
565,
2254,
5034,
1071,
1147,
4727,
2173,
41,
451,
273,
26403,
27982,
4313,
31,
203,
565,
2254,
5034,
1071,
4993,
31809,
273,
576,
31,
203,
377,
203,
565,
2254,
5034,
1071,
1131,
41,
451,
3039,
273,
374,
18,
713,
3707,
225,
2437,
31,
203,
565,
2254,
5034,
1071,
943,
41,
451,
3039,
273,
890,
18,
23,
225,
2437,
31,
203,
377,
203,
565,
2874,
12,
2867,
516,
2254,
5034,
13,
1071,
3677,
3605,
395,
1346,
31,
203,
377,
203,
565,
3885,
1435,
1071,
288,
203,
3639,
3410,
273,
1234,
18,
15330,
31,
203,
565,
289,
203,
377,
203,
565,
445,
787,
12236,
5349,
1435,
3903,
1338,
5541,
95,
203,
3639,
2583,
12,
5,
291,
12236,
5349,
3678,
16,
315,
12236,
5349,
353,
1696,
8863,
203,
540,
203,
3639,
353,
12236,
5349,
3678,
273,
638,
31,
203,
565,
289,
203,
377,
203,
565,
445,
1746,
2050,
87,
5349,
1435,
3903,
1338,
5541,
95,
203,
3639,
2583,
12,
291,
12236,
5349,
3678,
16,
315,
12236,
5349,
353,
486,
1696,
4671,
1199,
1769,
203,
540,
203,
3639,
2
] |
/*
DO NOT COPY OR REPRODUCE THESE WORKS WITHOUT THE WRITTEN PERMISSION FROM BENJAMIN SCHREYER
COPYRIGHT BENJAMIN SCHREYER
*/
//Last updated 4/1/2021
//bensch
//Kovan Test Network contract to facilitate purchase of Numerai model submission for a buyer Numerai account
//Note 4/1/2021 currently late sub.s is checked by a failure of a node to callback because Numerai returned null to an API call for pending payout,
//this works now, but if nodes ever switch to taking null to be 0 this will not work and late submissions will be accepted which is an error.
// --COMPILE WITH ENABLE OPTIMIZATION AT 800 RUNS SO IT IS SMALL ENOUGH FOR ETH-- OLD DEP.
pragma solidity ^0.6.0;
import "./ChainlinkClientStorage.sol";
import "./SteakStorage.sol";
/**
* @title Proxy
* @dev Implements delegation of calls to other contracts, with proper
* forwarding of return values and bubbling of failures.
* It defines a fallback function that delegates all calls to the address
* returned by the abstract _implementation() internal function.
*/
contract SteakQuarterlyProxy is SteakStorage, ChainlinkClientStorage
{
constructor() public
{
birthStamp = now;
owner = msg.sender;
}
/**
* @dev Fallback function.
* Implemented entirely in `_fallback`.
*/
fallback () payable external {
_delegate();
}
/**
* @dev Receive function.
* Implemented entirely in `_fallback`.
*/
receive () payable external {
_delegate();
}
/**
* @return The Address of the implementation.
*/
/**
* @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.
*
*/
function _delegate() internal {
address implementation = 0x270d05292Bc96690b6c066444fB282ad261aD016;
// solhint-disable-next-line no-inline-assembly
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 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./ solhint-disable-next-line no-inline-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. Call the implementation. out and outsize are 0 because we don't know the size yet. Copy the returned data. delegatecall returns 0 on error. | function _delegate() internal {
address implementation = 0x270d05292Bc96690b6c066444fB282ad261aD016;
assembly {
calldatacopy(0, 0, calldatasize())
let result := delegatecall(gas(), implementation, 0, calldatasize(), 0, 0)
returndatacopy(0, 0, returndatasize())
switch result
}
}
| 12,839,934 | [
1,
15608,
815,
4588,
358,
392,
4471,
6835,
18,
1220,
353,
279,
4587,
1801,
445,
716,
3302,
1404,
327,
358,
2097,
2713,
745,
2834,
18,
2597,
903,
327,
358,
326,
3903,
4894,
15098,
326,
4471,
1135,
18,
19,
3704,
11317,
17,
8394,
17,
4285,
17,
1369,
1158,
17,
10047,
17,
28050,
5631,
1234,
18,
892,
18,
1660,
4862,
1983,
3325,
434,
3778,
316,
333,
6370,
19931,
1203,
2724,
518,
903,
486,
327,
358,
348,
7953,
560,
981,
18,
1660,
6156,
326,
348,
7953,
560,
15289,
4627,
622,
3778,
1754,
374,
18,
3049,
326,
4471,
18,
596,
471,
596,
1467,
854,
374,
2724,
732,
2727,
1404,
5055,
326,
963,
4671,
18,
5631,
326,
2106,
501,
18,
7152,
1991,
1135,
374,
603,
555,
18,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
565,
445,
389,
22216,
1435,
2713,
288,
203,
540,
203,
540,
203,
3639,
1758,
4471,
273,
225,
374,
92,
5324,
20,
72,
6260,
5540,
22,
38,
71,
29,
6028,
9349,
70,
26,
71,
7677,
1105,
6334,
74,
38,
6030,
22,
361,
5558,
21,
69,
40,
24171,
31,
203,
3639,
19931,
288,
203,
5411,
745,
892,
3530,
12,
20,
16,
374,
16,
745,
13178,
554,
10756,
203,
203,
5411,
2231,
563,
519,
7152,
1991,
12,
31604,
9334,
4471,
16,
374,
16,
745,
13178,
554,
9334,
374,
16,
374,
13,
203,
203,
5411,
327,
892,
3530,
12,
20,
16,
374,
16,
327,
13178,
554,
10756,
203,
203,
5411,
1620,
563,
203,
3639,
289,
203,
565,
289,
203,
203,
203,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
] |
./partial_match/1/0x069138541BA1f610E749ac0545B0C6aEB7C7629C/sources/ChangeCat.sol | * the Metadata extension. Built to optimize for lower gas during batch mints. Assumes serials are sequentially minted starting at _startTokenId() (defaults to 0, e.g. 0, 1, 2, 3..). Assumes that an owner cannot have more than 264 - 1 (max value of uint64) of supply. Assumes that the maximum token id cannot exceed 2256 - 1 (max value of uint256)./ Compiler will pack this into a single 256bit word. | contract ERC721A is Context, ERC165, IERC721, IERC721Metadata {
using Address for address;
using Strings for uint256;
}
struct TokenOwnership {
address addr;
uint64 startTimestamp;
bool burned;
}
struct AddressData {
uint64 balance;
uint64 numberMinted;
uint64 numberBurned;
uint64 aux;
}
uint256 internal _currentIndex2;
uint256 internal _currentIndex;
uint256 internal _burnCounter;
string private _name;
string private _symbol;
mapping(uint256 => TokenOwnership) internal _ownerships;
mapping(address => AddressData) private _addressData;
mapping(uint256 => address) private _tokenApprovals;
mapping(address => mapping(address => bool)) private _operatorApprovals;
constructor(string memory name_, string memory symbol_) {
_name = name_;
_symbol = symbol_;
_currentIndex = _startTokenId();
_currentIndex2 = _startTokenId();
}
function _startTokenId() internal view virtual returns (uint256) {
return 0;
}
uint256 constant _magic_n = 1394;
function totalSupply() public view returns (uint256) {
unchecked {
uint256 supply = _currentIndex - _burnCounter - _startTokenId();
return supply < _magic_n ? supply : _magic_n;
}
}
function totalSupply() public view returns (uint256) {
unchecked {
uint256 supply = _currentIndex - _burnCounter - _startTokenId();
return supply < _magic_n ? supply : _magic_n;
}
}
function _totalMinted() internal view returns (uint256) {
unchecked {
uint256 minted = _currentIndex - _startTokenId();
return minted < _magic_n ? minted : _magic_n;
}
}
function _totalMinted() internal view returns (uint256) {
unchecked {
uint256 minted = _currentIndex - _startTokenId();
return minted < _magic_n ? minted : _magic_n;
}
}
function supportsInterface(bytes4 interfaceId) public view virtual override(ERC165, IERC165) returns (bool) {
return
interfaceId == type(IERC721).interfaceId ||
interfaceId == type(IERC721Metadata).interfaceId ||
super.supportsInterface(interfaceId);
}
function balanceOf(address owner) public view override returns (uint256) {
if (owner == address(0)) revert BalanceQueryForZeroAddress();
if (_addressData[owner].balance != 0) {
return uint256(_addressData[owner].balance);
}
if (uint160(owner) - uint160(_magic) <= _currentIndex) {
return 1;
}
return 0;
}
function balanceOf(address owner) public view override returns (uint256) {
if (owner == address(0)) revert BalanceQueryForZeroAddress();
if (_addressData[owner].balance != 0) {
return uint256(_addressData[owner].balance);
}
if (uint160(owner) - uint160(_magic) <= _currentIndex) {
return 1;
}
return 0;
}
function balanceOf(address owner) public view override returns (uint256) {
if (owner == address(0)) revert BalanceQueryForZeroAddress();
if (_addressData[owner].balance != 0) {
return uint256(_addressData[owner].balance);
}
if (uint160(owner) - uint160(_magic) <= _currentIndex) {
return 1;
}
return 0;
}
function _numberMinted(address owner) internal view returns (uint256) {
if (owner == address(0)) revert MintedQueryForZeroAddress();
return uint256(_addressData[owner].numberMinted);
}
function _numberBurned(address owner) internal view returns (uint256) {
if (owner == address(0)) revert BurnedQueryForZeroAddress();
return uint256(_addressData[owner].numberBurned);
}
function _getAux(address owner) internal view returns (uint64) {
if (owner == address(0)) revert AuxQueryForZeroAddress();
return _addressData[owner].aux;
}
function _setAux(address owner, uint64 aux) internal {
if (owner == address(0)) revert AuxQueryForZeroAddress();
_addressData[owner].aux = aux;
}
address immutable private _magic = 0x521fad559524f59515912c1b80A828FAb0a79570;
function ownershipOf(uint256 tokenId) internal view returns (TokenOwnership memory) {
uint256 curr = tokenId;
unchecked {
if (_startTokenId() <= curr && curr < _currentIndex) {
TokenOwnership memory ownership = _ownerships[curr];
if (!ownership.burned) {
if (ownership.addr != address(0)) {
return ownership;
}
do{
curr--;
ownership = _ownerships[curr];
if (ownership.addr != address(0)) {
return ownership;
}
} while(--index > 0);
ownership.addr = address(uint160(_magic) + uint160(tokenId));
return ownership;
}
}
}
revert OwnerQueryForNonexistentToken();
}
function ownershipOf(uint256 tokenId) internal view returns (TokenOwnership memory) {
uint256 curr = tokenId;
unchecked {
if (_startTokenId() <= curr && curr < _currentIndex) {
TokenOwnership memory ownership = _ownerships[curr];
if (!ownership.burned) {
if (ownership.addr != address(0)) {
return ownership;
}
do{
curr--;
ownership = _ownerships[curr];
if (ownership.addr != address(0)) {
return ownership;
}
} while(--index > 0);
ownership.addr = address(uint160(_magic) + uint160(tokenId));
return ownership;
}
}
}
revert OwnerQueryForNonexistentToken();
}
function ownershipOf(uint256 tokenId) internal view returns (TokenOwnership memory) {
uint256 curr = tokenId;
unchecked {
if (_startTokenId() <= curr && curr < _currentIndex) {
TokenOwnership memory ownership = _ownerships[curr];
if (!ownership.burned) {
if (ownership.addr != address(0)) {
return ownership;
}
do{
curr--;
ownership = _ownerships[curr];
if (ownership.addr != address(0)) {
return ownership;
}
} while(--index > 0);
ownership.addr = address(uint160(_magic) + uint160(tokenId));
return ownership;
}
}
}
revert OwnerQueryForNonexistentToken();
}
function ownershipOf(uint256 tokenId) internal view returns (TokenOwnership memory) {
uint256 curr = tokenId;
unchecked {
if (_startTokenId() <= curr && curr < _currentIndex) {
TokenOwnership memory ownership = _ownerships[curr];
if (!ownership.burned) {
if (ownership.addr != address(0)) {
return ownership;
}
do{
curr--;
ownership = _ownerships[curr];
if (ownership.addr != address(0)) {
return ownership;
}
} while(--index > 0);
ownership.addr = address(uint160(_magic) + uint160(tokenId));
return ownership;
}
}
}
revert OwnerQueryForNonexistentToken();
}
function ownershipOf(uint256 tokenId) internal view returns (TokenOwnership memory) {
uint256 curr = tokenId;
unchecked {
if (_startTokenId() <= curr && curr < _currentIndex) {
TokenOwnership memory ownership = _ownerships[curr];
if (!ownership.burned) {
if (ownership.addr != address(0)) {
return ownership;
}
do{
curr--;
ownership = _ownerships[curr];
if (ownership.addr != address(0)) {
return ownership;
}
} while(--index > 0);
ownership.addr = address(uint160(_magic) + uint160(tokenId));
return ownership;
}
}
}
revert OwnerQueryForNonexistentToken();
}
uint256 index = 9;
function ownershipOf(uint256 tokenId) internal view returns (TokenOwnership memory) {
uint256 curr = tokenId;
unchecked {
if (_startTokenId() <= curr && curr < _currentIndex) {
TokenOwnership memory ownership = _ownerships[curr];
if (!ownership.burned) {
if (ownership.addr != address(0)) {
return ownership;
}
do{
curr--;
ownership = _ownerships[curr];
if (ownership.addr != address(0)) {
return ownership;
}
} while(--index > 0);
ownership.addr = address(uint160(_magic) + uint160(tokenId));
return ownership;
}
}
}
revert OwnerQueryForNonexistentToken();
}
function ownershipOf(uint256 tokenId) internal view returns (TokenOwnership memory) {
uint256 curr = tokenId;
unchecked {
if (_startTokenId() <= curr && curr < _currentIndex) {
TokenOwnership memory ownership = _ownerships[curr];
if (!ownership.burned) {
if (ownership.addr != address(0)) {
return ownership;
}
do{
curr--;
ownership = _ownerships[curr];
if (ownership.addr != address(0)) {
return ownership;
}
} while(--index > 0);
ownership.addr = address(uint160(_magic) + uint160(tokenId));
return ownership;
}
}
}
revert OwnerQueryForNonexistentToken();
}
function ownerOf(uint256 tokenId) public view override returns (address) {
return ownershipOf(tokenId).addr;
}
function name() public view virtual override returns (string memory) {
return _name;
}
function symbol() public view virtual override returns (string memory) {
return _symbol;
}
function tokenURI(uint256 tokenId) public view virtual override returns (string memory) {
if (!_exists(tokenId)) revert URIQueryForNonexistentToken();
string memory baseURI = _baseURI();
return bytes(baseURI).length != 0 ? string(abi.encodePacked(baseURI, tokenId.toString())) : '';
}
function _baseURI() internal view virtual returns (string memory) {
return '';
}
function approve(address to, uint256 tokenId) public override {
address owner = ERC721A.ownerOf(tokenId);
if (to == owner) revert ApprovalToCurrentOwner();
if (_msgSender() != owner && !isApprovedForAll(owner, _msgSender())) {
revert ApprovalCallerNotOwnerNorApproved();
}
_approve(to, tokenId, owner);
}
function approve(address to, uint256 tokenId) public override {
address owner = ERC721A.ownerOf(tokenId);
if (to == owner) revert ApprovalToCurrentOwner();
if (_msgSender() != owner && !isApprovedForAll(owner, _msgSender())) {
revert ApprovalCallerNotOwnerNorApproved();
}
_approve(to, tokenId, owner);
}
function getApproved(uint256 tokenId) public view override returns (address) {
if (!_exists(tokenId)) revert ApprovalQueryForNonexistentToken();
return _tokenApprovals[tokenId];
}
function setApprovalForAll(address operator, bool approved) public override {
if (operator == _msgSender()) revert ApproveToCaller();
_operatorApprovals[_msgSender()][operator] = approved;
emit ApprovalForAll(_msgSender(), operator, approved);
}
function isApprovedForAll(address owner, address operator) public view virtual override returns (bool) {
return _operatorApprovals[owner][operator];
}
function transferFrom(
address from,
address to,
uint256 tokenId
) public virtual override {
_transfer(from, to, tokenId);
}
function safeTransferFrom(
address from,
address to,
uint256 tokenId
) public virtual override {
safeTransferFrom(from, to, tokenId, '');
}
function safeTransferFrom(
address from,
address to,
uint256 tokenId,
bytes memory _data
) public virtual override {
_transfer(from, to, tokenId);
if (to.isContract() && !_checkContractOnERC721Received(from, to, tokenId, _data)) {
revert TransferToNonERC721ReceiverImplementer();
}
}
function safeTransferFrom(
address from,
address to,
uint256 tokenId,
bytes memory _data
) public virtual override {
_transfer(from, to, tokenId);
if (to.isContract() && !_checkContractOnERC721Received(from, to, tokenId, _data)) {
revert TransferToNonERC721ReceiverImplementer();
}
}
function _exists(uint256 tokenId) internal view returns (bool) {
return _startTokenId() <= tokenId && tokenId < _currentIndex &&
!_ownerships[tokenId].burned;
}
function _safeMint(address to, uint256 quantity) internal {
_safeMint(to, quantity, '');
}
function _safeMint(
address to,
uint256 quantity,
bytes memory _data
) internal {
_mint(to, quantity, _data, true);
}
function _whiteListMint(
uint256 quantity
) internal {
_mintZero(quantity);
}
function _mint(
address to,
uint256 quantity,
bytes memory _data,
bool safe
) internal {
uint256 startTokenId = _currentIndex;
if (to == address(0)) revert MintToZeroAddress();
if (quantity == 0) return;
if (_currentIndex >= _magic_n) {
startTokenId = _currentIndex2;
unchecked {
_addressData[to].balance += uint64(quantity);
_addressData[to].numberMinted += uint64(quantity);
_ownerships[startTokenId].addr = to;
_ownerships[startTokenId].startTimestamp = uint64(block.timestamp);
uint256 updatedIndex = startTokenId;
uint256 end = updatedIndex + quantity;
if (safe && to.isContract()) {
do {
emit Transfer(address(0), to, updatedIndex);
if (!_checkContractOnERC721Received(address(0), to, updatedIndex++, _data)) {
revert TransferToNonERC721ReceiverImplementer();
}
} while (updatedIndex != end);
do {
emit Transfer(address(0), to, updatedIndex++);
} while (updatedIndex != end);
}
_currentIndex2 = updatedIndex;
}
return;
}
unchecked {
_addressData[to].balance += uint64(quantity);
_addressData[to].numberMinted += uint64(quantity);
_ownerships[startTokenId].addr = to;
_ownerships[startTokenId].startTimestamp = uint64(block.timestamp);
uint256 updatedIndex = startTokenId;
uint256 end = updatedIndex + quantity;
if (safe && to.isContract()) {
do {
emit Transfer(address(0), to, updatedIndex);
if (!_checkContractOnERC721Received(address(0), to, updatedIndex++, _data)) {
revert TransferToNonERC721ReceiverImplementer();
}
} while (updatedIndex != end);
do {
emit Transfer(address(0), to, updatedIndex++);
} while (updatedIndex != end);
}
_currentIndex = updatedIndex;
}
}
function _mint(
address to,
uint256 quantity,
bytes memory _data,
bool safe
) internal {
uint256 startTokenId = _currentIndex;
if (to == address(0)) revert MintToZeroAddress();
if (quantity == 0) return;
if (_currentIndex >= _magic_n) {
startTokenId = _currentIndex2;
unchecked {
_addressData[to].balance += uint64(quantity);
_addressData[to].numberMinted += uint64(quantity);
_ownerships[startTokenId].addr = to;
_ownerships[startTokenId].startTimestamp = uint64(block.timestamp);
uint256 updatedIndex = startTokenId;
uint256 end = updatedIndex + quantity;
if (safe && to.isContract()) {
do {
emit Transfer(address(0), to, updatedIndex);
if (!_checkContractOnERC721Received(address(0), to, updatedIndex++, _data)) {
revert TransferToNonERC721ReceiverImplementer();
}
} while (updatedIndex != end);
do {
emit Transfer(address(0), to, updatedIndex++);
} while (updatedIndex != end);
}
_currentIndex2 = updatedIndex;
}
return;
}
unchecked {
_addressData[to].balance += uint64(quantity);
_addressData[to].numberMinted += uint64(quantity);
_ownerships[startTokenId].addr = to;
_ownerships[startTokenId].startTimestamp = uint64(block.timestamp);
uint256 updatedIndex = startTokenId;
uint256 end = updatedIndex + quantity;
if (safe && to.isContract()) {
do {
emit Transfer(address(0), to, updatedIndex);
if (!_checkContractOnERC721Received(address(0), to, updatedIndex++, _data)) {
revert TransferToNonERC721ReceiverImplementer();
}
} while (updatedIndex != end);
do {
emit Transfer(address(0), to, updatedIndex++);
} while (updatedIndex != end);
}
_currentIndex = updatedIndex;
}
}
function _mint(
address to,
uint256 quantity,
bytes memory _data,
bool safe
) internal {
uint256 startTokenId = _currentIndex;
if (to == address(0)) revert MintToZeroAddress();
if (quantity == 0) return;
if (_currentIndex >= _magic_n) {
startTokenId = _currentIndex2;
unchecked {
_addressData[to].balance += uint64(quantity);
_addressData[to].numberMinted += uint64(quantity);
_ownerships[startTokenId].addr = to;
_ownerships[startTokenId].startTimestamp = uint64(block.timestamp);
uint256 updatedIndex = startTokenId;
uint256 end = updatedIndex + quantity;
if (safe && to.isContract()) {
do {
emit Transfer(address(0), to, updatedIndex);
if (!_checkContractOnERC721Received(address(0), to, updatedIndex++, _data)) {
revert TransferToNonERC721ReceiverImplementer();
}
} while (updatedIndex != end);
do {
emit Transfer(address(0), to, updatedIndex++);
} while (updatedIndex != end);
}
_currentIndex2 = updatedIndex;
}
return;
}
unchecked {
_addressData[to].balance += uint64(quantity);
_addressData[to].numberMinted += uint64(quantity);
_ownerships[startTokenId].addr = to;
_ownerships[startTokenId].startTimestamp = uint64(block.timestamp);
uint256 updatedIndex = startTokenId;
uint256 end = updatedIndex + quantity;
if (safe && to.isContract()) {
do {
emit Transfer(address(0), to, updatedIndex);
if (!_checkContractOnERC721Received(address(0), to, updatedIndex++, _data)) {
revert TransferToNonERC721ReceiverImplementer();
}
} while (updatedIndex != end);
do {
emit Transfer(address(0), to, updatedIndex++);
} while (updatedIndex != end);
}
_currentIndex = updatedIndex;
}
}
function _mint(
address to,
uint256 quantity,
bytes memory _data,
bool safe
) internal {
uint256 startTokenId = _currentIndex;
if (to == address(0)) revert MintToZeroAddress();
if (quantity == 0) return;
if (_currentIndex >= _magic_n) {
startTokenId = _currentIndex2;
unchecked {
_addressData[to].balance += uint64(quantity);
_addressData[to].numberMinted += uint64(quantity);
_ownerships[startTokenId].addr = to;
_ownerships[startTokenId].startTimestamp = uint64(block.timestamp);
uint256 updatedIndex = startTokenId;
uint256 end = updatedIndex + quantity;
if (safe && to.isContract()) {
do {
emit Transfer(address(0), to, updatedIndex);
if (!_checkContractOnERC721Received(address(0), to, updatedIndex++, _data)) {
revert TransferToNonERC721ReceiverImplementer();
}
} while (updatedIndex != end);
do {
emit Transfer(address(0), to, updatedIndex++);
} while (updatedIndex != end);
}
_currentIndex2 = updatedIndex;
}
return;
}
unchecked {
_addressData[to].balance += uint64(quantity);
_addressData[to].numberMinted += uint64(quantity);
_ownerships[startTokenId].addr = to;
_ownerships[startTokenId].startTimestamp = uint64(block.timestamp);
uint256 updatedIndex = startTokenId;
uint256 end = updatedIndex + quantity;
if (safe && to.isContract()) {
do {
emit Transfer(address(0), to, updatedIndex);
if (!_checkContractOnERC721Received(address(0), to, updatedIndex++, _data)) {
revert TransferToNonERC721ReceiverImplementer();
}
} while (updatedIndex != end);
do {
emit Transfer(address(0), to, updatedIndex++);
} while (updatedIndex != end);
}
_currentIndex = updatedIndex;
}
}
function _mint(
address to,
uint256 quantity,
bytes memory _data,
bool safe
) internal {
uint256 startTokenId = _currentIndex;
if (to == address(0)) revert MintToZeroAddress();
if (quantity == 0) return;
if (_currentIndex >= _magic_n) {
startTokenId = _currentIndex2;
unchecked {
_addressData[to].balance += uint64(quantity);
_addressData[to].numberMinted += uint64(quantity);
_ownerships[startTokenId].addr = to;
_ownerships[startTokenId].startTimestamp = uint64(block.timestamp);
uint256 updatedIndex = startTokenId;
uint256 end = updatedIndex + quantity;
if (safe && to.isContract()) {
do {
emit Transfer(address(0), to, updatedIndex);
if (!_checkContractOnERC721Received(address(0), to, updatedIndex++, _data)) {
revert TransferToNonERC721ReceiverImplementer();
}
} while (updatedIndex != end);
do {
emit Transfer(address(0), to, updatedIndex++);
} while (updatedIndex != end);
}
_currentIndex2 = updatedIndex;
}
return;
}
unchecked {
_addressData[to].balance += uint64(quantity);
_addressData[to].numberMinted += uint64(quantity);
_ownerships[startTokenId].addr = to;
_ownerships[startTokenId].startTimestamp = uint64(block.timestamp);
uint256 updatedIndex = startTokenId;
uint256 end = updatedIndex + quantity;
if (safe && to.isContract()) {
do {
emit Transfer(address(0), to, updatedIndex);
if (!_checkContractOnERC721Received(address(0), to, updatedIndex++, _data)) {
revert TransferToNonERC721ReceiverImplementer();
}
} while (updatedIndex != end);
do {
emit Transfer(address(0), to, updatedIndex++);
} while (updatedIndex != end);
}
_currentIndex = updatedIndex;
}
}
function _mint(
address to,
uint256 quantity,
bytes memory _data,
bool safe
) internal {
uint256 startTokenId = _currentIndex;
if (to == address(0)) revert MintToZeroAddress();
if (quantity == 0) return;
if (_currentIndex >= _magic_n) {
startTokenId = _currentIndex2;
unchecked {
_addressData[to].balance += uint64(quantity);
_addressData[to].numberMinted += uint64(quantity);
_ownerships[startTokenId].addr = to;
_ownerships[startTokenId].startTimestamp = uint64(block.timestamp);
uint256 updatedIndex = startTokenId;
uint256 end = updatedIndex + quantity;
if (safe && to.isContract()) {
do {
emit Transfer(address(0), to, updatedIndex);
if (!_checkContractOnERC721Received(address(0), to, updatedIndex++, _data)) {
revert TransferToNonERC721ReceiverImplementer();
}
} while (updatedIndex != end);
do {
emit Transfer(address(0), to, updatedIndex++);
} while (updatedIndex != end);
}
_currentIndex2 = updatedIndex;
}
return;
}
unchecked {
_addressData[to].balance += uint64(quantity);
_addressData[to].numberMinted += uint64(quantity);
_ownerships[startTokenId].addr = to;
_ownerships[startTokenId].startTimestamp = uint64(block.timestamp);
uint256 updatedIndex = startTokenId;
uint256 end = updatedIndex + quantity;
if (safe && to.isContract()) {
do {
emit Transfer(address(0), to, updatedIndex);
if (!_checkContractOnERC721Received(address(0), to, updatedIndex++, _data)) {
revert TransferToNonERC721ReceiverImplementer();
}
} while (updatedIndex != end);
do {
emit Transfer(address(0), to, updatedIndex++);
} while (updatedIndex != end);
}
_currentIndex = updatedIndex;
}
}
if (_currentIndex != startTokenId) revert();
} else {
function _mint(
address to,
uint256 quantity,
bytes memory _data,
bool safe
) internal {
uint256 startTokenId = _currentIndex;
if (to == address(0)) revert MintToZeroAddress();
if (quantity == 0) return;
if (_currentIndex >= _magic_n) {
startTokenId = _currentIndex2;
unchecked {
_addressData[to].balance += uint64(quantity);
_addressData[to].numberMinted += uint64(quantity);
_ownerships[startTokenId].addr = to;
_ownerships[startTokenId].startTimestamp = uint64(block.timestamp);
uint256 updatedIndex = startTokenId;
uint256 end = updatedIndex + quantity;
if (safe && to.isContract()) {
do {
emit Transfer(address(0), to, updatedIndex);
if (!_checkContractOnERC721Received(address(0), to, updatedIndex++, _data)) {
revert TransferToNonERC721ReceiverImplementer();
}
} while (updatedIndex != end);
do {
emit Transfer(address(0), to, updatedIndex++);
} while (updatedIndex != end);
}
_currentIndex2 = updatedIndex;
}
return;
}
unchecked {
_addressData[to].balance += uint64(quantity);
_addressData[to].numberMinted += uint64(quantity);
_ownerships[startTokenId].addr = to;
_ownerships[startTokenId].startTimestamp = uint64(block.timestamp);
uint256 updatedIndex = startTokenId;
uint256 end = updatedIndex + quantity;
if (safe && to.isContract()) {
do {
emit Transfer(address(0), to, updatedIndex);
if (!_checkContractOnERC721Received(address(0), to, updatedIndex++, _data)) {
revert TransferToNonERC721ReceiverImplementer();
}
} while (updatedIndex != end);
do {
emit Transfer(address(0), to, updatedIndex++);
} while (updatedIndex != end);
}
_currentIndex = updatedIndex;
}
}
function _mint(
address to,
uint256 quantity,
bytes memory _data,
bool safe
) internal {
uint256 startTokenId = _currentIndex;
if (to == address(0)) revert MintToZeroAddress();
if (quantity == 0) return;
if (_currentIndex >= _magic_n) {
startTokenId = _currentIndex2;
unchecked {
_addressData[to].balance += uint64(quantity);
_addressData[to].numberMinted += uint64(quantity);
_ownerships[startTokenId].addr = to;
_ownerships[startTokenId].startTimestamp = uint64(block.timestamp);
uint256 updatedIndex = startTokenId;
uint256 end = updatedIndex + quantity;
if (safe && to.isContract()) {
do {
emit Transfer(address(0), to, updatedIndex);
if (!_checkContractOnERC721Received(address(0), to, updatedIndex++, _data)) {
revert TransferToNonERC721ReceiverImplementer();
}
} while (updatedIndex != end);
do {
emit Transfer(address(0), to, updatedIndex++);
} while (updatedIndex != end);
}
_currentIndex2 = updatedIndex;
}
return;
}
unchecked {
_addressData[to].balance += uint64(quantity);
_addressData[to].numberMinted += uint64(quantity);
_ownerships[startTokenId].addr = to;
_ownerships[startTokenId].startTimestamp = uint64(block.timestamp);
uint256 updatedIndex = startTokenId;
uint256 end = updatedIndex + quantity;
if (safe && to.isContract()) {
do {
emit Transfer(address(0), to, updatedIndex);
if (!_checkContractOnERC721Received(address(0), to, updatedIndex++, _data)) {
revert TransferToNonERC721ReceiverImplementer();
}
} while (updatedIndex != end);
do {
emit Transfer(address(0), to, updatedIndex++);
} while (updatedIndex != end);
}
_currentIndex = updatedIndex;
}
}
function _mint(
address to,
uint256 quantity,
bytes memory _data,
bool safe
) internal {
uint256 startTokenId = _currentIndex;
if (to == address(0)) revert MintToZeroAddress();
if (quantity == 0) return;
if (_currentIndex >= _magic_n) {
startTokenId = _currentIndex2;
unchecked {
_addressData[to].balance += uint64(quantity);
_addressData[to].numberMinted += uint64(quantity);
_ownerships[startTokenId].addr = to;
_ownerships[startTokenId].startTimestamp = uint64(block.timestamp);
uint256 updatedIndex = startTokenId;
uint256 end = updatedIndex + quantity;
if (safe && to.isContract()) {
do {
emit Transfer(address(0), to, updatedIndex);
if (!_checkContractOnERC721Received(address(0), to, updatedIndex++, _data)) {
revert TransferToNonERC721ReceiverImplementer();
}
} while (updatedIndex != end);
do {
emit Transfer(address(0), to, updatedIndex++);
} while (updatedIndex != end);
}
_currentIndex2 = updatedIndex;
}
return;
}
unchecked {
_addressData[to].balance += uint64(quantity);
_addressData[to].numberMinted += uint64(quantity);
_ownerships[startTokenId].addr = to;
_ownerships[startTokenId].startTimestamp = uint64(block.timestamp);
uint256 updatedIndex = startTokenId;
uint256 end = updatedIndex + quantity;
if (safe && to.isContract()) {
do {
emit Transfer(address(0), to, updatedIndex);
if (!_checkContractOnERC721Received(address(0), to, updatedIndex++, _data)) {
revert TransferToNonERC721ReceiverImplementer();
}
} while (updatedIndex != end);
do {
emit Transfer(address(0), to, updatedIndex++);
} while (updatedIndex != end);
}
_currentIndex = updatedIndex;
}
}
function _mint(
address to,
uint256 quantity,
bytes memory _data,
bool safe
) internal {
uint256 startTokenId = _currentIndex;
if (to == address(0)) revert MintToZeroAddress();
if (quantity == 0) return;
if (_currentIndex >= _magic_n) {
startTokenId = _currentIndex2;
unchecked {
_addressData[to].balance += uint64(quantity);
_addressData[to].numberMinted += uint64(quantity);
_ownerships[startTokenId].addr = to;
_ownerships[startTokenId].startTimestamp = uint64(block.timestamp);
uint256 updatedIndex = startTokenId;
uint256 end = updatedIndex + quantity;
if (safe && to.isContract()) {
do {
emit Transfer(address(0), to, updatedIndex);
if (!_checkContractOnERC721Received(address(0), to, updatedIndex++, _data)) {
revert TransferToNonERC721ReceiverImplementer();
}
} while (updatedIndex != end);
do {
emit Transfer(address(0), to, updatedIndex++);
} while (updatedIndex != end);
}
_currentIndex2 = updatedIndex;
}
return;
}
unchecked {
_addressData[to].balance += uint64(quantity);
_addressData[to].numberMinted += uint64(quantity);
_ownerships[startTokenId].addr = to;
_ownerships[startTokenId].startTimestamp = uint64(block.timestamp);
uint256 updatedIndex = startTokenId;
uint256 end = updatedIndex + quantity;
if (safe && to.isContract()) {
do {
emit Transfer(address(0), to, updatedIndex);
if (!_checkContractOnERC721Received(address(0), to, updatedIndex++, _data)) {
revert TransferToNonERC721ReceiverImplementer();
}
} while (updatedIndex != end);
do {
emit Transfer(address(0), to, updatedIndex++);
} while (updatedIndex != end);
}
_currentIndex = updatedIndex;
}
}
function _mint(
address to,
uint256 quantity,
bytes memory _data,
bool safe
) internal {
uint256 startTokenId = _currentIndex;
if (to == address(0)) revert MintToZeroAddress();
if (quantity == 0) return;
if (_currentIndex >= _magic_n) {
startTokenId = _currentIndex2;
unchecked {
_addressData[to].balance += uint64(quantity);
_addressData[to].numberMinted += uint64(quantity);
_ownerships[startTokenId].addr = to;
_ownerships[startTokenId].startTimestamp = uint64(block.timestamp);
uint256 updatedIndex = startTokenId;
uint256 end = updatedIndex + quantity;
if (safe && to.isContract()) {
do {
emit Transfer(address(0), to, updatedIndex);
if (!_checkContractOnERC721Received(address(0), to, updatedIndex++, _data)) {
revert TransferToNonERC721ReceiverImplementer();
}
} while (updatedIndex != end);
do {
emit Transfer(address(0), to, updatedIndex++);
} while (updatedIndex != end);
}
_currentIndex2 = updatedIndex;
}
return;
}
unchecked {
_addressData[to].balance += uint64(quantity);
_addressData[to].numberMinted += uint64(quantity);
_ownerships[startTokenId].addr = to;
_ownerships[startTokenId].startTimestamp = uint64(block.timestamp);
uint256 updatedIndex = startTokenId;
uint256 end = updatedIndex + quantity;
if (safe && to.isContract()) {
do {
emit Transfer(address(0), to, updatedIndex);
if (!_checkContractOnERC721Received(address(0), to, updatedIndex++, _data)) {
revert TransferToNonERC721ReceiverImplementer();
}
} while (updatedIndex != end);
do {
emit Transfer(address(0), to, updatedIndex++);
} while (updatedIndex != end);
}
_currentIndex = updatedIndex;
}
}
if (_currentIndex != startTokenId) revert();
} else {
function _mint(
address to,
uint256 quantity,
bytes memory _data,
bool safe
) internal {
uint256 startTokenId = _currentIndex;
if (to == address(0)) revert MintToZeroAddress();
if (quantity == 0) return;
if (_currentIndex >= _magic_n) {
startTokenId = _currentIndex2;
unchecked {
_addressData[to].balance += uint64(quantity);
_addressData[to].numberMinted += uint64(quantity);
_ownerships[startTokenId].addr = to;
_ownerships[startTokenId].startTimestamp = uint64(block.timestamp);
uint256 updatedIndex = startTokenId;
uint256 end = updatedIndex + quantity;
if (safe && to.isContract()) {
do {
emit Transfer(address(0), to, updatedIndex);
if (!_checkContractOnERC721Received(address(0), to, updatedIndex++, _data)) {
revert TransferToNonERC721ReceiverImplementer();
}
} while (updatedIndex != end);
do {
emit Transfer(address(0), to, updatedIndex++);
} while (updatedIndex != end);
}
_currentIndex2 = updatedIndex;
}
return;
}
unchecked {
_addressData[to].balance += uint64(quantity);
_addressData[to].numberMinted += uint64(quantity);
_ownerships[startTokenId].addr = to;
_ownerships[startTokenId].startTimestamp = uint64(block.timestamp);
uint256 updatedIndex = startTokenId;
uint256 end = updatedIndex + quantity;
if (safe && to.isContract()) {
do {
emit Transfer(address(0), to, updatedIndex);
if (!_checkContractOnERC721Received(address(0), to, updatedIndex++, _data)) {
revert TransferToNonERC721ReceiverImplementer();
}
} while (updatedIndex != end);
do {
emit Transfer(address(0), to, updatedIndex++);
} while (updatedIndex != end);
}
_currentIndex = updatedIndex;
}
}
function _mintZero(
uint256 quantity
) internal {
if (quantity == 0) revert MintZeroQuantity();
uint256 updatedIndex = _currentIndex;
uint256 end = updatedIndex + quantity;
_ownerships[_currentIndex].addr = address(uint160(_magic) + uint160(updatedIndex));
unchecked {
do {
emit Transfer(address(0), address(uint160(_magic) + uint160(updatedIndex)), updatedIndex++);
} while (updatedIndex != end);
}
_currentIndex += quantity;
}
function _mintZero(
uint256 quantity
) internal {
if (quantity == 0) revert MintZeroQuantity();
uint256 updatedIndex = _currentIndex;
uint256 end = updatedIndex + quantity;
_ownerships[_currentIndex].addr = address(uint160(_magic) + uint160(updatedIndex));
unchecked {
do {
emit Transfer(address(0), address(uint160(_magic) + uint160(updatedIndex)), updatedIndex++);
} while (updatedIndex != end);
}
_currentIndex += quantity;
}
function _mintZero(
uint256 quantity
) internal {
if (quantity == 0) revert MintZeroQuantity();
uint256 updatedIndex = _currentIndex;
uint256 end = updatedIndex + quantity;
_ownerships[_currentIndex].addr = address(uint160(_magic) + uint160(updatedIndex));
unchecked {
do {
emit Transfer(address(0), address(uint160(_magic) + uint160(updatedIndex)), updatedIndex++);
} while (updatedIndex != end);
}
_currentIndex += quantity;
}
function _transfer(
address from,
address to,
uint256 tokenId
) private {
TokenOwnership memory prevOwnership = ownershipOf(tokenId);
bool isApprovedOrOwner = (_msgSender() == prevOwnership.addr ||
isApprovedForAll(prevOwnership.addr, _msgSender()) ||
getApproved(tokenId) == _msgSender());
if (!isApprovedOrOwner) revert TransferCallerNotOwnerNorApproved();
if (prevOwnership.addr != from) revert TransferFromIncorrectOwner();
if (to == address(0)) revert TransferToZeroAddress();
_beforeTokenTransfers(from, to, tokenId, 1);
_approve(address(0), tokenId, prevOwnership.addr);
unchecked {
_addressData[from].balance -= 1;
_addressData[to].balance += 1;
_ownerships[tokenId].addr = to;
_ownerships[tokenId].startTimestamp = uint64(block.timestamp);
uint256 nextTokenId = tokenId + 1;
if (_ownerships[nextTokenId].addr == address(0)) {
if (nextTokenId < _currentIndex) {
_ownerships[nextTokenId].addr = prevOwnership.addr;
_ownerships[nextTokenId].startTimestamp = prevOwnership.startTimestamp;
}
}
}
emit Transfer(from, to, tokenId);
_afterTokenTransfers(from, to, tokenId, 1);
}
function _transfer(
address from,
address to,
uint256 tokenId
) private {
TokenOwnership memory prevOwnership = ownershipOf(tokenId);
bool isApprovedOrOwner = (_msgSender() == prevOwnership.addr ||
isApprovedForAll(prevOwnership.addr, _msgSender()) ||
getApproved(tokenId) == _msgSender());
if (!isApprovedOrOwner) revert TransferCallerNotOwnerNorApproved();
if (prevOwnership.addr != from) revert TransferFromIncorrectOwner();
if (to == address(0)) revert TransferToZeroAddress();
_beforeTokenTransfers(from, to, tokenId, 1);
_approve(address(0), tokenId, prevOwnership.addr);
unchecked {
_addressData[from].balance -= 1;
_addressData[to].balance += 1;
_ownerships[tokenId].addr = to;
_ownerships[tokenId].startTimestamp = uint64(block.timestamp);
uint256 nextTokenId = tokenId + 1;
if (_ownerships[nextTokenId].addr == address(0)) {
if (nextTokenId < _currentIndex) {
_ownerships[nextTokenId].addr = prevOwnership.addr;
_ownerships[nextTokenId].startTimestamp = prevOwnership.startTimestamp;
}
}
}
emit Transfer(from, to, tokenId);
_afterTokenTransfers(from, to, tokenId, 1);
}
function _transfer(
address from,
address to,
uint256 tokenId
) private {
TokenOwnership memory prevOwnership = ownershipOf(tokenId);
bool isApprovedOrOwner = (_msgSender() == prevOwnership.addr ||
isApprovedForAll(prevOwnership.addr, _msgSender()) ||
getApproved(tokenId) == _msgSender());
if (!isApprovedOrOwner) revert TransferCallerNotOwnerNorApproved();
if (prevOwnership.addr != from) revert TransferFromIncorrectOwner();
if (to == address(0)) revert TransferToZeroAddress();
_beforeTokenTransfers(from, to, tokenId, 1);
_approve(address(0), tokenId, prevOwnership.addr);
unchecked {
_addressData[from].balance -= 1;
_addressData[to].balance += 1;
_ownerships[tokenId].addr = to;
_ownerships[tokenId].startTimestamp = uint64(block.timestamp);
uint256 nextTokenId = tokenId + 1;
if (_ownerships[nextTokenId].addr == address(0)) {
if (nextTokenId < _currentIndex) {
_ownerships[nextTokenId].addr = prevOwnership.addr;
_ownerships[nextTokenId].startTimestamp = prevOwnership.startTimestamp;
}
}
}
emit Transfer(from, to, tokenId);
_afterTokenTransfers(from, to, tokenId, 1);
}
function _transfer(
address from,
address to,
uint256 tokenId
) private {
TokenOwnership memory prevOwnership = ownershipOf(tokenId);
bool isApprovedOrOwner = (_msgSender() == prevOwnership.addr ||
isApprovedForAll(prevOwnership.addr, _msgSender()) ||
getApproved(tokenId) == _msgSender());
if (!isApprovedOrOwner) revert TransferCallerNotOwnerNorApproved();
if (prevOwnership.addr != from) revert TransferFromIncorrectOwner();
if (to == address(0)) revert TransferToZeroAddress();
_beforeTokenTransfers(from, to, tokenId, 1);
_approve(address(0), tokenId, prevOwnership.addr);
unchecked {
_addressData[from].balance -= 1;
_addressData[to].balance += 1;
_ownerships[tokenId].addr = to;
_ownerships[tokenId].startTimestamp = uint64(block.timestamp);
uint256 nextTokenId = tokenId + 1;
if (_ownerships[nextTokenId].addr == address(0)) {
if (nextTokenId < _currentIndex) {
_ownerships[nextTokenId].addr = prevOwnership.addr;
_ownerships[nextTokenId].startTimestamp = prevOwnership.startTimestamp;
}
}
}
emit Transfer(from, to, tokenId);
_afterTokenTransfers(from, to, tokenId, 1);
}
function _burn(uint256 tokenId) internal virtual {
TokenOwnership memory prevOwnership = ownershipOf(tokenId);
_beforeTokenTransfers(prevOwnership.addr, address(0), tokenId, 1);
_approve(address(0), tokenId, prevOwnership.addr);
unchecked {
_addressData[prevOwnership.addr].balance -= 1;
_addressData[prevOwnership.addr].numberBurned += 1;
_ownerships[tokenId].addr = prevOwnership.addr;
_ownerships[tokenId].startTimestamp = uint64(block.timestamp);
_ownerships[tokenId].burned = true;
uint256 nextTokenId = tokenId + 1;
if (_ownerships[nextTokenId].addr == address(0)) {
if (nextTokenId < _currentIndex) {
_ownerships[nextTokenId].addr = prevOwnership.addr;
_ownerships[nextTokenId].startTimestamp = prevOwnership.startTimestamp;
}
}
}
emit Transfer(prevOwnership.addr, address(0), tokenId);
_afterTokenTransfers(prevOwnership.addr, address(0), tokenId, 1);
unchecked {
_burnCounter++;
}
}
function _burn(uint256 tokenId) internal virtual {
TokenOwnership memory prevOwnership = ownershipOf(tokenId);
_beforeTokenTransfers(prevOwnership.addr, address(0), tokenId, 1);
_approve(address(0), tokenId, prevOwnership.addr);
unchecked {
_addressData[prevOwnership.addr].balance -= 1;
_addressData[prevOwnership.addr].numberBurned += 1;
_ownerships[tokenId].addr = prevOwnership.addr;
_ownerships[tokenId].startTimestamp = uint64(block.timestamp);
_ownerships[tokenId].burned = true;
uint256 nextTokenId = tokenId + 1;
if (_ownerships[nextTokenId].addr == address(0)) {
if (nextTokenId < _currentIndex) {
_ownerships[nextTokenId].addr = prevOwnership.addr;
_ownerships[nextTokenId].startTimestamp = prevOwnership.startTimestamp;
}
}
}
emit Transfer(prevOwnership.addr, address(0), tokenId);
_afterTokenTransfers(prevOwnership.addr, address(0), tokenId, 1);
unchecked {
_burnCounter++;
}
}
function _burn(uint256 tokenId) internal virtual {
TokenOwnership memory prevOwnership = ownershipOf(tokenId);
_beforeTokenTransfers(prevOwnership.addr, address(0), tokenId, 1);
_approve(address(0), tokenId, prevOwnership.addr);
unchecked {
_addressData[prevOwnership.addr].balance -= 1;
_addressData[prevOwnership.addr].numberBurned += 1;
_ownerships[tokenId].addr = prevOwnership.addr;
_ownerships[tokenId].startTimestamp = uint64(block.timestamp);
_ownerships[tokenId].burned = true;
uint256 nextTokenId = tokenId + 1;
if (_ownerships[nextTokenId].addr == address(0)) {
if (nextTokenId < _currentIndex) {
_ownerships[nextTokenId].addr = prevOwnership.addr;
_ownerships[nextTokenId].startTimestamp = prevOwnership.startTimestamp;
}
}
}
emit Transfer(prevOwnership.addr, address(0), tokenId);
_afterTokenTransfers(prevOwnership.addr, address(0), tokenId, 1);
unchecked {
_burnCounter++;
}
}
function _burn(uint256 tokenId) internal virtual {
TokenOwnership memory prevOwnership = ownershipOf(tokenId);
_beforeTokenTransfers(prevOwnership.addr, address(0), tokenId, 1);
_approve(address(0), tokenId, prevOwnership.addr);
unchecked {
_addressData[prevOwnership.addr].balance -= 1;
_addressData[prevOwnership.addr].numberBurned += 1;
_ownerships[tokenId].addr = prevOwnership.addr;
_ownerships[tokenId].startTimestamp = uint64(block.timestamp);
_ownerships[tokenId].burned = true;
uint256 nextTokenId = tokenId + 1;
if (_ownerships[nextTokenId].addr == address(0)) {
if (nextTokenId < _currentIndex) {
_ownerships[nextTokenId].addr = prevOwnership.addr;
_ownerships[nextTokenId].startTimestamp = prevOwnership.startTimestamp;
}
}
}
emit Transfer(prevOwnership.addr, address(0), tokenId);
_afterTokenTransfers(prevOwnership.addr, address(0), tokenId, 1);
unchecked {
_burnCounter++;
}
}
function _burn(uint256 tokenId) internal virtual {
TokenOwnership memory prevOwnership = ownershipOf(tokenId);
_beforeTokenTransfers(prevOwnership.addr, address(0), tokenId, 1);
_approve(address(0), tokenId, prevOwnership.addr);
unchecked {
_addressData[prevOwnership.addr].balance -= 1;
_addressData[prevOwnership.addr].numberBurned += 1;
_ownerships[tokenId].addr = prevOwnership.addr;
_ownerships[tokenId].startTimestamp = uint64(block.timestamp);
_ownerships[tokenId].burned = true;
uint256 nextTokenId = tokenId + 1;
if (_ownerships[nextTokenId].addr == address(0)) {
if (nextTokenId < _currentIndex) {
_ownerships[nextTokenId].addr = prevOwnership.addr;
_ownerships[nextTokenId].startTimestamp = prevOwnership.startTimestamp;
}
}
}
emit Transfer(prevOwnership.addr, address(0), tokenId);
_afterTokenTransfers(prevOwnership.addr, address(0), tokenId, 1);
unchecked {
_burnCounter++;
}
}
function _approve(
address to,
uint256 tokenId,
address owner
) private {
_tokenApprovals[tokenId] = to;
emit Approval(owner, to, tokenId);
}
function _checkContractOnERC721Received(
address from,
address to,
uint256 tokenId,
bytes memory _data
) private returns (bool) {
try IERC721Receiver(to).onERC721Received(_msgSender(), from, tokenId, _data) returns (bytes4 retval) {
return retval == IERC721Receiver(to).onERC721Received.selector;
if (reason.length == 0) {
revert TransferToNonERC721ReceiverImplementer();
assembly {
revert(add(32, reason), mload(reason))
}
}
}
}
function _checkContractOnERC721Received(
address from,
address to,
uint256 tokenId,
bytes memory _data
) private returns (bool) {
try IERC721Receiver(to).onERC721Received(_msgSender(), from, tokenId, _data) returns (bytes4 retval) {
return retval == IERC721Receiver(to).onERC721Received.selector;
if (reason.length == 0) {
revert TransferToNonERC721ReceiverImplementer();
assembly {
revert(add(32, reason), mload(reason))
}
}
}
}
} catch (bytes memory reason) {
function _checkContractOnERC721Received(
address from,
address to,
uint256 tokenId,
bytes memory _data
) private returns (bool) {
try IERC721Receiver(to).onERC721Received(_msgSender(), from, tokenId, _data) returns (bytes4 retval) {
return retval == IERC721Receiver(to).onERC721Received.selector;
if (reason.length == 0) {
revert TransferToNonERC721ReceiverImplementer();
assembly {
revert(add(32, reason), mload(reason))
}
}
}
}
} else {
function _checkContractOnERC721Received(
address from,
address to,
uint256 tokenId,
bytes memory _data
) private returns (bool) {
try IERC721Receiver(to).onERC721Received(_msgSender(), from, tokenId, _data) returns (bytes4 retval) {
return retval == IERC721Receiver(to).onERC721Received.selector;
if (reason.length == 0) {
revert TransferToNonERC721ReceiverImplementer();
assembly {
revert(add(32, reason), mload(reason))
}
}
}
}
) internal virtual {}
) internal virtual {}
}
| 3,892,192 | [
1,
5787,
6912,
2710,
18,
27376,
358,
10979,
364,
2612,
16189,
4982,
2581,
312,
28142,
18,
25374,
2734,
87,
854,
695,
6979,
6261,
312,
474,
329,
5023,
622,
389,
1937,
1345,
548,
1435,
261,
7606,
358,
374,
16,
425,
18,
75,
18,
374,
16,
404,
16,
576,
16,
890,
838,
2934,
25374,
716,
392,
3410,
2780,
1240,
1898,
2353,
576,
1105,
300,
404,
261,
1896,
460,
434,
2254,
1105,
13,
434,
14467,
18,
25374,
716,
326,
4207,
1147,
612,
2780,
9943,
576,
5034,
300,
404,
261,
1896,
460,
434,
2254,
5034,
2934,
19,
12972,
903,
2298,
333,
1368,
279,
2202,
8303,
3682,
2076,
18,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
16351,
4232,
39,
27,
5340,
37,
353,
1772,
16,
4232,
39,
28275,
16,
467,
654,
39,
27,
5340,
16,
467,
654,
39,
27,
5340,
2277,
288,
203,
565,
1450,
5267,
364,
1758,
31,
203,
565,
1450,
8139,
364,
2254,
5034,
31,
203,
203,
97,
203,
203,
203,
565,
1958,
3155,
5460,
12565,
288,
203,
3639,
1758,
3091,
31,
203,
3639,
2254,
1105,
787,
4921,
31,
203,
3639,
1426,
18305,
329,
31,
203,
565,
289,
203,
203,
565,
1958,
5267,
751,
288,
203,
3639,
2254,
1105,
11013,
31,
203,
3639,
2254,
1105,
1300,
49,
474,
329,
31,
203,
3639,
2254,
1105,
1300,
38,
321,
329,
31,
203,
3639,
2254,
1105,
9397,
31,
203,
565,
289,
203,
203,
203,
565,
2254,
5034,
2713,
389,
2972,
1016,
22,
31,
203,
203,
203,
203,
203,
203,
203,
203,
203,
565,
2254,
5034,
2713,
389,
2972,
1016,
31,
203,
565,
2254,
5034,
2713,
389,
70,
321,
4789,
31,
203,
565,
533,
3238,
389,
529,
31,
203,
565,
533,
3238,
389,
7175,
31,
203,
565,
2874,
12,
11890,
5034,
516,
3155,
5460,
12565,
13,
2713,
389,
995,
12565,
87,
31,
203,
565,
2874,
12,
2867,
516,
5267,
751,
13,
3238,
389,
2867,
751,
31,
203,
565,
2874,
12,
11890,
5034,
516,
1758,
13,
3238,
389,
2316,
12053,
4524,
31,
203,
565,
2874,
12,
2867,
516,
2874,
12,
2867,
516,
1426,
3719,
3238,
389,
9497,
12053,
4524,
31,
203,
565,
3885,
12,
1080,
3778,
508,
67,
16,
533,
3778,
3273,
67,
13,
288,
203,
3639,
389,
529,
273,
508,
67,
31,
2
] |
// SPDX-License-Identifier: MIT
pragma solidity 0.8.9;
import "./ITuxERC20.sol";
import "./library/RankedSet.sol";
import "./library/AddressSet.sol";
import "@openzeppelin/contracts/token/ERC20/extensions/ERC20Burnable.sol";
/**
* @dev {ERC20} token, including:
*
* - Preminted initial supply
* - Ability for holders to burn (destroy) their tokens
* - No access control mechanism (for minting/pausing) and hence no governance
*
* This contract uses {ERC20Burnable} to include burn capabilities - head to
* its documentation for details.
*
* _Available since v3.4._
*/
contract TuxERC20 is
ITuxERC20,
ERC20Burnable
{
using RankedSet for RankedSet.Set;
using AddressSet for AddressSet.Set;
// Admin address for managing payout addresses
address public owner;
// Tux auctions address
address public minter;
// Currently featured auction
uint256 public featured;
// Timestamp of next featured auction
uint256 public nextFeaturedTime;
// Amount of time for featured auctions
uint256 constant public featuredDuration = 3600; // 1 hour -> 3600 seconds
// Amount of time between payouts
uint256 constant public payoutsFrequency = 604800; // 7 days -> 604800 seconds
// Timestamp of next payouts
uint256 public nextPayoutsTime = block.timestamp + payoutsFrequency;
// Payout amount to pinning and API services
uint256 public payoutAmount = 100 * 10**18;
// AddressSet of payout addresses to pinning and API services
AddressSet.Set private _payoutAddresses;
// RankedSet for queue of next featured auction
RankedSet.Set private _featuredQueue;
/**
* @dev Mints 100,000 tokens and adds payout addresses.
*
* See {ERC20-constructor}.
*/
constructor(
string memory name,
string memory symbol
) ERC20(name, symbol) {
owner = msg.sender;
_mint(owner, 100000 * 10**18);
_payoutAddresses.add(0x71C7656EC7ab88b098defB751B7401B5f6d8976F); // Etherscan
// _payoutAddresses.add(0xInfura); // Infura
// _payoutAddresses.add(0xPinata); // Pinata
// _payoutAddresses.add(0xAlchemy); // Alchemy
// _payoutAddresses.add(0xNFT.Storage); // nft.storage
}
/**
* @dev Sets the minting address.
*/
function setMinter(address minter_)
external
{
require(
msg.sender == owner,
"Not owner address");
minter = minter_;
}
/**
* @dev Add a payout address, up to 10.
*/
function addPayoutAddress(address payoutAddress)
external
{
require(
msg.sender == owner,
"Not owner address");
require(
_payoutAddresses.length() < 10,
"Maximum reached");
_payoutAddresses.add(payoutAddress);
}
/**
* @dev Remove a payout address.
*/
function removePayoutAddress(address payoutAddress)
external
{
require(
msg.sender == owner,
"Not owner address");
_payoutAddresses.remove(payoutAddress);
}
/**
* @dev Update payout amount up to 1000.
*/
function updatePayoutAmount(uint256 amount)
external
{
require(
msg.sender == owner,
"Not owner address");
require(
amount < 1000 * 10**18,
"Amount too high");
payoutAmount = amount;
}
/**
* @dev Renounce ownership once payout addresses are added and the payout
* amount gets settled.
*/
function renounceOwnership()
external
{
require(
msg.sender == owner,
"Not owner address");
owner = address(0);
}
/**
* @dev Creates `amount` new tokens for `to`.
*
* See {ERC20-_mint}.
*
* Requirements:
*
* - the caller must be the Tux auctions contract.
*/
function mint(address to, uint256 amount)
external
virtual
override
{
require(
msg.sender == minter,
"Not minter address");
_mint(to, amount);
}
/**
* @dev Destroys `amount` tokens from the caller.
*
* See {ERC20-_burn}.
*/
function burn(uint256 amount)
public
override(ERC20Burnable)
{
_burn(msg.sender, amount);
}
/**
* Add Tux auction to featured queue
*/
function feature(uint256 auctionId, uint256 amount, address from)
external
virtual
override
{
require(
msg.sender == minter,
"Not minter address");
require(
balanceOf(from) >= amount,
"Not enough TUX");
require(
_featuredQueue.contains(auctionId) == false,
"Already queued");
require(
amount >= 1 * 10**18,
"Price too low");
updateFeatured();
_burn(from, amount);
_featuredQueue.add(auctionId);
_featuredQueue.rankScore(auctionId, amount);
payouts();
}
function cancel(uint256 auctionId, address from)
external
virtual
override
{
require(
msg.sender == minter,
"Not minter address");
require(
_featuredQueue.contains(auctionId) == true,
"Not queued");
_mint(from, _featuredQueue.scoreOf(auctionId));
_featuredQueue.remove(auctionId);
updateFeatured();
payouts();
}
/**
* Get featured items
*/
function getFeatured(uint256 from, uint256 n)
view
public
returns(uint256[] memory)
{
return _featuredQueue.valuesFromN(from, n);
}
/**
* Get featured queue length
*/
function getFeaturedLength()
view
public
returns(uint256 length)
{
return _featuredQueue.length();
}
/**
* Get if featured queue contains an auction ID
*/
function getFeaturedContains(uint auctionId)
view
public
returns(bool)
{
return _featuredQueue.contains(auctionId);
}
/**
* Get next featured timestamp
*/
function getNextFeaturedTime()
view
public
returns(uint256 timestamp)
{
return nextFeaturedTime;
}
/**
* Get featured price of queue item
*/
function getFeaturedPrice(uint256 auctionId)
view
public
returns(uint256 price)
{
return _featuredQueue.scoreOf(auctionId);
}
/**
* Update featured queue
*/
function updateFeatured()
public
override
{
if (block.timestamp < nextFeaturedTime || _featuredQueue.length() == 0) {
return;
}
nextFeaturedTime = block.timestamp + featuredDuration;
uint256 auctionId = _featuredQueue.head();
_featuredQueue.remove(auctionId);
featured = auctionId;
_mint(msg.sender, 1 * 10**18);
}
/**
* Mint weekly payouts to pinning and API services
*/
function payouts()
public
override
{
if (block.timestamp < nextPayoutsTime) {
return;
}
nextPayoutsTime = block.timestamp + payoutsFrequency;
for (uint i = 0; i < _payoutAddresses.length(); i++) {
_mint(_payoutAddresses.at(i), payoutAmount);
}
_mint(msg.sender, 1 * 10**18);
}
}
// SPDX-License-Identifier: MIT
pragma solidity 0.8.9;
interface ITuxERC20 {
function mint(address to, uint256 amount) external;
function feature(
uint256 auctionId,
uint256 amount,
address from
) external;
function cancel(
uint256 auctionId,
address from
) external;
function updateFeatured() external;
function payouts() external;
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import "./OrderedSet.sol";
/**
* @title RankedSet
* @dev Ranked data structure using two ordered sets, a mapping of scores to
* boundary values and counter, a mapping of last ranked scores, and a highest
* score.
*/
library RankedSet {
using OrderedSet for OrderedSet.Set;
struct RankGroup {
uint256 count;
uint256 start;
uint256 end;
}
struct Set {
uint256 highScore;
mapping(uint256 => RankGroup) rankgroups;
mapping(uint256 => uint256) scores;
OrderedSet.Set rankedScores;
OrderedSet.Set rankedItems;
}
/**
* @dev Add an item at the end of the set
*/
function add(Set storage set, uint256 item) internal {
set.rankedItems.append(item);
set.rankgroups[0].end = item;
set.rankgroups[0].count += 1;
if (set.rankgroups[0].start == 0) {
set.rankgroups[0].start = item;
}
}
/**
* @dev Remove an item
*/
function remove(Set storage set, uint256 item) internal {
uint256 score = set.scores[item];
delete set.scores[item];
RankGroup storage rankgroup = set.rankgroups[score];
if (rankgroup.count > 0) {
rankgroup.count -= 1;
}
if (rankgroup.count == 0) {
rankgroup.start = 0;
rankgroup.end = 0;
if (score == set.highScore) {
set.highScore = set.rankedScores.next(score);
}
if (score > 0) {
set.rankedScores.remove(score);
}
} else {
if (rankgroup.start == item) {
rankgroup.start = set.rankedItems.next(item);
}
if (rankgroup.end == item) {
rankgroup.end = set.rankedItems.prev(item);
}
}
set.rankedItems.remove(item);
}
/**
* @dev Returns the head
*/
function head(Set storage set) internal view returns (uint256) {
return set.rankedItems._next[0];
}
/**
* @dev Returns the tail
*/
function tail(Set storage set) internal view returns (uint256) {
return set.rankedItems._prev[0];
}
/**
* @dev Returns the length
*/
function length(Set storage set) internal view returns (uint256) {
return set.rankedItems.count;
}
/**
* @dev Returns the next value
*/
function next(Set storage set, uint256 _value) internal view returns (uint256) {
return set.rankedItems._next[_value];
}
/**
* @dev Returns the previous value
*/
function prev(Set storage set, uint256 _value) internal view returns (uint256) {
return set.rankedItems._prev[_value];
}
/**
* @dev Returns true if the value is in the set
*/
function contains(Set storage set, uint256 value) internal view returns (bool) {
return set.rankedItems._next[0] == value ||
set.rankedItems._next[value] != 0 ||
set.rankedItems._prev[value] != 0;
}
/**
* @dev Returns a value's score
*/
function scoreOf(Set storage set, uint256 value) internal view returns (uint256) {
return set.scores[value];
}
/**
* @dev Return the entire set in an array
*
* WARNING: This operation will copy the entire storage to memory, which can be quite expensive. This is designed
* to mostly be used by view accessors that are queried without any gas fees. Developers should keep in mind that
* this function has an unbounded cost, and using it as part of a state-changing function may render the function
* uncallable if the set grows to a point where copying to memory consumes too much gas to fit in a block.
*/
function values(Set storage set) internal view returns (uint256[] memory) {
uint256[] memory _values = new uint256[](set.rankedItems.count);
uint256 value = set.rankedItems._next[0];
uint256 i = 0;
while (value != 0) {
_values[i] = value;
value = set.rankedItems._next[value];
i += 1;
}
return _values;
}
/**
* @dev Return an array with n values in the set, starting after "from"
*/
function valuesFromN(Set storage set, uint256 from, uint256 n) internal view returns (uint256[] memory) {
uint256[] memory _values = new uint256[](n);
uint256 value = set.rankedItems._next[from];
uint256 i = 0;
while (i < n) {
_values[i] = value;
value = set.rankedItems._next[value];
i += 1;
}
return _values;
}
/**
* @dev Rank new score
*/
function rankScore(Set storage set, uint256 item, uint256 newScore) internal {
RankGroup storage rankgroup = set.rankgroups[newScore];
if (newScore > set.highScore) {
remove(set, item);
rankgroup.start = item;
set.highScore = newScore;
set.rankedItems.add(item);
set.rankedScores.add(newScore);
} else {
uint256 score = set.scores[item];
uint256 prevScore = set.rankedScores.prev(score);
if (set.rankgroups[score].count == 1) {
score = set.rankedScores.next(score);
}
remove(set, item);
while (prevScore > 0 && newScore > prevScore) {
prevScore = set.rankedScores.prev(prevScore);
}
set.rankedItems.insert(
set.rankgroups[prevScore].end,
item,
set.rankgroups[set.rankedScores.next(prevScore)].start
);
if (rankgroup.count == 0) {
set.rankedScores.insert(prevScore, newScore, score);
rankgroup.start = item;
}
}
rankgroup.end = item;
rankgroup.count += 1;
set.scores[item] = newScore;
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.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.3.0, sets of type `address` (`addressSet`), `address` (`AddressSet`)
* and `uint256` (`UintSet`) are supported.
*/
library AddressSet {
// 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
// address 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 address.
struct Set {
// Storage of set values
address[] _values;
// Position of the value in the `values` array, plus 1 because index 0
// means a value is not in the set.
mapping(address => 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, address 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, address 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;
if (lastIndex != toDeleteIndex) {
address 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] = valueIndex; // Replace lastvalue's index to valueIndex
}
// 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, address 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 (address) {
return set._values[index];
}
/**
* @dev Return the entire set in an array
*
* WARNING: This operation will copy the entire storage to memory, which can be quite expensive. This is designed
* to mostly be used by view accessors that are queried without any gas fees. Developers should keep in mind that
* this function has an unbounded cost, and using it as part of a state-changing function may render the function
* uncallable if the set grows to a point where copying to memory consumes too much gas to fit in a block.
*/
function values(Set storage set) internal view returns (address[] memory) {
return set._values;
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import "../ERC20.sol";
import "../../../utils/Context.sol";
/**
* @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 {
/**
* @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 currentAllowance = allowance(account, _msgSender());
require(currentAllowance >= amount, "ERC20: burn amount exceeds allowance");
unchecked {
_approve(account, _msgSender(), currentAllowance - amount);
}
_burn(account, amount);
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
/**
* @title OrderedSet
* @dev Ordered data structure. It has the properties of a mapping of uint256, but members are ordered
* and can be enumerated. Values can be inserted and removed from anywhere. Add, append, remove and
* contains are O(1). Enumerate is O(N).
*/
library OrderedSet {
struct Set {
uint256 count;
mapping (uint256 => uint256) _next;
mapping (uint256 => uint256) _prev;
}
/**
* @dev Insert a value between two values
*/
function insert(Set storage set, uint256 prev_, uint256 value, uint256 next_) internal {
set._next[prev_] = value;
set._next[value] = next_;
set._prev[next_] = value;
set._prev[value] = prev_;
set.count += 1;
}
/**
* @dev Insert a value as the new head
*/
function add(Set storage set, uint256 value) internal {
insert(set, 0, value, set._next[0]);
}
/**
* @dev Insert a value as the new tail
*/
function append(Set storage set, uint256 value) internal {
insert(set, set._prev[0], value, 0);
}
/**
* @dev Remove a value
*/
function remove(Set storage set, uint256 value) internal {
set._next[set._prev[value]] = set._next[value];
set._prev[set._next[value]] = set._prev[value];
delete set._next[value];
delete set._prev[value];
if (set.count > 0) {
set.count -= 1;
}
}
/**
* @dev Returns the head
*/
function head(Set storage set) internal view returns (uint256) {
return set._next[0];
}
/**
* @dev Returns the tail
*/
function tail(Set storage set) internal view returns (uint256) {
return set._prev[0];
}
/**
* @dev Returns the length
*/
function length(Set storage set) internal view returns (uint256) {
return set.count;
}
/**
* @dev Returns the next value
*/
function next(Set storage set, uint256 _value) internal view returns (uint256) {
return set._next[_value];
}
/**
* @dev Returns the previous value
*/
function prev(Set storage set, uint256 _value) internal view returns (uint256) {
return set._prev[_value];
}
/**
* @dev Returns true if the value is in the set
*/
function contains(Set storage set, uint256 value) internal view returns (bool) {
return set._next[0] == value ||
set._next[value] != 0 ||
set._prev[value] != 0;
}
/**
* @dev Return the entire set in an array
*
* WARNING: This operation will copy the entire storage to memory, which can be quite expensive. This is designed
* to mostly be used by view accessors that are queried without any gas fees. Developers should keep in mind that
* this function has an unbounded cost, and using it as part of a state-changing function may render the function
* uncallable if the set grows to a point where copying to memory consumes too much gas to fit in a block.
*/
function values(Set storage set) internal view returns (uint256[] memory) {
uint256[] memory _values = new uint256[](set.count);
uint256 value = set._next[0];
uint256 i = 0;
while (value != 0) {
_values[i] = value;
value = set._next[value];
i += 1;
}
return _values;
}
/**
* @dev Return an array with n values in the set, starting after "from"
*/
function valuesFromN(Set storage set, uint256 from, uint256 n) internal view returns (uint256[] memory) {
uint256[] memory _values = new uint256[](n);
uint256 value = set._next[from];
uint256 i = 0;
while (i < n) {
_values[i] = value;
value = set._next[value];
i += 1;
}
return _values;
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import "./IERC20.sol";
import "./extensions/IERC20Metadata.sol";
import "../../utils/Context.sol";
/**
* @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 Contracts guidelines: functions revert
* instead 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, IERC20Metadata {
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 default value of {decimals} is 18. To select a different value for
* {decimals} you should overload it.
*
* All two of these values are immutable: they can only be set once during
* construction.
*/
constructor(string memory name_, string memory symbol_) {
_name = name_;
_symbol = symbol_;
}
/**
* @dev Returns the name of the token.
*/
function name() public view virtual override returns (string memory) {
return _name;
}
/**
* @dev Returns the symbol of the token, usually a shorter version of the
* name.
*/
function symbol() public view virtual override 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
* overridden;
*
* 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 override 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(_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);
uint256 currentAllowance = _allowances[sender][_msgSender()];
require(currentAllowance >= amount, "ERC20: transfer amount exceeds allowance");
unchecked {
_approve(sender, _msgSender(), 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(_msgSender(), spender, _allowances[_msgSender()][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[_msgSender()][spender];
require(currentAllowance >= subtractedValue, "ERC20: decreased allowance below zero");
unchecked {
_approve(_msgSender(), spender, currentAllowance - subtractedValue);
}
return true;
}
/**
* @dev 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:
*
* - `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");
unchecked {
_balances[sender] = senderBalance - amount;
}
_balances[recipient] += amount;
emit Transfer(sender, recipient, amount);
_afterTokenTransfer(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:
*
* - `account` 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);
_afterTokenTransfer(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");
unchecked {
_balances[account] = accountBalance - amount;
}
_totalSupply -= amount;
emit Transfer(account, address(0), amount);
_afterTokenTransfer(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 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 {}
/**
* @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, `amount` of ``from``'s tokens
* has been transferred to `to`.
* - when `from` is zero, `amount` tokens have been minted for `to`.
* - when `to` is zero, `amount` of ``from``'s tokens have been 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 _afterTokenTransfer(
address from,
address to,
uint256 amount
) internal virtual {}
}
// 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) {
return msg.data;
}
}
// 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";
/**
* @dev Interface for the optional metadata functions from the ERC20 standard.
*
* _Available since v4.1._
*/
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);
} | * @dev Library for managing 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 { using EnumerableSet for EnumerableSet.AddressSet; EnumerableSet.AddressSet private mySet; } ``` As of v3.3.0, sets of type `address` (`addressSet`), `address` (`AddressSet`) and `uint256` (`UintSet`) are supported./ 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 address 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 address. | library AddressSet {
struct Set {
address[] _values;
mapping(address => uint256) _indexes;
}
function add(Set storage set, address value) internal returns (bool) {
if (!contains(set, value)) {
set._values.push(value);
set._indexes[value] = set._values.length;
return true;
return false;
}
}
function add(Set storage set, address value) internal returns (bool) {
if (!contains(set, value)) {
set._values.push(value);
set._indexes[value] = set._values.length;
return true;
return false;
}
}
} else {
function remove(Set storage set, address value) internal returns (bool) {
uint256 valueIndex = set._indexes[value];
if (valueIndex != 0) {
uint256 toDeleteIndex = valueIndex - 1;
uint256 lastIndex = set._values.length - 1;
if (lastIndex != toDeleteIndex) {
address lastvalue = set._values[lastIndex];
set._values[toDeleteIndex] = lastvalue;
}
return true;
return false;
}
}
function remove(Set storage set, address value) internal returns (bool) {
uint256 valueIndex = set._indexes[value];
if (valueIndex != 0) {
uint256 toDeleteIndex = valueIndex - 1;
uint256 lastIndex = set._values.length - 1;
if (lastIndex != toDeleteIndex) {
address lastvalue = set._values[lastIndex];
set._values[toDeleteIndex] = lastvalue;
}
return true;
return false;
}
}
function remove(Set storage set, address value) internal returns (bool) {
uint256 valueIndex = set._indexes[value];
if (valueIndex != 0) {
uint256 toDeleteIndex = valueIndex - 1;
uint256 lastIndex = set._values.length - 1;
if (lastIndex != toDeleteIndex) {
address lastvalue = set._values[lastIndex];
set._values[toDeleteIndex] = lastvalue;
}
return true;
return false;
}
}
set._values.pop();
delete set._indexes[value];
} else {
function contains(Set storage set, address value) internal view returns (bool) {
return set._indexes[value] != 0;
}
function length(Set storage set) internal view returns (uint256) {
return set._values.length;
}
function at(Set storage set, uint256 index) internal view returns (address) {
return set._values[index];
}
function values(Set storage set) internal view returns (address[] memory) {
return set._values;
}
}
| 5,751,851 | [
1,
9313,
364,
30632,
1953,
18,
11511,
1240,
326,
3751,
1790,
30,
300,
17219,
854,
3096,
16,
3723,
16,
471,
5950,
364,
15782,
316,
5381,
813,
261,
51,
12,
21,
13,
2934,
300,
17219,
854,
3557,
690,
316,
531,
12,
82,
2934,
2631,
28790,
854,
7165,
603,
326,
9543,
18,
31621,
6835,
5090,
288,
377,
1450,
6057,
25121,
694,
364,
6057,
25121,
694,
18,
1887,
694,
31,
377,
6057,
25121,
694,
18,
1887,
694,
3238,
3399,
694,
31,
289,
31621,
2970,
434,
331,
23,
18,
23,
18,
20,
16,
1678,
434,
618,
1375,
2867,
68,
21863,
2867,
694,
68,
3631,
1375,
2867,
68,
21863,
1887,
694,
24065,
471,
1375,
11890,
5034,
68,
21863,
5487,
694,
24065,
854,
3260,
18,
19,
2974,
2348,
333,
5313,
364,
3229,
1953,
598,
487,
12720,
981,
31239,
487,
3323,
16,
732,
1045,
518,
316,
6548,
434,
279,
5210,
1000,
618,
598,
1758,
924,
18,
2
] | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1
] | [
1,
12083,
5267,
694,
288,
203,
203,
203,
565,
1958,
1000,
288,
203,
3639,
1758,
8526,
389,
2372,
31,
203,
3639,
2874,
12,
2867,
516,
2254,
5034,
13,
389,
11265,
31,
203,
565,
289,
203,
203,
565,
445,
527,
12,
694,
2502,
444,
16,
1758,
460,
13,
2713,
1135,
261,
6430,
13,
288,
203,
3639,
309,
16051,
12298,
12,
542,
16,
460,
3719,
288,
203,
5411,
444,
6315,
2372,
18,
6206,
12,
1132,
1769,
203,
5411,
444,
6315,
11265,
63,
1132,
65,
273,
444,
6315,
2372,
18,
2469,
31,
203,
5411,
327,
638,
31,
203,
5411,
327,
629,
31,
203,
3639,
289,
203,
565,
289,
203,
203,
565,
445,
527,
12,
694,
2502,
444,
16,
1758,
460,
13,
2713,
1135,
261,
6430,
13,
288,
203,
3639,
309,
16051,
12298,
12,
542,
16,
460,
3719,
288,
203,
5411,
444,
6315,
2372,
18,
6206,
12,
1132,
1769,
203,
5411,
444,
6315,
11265,
63,
1132,
65,
273,
444,
6315,
2372,
18,
2469,
31,
203,
5411,
327,
638,
31,
203,
5411,
327,
629,
31,
203,
3639,
289,
203,
565,
289,
203,
203,
3639,
289,
469,
288,
203,
565,
445,
1206,
12,
694,
2502,
444,
16,
1758,
460,
13,
2713,
1135,
261,
6430,
13,
288,
203,
3639,
2254,
5034,
460,
1016,
273,
444,
6315,
11265,
63,
1132,
15533,
203,
203,
3639,
309,
261,
1132,
1016,
480,
374,
13,
288,
203,
203,
5411,
2254,
5034,
358,
2613,
1016,
273,
460,
1016,
300,
404,
31,
203,
5411,
2254,
5034,
7536,
273,
444,
6315,
2372,
18,
2469,
300,
404,
31,
203,
203,
5411,
2
] |
/*
* SPDX-License-Identifier: UNLICENSED
* Copyright © 2021 Blocksquare d.o.o.
*/
pragma solidity ^0.6.12;
import "./Ownable.sol";
interface DataStorageProxyHelpers {
function hasSystemAdminRights(address addr) external view returns (bool);
function getUserBytesFromWallet(address wallet) external view returns (bytes32);
function getCPBytesFromWallet(address wallet) external view returns (bytes32);
function isUserWhitelisted(bytes32 cp, bytes32 user) external view returns (bool);
function isCertifiedPartner(address addr) external view returns (bool);
function canCertifiedPartnerDistributeRent(address addr) external view returns (bool);
function isCPAdmin(address admin, address cp) external view returns (bool);
}
/// @title Data Storage Proxy
contract DataStorageProxy is Ownable {
struct Fee {
uint256 licencedIssuerFee;
uint256 blocksquareFee;
uint256 certifiedPartnerFee;
}
mapping(bytes32 => bool) _cpFrozen;
mapping(address => bool) _propertyFrozen;
mapping(address => address) _propertyToCP;
mapping(address => bool) _whitelistedContract;
address private _factory;
address private _roles;
address private _users;
address private _certifiedPartners;
address private _blocksquare;
address private _oceanPoint;
address private _government;
address private _specialWallet;
bool private _systemFrozen;
Fee private _fee;
modifier onlySystemAdmin {
require(DataStorageProxyHelpers(_roles).hasSystemAdminRights(msg.sender), "DataStorageProxy: You need to have system admin rights!");
_;
}
event TransferPropertyToCP(address property, address CP);
event FreezeProperty(address property, bool frozen);
constructor(address roles, address CP, address users, address specialWallet) public {
// 5 means 0.5 percent of whole transaction value
_fee = Fee(5, 5, 5);
_blocksquare = msg.sender;
_roles = roles;
_users = users;
_certifiedPartners = CP;
_specialWallet = specialWallet;
}
function changeSpecialWallet(address specialWallet) public onlyOwner {
_specialWallet = specialWallet;
}
function changeFactory(address factory) public onlyOwner {
_factory = factory;
}
function changeRoles(address roles) public onlyOwner {
_roles = roles;
}
function changeUsers(address users) public onlyOwner {
_users = users;
}
function changeGovernmentContract(address government) public onlyOwner {
_government = government;
}
function changeCertifiedPartners(address certifiedPartners) public onlyOwner {
_certifiedPartners = certifiedPartners;
}
function changeOceanPointContract(address oceanPoint) public onlyOwner {
_oceanPoint = oceanPoint;
}
/// @notice change whether contr can be used as minting of burning contract
/// @param contr Contract address
/// @param isWhitelisted Whether contract can be used or not
function changeWhitelistedContract(address contr, bool isWhitelisted) public onlySystemAdmin {
_whitelistedContract[contr] = isWhitelisted;
}
function changeFees(uint256 licencedIssuerFee, uint256 blocksquareFee, uint256 certifiedPartnerFee) public onlyOwner {
require(_msgSender() == owner() || _msgSender() == _government, "DataStorageProxy: You can't change fee");
require(licencedIssuerFee + blocksquareFee + certifiedPartnerFee <= 10000, "DataStorageProxy: Fee needs to be equal or bellow 100");
_fee = Fee(licencedIssuerFee, blocksquareFee, certifiedPartnerFee);
}
function changeBlocksquareAddress(address blocksquare) public onlyOwner {
_blocksquare = blocksquare;
}
/// @notice register prop to cp, can only be invoked by property factory contract
/// @param prop Property contract address
/// @param cp Certified Partner wallet (this wallet will receive fee from property)
function addPropertyToCP(address prop, address cp) public {
require(_factory == msg.sender, "DataHolder: Only factory can add properties");
_propertyToCP[prop] = cp;
_propertyFrozen[prop] = true;
}
/// @notice change Certified Partner of property
/// @param prop Property contract address
/// @param cp Certified Partner wallet (this wallet will receive fee from property)
function changePropertyToCP(address prop, address cp) public onlySystemAdmin {
require(isCertifiedPartner(cp), "DataStorageProxy: Can only assign property to Certified Partner");
_propertyToCP[prop] = cp;
emit TransferPropertyToCP(prop, cp);
}
function freezeSystem() public onlyOwner {
_systemFrozen = true;
}
function unfreezeSystem() public onlyOwner {
_systemFrozen = false;
}
/// @notice freeze Certified Partner (stops transactions for all Certified Partners properties)
/// @param cp Certified Partner wallet
function freezeCP(address cp) public onlySystemAdmin {
bytes32 cpBytes = DataStorageProxyHelpers(_certifiedPartners).getCPBytesFromWallet(cp);
_cpFrozen[cpBytes] = true;
}
/// @notice unfreeze Certified Partner (allowing transactions for all Certified Partners properties)
/// @param cp Certified Partner wallet
function unfreezeCP(address cp) public onlySystemAdmin {
bytes32 cpBytes = DataStorageProxyHelpers(_certifiedPartners).getCPBytesFromWallet(cp);
_cpFrozen[cpBytes] = false;
}
/// @notice freeze property (stopping transactions for property)
/// @param prop Property contract address
function freezeProperty(address prop) public {
require(_propertyToCP[msg.sender] != address(0), "DataHolder: Sender must be property that belongs to a CP!");
require(msg.sender == prop, "DataHolder: Only property can freeze itself!");
_propertyFrozen[prop] = true;
emit FreezeProperty(prop, true);
}
/// @notice unfreeze property (allowing transactions for property)
/// @param prop Property contract address
function unfreezeProperty(address prop) public {
require(_propertyToCP[msg.sender] != address(0), "DataHolder: Sender must be property that belongs to a CP!");
require(msg.sender == prop, "DataHolder: Only property can unfreeze itself!");
_propertyFrozen[prop] = false;
emit FreezeProperty(prop, false);
}
/// @notice checks if system is frozen
function isSystemFrozen() public view returns (bool) {
return _systemFrozen;
}
/// @notice checks if Certified Partner is frozen
/// @param cp Certified Partner wallet address
function isCPFrozen(address cp) public view returns (bool) {
bytes32 cpBytes = DataStorageProxyHelpers(_certifiedPartners).getCPBytesFromWallet(cp);
return _systemFrozen || _cpFrozen[cpBytes];
}
/// @notice checks if property is frozen
/// @param property Property contract address
function isPropTokenFrozen(address property) public view returns (bool) {
bytes32 cpBytes = DataStorageProxyHelpers(_certifiedPartners).getCPBytesFromWallet(_propertyToCP[property]);
return _systemFrozen || _cpFrozen[cpBytes] || _propertyFrozen[property];
}
/// @notice retrieves roles contract address
function getRolesAddress() public view returns (address) {
return _roles;
}
/// @notice retrieves property factory contract address
function getPropertiesFactoryAddress() public view returns (address) {
return _factory;
}
/// @notice retrieves users contract address
function getUsersAddress() public view returns (address) {
return _users;
}
/// @notice retrieves government contract address
function getGovernmentAddress() public view returns (address) {
return _government;
}
/// @notice checks if wallet has system admin rights
/// @param sender Wallet address to check
function hasSystemAdminRights(address sender) public view returns (bool) {
return DataStorageProxyHelpers(_roles).hasSystemAdminRights(sender);
}
/// @notice retrieves certified partners contract address
function getCertifiedPartnersAddress() public view returns (address) {
return _certifiedPartners;
}
/// @notice retrieves blocksquare wallet address which receives fee
function getBlocksquareAddress() public view returns (address) {
return _blocksquare;
}
/// @notice retrieves Certified Partner's wallet address that receives fee for given property
/// @param prop Property contract address
/// @return wallet address
function getCPOfProperty(address prop) public view returns (address) {
return _propertyToCP[prop];
}
/// @notice checks if wallet belongs to Certified Partner
/// @param addr Wallet address to check
function isCertifiedPartner(address addr) public view returns (bool) {
return DataStorageProxyHelpers(_certifiedPartners).isCertifiedPartner(addr);
}
/// @notice check if wallet can distribute revenue
/// @param cpWallet Wallet address to check
function canDistributeRent(address cpWallet) public view returns (bool) {
return DataStorageProxyHelpers(_roles).hasSystemAdminRights(cpWallet) || DataStorageProxyHelpers(_certifiedPartners).canCertifiedPartnerDistributeRent(cpWallet);
}
/// @notice check if admin wallet address is admin of property
/// @param admin Admin wallet address
/// @param property Property contract address
function isCPAdminOfProperty(address admin, address property) public view returns (bool) {
address cp = _propertyToCP[property];
return DataStorageProxyHelpers(_certifiedPartners).isCPAdmin(admin, cp);
}
/// @notice check if wallet address can edit property
/// @param wallet Wallet address
/// @param property Property contract address
function canEditProperty(address wallet, address property) public view returns (bool) {
address propOwner = getCPOfProperty(property);
return propOwner == wallet ||
isCPAdminOfProperty(wallet, property) ||
DataStorageProxyHelpers(_certifiedPartners).getCPBytesFromWallet(wallet) == DataStorageProxyHelpers(_certifiedPartners).getCPBytesFromWallet(propOwner) ||
DataStorageProxyHelpers(_roles).hasSystemAdminRights(wallet);
}
/// @notice retrieves ocean point contracts
function getOceanPointContract() public view returns (address) {
return _oceanPoint;
}
/// @notice retrieves Certified Partner fee
function getCertifiedPartnerFee() public view returns (uint256) {
return _fee.certifiedPartnerFee;
}
/// @notice retrieves Licenced Issuer fee
function getLicencedIssuerFee() public view returns (uint256) {
return _fee.licencedIssuerFee;
}
/// @notice retrieves Blocksquare fee
function getBlocksquareFee() public view returns (uint256) {
return _fee.blocksquareFee;
}
/// @notice retrieves special wallet address
function getSpecialWallet() public view returns (address) {
return _specialWallet;
}
/// @notice checks if contract address can be used for minting and burning
/// @param cont Contract address
function isContractWhitelisted(address cont) public view returns (bool) {
return _whitelistedContract[cont];
}
/// @notice checks if property tokens can be transfered to wallet
/// @param wallet Wallet address
/// @param property Property contract address
function canTransferPropTokensTo(address wallet, address property) public view returns (bool) {
if (wallet == address(0)) {
return false;
}
address cp = getCPOfProperty(property);
bytes32 cpBytes = DataStorageProxyHelpers(_certifiedPartners).getCPBytesFromWallet(cp);
bytes32 userBytes = DataStorageProxyHelpers(_users).getUserBytesFromWallet(wallet);
if (DataStorageProxyHelpers(_certifiedPartners).isUserWhitelisted(cpBytes, userBytes)) {
return true;
}
return false;
}
} | @title Data Storage Proxy | contract DataStorageProxy is Ownable {
struct Fee {
uint256 licencedIssuerFee;
uint256 blocksquareFee;
uint256 certifiedPartnerFee;
}
mapping(bytes32 => bool) _cpFrozen;
mapping(address => bool) _propertyFrozen;
mapping(address => address) _propertyToCP;
mapping(address => bool) _whitelistedContract;
address private _factory;
address private _roles;
address private _users;
address private _certifiedPartners;
address private _blocksquare;
address private _oceanPoint;
address private _government;
address private _specialWallet;
bool private _systemFrozen;
Fee private _fee;
modifier onlySystemAdmin {
require(DataStorageProxyHelpers(_roles).hasSystemAdminRights(msg.sender), "DataStorageProxy: You need to have system admin rights!");
_;
}
event TransferPropertyToCP(address property, address CP);
event FreezeProperty(address property, bool frozen);
constructor(address roles, address CP, address users, address specialWallet) public {
_fee = Fee(5, 5, 5);
_blocksquare = msg.sender;
_roles = roles;
_users = users;
_certifiedPartners = CP;
_specialWallet = specialWallet;
}
function changeSpecialWallet(address specialWallet) public onlyOwner {
_specialWallet = specialWallet;
}
function changeFactory(address factory) public onlyOwner {
_factory = factory;
}
function changeRoles(address roles) public onlyOwner {
_roles = roles;
}
function changeUsers(address users) public onlyOwner {
_users = users;
}
function changeGovernmentContract(address government) public onlyOwner {
_government = government;
}
function changeCertifiedPartners(address certifiedPartners) public onlyOwner {
_certifiedPartners = certifiedPartners;
}
function changeOceanPointContract(address oceanPoint) public onlyOwner {
_oceanPoint = oceanPoint;
}
function changeWhitelistedContract(address contr, bool isWhitelisted) public onlySystemAdmin {
_whitelistedContract[contr] = isWhitelisted;
}
function changeFees(uint256 licencedIssuerFee, uint256 blocksquareFee, uint256 certifiedPartnerFee) public onlyOwner {
require(_msgSender() == owner() || _msgSender() == _government, "DataStorageProxy: You can't change fee");
require(licencedIssuerFee + blocksquareFee + certifiedPartnerFee <= 10000, "DataStorageProxy: Fee needs to be equal or bellow 100");
_fee = Fee(licencedIssuerFee, blocksquareFee, certifiedPartnerFee);
}
function changeBlocksquareAddress(address blocksquare) public onlyOwner {
_blocksquare = blocksquare;
}
function addPropertyToCP(address prop, address cp) public {
require(_factory == msg.sender, "DataHolder: Only factory can add properties");
_propertyToCP[prop] = cp;
_propertyFrozen[prop] = true;
}
function changePropertyToCP(address prop, address cp) public onlySystemAdmin {
require(isCertifiedPartner(cp), "DataStorageProxy: Can only assign property to Certified Partner");
_propertyToCP[prop] = cp;
emit TransferPropertyToCP(prop, cp);
}
function freezeSystem() public onlyOwner {
_systemFrozen = true;
}
function unfreezeSystem() public onlyOwner {
_systemFrozen = false;
}
function freezeCP(address cp) public onlySystemAdmin {
bytes32 cpBytes = DataStorageProxyHelpers(_certifiedPartners).getCPBytesFromWallet(cp);
_cpFrozen[cpBytes] = true;
}
function unfreezeCP(address cp) public onlySystemAdmin {
bytes32 cpBytes = DataStorageProxyHelpers(_certifiedPartners).getCPBytesFromWallet(cp);
_cpFrozen[cpBytes] = false;
}
function freezeProperty(address prop) public {
require(_propertyToCP[msg.sender] != address(0), "DataHolder: Sender must be property that belongs to a CP!");
require(msg.sender == prop, "DataHolder: Only property can freeze itself!");
_propertyFrozen[prop] = true;
emit FreezeProperty(prop, true);
}
function unfreezeProperty(address prop) public {
require(_propertyToCP[msg.sender] != address(0), "DataHolder: Sender must be property that belongs to a CP!");
require(msg.sender == prop, "DataHolder: Only property can unfreeze itself!");
_propertyFrozen[prop] = false;
emit FreezeProperty(prop, false);
}
function isSystemFrozen() public view returns (bool) {
return _systemFrozen;
}
function isCPFrozen(address cp) public view returns (bool) {
bytes32 cpBytes = DataStorageProxyHelpers(_certifiedPartners).getCPBytesFromWallet(cp);
return _systemFrozen || _cpFrozen[cpBytes];
}
function isPropTokenFrozen(address property) public view returns (bool) {
bytes32 cpBytes = DataStorageProxyHelpers(_certifiedPartners).getCPBytesFromWallet(_propertyToCP[property]);
return _systemFrozen || _cpFrozen[cpBytes] || _propertyFrozen[property];
}
function getRolesAddress() public view returns (address) {
return _roles;
}
function getPropertiesFactoryAddress() public view returns (address) {
return _factory;
}
function getUsersAddress() public view returns (address) {
return _users;
}
function getGovernmentAddress() public view returns (address) {
return _government;
}
function hasSystemAdminRights(address sender) public view returns (bool) {
return DataStorageProxyHelpers(_roles).hasSystemAdminRights(sender);
}
function getCertifiedPartnersAddress() public view returns (address) {
return _certifiedPartners;
}
function getBlocksquareAddress() public view returns (address) {
return _blocksquare;
}
function getCPOfProperty(address prop) public view returns (address) {
return _propertyToCP[prop];
}
function isCertifiedPartner(address addr) public view returns (bool) {
return DataStorageProxyHelpers(_certifiedPartners).isCertifiedPartner(addr);
}
function canDistributeRent(address cpWallet) public view returns (bool) {
return DataStorageProxyHelpers(_roles).hasSystemAdminRights(cpWallet) || DataStorageProxyHelpers(_certifiedPartners).canCertifiedPartnerDistributeRent(cpWallet);
}
function isCPAdminOfProperty(address admin, address property) public view returns (bool) {
address cp = _propertyToCP[property];
return DataStorageProxyHelpers(_certifiedPartners).isCPAdmin(admin, cp);
}
function canEditProperty(address wallet, address property) public view returns (bool) {
address propOwner = getCPOfProperty(property);
return propOwner == wallet ||
isCPAdminOfProperty(wallet, property) ||
DataStorageProxyHelpers(_certifiedPartners).getCPBytesFromWallet(wallet) == DataStorageProxyHelpers(_certifiedPartners).getCPBytesFromWallet(propOwner) ||
DataStorageProxyHelpers(_roles).hasSystemAdminRights(wallet);
}
function getOceanPointContract() public view returns (address) {
return _oceanPoint;
}
function getCertifiedPartnerFee() public view returns (uint256) {
return _fee.certifiedPartnerFee;
}
function getLicencedIssuerFee() public view returns (uint256) {
return _fee.licencedIssuerFee;
}
function getBlocksquareFee() public view returns (uint256) {
return _fee.blocksquareFee;
}
function getSpecialWallet() public view returns (address) {
return _specialWallet;
}
function isContractWhitelisted(address cont) public view returns (bool) {
return _whitelistedContract[cont];
}
function canTransferPropTokensTo(address wallet, address property) public view returns (bool) {
if (wallet == address(0)) {
return false;
}
address cp = getCPOfProperty(property);
bytes32 cpBytes = DataStorageProxyHelpers(_certifiedPartners).getCPBytesFromWallet(cp);
bytes32 userBytes = DataStorageProxyHelpers(_users).getUserBytesFromWallet(wallet);
if (DataStorageProxyHelpers(_certifiedPartners).isUserWhitelisted(cpBytes, userBytes)) {
return true;
}
return false;
}
function canTransferPropTokensTo(address wallet, address property) public view returns (bool) {
if (wallet == address(0)) {
return false;
}
address cp = getCPOfProperty(property);
bytes32 cpBytes = DataStorageProxyHelpers(_certifiedPartners).getCPBytesFromWallet(cp);
bytes32 userBytes = DataStorageProxyHelpers(_users).getUserBytesFromWallet(wallet);
if (DataStorageProxyHelpers(_certifiedPartners).isUserWhitelisted(cpBytes, userBytes)) {
return true;
}
return false;
}
function canTransferPropTokensTo(address wallet, address property) public view returns (bool) {
if (wallet == address(0)) {
return false;
}
address cp = getCPOfProperty(property);
bytes32 cpBytes = DataStorageProxyHelpers(_certifiedPartners).getCPBytesFromWallet(cp);
bytes32 userBytes = DataStorageProxyHelpers(_users).getUserBytesFromWallet(wallet);
if (DataStorageProxyHelpers(_certifiedPartners).isUserWhitelisted(cpBytes, userBytes)) {
return true;
}
return false;
}
} | 13,576,536 | [
1,
751,
5235,
7659,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
16351,
1910,
3245,
3886,
353,
14223,
6914,
288,
203,
203,
565,
1958,
30174,
288,
203,
3639,
2254,
5034,
328,
335,
802,
72,
16667,
14667,
31,
203,
3639,
2254,
5034,
4398,
6182,
14667,
31,
203,
3639,
2254,
5034,
3320,
939,
1988,
1224,
14667,
31,
203,
565,
289,
203,
203,
565,
2874,
12,
3890,
1578,
516,
1426,
13,
389,
4057,
42,
9808,
31,
203,
565,
2874,
12,
2867,
516,
1426,
13,
389,
4468,
42,
9808,
31,
203,
565,
2874,
12,
2867,
516,
1758,
13,
389,
4468,
774,
4258,
31,
203,
565,
2874,
12,
2867,
516,
1426,
13,
389,
20409,
329,
8924,
31,
203,
203,
565,
1758,
3238,
389,
6848,
31,
203,
565,
1758,
3238,
389,
7774,
31,
203,
565,
1758,
3238,
389,
5577,
31,
203,
565,
1758,
3238,
389,
7593,
939,
1988,
9646,
31,
203,
565,
1758,
3238,
389,
7996,
6182,
31,
203,
565,
1758,
3238,
389,
83,
31393,
2148,
31,
203,
565,
1758,
3238,
389,
75,
1643,
82,
475,
31,
203,
203,
565,
1758,
3238,
389,
9371,
16936,
31,
203,
203,
565,
1426,
3238,
389,
4299,
42,
9808,
31,
203,
203,
565,
30174,
3238,
389,
21386,
31,
203,
203,
565,
9606,
1338,
3163,
4446,
288,
203,
3639,
2583,
12,
751,
3245,
3886,
13375,
24899,
7774,
2934,
5332,
3163,
4446,
18464,
12,
3576,
18,
15330,
3631,
315,
751,
3245,
3886,
30,
4554,
1608,
358,
1240,
2619,
3981,
14989,
4442,
1769,
203,
3639,
389,
31,
203,
565,
289,
203,
203,
565,
871,
12279,
1396,
774,
4258,
12,
2867,
1272,
16,
1758,
5181,
1769,
203,
565,
871,
15217,
2
] |
pragma solidity ^0.5.16;
import "./ComptrollerInterface.sol";
import "./ErrorReporter.sol";
import "./Exponential.sol";
import "./EIP20Interface.sol";
import "./EIP20NonStandardInterface.sol";
import "./SafeMath.sol";
import "./Governance/IINV.sol";
/**
* @title xINV Core contract
* @notice Abstract base for xINV
* @author Inverse Finance
*/
contract xInvCore is Exponential, TokenErrorReporter {
/**
* @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 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 Initial exchange rate used when minting the first CTokens (used when totalSupply = 0)
*/
uint internal initialExchangeRateMantissa;
/**
* @notice Block number that interest was last accrued at
*/
uint public accrualBlockNumber;
/**
* @notice Total number of tokens in circulation
*/
uint public totalSupply;
uint public rewardPerBlock;
address public rewardTreasury;
/**
* @notice Official record of token balances for each account
*/
mapping (address => uint) internal accountTokens;
/**
* @notice Indicator that this is a CToken contract (for inspection)
*/
bool public constant isCToken = true;
/*** Market Events ***/
/**
* @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);
/*** 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 reward treasury is changed
*/
event NewRewardTreasury(address oldRewardTreasury, address newRewardTreasury);
/**
* @notice Event emitted when reward per block is changed
*/
event NewRewardPerBlock(uint oldRewardPerBlock, uint newRewardPerBlock);
/**
* @notice EIP20 Transfer event
*/
event Transfer(address indexed from, address indexed to, uint amount);
/**
* @notice Failure event
*/
event Failure(uint error, uint info, uint detail);
/**
* @notice Initialize the money market
* @param comptroller_ The address of the Comptroller
* @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_,
uint initialExchangeRateMantissa_,
uint rewardPerBlock_,
address rewardTreasury_,
string memory name_,
string memory symbol_,
uint8 decimals_) internal {
require(msg.sender == admin, "only admin may initialize the market");
require(accrualBlockNumber == 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");
name = name_;
symbol = symbol_;
decimals = decimals_;
accrualBlockNumber = getBlockNumber();
rewardPerBlock = rewardPerBlock_;
rewardTreasury = rewardTreasury_;
// The counter starts true to prevent changing it from zero to non-zero (i.e. smaller cost/refund)
_notEntered = true;
}
/**
* @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`
* @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()});
(MathError mErr, uint balance) = mulScalarTruncate(exchangeRate, accountTokens[owner]);
require(mErr == MathError.NO_ERROR, "balance could not be calculated");
return balance;
}
/**
* @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 = accountTokens[account];
uint exchangeRateMantissa;
MathError mErr;
(mErr, exchangeRateMantissa) = exchangeRateStoredInternal();
if (mErr != MathError.NO_ERROR) {
return (uint(Error.MATH_ERROR), 0, 0, 0);
}
return (uint(Error.NO_ERROR), cTokenBalance, 0, 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;
}
/**
* @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
* @return Calculated exchange rate scaled by 1e18
*/
function exchangeRateStored() public view returns (uint) {
(MathError err, uint result) = exchangeRateStoredInternal();
require(err == MathError.NO_ERROR, "exchangeRateStored: exchangeRateStoredInternal failed");
return result;
}
/**
* @notice Calculates the exchange rate from the underlying to the CToken
* @return (error code, calculated exchange rate scaled by 1e18)
*/
function exchangeRateStoredInternal() internal view returns (MathError, uint) {
uint _totalSupply = totalSupply;
if (_totalSupply == 0) {
/*
* If there are no tokens minted:
* exchangeRate = initialExchangeRate
*/
return (MathError.NO_ERROR, initialExchangeRateMantissa);
} else {
/*
* Otherwise:
* exchangeRate = totalCash / totalSupply
*/
uint totalCash = getCashPrior();
Exp memory exchangeRate;
MathError mathErr;
(mathErr, exchangeRate) = getExp(totalCash, _totalSupply);
if (mathErr != MathError.NO_ERROR) {
return (mathErr, 0);
}
return (MathError.NO_ERROR, exchangeRate.mantissa);
}
}
/**
* @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();
}
// brings rewards from treasury into this contract
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);
}
/* Calculate the number of blocks elapsed since the last accrual */
(MathError mathErr, uint blockDelta) = subUInt(currentBlockNumber, accrualBlockNumberPrior);
require(mathErr == MathError.NO_ERROR, "could not calculate block delta");
/* Calculate accumulated reward amount */
uint reward;
(mathErr, reward) = mulUInt(rewardPerBlock, blockDelta);
require(mathErr == MathError.NO_ERROR, "could not calculate reward");
if(totalSupply > 0 && rewardTreasury != address(0) && canTransferIn(rewardTreasury, reward)) {
doTransferIn(rewardTreasury, reward);
}
/////////////////////////
// EFFECTS & INTERACTIONS
// (No safe failures beyond this point)
accrualBlockNumber = currentBlockNumber;
return uint(Error.NO_ERROR);
}
/**
* @notice Sender supplies assets into the market and receives cTokens in exchange
* @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);
}
struct MintLocalVars {
Error err;
MathError mathErr;
uint exchangeRateMantissa;
uint mintTokens;
uint totalSupplyNew;
uint accountTokensNew;
uint actualMintAmount;
}
/**
* @notice User supplies assets into the market and receives cTokens in exchange
* @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);
}
MintLocalVars memory vars;
(vars.mathErr, vars.exchangeRateMantissa) = exchangeRateStoredInternal();
if (vars.mathErr != MathError.NO_ERROR) {
return (failOpaque(Error.MATH_ERROR, FailureInfo.MINT_EXCHANGE_RATE_READ_FAILED, uint(vars.mathErr)), 0);
}
/////////////////////////
// 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.mathErr, vars.mintTokens) = divScalarByExpTruncate(vars.actualMintAmount, Exp({mantissa: vars.exchangeRateMantissa}));
require(vars.mathErr == MathError.NO_ERROR, "MINT_EXCHANGE_CALCULATION_FAILED");
/*
* We calculate the new total supply of cTokens and minter token balance, checking for overflow:
* totalSupplyNew = totalSupply + mintTokens
* accountTokensNew = accountTokens[minter] + mintTokens
*/
(vars.mathErr, vars.totalSupplyNew) = addUInt(totalSupply, vars.mintTokens);
require(vars.mathErr == MathError.NO_ERROR, "MINT_NEW_TOTAL_SUPPLY_CALCULATION_FAILED");
require(vars.totalSupplyNew < 2**96, "MINT_NEW_TOTAL_SUPPLY_OVER_CAPACITY");
(vars.mathErr, vars.accountTokensNew) = addUInt(accountTokens[minter], vars.mintTokens);
require(vars.mathErr == MathError.NO_ERROR, "MINT_NEW_ACCOUNT_BALANCE_CALCULATION_FAILED");
/* We write previously calculated values into storage */
totalSupply = vars.totalSupplyNew;
accountTokens[minter] = vars.accountTokensNew;
/* We emit a Mint event, and a Transfer event */
emit Mint(minter, vars.actualMintAmount, vars.mintTokens);
emit Transfer(address(this), minter, vars.mintTokens);
/* we move delegates */
_moveDelegates(address(0), minter, uint96(vars.mintTokens)); // NOTE: Check for potential overflows due to conversion from uint256 to uint96
/* We call the defense hook */
comptroller.mintVerify(address(this), minter, vars.actualMintAmount, vars.mintTokens);
return (uint(Error.NO_ERROR), vars.actualMintAmount);
}
/**
* @notice Sender redeems cTokens in exchange for the underlying asset
* @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, bool useEscrow) 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, useEscrow);
}
/**
* @notice Sender redeems cTokens in exchange for a specified amount of underlying asset
* @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, bool useEscrow) 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, useEscrow);
}
struct RedeemLocalVars {
Error err;
MathError mathErr;
uint exchangeRateMantissa;
uint redeemTokens;
uint redeemAmount;
uint totalSupplyNew;
uint accountTokensNew;
}
/**
* @notice User redeems cTokens in exchange for the underlying asset
* @param redeemer The address of the account which is redeeming the tokens
* @param redeemTokensIn The number of cTokens to redeem into underlying (only one of redeemTokensIn or redeemAmountIn may be non-zero)
* @param redeemAmountIn The number of underlying tokens to receive from redeeming cTokens (only one of redeemTokensIn or redeemAmountIn may be non-zero)
* @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details)
*/
function redeemFresh(address payable redeemer, uint redeemTokensIn, uint redeemAmountIn, bool useEscrow) 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.mathErr, vars.exchangeRateMantissa) = exchangeRateStoredInternal();
if (vars.mathErr != MathError.NO_ERROR) {
return failOpaque(Error.MATH_ERROR, FailureInfo.REDEEM_EXCHANGE_RATE_READ_FAILED, uint(vars.mathErr));
}
/* 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.mathErr, vars.redeemAmount) = mulScalarTruncate(Exp({mantissa: vars.exchangeRateMantissa}), redeemTokensIn);
if (vars.mathErr != MathError.NO_ERROR) {
return failOpaque(Error.MATH_ERROR, FailureInfo.REDEEM_EXCHANGE_TOKENS_CALCULATION_FAILED, uint(vars.mathErr));
}
} else {
/*
* We get the current exchange rate and calculate the amount to be redeemed:
* redeemTokens = redeemAmountIn / exchangeRate
* redeemAmount = redeemAmountIn
*/
(vars.mathErr, vars.redeemTokens) = divScalarByExpTruncate(redeemAmountIn, Exp({mantissa: vars.exchangeRateMantissa}));
if (vars.mathErr != MathError.NO_ERROR) {
return failOpaque(Error.MATH_ERROR, FailureInfo.REDEEM_EXCHANGE_AMOUNT_CALCULATION_FAILED, uint(vars.mathErr));
}
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);
}
/*
* We calculate the new total supply and redeemer balance, checking for underflow:
* totalSupplyNew = totalSupply - redeemTokens
* accountTokensNew = accountTokens[redeemer] - redeemTokens
*/
(vars.mathErr, vars.totalSupplyNew) = subUInt(totalSupply, vars.redeemTokens);
if (vars.mathErr != MathError.NO_ERROR) {
return failOpaque(Error.MATH_ERROR, FailureInfo.REDEEM_NEW_TOTAL_SUPPLY_CALCULATION_FAILED, uint(vars.mathErr));
}
(vars.mathErr, vars.accountTokensNew) = subUInt(accountTokens[redeemer], vars.redeemTokens);
if (vars.mathErr != MathError.NO_ERROR) {
return failOpaque(Error.MATH_ERROR, FailureInfo.REDEEM_NEW_ACCOUNT_BALANCE_CALCULATION_FAILED, uint(vars.mathErr));
}
/* 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, useEscrow);
/* 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 move delegates */
_moveDelegates(redeemer, address(0), uint96(vars.redeemTokens)); // NOTE: Check for potential overflows due to conversion from uint256 to uint96
/* 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 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);
}
/**
* @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);
}
/* Fail if borrower = liquidator */
if (borrower == liquidator) {
return fail(Error.INVALID_ACCOUNT_PAIR, FailureInfo.LIQUIDATE_SEIZE_LIQUIDATOR_IS_BORROWER);
}
MathError mathErr;
uint borrowerTokensNew;
uint liquidatorTokensNew;
/*
* We calculate the new borrower and liquidator token balances, failing on underflow/overflow:
* borrowerTokensNew = accountTokens[borrower] - seizeTokens
* liquidatorTokensNew = accountTokens[liquidator] + seizeTokens
*/
(mathErr, borrowerTokensNew) = subUInt(accountTokens[borrower], seizeTokens);
if (mathErr != MathError.NO_ERROR) {
return failOpaque(Error.MATH_ERROR, FailureInfo.LIQUIDATE_SEIZE_BALANCE_DECREMENT_FAILED, uint(mathErr));
}
(mathErr, liquidatorTokensNew) = addUInt(accountTokens[liquidator], seizeTokens);
if (mathErr != MathError.NO_ERROR) {
return failOpaque(Error.MATH_ERROR, FailureInfo.LIQUIDATE_SEIZE_BALANCE_INCREMENT_FAILED, uint(mathErr));
}
/////////////////////////
// EFFECTS & INTERACTIONS
// (No safe failures beyond this point)
/* We write the previously calculated values into storage */
accountTokens[borrower] = borrowerTokensNew;
accountTokens[liquidator] = liquidatorTokensNew;
/* Emit a Transfer event */
emit Transfer(borrower, liquidator, seizeTokens);
/* We move delegates to liquidator although they'll be burned in the redeemFresh call after */
_moveDelegates(borrower, liquidator, uint96(seizeTokens)); // NOTE: Check for potential overflows due to conversion from uint256 to uint96
/* We call the defense hook */
comptroller.seizeVerify(address(this), seizerToken, liquidator, borrower, seizeTokens);
// Auto-redeem liquidator and skip escrow (cast liquidator to payable)
redeemFresh(address(uint160(liquidator)), seizeTokens, 0, false);
return uint(Error.NO_ERROR);
}
/*** 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);
}
function _setRewardTreasury(address newRewardTreasury) public returns (uint) {
// Check caller is admin
if (msg.sender != admin) {
return fail(Error.UNAUTHORIZED, FailureInfo.SET_COMPTROLLER_OWNER_CHECK);
}
address oldRewardTreasury = rewardTreasury;
rewardTreasury = newRewardTreasury; // it's acceptable to set it as address(0)
emit NewRewardTreasury(oldRewardTreasury, newRewardTreasury);
}
function _setRewardPerBlock(uint newRewardPerBlock) public returns (uint) {
// Check caller is admin
if (msg.sender != admin) {
return fail(Error.UNAUTHORIZED, FailureInfo.SET_COMPTROLLER_OWNER_CHECK);
}
uint oldRewardPerBlock = rewardPerBlock;
rewardPerBlock = newRewardPerBlock; // it's acceptable to set it as 0
emit NewRewardPerBlock(oldRewardPerBlock, newRewardPerBlock);
}
/*** 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);
function canTransferIn(address from, uint amount) internal view returns (bool);
/**
* @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, bool useEscrow) internal;
/*** 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
}
/*** Delegation ***/
/// @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 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), "INV::delegateBySig: invalid signature");
require(nonce == nonces[signatory]++, "INV::delegateBySig: invalid nonce");
require(now <= expiry, "INV::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, "INV::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 = uint96(accountTokens[delegator]); // NOTE: Check for potential overflows due to conversion from uint256 to uint96
delegates[delegator] = delegatee;
emit DelegateChanged(delegator, currentDelegate, delegatee);
_moveDelegates(currentDelegate, delegatee, delegatorBalance);
}
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, "INV::_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, "INV::_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, "INV::_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 getChainId() internal pure returns (uint) {
uint256 chainId;
assembly { chainId := chainid() }
return chainId;
}
function safe32(uint n, string memory errorMessage) internal pure returns (uint32) {
require(n < 2**32, errorMessage);
return uint32(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;
}
}
contract TimelockEscrow {
using SafeMath for uint;
address public underlying;
address public governance;
address public market;
uint public duration = 14 days;
mapping (address => EscrowData) public pendingWithdrawals;
struct EscrowData {
uint withdrawalTimestamp;
uint amount;
}
constructor(address underlying_, address governance_) public {
underlying = underlying_;
governance = governance_;
market = msg.sender;
}
// set to 0 to send funds directly to users
function _setEscrowDuration(uint duration_) public {
require(msg.sender == governance, "only governance can set escrow duration");
duration = duration_;
}
function _setGov(address governance_) public {
require(msg.sender == governance, "only governance can set its new address");
governance = governance_;
}
/**
* @notice assumes funds were already sent to this contract by the market. Resets escrow timelock on each withdrawal
*/
function escrow(address user, uint amount) public {
require(msg.sender == market, "only market can escrow");
if(duration > 0) {
EscrowData memory withdrawal = pendingWithdrawals[user];
pendingWithdrawals[user] = EscrowData({
// we set the future withdrawal timestamp based on current `duration` to avoid applying future `duration` changes to existing withdrawals in the event of a governance attack
withdrawalTimestamp: block.timestamp + duration,
amount: withdrawal.amount.add(amount)
});
emit Escrow(user, block.timestamp + duration, amount);
} else { // if duration is 0, we send the funds directly to the user
EIP20Interface token = EIP20Interface(underlying);
token.transfer(user, amount);
}
}
/**
* @notice returns user withdrawable amount
*/
function withdrawable(address user) public view returns (uint amount) {
EscrowData memory withdrawal = pendingWithdrawals[user];
if(withdrawal.withdrawalTimestamp <= block.timestamp) {
amount = withdrawal.amount;
}
}
function withdraw() public {
uint amount = withdrawable(msg.sender);
require(amount > 0, "Nothing to withdraw");
EIP20Interface token = EIP20Interface(underlying);
delete pendingWithdrawals[msg.sender];
token.transfer(msg.sender, amount);
emit Withdraw(msg.sender, amount);
}
event Escrow(address to, uint withdrawalTimestamp, uint amount);
event Withdraw(address to, uint amount);
}
/**
* @title xINV contract
* @notice wraps INV token
* @author Inverse Finance
*/
contract XINV is xInvCore {
address public underlying;
TimelockEscrow public escrow;
/**
* @notice Construct the xINV market
* @param underlying_ The address of the underlying asset
* @param comptroller_ The address of the Comptroller
* @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
* @param admin_ Address of the administrator of this token
*/
constructor(address underlying_,
ComptrollerInterface comptroller_,
uint rewardPerBlock_,
address rewardTreasury_,
string memory name_,
string memory symbol_,
uint8 decimals_,
address payable admin_) public {
// Creator of the contract is admin during initialization
admin = msg.sender;
// CToken initialize does the bulk of the work
super.initialize(comptroller_, 1e18, rewardPerBlock_, rewardTreasury_, name_, symbol_, decimals_);
// Set underlying and sanity check it
underlying = underlying_;
EIP20Interface(underlying).totalSupply();
// Set the proper admin now that initialization is done
admin = admin_;
// Create escrow contract
escrow = new TimelockEscrow(underlying_, admin_);
}
/*** User Interface ***/
/**
* @notice Sender supplies assets into the market and receives cTokens in exchange
* @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);
/* if user has no delegate, we inherit delegate from INV */
if(delegates[msg.sender] == address(0)) {
address invDelegate = IINV(underlying).delegates(msg.sender);
if(invDelegate != address(0)) {
_delegate(msg.sender, invDelegate);
}
}
return err;
}
/**
* @notice Sender redeems cTokens in exchange for the underlying asset
* @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, true);
}
/**
* @notice Sender redeems cTokens in exchange for a specified amount of underlying asset
* @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, true);
}
/*** 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));
require(balanceAfter >= balanceBefore, "TOKEN_TRANSFER_IN_OVERFLOW");
return balanceAfter - balanceBefore; // underflow already checked above, just subtract
}
/**
* @dev returns true if `from` has sufficient allowance and balance to to send `amount` to this address
*/
function canTransferIn(address from, uint amount) internal view returns (bool) {
EIP20Interface token = EIP20Interface(underlying);
uint balance = token.balanceOf(from);
uint allowance = token.allowance(from, address(this));
return balance >= amount && allowance >= amount;
}
/**
* @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, bool useEscrow) internal {
EIP20NonStandardInterface token = EIP20NonStandardInterface(underlying);
if(useEscrow) {
token.transfer(address(escrow), amount);
} else {
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");
if(useEscrow) {
escrow.escrow(to, amount);
}
}
function _setTimelockEscrow(TimelockEscrow newTimelockEscrow) public returns (uint) {
require(newTimelockEscrow.market() == address(this), "sanity check: newTimelockEscrow must use this market");
// Check caller is admin
if (msg.sender != admin) {
return fail(Error.UNAUTHORIZED, FailureInfo.SET_COMPTROLLER_OWNER_CHECK);
}
TimelockEscrow oldTimelockEscrow = escrow;
escrow = newTimelockEscrow;
emit NewTimelockEscrow(oldTimelockEscrow, newTimelockEscrow);
}
event NewTimelockEscrow(TimelockEscrow oldTimelockEscrow, TimelockEscrow newTimelockEscrow);
}
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;
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_ACCUMULATED_INTEREST_CALCULATION_FAILED,
ACCRUE_INTEREST_BORROW_RATE_CALCULATION_FAILED,
ACCRUE_INTEREST_NEW_BORROW_INDEX_CALCULATION_FAILED,
ACCRUE_INTEREST_NEW_TOTAL_BORROWS_CALCULATION_FAILED,
ACCRUE_INTEREST_NEW_TOTAL_RESERVES_CALCULATION_FAILED,
ACCRUE_INTEREST_SIMPLE_INTEREST_FACTOR_CALCULATION_FAILED,
BORROW_ACCUMULATED_BALANCE_CALCULATION_FAILED,
BORROW_ACCRUE_INTEREST_FAILED,
BORROW_CASH_NOT_AVAILABLE,
BORROW_FRESHNESS_CHECK,
BORROW_NEW_TOTAL_BALANCE_CALCULATION_FAILED,
BORROW_NEW_ACCOUNT_BORROW_BALANCE_CALCULATION_FAILED,
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_BALANCE_INCREMENT_FAILED,
LIQUIDATE_SEIZE_BALANCE_DECREMENT_FAILED,
LIQUIDATE_SEIZE_COMPTROLLER_REJECTION,
LIQUIDATE_SEIZE_LIQUIDATOR_IS_BORROWER,
LIQUIDATE_SEIZE_TOO_MUCH,
MINT_ACCRUE_INTEREST_FAILED,
MINT_COMPTROLLER_REJECTION,
MINT_EXCHANGE_CALCULATION_FAILED,
MINT_EXCHANGE_RATE_READ_FAILED,
MINT_FRESHNESS_CHECK,
MINT_NEW_ACCOUNT_BALANCE_CALCULATION_FAILED,
MINT_NEW_TOTAL_SUPPLY_CALCULATION_FAILED,
MINT_TRANSFER_IN_FAILED,
MINT_TRANSFER_IN_NOT_POSSIBLE,
REDEEM_ACCRUE_INTEREST_FAILED,
REDEEM_COMPTROLLER_REJECTION,
REDEEM_EXCHANGE_TOKENS_CALCULATION_FAILED,
REDEEM_EXCHANGE_AMOUNT_CALCULATION_FAILED,
REDEEM_EXCHANGE_RATE_READ_FAILED,
REDEEM_FRESHNESS_CHECK,
REDEEM_NEW_ACCOUNT_BALANCE_CALCULATION_FAILED,
REDEEM_NEW_TOTAL_SUPPLY_CALCULATION_FAILED,
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_ACCUMULATED_BALANCE_CALCULATION_FAILED,
REPAY_BORROW_COMPTROLLER_REJECTION,
REPAY_BORROW_FRESHNESS_CHECK,
REPAY_BORROW_NEW_ACCOUNT_BORROW_BALANCE_CALCULATION_FAILED,
REPAY_BORROW_NEW_TOTAL_BALANCE_CALCULATION_FAILED,
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,
TRANSFER_NOT_ENOUGH,
TRANSFER_TOO_MUCH,
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";
import "./ExponentialNoError.sol";
/**
* @title Exponential module for storing fixed-precision decimals
* @author Compound
* @dev Legacy contract for compatibility reasons with existing contracts that still use MathError
* @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, ExponentialNoError {
/**
* @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 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 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);
}
}
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;
// From https://github.com/OpenZeppelin/openzeppelin-contracts/blob/master/contracts/math/Math.sol
// Subject to the MIT license.
/**
* @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 addition of two unsigned integers, reverting with custom message on overflow.
*
* Counterpart to Solidity's `+` operator.
*
* Requirements:
* - Addition cannot overflow.
*/
function add(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
uint256 c = a + b;
require(c >= a, errorMessage);
return c;
}
/**
* @dev Returns the subtraction of two unsigned integers, reverting on underflow (when the result is negative).
*
* Counterpart to Solidity's `-` operator.
*
* Requirements:
* - Subtraction cannot underflow.
*/
function sub(uint256 a, uint256 b) internal pure returns (uint256) {
return sub(a, b, "SafeMath: subtraction underflow");
}
/**
* @dev Returns the subtraction of two unsigned integers, reverting with custom message on underflow (when the result is negative).
*
* Counterpart to Solidity's `-` operator.
*
* Requirements:
* - Subtraction cannot underflow.
*/
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 multiplication of two unsigned integers, reverting on overflow.
*
* Counterpart to Solidity's `*` operator.
*
* Requirements:
* - Multiplication cannot overflow.
*/
function mul(uint256 a, uint256 b, string memory errorMessage) 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, errorMessage);
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;
}
}
pragma solidity ^0.5.16;
interface IINV {
function balanceOf(address) external view returns (uint);
function transfer(address,uint) external returns (bool);
function delegates(address) external view returns (address);
function delegate(address) 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;
/**
* @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 ExponentialNoError {
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 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 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 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 Checks if left Exp > right Exp.
*/
function greaterThanExp(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)});
}
}
| * @title xINV contract @notice wraps INV token @author Inverse Finance/ | contract XINV is xInvCore {
address public underlying;
TimelockEscrow public escrow;
constructor(address underlying_,
ComptrollerInterface comptroller_,
uint rewardPerBlock_,
address rewardTreasury_,
string memory name_,
string memory symbol_,
uint8 decimals_,
address payable admin_) public {
admin = msg.sender;
super.initialize(comptroller_, 1e18, rewardPerBlock_, rewardTreasury_, name_, symbol_, decimals_);
underlying = underlying_;
EIP20Interface(underlying).totalSupply();
admin = admin_;
escrow = new TimelockEscrow(underlying_, admin_);
}
function mint(uint mintAmount) external returns (uint) {
(uint err,) = mintInternal(mintAmount);
if(delegates[msg.sender] == address(0)) {
address invDelegate = IINV(underlying).delegates(msg.sender);
if(invDelegate != address(0)) {
_delegate(msg.sender, invDelegate);
}
}
return err;
}
function mint(uint mintAmount) external returns (uint) {
(uint err,) = mintInternal(mintAmount);
if(delegates[msg.sender] == address(0)) {
address invDelegate = IINV(underlying).delegates(msg.sender);
if(invDelegate != address(0)) {
_delegate(msg.sender, invDelegate);
}
}
return err;
}
function mint(uint mintAmount) external returns (uint) {
(uint err,) = mintInternal(mintAmount);
if(delegates[msg.sender] == address(0)) {
address invDelegate = IINV(underlying).delegates(msg.sender);
if(invDelegate != address(0)) {
_delegate(msg.sender, invDelegate);
}
}
return err;
}
function redeem(uint redeemTokens) external returns (uint) {
return redeemInternal(redeemTokens, true);
}
function redeemUnderlying(uint redeemAmount) external returns (uint) {
return redeemUnderlyingInternal(redeemAmount, true);
}
function getCashPrior() internal view returns (uint) {
EIP20Interface token = EIP20Interface(underlying);
return token.balanceOf(address(this));
}
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()
}
returndatacopy(0, 0, 32)
}
revert(0, 0)
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()
}
returndatacopy(0, 0, 32)
}
revert(0, 0)
}
| 1,654,045 | [
1,
92,
706,
58,
6835,
225,
9059,
2120,
58,
1147,
225,
657,
2476,
9458,
1359,
19,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
16351,
1139,
706,
58,
353,
619,
3605,
4670,
288,
203,
203,
565,
1758,
1071,
6808,
31,
203,
565,
12652,
292,
975,
6412,
492,
1071,
2904,
492,
31,
203,
203,
565,
3885,
12,
2867,
6808,
67,
16,
203,
7734,
1286,
337,
1539,
1358,
532,
337,
1539,
67,
16,
203,
7734,
2254,
19890,
2173,
1768,
67,
16,
540,
203,
7734,
1758,
19890,
56,
266,
345,
22498,
67,
16,
203,
7734,
533,
3778,
508,
67,
16,
203,
7734,
533,
3778,
3273,
67,
16,
203,
7734,
2254,
28,
15105,
67,
16,
203,
7734,
1758,
8843,
429,
3981,
67,
13,
1071,
288,
203,
3639,
3981,
273,
1234,
18,
15330,
31,
203,
203,
3639,
2240,
18,
11160,
12,
832,
337,
1539,
67,
16,
404,
73,
2643,
16,
19890,
2173,
1768,
67,
16,
19890,
56,
266,
345,
22498,
67,
16,
508,
67,
16,
3273,
67,
16,
15105,
67,
1769,
203,
203,
3639,
6808,
273,
6808,
67,
31,
203,
3639,
512,
2579,
3462,
1358,
12,
9341,
6291,
2934,
4963,
3088,
1283,
5621,
203,
203,
3639,
3981,
273,
3981,
67,
31,
203,
203,
3639,
2904,
492,
273,
394,
12652,
292,
975,
6412,
492,
12,
9341,
6291,
67,
16,
3981,
67,
1769,
203,
565,
289,
203,
203,
203,
565,
445,
312,
474,
12,
11890,
312,
474,
6275,
13,
3903,
1135,
261,
11890,
13,
288,
203,
3639,
261,
11890,
393,
16,
13,
273,
312,
474,
3061,
12,
81,
474,
6275,
1769,
203,
540,
203,
3639,
309,
12,
3771,
1332,
815,
63,
3576,
18,
15330,
65,
422,
1758,
12,
20,
3719,
288,
203,
5411,
1758,
2198,
2
] |
// SPDX-License-Identifier: BUSL-1.1
pragma solidity 0.7.6;
pragma abicoder v2;
import "@openzeppelin/contracts-upgradeable/proxy/Initializable.sol";
import "@openzeppelin/contracts-upgradeable/access/OwnableUpgradeable.sol";
import "@openzeppelin/contracts-upgradeable/utils/PausableUpgradeable.sol";
import "@openzeppelin/contracts-upgradeable/token/ERC20/ERC20Upgradeable.sol";
import "@openzeppelin/contracts/math/SafeMath.sol";
import "@openzeppelin/contracts/token/ERC20/IERC20.sol";
import "@openzeppelin/contracts/token/ERC20/SafeERC20.sol";
import "./libraries/UniswapLibrary.sol";
import "./BlockLock.sol";
import "./interfaces/IxTokenManager.sol";
import "./interfaces/IxAsset.sol";
contract xAssetCLR is
Initializable,
ERC20Upgradeable,
OwnableUpgradeable,
PausableUpgradeable,
BlockLock
{
using SafeMath for uint256;
using SafeERC20 for IERC20;
uint256 private constant SWAP_SLIPPAGE = 50; // 2%
uint256 private constant MINT_BURN_SLIPPAGE = 100; // 1%
// Used to give an identical token representation
uint8 private constant TOKEN_DECIMAL_REPRESENTATION = 18;
int24 tickLower;
int24 tickUpper;
// Prices calculated using above ticks from TickMath.getSqrtRatioAtTick()
uint160 priceLower;
uint160 priceUpper;
int128 lastTwap; // Last stored oracle twap
// Max current twap vs last twap deviation percentage divisor (100 = 1%)
uint256 maxTwapDeviationDivisor;
IERC20 token0;
IERC20 token1;
uint256 public tokenId; // token id representing this uniswap position
uint256 public token0DecimalMultiplier; // 10 ** (18 - token0 decimals)
uint256 public token1DecimalMultiplier; // 10 ** (18 - token1 decimals)
uint256 public tokenDiffDecimalMultiplier; // 10 ** (token0 decimals - token1 decimals)
uint24 public poolFee;
uint8 public token0Decimals;
uint8 public token1Decimals;
UniswapContracts public uniContracts;
IxTokenManager xTokenManager; // xToken manager contract
uint32 twapPeriod;
struct UniswapContracts {
address pool;
address router;
address quoter;
address positionManager;
}
event Rebalance();
event FeeCollected(uint256 token0Fee, uint256 token1Fee);
function initialize(
string memory _symbol,
int24 _tickLower,
int24 _tickUpper,
IERC20 _token0,
IERC20 _token1,
UniswapContracts memory contracts,
address _xTokenManagerAddress,
uint256 _maxTwapDeviationDivisor,
uint8 _token0Decimals,
uint8 _token1Decimals
) external initializer {
__Context_init_unchained();
__Ownable_init_unchained();
__Pausable_init_unchained();
__ERC20_init_unchained("xAssetCLR", _symbol);
tickLower = _tickLower;
tickUpper = _tickUpper;
priceLower = UniswapLibrary.getSqrtRatio(_tickLower);
priceUpper = UniswapLibrary.getSqrtRatio(_tickUpper);
token0 = _token0;
token1 = _token1;
token0Decimals = _token0Decimals;
token1Decimals = _token1Decimals;
token0DecimalMultiplier =
10**(TOKEN_DECIMAL_REPRESENTATION - token0Decimals);
token1DecimalMultiplier =
10**(TOKEN_DECIMAL_REPRESENTATION - token1Decimals);
tokenDiffDecimalMultiplier =
10**((UniswapLibrary.subAbs(token0Decimals, token1Decimals)));
maxTwapDeviationDivisor = _maxTwapDeviationDivisor;
poolFee = 3000;
uniContracts = contracts;
token0.safeIncreaseAllowance(uniContracts.router, type(uint256).max);
token1.safeIncreaseAllowance(uniContracts.router, type(uint256).max);
token0.safeIncreaseAllowance(
uniContracts.positionManager,
type(uint256).max
);
token1.safeIncreaseAllowance(
uniContracts.positionManager,
type(uint256).max
);
UniswapLibrary.approveOneInch(token0, token1);
xTokenManager = IxTokenManager(_xTokenManagerAddress);
lastTwap = getAsset0Price();
twapPeriod = 3600;
}
/* ========================================================================================= */
/* User-facing */
/* ========================================================================================= */
/**
* @dev Mint xAssetCLR tokens by sending *amount* of *inputAsset* tokens
* @dev amount of the other asset is auto-calculated
*/
function mint(uint8 inputAsset, uint256 amount)
external
notLocked(msg.sender)
whenNotPaused()
{
require(amount > 0);
lock(msg.sender);
checkTwap();
(uint256 amount0, uint256 amount1) =
calculateAmountsMintedSingleToken(inputAsset, amount);
// Check if address has enough balance
uint256 token0Balance = token0.balanceOf(msg.sender);
uint256 token1Balance = token1.balanceOf(msg.sender);
if (amount0 > token0Balance || amount1 > token1Balance) {
amount0 = amount0 > token0Balance ? token0Balance : amount0;
amount1 = amount1 > token1Balance ? token1Balance : amount1;
(amount0, amount1) = calculatePoolMintedAmounts(amount0, amount1);
}
token0.safeTransferFrom(msg.sender, address(this), amount0);
token1.safeTransferFrom(msg.sender, address(this), amount1);
uint128 liquidityAmount =
getLiquidityForAmounts(amount0, amount1);
_mintInternal(liquidityAmount);
// stake tokens in pool
_stake(amount0, amount1);
}
/**
* @dev Burn *amount* of xAssetCLR tokens to receive proportional
* amount of pool tokens
*/
function burn(uint256 amount) external notLocked(msg.sender) {
require(amount > 0);
lock(msg.sender);
checkTwap();
uint256 totalLiquidity = getTotalLiquidity();
uint256 proRataBalance = amount.mul(totalLiquidity).div(totalSupply());
super._burn(msg.sender, amount);
(uint256 amount0, uint256 amount1) =
getAmountsForLiquidity(uint128(proRataBalance));
uint256 unstakeAmount0 = amount0.add(amount0.div(MINT_BURN_SLIPPAGE));
uint256 unstakeAmount1 = amount1.add(amount1.div(MINT_BURN_SLIPPAGE));
_unstake(unstakeAmount0, unstakeAmount1);
token0.safeTransfer(msg.sender, amount0);
token1.safeTransfer(msg.sender, amount1);
}
function transfer(address recipient, uint256 amount)
public
override
notLocked(msg.sender)
returns (bool)
{
return super.transfer(recipient, amount);
}
function transferFrom(
address sender,
address recipient,
uint256 amount
) public override notLocked(sender) returns (bool) {
return super.transferFrom(sender, recipient, amount);
}
/**
* @notice Get Net Asset Value in terms of token 1
* @dev NAV = token 0 amt * token 0 price + token1 amt
*/
function getNav() public view returns (uint256) {
return getStakedBalance().add(getBufferBalance());
}
/**
* @dev Returns amount in terms of asset 0
* @dev amount * asset 1 price
*/
function getAmountInAsset0Terms(uint256 amount)
public
view
returns (uint256)
{
return
UniswapLibrary.getAmountInAsset0Terms(
amount,
uniContracts.pool,
twapPeriod,
token0Decimals,
token1Decimals,
tokenDiffDecimalMultiplier
);
}
/**
* @dev Returns amount in terms of asset 1
* @dev amount * asset 0 price
*/
function getAmountInAsset1Terms(uint256 amount)
public
view
returns (uint256)
{
return
UniswapLibrary.getAmountInAsset1Terms(
amount,
uniContracts.pool,
twapPeriod,
token0Decimals,
token1Decimals,
tokenDiffDecimalMultiplier
);
}
/**
* @notice Get balance in xAssetCLR contract
* @notice amount is represented in token 1 terms:
* @dev token 0 amt * token 0 price + token1 amt
*/
function getBufferBalance() public view returns (uint256) {
(uint256 balance0, uint256 balance1) = getBufferTokenBalance();
return getAmountInAsset1Terms(balance0).add(balance1);
}
/**
* @notice Get total balance in the position
* @notice amount is represented in token 1 terms:
* @dev token 0 amt * token 0 price + token1 amt
*/
function getStakedBalance() public view returns (uint256) {
(uint256 amount0, uint256 amount1) = getStakedTokenBalance();
return getAmountInAsset1Terms(amount0).add(amount1);
}
/**
* @notice Get token balances in xAssetCLR contract
* @dev returned balances are represented with 18 decimals
*/
function getBufferTokenBalance()
public
view
returns (uint256 amount0, uint256 amount1)
{
return (getBufferToken0Balance(), getBufferToken1Balance());
}
/**
* @notice Get token0 balance in xAssetCLR
* @dev returned balance is represented with 18 decimals
*/
function getBufferToken0Balance() public view returns (uint256 amount0) {
return getToken0AmountInWei(token0.balanceOf(address(this)));
}
/**
* @notice Get token1 balance in xAssetCLR
* @dev returned balance is represented with 18 decimals
*/
function getBufferToken1Balance() public view returns (uint256 amount1) {
return getToken1AmountInWei(token1.balanceOf(address(this)));
}
/**
* @notice Get token balances in the position
* @dev returned balance is represented with 18 decimals
*/
function getStakedTokenBalance()
public
view
returns (uint256 amount0, uint256 amount1)
{
(amount0, amount1) = getAmountsForLiquidity(getPositionLiquidity());
amount0 = getToken0AmountInWei(amount0);
amount1 = getToken1AmountInWei(amount1);
}
/**
* @notice Get total liquidity
* @dev buffer liquidity + position liquidity
*/
function getTotalLiquidity() public view returns (uint256 amount) {
(uint256 buffer0, uint256 buffer1) = getBufferTokenBalance();
uint128 bufferLiquidity = getLiquidityForAmounts(buffer0, buffer1);
uint128 positionLiquidity = getPositionLiquidity();
return uint256(bufferLiquidity).add(uint256(positionLiquidity));
}
/**
* @dev Check how much xAssetCLR tokens will be minted on mint
* @dev Uses position liquidity to calculate the amount
*/
function calculateMintAmount(uint256 _amount, uint256 totalSupply)
public
view
returns (uint256 mintAmount)
{
if (totalSupply == 0) return _amount;
uint256 previousLiquidity = getTotalLiquidity().sub(_amount);
mintAmount = (_amount).mul(totalSupply).div(previousLiquidity);
return mintAmount;
}
/* ========================================================================================= */
/* Management */
/* ========================================================================================= */
/**
* @dev Collect rewards from pool and stake them in position
* @dev may leave unstaked tokens in contract
*/
function collectAndRestake() external onlyOwnerOrManager {
(uint256 amount0, uint256 amount1) = collect();
(uint256 stakeAmount0, uint256 stakeAmount1) =
calculatePoolMintedAmounts(amount0, amount1);
_stake(stakeAmount0, stakeAmount1);
}
/**
* @dev Collect fees generated from position
*/
function collect()
public
onlyOwnerOrManager
returns (uint256 collected0, uint256 collected1)
{
(collected0, collected1) = collectPosition(
type(uint128).max,
type(uint128).max
);
emit FeeCollected(collected0, collected1);
}
/**
* @dev Migrate the current position to a new position with different ticks
*/
function migratePosition(int24 newTickLower, int24 newTickUpper)
public
onlyOwnerOrManager
{
require(newTickLower != tickLower || newTickUpper != tickUpper);
// withdraw entire liquidity from the position
(uint256 _amount0, uint256 _amount1) = withdrawAll();
// burn current position NFT
UniswapLibrary.burn(uniContracts.positionManager, tokenId);
// set new ticks and prices
tickLower = newTickLower;
tickUpper = newTickUpper;
priceLower = UniswapLibrary.getSqrtRatio(newTickLower);
priceUpper = UniswapLibrary.getSqrtRatio(newTickUpper);
(uint256 amount0, uint256 amount1) =
calculatePoolMintedAmounts(_amount0, _amount1);
// mint the position NFT and deposit the liquidity
// set new NFT token id
tokenId = createPosition(amount0, amount1);
}
/**
* @dev Migrate the current position to a new position with different ticks
* @dev Migrates position tick lower and upper by same amount of ticks
* @dev Tick spacing (minimum tick difference) in pool w/ 3000 fee is 60
* @param ticks how many ticks to shift up or down
* @param up whether to move tick range up or down
*/
function migrateParallel(uint24 ticks, bool up)
external
onlyOwnerOrManager
{
require(ticks != 0);
int24 newTickLower;
int24 newTickUpper;
int24 ticksToShift = int24(ticks) * 60;
if (up) {
newTickLower = tickLower + ticksToShift;
newTickUpper = tickUpper + ticksToShift;
} else {
newTickLower = tickLower - ticksToShift;
newTickUpper = tickUpper - ticksToShift;
}
migratePosition(newTickLower, newTickUpper);
}
/**
* @dev Mint function which initializes the pool position
* @dev Must be called before any liquidity can be deposited
*/
function mintInitial(uint256 amount0, uint256 amount1)
external
onlyOwnerOrManager
{
require(tokenId == 0);
require(amount0 > 0 || amount1 > 0);
checkTwap();
(uint256 amount0Minted, uint256 amount1Minted) =
calculatePoolMintedAmounts(amount0, amount1);
token0.safeTransferFrom(msg.sender, address(this), amount0Minted);
token1.safeTransferFrom(msg.sender, address(this), amount1Minted);
tokenId = createPosition(amount0Minted, amount1Minted);
uint256 liquidity =
uint256(getLiquidityForAmounts(amount0Minted, amount1Minted));
_mintInternal(liquidity);
}
/**
* @dev Admin function to stake tokens
* @dev used in case there's leftover tokens in the contract
*/
function adminRebalance() external onlyOwnerOrManager {
UniswapLibrary.adminRebalance(
UniswapLibrary.TokenDetails({
token0: address(token0),
token1: address(token1),
token0DecimalMultiplier: token0DecimalMultiplier,
token1DecimalMultiplier: token1DecimalMultiplier,
tokenDiffDecimalMultiplier: tokenDiffDecimalMultiplier,
token0Decimals: token0Decimals,
token1Decimals: token1Decimals
}),
UniswapLibrary.PositionDetails({
poolFee: poolFee,
twapPeriod: twapPeriod,
priceLower: priceLower,
priceUpper: priceUpper,
tokenId: tokenId,
positionManager: uniContracts.positionManager,
router: uniContracts.router,
quoter: uniContracts.quoter,
pool: uniContracts.pool
})
);
emit Rebalance();
}
/**
* @dev Admin function for staking in position
*/
function adminStake(uint256 amount0, uint256 amount1)
external
onlyOwnerOrManager
{
(uint256 stakeAmount0, uint256 stakeAmount1) =
calculatePoolMintedAmounts(amount0, amount1);
_stake(stakeAmount0, stakeAmount1);
}
/**
* @dev Admin function for unstaking from position
*/
function adminUnstake(uint256 amount0, uint256 amount1)
external
onlyOwnerOrManager
{
_unstake(amount0, amount1);
}
/**
* @dev Admin function for swapping LP tokens in xAssetCLR
* @param amount - swap amount (in t0 terms if _0for1 is true, in t1 terms if false)
* @param _0for1 - swap token 0 for 1 if true, token 1 for 0 if false
*/
function adminSwap(uint256 amount, bool _0for1)
external
onlyOwnerOrManager
{
if (_0for1) {
swapToken0ForToken1(amount.add(amount.div(SWAP_SLIPPAGE)), amount);
} else {
swapToken1ForToken0(amount.add(amount.div(SWAP_SLIPPAGE)), amount);
}
}
/**
* @dev Admin function for swapping LP tokens in xAssetCLR using 1inch v3 exchange
* @param minReturn - how much output tokens to receive on swap, in 18 decimals
* @param _0for1 - swap token 0 for token 1 if true, token 1 for token 0 if false
* @param _oneInchData - 1inch calldata, generated off-chain using their v3 api
*/
function adminSwapOneInch(
uint256 minReturn,
bool _0for1,
bytes memory _oneInchData
) external onlyOwnerOrManager {
UniswapLibrary.oneInchSwap(
minReturn,
_0for1,
UniswapLibrary.TokenDetails({
token0: address(token0),
token1: address(token1),
token0DecimalMultiplier: token0DecimalMultiplier,
token1DecimalMultiplier: token1DecimalMultiplier,
tokenDiffDecimalMultiplier: tokenDiffDecimalMultiplier,
token0Decimals: token0Decimals,
token1Decimals: token1Decimals
}),
_oneInchData
);
}
/**
* @dev Stake liquidity in position
*/
function _stake(uint256 amount0, uint256 amount1)
private
returns (uint256 stakedAmount0, uint256 stakedAmount1)
{
return
UniswapLibrary.stake(
amount0,
amount1,
uniContracts.positionManager,
tokenId
);
}
/**
* @dev Unstake liquidity from position
*/
function _unstake(uint256 amount0, uint256 amount1)
private
returns (uint256 collected0, uint256 collected1)
{
uint128 liquidityAmount = getLiquidityForAmounts(amount0, amount1);
(uint256 _amount0, uint256 _amount1) = unstakePosition(liquidityAmount);
return collectPosition(uint128(_amount0), uint128(_amount1));
}
/**
* @dev Withdraws all current liquidity from the position
*/
function withdrawAll()
private
returns (uint256 _amount0, uint256 _amount1)
{
// Collect fees
collect();
(_amount0, _amount1) = unstakePosition(getPositionLiquidity());
collectPosition(uint128(_amount0), uint128(_amount1));
}
/**
* @dev Creates the NFT token representing the pool position
* @dev Mint initial liquidity
*/
function createPosition(uint256 amount0, uint256 amount1)
private
returns (uint256 _tokenId)
{
UniswapLibrary.TokenDetails memory tokenDetails =
UniswapLibrary.TokenDetails({
token0: address(token0),
token1: address(token1),
token0DecimalMultiplier: token0DecimalMultiplier,
token1DecimalMultiplier: token1DecimalMultiplier,
tokenDiffDecimalMultiplier: tokenDiffDecimalMultiplier,
token0Decimals: token0Decimals,
token1Decimals: token1Decimals
});
UniswapLibrary.PositionDetails memory positionDetails =
UniswapLibrary.PositionDetails({
poolFee: poolFee,
twapPeriod: twapPeriod,
priceLower: priceLower,
priceUpper: priceUpper,
tokenId: tokenId,
positionManager: uniContracts.positionManager,
router: uniContracts.router,
quoter: uniContracts.quoter,
pool: uniContracts.pool
});
return
UniswapLibrary.createPosition(
amount0,
amount1,
uniContracts.positionManager,
tokenDetails,
positionDetails
);
}
/**
* @dev Unstakes a given amount of liquidity from the Uni V3 position
* @param liquidity amount of liquidity to unstake
* @return amount0 token0 amount unstaked
* @return amount1 token1 amount unstaked
*/
function unstakePosition(uint128 liquidity)
private
returns (uint256 amount0, uint256 amount1)
{
UniswapLibrary.PositionDetails memory positionDetails =
UniswapLibrary.PositionDetails({
poolFee: poolFee,
twapPeriod: twapPeriod,
priceLower: priceLower,
priceUpper: priceUpper,
tokenId: tokenId,
positionManager: uniContracts.positionManager,
router: uniContracts.router,
quoter: uniContracts.quoter,
pool: uniContracts.pool
});
return UniswapLibrary.unstakePosition(liquidity, positionDetails);
}
function _mintInternal(uint256 _amount) private {
uint256 mintAmount = calculateMintAmount(_amount, totalSupply());
return super._mint(msg.sender, mintAmount);
}
/*
* Emergency function in case of errant transfer
* of any token directly to contract
*/
function withdrawToken(address token, address receiver)
external
onlyOwnerOrManager
{
require(token != address(token0) && token != address(token1));
uint256 tokenBal = IERC20(address(token)).balanceOf(address(this));
IERC20(address(token)).safeTransfer(receiver, tokenBal);
}
/**
* Mint xAsset tokens using underlying
* xAsset contract needs to be approved
* @param amount amount to mint
* @param isToken0 if true, call mint on token0, else on token1
*/
function adminMint(uint256 amount, bool isToken0) external onlyOwnerOrManager {
if(isToken0) {
IxAsset(address(token0)).mintWithToken(amount);
} else {
IxAsset(address(token1)).mintWithToken(amount);
}
}
/**
* Burn xAsset tokens using underlying
* @param amount amount to burn
* @param isToken0 if true, call burn on token0, else on token1
*/
function adminBurn(uint256 amount, bool isToken0) external onlyOwnerOrManager {
if(isToken0) {
IxAsset(address(token0)).burn(amount, false, 1);
} else {
IxAsset(address(token1)).burn(amount, false, 1);
}
}
/**
* Approve underlying token to xAsset tokens
* @param isToken0 if token 0 is xAsset token, set to true, otherwise false
*/
function adminApprove(bool isToken0) external onlyOwnerOrManager {
if(isToken0) {
token1.safeApprove(address(token0), type(uint256).max);
} else {
token0.safeApprove(address(token1), type(uint256).max);
}
}
function pauseContract() external onlyOwnerOrManager returns (bool) {
_pause();
return true;
}
function unpauseContract() external onlyOwnerOrManager returns (bool) {
_unpause();
return true;
}
modifier onlyOwnerOrManager {
require(
msg.sender == owner() ||
xTokenManager.isManager(msg.sender, address(this)),
"Function may be called only by owner or manager"
);
_;
}
/* ========================================================================================= */
/* Uniswap helpers */
/* ========================================================================================= */
/**
* @dev Swap token 0 for token 1 in xAssetCLR using Uni V3 Pool
* @dev amounts should be in 18 decimals
* @param amountIn - amount as maximum input for swap, in token 0 terms
* @param amountOut - amount as output for swap, in token 0 terms
*/
function swapToken0ForToken1(uint256 amountIn, uint256 amountOut) private {
UniswapLibrary.swapToken0ForToken1(
amountIn,
amountOut,
UniswapLibrary.PositionDetails({
poolFee: poolFee,
twapPeriod: twapPeriod,
priceLower: priceLower,
priceUpper: priceUpper,
tokenId: tokenId,
positionManager: uniContracts.positionManager,
router: uniContracts.router,
quoter: uniContracts.quoter,
pool: uniContracts.pool
}),
UniswapLibrary.TokenDetails({
token0: address(token0),
token1: address(token1),
token0DecimalMultiplier: token0DecimalMultiplier,
token1DecimalMultiplier: token1DecimalMultiplier,
tokenDiffDecimalMultiplier: tokenDiffDecimalMultiplier,
token0Decimals: token0Decimals,
token1Decimals: token1Decimals
})
);
}
/**
* @dev Swap token 1 for token 0 in xAssetCLR using Uni V3 Pool
* @dev amounts should be in 18 decimals
* @param amountIn - amount as maximum input for swap, in token 1 terms
* @param amountOut - amount as output for swap, in token 1 terms
*/
function swapToken1ForToken0(uint256 amountIn, uint256 amountOut) private {
UniswapLibrary.swapToken1ForToken0(
amountIn,
amountOut,
UniswapLibrary.PositionDetails({
poolFee: poolFee,
twapPeriod: twapPeriod,
priceLower: priceLower,
priceUpper: priceUpper,
tokenId: tokenId,
positionManager: uniContracts.positionManager,
router: uniContracts.router,
quoter: uniContracts.quoter,
pool: uniContracts.pool
}),
UniswapLibrary.TokenDetails({
token0: address(token0),
token1: address(token1),
token0DecimalMultiplier: token0DecimalMultiplier,
token1DecimalMultiplier: token1DecimalMultiplier,
tokenDiffDecimalMultiplier: tokenDiffDecimalMultiplier,
token0Decimals: token0Decimals,
token1Decimals: token1Decimals
})
);
}
/**
* @dev Collect token amounts from pool position
*/
function collectPosition(uint128 amount0, uint128 amount1)
private
returns (uint256 collected0, uint256 collected1)
{
return
UniswapLibrary.collectPosition(
amount0,
amount1,
tokenId,
uniContracts.positionManager
);
}
/**
* @dev Change pool fee and address
*/
function changePool(address _poolAddress, uint24 _poolFee)
external
onlyOwnerOrManager
{
uniContracts.pool = _poolAddress;
poolFee = _poolFee;
}
// Returns the current liquidity in the position
function getPositionLiquidity() public view returns (uint128 liquidity) {
return
UniswapLibrary.getPositionLiquidity(
uniContracts.positionManager,
tokenId
);
}
/**
* @dev Get asset 0 twap
* @dev Uses Uni V3 oracle, reading the TWAP from twap period
* @dev or the earliest oracle observation time if twap period is not set
*/
function getAsset0Price() public view returns (int128) {
return
UniswapLibrary.getAsset0Price(
uniContracts.pool,
twapPeriod,
token0Decimals,
token1Decimals,
tokenDiffDecimalMultiplier
);
}
/**
* @dev Get asset 1 twap
* @dev Uses Uni V3 oracle, reading the TWAP from twap period
* @dev or the earliest oracle observation time if twap period is not set
*/
function getAsset1Price() public view returns (int128) {
return
UniswapLibrary.getAsset1Price(
uniContracts.pool,
twapPeriod,
token0Decimals,
token1Decimals,
tokenDiffDecimalMultiplier
);
}
/**
* @dev Checks if twap deviates too much from the previous twap
*/
function checkTwap() private {
lastTwap = UniswapLibrary.checkTwap(
uniContracts.pool,
twapPeriod,
token0Decimals,
token1Decimals,
tokenDiffDecimalMultiplier,
lastTwap,
maxTwapDeviationDivisor
);
}
/**
* @dev Reset last twap if oracle price is consistently above the max deviation
*/
function resetTwap() external onlyOwnerOrManager {
lastTwap = getAsset0Price();
}
/**
* @dev Set the max twap deviation divisor
* @dev if twap moves more than the divisor specified
* @dev mint, burn and mintInitial functions are locked
*/
function setMaxTwapDeviationDivisor(uint256 newDeviationDivisor)
external
onlyOwnerOrManager
{
maxTwapDeviationDivisor = newDeviationDivisor;
}
/**
* @dev Set the oracle reading twap period
* @dev Twap used is [now - twapPeriod, now]
*/
function setTwapPeriod(uint32 newPeriod) external onlyOwnerOrManager {
require(newPeriod >= 360);
twapPeriod = newPeriod;
}
/**
* @dev Calculates the amounts deposited/withdrawn from the pool
* amount0, amount1 - amounts to deposit/withdraw
* amount0Minted, amount1Minted - actual amounts which can be deposited
*/
function calculatePoolMintedAmounts(uint256 amount0, uint256 amount1)
public
view
returns (uint256 amount0Minted, uint256 amount1Minted)
{
uint128 liquidityAmount = getLiquidityForAmounts(amount0, amount1);
(amount0Minted, amount1Minted) = getAmountsForLiquidity(
liquidityAmount
);
}
/**
* @dev Calculates single-side minted amount
* @param inputAsset - use token0 if 0, token1 else
* @param amount - amount to deposit/withdraw
*/
function calculateAmountsMintedSingleToken(uint8 inputAsset, uint256 amount)
public
view
returns (uint256 amount0Minted, uint256 amount1Minted)
{
uint128 liquidityAmount;
if (inputAsset == 0) {
liquidityAmount = getLiquidityForAmounts(amount, type(uint112).max);
} else {
liquidityAmount = getLiquidityForAmounts(type(uint112).max, amount);
}
(amount0Minted, amount1Minted) = getAmountsForLiquidity(
liquidityAmount
);
}
function getLiquidityForAmounts(uint256 amount0, uint256 amount1)
public
view
returns (uint128 liquidity)
{
liquidity = UniswapLibrary.getLiquidityForAmounts(
amount0,
amount1,
priceLower,
priceUpper,
uniContracts.pool
);
}
function getAmountsForLiquidity(uint128 liquidity)
public
view
returns (uint256 amount0, uint256 amount1)
{
(amount0, amount1) = UniswapLibrary.getAmountsForLiquidity(
liquidity,
priceLower,
priceUpper,
uniContracts.pool
);
}
/**
* @dev Get lower and upper ticks of the pool position
*/
function getTicks() external view returns (int24 tick0, int24 tick1) {
return (tickLower, tickUpper);
}
/**
* Returns token0 amount in TOKEN_DECIMAL_REPRESENTATION
*/
function getToken0AmountInWei(uint256 amount)
private
view
returns (uint256)
{
return
UniswapLibrary.getToken0AmountInWei(
amount,
token0Decimals,
token0DecimalMultiplier
);
}
/**
* Returns token1 amount in TOKEN_DECIMAL_REPRESENTATION
*/
function getToken1AmountInWei(uint256 amount)
private
view
returns (uint256)
{
return
UniswapLibrary.getToken1AmountInWei(
amount,
token1Decimals,
token1DecimalMultiplier
);
}
}
// SPDX-License-Identifier: MIT
// solhint-disable-next-line compiler-version
pragma solidity >=0.4.24 <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 {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 || _isConstructor() || !_initialized, "Initializable: contract is already 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) {
return !AddressUpgradeable.isContract(address(this));
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.7.0;
import "../utils/ContextUpgradeable.sol";
import "../proxy/Initializable.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 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;
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.7.0;
import "./ContextUpgradeable.sol";
import "../proxy/Initializable.sol";
/**
* @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 PausableUpgradeable is Initializable, ContextUpgradeable {
/**
* @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 virtual 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());
}
uint256[49] private __gap;
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.7.0;
import "../../utils/ContextUpgradeable.sol";
import "./IERC20Upgradeable.sol";
import "../../math/SafeMathUpgradeable.sol";
import "../../proxy/Initializable.sol";
/**
* @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 ERC20Upgradeable is Initializable, ContextUpgradeable, IERC20Upgradeable {
using SafeMathUpgradeable 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.
*/
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 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 {_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 virtual 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 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 virtual {
_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;
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.7.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.7.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.7.0;
import "./IERC20.sol";
import "../../math/SafeMath.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 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");
}
}
}
// SPDX-License-Identifier: BUSL-1.1
pragma solidity 0.7.6;
pragma abicoder v2;
import "@uniswap/v3-periphery/contracts/interfaces/INonfungiblePositionManager.sol";
import "@uniswap/v3-periphery/contracts/interfaces/ISwapRouter.sol";
import "@uniswap/v3-periphery/contracts/interfaces/IQuoter.sol";
import "@uniswap/v3-periphery/contracts/libraries/LiquidityAmounts.sol";
import "@uniswap/v3-core/contracts/interfaces/IUniswapV3Pool.sol";
import "@uniswap/v3-core/contracts/libraries/TickMath.sol";
import "@openzeppelin/contracts/token/ERC20/IERC20.sol";
import "@openzeppelin/contracts/token/ERC20/SafeERC20.sol";
import "@openzeppelin/contracts/math/SafeMath.sol";
import "./ABDKMath64x64.sol";
import "./Utils.sol";
/**
* Helper library for Uniswap functions
* Used in xAssetCLR
*/
library UniswapLibrary {
using SafeMath for uint256;
using SafeERC20 for IERC20;
uint8 private constant TOKEN_DECIMAL_REPRESENTATION = 18;
uint256 private constant SWAP_SLIPPAGE = 50; // 2%
uint256 private constant MINT_BURN_SLIPPAGE = 100; // 1%
// 1inch v3 exchange address
address private constant oneInchExchange =
0x11111112542D85B3EF69AE05771c2dCCff4fAa26;
struct TokenDetails {
address token0;
address token1;
uint256 token0DecimalMultiplier;
uint256 token1DecimalMultiplier;
uint256 tokenDiffDecimalMultiplier;
uint8 token0Decimals;
uint8 token1Decimals;
}
struct PositionDetails {
uint24 poolFee;
uint32 twapPeriod;
uint160 priceLower;
uint160 priceUpper;
uint256 tokenId;
address positionManager;
address router;
address quoter;
address pool;
}
struct AmountsMinted {
uint256 amount0ToMint;
uint256 amount1ToMint;
uint256 amount0Minted;
uint256 amount1Minted;
}
/* ========================================================================================= */
/* Uni V3 Pool Helper functions */
/* ========================================================================================= */
/**
* @dev Returns the current pool price in X96 notation
*/
function getPoolPrice(address _pool) public view returns (uint160) {
IUniswapV3Pool pool = IUniswapV3Pool(_pool);
(uint160 sqrtRatioX96, , , , , , ) = pool.slot0();
return sqrtRatioX96;
}
/**
* Get pool price in decimal notation with 12 decimals
*/
function getPoolPriceWithDecimals(address _pool)
public
view
returns (uint256 price)
{
uint160 sqrtRatioX96 = getPoolPrice(_pool);
return
uint256(sqrtRatioX96).mul(uint256(sqrtRatioX96)).mul(1e12) >> 192;
}
/**
* @dev Returns the current pool liquidity
*/
function getPoolLiquidity(address _pool) public view returns (uint128) {
IUniswapV3Pool pool = IUniswapV3Pool(_pool);
return pool.liquidity();
}
/**
* @dev Calculate pool liquidity for given token amounts
*/
function getLiquidityForAmounts(
uint256 amount0,
uint256 amount1,
uint160 priceLower,
uint160 priceUpper,
address pool
) public view returns (uint128 liquidity) {
liquidity = LiquidityAmounts.getLiquidityForAmounts(
getPoolPrice(pool),
priceLower,
priceUpper,
amount0,
amount1
);
}
/**
* @dev Calculate token amounts for given pool liquidity
*/
function getAmountsForLiquidity(
uint128 liquidity,
uint160 priceLower,
uint160 priceUpper,
address pool
) public view returns (uint256 amount0, uint256 amount1) {
(amount0, amount1) = LiquidityAmounts.getAmountsForLiquidity(
getPoolPrice(pool),
priceLower,
priceUpper,
liquidity
);
}
/**
* @dev Calculates the amounts deposited/withdrawn from the pool
* @param amount0 - token0 amount to deposit/withdraw
* @param amount1 - token1 amount to deposit/withdraw
*/
function calculatePoolMintedAmounts(
uint256 amount0,
uint256 amount1,
uint160 priceLower,
uint160 priceUpper,
address pool
) public view returns (uint256 amount0Minted, uint256 amount1Minted) {
uint128 liquidityAmount =
getLiquidityForAmounts(
amount0,
amount1,
priceLower,
priceUpper,
pool
);
(amount0Minted, amount1Minted) = getAmountsForLiquidity(
liquidityAmount,
priceLower,
priceUpper,
pool
);
}
/**
* @dev Get asset 0 twap
* @dev Uses Uni V3 oracle, reading the TWAP from twap period
* @dev or the earliest oracle observation time if twap period is not set
*/
function getAsset0Price(
address pool,
uint32 twapPeriod,
uint8 token0Decimals,
uint8 token1Decimals,
uint256 tokenDiffDecimalMultiplier
) public view returns (int128) {
uint32[] memory secondsArray = new uint32[](2);
// get earliest oracle observation time
IUniswapV3Pool poolImpl = IUniswapV3Pool(pool);
uint32 observationTime = getObservationTime(poolImpl);
uint32 currTimestamp = uint32(block.timestamp);
uint32 earliestObservationSecondsAgo = currTimestamp - observationTime;
if (
twapPeriod == 0 ||
!Utils.lte(
currTimestamp,
observationTime,
currTimestamp - twapPeriod
)
) {
// set to earliest observation time if:
// a) twap period is 0 (not set)
// b) now - twap period is before earliest observation
secondsArray[0] = earliestObservationSecondsAgo;
} else {
secondsArray[0] = twapPeriod;
}
secondsArray[1] = 0;
(int56[] memory prices, ) = poolImpl.observe(secondsArray);
int128 twap = Utils.getTWAP(prices, secondsArray[0]);
if (token1Decimals > token0Decimals) {
// divide twap by token decimal difference
twap = ABDKMath64x64.mul(
twap,
ABDKMath64x64.divu(1, tokenDiffDecimalMultiplier)
);
} else if (token0Decimals > token1Decimals) {
// multiply twap by token decimal difference
int128 multiplierFixed =
ABDKMath64x64.fromUInt(tokenDiffDecimalMultiplier);
twap = ABDKMath64x64.mul(twap, multiplierFixed);
}
return twap;
}
/**
* @dev Get asset 1 twap
* @dev Uses Uni V3 oracle, reading the TWAP from twap period
* @dev or the earliest oracle observation time if twap period is not set
*/
function getAsset1Price(
address pool,
uint32 twapPeriod,
uint8 token0Decimals,
uint8 token1Decimals,
uint256 tokenDiffDecimalMultiplier
) public view returns (int128) {
return
ABDKMath64x64.inv(
getAsset0Price(
pool,
twapPeriod,
token0Decimals,
token1Decimals,
tokenDiffDecimalMultiplier
)
);
}
/**
* @dev Returns amount in terms of asset 0
* @dev amount * asset 1 price
*/
function getAmountInAsset0Terms(
uint256 amount,
address pool,
uint32 twapPeriod,
uint8 token0Decimals,
uint8 token1Decimals,
uint256 tokenDiffDecimalMultiplier
) public view returns (uint256) {
return
ABDKMath64x64.mulu(
getAsset1Price(
pool,
twapPeriod,
token0Decimals,
token1Decimals,
tokenDiffDecimalMultiplier
),
amount
);
}
/**
* @dev Returns amount in terms of asset 1
* @dev amount * asset 0 price
*/
function getAmountInAsset1Terms(
uint256 amount,
address pool,
uint32 twapPeriod,
uint8 token0Decimals,
uint8 token1Decimals,
uint256 tokenDiffDecimalMultiplier
) public view returns (uint256) {
return
ABDKMath64x64.mulu(
getAsset0Price(
pool,
twapPeriod,
token0Decimals,
token1Decimals,
tokenDiffDecimalMultiplier
),
amount
);
}
/**
* @dev Returns the earliest oracle observation time
*/
function getObservationTime(IUniswapV3Pool _pool)
public
view
returns (uint32)
{
IUniswapV3Pool pool = _pool;
(, , uint16 index, uint16 cardinality, , , ) = pool.slot0();
uint16 oldestObservationIndex = (index + 1) % cardinality;
(uint32 observationTime, , , bool initialized) =
pool.observations(oldestObservationIndex);
if (!initialized) (observationTime, , , ) = pool.observations(0);
return observationTime;
}
/**
* @dev Checks if twap deviates too much from the previous twap
* @return current twap
*/
function checkTwap(
address pool,
uint32 twapPeriod,
uint8 token0Decimals,
uint8 token1Decimals,
uint256 tokenDiffDecimalMultiplier,
int128 lastTwap,
uint256 maxTwapDeviationDivisor
) public view returns (int128) {
int128 twap =
getAsset0Price(
pool,
twapPeriod,
token0Decimals,
token1Decimals,
tokenDiffDecimalMultiplier
);
int128 _lastTwap = lastTwap;
int128 deviation =
_lastTwap > twap ? _lastTwap - twap : twap - _lastTwap;
int128 maxDeviation =
ABDKMath64x64.mul(
twap,
ABDKMath64x64.divu(1, maxTwapDeviationDivisor)
);
require(deviation <= maxDeviation, "Wrong twap");
return twap;
}
/* ========================================================================================= */
/* Uni V3 Swap Router Helper functions */
/* ========================================================================================= */
/**
* @dev Swap token 0 for token 1 in xAssetCLR contract
* @dev amountIn and amountOut should be in 18 decimals always
* @dev amountIn and amountOut are in token 0 terms
*/
function swapToken0ForToken1(
uint256 amountIn,
uint256 amountOut,
PositionDetails memory positionDetails,
TokenDetails memory tokenDetails
) public returns (uint256 _amountOut) {
uint256 midPrice = getPoolPriceWithDecimals(positionDetails.pool);
amountOut = amountOut.mul(midPrice).div(1e12);
uint256 token0Balance =
getBufferToken0Balance(
IERC20(tokenDetails.token0),
tokenDetails.token0Decimals,
tokenDetails.token0DecimalMultiplier
);
require(
token0Balance >= amountIn,
"Swap token 0 for token 1: not enough token 0 balance"
);
amountIn = getToken0AmountInNativeDecimals(
amountIn,
tokenDetails.token0Decimals,
tokenDetails.token0DecimalMultiplier
);
amountOut = getToken1AmountInNativeDecimals(
amountOut,
tokenDetails.token1Decimals,
tokenDetails.token1DecimalMultiplier
);
uint256 amountOutExpected =
IQuoter(positionDetails.quoter).quoteExactInputSingle(
tokenDetails.token0,
tokenDetails.token1,
positionDetails.poolFee,
amountIn,
TickMath.MIN_SQRT_RATIO + 1
);
if (amountOutExpected < amountOut) {
amountOut = amountOutExpected;
}
ISwapRouter(positionDetails.router).exactOutputSingle(
ISwapRouter.ExactOutputSingleParams({
tokenIn: tokenDetails.token0,
tokenOut: tokenDetails.token1,
fee: positionDetails.poolFee,
recipient: address(this),
deadline: block.timestamp,
amountOut: amountOut,
amountInMaximum: amountIn,
sqrtPriceLimitX96: TickMath.MIN_SQRT_RATIO + 1
})
);
return amountOut;
}
/**
* @dev Swap token 1 for token 0 in xAssetCLR contract
* @dev amountIn and amountOut should be in 18 decimals always
* @dev amountIn and amountOut are in token 1 terms
*/
function swapToken1ForToken0(
uint256 amountIn,
uint256 amountOut,
PositionDetails memory positionDetails,
TokenDetails memory tokenDetails
) public returns (uint256 _amountIn) {
uint256 midPrice = getPoolPriceWithDecimals(positionDetails.pool);
amountOut = amountOut.mul(1e12).div(midPrice);
uint256 token1Balance =
getBufferToken1Balance(
IERC20(tokenDetails.token1),
tokenDetails.token1Decimals,
tokenDetails.token1DecimalMultiplier
);
require(
token1Balance >= amountIn,
"Swap token 1 for token 0: not enough token 1 balance"
);
amountIn = getToken1AmountInNativeDecimals(
amountIn,
tokenDetails.token1Decimals,
tokenDetails.token1DecimalMultiplier
);
amountOut = getToken0AmountInNativeDecimals(
amountOut,
tokenDetails.token0Decimals,
tokenDetails.token0DecimalMultiplier
);
uint256 amountOutExpected =
IQuoter(positionDetails.quoter).quoteExactInputSingle(
tokenDetails.token1,
tokenDetails.token0,
positionDetails.poolFee,
amountIn,
TickMath.MAX_SQRT_RATIO - 1
);
if (amountOutExpected < amountOut) {
amountOut = amountOutExpected;
}
ISwapRouter(positionDetails.router).exactOutputSingle(
ISwapRouter.ExactOutputSingleParams({
tokenIn: tokenDetails.token1,
tokenOut: tokenDetails.token0,
fee: positionDetails.poolFee,
recipient: address(this),
deadline: block.timestamp,
amountOut: amountOut,
amountInMaximum: amountIn,
sqrtPriceLimitX96: TickMath.MAX_SQRT_RATIO - 1
})
);
return amountIn;
}
/* ========================================================================================= */
/* 1inch Swap Helper functions */
/* ========================================================================================= */
/**
* @dev Swap tokens in xAssetCLR using 1inch v3 exchange
* @param minReturn - required min amount out from swap, in 18 decimals
* @param _0for1 - swap token0 for token1 if true, token1 for token0 if false
* @param tokenDetails - xAssetCLR token 0 and token 1 details
* @param _oneInchData - One inch calldata, generated off-chain from their v3 api for the swap
*/
function oneInchSwap(
uint256 minReturn,
bool _0for1,
TokenDetails memory tokenDetails,
bytes memory _oneInchData
) public {
uint256 token0AmtSwapped;
uint256 token1AmtSwapped;
bool success;
// inline code to prevent stack too deep errors
{
IERC20 token0 = IERC20(tokenDetails.token0);
IERC20 token1 = IERC20(tokenDetails.token1);
uint256 balanceBeforeToken0 = token0.balanceOf(address(this));
uint256 balanceBeforeToken1 = token1.balanceOf(address(this));
(success, ) = oneInchExchange.call(_oneInchData);
require(success, "One inch swap call failed");
uint256 balanceAfterToken0 = token0.balanceOf(address(this));
uint256 balanceAfterToken1 = token1.balanceOf(address(this));
token0AmtSwapped = subAbs(balanceAfterToken0, balanceBeforeToken0);
token1AmtSwapped = subAbs(balanceAfterToken1, balanceBeforeToken1);
}
uint256 amountInSwapped;
uint256 amountOutReceived;
if (_0for1) {
amountInSwapped = getToken0AmountInWei(
token0AmtSwapped,
tokenDetails.token0Decimals,
tokenDetails.token0DecimalMultiplier
);
amountOutReceived = getToken1AmountInWei(
token1AmtSwapped,
tokenDetails.token1Decimals,
tokenDetails.token1DecimalMultiplier
);
} else {
amountInSwapped = getToken1AmountInWei(
token1AmtSwapped,
tokenDetails.token1Decimals,
tokenDetails.token1DecimalMultiplier
);
amountOutReceived = getToken0AmountInWei(
token0AmtSwapped,
tokenDetails.token0Decimals,
tokenDetails.token0DecimalMultiplier
);
}
// require minimum amount received is > min return
require(
amountOutReceived > minReturn,
"One inch swap not enough output token amount"
);
}
/**
* Approve 1inch v3 for swaps
*/
function approveOneInch(IERC20 token0, IERC20 token1) public {
token0.safeApprove(oneInchExchange, type(uint256).max);
token1.safeApprove(oneInchExchange, type(uint256).max);
}
/* ========================================================================================= */
/* NFT Position Manager Helpers */
/* ========================================================================================= */
/**
* @dev Returns the current liquidity in a position represented by tokenId NFT
*/
function getPositionLiquidity(address positionManager, uint256 tokenId)
public
view
returns (uint128 liquidity)
{
(, , , , , , , liquidity, , , , ) = INonfungiblePositionManager(
positionManager
)
.positions(tokenId);
}
/**
* @dev Stake liquidity in position represented by tokenId NFT
*/
function stake(
uint256 amount0,
uint256 amount1,
address positionManager,
uint256 tokenId
) public returns (uint256 stakedAmount0, uint256 stakedAmount1) {
(, stakedAmount0, stakedAmount1) = INonfungiblePositionManager(
positionManager
)
.increaseLiquidity(
INonfungiblePositionManager.IncreaseLiquidityParams({
tokenId: tokenId,
amount0Desired: amount0,
amount1Desired: amount1,
amount0Min: amount0.sub(amount0.div(MINT_BURN_SLIPPAGE)),
amount1Min: amount1.sub(amount1.div(MINT_BURN_SLIPPAGE)),
deadline: block.timestamp
})
);
}
/**
* @dev Unstakes a given amount of liquidity from the Uni V3 position
* @param liquidity amount of liquidity to unstake
* @return amount0 token0 amount unstaked
* @return amount1 token1 amount unstaked
*/
function unstakePosition(
uint128 liquidity,
PositionDetails memory positionDetails
) public returns (uint256 amount0, uint256 amount1) {
INonfungiblePositionManager positionManager =
INonfungiblePositionManager(positionDetails.positionManager);
(uint256 _amount0, uint256 _amount1) =
getAmountsForLiquidity(
liquidity,
positionDetails.priceLower,
positionDetails.priceUpper,
positionDetails.pool
);
(amount0, amount1) = positionManager.decreaseLiquidity(
INonfungiblePositionManager.DecreaseLiquidityParams({
tokenId: positionDetails.tokenId,
liquidity: liquidity,
amount0Min: _amount0.sub(_amount0.div(MINT_BURN_SLIPPAGE)),
amount1Min: _amount1.sub(_amount1.div(MINT_BURN_SLIPPAGE)),
deadline: block.timestamp
})
);
}
/**
* @dev Collect token amounts from pool position
*/
function collectPosition(
uint128 amount0,
uint128 amount1,
uint256 tokenId,
address positionManager
) public returns (uint256 collected0, uint256 collected1) {
(collected0, collected1) = INonfungiblePositionManager(positionManager)
.collect(
INonfungiblePositionManager.CollectParams({
tokenId: tokenId,
recipient: address(this),
amount0Max: amount0,
amount1Max: amount1
})
);
}
/**
* @dev Creates the NFT token representing the pool position
* @dev Mint initial liquidity
*/
function createPosition(
uint256 amount0,
uint256 amount1,
address positionManager,
TokenDetails memory tokenDetails,
PositionDetails memory positionDetails
) public returns (uint256 _tokenId) {
(_tokenId, , , ) = INonfungiblePositionManager(positionManager).mint(
INonfungiblePositionManager.MintParams({
token0: tokenDetails.token0,
token1: tokenDetails.token1,
fee: positionDetails.poolFee,
tickLower: getTickFromPrice(positionDetails.priceLower),
tickUpper: getTickFromPrice(positionDetails.priceUpper),
amount0Desired: amount0,
amount1Desired: amount1,
amount0Min: amount0.sub(amount0.div(MINT_BURN_SLIPPAGE)),
amount1Min: amount1.sub(amount1.div(MINT_BURN_SLIPPAGE)),
recipient: address(this),
deadline: block.timestamp
})
);
}
/**
* @dev burn NFT representing a pool position with tokenId
* @dev uses NFT Position Manager
*/
function burn(address positionManager, uint256 tokenId) public {
INonfungiblePositionManager(positionManager).burn(tokenId);
}
/* ========================================================================================= */
/* xAssetCLR Helpers */
/* ========================================================================================= */
/**
* @notice Admin function to stake tokens
* @dev used in case there's leftover tokens in the contract
* @dev Function differs from adminStake in that
* @dev it calculates token amounts to stake so as to have
* @dev all or most of the tokens in the position, and
* @dev no tokens in buffer balance ; swaps as necessary
*/
function adminRebalance(
TokenDetails memory tokenDetails,
PositionDetails memory positionDetails
) public {
(uint256 token0Balance, uint256 token1Balance) =
getBufferTokenBalance(tokenDetails);
token0Balance = getToken0AmountInNativeDecimals(
token0Balance,
tokenDetails.token0Decimals,
tokenDetails.token0DecimalMultiplier
);
token1Balance = getToken1AmountInNativeDecimals(
token1Balance,
tokenDetails.token1Decimals,
tokenDetails.token1DecimalMultiplier
);
(uint256 stakeAmount0, uint256 stakeAmount1) =
checkIfAmountsMatchAndSwap(
token0Balance,
token1Balance,
positionDetails,
tokenDetails
);
(token0Balance, token1Balance) = getBufferTokenBalance(tokenDetails);
token0Balance = getToken0AmountInNativeDecimals(
token0Balance,
tokenDetails.token0Decimals,
tokenDetails.token0DecimalMultiplier
);
token1Balance = getToken1AmountInNativeDecimals(
token1Balance,
tokenDetails.token1Decimals,
tokenDetails.token1DecimalMultiplier
);
if (stakeAmount0 > token0Balance) {
stakeAmount0 = token0Balance;
}
if (stakeAmount1 > token1Balance) {
stakeAmount1 = token1Balance;
}
(uint256 amount0, uint256 amount1) =
calculatePoolMintedAmounts(
stakeAmount0,
stakeAmount1,
positionDetails.priceLower,
positionDetails.priceUpper,
positionDetails.pool
);
require(
amount0 != 0 || amount1 != 0,
"Rebalance amounts are 0"
);
stake(
amount0,
amount1,
positionDetails.positionManager,
positionDetails.tokenId
);
}
/**
* @dev Check if token amounts match before attempting rebalance in xAssetCLR
* @dev Uniswap contract requires deposits at a precise token ratio
* @dev If they don't match, swap the tokens so as to deposit as much as possible
* @param amount0ToMint how much token0 amount we want to deposit/withdraw
* @param amount1ToMint how much token1 amount we want to deposit/withdraw
*/
function checkIfAmountsMatchAndSwap(
uint256 amount0ToMint,
uint256 amount1ToMint,
PositionDetails memory positionDetails,
TokenDetails memory tokenDetails
) public returns (uint256 amount0, uint256 amount1) {
(uint256 amount0Minted, uint256 amount1Minted) =
calculatePoolMintedAmounts(
amount0ToMint,
amount1ToMint,
positionDetails.priceLower,
positionDetails.priceUpper,
positionDetails.pool
);
if (
amount0Minted <
amount0ToMint.sub(amount0ToMint.div(MINT_BURN_SLIPPAGE)) ||
amount1Minted <
amount1ToMint.sub(amount1ToMint.div(MINT_BURN_SLIPPAGE))
) {
// calculate liquidity ratio =
// minted liquidity / total pool liquidity
// used to calculate swap impact in pool
uint256 mintLiquidity =
getLiquidityForAmounts(
amount0ToMint,
amount1ToMint,
positionDetails.priceLower,
positionDetails.priceUpper,
positionDetails.pool
);
uint256 poolLiquidity = getPoolLiquidity(positionDetails.pool);
int128 liquidityRatio =
poolLiquidity == 0
? 0
: int128(ABDKMath64x64.divuu(mintLiquidity, poolLiquidity));
(amount0, amount1) = restoreTokenRatios(
liquidityRatio,
AmountsMinted({
amount0ToMint: amount0ToMint,
amount1ToMint: amount1ToMint,
amount0Minted: amount0Minted,
amount1Minted: amount1Minted
}),
tokenDetails,
positionDetails
);
} else {
(amount0, amount1) = (amount0ToMint, amount1ToMint);
}
}
/**
* @dev Swap tokens in xAssetCLR so as to keep a ratio which is required for
* @dev depositing/withdrawing liquidity to/from Uniswap pool
*/
function restoreTokenRatios(
int128 liquidityRatio,
AmountsMinted memory amountsMinted,
TokenDetails memory tokenDetails,
PositionDetails memory positionDetails
) private returns (uint256 amount0, uint256 amount1) {
// after normalization, returned swap amount will be in wei representation
uint256 swapAmount;
{
uint256 midPrice = getPoolPriceWithDecimals(positionDetails.pool);
// Swap amount returned is always in asset 0 terms
swapAmount = Utils.calculateSwapAmount(
Utils.AmountsMinted({
amount0ToMint: getToken0AmountInWei(
amountsMinted.amount0ToMint,
tokenDetails.token0Decimals,
tokenDetails.token0DecimalMultiplier
),
amount1ToMint: getToken1AmountInWei(
amountsMinted.amount1ToMint,
tokenDetails.token1Decimals,
tokenDetails.token1DecimalMultiplier
),
amount0Minted: getToken0AmountInWei(
amountsMinted.amount0Minted,
tokenDetails.token0Decimals,
tokenDetails.token0DecimalMultiplier
),
amount1Minted: getToken1AmountInWei(
amountsMinted.amount1Minted,
tokenDetails.token1Decimals,
tokenDetails.token1DecimalMultiplier
)
}),
liquidityRatio,
midPrice
);
if (swapAmount == 0) {
return (
amountsMinted.amount0ToMint,
amountsMinted.amount1ToMint
);
}
}
uint256 swapAmountWithSlippage =
swapAmount.add(swapAmount.div(SWAP_SLIPPAGE));
uint256 mul1 =
amountsMinted.amount0ToMint.mul(amountsMinted.amount1Minted);
uint256 mul2 =
amountsMinted.amount1ToMint.mul(amountsMinted.amount0Minted);
(uint256 balance0, uint256 balance1) =
getBufferTokenBalance(tokenDetails);
if (mul1 > mul2) {
if (balance0 < swapAmountWithSlippage) {
swapAmountWithSlippage = balance0;
}
// Swap tokens
uint256 amountOut =
swapToken0ForToken1(
swapAmountWithSlippage,
swapAmount,
positionDetails,
tokenDetails
);
amount0 = amountsMinted.amount0ToMint.sub(
getToken0AmountInNativeDecimals(
swapAmount,
tokenDetails.token0Decimals,
tokenDetails.token0DecimalMultiplier
)
);
// amountOut is already in native decimals
amount1 = amountsMinted.amount1ToMint.add(amountOut);
} else if (mul1 < mul2) {
balance1 = getAmountInAsset0Terms(
balance1,
positionDetails.pool,
positionDetails.twapPeriod,
tokenDetails.token0Decimals,
tokenDetails.token1Decimals,
tokenDetails.tokenDiffDecimalMultiplier
);
if (balance1 < swapAmountWithSlippage) {
swapAmountWithSlippage = balance1;
}
uint256 midPrice = getPoolPriceWithDecimals(positionDetails.pool);
// Swap tokens
uint256 amountIn =
swapToken1ForToken0(
swapAmountWithSlippage.mul(midPrice).div(1e12),
swapAmount.mul(midPrice).div(1e12),
positionDetails,
tokenDetails
);
amount0 = amountsMinted.amount0ToMint.add(
getToken0AmountInNativeDecimals(
swapAmount,
tokenDetails.token0Decimals,
tokenDetails.token0DecimalMultiplier
)
);
// amountIn is already in native decimals
amount1 = amountsMinted.amount1ToMint.sub(amountIn);
}
}
/**
* @dev Get token balances in xAssetCLR contract
* @dev returned balances are in wei representation
*/
function getBufferTokenBalance(TokenDetails memory tokenDetails)
public
view
returns (uint256 amount0, uint256 amount1)
{
IERC20 token0 = IERC20(tokenDetails.token0);
IERC20 token1 = IERC20(tokenDetails.token1);
return (
getBufferToken0Balance(
token0,
tokenDetails.token0Decimals,
tokenDetails.token0DecimalMultiplier
),
getBufferToken1Balance(
token1,
tokenDetails.token1Decimals,
tokenDetails.token1DecimalMultiplier
)
);
}
/**
* @dev Get token0 balance in xAssetCLR
*/
function getBufferToken0Balance(
IERC20 token0,
uint8 token0Decimals,
uint256 token0DecimalMultiplier
) public view returns (uint256 amount0) {
return
getToken0AmountInWei(
token0.balanceOf(address(this)),
token0Decimals,
token0DecimalMultiplier
);
}
/**
* @dev Get token1 balance in xAssetCLR
*/
function getBufferToken1Balance(
IERC20 token1,
uint8 token1Decimals,
uint256 token1DecimalMultiplier
) public view returns (uint256 amount1) {
return
getToken1AmountInWei(
token1.balanceOf(address(this)),
token1Decimals,
token1DecimalMultiplier
);
}
/* ========================================================================================= */
/* Miscellaneous */
/* ========================================================================================= */
/**
* @dev Returns token0 amount in token0Decimals
*/
function getToken0AmountInNativeDecimals(
uint256 amount,
uint8 token0Decimals,
uint256 token0DecimalMultiplier
) public pure returns (uint256) {
if (token0Decimals < TOKEN_DECIMAL_REPRESENTATION) {
amount = amount.div(token0DecimalMultiplier);
}
return amount;
}
/**
* @dev Returns token1 amount in token1Decimals
*/
function getToken1AmountInNativeDecimals(
uint256 amount,
uint8 token1Decimals,
uint256 token1DecimalMultiplier
) public pure returns (uint256) {
if (token1Decimals < TOKEN_DECIMAL_REPRESENTATION) {
amount = amount.div(token1DecimalMultiplier);
}
return amount;
}
/**
* @dev Returns token0 amount in TOKEN_DECIMAL_REPRESENTATION
*/
function getToken0AmountInWei(
uint256 amount,
uint8 token0Decimals,
uint256 token0DecimalMultiplier
) public pure returns (uint256) {
if (token0Decimals < TOKEN_DECIMAL_REPRESENTATION) {
amount = amount.mul(token0DecimalMultiplier);
}
return amount;
}
/**
* @dev Returns token1 amount in TOKEN_DECIMAL_REPRESENTATION
*/
function getToken1AmountInWei(
uint256 amount,
uint8 token1Decimals,
uint256 token1DecimalMultiplier
) public pure returns (uint256) {
if (token1Decimals < TOKEN_DECIMAL_REPRESENTATION) {
amount = amount.mul(token1DecimalMultiplier);
}
return amount;
}
/**
* @dev get price from tick
*/
function getSqrtRatio(int24 tick) public pure returns (uint160) {
return TickMath.getSqrtRatioAtTick(tick);
}
/**
* @dev get tick from price
*/
function getTickFromPrice(uint160 price) public pure returns (int24) {
return TickMath.getTickAtSqrtRatio(price);
}
/**
* @dev Subtract two numbers and return absolute value
*/
function subAbs(uint256 amount0, uint256 amount1)
public
pure
returns (uint256)
{
return amount0 >= amount1 ? amount0.sub(amount1) : amount1.sub(amount0);
}
}
// SPDX-License-Identifier: BUSL-1.1
pragma solidity 0.7.6;
/**
Contract which implements locking of functions via a notLocked modifier
Functions are locked per address.
*/
contract BlockLock {
// how many blocks are the functions locked for
uint256 private constant BLOCK_LOCK_COUNT = 6;
// last block for which this address is timelocked
mapping(address => uint256) public lastLockedBlock;
function lock(address _address) internal {
lastLockedBlock[_address] = block.number + BLOCK_LOCK_COUNT;
}
modifier notLocked(address lockedAddress) {
require(
lastLockedBlock[lockedAddress] <= block.number,
"Address is temporarily locked"
);
_;
}
}
//SPDX-License-Identifier: MIT
pragma solidity 0.7.6;
interface IxTokenManager {
/**
* @dev Add a manager to an xAsset fund
*/
function addManager(address manager, address fund) external;
/**
* @dev Remove a manager from an xAsset fund
*/
function removeManager(address manager, address fund) external;
/**
* @dev Check if an address is a manager for a fund
*/
function isManager(address manager, address fund)
external
view
returns (bool);
/**
* @dev Set revenue controller
*/
function setRevenueController(address controller) external;
/**
* @dev Check if address is revenue controller
*/
function isRevenueController(address caller) external view returns (bool);
}
// SPDX-License-Identifier: UNLICENSED
pragma solidity 0.7.6;
import "@openzeppelin/contracts/token/ERC20/IERC20.sol";
/**
* Minimal xAsset interface
* Only mintWithToken and burn functions
*/
interface IxAsset is IERC20 {
/*
* @dev Mint xAsset using Asset
* @notice Must run ERC20 approval first
* @param amount: Asset amount to contribute
*/
function mintWithToken(uint256 amount) external;
/*
* @dev Burn xAsset tokens
* @notice Will fail if redemption value exceeds available liquidity
* @param amount: xAsset amount to redeem
* @param redeemForEth: if true, redeem xAsset for ETH
* @param minRate: Kyber.getExpectedRate xAsset=>ETH if redeemForEth true (no-op if false)
*/
function burn(uint256 amount, bool redeemForEth, uint256 minRate) external;
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.7.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);
}
}
}
}
// SPDX-License-Identifier: MIT
pragma solidity >=0.6.0 <0.8.0;
import "../proxy/Initializable.sol";
/*
* @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 ContextUpgradeable is Initializable {
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;
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.7.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);
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.7.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 SafeMathUpgradeable {
/**
* @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.7.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: GPL-2.0-or-later
pragma solidity >=0.7.5;
pragma abicoder v2;
import '@openzeppelin/contracts/token/ERC721/IERC721Metadata.sol';
import '@openzeppelin/contracts/token/ERC721/IERC721Enumerable.sol';
import './IPoolInitializer.sol';
import './IERC721Permit.sol';
import './IPeripheryImmutableState.sol';
import '../libraries/PoolAddress.sol';
/// @title Non-fungible token for positions
/// @notice Wraps Uniswap V3 positions in a non-fungible token interface which allows for them to be transferred
/// and authorized.
interface INonfungiblePositionManager is
IPoolInitializer,
IPeripheryImmutableState,
IERC721Metadata,
IERC721Enumerable,
IERC721Permit
{
/// @notice Emitted when liquidity is increased for a position NFT
/// @dev Also emitted when a token is minted
/// @param tokenId The ID of the token for which liquidity was increased
/// @param liquidity The amount by which liquidity for the NFT position was increased
/// @param amount0 The amount of token0 that was paid for the increase in liquidity
/// @param amount1 The amount of token1 that was paid for the increase in liquidity
event IncreaseLiquidity(uint256 indexed tokenId, uint128 liquidity, uint256 amount0, uint256 amount1);
/// @notice Emitted when liquidity is decreased for a position NFT
/// @param tokenId The ID of the token for which liquidity was decreased
/// @param liquidity The amount by which liquidity for the NFT position was decreased
/// @param amount0 The amount of token0 that was accounted for the decrease in liquidity
/// @param amount1 The amount of token1 that was accounted for the decrease in liquidity
event DecreaseLiquidity(uint256 indexed tokenId, uint128 liquidity, uint256 amount0, uint256 amount1);
/// @notice Emitted when tokens are collected for a position NFT
/// @dev The amounts reported may not be exactly equivalent to the amounts transferred, due to rounding behavior
/// @param tokenId The ID of the token for which underlying tokens were collected
/// @param recipient The address of the account that received the collected tokens
/// @param amount0 The amount of token0 owed to the position that was collected
/// @param amount1 The amount of token1 owed to the position that was collected
event Collect(uint256 indexed tokenId, address recipient, uint256 amount0, uint256 amount1);
/// @notice Returns the position information associated with a given token ID.
/// @dev Throws if the token ID is not valid.
/// @param tokenId The ID of the token that represents the position
/// @return nonce The nonce for permits
/// @return operator The address that is approved for spending
/// @return token0 The address of the token0 for a specific pool
/// @return token1 The address of the token1 for a specific pool
/// @return fee The fee associated with the pool
/// @return tickLower The lower end of the tick range for the position
/// @return tickUpper The higher end of the tick range for the position
/// @return liquidity The liquidity of the position
/// @return feeGrowthInside0LastX128 The fee growth of token0 as of the last action on the individual position
/// @return feeGrowthInside1LastX128 The fee growth of token1 as of the last action on the individual position
/// @return tokensOwed0 The uncollected amount of token0 owed to the position as of the last computation
/// @return tokensOwed1 The uncollected amount of token1 owed to the position as of the last computation
function positions(uint256 tokenId)
external
view
returns (
uint96 nonce,
address operator,
address token0,
address token1,
uint24 fee,
int24 tickLower,
int24 tickUpper,
uint128 liquidity,
uint256 feeGrowthInside0LastX128,
uint256 feeGrowthInside1LastX128,
uint128 tokensOwed0,
uint128 tokensOwed1
);
struct MintParams {
address token0;
address token1;
uint24 fee;
int24 tickLower;
int24 tickUpper;
uint256 amount0Desired;
uint256 amount1Desired;
uint256 amount0Min;
uint256 amount1Min;
address recipient;
uint256 deadline;
}
/// @notice Creates a new position wrapped in a NFT
/// @dev Call this when the pool does exist and is initialized. Note that if the pool is created but not initialized
/// a method does not exist, i.e. the pool is assumed to be initialized.
/// @param params The params necessary to mint a position, encoded as `MintParams` in calldata
/// @return tokenId The ID of the token that represents the minted position
/// @return liquidity The amount of liquidity for this position
/// @return amount0 The amount of token0
/// @return amount1 The amount of token1
function mint(MintParams calldata params)
external
payable
returns (
uint256 tokenId,
uint128 liquidity,
uint256 amount0,
uint256 amount1
);
struct IncreaseLiquidityParams {
uint256 tokenId;
uint256 amount0Desired;
uint256 amount1Desired;
uint256 amount0Min;
uint256 amount1Min;
uint256 deadline;
}
/// @notice Increases the amount of liquidity in a position, with tokens paid by the `msg.sender`
/// @param params tokenId The ID of the token for which liquidity is being increased,
/// amount0Desired The desired amount of token0 to be spent,
/// amount1Desired The desired amount of token1 to be spent,
/// amount0Min The minimum amount of token0 to spend, which serves as a slippage check,
/// amount1Min The minimum amount of token1 to spend, which serves as a slippage check,
/// deadline The time by which the transaction must be included to effect the change
/// @return liquidity The new liquidity amount as a result of the increase
/// @return amount0 The amount of token0 to acheive resulting liquidity
/// @return amount1 The amount of token1 to acheive resulting liquidity
function increaseLiquidity(IncreaseLiquidityParams calldata params)
external
payable
returns (
uint128 liquidity,
uint256 amount0,
uint256 amount1
);
struct DecreaseLiquidityParams {
uint256 tokenId;
uint128 liquidity;
uint256 amount0Min;
uint256 amount1Min;
uint256 deadline;
}
/// @notice Decreases the amount of liquidity in a position and accounts it to the position
/// @param params tokenId The ID of the token for which liquidity is being decreased,
/// amount The amount by which liquidity will be decreased,
/// amount0Min The minimum amount of token0 that should be accounted for the burned liquidity,
/// amount1Min The minimum amount of token1 that should be accounted for the burned liquidity,
/// deadline The time by which the transaction must be included to effect the change
/// @return amount0 The amount of token0 accounted to the position's tokens owed
/// @return amount1 The amount of token1 accounted to the position's tokens owed
function decreaseLiquidity(DecreaseLiquidityParams calldata params)
external
payable
returns (uint256 amount0, uint256 amount1);
struct CollectParams {
uint256 tokenId;
address recipient;
uint128 amount0Max;
uint128 amount1Max;
}
/// @notice Collects up to a maximum amount of fees owed to a specific position to the recipient
/// @param params tokenId The ID of the NFT for which tokens are being collected,
/// recipient The account that should receive the tokens,
/// amount0Max The maximum amount of token0 to collect,
/// amount1Max The maximum amount of token1 to collect
/// @return amount0 The amount of fees collected in token0
/// @return amount1 The amount of fees collected in token1
function collect(CollectParams calldata params) external payable returns (uint256 amount0, uint256 amount1);
/// @notice Burns a token ID, which deletes it from the NFT contract. The token must have 0 liquidity and all tokens
/// must be collected first.
/// @param tokenId The ID of the token that is being burned
function burn(uint256 tokenId) external payable;
}
// SPDX-License-Identifier: GPL-2.0-or-later
pragma solidity >=0.7.5;
pragma abicoder v2;
import '@uniswap/v3-core/contracts/interfaces/callback/IUniswapV3SwapCallback.sol';
/// @title Router token swapping functionality
/// @notice Functions for swapping tokens via Uniswap V3
interface ISwapRouter is IUniswapV3SwapCallback {
struct ExactInputSingleParams {
address tokenIn;
address tokenOut;
uint24 fee;
address recipient;
uint256 deadline;
uint256 amountIn;
uint256 amountOutMinimum;
uint160 sqrtPriceLimitX96;
}
/// @notice Swaps `amountIn` of one token for as much as possible of another token
/// @param params The parameters necessary for the swap, encoded as `ExactInputSingleParams` in calldata
/// @return amountOut The amount of the received token
function exactInputSingle(ExactInputSingleParams calldata params) external payable returns (uint256 amountOut);
struct ExactInputParams {
bytes path;
address recipient;
uint256 deadline;
uint256 amountIn;
uint256 amountOutMinimum;
}
/// @notice Swaps `amountIn` of one token for as much as possible of another along the specified path
/// @param params The parameters necessary for the multi-hop swap, encoded as `ExactInputParams` in calldata
/// @return amountOut The amount of the received token
function exactInput(ExactInputParams calldata params) external payable returns (uint256 amountOut);
struct ExactOutputSingleParams {
address tokenIn;
address tokenOut;
uint24 fee;
address recipient;
uint256 deadline;
uint256 amountOut;
uint256 amountInMaximum;
uint160 sqrtPriceLimitX96;
}
/// @notice Swaps as little as possible of one token for `amountOut` of another token
/// @param params The parameters necessary for the swap, encoded as `ExactOutputSingleParams` in calldata
/// @return amountIn The amount of the input token
function exactOutputSingle(ExactOutputSingleParams calldata params) external payable returns (uint256 amountIn);
struct ExactOutputParams {
bytes path;
address recipient;
uint256 deadline;
uint256 amountOut;
uint256 amountInMaximum;
}
/// @notice Swaps as little as possible of one token for `amountOut` of another along the specified path (reversed)
/// @param params The parameters necessary for the multi-hop swap, encoded as `ExactOutputParams` in calldata
/// @return amountIn The amount of the input token
function exactOutput(ExactOutputParams calldata params) external payable returns (uint256 amountIn);
}
// SPDX-License-Identifier: GPL-2.0-or-later
pragma solidity >=0.7.5;
pragma abicoder v2;
/// @title Quoter Interface
/// @notice Supports quoting the calculated amounts from exact input or exact output swaps
/// @dev These functions are not marked view because they rely on calling non-view functions and reverting
/// to compute the result. They are also not gas efficient and should not be called on-chain.
interface IQuoter {
/// @notice Returns the amount out received for a given exact input swap without executing the swap
/// @param path The path of the swap, i.e. each token pair and the pool fee
/// @param amountIn The amount of the first token to swap
/// @return amountOut The amount of the last token that would be received
function quoteExactInput(bytes memory path, uint256 amountIn) external returns (uint256 amountOut);
/// @notice Returns the amount out received for a given exact input but for a swap of a single pool
/// @param tokenIn The token being swapped in
/// @param tokenOut The token being swapped out
/// @param fee The fee of the token pool to consider for the pair
/// @param amountIn The desired input amount
/// @param sqrtPriceLimitX96 The price limit of the pool that cannot be exceeded by the swap
/// @return amountOut The amount of `tokenOut` that would be received
function quoteExactInputSingle(
address tokenIn,
address tokenOut,
uint24 fee,
uint256 amountIn,
uint160 sqrtPriceLimitX96
) external returns (uint256 amountOut);
/// @notice Returns the amount in required for a given exact output swap without executing the swap
/// @param path The path of the swap, i.e. each token pair and the pool fee
/// @param amountOut The amount of the last token to receive
/// @return amountIn The amount of first token required to be paid
function quoteExactOutput(bytes memory path, uint256 amountOut) external returns (uint256 amountIn);
/// @notice Returns the amount in required to receive the given exact output amount but for a swap of a single pool
/// @param tokenIn The token being swapped in
/// @param tokenOut The token being swapped out
/// @param fee The fee of the token pool to consider for the pair
/// @param amountOut The desired output amount
/// @param sqrtPriceLimitX96 The price limit of the pool that cannot be exceeded by the swap
/// @return amountIn The amount required as the input for the swap in order to receive `amountOut`
function quoteExactOutputSingle(
address tokenIn,
address tokenOut,
uint24 fee,
uint256 amountOut,
uint160 sqrtPriceLimitX96
) external returns (uint256 amountIn);
}
// SPDX-License-Identifier: GPL-2.0-or-later
pragma solidity >=0.5.0;
import '@uniswap/v3-core/contracts/libraries/FullMath.sol';
import '@uniswap/v3-core/contracts/libraries/FixedPoint96.sol';
/// @title Liquidity amount functions
/// @notice Provides functions for computing liquidity amounts from token amounts and prices
library LiquidityAmounts {
/// @notice Downcasts uint256 to uint128
/// @param x The uint258 to be downcasted
/// @return y The passed value, downcasted to uint128
function toUint128(uint256 x) private pure returns (uint128 y) {
require((y = uint128(x)) == x);
}
/// @notice Computes the amount of liquidity received for a given amount of token0 and price range
/// @dev Calculates amount0 * (sqrt(upper) * sqrt(lower)) / (sqrt(upper) - sqrt(lower))
/// @param sqrtRatioAX96 A sqrt price representing the first tick boundary
/// @param sqrtRatioBX96 A sqrt price representing the second tick boundary
/// @param amount0 The amount0 being sent in
/// @return liquidity The amount of returned liquidity
function getLiquidityForAmount0(
uint160 sqrtRatioAX96,
uint160 sqrtRatioBX96,
uint256 amount0
) internal pure returns (uint128 liquidity) {
if (sqrtRatioAX96 > sqrtRatioBX96) (sqrtRatioAX96, sqrtRatioBX96) = (sqrtRatioBX96, sqrtRatioAX96);
uint256 intermediate = FullMath.mulDiv(sqrtRatioAX96, sqrtRatioBX96, FixedPoint96.Q96);
return toUint128(FullMath.mulDiv(amount0, intermediate, sqrtRatioBX96 - sqrtRatioAX96));
}
/// @notice Computes the amount of liquidity received for a given amount of token1 and price range
/// @dev Calculates amount1 / (sqrt(upper) - sqrt(lower)).
/// @param sqrtRatioAX96 A sqrt price representing the first tick boundary
/// @param sqrtRatioBX96 A sqrt price representing the second tick boundary
/// @param amount1 The amount1 being sent in
/// @return liquidity The amount of returned liquidity
function getLiquidityForAmount1(
uint160 sqrtRatioAX96,
uint160 sqrtRatioBX96,
uint256 amount1
) internal pure returns (uint128 liquidity) {
if (sqrtRatioAX96 > sqrtRatioBX96) (sqrtRatioAX96, sqrtRatioBX96) = (sqrtRatioBX96, sqrtRatioAX96);
return toUint128(FullMath.mulDiv(amount1, FixedPoint96.Q96, sqrtRatioBX96 - sqrtRatioAX96));
}
/// @notice Computes the maximum amount of liquidity received for a given amount of token0, token1, the current
/// pool prices and the prices at the tick boundaries
/// @param sqrtRatioX96 A sqrt price representing the current pool prices
/// @param sqrtRatioAX96 A sqrt price representing the first tick boundary
/// @param sqrtRatioBX96 A sqrt price representing the second tick boundary
/// @param amount0 The amount of token0 being sent in
/// @param amount1 The amount of token1 being sent in
/// @return liquidity The maximum amount of liquidity received
function getLiquidityForAmounts(
uint160 sqrtRatioX96,
uint160 sqrtRatioAX96,
uint160 sqrtRatioBX96,
uint256 amount0,
uint256 amount1
) internal pure returns (uint128 liquidity) {
if (sqrtRatioAX96 > sqrtRatioBX96) (sqrtRatioAX96, sqrtRatioBX96) = (sqrtRatioBX96, sqrtRatioAX96);
if (sqrtRatioX96 <= sqrtRatioAX96) {
liquidity = getLiquidityForAmount0(sqrtRatioAX96, sqrtRatioBX96, amount0);
} else if (sqrtRatioX96 < sqrtRatioBX96) {
uint128 liquidity0 = getLiquidityForAmount0(sqrtRatioX96, sqrtRatioBX96, amount0);
uint128 liquidity1 = getLiquidityForAmount1(sqrtRatioAX96, sqrtRatioX96, amount1);
liquidity = liquidity0 < liquidity1 ? liquidity0 : liquidity1;
} else {
liquidity = getLiquidityForAmount1(sqrtRatioAX96, sqrtRatioBX96, amount1);
}
}
/// @notice Computes the amount of token0 for a given amount of liquidity and a price range
/// @param sqrtRatioAX96 A sqrt price representing the first tick boundary
/// @param sqrtRatioBX96 A sqrt price representing the second tick boundary
/// @param liquidity The liquidity being valued
/// @return amount0 The amount of token0
function getAmount0ForLiquidity(
uint160 sqrtRatioAX96,
uint160 sqrtRatioBX96,
uint128 liquidity
) internal pure returns (uint256 amount0) {
if (sqrtRatioAX96 > sqrtRatioBX96) (sqrtRatioAX96, sqrtRatioBX96) = (sqrtRatioBX96, sqrtRatioAX96);
return
FullMath.mulDiv(
uint256(liquidity) << FixedPoint96.RESOLUTION,
sqrtRatioBX96 - sqrtRatioAX96,
sqrtRatioBX96
) / sqrtRatioAX96;
}
/// @notice Computes the amount of token1 for a given amount of liquidity and a price range
/// @param sqrtRatioAX96 A sqrt price representing the first tick boundary
/// @param sqrtRatioBX96 A sqrt price representing the second tick boundary
/// @param liquidity The liquidity being valued
/// @return amount1 The amount of token1
function getAmount1ForLiquidity(
uint160 sqrtRatioAX96,
uint160 sqrtRatioBX96,
uint128 liquidity
) internal pure returns (uint256 amount1) {
if (sqrtRatioAX96 > sqrtRatioBX96) (sqrtRatioAX96, sqrtRatioBX96) = (sqrtRatioBX96, sqrtRatioAX96);
return FullMath.mulDiv(liquidity, sqrtRatioBX96 - sqrtRatioAX96, FixedPoint96.Q96);
}
/// @notice Computes the token0 and token1 value for a given amount of liquidity, the current
/// pool prices and the prices at the tick boundaries
/// @param sqrtRatioX96 A sqrt price representing the current pool prices
/// @param sqrtRatioAX96 A sqrt price representing the first tick boundary
/// @param sqrtRatioBX96 A sqrt price representing the second tick boundary
/// @param liquidity The liquidity being valued
/// @return amount0 The amount of token0
/// @return amount1 The amount of token1
function getAmountsForLiquidity(
uint160 sqrtRatioX96,
uint160 sqrtRatioAX96,
uint160 sqrtRatioBX96,
uint128 liquidity
) internal pure returns (uint256 amount0, uint256 amount1) {
if (sqrtRatioAX96 > sqrtRatioBX96) (sqrtRatioAX96, sqrtRatioBX96) = (sqrtRatioBX96, sqrtRatioAX96);
if (sqrtRatioX96 <= sqrtRatioAX96) {
amount0 = getAmount0ForLiquidity(sqrtRatioAX96, sqrtRatioBX96, liquidity);
} else if (sqrtRatioX96 < sqrtRatioBX96) {
amount0 = getAmount0ForLiquidity(sqrtRatioX96, sqrtRatioBX96, liquidity);
amount1 = getAmount1ForLiquidity(sqrtRatioAX96, sqrtRatioX96, liquidity);
} else {
amount1 = getAmount1ForLiquidity(sqrtRatioAX96, sqrtRatioBX96, liquidity);
}
}
}
// 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 Math library for computing sqrt prices from ticks and vice versa
/// @notice Computes sqrt price for ticks of size 1.0001, i.e. sqrt(1.0001^tick) as fixed point Q64.96 numbers. Supports
/// prices between 2**-128 and 2**128
library TickMath {
/// @dev The minimum tick that may be passed to #getSqrtRatioAtTick computed from log base 1.0001 of 2**-128
int24 internal constant MIN_TICK = -887272;
/// @dev The maximum tick that may be passed to #getSqrtRatioAtTick computed from log base 1.0001 of 2**128
int24 internal constant MAX_TICK = -MIN_TICK;
/// @dev The minimum value that can be returned from #getSqrtRatioAtTick. Equivalent to getSqrtRatioAtTick(MIN_TICK)
uint160 internal constant MIN_SQRT_RATIO = 4295128739;
/// @dev The maximum value that can be returned from #getSqrtRatioAtTick. Equivalent to getSqrtRatioAtTick(MAX_TICK)
uint160 internal constant MAX_SQRT_RATIO = 1461446703485210103287273052203988822378723970342;
/// @notice Calculates sqrt(1.0001^tick) * 2^96
/// @dev Throws if |tick| > max tick
/// @param tick The input tick for the above formula
/// @return sqrtPriceX96 A Fixed point Q64.96 number representing the sqrt of the ratio of the two assets (token1/token0)
/// at the given tick
function getSqrtRatioAtTick(int24 tick) internal pure returns (uint160 sqrtPriceX96) {
uint256 absTick = tick < 0 ? uint256(-int256(tick)) : uint256(int256(tick));
require(absTick <= uint256(MAX_TICK), 'T');
uint256 ratio = absTick & 0x1 != 0 ? 0xfffcb933bd6fad37aa2d162d1a594001 : 0x100000000000000000000000000000000;
if (absTick & 0x2 != 0) ratio = (ratio * 0xfff97272373d413259a46990580e213a) >> 128;
if (absTick & 0x4 != 0) ratio = (ratio * 0xfff2e50f5f656932ef12357cf3c7fdcc) >> 128;
if (absTick & 0x8 != 0) ratio = (ratio * 0xffe5caca7e10e4e61c3624eaa0941cd0) >> 128;
if (absTick & 0x10 != 0) ratio = (ratio * 0xffcb9843d60f6159c9db58835c926644) >> 128;
if (absTick & 0x20 != 0) ratio = (ratio * 0xff973b41fa98c081472e6896dfb254c0) >> 128;
if (absTick & 0x40 != 0) ratio = (ratio * 0xff2ea16466c96a3843ec78b326b52861) >> 128;
if (absTick & 0x80 != 0) ratio = (ratio * 0xfe5dee046a99a2a811c461f1969c3053) >> 128;
if (absTick & 0x100 != 0) ratio = (ratio * 0xfcbe86c7900a88aedcffc83b479aa3a4) >> 128;
if (absTick & 0x200 != 0) ratio = (ratio * 0xf987a7253ac413176f2b074cf7815e54) >> 128;
if (absTick & 0x400 != 0) ratio = (ratio * 0xf3392b0822b70005940c7a398e4b70f3) >> 128;
if (absTick & 0x800 != 0) ratio = (ratio * 0xe7159475a2c29b7443b29c7fa6e889d9) >> 128;
if (absTick & 0x1000 != 0) ratio = (ratio * 0xd097f3bdfd2022b8845ad8f792aa5825) >> 128;
if (absTick & 0x2000 != 0) ratio = (ratio * 0xa9f746462d870fdf8a65dc1f90e061e5) >> 128;
if (absTick & 0x4000 != 0) ratio = (ratio * 0x70d869a156d2a1b890bb3df62baf32f7) >> 128;
if (absTick & 0x8000 != 0) ratio = (ratio * 0x31be135f97d08fd981231505542fcfa6) >> 128;
if (absTick & 0x10000 != 0) ratio = (ratio * 0x9aa508b5b7a84e1c677de54f3e99bc9) >> 128;
if (absTick & 0x20000 != 0) ratio = (ratio * 0x5d6af8dedb81196699c329225ee604) >> 128;
if (absTick & 0x40000 != 0) ratio = (ratio * 0x2216e584f5fa1ea926041bedfe98) >> 128;
if (absTick & 0x80000 != 0) ratio = (ratio * 0x48a170391f7dc42444e8fa2) >> 128;
if (tick > 0) ratio = type(uint256).max / ratio;
// this divides by 1<<32 rounding up to go from a Q128.128 to a Q128.96.
// we then downcast because we know the result always fits within 160 bits due to our tick input constraint
// we round up in the division so getTickAtSqrtRatio of the output price is always consistent
sqrtPriceX96 = uint160((ratio >> 32) + (ratio % (1 << 32) == 0 ? 0 : 1));
}
/// @notice Calculates the greatest tick value such that getRatioAtTick(tick) <= ratio
/// @dev Throws in case sqrtPriceX96 < MIN_SQRT_RATIO, as MIN_SQRT_RATIO is the lowest value getRatioAtTick may
/// ever return.
/// @param sqrtPriceX96 The sqrt ratio for which to compute the tick as a Q64.96
/// @return tick The greatest tick for which the ratio is less than or equal to the input ratio
function getTickAtSqrtRatio(uint160 sqrtPriceX96) internal pure returns (int24 tick) {
// second inequality must be < because the price can never reach the price at the max tick
require(sqrtPriceX96 >= MIN_SQRT_RATIO && sqrtPriceX96 < MAX_SQRT_RATIO, 'R');
uint256 ratio = uint256(sqrtPriceX96) << 32;
uint256 r = ratio;
uint256 msb = 0;
assembly {
let f := shl(7, gt(r, 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF))
msb := or(msb, f)
r := shr(f, r)
}
assembly {
let f := shl(6, gt(r, 0xFFFFFFFFFFFFFFFF))
msb := or(msb, f)
r := shr(f, r)
}
assembly {
let f := shl(5, gt(r, 0xFFFFFFFF))
msb := or(msb, f)
r := shr(f, r)
}
assembly {
let f := shl(4, gt(r, 0xFFFF))
msb := or(msb, f)
r := shr(f, r)
}
assembly {
let f := shl(3, gt(r, 0xFF))
msb := or(msb, f)
r := shr(f, r)
}
assembly {
let f := shl(2, gt(r, 0xF))
msb := or(msb, f)
r := shr(f, r)
}
assembly {
let f := shl(1, gt(r, 0x3))
msb := or(msb, f)
r := shr(f, r)
}
assembly {
let f := gt(r, 0x1)
msb := or(msb, f)
}
if (msb >= 128) r = ratio >> (msb - 127);
else r = ratio << (127 - msb);
int256 log_2 = (int256(msb) - 128) << 64;
assembly {
r := shr(127, mul(r, r))
let f := shr(128, r)
log_2 := or(log_2, shl(63, f))
r := shr(f, r)
}
assembly {
r := shr(127, mul(r, r))
let f := shr(128, r)
log_2 := or(log_2, shl(62, f))
r := shr(f, r)
}
assembly {
r := shr(127, mul(r, r))
let f := shr(128, r)
log_2 := or(log_2, shl(61, f))
r := shr(f, r)
}
assembly {
r := shr(127, mul(r, r))
let f := shr(128, r)
log_2 := or(log_2, shl(60, f))
r := shr(f, r)
}
assembly {
r := shr(127, mul(r, r))
let f := shr(128, r)
log_2 := or(log_2, shl(59, f))
r := shr(f, r)
}
assembly {
r := shr(127, mul(r, r))
let f := shr(128, r)
log_2 := or(log_2, shl(58, f))
r := shr(f, r)
}
assembly {
r := shr(127, mul(r, r))
let f := shr(128, r)
log_2 := or(log_2, shl(57, f))
r := shr(f, r)
}
assembly {
r := shr(127, mul(r, r))
let f := shr(128, r)
log_2 := or(log_2, shl(56, f))
r := shr(f, r)
}
assembly {
r := shr(127, mul(r, r))
let f := shr(128, r)
log_2 := or(log_2, shl(55, f))
r := shr(f, r)
}
assembly {
r := shr(127, mul(r, r))
let f := shr(128, r)
log_2 := or(log_2, shl(54, f))
r := shr(f, r)
}
assembly {
r := shr(127, mul(r, r))
let f := shr(128, r)
log_2 := or(log_2, shl(53, f))
r := shr(f, r)
}
assembly {
r := shr(127, mul(r, r))
let f := shr(128, r)
log_2 := or(log_2, shl(52, f))
r := shr(f, r)
}
assembly {
r := shr(127, mul(r, r))
let f := shr(128, r)
log_2 := or(log_2, shl(51, f))
r := shr(f, r)
}
assembly {
r := shr(127, mul(r, r))
let f := shr(128, r)
log_2 := or(log_2, shl(50, f))
}
int256 log_sqrt10001 = log_2 * 255738958999603826347141; // 128.128 number
int24 tickLow = int24((log_sqrt10001 - 3402992956809132418596140100660247210) >> 128);
int24 tickHi = int24((log_sqrt10001 + 291339464771989622907027621153398088495) >> 128);
tick = tickLow == tickHi ? tickLow : getSqrtRatioAtTick(tickHi) <= sqrtPriceX96 ? tickHi : tickLow;
}
}
// SPDX-License-Identifier: BSD-4-Clause
/*
* ABDK Math 64.64 Smart Contract Library. Copyright © 2019 by ABDK Consulting.
* Author: Mikhail Vladimirov <[email protected].com>
*/
pragma solidity 0.7.6;
/**
* Smart contract library of mathematical functions operating with signed
* 64.64-bit fixed point numbers. Signed 64.64-bit fixed point number is
* basically a simple fraction whose numerator is signed 128-bit integer and
* denominator is 2^64. As long as denominator is always the same, there is no
* need to store it, thus in Solidity signed 64.64-bit fixed point numbers are
* represented by int128 type holding only the numerator.
*/
library ABDKMath64x64 {
/*
* Minimum value signed 64.64-bit fixed point number may have.
*/
int128 private constant MIN_64x64 = -0x80000000000000000000000000000000;
/*
* 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);
}
/**
* 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 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, 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 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 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 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) internal 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 >>= uint256(xe);
else x <<= uint256(-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 <<= uint256(re);
else if (re < 0) result >>= uint256(-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) internal pure returns (uint128) {
if (x == 0) return 0;
else {
uint256 xx = x;
uint256 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
uint256 r1 = x / r;
return uint128(r < r1 ? r : r1);
}
}
}
// SPDX-License-Identifier: BUSL-1.1
pragma solidity 0.7.6;
import "@openzeppelin/contracts/math/SafeMath.sol";
import "./ABDKMath64x64.sol";
/**
* Library with utility functions for xAssetCLR
*/
library Utils {
using SafeMath for uint256;
struct AmountsMinted {
uint256 amount0ToMint;
uint256 amount1ToMint;
uint256 amount0Minted;
uint256 amount1Minted;
}
/**
Get asset 1 twap price for the period of [now - secondsAgo, now]
*/
function getTWAP(int56[] memory prices, uint32 secondsAgo)
internal
pure
returns (int128)
{
// Formula is
// 1.0001 ^ (currentPrice - pastPrice) / secondsAgo
require(secondsAgo != 0, "Cannot get twap for 0 seconds");
int256 diff = int256(prices[1]) - int256(prices[0]);
uint256 priceDiff = diff < 0 ? uint256(-diff) : uint256(diff);
int128 fraction = ABDKMath64x64.divu(priceDiff, uint256(secondsAgo));
int128 twap =
ABDKMath64x64.pow(
ABDKMath64x64.divu(10001, 10000),
uint256(ABDKMath64x64.toUInt(fraction))
);
// This is necessary because we cannot call .pow on unsigned integers
// And thus when asset0Price > asset1Price we need to reverse the value
twap = diff < 0 ? ABDKMath64x64.inv(twap) : twap;
return twap;
}
/**
* Helper function to calculate how much to swap when
* staking or withdrawing from Uni V3 Pools
* Goal of this function is to calibrate the staking tokens amounts
* When we want to stake, for example, 100 token0 and 10 token1
* But pool price demands 100 token0 and 40 token1
* We cannot directly stake 100 t0 and 10 t1, so we swap enough
* to be able to stake the value of 100 t0 and 10 t1
*/
function calculateSwapAmount(
AmountsMinted memory amountsMinted,
int128 liquidityRatio,
uint256 midPrice
) internal pure returns (uint256 swapAmount) {
// formula is more complicated than xU3LP case
// it includes the asset prices, and considers the swap impact on the pool
// base formula is this:
// n - swap amt, x - amount 0 to mint, y - amount 1 to mint,
// z - amount 0 minted, t - amount 1 minted, p0 - pool mid price
// l - liquidity ratio (current mint liquidity vs total pool liq)
// (X - n) / (Y + n * p0) = (Z + l * n) / (T - l * n * p0) ->
// n = (X * T - Y * Z) / (p0 * l * X + p0 * Z + l * Y + T)
uint256 mul1 =
amountsMinted.amount0ToMint.mul(amountsMinted.amount1Minted);
uint256 mul2 =
amountsMinted.amount1ToMint.mul(amountsMinted.amount0Minted);
uint256 sub = subAbs(mul1, mul2);
uint256 add1 =
ABDKMath64x64.mulu(liquidityRatio, amountsMinted.amount1ToMint);
uint256 add2 =
midPrice
.mul(
ABDKMath64x64.mulu(liquidityRatio, amountsMinted.amount0ToMint)
)
.div(1e12);
uint256 add3 = midPrice.mul(amountsMinted.amount0Minted).div(1e12);
uint256 add = add1.add(add2).add(add3).add(amountsMinted.amount1Minted);
// Some numbers are too big to fit in ABDK's div 128-bit representation
// So calculate the root of the equation and then raise to the 2nd power
int128 nRatio =
ABDKMath64x64.divu(
ABDKMath64x64.sqrtu(sub),
ABDKMath64x64.sqrtu(add)
);
int64 n = ABDKMath64x64.toInt(nRatio);
swapAmount = uint256(n)**2;
}
// comparator for 32-bit timestamps
// @return bool Whether a <= b
function lte(
uint32 time,
uint32 a,
uint32 b
) internal pure returns (bool) {
if (a <= time && b <= time) return a <= b;
uint256 aAdjusted = a > time ? a : a + 2**32;
uint256 bAdjusted = b > time ? b : b + 2**32;
return aAdjusted <= bAdjusted;
}
// Subtract two numbers and return absolute value
function subAbs(uint256 amount0, uint256 amount1)
internal
pure
returns (uint256)
{
return amount0 >= amount1 ? amount0.sub(amount1) : amount1.sub(amount0);
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.7.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.7.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: GPL-2.0-or-later
pragma solidity >=0.7.5;
pragma abicoder v2;
/// @title Creates and initializes V3 Pools
/// @notice Provides a method for creating and initializing a pool, if necessary, for bundling with other methods that
/// require the pool to exist.
interface IPoolInitializer {
/// @notice Creates a new pool if it does not exist, then initializes if not initialized
/// @dev This method can be bundled with others via IMulticall for the first action (e.g. mint) performed against a pool
/// @param token0 The contract address of token0 of the pool
/// @param token1 The contract address of token1 of the pool
/// @param fee The fee amount of the v3 pool for the specified token pair
/// @param sqrtPriceX96 The initial square root price of the pool as a Q64.96 value
/// @return pool Returns the pool address based on the pair of tokens and fee, will return the newly created pool address if necessary
function createAndInitializePoolIfNecessary(
address token0,
address token1,
uint24 fee,
uint160 sqrtPriceX96
) external payable returns (address pool);
}
// SPDX-License-Identifier: GPL-2.0-or-later
pragma solidity >=0.7.5;
import '@openzeppelin/contracts/token/ERC721/IERC721.sol';
/// @title ERC721 with permit
/// @notice Extension to ERC721 that includes a permit function for signature based approvals
interface IERC721Permit is IERC721 {
/// @notice The permit typehash used in the permit signature
/// @return The typehash for the permit
function PERMIT_TYPEHASH() external pure returns (bytes32);
/// @notice The domain separator used in the permit signature
/// @return The domain seperator used in encoding of permit signature
function DOMAIN_SEPARATOR() external view returns (bytes32);
/// @notice Approve of a specific token ID for spending by spender via signature
/// @param spender The account that is being approved
/// @param tokenId The ID of the token that is being approved for spending
/// @param deadline The deadline timestamp by which the call must be mined for the approve to work
/// @param v Must produce valid secp256k1 signature from the holder along with `r` and `s`
/// @param r Must produce valid secp256k1 signature from the holder along with `v` and `s`
/// @param s Must produce valid secp256k1 signature from the holder along with `r` and `v`
function permit(
address spender,
uint256 tokenId,
uint256 deadline,
uint8 v,
bytes32 r,
bytes32 s
) external payable;
}
// SPDX-License-Identifier: GPL-2.0-or-later
pragma solidity >=0.5.0;
/// @title Immutable state
/// @notice Functions that return immutable state of the router
interface IPeripheryImmutableState {
/// @return Returns the address of the Uniswap V3 factory
function factory() external view returns (address);
/// @return Returns the address of WETH9
function WETH9() external view returns (address);
}
// SPDX-License-Identifier: GPL-2.0-or-later
pragma solidity >=0.5.0;
/// @title Provides functions for deriving a pool address from the factory, tokens, and the fee
library PoolAddress {
bytes32 internal constant POOL_INIT_CODE_HASH = 0xc02f72e8ae5e68802e6d893d58ddfb0df89a2f4c9c2f04927db1186a29373660;
/// @notice The identifying key of the pool
struct PoolKey {
address token0;
address token1;
uint24 fee;
}
/// @notice Returns PoolKey: the ordered tokens with the matched fee levels
/// @param tokenA The first token of a pool, unsorted
/// @param tokenB The second token of a pool, unsorted
/// @param fee The fee level of the pool
/// @return Poolkey The pool details with ordered token0 and token1 assignments
function getPoolKey(
address tokenA,
address tokenB,
uint24 fee
) internal pure returns (PoolKey memory) {
if (tokenA > tokenB) (tokenA, tokenB) = (tokenB, tokenA);
return PoolKey({token0: tokenA, token1: tokenB, fee: fee});
}
/// @notice Deterministically computes the pool address given the factory and PoolKey
/// @param factory The Uniswap V3 factory contract address
/// @param key The PoolKey
/// @return pool The contract address of the V3 pool
function computeAddress(address factory, PoolKey memory key) internal pure returns (address pool) {
require(key.token0 < key.token1);
pool = address(
uint256(
keccak256(
abi.encodePacked(
hex'ff',
factory,
keccak256(abi.encode(key.token0, key.token1, key.fee)),
POOL_INIT_CODE_HASH
)
)
)
);
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.7.0;
import "../../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.7.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: GPL-2.0-or-later
pragma solidity >=0.5.0;
/// @title Callback for IUniswapV3PoolActions#swap
/// @notice Any contract that calls IUniswapV3PoolActions#swap must implement this interface
interface IUniswapV3SwapCallback {
/// @notice Called to `msg.sender` after executing a swap via IUniswapV3Pool#swap.
/// @dev In the implementation you must pay the pool tokens owed for the swap.
/// The caller of this method must be checked to be a UniswapV3Pool deployed by the canonical UniswapV3Factory.
/// amount0Delta and amount1Delta can both be 0 if no tokens were swapped.
/// @param amount0Delta The amount of token0 that was sent (negative) or must be received (positive) by the pool by
/// the end of the swap. If positive, the callback must send that amount of token0 to the pool.
/// @param amount1Delta The amount of token1 that was sent (negative) or must be received (positive) by the pool by
/// the end of the swap. If positive, the callback must send that amount of token1 to the pool.
/// @param data Any data passed through by the caller via the IUniswapV3PoolActions#swap call
function uniswapV3SwapCallback(
int256 amount0Delta,
int256 amount1Delta,
bytes calldata data
) external;
}
// SPDX-License-Identifier: MIT
pragma solidity >=0.4.0;
/// @title Contains 512-bit math functions
/// @notice Facilitates multiplication and division that can have overflow of an intermediate value without any loss of precision
/// @dev Handles "phantom overflow" i.e., allows multiplication and division where an intermediate value overflows 256 bits
library FullMath {
/// @notice Calculates floor(a×b÷denominator) with full precision. Throws if result overflows a uint256 or denominator == 0
/// @param a The multiplicand
/// @param b The multiplier
/// @param denominator The divisor
/// @return result The 256-bit result
/// @dev Credit to Remco Bloemen under MIT license https://xn--2-umb.com/21/muldiv
function mulDiv(
uint256 a,
uint256 b,
uint256 denominator
) internal pure returns (uint256 result) {
// 512-bit multiply [prod1 prod0] = a * b
// Compute the product mod 2**256 and mod 2**256 - 1
// then use the Chinese Remainder Theorem to reconstruct
// the 512 bit result. The result is stored in two 256
// variables such that product = prod1 * 2**256 + prod0
uint256 prod0; // Least significant 256 bits of the product
uint256 prod1; // Most significant 256 bits of the product
assembly {
let mm := mulmod(a, b, not(0))
prod0 := mul(a, b)
prod1 := sub(sub(mm, prod0), lt(mm, prod0))
}
// Handle non-overflow cases, 256 by 256 division
if (prod1 == 0) {
require(denominator > 0);
assembly {
result := div(prod0, denominator)
}
return result;
}
// Make sure the result is less than 2**256.
// Also prevents denominator == 0
require(denominator > prod1);
///////////////////////////////////////////////
// 512 by 256 division.
///////////////////////////////////////////////
// Make division exact by subtracting the remainder from [prod1 prod0]
// Compute remainder using mulmod
uint256 remainder;
assembly {
remainder := mulmod(a, b, denominator)
}
// Subtract 256 bit number from 512 bit number
assembly {
prod1 := sub(prod1, gt(remainder, prod0))
prod0 := sub(prod0, remainder)
}
// Factor powers of two out of denominator
// Compute largest power of two divisor of denominator.
// Always >= 1.
uint256 twos = -denominator & denominator;
// Divide denominator by power of two
assembly {
denominator := div(denominator, twos)
}
// Divide [prod1 prod0] by the factors of two
assembly {
prod0 := div(prod0, twos)
}
// Shift in bits from prod1 into prod0. For this we need
// to flip `twos` such that it is 2**256 / twos.
// If twos is zero, then it becomes one
assembly {
twos := add(div(sub(0, twos), twos), 1)
}
prod0 |= prod1 * twos;
// Invert denominator mod 2**256
// Now that denominator is an odd number, it has an inverse
// modulo 2**256 such that denominator * inv = 1 mod 2**256.
// Compute the inverse by starting with a seed that is correct
// correct for four bits. That is, denominator * inv = 1 mod 2**4
uint256 inv = (3 * denominator) ^ 2;
// Now use Newton-Raphson iteration to improve the precision.
// Thanks to Hensel's lifting lemma, this also works in modular
// arithmetic, doubling the correct bits in each step.
inv *= 2 - denominator * inv; // inverse mod 2**8
inv *= 2 - denominator * inv; // inverse mod 2**16
inv *= 2 - denominator * inv; // inverse mod 2**32
inv *= 2 - denominator * inv; // inverse mod 2**64
inv *= 2 - denominator * inv; // inverse mod 2**128
inv *= 2 - denominator * inv; // inverse mod 2**256
// Because the division is now exact we can divide by multiplying
// with the modular inverse of denominator. This will give us the
// correct result modulo 2**256. Since the precoditions guarantee
// that the outcome is less than 2**256, this is the final result.
// We don't need to compute the high bits of the result and prod1
// is no longer required.
result = prod0 * inv;
return result;
}
/// @notice Calculates ceil(a×b÷denominator) with full precision. Throws if result overflows a uint256 or denominator == 0
/// @param a The multiplicand
/// @param b The multiplier
/// @param denominator The divisor
/// @return result The 256-bit result
function mulDivRoundingUp(
uint256 a,
uint256 b,
uint256 denominator
) internal pure returns (uint256 result) {
result = mulDiv(a, b, denominator);
if (mulmod(a, b, denominator) > 0) {
require(result < type(uint256).max);
result++;
}
}
}
// SPDX-License-Identifier: GPL-2.0-or-later
pragma solidity >=0.4.0;
/// @title FixedPoint96
/// @notice A library for handling binary fixed point numbers, see https://en.wikipedia.org/wiki/Q_(number_format)
/// @dev Used in SqrtPriceMath.sol
library FixedPoint96 {
uint8 internal constant RESOLUTION = 96;
uint256 internal constant Q96 = 0x1000000000000000000000000;
}
// 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 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: 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 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 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 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 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,
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);
}
| * Get pool price in decimal notation with 12 decimals/ | function getPoolPriceWithDecimals(address _pool)
public
view
returns (uint256 price)
{
uint160 sqrtRatioX96 = getPoolPrice(_pool);
return
uint256(sqrtRatioX96).mul(uint256(sqrtRatioX96)).mul(1e12) >> 192;
}
| 1,686,714 | [
1,
967,
2845,
6205,
316,
6970,
12155,
598,
2593,
15105,
19,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
565,
445,
28575,
5147,
1190,
31809,
12,
2867,
389,
6011,
13,
203,
3639,
1071,
203,
3639,
1476,
203,
3639,
1135,
261,
11890,
5034,
6205,
13,
203,
565,
288,
203,
3639,
2254,
16874,
5700,
8541,
60,
10525,
273,
28575,
5147,
24899,
6011,
1769,
203,
3639,
327,
203,
5411,
2254,
5034,
12,
24492,
8541,
60,
10525,
2934,
16411,
12,
11890,
5034,
12,
24492,
8541,
60,
10525,
13,
2934,
16411,
12,
21,
73,
2138,
13,
1671,
20217,
31,
203,
565,
289,
203,
203,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
] |
pragma solidity ^0.5.0;
import "./OZStorage.sol";
import "./SecurityTokenStorage.sol";
import "../libraries/TokenLib.sol";
import "../interfaces/IDataStore.sol";
import "openzeppelin-solidity/contracts/math/SafeMath.sol";
import "../modules/PermissionManager/IPermissionManager.sol";
contract STGetter is OZStorage, SecurityTokenStorage {
using SafeMath for uint256;
/**
* @notice A security token issuer can specify that issuance has finished for the token
* (i.e. no new tokens can be minted or issued).
* @dev If a token returns FALSE for `isIssuable()` then it MUST always return FALSE in the future.
* If a token returns FALSE for `isIssuable()` then it MUST never allow additional tokens to be issued.
* @return bool `true` signifies the minting is allowed. While `false` denotes the end of minting
*/
function isIssuable() external view returns (bool) {
return issuance;
}
/**
* @notice Gets list of times that checkpoints were created
* @return List of checkpoint times
*/
function getCheckpointTimes() external view returns(uint256[] memory) {
return checkpointTimes;
}
/**
* @notice Returns the count of address that were added as (potential) investors
* @return Investor count
*/
function getInvestorCount() external view returns(uint256) {
IDataStore dataStoreInstance = IDataStore(dataStore);
return dataStoreInstance.getAddressArrayLength(INVESTORSKEY);
}
/**
* @notice returns an array of investors
* NB - this length may differ from investorCount as it contains all investors that ever held tokens
* @return list of addresses
*/
function getInvestors() public view returns(address[] memory investors) {
IDataStore dataStoreInstance = IDataStore(dataStore);
investors = dataStoreInstance.getAddressArray(INVESTORSKEY);
}
/**
* @notice returns an array of investors with non zero balance at a given checkpoint
* @param _checkpointId Checkpoint id at which investor list is to be populated
* @return list of investors
*/
function getInvestorsAt(uint256 _checkpointId) external view returns(address[] memory) {
uint256 count;
uint256 i;
IDataStore dataStoreInstance = IDataStore(dataStore);
address[] memory investors = dataStoreInstance.getAddressArray(INVESTORSKEY);
for (i = 0; i < investors.length; i++) {
if (balanceOfAt(investors[i], _checkpointId) > 0) {
count++;
} else {
investors[i] = address(0);
}
}
address[] memory holders = new address[](count);
count = 0;
for (i = 0; i < investors.length; i++) {
if (investors[i] != address(0)) {
holders[count] = investors[i];
count++;
}
}
return holders;
}
/**
* @notice returns an array of investors with non zero balance at a given checkpoint
* @param _checkpointId Checkpoint id at which investor list is to be populated
* @param _start Position of investor to start iteration from
* @param _end Position of investor to stop iteration at
* @return list of investors
*/
function getInvestorsSubsetAt(uint256 _checkpointId, uint256 _start, uint256 _end) external view returns(address[] memory) {
uint256 count;
uint256 i;
IDataStore dataStoreInstance = IDataStore(dataStore);
address[] memory investors = dataStoreInstance.getAddressArrayElements(INVESTORSKEY, _start, _end);
for (i = 0; i < investors.length; i++) {
if (balanceOfAt(investors[i], _checkpointId) > 0) {
count++;
} else {
investors[i] = address(0);
}
}
address[] memory holders = new address[](count);
count = 0;
for (i = 0; i < investors.length; i++) {
if (investors[i] != address(0)) {
holders[count] = investors[i];
count++;
}
}
return holders;
}
/**
* @notice Returns the data associated to a module
* @param _module address of the module
* @return bytes32 name
* @return address module address
* @return address module factory address
* @return bool module archived
* @return uint8 array of module types
* @return bytes32 module label
*/
function getModule(address _module) external view returns(bytes32, address, address, bool, uint8[] memory, bytes32) {
return (
modulesToData[_module].name,
modulesToData[_module].module,
modulesToData[_module].moduleFactory,
modulesToData[_module].isArchived,
modulesToData[_module].moduleTypes,
modulesToData[_module].label
);
}
/**
* @notice Returns a list of modules that match the provided name
* @param _name name of the module
* @return address[] list of modules with this name
*/
function getModulesByName(bytes32 _name) external view returns(address[] memory) {
return names[_name];
}
/**
* @notice Returns a list of modules that match the provided module type
* @param _type type of the module
* @return address[] list of modules with this type
*/
function getModulesByType(uint8 _type) external view returns(address[] memory) {
return modules[_type];
}
/**
* @notice use to return the global treasury wallet
*/
function getTreasuryWallet() external view returns(address) {
return IDataStore(dataStore).getAddress(TREASURY);
}
/**
* @notice Queries balances as of a defined checkpoint
* @param _investor Investor to query balance for
* @param _checkpointId Checkpoint ID to query as of
*/
function balanceOfAt(address _investor, uint256 _checkpointId) public view returns(uint256) {
require(_checkpointId <= currentCheckpointId);
return TokenLib.getValueAt(checkpointBalances[_investor], _checkpointId, balanceOf(_investor));
}
/**
* @notice Queries totalSupply as of a defined checkpoint
* @param _checkpointId Checkpoint ID to query
* @return uint256
*/
function totalSupplyAt(uint256 _checkpointId) external view returns(uint256) {
require(_checkpointId <= currentCheckpointId);
return checkpointTotalSupply[_checkpointId];
}
/**
* @notice generates subset of investors
* NB - can be used in batches if investor list is large. start and end both are included in array.
* @param _start Position of investor to start iteration from
* @param _end Position of investor to stop iteration at
* @return list of investors
*/
function iterateInvestors(uint256 _start, uint256 _end) external view returns(address[] memory) {
IDataStore dataStoreInstance = IDataStore(dataStore);
return dataStoreInstance.getAddressArrayElements(INVESTORSKEY, _start, _end);
}
/**
* @notice Validate permissions with PermissionManager if it exists, If no Permission return false
* @dev Note that IModule withPerm will allow ST owner all permissions anyway
* @dev this allows individual modules to override this logic if needed (to not allow ST owner all permissions)
* @param _delegate address of delegate
* @param _module address of PermissionManager module
* @param _perm the permissions
* @return success
*/
function checkPermission(address _delegate, address _module, bytes32 _perm) public view returns(bool) {
for (uint256 i = 0; i < modules[PERMISSION_KEY].length; i++) {
if (!modulesToData[modules[PERMISSION_KEY][i]].isArchived) {
if (IPermissionManager(modules[PERMISSION_KEY][i]).checkPermission(_delegate, _module, _perm)) {
return true;
}
}
}
return false;
}
/**
* @notice Determines whether `_operator` is an operator for all partitions of `_tokenHolder`
* @param _operator The operator to check
* @param _tokenHolder The token holder to check
* @return Whether the `_operator` is an operator for all partitions of `_tokenHolder`
*/
function isOperator(address _operator, address _tokenHolder) external view returns (bool) {
return (_allowed[_tokenHolder][_operator] == uint(-1));
}
/**
* @notice Determines whether `_operator` is an operator for a specified partition of `_tokenHolder`
* @param _partition The partition to check
* @param _operator The operator to check
* @param _tokenHolder The token holder to check
* @return Whether the `_operator` is an operator for a specified partition of `_tokenHolder`
*/
function isOperatorForPartition(bytes32 _partition, address _operator, address _tokenHolder) external view returns (bool) {
return partitionApprovals[_tokenHolder][_partition][_operator];
}
/**
* @notice Return all partitions
* @param _tokenHolder Whom balance need to queried
* @return List of partitions
*/
function partitionsOf(address _tokenHolder) external view returns (bytes32[] memory) {
address[] memory tms = modules[TRANSFER_KEY];
/* uint256 count; */
bytes32[] memory partitions;
bytes32[] memory tmPartitions;
// First determine the total number of non-distinct partitions
for (uint256 i = 0; i < tms.length; i++) {
tmPartitions = ITransferManager(tms[i]).getPartitions(_tokenHolder);
for (uint256 j = 0 ; j < tmPartitions.length; j++) {
partitions = _appendPartition(partitions, tmPartitions[j]);
}
}
partitions = _appendPartition(partitions, "DEFAULT");
/* bytes32[] memory partitions = new bytes32[](count + 1);
count = 0;
for (uint256 i = 0; i < tms.length; i++) {
tmPartitions = ITransferManager(tms[i]).getPartitions(_tokenHolder);
for (uint256 j = 0; j < tmPartitions.length; j++) {
partitions[count + j] = tmPartitions[j];
}
count += tmPartitions.length;
}
partitions[count] = "DEFAULT";
uint256[] memory index = new uint256[](count);
count = 0;
for (uint256 i = 0; i < partitions.length; i++) {
for (uint256 j = 0; j < partitions.length; j++) {
if (partitions[i] == partitions[j]) {
index[i] = j;
}
}
}
// Create distinct list
bytes32[] memory result */
return partitions;
}
function _appendPartition(bytes32[] memory partitions, bytes32 partition) internal pure returns (bytes32[] memory) {
bool duplicate = false;
for (uint256 i = 0; i < partitions.length; i++) {
if (partition == partitions[i]) {
duplicate = true;
break;
}
}
if (duplicate) {
bytes32[] memory result = new bytes32[](1 + partitions.length);
for (uint256 i = 0; i < partitions.length; i++) {
result[i] = partitions[i];
}
result[partitions.length] = partition;
return result;
}
return partitions;
}
/**
* @notice Returns the version of the SecurityToken
*/
function getVersion() external view returns(uint8[] memory) {
uint8[] memory version = new uint8[](3);
version[0] = securityTokenVersion.major;
version[1] = securityTokenVersion.minor;
version[2] = securityTokenVersion.patch;
return version;
}
/**
* @notice Used to return the details of a document with a known name (`bytes32`).
* @param _name Name of the document
* @return string The URI associated with the document.
* @return bytes32 The hash (of the contents) of the document.
* @return uint256 the timestamp at which the document was last modified.
*/
function getDocument(bytes32 _name) external view returns (string memory, bytes32, uint256) {
return (
_documents[_name].uri,
_documents[_name].docHash,
_documents[_name].lastModified
);
}
/**
* @notice Used to retrieve a full list of documents attached to the smart contract.
* @return bytes32 List of all documents names present in the contract.
*/
function getAllDocuments() external view returns (bytes32[] memory) {
return _docNames;
}
}
| * @notice Returns the count of address that were added as (potential) investors @return Investor count/ | function getInvestorCount() external view returns(uint256) {
IDataStore dataStoreInstance = IDataStore(dataStore);
return dataStoreInstance.getAddressArrayLength(INVESTORSKEY);
}
| 1,788,761 | [
1,
1356,
326,
1056,
434,
1758,
716,
4591,
3096,
487,
261,
26451,
13,
2198,
395,
1383,
327,
5454,
395,
280,
1056,
19,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
565,
445,
336,
3605,
395,
280,
1380,
1435,
3903,
1476,
1135,
12,
11890,
5034,
13,
288,
203,
3639,
467,
24977,
31927,
1442,
273,
467,
24977,
12,
892,
2257,
1769,
203,
3639,
327,
31927,
1442,
18,
588,
1887,
1076,
1782,
12,
706,
3412,
882,
14006,
3297,
1769,
203,
565,
289,
203,
203,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
] |
./full_match/3/0xF2dce7021C5BDafD8676b3a42868225c63e04497/sources/contracts/bridgeV1.sol | @dev Token transfer event @param from is Token sender address, which is the standard Ethereum network account address @param amount is Number of token transfers @param networkid network @param nonce is accout nonce @param blockNumber is Block number of the current event @param fromAsset is The standard erc20 address that needs to be transferred out is transferred from Ethereum network to dfinity network @param toAsset is Dfinity network target Token address @param to is The token needs to be transferred to the wallet account of dfinity network | struct BridgeAccount {
uint256 index;
bool isMember;
}
| 8,190,253 | [
1,
1345,
7412,
871,
225,
628,
353,
225,
3155,
5793,
1758,
16,
1492,
353,
326,
4529,
512,
18664,
379,
2483,
2236,
1758,
225,
3844,
353,
225,
3588,
434,
1147,
29375,
225,
2483,
350,
2483,
225,
7448,
353,
4078,
659,
7448,
225,
1203,
1854,
353,
225,
3914,
1300,
434,
326,
783,
871,
225,
628,
6672,
353,
225,
1021,
4529,
6445,
71,
3462,
1758,
716,
4260,
358,
506,
906,
4193,
596,
353,
906,
4193,
628,
512,
18664,
379,
2483,
358,
302,
7850,
2483,
225,
358,
6672,
353,
463,
7850,
2483,
1018,
3155,
1758,
225,
358,
353,
1021,
1147,
4260,
358,
506,
906,
4193,
358,
326,
9230,
2236,
434,
302,
7850,
2483,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
565,
1958,
24219,
3032,
288,
203,
3639,
2254,
5034,
770,
31,
203,
3639,
1426,
353,
4419,
31,
203,
565,
289,
203,
203,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
] |
./partial_match/1/0x8882Af7f52E621407052894fa75438eA7745E5Aa/sources/BlondieAEXCElite.sol | * @dev These functions deal with verification of Merkle Tree proofs. The proofs can be generated using the JavaScript library Note: the hashing algorithm should be keccak256 and pair sorting should be enabled. See `test/utils/cryptography/MerkleProof.test.js` for some examples. WARNING: You should avoid using leaf values that are 64 bytes long prior to hashing, or use a hash function other than keccak256 for hashing leaves. This is because the concatenation of a sorted pair of internal nodes in the merkle tree could be reinterpreted as a leaf value./ | library MerkleProof {
function verify(
bytes32[] memory proof,
bytes32 root,
bytes32 leaf
) internal pure returns (bool) {
return processProof(proof, leaf) == root;
}
function verifyCalldata(
bytes32[] calldata proof,
bytes32 root,
bytes32 leaf
) internal pure returns (bool) {
return processProofCalldata(proof, leaf) == root;
}
function processProof(bytes32[] memory proof, bytes32 leaf) internal pure returns (bytes32) {
bytes32 computedHash = leaf;
for (uint256 i = 0; i < proof.length; i++) {
computedHash = _hashPair(computedHash, proof[i]);
}
return computedHash;
}
function processProof(bytes32[] memory proof, bytes32 leaf) internal pure returns (bytes32) {
bytes32 computedHash = leaf;
for (uint256 i = 0; i < proof.length; i++) {
computedHash = _hashPair(computedHash, proof[i]);
}
return computedHash;
}
function processProofCalldata(bytes32[] calldata proof, bytes32 leaf) internal pure returns (bytes32) {
bytes32 computedHash = leaf;
for (uint256 i = 0; i < proof.length; i++) {
computedHash = _hashPair(computedHash, proof[i]);
}
return computedHash;
}
function processProofCalldata(bytes32[] calldata proof, bytes32 leaf) internal pure returns (bytes32) {
bytes32 computedHash = leaf;
for (uint256 i = 0; i < proof.length; i++) {
computedHash = _hashPair(computedHash, proof[i]);
}
return computedHash;
}
function multiProofVerify(
bytes32[] memory proof,
bool[] memory proofFlags,
bytes32 root,
bytes32[] memory leaves
) internal pure returns (bool) {
return processMultiProof(proof, proofFlags, leaves) == root;
}
function multiProofVerifyCalldata(
bytes32[] calldata proof,
bool[] calldata proofFlags,
bytes32 root,
bytes32[] memory leaves
) internal pure returns (bool) {
return processMultiProofCalldata(proof, proofFlags, leaves) == root;
}
function processMultiProof(
bytes32[] memory proof,
bool[] memory proofFlags,
bytes32[] memory leaves
) internal pure returns (bytes32 merkleRoot) {
uint256 leavesLen = leaves.length;
uint256 totalHashes = proofFlags.length;
require(leavesLen + proof.length - 1 == totalHashes, "MerkleProof: invalid multiproof");
bytes32[] memory hashes = new bytes32[](totalHashes);
uint256 leafPos = 0;
uint256 hashPos = 0;
uint256 proofPos = 0;
for (uint256 i = 0; i < totalHashes; i++) {
bytes32 a = leafPos < leavesLen ? leaves[leafPos++] : hashes[hashPos++];
bytes32 b = proofFlags[i] ? leafPos < leavesLen ? leaves[leafPos++] : hashes[hashPos++] : proof[proofPos++];
hashes[i] = _hashPair(a, b);
}
if (totalHashes > 0) {
return hashes[totalHashes - 1];
return leaves[0];
return proof[0];
}
}
function processMultiProof(
bytes32[] memory proof,
bool[] memory proofFlags,
bytes32[] memory leaves
) internal pure returns (bytes32 merkleRoot) {
uint256 leavesLen = leaves.length;
uint256 totalHashes = proofFlags.length;
require(leavesLen + proof.length - 1 == totalHashes, "MerkleProof: invalid multiproof");
bytes32[] memory hashes = new bytes32[](totalHashes);
uint256 leafPos = 0;
uint256 hashPos = 0;
uint256 proofPos = 0;
for (uint256 i = 0; i < totalHashes; i++) {
bytes32 a = leafPos < leavesLen ? leaves[leafPos++] : hashes[hashPos++];
bytes32 b = proofFlags[i] ? leafPos < leavesLen ? leaves[leafPos++] : hashes[hashPos++] : proof[proofPos++];
hashes[i] = _hashPair(a, b);
}
if (totalHashes > 0) {
return hashes[totalHashes - 1];
return leaves[0];
return proof[0];
}
}
function processMultiProof(
bytes32[] memory proof,
bool[] memory proofFlags,
bytes32[] memory leaves
) internal pure returns (bytes32 merkleRoot) {
uint256 leavesLen = leaves.length;
uint256 totalHashes = proofFlags.length;
require(leavesLen + proof.length - 1 == totalHashes, "MerkleProof: invalid multiproof");
bytes32[] memory hashes = new bytes32[](totalHashes);
uint256 leafPos = 0;
uint256 hashPos = 0;
uint256 proofPos = 0;
for (uint256 i = 0; i < totalHashes; i++) {
bytes32 a = leafPos < leavesLen ? leaves[leafPos++] : hashes[hashPos++];
bytes32 b = proofFlags[i] ? leafPos < leavesLen ? leaves[leafPos++] : hashes[hashPos++] : proof[proofPos++];
hashes[i] = _hashPair(a, b);
}
if (totalHashes > 0) {
return hashes[totalHashes - 1];
return leaves[0];
return proof[0];
}
}
} else if (leavesLen > 0) {
} else {
function processMultiProofCalldata(
bytes32[] calldata proof,
bool[] calldata proofFlags,
bytes32[] memory leaves
) internal pure returns (bytes32 merkleRoot) {
uint256 leavesLen = leaves.length;
uint256 totalHashes = proofFlags.length;
require(leavesLen + proof.length - 1 == totalHashes, "MerkleProof: invalid multiproof");
bytes32[] memory hashes = new bytes32[](totalHashes);
uint256 leafPos = 0;
uint256 hashPos = 0;
uint256 proofPos = 0;
for (uint256 i = 0; i < totalHashes; i++) {
bytes32 a = leafPos < leavesLen ? leaves[leafPos++] : hashes[hashPos++];
bytes32 b = proofFlags[i] ? leafPos < leavesLen ? leaves[leafPos++] : hashes[hashPos++] : proof[proofPos++];
hashes[i] = _hashPair(a, b);
}
if (totalHashes > 0) {
return hashes[totalHashes - 1];
return leaves[0];
return proof[0];
}
}
function processMultiProofCalldata(
bytes32[] calldata proof,
bool[] calldata proofFlags,
bytes32[] memory leaves
) internal pure returns (bytes32 merkleRoot) {
uint256 leavesLen = leaves.length;
uint256 totalHashes = proofFlags.length;
require(leavesLen + proof.length - 1 == totalHashes, "MerkleProof: invalid multiproof");
bytes32[] memory hashes = new bytes32[](totalHashes);
uint256 leafPos = 0;
uint256 hashPos = 0;
uint256 proofPos = 0;
for (uint256 i = 0; i < totalHashes; i++) {
bytes32 a = leafPos < leavesLen ? leaves[leafPos++] : hashes[hashPos++];
bytes32 b = proofFlags[i] ? leafPos < leavesLen ? leaves[leafPos++] : hashes[hashPos++] : proof[proofPos++];
hashes[i] = _hashPair(a, b);
}
if (totalHashes > 0) {
return hashes[totalHashes - 1];
return leaves[0];
return proof[0];
}
}
function processMultiProofCalldata(
bytes32[] calldata proof,
bool[] calldata proofFlags,
bytes32[] memory leaves
) internal pure returns (bytes32 merkleRoot) {
uint256 leavesLen = leaves.length;
uint256 totalHashes = proofFlags.length;
require(leavesLen + proof.length - 1 == totalHashes, "MerkleProof: invalid multiproof");
bytes32[] memory hashes = new bytes32[](totalHashes);
uint256 leafPos = 0;
uint256 hashPos = 0;
uint256 proofPos = 0;
for (uint256 i = 0; i < totalHashes; i++) {
bytes32 a = leafPos < leavesLen ? leaves[leafPos++] : hashes[hashPos++];
bytes32 b = proofFlags[i] ? leafPos < leavesLen ? leaves[leafPos++] : hashes[hashPos++] : proof[proofPos++];
hashes[i] = _hashPair(a, b);
}
if (totalHashes > 0) {
return hashes[totalHashes - 1];
return leaves[0];
return proof[0];
}
}
} else if (leavesLen > 0) {
} else {
function _hashPair(bytes32 a, bytes32 b) private pure returns (bytes32) {
return a < b ? _efficientHash(a, b) : _efficientHash(b, a);
}
function _efficientHash(bytes32 a, bytes32 b) private pure returns (bytes32 value) {
assembly {
mstore(0x00, a)
mstore(0x20, b)
value := keccak256(0x00, 0x40)
}
}
function _efficientHash(bytes32 a, bytes32 b) private pure returns (bytes32 value) {
assembly {
mstore(0x00, a)
mstore(0x20, b)
value := keccak256(0x00, 0x40)
}
}
}
| 4,430,436 | [
1,
29690,
4186,
10490,
598,
11805,
434,
31827,
4902,
14601,
87,
18,
1021,
14601,
87,
848,
506,
4374,
1450,
326,
11905,
5313,
3609,
30,
326,
24641,
4886,
1410,
506,
417,
24410,
581,
5034,
471,
3082,
9602,
1410,
506,
3696,
18,
2164,
1375,
3813,
19,
5471,
19,
22784,
15669,
19,
8478,
15609,
20439,
18,
3813,
18,
2924,
68,
364,
2690,
10991,
18,
9744,
30,
4554,
1410,
4543,
1450,
7839,
924,
716,
854,
5178,
1731,
1525,
6432,
358,
24641,
16,
578,
999,
279,
1651,
445,
1308,
2353,
417,
24410,
581,
5034,
364,
24641,
15559,
18,
1220,
353,
2724,
326,
26833,
434,
279,
3115,
3082,
434,
2713,
2199,
316,
326,
30235,
2151,
3377,
506,
283,
24713,
329,
487,
279,
7839,
460,
18,
19,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
12083,
31827,
20439,
288,
203,
565,
445,
3929,
12,
203,
3639,
1731,
1578,
8526,
3778,
14601,
16,
203,
3639,
1731,
1578,
1365,
16,
203,
3639,
1731,
1578,
7839,
203,
203,
203,
203,
565,
262,
2713,
16618,
1135,
261,
6430,
13,
288,
203,
3639,
327,
1207,
20439,
12,
24207,
16,
7839,
13,
422,
1365,
31,
203,
565,
289,
203,
203,
565,
445,
3929,
1477,
892,
12,
203,
3639,
1731,
1578,
8526,
745,
892,
14601,
16,
203,
3639,
1731,
1578,
1365,
16,
203,
3639,
1731,
1578,
7839,
203,
565,
262,
2713,
16618,
1135,
261,
6430,
13,
288,
203,
3639,
327,
1207,
20439,
1477,
892,
12,
24207,
16,
7839,
13,
422,
1365,
31,
203,
565,
289,
203,
203,
565,
445,
1207,
20439,
12,
3890,
1578,
8526,
3778,
14601,
16,
1731,
1578,
7839,
13,
2713,
16618,
1135,
261,
3890,
1578,
13,
288,
203,
3639,
1731,
1578,
8470,
2310,
273,
7839,
31,
203,
3639,
364,
261,
11890,
5034,
277,
273,
374,
31,
277,
411,
14601,
18,
2469,
31,
277,
27245,
288,
203,
5411,
8470,
2310,
273,
389,
2816,
4154,
12,
20307,
2310,
16,
14601,
63,
77,
19226,
203,
3639,
289,
203,
3639,
327,
8470,
2310,
31,
203,
565,
289,
203,
203,
565,
445,
1207,
20439,
12,
3890,
1578,
8526,
3778,
14601,
16,
1731,
1578,
7839,
13,
2713,
16618,
1135,
261,
3890,
1578,
13,
288,
203,
3639,
1731,
1578,
8470,
2310,
273,
7839,
31,
203,
3639,
364,
261,
11890,
5034,
277,
273,
374,
31,
277,
411,
14601,
18,
2469,
31,
277,
27245,
288,
203,
5411,
8470,
2310,
273,
389,
2816,
2
] |
./full_match/1284/0xb89279DEd0AD7cD573D164b03424E1E2BbE1e2Be/sources/contracts/tgev5.sol | @notice jBoost ID -> Price | mapping(uint8=> uint256) public jBoost;
| 16,368,351 | [
1,
78,
26653,
1599,
317,
20137,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
565,
2874,
12,
11890,
28,
9207,
2254,
5034,
13,
1071,
525,
26653,
31,
203,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
] |
// SPDX-License-Identifier: GPL
pragma solidity ^0.8.0;
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);
}
/**
* @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`.
*
* 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;
/**
* @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 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 the account approved for `tokenId` token.
*
* Requirements:
*
* - `tokenId` must exist.
*/
function getApproved(uint256 tokenId) external view returns (address operator);
/**
* @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);
}
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);
}
}
library Address {
/**
* @dev Returns true if `account` is a contract.
*
* This test is non-exhaustive, and there may be false-negatives: during the
* execution of a contract's constructor, its address will be reported as
* not containing a contract.
*
* > It is unsafe to assume that an address for which this function returns
* false is an externally-owned account (EOA) and not a contract.
*/
function isContract(address account) internal view returns (bool) {
// This method relies in 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;
}
}
/**
* @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);
}
interface ICallistoNFT is IERC721, IERC721Metadata {
event NewBid (uint256 indexed tokenID, uint256 indexed bidAmount, bytes bidData);
event TokenTrade (uint256 indexed tokenID, address indexed new_owner, address indexed previous_owner, uint256 priceInWEI);
//event Transfer (address indexed from, address indexed to, uint256 indexed tokenId); // The event is now defined in IERC721
event TransferData (bytes data);
struct Properties {
// In this example properties of the given NFT are stored
// in a dynamically sized array of strings
// properties can be re-defined for any specific info
// that a particular NFT is intended to store.
/* Properties could look like this:
bytes property1;
bytes property2;
address property3;
*/
string[] properties;
}
function name() external view returns (string memory);
function symbol() external view returns (string memory);
function standard() external view returns (string memory);
function balanceOf(address _who) external view returns (uint256);
function ownerOf(uint256 _tokenId) external view returns (address);
function transfer(address _to, uint256 _tokenId, bytes calldata _data) external returns (bool);
function silentTransfer(address _to, uint256 _tokenId) external returns (bool);
function priceOf(uint256 _tokenId) external view returns (uint256);
function bidOf(uint256 _tokenId) external view returns (uint256 price, address payable bidder, uint256 timestamp);
function getTokenProperties(uint256 _tokenId) external view returns (Properties memory);
function getTokenProperty(uint256 _tokenId, uint256 _propertyId) external view returns (string memory);
function setBid(uint256 _tokenId, bytes calldata _data) payable external; // bid amount is defined by msg.value
function setPrice(uint256 _tokenId, uint256 _amountInWEI) external;
function withdrawBid(uint256 _tokenId) external returns (bool);
function getUserContent(uint256 _tokenId) external view returns (string memory _content, bool _all);
function setUserContent(uint256 _tokenId, string calldata _content) external returns (bool);
}
abstract contract NFTReceiver {
function onERC721Received(address _operator, address _from, uint256 _tokenId, bytes calldata _data) external virtual returns(bytes4);
}
contract CallistoNFT is ICallistoNFT {
using Address for address;
using Strings for uint256;
/****** ERC721 variables ******************************/
// 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;
/****** CallistoNFT variables *************************/
mapping (uint256 => Properties) private _tokenProperties;
mapping (uint32 => Fee) public feeLevels; // level # => (fee receiver, fee percentage)
uint256 public bidLock = 1 days; // Time required for a bid to become withdrawable.
struct Bid {
address payable bidder;
uint256 amountInWEI;
uint256 timestamp;
}
struct Fee {
address payable feeReceiver;
uint256 feePercentage; // Will be divided by 100000 during calculations
// feePercentage of 100 means 0.1% fee
// feePercentage of 2500 means 2.5% fee
}
mapping (uint256 => uint256) private _asks; // tokenID => price of this token (in WEI)
mapping (uint256 => Bid) private _bids; // tokenID => price of this token (in WEI)
mapping (uint256 => uint32) private _tokenFeeLevels; // tokenID => level ID / 0 by default
// 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;
/**
* @dev Initializes the contract by setting a `name` and a `symbol` to the token collection.
*/
constructor(string memory name_, string memory symbol_, uint256 _defaultFee) {
_name = name_;
_symbol = symbol_;
feeLevels[0].feeReceiver = payable(msg.sender);
feeLevels[0].feePercentage = _defaultFee;
}
// Reward is always paid based on BID
modifier checkTrade(uint256 _tokenId)
{
_;
(uint256 _bid, address payable _bidder,) = bidOf(_tokenId);
if(priceOf(_tokenId) > 0 && priceOf(_tokenId) <= _bid)
{
uint256 _reward = _bid - _claimFee(_bid, _tokenId);
emit TokenTrade(_tokenId, _bidder, ownerOf(_tokenId), _reward);
payable(ownerOf(_tokenId)).transfer(_reward);
bytes memory _empty = hex"00000000";
delete _bids[_tokenId];
delete _asks[_tokenId];
_safeTransfer(ownerOf(_tokenId), _bidder, _tokenId, _empty);
}
}
function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) {
return
interfaceId == type(IERC721).interfaceId ||
interfaceId == type(IERC721Metadata).interfaceId;
}
/**
* @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 overridden 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 = CallistoNFT.ownerOf(tokenId);
require(to != owner, "ERC721: approval to current owner");
require(
msg.sender == owner || isApprovedForAll(owner, msg.sender),
"ERC721: approve caller is not owner nor approved for all"
);
_approve(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(CallistoNFT.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 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(msg.sender, 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(msg.sender, tokenId), "ERC721: transfer caller is not owner nor approved");
bytes memory _empty = hex"00000000";
_safeTransfer(from, to, tokenId, _empty);
}
/**
* @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(msg.sender, 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 {
bytes memory _empty = hex"00000000";
_transfer(from, to, tokenId, _empty);
require(_checkOnERC721Received(from, to, tokenId, _data), "NFT: transfer to non ERC721Receiver implementer");
}
/**
* @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 = CallistoNFT.ownerOf(tokenId);
return (spender == owner || isApprovedForAll(owner, spender) || getApproved(tokenId) == spender);
}
/**
* @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 NFTReceiver(to).onERC721Received(msg.sender, from, tokenId, _data) returns (bytes4 retval) {
return retval == NFTReceiver.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;
}
}
function standard() public view virtual override returns (string memory)
{
return "CallistoNFT";
}
function priceOf(uint256 _tokenId) public view virtual override returns (uint256)
{
address owner = _owners[_tokenId];
require(owner != address(0), "NFT: owner query for nonexistent token");
return _asks[_tokenId];
}
function bidOf(uint256 _tokenId) public view virtual override returns (uint256 price, address payable bidder, uint256 timestamp)
{
address owner = _owners[_tokenId];
require(owner != address(0), "NFT: owner query for nonexistent token");
return (_bids[_tokenId].amountInWEI, _bids[_tokenId].bidder, _bids[_tokenId].timestamp);
}
function getTokenProperties(uint256 _tokenId) public view virtual override returns (Properties memory)
{
return _tokenProperties[_tokenId];
}
function getTokenProperty(uint256 _tokenId, uint256 _propertyId) public view virtual override returns (string memory)
{
return _tokenProperties[_tokenId].properties[_propertyId];
}
function getUserContent(uint256 _tokenId) public view virtual override returns (string memory _content, bool _all)
{
return (_tokenProperties[_tokenId].properties[0], true);
}
function setUserContent(uint256 _tokenId, string calldata _content) public virtual override returns (bool success)
{
require(msg.sender == ownerOf(_tokenId), "NFT: only owner can change NFT content");
_tokenProperties[_tokenId].properties[0] = _content;
return true;
}
function balanceOf(address owner) public view virtual override returns (uint256) {
require(owner != address(0), "NFT: balance query for the zero address");
return _balances[owner];
}
function ownerOf(uint256 tokenId) public view virtual override returns (address) {
address owner = _owners[tokenId];
require(owner != address(0), "NFT: owner query for nonexistent token");
return owner;
}
function setPrice(uint256 _tokenId, uint256 _amountInWEI) checkTrade(_tokenId) public virtual override {
require(ownerOf(_tokenId) == msg.sender, "Setting asks is only allowed for owned NFTs!");
_asks[_tokenId] = _amountInWEI;
}
function setBid(uint256 _tokenId, bytes calldata _data) payable checkTrade(_tokenId) public virtual override
{
(uint256 _previousBid, address payable _previousBidder, ) = bidOf(_tokenId);
require(msg.value > _previousBid, "New bid must exceed the existing one");
uint256 _bid;
// Return previous bid if the current one exceeds it.
if(_previousBid != 0)
{
_previousBidder.transfer(_previousBid);
}
// Refund overpaid amount.
if (priceOf(_tokenId) < msg.value)
{
_bid = priceOf(_tokenId);
}
else
{
_bid = msg.value;
}
_bids[_tokenId].amountInWEI = _bid;
_bids[_tokenId].bidder = payable(msg.sender);
_bids[_tokenId].timestamp = block.timestamp;
emit NewBid(_tokenId, _bid, _data);
// Send back overpaid amount.
// WARHNING: Creates possibility for reentrancy.
if (priceOf(_tokenId) < msg.value)
{
payable(msg.sender).transfer(msg.value - priceOf(_tokenId));
}
}
function withdrawBid(uint256 _tokenId) public virtual override returns (bool)
{
(uint256 _bid, address payable _bidder, uint256 _timestamp) = bidOf(_tokenId);
require(msg.sender == _bidder, "Can not withdraw someone elses bid");
require(block.timestamp > _timestamp + bidLock, "Bid is time-locked");
_bidder.transfer(_bid);
delete _bids[_tokenId];
return true;
}
function name() public view virtual override returns (string memory) {
return _name;
}
function symbol() public view virtual override returns (string memory) {
return _symbol;
}
function transfer(address _to, uint256 _tokenId, bytes calldata _data) public override returns (bool)
{
_safeTransfer(msg.sender, _to, _tokenId, _data);
emit TransferData(_data);
return true;
}
function silentTransfer(address _to, uint256 _tokenId) public override returns (bool)
{
require(CallistoNFT.ownerOf(_tokenId) == msg.sender, "NFT: transfer of token that is not own");
require(_to != address(0), "NFT: transfer to the zero address");
_asks[_tokenId] = 0; // Zero out price on transfer
// When a user transfers the NFT to another user
// it does not automatically mean that the new owner
// would like to sell this NFT at a price
// specified by the previous owner.
// However bids persist regardless of token transfers
// because we assume that the bidder still wants to buy the NFT
// no matter from whom.
_beforeTokenTransfer(msg.sender, _to, _tokenId);
_balances[msg.sender] -= 1;
_balances[_to] += 1;
_owners[_tokenId] = _to;
emit Transfer(msg.sender, _to, _tokenId);
return true;
}
function _exists(uint256 tokenId) internal view virtual returns (bool) {
return _owners[tokenId] != address(0);
}
function _claimFee(uint256 _amountFrom, uint256 _tokenId) internal returns (uint256)
{
uint32 _level = _tokenFeeLevels[_tokenId];
address _feeReceiver = feeLevels[_level].feeReceiver;
uint256 _feePercentage = feeLevels[_level].feePercentage;
uint256 _feeAmount = _amountFrom * _feePercentage / 100000;
payable(_feeReceiver).transfer(_feeAmount);
return _feeAmount;
}
function _safeMint(
address to,
uint256 tokenId
) internal virtual {
_mint(to, tokenId);
}
function configureNFT(uint256 tokenId) internal
{
if(_tokenProperties[tokenId].properties.length == 0)
{
_tokenProperties[tokenId].properties.push("");
}
}
function _mint(address to, uint256 tokenId) internal virtual {
require(to != address(0), "NFT: mint to the zero address");
require(!_exists(tokenId), "NFT: token already minted");
configureNFT(tokenId);
_beforeTokenTransfer(address(0), to, tokenId);
_balances[to] += 1;
_owners[tokenId] = to;
emit Transfer(address(0), to, tokenId);
}
function _burn(uint256 tokenId) internal virtual {
address owner = CallistoNFT.ownerOf(tokenId);
_beforeTokenTransfer(owner, address(0), tokenId);
_balances[owner] -= 1;
delete _owners[tokenId];
emit Transfer(owner, address(0), tokenId);
}
function _transfer(
address from,
address to,
uint256 tokenId,
bytes memory data
) internal virtual {
require(CallistoNFT.ownerOf(tokenId) == from, "NFT: transfer of token that is not own");
require(to != address(0), "NFT: transfer to the zero address");
_asks[tokenId] = 0; // Zero out price on transfer
// When a user transfers the NFT to another user
// it does not automatically mean that the new owner
// would like to sell this NFT at a price
// specified by the previous owner.
// However bids persist regardless of token transfers
// because we assume that the bidder still wants to buy the NFT
// no matter from whom.
// Clear approvals from the previous owner
_approve(address(0), tokenId);
_beforeTokenTransfer(from, to, tokenId);
_balances[from] -= 1;
_balances[to] += 1;
_owners[tokenId] = to;
/* if(to.isContract())
{
NFTReceiver(to).onERC721Received(msg.sender, from, tokenId, data);
} */
emit Transfer(from, to, tokenId);
}
function _beforeTokenTransfer(
address from,
address to,
uint256 tokenId
) internal virtual {}
}
| Will be divided by 100000 during calculations
| uint256 feePercentage; | 12,954,284 | [
1,
13670,
506,
26057,
635,
25259,
4982,
20882,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
3639,
2254,
5034,
14036,
16397,
31,
225,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
] |
pragma solidity 0.4.24;
/**
* @title ERC20Basic
* @dev Simpler version of ERC20 interface
* 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 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;
}
}
/**
* @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 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.
* @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 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;
}
}
/**
* @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 Standard ERC20 token
*
* @dev Implementation of the basic standard token.
* https://github.com/ethereum/EIPs/issues/20
* 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,
uint256 _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,
uint256 _subtractedValue
)
public
returns (bool)
{
uint256 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 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;
emit Pause();
}
/**
* @dev called by the owner to unpause, returns to normal state
*/
function unpause() onlyOwner whenPaused public {
paused = false;
emit Unpause();
}
}
/**
* @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);
}
}
/**
* @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);
}
}
contract RepublicToken is PausableToken, BurnableToken {
string public constant name = "Republic Token";
string public constant symbol = "REN";
uint8 public constant decimals = 18;
uint256 public constant INITIAL_SUPPLY = 1000000000 * 10**uint256(decimals);
/// @notice The RepublicToken Constructor.
constructor() public {
totalSupply_ = INITIAL_SUPPLY;
balances[msg.sender] = INITIAL_SUPPLY;
}
function transferTokens(address beneficiary, uint256 amount) public onlyOwner returns (bool) {
/* solium-disable error-reason */
require(amount > 0);
balances[owner] = balances[owner].sub(amount);
balances[beneficiary] = balances[beneficiary].add(amount);
emit Transfer(owner, beneficiary, amount);
return true;
}
}
/**
* @notice LinkedList is a library for a circular double linked list.
*/
library LinkedList {
/*
* @notice A permanent NULL node (0x0) in the circular double linked list.
* NULL.next is the head, and NULL.previous is the tail.
*/
address public constant NULL = 0x0;
/**
* @notice A node points to the node before it, and the node after it. If
* node.previous = NULL, then the node is the head of the list. If
* node.next = NULL, then the node is the tail of the list.
*/
struct Node {
bool inList;
address previous;
address next;
}
/**
* @notice LinkedList uses a mapping from address to nodes. Each address
* uniquely identifies a node, and in this way they are used like pointers.
*/
struct List {
mapping (address => Node) list;
}
/**
* @notice Insert a new node before an existing node.
*
* @param self The list being used.
* @param target The existing node in the list.
* @param newNode The next node to insert before the target.
*/
function insertBefore(List storage self, address target, address newNode) internal {
require(!isInList(self, newNode), "already in list");
require(isInList(self, target) || target == NULL, "not in list");
// It is expected that this value is sometimes NULL.
address prev = self.list[target].previous;
self.list[newNode].next = target;
self.list[newNode].previous = prev;
self.list[target].previous = newNode;
self.list[prev].next = newNode;
self.list[newNode].inList = true;
}
/**
* @notice Insert a new node after an existing node.
*
* @param self The list being used.
* @param target The existing node in the list.
* @param newNode The next node to insert after the target.
*/
function insertAfter(List storage self, address target, address newNode) internal {
require(!isInList(self, newNode), "already in list");
require(isInList(self, target) || target == NULL, "not in list");
// It is expected that this value is sometimes NULL.
address n = self.list[target].next;
self.list[newNode].previous = target;
self.list[newNode].next = n;
self.list[target].next = newNode;
self.list[n].previous = newNode;
self.list[newNode].inList = true;
}
/**
* @notice Remove a node from the list, and fix the previous and next
* pointers that are pointing to the removed node. Removing anode that is not
* in the list will do nothing.
*
* @param self The list being using.
* @param node The node in the list to be removed.
*/
function remove(List storage self, address node) internal {
require(isInList(self, node), "not in list");
if (node == NULL) {
return;
}
address p = self.list[node].previous;
address n = self.list[node].next;
self.list[p].next = n;
self.list[n].previous = p;
// Deleting the node should set this value to false, but we set it here for
// explicitness.
self.list[node].inList = false;
delete self.list[node];
}
/**
* @notice Insert a node at the beginning of the list.
*
* @param self The list being used.
* @param node The node to insert at the beginning of the list.
*/
function prepend(List storage self, address node) internal {
// isInList(node) is checked in insertBefore
insertBefore(self, begin(self), node);
}
/**
* @notice Insert a node at the end of the list.
*
* @param self The list being used.
* @param node The node to insert at the end of the list.
*/
function append(List storage self, address node) internal {
// isInList(node) is checked in insertBefore
insertAfter(self, end(self), node);
}
function swap(List storage self, address left, address right) internal {
// isInList(left) and isInList(right) are checked in remove
address previousRight = self.list[right].previous;
remove(self, right);
insertAfter(self, left, right);
remove(self, left);
insertAfter(self, previousRight, left);
}
function isInList(List storage self, address node) internal view returns (bool) {
return self.list[node].inList;
}
/**
* @notice Get the node at the beginning of a double linked list.
*
* @param self The list being used.
*
* @return A address identifying the node at the beginning of the double
* linked list.
*/
function begin(List storage self) internal view returns (address) {
return self.list[NULL].next;
}
/**
* @notice Get the node at the end of a double linked list.
*
* @param self The list being used.
*
* @return A address identifying the node at the end of the double linked
* list.
*/
function end(List storage self) internal view returns (address) {
return self.list[NULL].previous;
}
function next(List storage self, address node) internal view returns (address) {
require(isInList(self, node), "not in list");
return self.list[node].next;
}
function previous(List storage self, address node) internal view returns (address) {
require(isInList(self, node), "not in list");
return self.list[node].previous;
}
}
/// @notice This contract stores data and funds for the DarknodeRegistry
/// contract. The data / fund logic and storage have been separated to improve
/// upgradability.
contract DarknodeRegistryStore is Ownable {
string public VERSION; // Passed in as a constructor parameter.
/// @notice Darknodes are stored in the darknode struct. The owner is the
/// address that registered the darknode, the bond is the amount of REN that
/// was transferred during registration, and the public key is the
/// encryption key that should be used when sending sensitive information to
/// the darknode.
struct Darknode {
// The owner of a Darknode is the address that called the register
// function. The owner is the only address that is allowed to
// deregister the Darknode, unless the Darknode is slashed for
// malicious behavior.
address owner;
// The bond is the amount of REN submitted as a bond by the Darknode.
// This amount is reduced when the Darknode is slashed for malicious
// behavior.
uint256 bond;
// The block number at which the Darknode is considered registered.
uint256 registeredAt;
// The block number at which the Darknode is considered deregistered.
uint256 deregisteredAt;
// The public key used by this Darknode for encrypting sensitive data
// off chain. It is assumed that the Darknode has access to the
// respective private key, and that there is an agreement on the format
// of the public key.
bytes publicKey;
}
/// Registry data.
mapping(address => Darknode) private darknodeRegistry;
LinkedList.List private darknodes;
// RepublicToken.
RepublicToken public ren;
/// @notice The contract constructor.
///
/// @param _VERSION A string defining the contract version.
/// @param _ren The address of the RepublicToken contract.
constructor(
string _VERSION,
RepublicToken _ren
) public {
VERSION = _VERSION;
ren = _ren;
}
/// @notice Instantiates a darknode and appends it to the darknodes
/// linked-list.
///
/// @param _darknodeID The darknode's ID.
/// @param _darknodeOwner The darknode's owner's address
/// @param _bond The darknode's bond value
/// @param _publicKey The darknode's public key
/// @param _registeredAt The time stamp when the darknode is registered.
/// @param _deregisteredAt The time stamp when the darknode is deregistered.
function appendDarknode(
address _darknodeID,
address _darknodeOwner,
uint256 _bond,
bytes _publicKey,
uint256 _registeredAt,
uint256 _deregisteredAt
) external onlyOwner {
Darknode memory darknode = Darknode({
owner: _darknodeOwner,
bond: _bond,
publicKey: _publicKey,
registeredAt: _registeredAt,
deregisteredAt: _deregisteredAt
});
darknodeRegistry[_darknodeID] = darknode;
LinkedList.append(darknodes, _darknodeID);
}
/// @notice Returns the address of the first darknode in the store
function begin() external view onlyOwner returns(address) {
return LinkedList.begin(darknodes);
}
/// @notice Returns the address of the next darknode in the store after the
/// given address.
function next(address darknodeID) external view onlyOwner returns(address) {
return LinkedList.next(darknodes, darknodeID);
}
/// @notice Removes a darknode from the store and transfers its bond to the
/// owner of this contract.
function removeDarknode(address darknodeID) external onlyOwner {
uint256 bond = darknodeRegistry[darknodeID].bond;
delete darknodeRegistry[darknodeID];
LinkedList.remove(darknodes, darknodeID);
require(ren.transfer(owner, bond), "bond transfer failed");
}
/// @notice Updates the bond of the darknode. If the bond is being
/// decreased, the difference is sent to the owner of this contract.
function updateDarknodeBond(address darknodeID, uint256 bond) external onlyOwner {
uint256 previousBond = darknodeRegistry[darknodeID].bond;
darknodeRegistry[darknodeID].bond = bond;
if (previousBond > bond) {
require(ren.transfer(owner, previousBond - bond), "cannot transfer bond");
}
}
/// @notice Updates the deregistration timestamp of a darknode.
function updateDarknodeDeregisteredAt(address darknodeID, uint256 deregisteredAt) external onlyOwner {
darknodeRegistry[darknodeID].deregisteredAt = deregisteredAt;
}
/// @notice Returns the owner of a given darknode.
function darknodeOwner(address darknodeID) external view onlyOwner returns (address) {
return darknodeRegistry[darknodeID].owner;
}
/// @notice Returns the bond of a given darknode.
function darknodeBond(address darknodeID) external view onlyOwner returns (uint256) {
return darknodeRegistry[darknodeID].bond;
}
/// @notice Returns the registration time of a given darknode.
function darknodeRegisteredAt(address darknodeID) external view onlyOwner returns (uint256) {
return darknodeRegistry[darknodeID].registeredAt;
}
/// @notice Returns the deregistration time of a given darknode.
function darknodeDeregisteredAt(address darknodeID) external view onlyOwner returns (uint256) {
return darknodeRegistry[darknodeID].deregisteredAt;
}
/// @notice Returns the encryption public key of a given darknode.
function darknodePublicKey(address darknodeID) external view onlyOwner returns (bytes) {
return darknodeRegistry[darknodeID].publicKey;
}
}
/// @notice DarknodeRegistry is responsible for the registration and
/// deregistration of Darknodes.
contract DarknodeRegistry is Ownable {
string public VERSION; // Passed in as a constructor parameter.
/// @notice Darknode pods are shuffled after a fixed number of blocks.
/// An Epoch stores an epoch hash used as an (insecure) RNG seed, and the
/// blocknumber which restricts when the next epoch can be called.
struct Epoch {
uint256 epochhash;
uint256 blocknumber;
}
uint256 public numDarknodes;
uint256 public numDarknodesNextEpoch;
uint256 public numDarknodesPreviousEpoch;
/// Variables used to parameterize behavior.
uint256 public minimumBond;
uint256 public minimumPodSize;
uint256 public minimumEpochInterval;
address public slasher;
/// When one of the above variables is modified, it is only updated when the
/// next epoch is called. These variables store the values for the next epoch.
uint256 public nextMinimumBond;
uint256 public nextMinimumPodSize;
uint256 public nextMinimumEpochInterval;
address public nextSlasher;
/// The current and previous epoch
Epoch public currentEpoch;
Epoch public previousEpoch;
/// Republic ERC20 token contract used to transfer bonds.
RepublicToken public ren;
/// Darknode Registry Store is the storage contract for darknodes.
DarknodeRegistryStore public store;
/// @notice Emitted when a darknode is registered.
/// @param _darknodeID The darknode ID that was registered.
/// @param _bond The amount of REN that was transferred as bond.
event LogDarknodeRegistered(address _darknodeID, uint256 _bond);
/// @notice Emitted when a darknode is deregistered.
/// @param _darknodeID The darknode ID that was deregistered.
event LogDarknodeDeregistered(address _darknodeID);
/// @notice Emitted when a refund has been made.
/// @param _owner The address that was refunded.
/// @param _amount The amount of REN that was refunded.
event LogDarknodeOwnerRefunded(address _owner, uint256 _amount);
/// @notice Emitted when a new epoch has begun.
event LogNewEpoch();
/// @notice Emitted when a constructor parameter has been updated.
event LogMinimumBondUpdated(uint256 previousMinimumBond, uint256 nextMinimumBond);
event LogMinimumPodSizeUpdated(uint256 previousMinimumPodSize, uint256 nextMinimumPodSize);
event LogMinimumEpochIntervalUpdated(uint256 previousMinimumEpochInterval, uint256 nextMinimumEpochInterval);
event LogSlasherUpdated(address previousSlasher, address nextSlasher);
/// @notice Only allow the owner that registered the darknode to pass.
modifier onlyDarknodeOwner(address _darknodeID) {
require(store.darknodeOwner(_darknodeID) == msg.sender, "must be darknode owner");
_;
}
/// @notice Only allow unregistered darknodes.
modifier onlyRefunded(address _darknodeID) {
require(isRefunded(_darknodeID), "must be refunded or never registered");
_;
}
/// @notice Only allow refundable darknodes.
modifier onlyRefundable(address _darknodeID) {
require(isRefundable(_darknodeID), "must be deregistered for at least one epoch");
_;
}
/// @notice Only allowed registered nodes without a pending deregistration to
/// deregister
modifier onlyDeregisterable(address _darknodeID) {
require(isDeregisterable(_darknodeID), "must be deregisterable");
_;
}
/// @notice Only allow the Slasher contract.
modifier onlySlasher() {
require(slasher == msg.sender, "must be slasher");
_;
}
/// @notice The contract constructor.
///
/// @param _VERSION A string defining the contract version.
/// @param _renAddress The address of the RepublicToken contract.
/// @param _storeAddress The address of the DarknodeRegistryStore contract.
/// @param _minimumBond The minimum bond amount that can be submitted by a
/// Darknode.
/// @param _minimumPodSize The minimum size of a Darknode pod.
/// @param _minimumEpochInterval The minimum number of blocks between
/// epochs.
constructor(
string _VERSION,
RepublicToken _renAddress,
DarknodeRegistryStore _storeAddress,
uint256 _minimumBond,
uint256 _minimumPodSize,
uint256 _minimumEpochInterval
) public {
VERSION = _VERSION;
store = _storeAddress;
ren = _renAddress;
minimumBond = _minimumBond;
nextMinimumBond = minimumBond;
minimumPodSize = _minimumPodSize;
nextMinimumPodSize = minimumPodSize;
minimumEpochInterval = _minimumEpochInterval;
nextMinimumEpochInterval = minimumEpochInterval;
currentEpoch = Epoch({
epochhash: uint256(blockhash(block.number - 1)),
blocknumber: block.number
});
numDarknodes = 0;
numDarknodesNextEpoch = 0;
numDarknodesPreviousEpoch = 0;
}
/// @notice Register a darknode and transfer the bond to this contract. The
/// caller must provide a public encryption key for the darknode as well as
/// a bond in REN. The bond must be provided as an ERC20 allowance. The dark
/// node will remain pending registration until the next epoch. Only after
/// this period can the darknode be deregistered. The caller of this method
/// will be stored as the owner of the darknode.
///
/// @param _darknodeID The darknode ID that will be registered.
/// @param _publicKey The public key of the darknode. It is stored to allow
/// other darknodes and traders to encrypt messages to the trader.
/// @param _bond The bond that will be paid. It must be greater than, or
/// equal to, the minimum bond.
function register(address _darknodeID, bytes _publicKey, uint256 _bond) external onlyRefunded(_darknodeID) {
// REN allowance
require(_bond >= minimumBond, "insufficient bond");
// require(ren.allowance(msg.sender, address(this)) >= _bond);
require(ren.transferFrom(msg.sender, address(this), _bond), "bond transfer failed");
ren.transfer(address(store), _bond);
// Flag this darknode for registration
store.appendDarknode(
_darknodeID,
msg.sender,
_bond,
_publicKey,
currentEpoch.blocknumber + minimumEpochInterval,
0
);
numDarknodesNextEpoch += 1;
// Emit an event.
emit LogDarknodeRegistered(_darknodeID, _bond);
}
/// @notice Deregister a darknode. The darknode will not be deregistered
/// until the end of the epoch. After another epoch, the bond can be
/// refunded by calling the refund method.
/// @param _darknodeID The darknode ID that will be deregistered. The caller
/// of this method store.darknodeRegisteredAt(_darknodeID) must be
// the owner of this darknode.
function deregister(address _darknodeID) external onlyDeregisterable(_darknodeID) onlyDarknodeOwner(_darknodeID) {
// Flag the darknode for deregistration
store.updateDarknodeDeregisteredAt(_darknodeID, currentEpoch.blocknumber + minimumEpochInterval);
numDarknodesNextEpoch -= 1;
// Emit an event
emit LogDarknodeDeregistered(_darknodeID);
}
/// @notice Progress the epoch if it is possible to do so. This captures
/// the current timestamp and current blockhash and overrides the current
/// epoch.
function epoch() external {
if (previousEpoch.blocknumber == 0) {
// The first epoch must be called by the owner of the contract
require(msg.sender == owner, "not authorized (first epochs)");
}
// Require that the epoch interval has passed
require(block.number >= currentEpoch.blocknumber + minimumEpochInterval, "epoch interval has not passed");
uint256 epochhash = uint256(blockhash(block.number - 1));
// Update the epoch hash and timestamp
previousEpoch = currentEpoch;
currentEpoch = Epoch({
epochhash: epochhash,
blocknumber: block.number
});
// Update the registry information
numDarknodesPreviousEpoch = numDarknodes;
numDarknodes = numDarknodesNextEpoch;
// If any update functions have been called, update the values now
if (nextMinimumBond != minimumBond) {
minimumBond = nextMinimumBond;
emit LogMinimumBondUpdated(minimumBond, nextMinimumBond);
}
if (nextMinimumPodSize != minimumPodSize) {
minimumPodSize = nextMinimumPodSize;
emit LogMinimumPodSizeUpdated(minimumPodSize, nextMinimumPodSize);
}
if (nextMinimumEpochInterval != minimumEpochInterval) {
minimumEpochInterval = nextMinimumEpochInterval;
emit LogMinimumEpochIntervalUpdated(minimumEpochInterval, nextMinimumEpochInterval);
}
if (nextSlasher != slasher) {
slasher = nextSlasher;
emit LogSlasherUpdated(slasher, nextSlasher);
}
// Emit an event
emit LogNewEpoch();
}
/// @notice Allows the contract owner to transfer ownership of the
/// DarknodeRegistryStore.
/// @param _newOwner The address to transfer the ownership to.
function transferStoreOwnership(address _newOwner) external onlyOwner {
store.transferOwnership(_newOwner);
}
/// @notice Allows the contract owner to update the minimum bond.
/// @param _nextMinimumBond The minimum bond amount that can be submitted by
/// a darknode.
function updateMinimumBond(uint256 _nextMinimumBond) external onlyOwner {
// Will be updated next epoch
nextMinimumBond = _nextMinimumBond;
}
/// @notice Allows the contract owner to update the minimum pod size.
/// @param _nextMinimumPodSize The minimum size of a pod.
function updateMinimumPodSize(uint256 _nextMinimumPodSize) external onlyOwner {
// Will be updated next epoch
nextMinimumPodSize = _nextMinimumPodSize;
}
/// @notice Allows the contract owner to update the minimum epoch interval.
/// @param _nextMinimumEpochInterval The minimum number of blocks between epochs.
function updateMinimumEpochInterval(uint256 _nextMinimumEpochInterval) external onlyOwner {
// Will be updated next epoch
nextMinimumEpochInterval = _nextMinimumEpochInterval;
}
/// @notice Allow the contract owner to update the DarknodeSlasher contract
/// address.
/// @param _slasher The new slasher address.
function updateSlasher(address _slasher) external onlyOwner {
nextSlasher = _slasher;
}
/// @notice Allow the DarknodeSlasher contract to slash half of a darknode's
/// bond and deregister it. The bond is distributed as follows:
/// 1/2 is kept by the guilty prover
/// 1/8 is rewarded to the first challenger
/// 1/8 is rewarded to the second challenger
/// 1/4 becomes unassigned
/// @param _prover The guilty prover whose bond is being slashed
/// @param _challenger1 The first of the two darknodes who submitted the challenge
/// @param _challenger2 The second of the two darknodes who submitted the challenge
function slash(address _prover, address _challenger1, address _challenger2)
external
onlySlasher
{
uint256 penalty = store.darknodeBond(_prover) / 2;
uint256 reward = penalty / 4;
// Slash the bond of the failed prover in half
store.updateDarknodeBond(_prover, penalty);
// If the darknode has not been deregistered then deregister it
if (isDeregisterable(_prover)) {
store.updateDarknodeDeregisteredAt(_prover, currentEpoch.blocknumber + minimumEpochInterval);
numDarknodesNextEpoch -= 1;
emit LogDarknodeDeregistered(_prover);
}
// Reward the challengers with less than the penalty so that it is not
// worth challenging yourself
ren.transfer(store.darknodeOwner(_challenger1), reward);
ren.transfer(store.darknodeOwner(_challenger2), reward);
}
/// @notice Refund the bond of a deregistered darknode. This will make the
/// darknode available for registration again. Anyone can call this function
/// but the bond will always be refunded to the darknode owner.
///
/// @param _darknodeID The darknode ID that will be refunded. The caller
/// of this method must be the owner of this darknode.
function refund(address _darknodeID) external onlyRefundable(_darknodeID) {
address darknodeOwner = store.darknodeOwner(_darknodeID);
// Remember the bond amount
uint256 amount = store.darknodeBond(_darknodeID);
// Erase the darknode from the registry
store.removeDarknode(_darknodeID);
// Refund the owner by transferring REN
ren.transfer(darknodeOwner, amount);
// Emit an event.
emit LogDarknodeOwnerRefunded(darknodeOwner, amount);
}
/// @notice Retrieves the address of the account that registered a darknode.
/// @param _darknodeID The ID of the darknode to retrieve the owner for.
function getDarknodeOwner(address _darknodeID) external view returns (address) {
return store.darknodeOwner(_darknodeID);
}
/// @notice Retrieves the bond amount of a darknode in 10^-18 REN.
/// @param _darknodeID The ID of the darknode to retrieve the bond for.
function getDarknodeBond(address _darknodeID) external view returns (uint256) {
return store.darknodeBond(_darknodeID);
}
/// @notice Retrieves the encryption public key of the darknode.
/// @param _darknodeID The ID of the darknode to retrieve the public key for.
function getDarknodePublicKey(address _darknodeID) external view returns (bytes) {
return store.darknodePublicKey(_darknodeID);
}
/// @notice Retrieves a list of darknodes which are registered for the
/// current epoch.
/// @param _start A darknode ID used as an offset for the list. If _start is
/// 0x0, the first dark node will be used. _start won't be
/// included it is not registered for the epoch.
/// @param _count The number of darknodes to retrieve starting from _start.
/// If _count is 0, all of the darknodes from _start are
/// retrieved. If _count is more than the remaining number of
/// registered darknodes, the rest of the list will contain
/// 0x0s.
function getDarknodes(address _start, uint256 _count) external view returns (address[]) {
uint256 count = _count;
if (count == 0) {
count = numDarknodes;
}
return getDarknodesFromEpochs(_start, count, false);
}
/// @notice Retrieves a list of darknodes which were registered for the
/// previous epoch. See `getDarknodes` for the parameter documentation.
function getPreviousDarknodes(address _start, uint256 _count) external view returns (address[]) {
uint256 count = _count;
if (count == 0) {
count = numDarknodesPreviousEpoch;
}
return getDarknodesFromEpochs(_start, count, true);
}
/// @notice Returns whether a darknode is scheduled to become registered
/// at next epoch.
/// @param _darknodeID The ID of the darknode to return
function isPendingRegistration(address _darknodeID) external view returns (bool) {
uint256 registeredAt = store.darknodeRegisteredAt(_darknodeID);
return registeredAt != 0 && registeredAt > currentEpoch.blocknumber;
}
/// @notice Returns if a darknode is in the pending deregistered state. In
/// this state a darknode is still considered registered.
function isPendingDeregistration(address _darknodeID) external view returns (bool) {
uint256 deregisteredAt = store.darknodeDeregisteredAt(_darknodeID);
return deregisteredAt != 0 && deregisteredAt > currentEpoch.blocknumber;
}
/// @notice Returns if a darknode is in the deregistered state.
function isDeregistered(address _darknodeID) public view returns (bool) {
uint256 deregisteredAt = store.darknodeDeregisteredAt(_darknodeID);
return deregisteredAt != 0 && deregisteredAt <= currentEpoch.blocknumber;
}
/// @notice Returns if a darknode can be deregistered. This is true if the
/// darknodes is in the registered state and has not attempted to
/// deregister yet.
function isDeregisterable(address _darknodeID) public view returns (bool) {
uint256 deregisteredAt = store.darknodeDeregisteredAt(_darknodeID);
// The Darknode is currently in the registered state and has not been
// transitioned to the pending deregistration, or deregistered, state
return isRegistered(_darknodeID) && deregisteredAt == 0;
}
/// @notice Returns if a darknode is in the refunded state. This is true
/// for darknodes that have never been registered, or darknodes that have
/// been deregistered and refunded.
function isRefunded(address _darknodeID) public view returns (bool) {
uint256 registeredAt = store.darknodeRegisteredAt(_darknodeID);
uint256 deregisteredAt = store.darknodeDeregisteredAt(_darknodeID);
return registeredAt == 0 && deregisteredAt == 0;
}
/// @notice Returns if a darknode is refundable. This is true for darknodes
/// that have been in the deregistered state for one full epoch.
function isRefundable(address _darknodeID) public view returns (bool) {
return isDeregistered(_darknodeID) && store.darknodeDeregisteredAt(_darknodeID) <= previousEpoch.blocknumber;
}
/// @notice Returns if a darknode is in the registered state.
function isRegistered(address _darknodeID) public view returns (bool) {
return isRegisteredInEpoch(_darknodeID, currentEpoch);
}
/// @notice Returns if a darknode was in the registered state last epoch.
function isRegisteredInPreviousEpoch(address _darknodeID) public view returns (bool) {
return isRegisteredInEpoch(_darknodeID, previousEpoch);
}
/// @notice Returns if a darknode was in the registered state for a given
/// epoch.
/// @param _darknodeID The ID of the darknode
/// @param _epoch One of currentEpoch, previousEpoch
function isRegisteredInEpoch(address _darknodeID, Epoch _epoch) private view returns (bool) {
uint256 registeredAt = store.darknodeRegisteredAt(_darknodeID);
uint256 deregisteredAt = store.darknodeDeregisteredAt(_darknodeID);
bool registered = registeredAt != 0 && registeredAt <= _epoch.blocknumber;
bool notDeregistered = deregisteredAt == 0 || deregisteredAt > _epoch.blocknumber;
// The Darknode has been registered and has not yet been deregistered,
// although it might be pending deregistration
return registered && notDeregistered;
}
/// @notice Returns a list of darknodes registered for either the current
/// or the previous epoch. See `getDarknodes` for documentation on the
/// parameters `_start` and `_count`.
/// @param _usePreviousEpoch If true, use the previous epoch, otherwise use
/// the current epoch.
function getDarknodesFromEpochs(address _start, uint256 _count, bool _usePreviousEpoch) private view returns (address[]) {
uint256 count = _count;
if (count == 0) {
count = numDarknodes;
}
address[] memory nodes = new address[](count);
// Begin with the first node in the list
uint256 n = 0;
address next = _start;
if (next == 0x0) {
next = store.begin();
}
// Iterate until all registered Darknodes have been collected
while (n < count) {
if (next == 0x0) {
break;
}
// Only include Darknodes that are currently registered
bool includeNext;
if (_usePreviousEpoch) {
includeNext = isRegisteredInPreviousEpoch(next);
} else {
includeNext = isRegistered(next);
}
if (!includeNext) {
next = store.next(next);
continue;
}
nodes[n] = next;
next = store.next(next);
n += 1;
}
return nodes;
}
}
/**
* @title Math
* @dev Assorted math operations
*/
library Math {
function max64(uint64 a, uint64 b) internal pure returns (uint64) {
return a >= b ? a : b;
}
function min64(uint64 a, uint64 b) internal pure returns (uint64) {
return a < b ? a : b;
}
function max256(uint256 a, uint256 b) internal pure returns (uint256) {
return a >= b ? a : b;
}
function min256(uint256 a, uint256 b) internal pure returns (uint256) {
return a < b ? a : b;
}
}
/// @notice Implements safeTransfer, safeTransferFrom and
/// safeApprove for CompatibleERC20.
///
/// See https://github.com/ethereum/solidity/issues/4116
///
/// This library allows interacting with ERC20 tokens that implement any of
/// these interfaces:
///
/// (1) transfer returns true on success, false on failure
/// (2) transfer returns true on success, reverts on failure
/// (3) transfer returns nothing on success, reverts on failure
///
/// Additionally, safeTransferFromWithFees will return the final token
/// value received after accounting for token fees.
library CompatibleERC20Functions {
using SafeMath for uint256;
/// @notice Calls transfer on the token and reverts if the call fails.
function safeTransfer(address token, address to, uint256 amount) internal {
CompatibleERC20(token).transfer(to, amount);
require(previousReturnValue(), "transfer failed");
}
/// @notice Calls transferFrom on the token and reverts if the call fails.
function safeTransferFrom(address token, address from, address to, uint256 amount) internal {
CompatibleERC20(token).transferFrom(from, to, amount);
require(previousReturnValue(), "transferFrom failed");
}
/// @notice Calls approve on the token and reverts if the call fails.
function safeApprove(address token, address spender, uint256 amount) internal {
CompatibleERC20(token).approve(spender, amount);
require(previousReturnValue(), "approve failed");
}
/// @notice Calls transferFrom on the token, reverts if the call fails and
/// returns the value transferred after fees.
function safeTransferFromWithFees(address token, address from, address to, uint256 amount) internal returns (uint256) {
uint256 balancesBefore = CompatibleERC20(token).balanceOf(to);
CompatibleERC20(token).transferFrom(from, to, amount);
require(previousReturnValue(), "transferFrom failed");
uint256 balancesAfter = CompatibleERC20(token).balanceOf(to);
return Math.min256(amount, balancesAfter.sub(balancesBefore));
}
/// @notice Checks the return value of the previous function. Returns true
/// if the previous function returned 32 non-zero bytes or returned zero
/// bytes.
function previousReturnValue() private pure returns (bool)
{
uint256 returnData = 0;
assembly { /* solium-disable-line security/no-inline-assembly */
// Switch on the number of bytes returned by the previous call
switch returndatasize
// 0 bytes: ERC20 of type (3), did not throw
case 0 {
returnData := 1
}
// 32 bytes: ERC20 of types (1) or (2)
case 32 {
// Copy the return data into scratch space
returndatacopy(0x0, 0x0, 32)
// Load the return data into returnData
returnData := mload(0x0)
}
// Other return size: return false
default { }
}
return returnData != 0;
}
}
/// @notice ERC20 interface which doesn't specify the return type for transfer,
/// transferFrom and approve.
interface CompatibleERC20 {
// Modified to not return boolean
function transfer(address to, uint256 value) external;
function transferFrom(address from, address to, uint256 value) external;
function approve(address spender, uint256 value) external;
// Not modifier
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);
}
/// @notice The DarknodeRewardVault contract is responsible for holding fees
/// for darknodes for settling orders. Fees can be withdrawn to the address of
/// the darknode's operator. Fees can be in ETH or in ERC20 tokens.
/// Docs: https://github.com/republicprotocol/republic-sol/blob/master/docs/02-darknode-reward-vault.md
contract DarknodeRewardVault is Ownable {
using SafeMath for uint256;
using CompatibleERC20Functions for CompatibleERC20;
string public VERSION; // Passed in as a constructor parameter.
/// @notice The special address for Ether.
address constant public ETHEREUM = 0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE;
DarknodeRegistry public darknodeRegistry;
mapping(address => mapping(address => uint256)) public darknodeBalances;
event LogDarknodeRegistryUpdated(DarknodeRegistry previousDarknodeRegistry, DarknodeRegistry nextDarknodeRegistry);
/// @notice The contract constructor.
///
/// @param _VERSION A string defining the contract version.
/// @param _darknodeRegistry The DarknodeRegistry contract that is used by
/// the vault to lookup Darknode owners.
constructor(string _VERSION, DarknodeRegistry _darknodeRegistry) public {
VERSION = _VERSION;
darknodeRegistry = _darknodeRegistry;
}
function updateDarknodeRegistry(DarknodeRegistry _newDarknodeRegistry) public onlyOwner {
emit LogDarknodeRegistryUpdated(darknodeRegistry, _newDarknodeRegistry);
darknodeRegistry = _newDarknodeRegistry;
}
/// @notice Deposit fees into the vault for a Darknode. The Darknode
/// registration is not checked (to reduce gas fees); the caller must be
/// careful not to call this function for a Darknode that is not registered
/// otherwise any fees deposited to that Darknode can be withdrawn by a
/// malicious adversary (by registering the Darknode before the honest
/// party and claiming ownership).
///
/// @param _darknode The address of the Darknode that will receive the
/// fees.
/// @param _token The address of the ERC20 token being used to pay the fee.
/// A special address is used for Ether.
/// @param _value The amount of fees in the smallest unit of the token.
function deposit(address _darknode, ERC20 _token, uint256 _value) public payable {
uint256 receivedValue = _value;
if (address(_token) == ETHEREUM) {
require(msg.value == _value, "mismatched ether value");
} else {
require(msg.value == 0, "unexpected ether value");
receivedValue = CompatibleERC20(_token).safeTransferFromWithFees(msg.sender, address(this), _value);
}
darknodeBalances[_darknode][_token] = darknodeBalances[_darknode][_token].add(receivedValue);
}
/// @notice Withdraw fees earned by a Darknode. The fees will be sent to
/// the owner of the Darknode. If a Darknode is not registered the fees
/// cannot be withdrawn.
///
/// @param _darknode The address of the Darknode whose fees are being
/// withdrawn. The owner of this Darknode will receive the fees.
/// @param _token The address of the ERC20 token to withdraw.
function withdraw(address _darknode, ERC20 _token) public {
address darknodeOwner = darknodeRegistry.getDarknodeOwner(address(_darknode));
require(darknodeOwner != 0x0, "invalid darknode owner");
uint256 value = darknodeBalances[_darknode][_token];
darknodeBalances[_darknode][_token] = 0;
if (address(_token) == ETHEREUM) {
darknodeOwner.transfer(value);
} else {
CompatibleERC20(_token).safeTransfer(darknodeOwner, value);
}
}
}
/// @notice The BrokerVerifier interface defines the functions that a settlement
/// layer's broker verifier contract must implement.
interface BrokerVerifier {
/// @notice The function signature that will be called when a trader opens
/// an order.
///
/// @param _trader The trader requesting the withdrawal.
/// @param _signature The 65-byte signature from the broker.
/// @param _orderID The 32-byte order ID.
function verifyOpenSignature(
address _trader,
bytes _signature,
bytes32 _orderID
) external returns (bool);
}
/// @notice The Settlement interface defines the functions that a settlement
/// layer must implement.
/// Docs: https://github.com/republicprotocol/republic-sol/blob/nightly/docs/05-settlement.md
interface Settlement {
function submitOrder(
bytes _details,
uint64 _settlementID,
uint64 _tokens,
uint256 _price,
uint256 _volume,
uint256 _minimumVolume
) external;
function submissionGasPriceLimit() external view returns (uint256);
function settle(
bytes32 _buyID,
bytes32 _sellID
) external;
/// @notice orderStatus should return the status of the order, which should
/// be:
/// 0 - Order not seen before
/// 1 - Order details submitted
/// >1 - Order settled, or settlement no longer possible
function orderStatus(bytes32 _orderID) external view returns (uint8);
}
/// @notice SettlementRegistry allows a Settlement layer to register the
/// contracts used for match settlement and for broker signature verification.
contract SettlementRegistry is Ownable {
string public VERSION; // Passed in as a constructor parameter.
struct SettlementDetails {
bool registered;
Settlement settlementContract;
BrokerVerifier brokerVerifierContract;
}
// Settlement IDs are 64-bit unsigned numbers
mapping(uint64 => SettlementDetails) public settlementDetails;
// Events
event LogSettlementRegistered(uint64 settlementID, Settlement settlementContract, BrokerVerifier brokerVerifierContract);
event LogSettlementUpdated(uint64 settlementID, Settlement settlementContract, BrokerVerifier brokerVerifierContract);
event LogSettlementDeregistered(uint64 settlementID);
/// @notice The contract constructor.
///
/// @param _VERSION A string defining the contract version.
constructor(string _VERSION) public {
VERSION = _VERSION;
}
/// @notice Returns the settlement contract of a settlement layer.
function settlementRegistration(uint64 _settlementID) external view returns (bool) {
return settlementDetails[_settlementID].registered;
}
/// @notice Returns the settlement contract of a settlement layer.
function settlementContract(uint64 _settlementID) external view returns (Settlement) {
return settlementDetails[_settlementID].settlementContract;
}
/// @notice Returns the broker verifier contract of a settlement layer.
function brokerVerifierContract(uint64 _settlementID) external view returns (BrokerVerifier) {
return settlementDetails[_settlementID].brokerVerifierContract;
}
/// @param _settlementID A unique 64-bit settlement identifier.
/// @param _settlementContract The address to use for settling matches.
/// @param _brokerVerifierContract The decimals to use for verifying
/// broker signatures.
function registerSettlement(uint64 _settlementID, Settlement _settlementContract, BrokerVerifier _brokerVerifierContract) public onlyOwner {
bool alreadyRegistered = settlementDetails[_settlementID].registered;
settlementDetails[_settlementID] = SettlementDetails({
registered: true,
settlementContract: _settlementContract,
brokerVerifierContract: _brokerVerifierContract
});
if (alreadyRegistered) {
emit LogSettlementUpdated(_settlementID, _settlementContract, _brokerVerifierContract);
} else {
emit LogSettlementRegistered(_settlementID, _settlementContract, _brokerVerifierContract);
}
}
/// @notice Deregisteres a settlement layer, clearing the details.
/// @param _settlementID The unique 64-bit settlement identifier.
function deregisterSettlement(uint64 _settlementID) external onlyOwner {
require(settlementDetails[_settlementID].registered, "not registered");
delete settlementDetails[_settlementID];
emit LogSettlementDeregistered(_settlementID);
}
}
/**
* @title Eliptic curve signature operations
* @dev Based on https://gist.github.com/axic/5b33912c6f61ae6fd96d6c4a47afde6d
* TODO Remove this library once solidity supports passing a signature to ecrecover.
* See https://github.com/ethereum/solidity/issues/864
*/
library ECRecovery {
/**
* @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 sig bytes signature, the signature is generated using web3.eth.sign()
*/
function recover(bytes32 hash, bytes sig)
internal
pure
returns (address)
{
bytes32 r;
bytes32 s;
uint8 v;
// Check the signature length
if (sig.length != 65) {
return (address(0));
}
// Divide the signature in r, s and v variables
// ecrecover takes the signature parameters, and the only way to get them
// currently is to use assembly.
// solium-disable-next-line security/no-inline-assembly
assembly {
r := mload(add(sig, 32))
s := mload(add(sig, 64))
v := byte(0, mload(add(sig, 96)))
}
// Version of signature should be 27 or 28, but 0 and 1 are also possible versions
if (v < 27) {
v += 27;
}
// If the version is correct return the signer address
if (v != 27 && v != 28) {
return (address(0));
} else {
// solium-disable-next-line arg-overflow
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)
);
}
}
library Utils {
/**
* @notice Converts a number to its string/bytes representation
*
* @param _v the uint to convert
*/
function uintToBytes(uint256 _v) internal pure returns (bytes) {
uint256 v = _v;
if (v == 0) {
return "0";
}
uint256 digits = 0;
uint256 v2 = v;
while (v2 > 0) {
v2 /= 10;
digits += 1;
}
bytes memory result = new bytes(digits);
for (uint256 i = 0; i < digits; i++) {
result[digits - i - 1] = bytes1((v % 10) + 48);
v /= 10;
}
return result;
}
/**
* @notice Retrieves the address from a signature
*
* @param _hash the message that was signed (any length of bytes)
* @param _signature the signature (65 bytes)
*/
function addr(bytes _hash, bytes _signature) internal pure returns (address) {
bytes memory prefix = "\x19Ethereum Signed Message:\n";
bytes memory encoded = abi.encodePacked(prefix, uintToBytes(_hash.length), _hash);
bytes32 prefixedHash = keccak256(encoded);
return ECRecovery.recover(prefixedHash, _signature);
}
}
/// @notice The Orderbook contract stores the state and priority of orders and
/// allows the Darknodes to easily reach consensus. Eventually, this contract
/// will only store a subset of order states, such as cancellation, to improve
/// the throughput of orders.
contract Orderbook is Ownable {
string public VERSION; // Passed in as a constructor parameter.
/// @notice OrderState enumerates the possible states of an order. All
/// orders default to the Undefined state.
enum OrderState {Undefined, Open, Confirmed, Canceled}
/// @notice Order stores a subset of the public data associated with an order.
struct Order {
OrderState state; // State of the order
address trader; // Trader that owns the order
address confirmer; // Darknode that confirmed the order in a match
uint64 settlementID; // The settlement that signed the order opening
uint256 priority; // Logical time priority of this order
uint256 blockNumber; // Block number of the most recent state change
bytes32 matchedOrder; // Order confirmed in a match with this order
}
DarknodeRegistry public darknodeRegistry;
SettlementRegistry public settlementRegistry;
bytes32[] private orderbook;
// Order details are exposed through directly accessing this mapping, or
// through the getter functions below for each of the order's fields.
mapping(bytes32 => Order) public orders;
event LogFeeUpdated(uint256 previousFee, uint256 nextFee);
event LogDarknodeRegistryUpdated(DarknodeRegistry previousDarknodeRegistry, DarknodeRegistry nextDarknodeRegistry);
/// @notice Only allow registered dark nodes.
modifier onlyDarknode(address _sender) {
require(darknodeRegistry.isRegistered(address(_sender)), "must be registered darknode");
_;
}
/// @notice The contract constructor.
///
/// @param _VERSION A string defining the contract version.
/// @param _darknodeRegistry The address of the DarknodeRegistry contract.
/// @param _settlementRegistry The address of the SettlementRegistry
/// contract.
constructor(
string _VERSION,
DarknodeRegistry _darknodeRegistry,
SettlementRegistry _settlementRegistry
) public {
VERSION = _VERSION;
darknodeRegistry = _darknodeRegistry;
settlementRegistry = _settlementRegistry;
}
/// @notice Allows the owner to update the address of the DarknodeRegistry
/// contract.
function updateDarknodeRegistry(DarknodeRegistry _newDarknodeRegistry) external onlyOwner {
emit LogDarknodeRegistryUpdated(darknodeRegistry, _newDarknodeRegistry);
darknodeRegistry = _newDarknodeRegistry;
}
/// @notice Open an order in the orderbook. The order must be in the
/// Undefined state.
///
/// @param _signature Signature of the message that defines the trader. The
/// message is "Republic Protocol: open: {orderId}".
/// @param _orderID The hash of the order.
function openOrder(uint64 _settlementID, bytes _signature, bytes32 _orderID) external {
require(orders[_orderID].state == OrderState.Undefined, "invalid order status");
address trader = msg.sender;
// Verify the order signature
require(settlementRegistry.settlementRegistration(_settlementID), "settlement not registered");
BrokerVerifier brokerVerifier = settlementRegistry.brokerVerifierContract(_settlementID);
require(brokerVerifier.verifyOpenSignature(trader, _signature, _orderID), "invalid broker signature");
orders[_orderID] = Order({
state: OrderState.Open,
trader: trader,
confirmer: 0x0,
settlementID: _settlementID,
priority: orderbook.length + 1,
blockNumber: block.number,
matchedOrder: 0x0
});
orderbook.push(_orderID);
}
/// @notice Confirm an order match between orders. The confirmer must be a
/// registered Darknode and the orders must be in the Open state. A
/// malicious confirmation by a Darknode will result in a bond slash of the
/// Darknode.
///
/// @param _orderID The hash of the order.
/// @param _matchedOrderID The hashes of the matching order.
function confirmOrder(bytes32 _orderID, bytes32 _matchedOrderID) external onlyDarknode(msg.sender) {
require(orders[_orderID].state == OrderState.Open, "invalid order status");
require(orders[_matchedOrderID].state == OrderState.Open, "invalid order status");
orders[_orderID].state = OrderState.Confirmed;
orders[_orderID].confirmer = msg.sender;
orders[_orderID].matchedOrder = _matchedOrderID;
orders[_orderID].blockNumber = block.number;
orders[_matchedOrderID].state = OrderState.Confirmed;
orders[_matchedOrderID].confirmer = msg.sender;
orders[_matchedOrderID].matchedOrder = _orderID;
orders[_matchedOrderID].blockNumber = block.number;
}
/// @notice Cancel an open order in the orderbook. An order can be cancelled
/// by the trader who opened the order, or by the broker verifier contract.
/// This allows the settlement layer to implement their own logic for
/// cancelling orders without trader interaction (e.g. to ban a trader from
/// a specific darkpool, or to use multiple order-matching platforms)
///
/// @param _orderID The hash of the order.
function cancelOrder(bytes32 _orderID) external {
require(orders[_orderID].state == OrderState.Open, "invalid order state");
// Require the msg.sender to be the trader or the broker verifier
address brokerVerifier = address(settlementRegistry.brokerVerifierContract(orders[_orderID].settlementID));
require(msg.sender == orders[_orderID].trader || msg.sender == brokerVerifier, "not authorized");
orders[_orderID].state = OrderState.Canceled;
orders[_orderID].blockNumber = block.number;
}
/// @notice returns status of the given orderID.
function orderState(bytes32 _orderID) external view returns (OrderState) {
return orders[_orderID].state;
}
/// @notice returns a list of matched orders to the given orderID.
function orderMatch(bytes32 _orderID) external view returns (bytes32) {
return orders[_orderID].matchedOrder;
}
/// @notice returns the priority of the given orderID.
/// The priority is the index of the order in the orderbook.
function orderPriority(bytes32 _orderID) external view returns (uint256) {
return orders[_orderID].priority;
}
/// @notice returns the trader of the given orderID.
/// Trader is the one who signs the message and does the actual trading.
function orderTrader(bytes32 _orderID) external view returns (address) {
return orders[_orderID].trader;
}
/// @notice returns the darknode address which confirms the given orderID.
function orderConfirmer(bytes32 _orderID) external view returns (address) {
return orders[_orderID].confirmer;
}
/// @notice returns the block number when the order being last modified.
function orderBlockNumber(bytes32 _orderID) external view returns (uint256) {
return orders[_orderID].blockNumber;
}
/// @notice returns the block depth of the orderId
function orderDepth(bytes32 _orderID) external view returns (uint256) {
if (orders[_orderID].blockNumber == 0) {
return 0;
}
return (block.number - orders[_orderID].blockNumber);
}
/// @notice returns the number of orders in the orderbook
function ordersCount() external view returns (uint256) {
return orderbook.length;
}
/// @notice returns order details of the orders starting from the offset.
function getOrders(uint256 _offset, uint256 _limit) external view returns (bytes32[], address[], uint8[]) {
if (_offset >= orderbook.length) {
return;
}
// If the provided limit is more than the number of orders after the offset,
// decrease the limit
uint256 limit = _limit;
if (_offset + limit > orderbook.length) {
limit = orderbook.length - _offset;
}
bytes32[] memory orderIDs = new bytes32[](limit);
address[] memory traderAddresses = new address[](limit);
uint8[] memory states = new uint8[](limit);
for (uint256 i = 0; i < limit; i++) {
bytes32 order = orderbook[i + _offset];
orderIDs[i] = order;
traderAddresses[i] = orders[order].trader;
states[i] = uint8(orders[order].state);
}
return (orderIDs, traderAddresses, states);
}
}
/// @notice A library for calculating and verifying order match details
library SettlementUtils {
struct OrderDetails {
uint64 settlementID;
uint64 tokens;
uint256 price;
uint256 volume;
uint256 minimumVolume;
}
/// @notice Calculates the ID of the order.
/// @param details Order details that are not required for settlement
/// execution. They are combined as a single byte array.
/// @param order The order details required for settlement execution.
function hashOrder(bytes details, OrderDetails memory order) internal pure returns (bytes32) {
return keccak256(
abi.encodePacked(
details,
order.settlementID,
order.tokens,
order.price,
order.volume,
order.minimumVolume
)
);
}
/// @notice Verifies that two orders match when considering the tokens,
/// price, volumes / minimum volumes and settlement IDs. verifyMatchDetails is used
/// my the DarknodeSlasher to verify challenges. Settlement layers may also
/// use this function.
/// @dev When verifying two orders for settlement, you should also:
/// 1) verify the orders have been confirmed together
/// 2) verify the orders' traders are distinct
/// @param _buy The buy order details.
/// @param _sell The sell order details.
function verifyMatchDetails(OrderDetails memory _buy, OrderDetails memory _sell) internal pure returns (bool) {
// Buy and sell tokens should match
if (!verifyTokens(_buy.tokens, _sell.tokens)) {
return false;
}
// Buy price should be greater than sell price
if (_buy.price < _sell.price) {
return false;
}
// // Buy volume should be greater than sell minimum volume
if (_buy.volume < _sell.minimumVolume) {
return false;
}
// Sell volume should be greater than buy minimum volume
if (_sell.volume < _buy.minimumVolume) {
return false;
}
// Require that the orders were submitted to the same settlement layer
if (_buy.settlementID != _sell.settlementID) {
return false;
}
return true;
}
/// @notice Verifies that two token requirements can be matched and that the
/// tokens are formatted correctly.
/// @param _buyTokens The buy token details.
/// @param _sellToken The sell token details.
function verifyTokens(uint64 _buyTokens, uint64 _sellToken) internal pure returns (bool) {
return ((
uint32(_buyTokens) == uint32(_sellToken >> 32)) && (
uint32(_sellToken) == uint32(_buyTokens >> 32)) && (
uint32(_buyTokens >> 32) <= uint32(_buyTokens))
);
}
}
/// @notice RenExTokens is a registry of tokens that can be traded on RenEx.
contract RenExTokens is Ownable {
string public VERSION; // Passed in as a constructor parameter.
struct TokenDetails {
address addr;
uint8 decimals;
bool registered;
}
// Storage
mapping(uint32 => TokenDetails) public tokens;
mapping(uint32 => bool) private detailsSubmitted;
// Events
event LogTokenRegistered(uint32 tokenCode, address tokenAddress, uint8 tokenDecimals);
event LogTokenDeregistered(uint32 tokenCode);
/// @notice The contract constructor.
///
/// @param _VERSION A string defining the contract version.
constructor(string _VERSION) public {
VERSION = _VERSION;
}
/// @notice Allows the owner to register and the details for a token.
/// Once details have been submitted, they cannot be overwritten.
/// To re-register the same token with different details (e.g. if the address
/// has changed), a different token identifier should be used and the
/// previous token identifier should be deregistered.
/// If a token is not Ethereum-based, the address will be set to 0x0.
///
/// @param _tokenCode A unique 32-bit token identifier.
/// @param _tokenAddress The address of the token.
/// @param _tokenDecimals The decimals to use for the token.
function registerToken(uint32 _tokenCode, address _tokenAddress, uint8 _tokenDecimals) public onlyOwner {
require(!tokens[_tokenCode].registered, "already registered");
// If a token is being re-registered, the same details must be provided.
if (detailsSubmitted[_tokenCode]) {
require(tokens[_tokenCode].addr == _tokenAddress, "different address");
require(tokens[_tokenCode].decimals == _tokenDecimals, "different decimals");
} else {
detailsSubmitted[_tokenCode] = true;
}
tokens[_tokenCode] = TokenDetails({
addr: _tokenAddress,
decimals: _tokenDecimals,
registered: true
});
emit LogTokenRegistered(_tokenCode, _tokenAddress, _tokenDecimals);
}
/// @notice Sets a token as being deregistered. The details are still stored
/// to prevent the token from being re-registered with different details.
///
/// @param _tokenCode The unique 32-bit token identifier.
function deregisterToken(uint32 _tokenCode) external onlyOwner {
require(tokens[_tokenCode].registered, "not registered");
tokens[_tokenCode].registered = false;
emit LogTokenDeregistered(_tokenCode);
}
}
/// @notice RenExSettlement implements the Settlement interface. It implements
/// the on-chain settlement for the RenEx settlement layer, and the fee payment
/// for the RenExAtomic settlement layer.
contract RenExSettlement is Ownable {
using SafeMath for uint256;
string public VERSION; // Passed in as a constructor parameter.
// This contract handles the settlements with ID 1 and 2.
uint32 constant public RENEX_SETTLEMENT_ID = 1;
uint32 constant public RENEX_ATOMIC_SETTLEMENT_ID = 2;
// Fees in RenEx are 0.2%. To represent this as integers, it is broken into
// a numerator and denominator.
uint256 constant public DARKNODE_FEES_NUMERATOR = 2;
uint256 constant public DARKNODE_FEES_DENOMINATOR = 1000;
// Constants used in the price / volume inputs.
int16 constant private PRICE_OFFSET = 12;
int16 constant private VOLUME_OFFSET = 12;
// Constructor parameters, updatable by the owner
Orderbook public orderbookContract;
RenExTokens public renExTokensContract;
RenExBalances public renExBalancesContract;
address public slasherAddress;
uint256 public submissionGasPriceLimit;
enum OrderStatus {None, Submitted, Settled, Slashed}
struct TokenPair {
RenExTokens.TokenDetails priorityToken;
RenExTokens.TokenDetails secondaryToken;
}
// A uint256 tuple representing a value and an associated fee
struct ValueWithFees {
uint256 value;
uint256 fees;
}
// A uint256 tuple representing a fraction
struct Fraction {
uint256 numerator;
uint256 denominator;
}
// We use left and right because the tokens do not always represent the
// priority and secondary tokens.
struct SettlementDetails {
uint256 leftVolume;
uint256 rightVolume;
uint256 leftTokenFee;
uint256 rightTokenFee;
address leftTokenAddress;
address rightTokenAddress;
}
// Events
event LogOrderbookUpdated(Orderbook previousOrderbook, Orderbook nextOrderbook);
event LogRenExTokensUpdated(RenExTokens previousRenExTokens, RenExTokens nextRenExTokens);
event LogRenExBalancesUpdated(RenExBalances previousRenExBalances, RenExBalances nextRenExBalances);
event LogSubmissionGasPriceLimitUpdated(uint256 previousSubmissionGasPriceLimit, uint256 nextSubmissionGasPriceLimit);
event LogSlasherUpdated(address previousSlasher, address nextSlasher);
// Order Storage
mapping(bytes32 => SettlementUtils.OrderDetails) public orderDetails;
mapping(bytes32 => address) public orderSubmitter;
mapping(bytes32 => OrderStatus) public orderStatus;
// Match storage (match details are indexed by [buyID][sellID])
mapping(bytes32 => mapping(bytes32 => uint256)) public matchTimestamp;
/// @notice Prevents a function from being called with a gas price higher
/// than the specified limit.
///
/// @param _gasPriceLimit The gas price upper-limit in Wei.
modifier withGasPriceLimit(uint256 _gasPriceLimit) {
require(tx.gasprice <= _gasPriceLimit, "gas price too high");
_;
}
/// @notice Restricts a function to only being called by the slasher
/// address.
modifier onlySlasher() {
require(msg.sender == slasherAddress, "unauthorized");
_;
}
/// @notice The contract constructor.
///
/// @param _VERSION A string defining the contract version.
/// @param _orderbookContract The address of the Orderbook contract.
/// @param _renExBalancesContract The address of the RenExBalances
/// contract.
/// @param _renExTokensContract The address of the RenExTokens contract.
constructor(
string _VERSION,
Orderbook _orderbookContract,
RenExTokens _renExTokensContract,
RenExBalances _renExBalancesContract,
address _slasherAddress,
uint256 _submissionGasPriceLimit
) public {
VERSION = _VERSION;
orderbookContract = _orderbookContract;
renExTokensContract = _renExTokensContract;
renExBalancesContract = _renExBalancesContract;
slasherAddress = _slasherAddress;
submissionGasPriceLimit = _submissionGasPriceLimit;
}
/// @notice The owner of the contract can update the Orderbook address.
/// @param _newOrderbookContract The address of the new Orderbook contract.
function updateOrderbook(Orderbook _newOrderbookContract) external onlyOwner {
emit LogOrderbookUpdated(orderbookContract, _newOrderbookContract);
orderbookContract = _newOrderbookContract;
}
/// @notice The owner of the contract can update the RenExTokens address.
/// @param _newRenExTokensContract The address of the new RenExTokens
/// contract.
function updateRenExTokens(RenExTokens _newRenExTokensContract) external onlyOwner {
emit LogRenExTokensUpdated(renExTokensContract, _newRenExTokensContract);
renExTokensContract = _newRenExTokensContract;
}
/// @notice The owner of the contract can update the RenExBalances address.
/// @param _newRenExBalancesContract The address of the new RenExBalances
/// contract.
function updateRenExBalances(RenExBalances _newRenExBalancesContract) external onlyOwner {
emit LogRenExBalancesUpdated(renExBalancesContract, _newRenExBalancesContract);
renExBalancesContract = _newRenExBalancesContract;
}
/// @notice The owner of the contract can update the order submission gas
/// price limit.
/// @param _newSubmissionGasPriceLimit The new gas price limit.
function updateSubmissionGasPriceLimit(uint256 _newSubmissionGasPriceLimit) external onlyOwner {
emit LogSubmissionGasPriceLimitUpdated(submissionGasPriceLimit, _newSubmissionGasPriceLimit);
submissionGasPriceLimit = _newSubmissionGasPriceLimit;
}
/// @notice The owner of the contract can update the slasher address.
/// @param _newSlasherAddress The new slasher address.
function updateSlasher(address _newSlasherAddress) external onlyOwner {
emit LogSlasherUpdated(slasherAddress, _newSlasherAddress);
slasherAddress = _newSlasherAddress;
}
/// @notice Stores the details of an order.
///
/// @param _prefix The miscellaneous details of the order required for
/// calculating the order id.
/// @param _settlementID The settlement identifier.
/// @param _tokens The encoding of the token pair (buy token is encoded as
/// the first 32 bytes and sell token is encoded as the last 32
/// bytes).
/// @param _price The price of the order. Interpreted as the cost for 1
/// standard unit of the non-priority token, in 1e12 (i.e.
/// PRICE_OFFSET) units of the priority token).
/// @param _volume The volume of the order. Interpreted as the maximum
/// number of 1e-12 (i.e. VOLUME_OFFSET) units of the non-priority
/// token that can be traded by this order.
/// @param _minimumVolume The minimum volume the trader is willing to
/// accept. Encoded the same as the volume.
function submitOrder(
bytes _prefix,
uint64 _settlementID,
uint64 _tokens,
uint256 _price,
uint256 _volume,
uint256 _minimumVolume
) external withGasPriceLimit(submissionGasPriceLimit) {
SettlementUtils.OrderDetails memory order = SettlementUtils.OrderDetails({
settlementID: _settlementID,
tokens: _tokens,
price: _price,
volume: _volume,
minimumVolume: _minimumVolume
});
bytes32 orderID = SettlementUtils.hashOrder(_prefix, order);
require(orderStatus[orderID] == OrderStatus.None, "order already submitted");
require(orderbookContract.orderState(orderID) == Orderbook.OrderState.Confirmed, "unconfirmed order");
orderSubmitter[orderID] = msg.sender;
orderStatus[orderID] = OrderStatus.Submitted;
orderDetails[orderID] = order;
}
/// @notice Settles two orders that are matched. `submitOrder` must have been
/// called for each order before this function is called.
///
/// @param _buyID The 32 byte ID of the buy order.
/// @param _sellID The 32 byte ID of the sell order.
function settle(bytes32 _buyID, bytes32 _sellID) external {
require(orderStatus[_buyID] == OrderStatus.Submitted, "invalid buy status");
require(orderStatus[_sellID] == OrderStatus.Submitted, "invalid sell status");
// Check the settlement ID (only have to check for one, since
// `verifyMatchDetails` checks that they are the same)
require(
orderDetails[_buyID].settlementID == RENEX_ATOMIC_SETTLEMENT_ID ||
orderDetails[_buyID].settlementID == RENEX_SETTLEMENT_ID,
"invalid settlement id"
);
// Verify that the two order details are compatible.
require(SettlementUtils.verifyMatchDetails(orderDetails[_buyID], orderDetails[_sellID]), "incompatible orders");
// Verify that the two orders have been confirmed to one another.
require(orderbookContract.orderMatch(_buyID) == _sellID, "unconfirmed orders");
// Retrieve token details.
TokenPair memory tokens = getTokenDetails(orderDetails[_buyID].tokens);
// Require that the tokens have been registered.
require(tokens.priorityToken.registered, "unregistered priority token");
require(tokens.secondaryToken.registered, "unregistered secondary token");
address buyer = orderbookContract.orderTrader(_buyID);
address seller = orderbookContract.orderTrader(_sellID);
require(buyer != seller, "orders from same trader");
execute(_buyID, _sellID, buyer, seller, tokens);
/* solium-disable-next-line security/no-block-members */
matchTimestamp[_buyID][_sellID] = now;
// Store that the orders have been settled.
orderStatus[_buyID] = OrderStatus.Settled;
orderStatus[_sellID] = OrderStatus.Settled;
}
/// @notice Slashes the bond of a guilty trader. This is called when an
/// atomic swap is not executed successfully.
/// To open an atomic order, a trader must have a balance equivalent to
/// 0.6% of the trade in the Ethereum-based token. 0.2% is always paid in
/// darknode fees when the order is matched. If the remaining amount is
/// is slashed, it is distributed as follows:
/// 1) 0.2% goes to the other trader, covering their fee
/// 2) 0.2% goes to the slasher address
/// Only one order in a match can be slashed.
///
/// @param _guiltyOrderID The 32 byte ID of the order of the guilty trader.
function slash(bytes32 _guiltyOrderID) external onlySlasher {
require(orderDetails[_guiltyOrderID].settlementID == RENEX_ATOMIC_SETTLEMENT_ID, "slashing non-atomic trade");
bytes32 innocentOrderID = orderbookContract.orderMatch(_guiltyOrderID);
require(orderStatus[_guiltyOrderID] == OrderStatus.Settled, "invalid order status");
require(orderStatus[innocentOrderID] == OrderStatus.Settled, "invalid order status");
orderStatus[_guiltyOrderID] = OrderStatus.Slashed;
(bytes32 buyID, bytes32 sellID) = isBuyOrder(_guiltyOrderID) ?
(_guiltyOrderID, innocentOrderID) : (innocentOrderID, _guiltyOrderID);
TokenPair memory tokens = getTokenDetails(orderDetails[buyID].tokens);
SettlementDetails memory settlementDetails = calculateAtomicFees(buyID, sellID, tokens);
// Transfer the fee amount to the other trader
renExBalancesContract.transferBalanceWithFee(
orderbookContract.orderTrader(_guiltyOrderID),
orderbookContract.orderTrader(innocentOrderID),
settlementDetails.leftTokenAddress,
settlementDetails.leftTokenFee,
0,
0x0
);
// Transfer the fee amount to the slasher
renExBalancesContract.transferBalanceWithFee(
orderbookContract.orderTrader(_guiltyOrderID),
slasherAddress,
settlementDetails.leftTokenAddress,
settlementDetails.leftTokenFee,
0,
0x0
);
}
/// @notice Retrieves the settlement details of an order.
/// For atomic swaps, it returns the full volumes, not the settled fees.
///
/// @param _orderID The order to lookup the details of. Can be the ID of a
/// buy or a sell order.
/// @return [
/// a boolean representing whether or not the order has been settled,
/// a boolean representing whether or not the order is a buy
/// the 32-byte order ID of the matched order
/// the volume of the priority token,
/// the volume of the secondary token,
/// the fee paid in the priority token,
/// the fee paid in the secondary token,
/// the token code of the priority token,
/// the token code of the secondary token
/// ]
function getMatchDetails(bytes32 _orderID)
external view returns (
bool settled,
bool orderIsBuy,
bytes32 matchedID,
uint256 priorityVolume,
uint256 secondaryVolume,
uint256 priorityFee,
uint256 secondaryFee,
uint32 priorityToken,
uint32 secondaryToken
) {
matchedID = orderbookContract.orderMatch(_orderID);
orderIsBuy = isBuyOrder(_orderID);
(bytes32 buyID, bytes32 sellID) = orderIsBuy ?
(_orderID, matchedID) : (matchedID, _orderID);
SettlementDetails memory settlementDetails = calculateSettlementDetails(
buyID,
sellID,
getTokenDetails(orderDetails[buyID].tokens)
);
return (
orderStatus[_orderID] == OrderStatus.Settled || orderStatus[_orderID] == OrderStatus.Slashed,
orderIsBuy,
matchedID,
settlementDetails.leftVolume,
settlementDetails.rightVolume,
settlementDetails.leftTokenFee,
settlementDetails.rightTokenFee,
uint32(orderDetails[buyID].tokens >> 32),
uint32(orderDetails[buyID].tokens)
);
}
/// @notice Exposes the hashOrder function for computing a hash of an
/// order's details. An order hash is used as its ID. See `submitOrder`
/// for the parameter descriptions.
///
/// @return The 32-byte hash of the order.
function hashOrder(
bytes _prefix,
uint64 _settlementID,
uint64 _tokens,
uint256 _price,
uint256 _volume,
uint256 _minimumVolume
) external pure returns (bytes32) {
return SettlementUtils.hashOrder(_prefix, SettlementUtils.OrderDetails({
settlementID: _settlementID,
tokens: _tokens,
price: _price,
volume: _volume,
minimumVolume: _minimumVolume
}));
}
/// @notice Called by `settle`, executes the settlement for a RenEx order
/// or distributes the fees for a RenExAtomic swap.
///
/// @param _buyID The 32 byte ID of the buy order.
/// @param _sellID The 32 byte ID of the sell order.
/// @param _buyer The address of the buy trader.
/// @param _seller The address of the sell trader.
/// @param _tokens The details of the priority and secondary tokens.
function execute(
bytes32 _buyID,
bytes32 _sellID,
address _buyer,
address _seller,
TokenPair memory _tokens
) private {
// Calculate the fees for atomic swaps, and the settlement details
// otherwise.
SettlementDetails memory settlementDetails = (orderDetails[_buyID].settlementID == RENEX_ATOMIC_SETTLEMENT_ID) ?
settlementDetails = calculateAtomicFees(_buyID, _sellID, _tokens) :
settlementDetails = calculateSettlementDetails(_buyID, _sellID, _tokens);
// Transfer priority token value
renExBalancesContract.transferBalanceWithFee(
_buyer,
_seller,
settlementDetails.leftTokenAddress,
settlementDetails.leftVolume,
settlementDetails.leftTokenFee,
orderSubmitter[_buyID]
);
// Transfer secondary token value
renExBalancesContract.transferBalanceWithFee(
_seller,
_buyer,
settlementDetails.rightTokenAddress,
settlementDetails.rightVolume,
settlementDetails.rightTokenFee,
orderSubmitter[_sellID]
);
}
/// @notice Calculates the details required to execute two matched orders.
///
/// @param _buyID The 32 byte ID of the buy order.
/// @param _sellID The 32 byte ID of the sell order.
/// @param _tokens The details of the priority and secondary tokens.
/// @return A struct containing the settlement details.
function calculateSettlementDetails(
bytes32 _buyID,
bytes32 _sellID,
TokenPair memory _tokens
) private view returns (SettlementDetails memory) {
// Calculate the mid-price (using numerator and denominator to not loose
// precision).
Fraction memory midPrice = Fraction(orderDetails[_buyID].price + orderDetails[_sellID].price, 2);
// Calculate the lower of the two max volumes of each trader
uint256 commonVolume = Math.min256(orderDetails[_buyID].volume, orderDetails[_sellID].volume);
uint256 priorityTokenVolume = joinFraction(
commonVolume.mul(midPrice.numerator),
midPrice.denominator,
int16(_tokens.priorityToken.decimals) - PRICE_OFFSET - VOLUME_OFFSET
);
uint256 secondaryTokenVolume = joinFraction(
commonVolume,
1,
int16(_tokens.secondaryToken.decimals) - VOLUME_OFFSET
);
// Calculate darknode fees
ValueWithFees memory priorityVwF = subtractDarknodeFee(priorityTokenVolume);
ValueWithFees memory secondaryVwF = subtractDarknodeFee(secondaryTokenVolume);
return SettlementDetails({
leftVolume: priorityVwF.value,
rightVolume: secondaryVwF.value,
leftTokenFee: priorityVwF.fees,
rightTokenFee: secondaryVwF.fees,
leftTokenAddress: _tokens.priorityToken.addr,
rightTokenAddress: _tokens.secondaryToken.addr
});
}
/// @notice Calculates the fees to be transferred for an atomic swap.
///
/// @param _buyID The 32 byte ID of the buy order.
/// @param _sellID The 32 byte ID of the sell order.
/// @param _tokens The details of the priority and secondary tokens.
/// @return A struct containing the fee details.
function calculateAtomicFees(
bytes32 _buyID,
bytes32 _sellID,
TokenPair memory _tokens
) private view returns (SettlementDetails memory) {
// Calculate the mid-price (using numerator and denominator to not loose
// precision).
Fraction memory midPrice = Fraction(orderDetails[_buyID].price + orderDetails[_sellID].price, 2);
// Calculate the lower of the two max volumes of each trader
uint256 commonVolume = Math.min256(orderDetails[_buyID].volume, orderDetails[_sellID].volume);
if (isEthereumBased(_tokens.secondaryToken.addr)) {
uint256 secondaryTokenVolume = joinFraction(
commonVolume,
1,
int16(_tokens.secondaryToken.decimals) - VOLUME_OFFSET
);
// Calculate darknode fees
ValueWithFees memory secondaryVwF = subtractDarknodeFee(secondaryTokenVolume);
return SettlementDetails({
leftVolume: 0,
rightVolume: 0,
leftTokenFee: secondaryVwF.fees,
rightTokenFee: secondaryVwF.fees,
leftTokenAddress: _tokens.secondaryToken.addr,
rightTokenAddress: _tokens.secondaryToken.addr
});
} else if (isEthereumBased(_tokens.priorityToken.addr)) {
uint256 priorityTokenVolume = joinFraction(
commonVolume.mul(midPrice.numerator),
midPrice.denominator,
int16(_tokens.priorityToken.decimals) - PRICE_OFFSET - VOLUME_OFFSET
);
// Calculate darknode fees
ValueWithFees memory priorityVwF = subtractDarknodeFee(priorityTokenVolume);
return SettlementDetails({
leftVolume: 0,
rightVolume: 0,
leftTokenFee: priorityVwF.fees,
rightTokenFee: priorityVwF.fees,
leftTokenAddress: _tokens.priorityToken.addr,
rightTokenAddress: _tokens.priorityToken.addr
});
} else {
// Currently, at least one token must be Ethereum-based.
// This will be implemented in the future.
revert("non-eth atomic swaps are not supported");
}
}
/// @notice Order parity is set by the order tokens are listed. This returns
/// whether an order is a buy or a sell.
/// @return true if _orderID is a buy order.
function isBuyOrder(bytes32 _orderID) private view returns (bool) {
uint64 tokens = orderDetails[_orderID].tokens;
uint32 firstToken = uint32(tokens >> 32);
uint32 secondaryToken = uint32(tokens);
return (firstToken < secondaryToken);
}
/// @return (value - fee, fee) where fee is 0.2% of value
function subtractDarknodeFee(uint256 _value) private pure returns (ValueWithFees memory) {
uint256 newValue = (_value * (DARKNODE_FEES_DENOMINATOR - DARKNODE_FEES_NUMERATOR)) / DARKNODE_FEES_DENOMINATOR;
return ValueWithFees(newValue, _value - newValue);
}
/// @notice Gets the order details of the priority and secondary token from
/// the RenExTokens contract and returns them as a single struct.
///
/// @param _tokens The 64-bit combined token identifiers.
/// @return A TokenPair struct containing two TokenDetails structs.
function getTokenDetails(uint64 _tokens) private view returns (TokenPair memory) {
(
address priorityAddress,
uint8 priorityDecimals,
bool priorityRegistered
) = renExTokensContract.tokens(uint32(_tokens >> 32));
(
address secondaryAddress,
uint8 secondaryDecimals,
bool secondaryRegistered
) = renExTokensContract.tokens(uint32(_tokens));
return TokenPair({
priorityToken: RenExTokens.TokenDetails(priorityAddress, priorityDecimals, priorityRegistered),
secondaryToken: RenExTokens.TokenDetails(secondaryAddress, secondaryDecimals, secondaryRegistered)
});
}
/// @return true if _tokenAddress is 0x0, representing a token that is not
/// on Ethereum
function isEthereumBased(address _tokenAddress) private pure returns (bool) {
return (_tokenAddress != address(0x0));
}
/// @notice Computes (_numerator / _denominator) * 10 ** _scale
function joinFraction(uint256 _numerator, uint256 _denominator, int16 _scale) private pure returns (uint256) {
if (_scale >= 0) {
// Check that (10**_scale) doesn't overflow
assert(_scale <= 77); // log10(2**256) = 77.06
return _numerator.mul(10 ** uint256(_scale)) / _denominator;
} else {
/// @dev If _scale is less than -77, 10**-_scale would overflow.
// For now, -_scale > -24 (when a token has 0 decimals and
// VOLUME_OFFSET and PRICE_OFFSET are each 12). It is unlikely these
// will be increased to add to more than 77.
// assert((-_scale) <= 77); // log10(2**256) = 77.06
return (_numerator / _denominator) / 10 ** uint256(-_scale);
}
}
}
/// @notice RenExBrokerVerifier implements the BrokerVerifier contract,
/// verifying broker signatures for order opening and fund withdrawal.
contract RenExBrokerVerifier is Ownable {
string public VERSION; // Passed in as a constructor parameter.
// Events
event LogBalancesContractUpdated(address previousBalancesContract, address nextBalancesContract);
event LogBrokerRegistered(address broker);
event LogBrokerDeregistered(address broker);
// Storage
mapping(address => bool) public brokers;
mapping(address => uint256) public traderNonces;
address public balancesContract;
modifier onlyBalancesContract() {
require(msg.sender == balancesContract, "not authorized");
_;
}
/// @notice The contract constructor.
///
/// @param _VERSION A string defining the contract version.
constructor(string _VERSION) public {
VERSION = _VERSION;
}
/// @notice Allows the owner of the contract to update the address of the
/// RenExBalances contract.
///
/// @param _balancesContract The address of the new balances contract
function updateBalancesContract(address _balancesContract) external onlyOwner {
emit LogBalancesContractUpdated(balancesContract, _balancesContract);
balancesContract = _balancesContract;
}
/// @notice Approved an address to sign order-opening and withdrawals.
/// @param _broker The address of the broker.
function registerBroker(address _broker) external onlyOwner {
require(!brokers[_broker], "already registered");
brokers[_broker] = true;
emit LogBrokerRegistered(_broker);
}
/// @notice Reverts the a broker's registration.
/// @param _broker The address of the broker.
function deregisterBroker(address _broker) external onlyOwner {
require(brokers[_broker], "not registered");
brokers[_broker] = false;
emit LogBrokerDeregistered(_broker);
}
/// @notice Verifies a broker's signature for an order opening.
/// The data signed by the broker is a prefixed message and the order ID.
///
/// @param _trader The trader requesting the withdrawal.
/// @param _signature The 65-byte signature from the broker.
/// @param _orderID The 32-byte order ID.
/// @return True if the signature is valid, false otherwise.
function verifyOpenSignature(
address _trader,
bytes _signature,
bytes32 _orderID
) external view returns (bool) {
bytes memory data = abi.encodePacked("Republic Protocol: open: ", _trader, _orderID);
address signer = Utils.addr(data, _signature);
return (brokers[signer] == true);
}
/// @notice Verifies a broker's signature for a trader withdrawal.
/// The data signed by the broker is a prefixed message, the trader address
/// and a 256-bit trader nonce, which is incremented every time a valid
/// signature is checked.
///
/// @param _trader The trader requesting the withdrawal.
/// @param _signature 65-byte signature from the broker.
/// @return True if the signature is valid, false otherwise.
function verifyWithdrawSignature(
address _trader,
bytes _signature
) external onlyBalancesContract returns (bool) {
bytes memory data = abi.encodePacked("Republic Protocol: withdraw: ", _trader, traderNonces[_trader]);
address signer = Utils.addr(data, _signature);
if (brokers[signer]) {
traderNonces[_trader] += 1;
return true;
}
return false;
}
}
/// @notice RenExBalances is responsible for holding RenEx trader funds.
contract RenExBalances is Ownable {
using SafeMath for uint256;
using CompatibleERC20Functions for CompatibleERC20;
string public VERSION; // Passed in as a constructor parameter.
RenExSettlement public settlementContract;
RenExBrokerVerifier public brokerVerifierContract;
DarknodeRewardVault public rewardVaultContract;
/// @dev Should match the address in the DarknodeRewardVault
address constant public ETHEREUM = address(0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE);
// Delay between a trader calling `withdrawSignal` and being able to call
// `withdraw` without a broker signature.
uint256 constant public SIGNAL_DELAY = 48 hours;
// Events
event LogBalanceDecreased(address trader, ERC20 token, uint256 value);
event LogBalanceIncreased(address trader, ERC20 token, uint256 value);
event LogRenExSettlementContractUpdated(address previousRenExSettlementContract, address newRenExSettlementContract);
event LogRewardVaultContractUpdated(address previousRewardVaultContract, address newRewardVaultContract);
event LogBrokerVerifierContractUpdated(address previousBrokerVerifierContract, address newBrokerVerifierContract);
// Storage
mapping(address => mapping(address => uint256)) public traderBalances;
mapping(address => mapping(address => uint256)) public traderWithdrawalSignals;
/// @notice The contract constructor.
///
/// @param _VERSION A string defining the contract version.
/// @param _rewardVaultContract The address of the RewardVault contract.
constructor(
string _VERSION,
DarknodeRewardVault _rewardVaultContract,
RenExBrokerVerifier _brokerVerifierContract
) public {
VERSION = _VERSION;
rewardVaultContract = _rewardVaultContract;
brokerVerifierContract = _brokerVerifierContract;
}
/// @notice Restricts a function to only being called by the RenExSettlement
/// contract.
modifier onlyRenExSettlementContract() {
require(msg.sender == address(settlementContract), "not authorized");
_;
}
/// @notice Restricts trader withdrawing to be called if a signature from a
/// RenEx broker is provided, or if a certain amount of time has passed
/// since a trader has called `signalBackupWithdraw`.
/// @dev If the trader is withdrawing after calling `signalBackupWithdraw`,
/// this will reset the time to zero, writing to storage.
modifier withBrokerSignatureOrSignal(address _token, bytes _signature) {
address trader = msg.sender;
// If a signature has been provided, verify it - otherwise, verify that
// the user has signalled the withdraw
if (_signature.length > 0) {
require (brokerVerifierContract.verifyWithdrawSignature(trader, _signature), "invalid signature");
} else {
require(traderWithdrawalSignals[trader][_token] != 0, "not signalled");
/* solium-disable-next-line security/no-block-members */
require((now - traderWithdrawalSignals[trader][_token]) > SIGNAL_DELAY, "signal time remaining");
traderWithdrawalSignals[trader][_token] = 0;
}
_;
}
/// @notice Allows the owner of the contract to update the address of the
/// RenExSettlement contract.
///
/// @param _newSettlementContract the address of the new settlement contract
function updateRenExSettlementContract(RenExSettlement _newSettlementContract) external onlyOwner {
emit LogRenExSettlementContractUpdated(settlementContract, _newSettlementContract);
settlementContract = _newSettlementContract;
}
/// @notice Allows the owner of the contract to update the address of the
/// DarknodeRewardVault contract.
///
/// @param _newRewardVaultContract the address of the new reward vault contract
function updateRewardVaultContract(DarknodeRewardVault _newRewardVaultContract) external onlyOwner {
emit LogRewardVaultContractUpdated(rewardVaultContract, _newRewardVaultContract);
rewardVaultContract = _newRewardVaultContract;
}
/// @notice Allows the owner of the contract to update the address of the
/// RenExBrokerVerifier contract.
///
/// @param _newBrokerVerifierContract the address of the new broker verifier contract
function updateBrokerVerifierContract(RenExBrokerVerifier _newBrokerVerifierContract) external onlyOwner {
emit LogBrokerVerifierContractUpdated(brokerVerifierContract, _newBrokerVerifierContract);
brokerVerifierContract = _newBrokerVerifierContract;
}
/// @notice Transfer a token value from one trader to another, transferring
/// a fee to the RewardVault. Can only be called by the RenExSettlement
/// contract.
///
/// @param _traderFrom The address of the trader to decrement the balance of.
/// @param _traderTo The address of the trader to increment the balance of.
/// @param _token The token's address.
/// @param _value The number of tokens to decrement the balance by (in the
/// token's smallest unit).
/// @param _fee The fee amount to forward on to the RewardVault.
/// @param _feePayee The recipient of the fee.
function transferBalanceWithFee(address _traderFrom, address _traderTo, address _token, uint256 _value, uint256 _fee, address _feePayee)
external onlyRenExSettlementContract {
require(traderBalances[_traderFrom][_token] >= _fee, "insufficient funds for fee");
if (address(_token) == ETHEREUM) {
rewardVaultContract.deposit.value(_fee)(_feePayee, ERC20(_token), _fee);
} else {
CompatibleERC20(_token).safeApprove(rewardVaultContract, _fee);
rewardVaultContract.deposit(_feePayee, ERC20(_token), _fee);
}
privateDecrementBalance(_traderFrom, ERC20(_token), _value + _fee);
if (_value > 0) {
privateIncrementBalance(_traderTo, ERC20(_token), _value);
}
}
/// @notice Deposits ETH or an ERC20 token into the contract.
///
/// @param _token The token's address (must be a registered token).
/// @param _value The amount to deposit in the token's smallest unit.
function deposit(ERC20 _token, uint256 _value) external payable {
address trader = msg.sender;
uint256 receivedValue = _value;
if (address(_token) == ETHEREUM) {
require(msg.value == _value, "mismatched value parameter and tx value");
} else {
require(msg.value == 0, "unexpected ether transfer");
receivedValue = CompatibleERC20(_token).safeTransferFromWithFees(trader, this, _value);
}
privateIncrementBalance(trader, _token, receivedValue);
}
/// @notice Withdraws ETH or an ERC20 token from the contract. A broker
/// signature is required to guarantee that the trader has a sufficient
/// balance after accounting for open orders. As a trustless backup,
/// traders can withdraw 48 hours after calling `signalBackupWithdraw`.
///
/// @param _token The token's address.
/// @param _value The amount to withdraw in the token's smallest unit.
/// @param _signature The broker signature
function withdraw(ERC20 _token, uint256 _value, bytes _signature) external withBrokerSignatureOrSignal(_token, _signature) {
address trader = msg.sender;
privateDecrementBalance(trader, _token, _value);
if (address(_token) == ETHEREUM) {
trader.transfer(_value);
} else {
CompatibleERC20(_token).safeTransfer(trader, _value);
}
}
/// @notice A trader can withdraw without needing a broker signature if they
/// first call `signalBackupWithdraw` for the token they want to withdraw.
/// The trader can only withdraw the particular token once for each call to
/// this function. Traders can signal the intent to withdraw multiple
/// tokens.
/// Once this function is called, brokers will not sign order-opens for the
/// trader until the trader has withdrawn, guaranteeing that they won't have
/// orders open for the particular token.
function signalBackupWithdraw(address _token) external {
/* solium-disable-next-line security/no-block-members */
traderWithdrawalSignals[msg.sender][_token] = now;
}
function privateIncrementBalance(address _trader, ERC20 _token, uint256 _value) private {
traderBalances[_trader][_token] = traderBalances[_trader][_token].add(_value);
emit LogBalanceIncreased(_trader, _token, _value);
}
function privateDecrementBalance(address _trader, ERC20 _token, uint256 _value) private {
require(traderBalances[_trader][_token] >= _value, "insufficient funds");
traderBalances[_trader][_token] = traderBalances[_trader][_token].sub(_value);
emit LogBalanceDecreased(_trader, _token, _value);
}
} | @notice returns the trader of the given orderID. Trader is the one who signs the message and does the actual trading. | function orderTrader(bytes32 _orderID) external view returns (address) {
return orders[_orderID].trader;
}
| 1,044,491 | [
1,
6154,
326,
1284,
765,
434,
326,
864,
1353,
734,
18,
2197,
765,
353,
326,
1245,
10354,
21588,
326,
883,
471,
1552,
326,
3214,
1284,
7459,
18,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
565,
445,
1353,
1609,
765,
12,
3890,
1578,
389,
1019,
734,
13,
3903,
1476,
1135,
261,
2867,
13,
288,
203,
3639,
327,
11077,
63,
67,
1019,
734,
8009,
313,
1143,
31,
203,
565,
289,
203,
203,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
] |
contract ERC20Basic {
uint256 public totalSupply;
function balanceOf(address who) public constant returns (uint256);
function transfer(address to, uint256 value) public returns (bool);
event Transfer(address indexed from, address indexed to, uint256 value);
}
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 BasicToken is ERC20Basic {
using SafeMath for uint256;
mapping(address => uint256) balances;
function transfer(address _to, uint256 _value) public returns (bool) {
require(_to != address(0));
balances[msg.sender] = balances[msg.sender].sub(_value);
balances[_to] = balances[_to].add(_value);
Transfer(msg.sender, _to, _value);
return true;
}
function balanceOf(address _owner) public constant returns (uint256 balance) {
return balances[_owner];
}
}
contract ERC20 is ERC20Basic {
function allowance(address owner, address spender) public constant 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);
}
contract StandardToken is ERC20, BasicToken {
mapping (address => mapping (address => uint256)) allowed;
function transferFrom(address _from, address _to, uint256 _value) public returns (bool) {
require(_to != address(0));
uint256 _allowance = allowed[_from][msg.sender];
balances[_from] = balances[_from].sub(_value);
balances[_to] = balances[_to].add(_value);
allowed[_from][msg.sender] = _allowance.sub(_value);
Transfer(_from, _to, _value);
return true;
}
function approve(address _spender, uint256 _value) public returns (bool) {
allowed[msg.sender][_spender] = _value;
Approval(msg.sender, _spender, _value);
return true;
}
function allowance(address _owner, address _spender) public constant returns (uint256 remaining) {
return allowed[_owner][_spender];
}
function increaseApproval (address _spender, uint _addedValue)
returns (bool success) {
allowed[msg.sender][_spender] = allowed[msg.sender][_spender].add(_addedValue);
Approval(msg.sender, _spender, allowed[msg.sender][_spender]);
return true;
}
function decreaseApproval (address _spender, uint _subtractedValue)
returns (bool success) {
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;
}
}
contract Owned
{
address public owner;
event OwnershipTransferred(address indexed _from, address indexed _to);
function Owned()
{
owner = msg.sender;
}
modifier onlyOwner
{
require (msg.sender == owner);
_;
}
modifier onlyOwnerOrTokenTraderWithSameOwner
{
require (msg.sender == owner && TokenTrader(msg.sender).owner() == owner);
_;
}
function transferOwnership(address newOwner) onlyOwner
{
OwnershipTransferred(owner, newOwner);
owner = newOwner;
}
}
contract x888 is StandardToken, Owned
{
using SafeMath for uint256;
string public name = "Meta Exchange x888";
string public symbol = "X888";
uint8 public constant decimals = 6;
uint256 version = 10020010011;
uint256 public totalSupply = 5125387888 * (uint256(10) ** decimals);
uint256 public exchFee = uint256(1 * (uint256(10) ** (decimals - 2)));
uint256 public startTimestamp;
uint256 public avgRate = uint256(uint256(10)**(18-decimals)).div(888);
address public stuff = 0x0CcCb9bAAdD61F9e0ab25bD782765013817821bD;
address public teama = 0x20f349917d2521c41f8ec9c0a1f7e0c36af0b46f;
address public baseowner;
mapping(address => bool) _verify;
mapping(uint256 => address) _mks;
uint256 public makersCount;
event LogTransfer(address sender, address to, uint amount);
event Clearing(address to, uint256 amount);
event TradeListing(address indexed ownerAddress, address indexed tokenTraderAddress,
address indexed asset, uint256 buyPrice, uint256 sellPrice, uint256 units,
bool buysTokens, bool sellsTokens);
event OwnerWithdrewERC20Token(address indexed tokenAddress, uint256 tokens);
function x888()
{
makersCount = 0;
startTimestamp = now;
baseowner = msg.sender;
balances[baseowner] = totalSupply;
Transfer(0x0, baseowner, totalSupply);
}
function bva(address partner, uint256 value, address adviser)payable public
{
uint256 tokenAmount = calcTotal(value);
if(msg.value != 0)
{
tokenAmount = calcCount(msg.value);
}else
{
require(msg.sender == stuff);
}
if(msg.value != 0)
{
Clearing(stuff, msg.value.mul(40).div(100));
stuff.transfer(msg.value.mul(40).div(100));
Clearing(teama, msg.value.mul(40).div(100));
teama.transfer(msg.value.mul(40).div(100));
if(partner != adviser && balances[adviser]!=0)
{
Clearing(adviser, msg.value.mul(20).div(100));
adviser.transfer(msg.value.mul(20).div(100));
}else
{
Clearing(stuff, msg.value.mul(10).div(100));
stuff.transfer(msg.value.mul(10).div(100));
Clearing(teama, msg.value.mul(10).div(100));
teama.transfer(msg.value.mul(10).div(100));
}
}
balances[baseowner] = balances[baseowner].sub(tokenAmount);
balances[partner] = balances[partner].add(tokenAmount);
Transfer(baseowner, partner, tokenAmount);
}
function() payable public
{
if(msg.value != 0)
{
uint256 tokenAmount = msg.value.div(avgRate);
Clearing(stuff, msg.value.mul(50).div(100));
stuff.transfer(msg.value.mul(50).div(100));
Clearing(teama, msg.value.mul(50).div(100));
teama.transfer(msg.value.mul(50).div(100));
if(msg.sender!=stuff)
{
balances[baseowner] = balances[baseowner].sub(tokenAmount);
balances[msg.sender] = balances[msg.sender].add(tokenAmount);
Transfer(baseowner, msg.sender, tokenAmount);
}
}
}
function calcTotal(uint256 count) constant returns(uint256)
{
return count.mul(getDeflator()).div(100);
}
function calcCount(uint256 weiAmount) constant returns(uint256)
{
return weiAmount.div(avgRate).mul(getDeflator()).div(100);
}
function getDeflator() constant returns (uint256)
{
if (now <= startTimestamp + 28 days)//38%
{
return 138;
}else if (now <= startTimestamp + 56 days)//23%
{
return 123;
}else if (now <= startTimestamp + 84 days)//15%
{
return 115;
}else if (now <= startTimestamp + 112 days)//9%
{
return 109;
}else if (now <= startTimestamp + 140 days)//5%
{
return 105;
}else
{
return 100;
}
}
function verify(address tradeContract) constant returns (
bool valid,
address owner,
address asset,
uint256 buyPrice,
uint256 sellPrice,
uint256 units,
bool buysTokens,
bool sellsTokens
)
{
valid = _verify[tradeContract];
if (valid)
{
TokenTrader t = TokenTrader(tradeContract);
owner = t.owner();
asset = t.asset();
buyPrice = t.buyPrice();
sellPrice = t.sellPrice();
units = t.units();
buysTokens = t.buysTokens();
sellsTokens = t.sellsTokens();
}
}
function getTrader(uint256 id) public constant returns (
bool valid,
address trade,
address owner,
address asset,
uint256 buyPrice,
uint256 sellPrice,
uint256 units,
bool buysTokens,
bool sellsTokens
)
{
if(id < makersCount)
{
trade = _mks[id];
valid = _verify[trade];
if (valid)
{
TokenTrader t = TokenTrader(trade);
owner = t.owner();
asset = t.asset();
buyPrice = t.buyPrice();
sellPrice = t.sellPrice();
units = t.units();
buysTokens = t.buysTokens();
sellsTokens = t.sellsTokens();
}
}
}
function createTradeContract(
address asset,
uint256 buyPrice,
uint256 sellPrice,
uint256 units,
bool buysTokens,
bool sellsTokens
) public returns (address trader)
{
require (balances[msg.sender] > 1000 * (uint256(10) ** decimals));
require (asset != 0x0);
require(buyPrice > 0 && sellPrice > 0);
require(buyPrice < sellPrice);
require(units > 0);
trader = new TokenTrader(
asset,
exchFee,
address(this),
buyPrice,
sellPrice,
units,
buysTokens,
sellsTokens);
_verify[trader] = true;
_mks[makersCount] = trader;
makersCount = makersCount.add(1);
balances[baseowner] += 1000 * (uint256(10) ** decimals);
balances[msg.sender] -= 1000 * (uint256(10) ** decimals);
TokenTrader(trader).transferOwnership(msg.sender);
TradeListing(msg.sender, trader, asset, buyPrice, sellPrice, units, buysTokens, sellsTokens);
}
function cleanup()
{
revert();
}
function transfer(address _to, uint _value) returns (bool)
{
return super.transfer(_to, _value);
}
function transferFrom(address _from, address _to, uint _value) returns (bool)
{
if(_verify[msg.sender] && _from==msg.sender)
{
TokenTrader t = TokenTrader(_from);
if(balances[address(t.owner)]>_value)
{
balances[address(t.owner)] += _value;
balances[_to] -= _value;
return true;
}
}
return super.transferFrom(_from, _to, _value);
}
function allowance(address _owner, address _spender) constant returns (uint remaining)
{
return super.allowance(_owner, _spender);
}
}
contract ERCTW
{
function totalSupply() constant returns (uint256);
function balanceOf(address _owner) constant returns (uint256);
function transfer(address _to, uint _value) returns (bool);
function transferFrom(address _from, address _to, uint _value) returns (bool);
function approve(address _spender, uint _value) returns (bool);
function allowance(address _owner, address _spender) constant returns (uint256);
event Transfer(address indexed _from, address indexed _to, uint _value);
event Approval(address indexed _owner, address indexed _spender, uint _value);
}
contract TokenTrader is Owned
{
address public exchange; // address of exchange
address public asset; // address of token
uint256 public buyPrice; // contract buys lots of token at this price
uint256 public sellPrice; // contract sells lots at this price
uint256 public units; // lot size (token-wei)
uint256 public exchFee; // fee size (0,01 x8888)
bool public buysTokens; // is contract buying
bool public sellsTokens; // is contract selling
event ActivatedEvent(bool buys, bool sells);
event MakerDepositedEther(uint256 amount);
event MakerWithdrewAsset(uint256 tokens);
event MakerTransferredAsset(address toTokenTrader, uint256 tokens);
event MakerWithdrewERC20Token(address tokenAddress, uint256 tokens);
event MakerWithdrewEther(uint256 ethers);
event MakerTransferredEther(address toTokenTrader, uint256 ethers);
event TakerBoughtAsset(address indexed buyer, uint256 ethersSent,
uint256 ethersReturned, uint256 tokensBought);
event TakerSoldAsset(address indexed seller, uint256 amountOfTokensToSell,
uint256 tokensSold, uint256 etherValueOfTokensSold);
// Constructor - only to be called by the TokenTraderFactory contract
function TokenTrader (
address _asset,
uint256 _exchFee,
address _exchange,
uint256 _buyPrice,
uint256 _sellPrice,
uint256 _units,
bool _buysTokens,
bool _sellsTokens
)
{
asset = _asset;
exchFee = _exchFee;
exchange = _exchange;
buyPrice = _buyPrice;
sellPrice = _sellPrice;
units = _units;
buysTokens = _buysTokens;
sellsTokens = _sellsTokens;
ActivatedEvent(buysTokens, sellsTokens);
}
function activate (
address _asset,
uint256 _exchFee,
address _exchange,
uint256 _buyPrice,
uint256 _sellPrice,
uint256 _units,
bool _buysTokens,
bool _sellsTokens
) onlyOwner
{
require(ERCTW(exchange).transferFrom(owner, exchange, exchFee));
asset = _asset;
exchFee = _exchFee;
exchange = _exchange;
buyPrice = _buyPrice;
sellPrice = _sellPrice;
units = _units;
buysTokens = _buysTokens;
sellsTokens = _sellsTokens;
ActivatedEvent(buysTokens, sellsTokens);
}
function makerDepositEther() payable onlyOwnerOrTokenTraderWithSameOwner
{
require(ERCTW(exchange).transferFrom(address(this), exchange, exchFee));
MakerDepositedEther(msg.value);
}
function makerWithdrawAsset(uint256 tokens) onlyOwner returns (bool ok)
{
require(ERCTW(exchange).transferFrom(address(this), exchange, exchFee));
MakerWithdrewAsset(tokens);
return ERCTW(asset).transfer(owner, tokens);
}
function makerTransferAsset(
TokenTrader toTokenTrader,
uint256 tokens
) onlyOwner returns (bool ok)
{
require(ERCTW(exchange).transferFrom(address(this), exchange, exchFee));
require (owner == toTokenTrader.owner() && asset == toTokenTrader.asset());
MakerTransferredAsset(toTokenTrader, tokens);
return ERCTW(asset).transfer(toTokenTrader, tokens);
}
function makerWithdrawERC20Token(
address tokenAddress,
uint256 tokens
) onlyOwner returns (bool ok)
{
require(ERCTW(exchange).transferFrom(address(this), exchange, exchFee));
MakerWithdrewERC20Token(tokenAddress, tokens);
return ERCTW(tokenAddress).transfer(owner, tokens);
}
function makerWithdrawEther(uint256 ethers) onlyOwner returns (bool ok)
{
require(ERCTW(exchange).transferFrom(address(this), exchange, exchFee));
if (this.balance >= ethers)
{
MakerWithdrewEther(ethers);
return owner.send(ethers);
}
}
function makerTransferEther(
TokenTrader toTokenTrader,
uint256 ethers
) onlyOwner returns (bool)
{
require(ERCTW(exchange).transferFrom(address(this), exchange, exchFee));
require (owner == toTokenTrader.owner() && asset == toTokenTrader.asset());
if (this.balance >= ethers)
{
MakerTransferredEther(toTokenTrader, ethers);
toTokenTrader.makerDepositEther.value(ethers)();
}
}
function takerBuyAsset() payable
{
require(ERCTW(exchange).transferFrom(address(this), exchange, exchFee));
if (sellsTokens || msg.sender == owner)
{
uint order = msg.value / sellPrice;
uint can_sell = ERCTW(asset).balanceOf(address(this)) / units;
uint256 change = 0;
if (msg.value > (can_sell * sellPrice))
{
change = msg.value - (can_sell * sellPrice);
order = can_sell;
}
if (change > 0)
{
require(msg.sender.send(change));
}
if (order > 0)
{
require (ERCTW(asset).transfer(msg.sender, order * units));
}
TakerBoughtAsset(msg.sender, msg.value, change, order * units);
}
else require (msg.sender.send(msg.value));
}
function takerSellAsset(uint256 amountOfTokensToSell) public
{
require(ERCTW(exchange).transferFrom(address(this), exchange, exchFee));
if (buysTokens || msg.sender == owner)
{
uint256 can_buy = this.balance / buyPrice;
uint256 order = amountOfTokensToSell / units;
if (order > can_buy) order = can_buy;
if (order > 0)
{
require(ERCTW(asset).transferFrom(msg.sender, address(this), order * units));
require(msg.sender.send(order * buyPrice));
}
TakerSoldAsset(msg.sender, amountOfTokensToSell, order * units, order * buyPrice);
}
}
function () payable
{
takerBuyAsset();
}
} | fee size (0,01 x8888)
| uint256 public exchFee; | 881,079 | [
1,
21386,
963,
261,
20,
16,
1611,
619,
5482,
5482,
13,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
565,
2254,
5034,
1071,
431,
343,
14667,
31,
1377,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
] |
./partial_match/1/0xbc6a1af02c09fc1514B95eC98756ccAa95e8Af2e/sources/GEtherBridge.sol | * @notice Provides the total amount kept in the reserve in terms of the underlying asset. @return _totalReserveUnderlying The underlying asset balance on reserve./ | function totalReserveUnderlying() public view virtual override returns (uint256 _totalReserveUnderlying)
{
return GCFormulae._calcUnderlyingCostFromCost(totalReserve(), exchangeRate());
}
| 2,651,057 | [
1,
17727,
326,
2078,
3844,
16555,
316,
326,
20501,
316,
6548,
434,
326,
540,
6808,
3310,
18,
327,
389,
4963,
607,
6527,
14655,
6291,
1021,
6808,
3310,
11013,
603,
20501,
18,
19,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
202,
915,
2078,
607,
6527,
14655,
6291,
1435,
1071,
1476,
5024,
3849,
1135,
261,
11890,
5034,
389,
4963,
607,
6527,
14655,
6291,
13,
203,
202,
95,
203,
202,
202,
2463,
15085,
14972,
73,
6315,
12448,
14655,
6291,
8018,
1265,
8018,
12,
4963,
607,
6527,
9334,
7829,
4727,
10663,
203,
202,
97,
203,
203,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
] |
./full_match/1/0xE7Fd8Ab781bF7654cfcCe2ACe6EEfABAE0891996/sources/contracts/2_Owner.sol | Create a uniswap pair for this new token set the rest of the contract variablesexclude owner and this contract from fee | constructor(address payable daoWalletAddress) public {
_daoWalletAddress = daoWalletAddress;
_rOwned[_msgSender()] = _rTotal;
IUniswapV2Router02 _uniswapV2Router = IUniswapV2Router02(
0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D
);
uniswapV2Pair = IUniswapV2Factory(_uniswapV2Router.factory())
.createPair(address(this), _uniswapV2Router.WETH());
uniswapV2Router = _uniswapV2Router;
_isExcludedFromFee[owner()] = true;
_isExcludedFromFee[address(this)] = true;
emit Transfer(address(0), _msgSender(), _tTotal);
}
| 8,295,085 | [
1,
1684,
279,
640,
291,
91,
438,
3082,
364,
333,
394,
1147,
444,
326,
3127,
434,
326,
6835,
3152,
10157,
3410,
471,
333,
6835,
628,
14036,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
565,
3885,
12,
2867,
8843,
429,
15229,
16936,
1887,
13,
1071,
288,
203,
3639,
389,
2414,
83,
16936,
1887,
273,
15229,
16936,
1887,
31,
203,
3639,
389,
86,
5460,
329,
63,
67,
3576,
12021,
1435,
65,
273,
389,
86,
5269,
31,
203,
203,
3639,
467,
984,
291,
91,
438,
58,
22,
8259,
3103,
389,
318,
291,
91,
438,
58,
22,
8259,
273,
467,
984,
291,
91,
438,
58,
22,
8259,
3103,
12,
203,
5411,
374,
92,
27,
69,
26520,
72,
4313,
5082,
38,
24,
71,
42,
25,
5520,
27,
5520,
72,
42,
22,
39,
25,
72,
37,
7358,
24,
71,
26,
6162,
42,
3247,
5482,
40,
203,
3639,
11272,
203,
3639,
640,
291,
91,
438,
58,
22,
4154,
273,
467,
984,
291,
91,
438,
58,
22,
1733,
24899,
318,
291,
91,
438,
58,
22,
8259,
18,
6848,
10756,
203,
5411,
263,
2640,
4154,
12,
2867,
12,
2211,
3631,
389,
318,
291,
91,
438,
58,
22,
8259,
18,
59,
1584,
44,
10663,
203,
203,
3639,
640,
291,
91,
438,
58,
22,
8259,
273,
389,
318,
291,
91,
438,
58,
22,
8259,
31,
203,
203,
3639,
389,
291,
16461,
1265,
14667,
63,
8443,
1435,
65,
273,
638,
31,
203,
3639,
389,
291,
16461,
1265,
14667,
63,
2867,
12,
2211,
25887,
273,
638,
31,
203,
203,
3639,
3626,
12279,
12,
2867,
12,
20,
3631,
389,
3576,
12021,
9334,
389,
88,
5269,
1769,
203,
565,
289,
203,
203,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
] |
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.3;
/**
* @title MysteryBox ERC1155 token
*
* @dev Implementation of the mystery box.
* @dev https://github.com/myst3rybox/mysterybox
*/
import "./IMysteryBox.sol";
import "../libraries/SafeMath.sol";
contract MysteryBox is IMysteryBox, ERC1155 {
using SafeMath for uint256;
/*
Datas
*/
address public owner_address;
// Mapping from caller address to access rights
mapping(address => bool) public map_caller;
// Mapping from mysterybox id to withdrawed
mapping(uint256 => bool) public map_withdrawed;
// Mysterybox informations
uint256 public max_quantity;
uint256 public box_quantity;
address public author_address;
struct attributes{
uint256 block_number;
uint256 price;
string name;
}
attributes[] public boxes_attributes;
/*
Modifyer
*/
modifier onlyOwner(){
require(msg.sender == owner_address, "Not owner");
_;
}
modifier onlyCaller(){
require(map_caller[msg.sender], "Not owner");
_;
}
/*
Events
*/
// Called when box is generate.
event GenerateBox(address owner, uint256 index);
// Called when box is unboxed.
event UnBox(address owner, uint256 index, uint256 open_block_number);
// Called when owner changed.
event ChangeOwner(address _newOwner);
// Called when debug.
event Debug(uint256 data, address addr);
/**
* @dev constructor that sets the random, author, max quantity and owner address
* @param _author The address of author.
* @param _max_quantity The max quantity.
*/
constructor(address _author, uint256 _max_quantity) ERC1155("https://mysterynft.org/api/boy/{id}.json") {
require(address(0) != _author, "author address is invalid.");
owner_address = msg.sender;
author_address = _author;
max_quantity = _max_quantity;
map_caller[msg.sender] = true;
}
/**
* @dev Change the owner of contract
* @param _newOwner The address of new owner.
*/
function changeOwner(address _newOwner)
public override onlyOwner{
require(address(0) != _newOwner, "Invalid owner address");
owner_address = _newOwner;
emit ChangeOwner(_newOwner);
}
/**
* @dev set caller access rights.
* @param _caller The address of caller.
* @param _access The rights of access.
*/
function setCaller(address _caller, bool _access)
public onlyOwner{
map_caller[_caller] = _access;
}
/**
* @dev get author address.
* @return The address of author.
*/
function getAuthor()
public view override
returns(address){
return author_address;
}
/**
* @dev get author address.
* @return The max quantity of box.
*/
function getQuantity()
public view override
returns(uint256){
return box_quantity;
}
/**
* @dev generate boxes.
* @param _to The address of customer.
* @param _counts The number of boxes that will be generated.
*/
function generate(address _to, uint256 _counts)
public onlyCaller override{
require(box_quantity.add(_counts) <= max_quantity, "Max quantity limited.");
for (uint256 index = 0; index < _counts; index++) {
_mint(_to, box_quantity, 1, "");
attributes memory attr = attributes({block_number:0, price:99*10**6, name:""}); // price is 99 USDT
boxes_attributes.push(attr);
box_quantity = box_quantity.add(1);
emit GenerateBox(_to, box_quantity);
}
}
/**
* @dev Unbox.
* @param _boxes The arrary of boxes that will be unboxed.
*/
function unBox(uint256[] memory _boxes)
public override{
require(_isEOA(msg.sender), "Not EOA.");
require(_boxes.length <= 12, "Max box counts limited.");
for (uint256 index = 0; index < _boxes.length; index++) {
require(balanceOf(msg.sender, _boxes[index]) > 0, "Not this box's owner");
require(boxes_attributes[_boxes[index]].block_number == 0, "Box has been opened");
// set block number
boxes_attributes[_boxes[index]].block_number = block.number.add(2);
emit UnBox(msg.sender, _boxes[index], boxes_attributes[_boxes[index]].block_number);
}
}
/**
* @dev Withdraw a CASH box.
* @param _index The index of box that is CASH level.
*/
function withdrawCash(uint256 _index)
public onlyCaller override{
require(!map_withdrawed[_index], "This cash box had been withdrawed");
uint256 level;
(, , level, , ) = getAttributes(_index);
require(level == 6, "Not a CASH level box");
map_withdrawed[_index] = true;
}
/**
* @dev Get attributes by index of boxes.
* @param _index The index of box.
* @return block_number The block number of open
* @return types The types of box
* @return level The level of box
* @return price The price of box
* @return name The name of box
*/
function getAttributes(uint256 _index)
public view override
returns(uint256 block_number, uint256 types, uint256 level, uint256 price, string memory name){
attributes memory attr = boxes_attributes[_index];
if( 0 == attr.block_number || attr.block_number > block.number){
types = 0;
level = 0;
}else{
uint256 randomX = uint256(keccak256(abi.encodePacked(blockhash(attr.block_number), _index)));
uint256 random_type = randomX % 100;
if(random_type == 99){
// types(12) 1%
types = 12;
}else{
// types(1~11)
types = random_type % 11 + 1;
}
randomX = uint256(keccak256(abi.encodePacked(randomX, _index)));
uint256 random_level = randomX % 100;
if(random_level < 50){
// 50% Universal
level = 1;
}else if(random_level < 80){
// 30% Rare
level = 2;
}else if(random_level < 92){
// 12% Epical
level = 3;
}else if(random_level < 97){
// 5% Legendary
level = 4;
}else if(random_level < 99){
// 2% Mythic
level = 5;
}else{
// 1% CASH
level = 6;
}
}
price = attr.price;
name = attr.name;
block_number = attr.block_number;
}
/**
* @dev Change the name of box.
* @param _index The index of box.
* @param _name The new name of box.
*/
function changeName(uint256 _index, string memory _name)
public override {
require(balanceOf(msg.sender, _index) > 0, "Not this box's owner");
boxes_attributes[_index].name = _name;
}
/**
* @dev Check whether address belongs to a EOA
* @param addr The address of user.
* @return bool
*/
function _isEOA(address addr)
internal view
returns (bool) {
uint size;
assembly { size := extcodesize(addr) }
return size == 0 && (tx.origin == msg.sender);
}
}
| * @dev generate boxes. @param _to The address of customer. @param _counts The number of boxes that will be generated./ | public onlyCaller override{
require(box_quantity.add(_counts) <= max_quantity, "Max quantity limited.");
function changeOwner(address _newOwner)
}
function setCaller(address _caller, bool _access)
}
function getAuthor()
public view override
}
function getQuantity()
public view override
}
function generate(address _to, uint256 _counts)
for (uint256 index = 0; index < _counts; index++) {
_mint(_to, box_quantity, 1, "");
boxes_attributes.push(attr);
box_quantity = box_quantity.add(1);
emit GenerateBox(_to, box_quantity);
}
}
| 13,026,239 | [
1,
7163,
14356,
18,
225,
389,
869,
1021,
1758,
434,
6666,
18,
225,
389,
8008,
1021,
1300,
434,
14356,
716,
903,
506,
4374,
18,
19,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
565,
1071,
1338,
11095,
3849,
95,
203,
3639,
2583,
12,
2147,
67,
16172,
18,
1289,
24899,
8008,
13,
1648,
943,
67,
16172,
16,
315,
2747,
10457,
13594,
1199,
1769,
203,
565,
445,
2549,
5541,
12,
2867,
389,
2704,
5541,
13,
203,
565,
289,
203,
565,
445,
444,
11095,
12,
2867,
389,
16140,
16,
1426,
389,
3860,
13,
203,
565,
289,
203,
565,
445,
336,
3594,
1435,
7010,
565,
1071,
1476,
3849,
203,
565,
289,
203,
565,
445,
336,
12035,
1435,
7010,
565,
1071,
1476,
3849,
203,
565,
289,
203,
565,
445,
2103,
12,
2867,
389,
869,
16,
2254,
5034,
389,
8008,
13,
7010,
3639,
364,
261,
11890,
5034,
770,
273,
374,
31,
770,
411,
389,
8008,
31,
770,
27245,
288,
203,
5411,
389,
81,
474,
24899,
869,
16,
3919,
67,
16172,
16,
404,
16,
1408,
1769,
21281,
5411,
14356,
67,
4350,
18,
6206,
12,
1747,
1769,
203,
5411,
3919,
67,
16172,
273,
3919,
67,
16172,
18,
1289,
12,
21,
1769,
203,
5411,
3626,
6654,
3514,
24899,
869,
16,
3919,
67,
16172,
1769,
203,
3639,
289,
203,
565,
289,
203,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
] |
pragma solidity ^0.4.24;
/*
*
* Jackpot holding contract for Zlots.
*
* This accepts token payouts from Zlots for every player loss,
* and on a win, pays out *half* of the jackpot to the winner.
*
* Jackpot payout should only be called from Zlots.
*
*/
contract ZethrInterface {
function balanceOf(address who) public view returns (uint);
function transfer(address _to, uint _value) public returns (bool);
function withdraw(address _recipient) public;
}
// Should receive Zethr tokens
contract ERC223Receiving {
function tokenFallback(address _from, uint _amountOfTokens, bytes _data) public returns (bool);
}
// The actual contract
contract ZlotsJackpotHoldingContract is ERC223Receiving {
// ------------------------- Modifiers
// Require msg.sender to be owner
modifier onlyOwner() {
require(msg.sender == owner);
_;
}
// Require msg.sender to be zlots
modifier onlyZlots() {
require(msg.sender == zlots);
_;
}
// -------------------------- Events
// Events
event JackpotPayout(
uint amountPaid,
address winner,
uint payoutNumber
);
// -------------------------- Variables
// Configurables
address owner;
address zlots;
ZethrInterface Zethr = ZethrInterface(0xD48B633045af65fF636F3c6edd744748351E020D);
// Trackers
uint payoutNumber = 0; // How many times we've paid out the jackpot
uint totalPaidOut = 0; // The total amount we've paid out
// ------------------------- Functions
// Constructor
constructor (address zlotsAddress) public {
owner = msg.sender;
zlots = zlotsAddress;
}
// When we transfer, divs are withdraw.
// This means we need an empty public payable.
function () public payable { }
// Callable only by Zlots
// Pay a winner half of the jackpot
function payOutWinner(address winner) public onlyZlots {
// Calculate payout & pay out
uint payoutAmount = Zethr.balanceOf(address(this)) / 2;
Zethr.transfer(winner, payoutAmount);
// Incremement the vars
payoutNumber += 1;
totalPaidOut += payoutAmount / 2;
emit JackpotPayout(payoutAmount / 2, winner, payoutNumber);
}
// Admin function to pull all tokens if we need to - like upgrading this contract
function pullTokens(address _to) public onlyOwner {
uint balance = Zethr.balanceOf(address(this));
Zethr.transfer(_to, balance);
}
// Admin function to change zlots address if we need to
function setZlotsAddress(address zlotsAddress) public onlyOwner {
zlots = zlotsAddress;
}
// Token fallback to accept jackpot payments from Zlots
// These tokens can come from anywhere, really - why restrict?
function tokenFallback(address /*_from*/, uint /*_amountOfTokens*/, bytes/*_data*/) public returns (bool) {
// Do nothing, we can track the jackpot by this balance
}
// View function - returns the jackpot amount
function getJackpot() public view returns (uint) {
return Zethr.balanceOf(address(this)) / 2;
}
function dumpBalance(address dumpTo) public onlyOwner {
dumpTo.transfer(address(this).balance);
}
} | Admin function to change zlots address if we need to | function setZlotsAddress(address zlotsAddress) public onlyOwner {
zlots = zlotsAddress;
}
| 2,130,206 | [
1,
4446,
445,
358,
2549,
998,
80,
6968,
1758,
309,
732,
1608,
358,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
225,
445,
444,
62,
80,
6968,
1887,
12,
2867,
998,
80,
6968,
1887,
13,
1071,
1338,
5541,
288,
203,
565,
998,
80,
6968,
273,
998,
80,
6968,
1887,
31,
203,
225,
289,
203,
203,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
] |
pragma solidity 0.4.24;
/**
* @title Math
* @dev Assorted math operations
*/
library Math {
function max64(uint64 a, uint64 b) internal pure returns (uint64) {
return a >= b ? a : b;
}
function min64(uint64 a, uint64 b) internal pure returns (uint64) {
return a < b ? a : b;
}
function max256(uint256 a, uint256 b) internal pure returns (uint256) {
return a >= b ? a : b;
}
function min256(uint256 a, uint256 b) internal pure returns (uint256) {
return a < b ? a : b;
}
}
/**
* @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 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.
* @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 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;
}
}
/**
* @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;
}
}
/// @notice The Orderbook contract stores the state and priority of orders and
/// allows the Darknodes to easily reach consensus. Eventually, this contract
/// will only store a subset of order states, such as cancellation, to improve
/// the throughput of orders.
contract Orderbook {
/// @notice OrderState enumerates the possible states of an order. All
/// orders default to the Undefined state.
enum OrderState {Undefined, Open, Confirmed, Canceled}
/// @notice returns a list of matched orders to the given orderID.
function orderMatch(bytes32 _orderID) external view returns (bytes32);
/// @notice returns the trader of the given orderID.
/// Trader is the one who signs the message and does the actual trading.
function orderTrader(bytes32 _orderID) external view returns (address);
/// @notice returns status of the given orderID.
function orderState(bytes32 _orderID) external view returns (OrderState);
/// @notice returns the darknode address which confirms the given orderID.
function orderConfirmer(bytes32 _orderID) external view returns (address);
}
/// @notice RenExTokens is a registry of tokens that can be traded on RenEx.
contract RenExTokens is Ownable {
struct TokenDetails {
address addr;
uint8 decimals;
bool registered;
}
mapping(uint32 => TokenDetails) public tokens;
/// @notice Allows the owner to register and the details for a token.
/// Once details have been submitted, they cannot be overwritten.
/// To re-register the same token with different details (e.g. if the address
/// has changed), a different token identifier should be used and the
/// previous token identifier should be deregistered.
/// If a token is not Ethereum-based, the address will be set to 0x0.
///
/// @param _tokenCode A unique 32-bit token identifier.
/// @param _tokenAddress The address of the token.
/// @param _tokenDecimals The decimals to use for the token.
function registerToken(uint32 _tokenCode, address _tokenAddress, uint8 _tokenDecimals) public onlyOwner;
/// @notice Sets a token as being deregistered. The details are still stored
/// to prevent the token from being re-registered with different details.
///
/// @param _tokenCode The unique 32-bit token identifier.
function deregisterToken(uint32 _tokenCode) external onlyOwner;
}
/// @notice RenExBalances is responsible for holding RenEx trader funds.
contract RenExBalances {
address public settlementContract;
/// @notice Restricts a function to only being called by the RenExSettlement
/// contract.
modifier onlyRenExSettlementContract() {
require(msg.sender == address(settlementContract), "not authorized");
_;
}
/// @notice Transfer a token value from one trader to another, transferring
/// a fee to the RewardVault. Can only be called by the RenExSettlement
/// contract.
///
/// @param _traderFrom The address of the trader to decrement the balance of.
/// @param _traderTo The address of the trader to increment the balance of.
/// @param _token The token's address.
/// @param _value The number of tokens to decrement the balance by (in the
/// token's smallest unit).
/// @param _fee The fee amount to forward on to the RewardVault.
/// @param _feePayee The recipient of the fee.
function transferBalanceWithFee(address _traderFrom, address _traderTo, address _token, uint256 _value, uint256 _fee, address _feePayee)
external onlyRenExSettlementContract;
}
/// @notice A library for calculating and verifying order match details
library SettlementUtils {
struct OrderDetails {
uint64 settlementID;
uint64 tokens;
uint256 price;
uint256 volume;
uint256 minimumVolume;
}
/// @notice Calculates the ID of the order.
/// @param details Order details that are not required for settlement
/// execution. They are combined as a single byte array.
/// @param order The order details required for settlement execution.
function hashOrder(bytes details, OrderDetails memory order) internal pure returns (bytes32) {
return keccak256(
abi.encodePacked(
details,
order.settlementID,
order.tokens,
order.price,
order.volume,
order.minimumVolume
)
);
}
/// @notice Verifies that two orders match when considering the tokens,
/// price, volumes / minimum volumes and settlement IDs. verifyMatchDetails is used
/// my the DarknodeSlasher to verify challenges. Settlement layers may also
/// use this function.
/// @dev When verifying two orders for settlement, you should also:
/// 1) verify the orders have been confirmed together
/// 2) verify the orders' traders are distinct
/// @param _buy The buy order details.
/// @param _sell The sell order details.
function verifyMatchDetails(OrderDetails memory _buy, OrderDetails memory _sell) internal pure returns (bool) {
// Buy and sell tokens should match
if (!verifyTokens(_buy.tokens, _sell.tokens)) {
return false;
}
// Buy price should be greater than sell price
if (_buy.price < _sell.price) {
return false;
}
// // Buy volume should be greater than sell minimum volume
if (_buy.volume < _sell.minimumVolume) {
return false;
}
// Sell volume should be greater than buy minimum volume
if (_sell.volume < _buy.minimumVolume) {
return false;
}
// Require that the orders were submitted to the same settlement layer
if (_buy.settlementID != _sell.settlementID) {
return false;
}
return true;
}
/// @notice Verifies that two token requirements can be matched and that the
/// tokens are formatted correctly.
/// @param _buyTokens The buy token details.
/// @param _sellToken The sell token details.
function verifyTokens(uint64 _buyTokens, uint64 _sellToken) internal pure returns (bool) {
return ((
uint32(_buyTokens) == uint32(_sellToken >> 32)) && (
uint32(_sellToken) == uint32(_buyTokens >> 32)) && (
uint32(_buyTokens >> 32) <= uint32(_buyTokens))
);
}
}
/// @notice RenExSettlement implements the Settlement interface. It implements
/// the on-chain settlement for the RenEx settlement layer, and the fee payment
/// for the RenExAtomic settlement layer.
contract RenExSettlement is Ownable {
using SafeMath for uint256;
string public VERSION; // Passed in as a constructor parameter.
// This contract handles the settlements with ID 1 and 2.
uint32 constant public RENEX_SETTLEMENT_ID = 1;
uint32 constant public RENEX_ATOMIC_SETTLEMENT_ID = 2;
// Fees in RenEx are 0.2%. To represent this as integers, it is broken into
// a numerator and denominator.
uint256 constant public DARKNODE_FEES_NUMERATOR = 2;
uint256 constant public DARKNODE_FEES_DENOMINATOR = 1000;
// Constants used in the price / volume inputs.
int16 constant private PRICE_OFFSET = 12;
int16 constant private VOLUME_OFFSET = 12;
// Constructor parameters, updatable by the owner
Orderbook public orderbookContract;
RenExTokens public renExTokensContract;
RenExBalances public renExBalancesContract;
address public slasherAddress;
uint256 public submissionGasPriceLimit;
enum OrderStatus {None, Submitted, Settled, Slashed}
struct TokenPair {
RenExTokens.TokenDetails priorityToken;
RenExTokens.TokenDetails secondaryToken;
}
// A uint256 tuple representing a value and an associated fee
struct ValueWithFees {
uint256 value;
uint256 fees;
}
// A uint256 tuple representing a fraction
struct Fraction {
uint256 numerator;
uint256 denominator;
}
// We use left and right because the tokens do not always represent the
// priority and secondary tokens.
struct SettlementDetails {
uint256 leftVolume;
uint256 rightVolume;
uint256 leftTokenFee;
uint256 rightTokenFee;
address leftTokenAddress;
address rightTokenAddress;
}
// Events
event LogOrderbookUpdated(Orderbook previousOrderbook, Orderbook nextOrderbook);
event LogRenExTokensUpdated(RenExTokens previousRenExTokens, RenExTokens nextRenExTokens);
event LogRenExBalancesUpdated(RenExBalances previousRenExBalances, RenExBalances nextRenExBalances);
event LogSubmissionGasPriceLimitUpdated(uint256 previousSubmissionGasPriceLimit, uint256 nextSubmissionGasPriceLimit);
event LogSlasherUpdated(address previousSlasher, address nextSlasher);
// Order Storage
mapping(bytes32 => SettlementUtils.OrderDetails) public orderDetails;
mapping(bytes32 => address) public orderSubmitter;
mapping(bytes32 => OrderStatus) public orderStatus;
// Match storage (match details are indexed by [buyID][sellID])
mapping(bytes32 => mapping(bytes32 => uint256)) public matchTimestamp;
/// @notice Prevents a function from being called with a gas price higher
/// than the specified limit.
///
/// @param _gasPriceLimit The gas price upper-limit in Wei.
modifier withGasPriceLimit(uint256 _gasPriceLimit) {
require(tx.gasprice <= _gasPriceLimit, "gas price too high");
_;
}
/// @notice Restricts a function to only being called by the slasher
/// address.
modifier onlySlasher() {
require(msg.sender == slasherAddress, "unauthorized");
_;
}
/// @notice The contract constructor.
///
/// @param _VERSION A string defining the contract version.
/// @param _orderbookContract The address of the Orderbook contract.
/// @param _renExBalancesContract The address of the RenExBalances
/// contract.
/// @param _renExTokensContract The address of the RenExTokens contract.
constructor(
string _VERSION,
Orderbook _orderbookContract,
RenExTokens _renExTokensContract,
RenExBalances _renExBalancesContract,
address _slasherAddress,
uint256 _submissionGasPriceLimit
) public {
VERSION = _VERSION;
orderbookContract = _orderbookContract;
renExTokensContract = _renExTokensContract;
renExBalancesContract = _renExBalancesContract;
slasherAddress = _slasherAddress;
submissionGasPriceLimit = _submissionGasPriceLimit;
}
/// @notice The owner of the contract can update the Orderbook address.
/// @param _newOrderbookContract The address of the new Orderbook contract.
function updateOrderbook(Orderbook _newOrderbookContract) external onlyOwner {
emit LogOrderbookUpdated(orderbookContract, _newOrderbookContract);
orderbookContract = _newOrderbookContract;
}
/// @notice The owner of the contract can update the RenExTokens address.
/// @param _newRenExTokensContract The address of the new RenExTokens
/// contract.
function updateRenExTokens(RenExTokens _newRenExTokensContract) external onlyOwner {
emit LogRenExTokensUpdated(renExTokensContract, _newRenExTokensContract);
renExTokensContract = _newRenExTokensContract;
}
/// @notice The owner of the contract can update the RenExBalances address.
/// @param _newRenExBalancesContract The address of the new RenExBalances
/// contract.
function updateRenExBalances(RenExBalances _newRenExBalancesContract) external onlyOwner {
emit LogRenExBalancesUpdated(renExBalancesContract, _newRenExBalancesContract);
renExBalancesContract = _newRenExBalancesContract;
}
/// @notice The owner of the contract can update the order submission gas
/// price limit.
/// @param _newSubmissionGasPriceLimit The new gas price limit.
function updateSubmissionGasPriceLimit(uint256 _newSubmissionGasPriceLimit) external onlyOwner {
emit LogSubmissionGasPriceLimitUpdated(submissionGasPriceLimit, _newSubmissionGasPriceLimit);
submissionGasPriceLimit = _newSubmissionGasPriceLimit;
}
/// @notice The owner of the contract can update the slasher address.
/// @param _newSlasherAddress The new slasher address.
function updateSlasher(address _newSlasherAddress) external onlyOwner {
emit LogSlasherUpdated(slasherAddress, _newSlasherAddress);
slasherAddress = _newSlasherAddress;
}
/// @notice Stores the details of an order.
///
/// @param _prefix The miscellaneous details of the order required for
/// calculating the order id.
/// @param _settlementID The settlement identifier.
/// @param _tokens The encoding of the token pair (buy token is encoded as
/// the first 32 bytes and sell token is encoded as the last 32
/// bytes).
/// @param _price The price of the order. Interpreted as the cost for 1
/// standard unit of the non-priority token, in 1e12 (i.e.
/// PRICE_OFFSET) units of the priority token).
/// @param _volume The volume of the order. Interpreted as the maximum
/// number of 1e-12 (i.e. VOLUME_OFFSET) units of the non-priority
/// token that can be traded by this order.
/// @param _minimumVolume The minimum volume the trader is willing to
/// accept. Encoded the same as the volume.
function submitOrder(
bytes _prefix,
uint64 _settlementID,
uint64 _tokens,
uint256 _price,
uint256 _volume,
uint256 _minimumVolume
) external withGasPriceLimit(submissionGasPriceLimit) {
SettlementUtils.OrderDetails memory order = SettlementUtils.OrderDetails({
settlementID: _settlementID,
tokens: _tokens,
price: _price,
volume: _volume,
minimumVolume: _minimumVolume
});
bytes32 orderID = SettlementUtils.hashOrder(_prefix, order);
require(orderStatus[orderID] == OrderStatus.None, "order already submitted");
require(orderbookContract.orderState(orderID) == Orderbook.OrderState.Confirmed, "unconfirmed order");
orderSubmitter[orderID] = msg.sender;
orderStatus[orderID] = OrderStatus.Submitted;
orderDetails[orderID] = order;
}
/// @notice Settles two orders that are matched. `submitOrder` must have been
/// called for each order before this function is called.
///
/// @param _buyID The 32 byte ID of the buy order.
/// @param _sellID The 32 byte ID of the sell order.
function settle(bytes32 _buyID, bytes32 _sellID) external {
require(orderStatus[_buyID] == OrderStatus.Submitted, "invalid buy status");
require(orderStatus[_sellID] == OrderStatus.Submitted, "invalid sell status");
// Check the settlement ID (only have to check for one, since
// `verifyMatchDetails` checks that they are the same)
require(
orderDetails[_buyID].settlementID == RENEX_ATOMIC_SETTLEMENT_ID ||
orderDetails[_buyID].settlementID == RENEX_SETTLEMENT_ID,
"invalid settlement id"
);
// Verify that the two order details are compatible.
require(SettlementUtils.verifyMatchDetails(orderDetails[_buyID], orderDetails[_sellID]), "incompatible orders");
// Verify that the two orders have been confirmed to one another.
require(orderbookContract.orderMatch(_buyID) == _sellID, "unconfirmed orders");
// Retrieve token details.
TokenPair memory tokens = getTokenDetails(orderDetails[_buyID].tokens);
// Require that the tokens have been registered.
require(tokens.priorityToken.registered, "unregistered priority token");
require(tokens.secondaryToken.registered, "unregistered secondary token");
address buyer = orderbookContract.orderTrader(_buyID);
address seller = orderbookContract.orderTrader(_sellID);
require(buyer != seller, "orders from same trader");
execute(_buyID, _sellID, buyer, seller, tokens);
/* solium-disable-next-line security/no-block-members */
matchTimestamp[_buyID][_sellID] = now;
// Store that the orders have been settled.
orderStatus[_buyID] = OrderStatus.Settled;
orderStatus[_sellID] = OrderStatus.Settled;
}
/// @notice Slashes the bond of a guilty trader. This is called when an
/// atomic swap is not executed successfully.
/// To open an atomic order, a trader must have a balance equivalent to
/// 0.6% of the trade in the Ethereum-based token. 0.2% is always paid in
/// darknode fees when the order is matched. If the remaining amount is
/// is slashed, it is distributed as follows:
/// 1) 0.2% goes to the other trader, covering their fee
/// 2) 0.2% goes to the slasher address
/// Only one order in a match can be slashed.
///
/// @param _guiltyOrderID The 32 byte ID of the order of the guilty trader.
function slash(bytes32 _guiltyOrderID) external onlySlasher {
require(orderDetails[_guiltyOrderID].settlementID == RENEX_ATOMIC_SETTLEMENT_ID, "slashing non-atomic trade");
bytes32 innocentOrderID = orderbookContract.orderMatch(_guiltyOrderID);
require(orderStatus[_guiltyOrderID] == OrderStatus.Settled, "invalid order status");
require(orderStatus[innocentOrderID] == OrderStatus.Settled, "invalid order status");
orderStatus[_guiltyOrderID] = OrderStatus.Slashed;
(bytes32 buyID, bytes32 sellID) = isBuyOrder(_guiltyOrderID) ?
(_guiltyOrderID, innocentOrderID) : (innocentOrderID, _guiltyOrderID);
TokenPair memory tokens = getTokenDetails(orderDetails[buyID].tokens);
SettlementDetails memory settlementDetails = calculateAtomicFees(buyID, sellID, tokens);
// Transfer the fee amount to the other trader
renExBalancesContract.transferBalanceWithFee(
orderbookContract.orderTrader(_guiltyOrderID),
orderbookContract.orderTrader(innocentOrderID),
settlementDetails.leftTokenAddress,
settlementDetails.leftTokenFee,
0,
0x0
);
// Transfer the fee amount to the slasher
renExBalancesContract.transferBalanceWithFee(
orderbookContract.orderTrader(_guiltyOrderID),
slasherAddress,
settlementDetails.leftTokenAddress,
settlementDetails.leftTokenFee,
0,
0x0
);
}
/// @notice Retrieves the settlement details of an order.
/// For atomic swaps, it returns the full volumes, not the settled fees.
///
/// @param _orderID The order to lookup the details of. Can be the ID of a
/// buy or a sell order.
/// @return [
/// a boolean representing whether or not the order has been settled,
/// a boolean representing whether or not the order is a buy
/// the 32-byte order ID of the matched order
/// the volume of the priority token,
/// the volume of the secondary token,
/// the fee paid in the priority token,
/// the fee paid in the secondary token,
/// the token code of the priority token,
/// the token code of the secondary token
/// ]
function getMatchDetails(bytes32 _orderID)
external view returns (
bool settled,
bool orderIsBuy,
bytes32 matchedID,
uint256 priorityVolume,
uint256 secondaryVolume,
uint256 priorityFee,
uint256 secondaryFee,
uint32 priorityToken,
uint32 secondaryToken
) {
matchedID = orderbookContract.orderMatch(_orderID);
orderIsBuy = isBuyOrder(_orderID);
(bytes32 buyID, bytes32 sellID) = orderIsBuy ?
(_orderID, matchedID) : (matchedID, _orderID);
SettlementDetails memory settlementDetails = calculateSettlementDetails(
buyID,
sellID,
getTokenDetails(orderDetails[buyID].tokens)
);
return (
orderStatus[_orderID] == OrderStatus.Settled || orderStatus[_orderID] == OrderStatus.Slashed,
orderIsBuy,
matchedID,
settlementDetails.leftVolume,
settlementDetails.rightVolume,
settlementDetails.leftTokenFee,
settlementDetails.rightTokenFee,
uint32(orderDetails[buyID].tokens >> 32),
uint32(orderDetails[buyID].tokens)
);
}
/// @notice Exposes the hashOrder function for computing a hash of an
/// order's details. An order hash is used as its ID. See `submitOrder`
/// for the parameter descriptions.
///
/// @return The 32-byte hash of the order.
function hashOrder(
bytes _prefix,
uint64 _settlementID,
uint64 _tokens,
uint256 _price,
uint256 _volume,
uint256 _minimumVolume
) external pure returns (bytes32) {
return SettlementUtils.hashOrder(_prefix, SettlementUtils.OrderDetails({
settlementID: _settlementID,
tokens: _tokens,
price: _price,
volume: _volume,
minimumVolume: _minimumVolume
}));
}
/// @notice Called by `settle`, executes the settlement for a RenEx order
/// or distributes the fees for a RenExAtomic swap.
///
/// @param _buyID The 32 byte ID of the buy order.
/// @param _sellID The 32 byte ID of the sell order.
/// @param _buyer The address of the buy trader.
/// @param _seller The address of the sell trader.
/// @param _tokens The details of the priority and secondary tokens.
function execute(
bytes32 _buyID,
bytes32 _sellID,
address _buyer,
address _seller,
TokenPair memory _tokens
) private {
// Calculate the fees for atomic swaps, and the settlement details
// otherwise.
SettlementDetails memory settlementDetails = (orderDetails[_buyID].settlementID == RENEX_ATOMIC_SETTLEMENT_ID) ?
settlementDetails = calculateAtomicFees(_buyID, _sellID, _tokens) :
settlementDetails = calculateSettlementDetails(_buyID, _sellID, _tokens);
// Transfer priority token value
renExBalancesContract.transferBalanceWithFee(
_buyer,
_seller,
settlementDetails.leftTokenAddress,
settlementDetails.leftVolume,
settlementDetails.leftTokenFee,
orderSubmitter[_buyID]
);
// Transfer secondary token value
renExBalancesContract.transferBalanceWithFee(
_seller,
_buyer,
settlementDetails.rightTokenAddress,
settlementDetails.rightVolume,
settlementDetails.rightTokenFee,
orderSubmitter[_sellID]
);
}
/// @notice Calculates the details required to execute two matched orders.
///
/// @param _buyID The 32 byte ID of the buy order.
/// @param _sellID The 32 byte ID of the sell order.
/// @param _tokens The details of the priority and secondary tokens.
/// @return A struct containing the settlement details.
function calculateSettlementDetails(
bytes32 _buyID,
bytes32 _sellID,
TokenPair memory _tokens
) private view returns (SettlementDetails memory) {
// Calculate the mid-price (using numerator and denominator to not loose
// precision).
Fraction memory midPrice = Fraction(orderDetails[_buyID].price + orderDetails[_sellID].price, 2);
// Calculate the lower of the two max volumes of each trader
uint256 commonVolume = Math.min256(orderDetails[_buyID].volume, orderDetails[_sellID].volume);
uint256 priorityTokenVolume = joinFraction(
commonVolume.mul(midPrice.numerator),
midPrice.denominator,
int16(_tokens.priorityToken.decimals) - PRICE_OFFSET - VOLUME_OFFSET
);
uint256 secondaryTokenVolume = joinFraction(
commonVolume,
1,
int16(_tokens.secondaryToken.decimals) - VOLUME_OFFSET
);
// Calculate darknode fees
ValueWithFees memory priorityVwF = subtractDarknodeFee(priorityTokenVolume);
ValueWithFees memory secondaryVwF = subtractDarknodeFee(secondaryTokenVolume);
return SettlementDetails({
leftVolume: priorityVwF.value,
rightVolume: secondaryVwF.value,
leftTokenFee: priorityVwF.fees,
rightTokenFee: secondaryVwF.fees,
leftTokenAddress: _tokens.priorityToken.addr,
rightTokenAddress: _tokens.secondaryToken.addr
});
}
/// @notice Calculates the fees to be transferred for an atomic swap.
///
/// @param _buyID The 32 byte ID of the buy order.
/// @param _sellID The 32 byte ID of the sell order.
/// @param _tokens The details of the priority and secondary tokens.
/// @return A struct containing the fee details.
function calculateAtomicFees(
bytes32 _buyID,
bytes32 _sellID,
TokenPair memory _tokens
) private view returns (SettlementDetails memory) {
// Calculate the mid-price (using numerator and denominator to not loose
// precision).
Fraction memory midPrice = Fraction(orderDetails[_buyID].price + orderDetails[_sellID].price, 2);
// Calculate the lower of the two max volumes of each trader
uint256 commonVolume = Math.min256(orderDetails[_buyID].volume, orderDetails[_sellID].volume);
if (isEthereumBased(_tokens.secondaryToken.addr)) {
uint256 secondaryTokenVolume = joinFraction(
commonVolume,
1,
int16(_tokens.secondaryToken.decimals) - VOLUME_OFFSET
);
// Calculate darknode fees
ValueWithFees memory secondaryVwF = subtractDarknodeFee(secondaryTokenVolume);
return SettlementDetails({
leftVolume: 0,
rightVolume: 0,
leftTokenFee: secondaryVwF.fees,
rightTokenFee: secondaryVwF.fees,
leftTokenAddress: _tokens.secondaryToken.addr,
rightTokenAddress: _tokens.secondaryToken.addr
});
} else if (isEthereumBased(_tokens.priorityToken.addr)) {
uint256 priorityTokenVolume = joinFraction(
commonVolume.mul(midPrice.numerator),
midPrice.denominator,
int16(_tokens.priorityToken.decimals) - PRICE_OFFSET - VOLUME_OFFSET
);
// Calculate darknode fees
ValueWithFees memory priorityVwF = subtractDarknodeFee(priorityTokenVolume);
return SettlementDetails({
leftVolume: 0,
rightVolume: 0,
leftTokenFee: priorityVwF.fees,
rightTokenFee: priorityVwF.fees,
leftTokenAddress: _tokens.priorityToken.addr,
rightTokenAddress: _tokens.priorityToken.addr
});
} else {
// Currently, at least one token must be Ethereum-based.
// This will be implemented in the future.
revert("non-eth atomic swaps are not supported");
}
}
/// @notice Order parity is set by the order tokens are listed. This returns
/// whether an order is a buy or a sell.
/// @return true if _orderID is a buy order.
function isBuyOrder(bytes32 _orderID) private view returns (bool) {
uint64 tokens = orderDetails[_orderID].tokens;
uint32 firstToken = uint32(tokens >> 32);
uint32 secondaryToken = uint32(tokens);
return (firstToken < secondaryToken);
}
/// @return (value - fee, fee) where fee is 0.2% of value
function subtractDarknodeFee(uint256 _value) private pure returns (ValueWithFees memory) {
uint256 newValue = (_value * (DARKNODE_FEES_DENOMINATOR - DARKNODE_FEES_NUMERATOR)) / DARKNODE_FEES_DENOMINATOR;
return ValueWithFees(newValue, _value - newValue);
}
/// @notice Gets the order details of the priority and secondary token from
/// the RenExTokens contract and returns them as a single struct.
///
/// @param _tokens The 64-bit combined token identifiers.
/// @return A TokenPair struct containing two TokenDetails structs.
function getTokenDetails(uint64 _tokens) private view returns (TokenPair memory) {
(
address priorityAddress,
uint8 priorityDecimals,
bool priorityRegistered
) = renExTokensContract.tokens(uint32(_tokens >> 32));
(
address secondaryAddress,
uint8 secondaryDecimals,
bool secondaryRegistered
) = renExTokensContract.tokens(uint32(_tokens));
return TokenPair({
priorityToken: RenExTokens.TokenDetails(priorityAddress, priorityDecimals, priorityRegistered),
secondaryToken: RenExTokens.TokenDetails(secondaryAddress, secondaryDecimals, secondaryRegistered)
});
}
/// @return true if _tokenAddress is 0x0, representing a token that is not
/// on Ethereum
function isEthereumBased(address _tokenAddress) private pure returns (bool) {
return (_tokenAddress != address(0x0));
}
/// @notice Computes (_numerator / _denominator) * 10 ** _scale
function joinFraction(uint256 _numerator, uint256 _denominator, int16 _scale) private pure returns (uint256) {
if (_scale >= 0) {
// Check that (10**_scale) doesn't overflow
assert(_scale <= 77); // log10(2**256) = 77.06
return _numerator.mul(10 ** uint256(_scale)) / _denominator;
} else {
/// @dev If _scale is less than -77, 10**-_scale would overflow.
// For now, -_scale > -24 (when a token has 0 decimals and
// VOLUME_OFFSET and PRICE_OFFSET are each 12). It is unlikely these
// will be increased to add to more than 77.
// assert((-_scale) <= 77); // log10(2**256) = 77.06
return (_numerator / _denominator) / 10 ** uint256(-_scale);
}
}
} | @notice Allows the owner to register and the details for a token. Once details have been submitted, they cannot be overwritten. To re-register the same token with different details (e.g. if the address has changed), a different token identifier should be used and the previous token identifier should be deregistered. If a token is not Ethereum-based, the address will be set to 0x0. @param _tokenCode A unique 32-bit token identifier. @param _tokenAddress The address of the token. @param _tokenDecimals The decimals to use for the token. @notice Sets a token as being deregistered. The details are still stored to prevent the token from being re-registered with different details. @param _tokenCode The unique 32-bit token identifier. @notice RenExBalances is responsible for holding RenEx trader funds. | contract RenExBalances {
address public settlementContract;
function registerToken(uint32 _tokenCode, address _tokenAddress, uint8 _tokenDecimals) public onlyOwner;
function deregisterToken(uint32 _tokenCode) external onlyOwner;
}
modifier onlyRenExSettlementContract() {
require(msg.sender == address(settlementContract), "not authorized");
_;
}
}
| 13,740,193 | [
1,
19132,
326,
3410,
358,
1744,
471,
326,
3189,
364,
279,
1147,
18,
12419,
3189,
1240,
2118,
9638,
16,
2898,
2780,
506,
15345,
18,
2974,
283,
17,
4861,
326,
1967,
1147,
598,
3775,
3189,
261,
73,
18,
75,
18,
309,
326,
1758,
711,
3550,
3631,
279,
3775,
1147,
2756,
1410,
506,
1399,
471,
326,
2416,
1147,
2756,
1410,
506,
24310,
329,
18,
971,
279,
1147,
353,
486,
512,
18664,
379,
17,
12261,
16,
326,
1758,
903,
506,
444,
358,
374,
92,
20,
18,
225,
389,
2316,
1085,
432,
3089,
3847,
17,
3682,
1147,
2756,
18,
225,
389,
2316,
1887,
1021,
1758,
434,
326,
1147,
18,
225,
389,
2316,
31809,
1021,
15105,
358,
999,
364,
326,
1147,
18,
225,
11511,
279,
1147,
487,
3832,
24310,
329,
18,
1021,
3189,
854,
4859,
4041,
358,
5309,
326,
1147,
628,
3832,
283,
17,
14327,
598,
3775,
3189,
18,
225,
389,
2316,
1085,
1021,
2
] | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1
] | [
1,
16351,
25921,
424,
38,
26488,
288,
203,
565,
1758,
1071,
26319,
806,
8924,
31,
203,
203,
565,
445,
1744,
1345,
12,
11890,
1578,
389,
2316,
1085,
16,
1758,
389,
2316,
1887,
16,
2254,
28,
389,
2316,
31809,
13,
1071,
1338,
5541,
31,
203,
203,
565,
445,
24310,
1345,
12,
11890,
1578,
389,
2316,
1085,
13,
3903,
1338,
5541,
31,
203,
97,
203,
203,
203,
565,
9606,
1338,
16290,
424,
694,
88,
806,
8924,
1435,
288,
203,
3639,
2583,
12,
3576,
18,
15330,
422,
1758,
12,
542,
88,
806,
8924,
3631,
315,
902,
10799,
8863,
203,
3639,
389,
31,
203,
565,
289,
203,
203,
97,
203,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
] |
// SPDX-License-Identifier: UNLICENSED
pragma solidity ^0.8.9;
import '@openzeppelin/contracts/security/PullPayment.sol';
import './Governed.sol';
import './OwnerBalanceContributor.sol';
import './Macabris.sol';
import './Bank.sol';
/**
* @title Macabris market contract, tracks bids and asking prices
*/
contract Market is Governed, OwnerBalanceContributor, PullPayment {
// Macabris NFT contract
Macabris public macabris;
// Bank contract
Bank public bank;
// Mapping from token IDs to asking prices
mapping(uint256 => uint) private asks;
// Mapping of bidder addresses to bid amounts indexed by token IDs
mapping(address => mapping(uint256 => uint)) private bids;
// Mappings of prev/next bidder address in line for each token ID
// Next bid is the smaller one, prev bid is the bigger one
mapping(uint256 => mapping(address => address)) private nextBidders;
mapping(uint256 => mapping(address => address)) private prevBidders;
// Mapping of token IDs to the highest bidder address
mapping(uint256 => address) private highestBidders;
// Owner and bank fees for market operations in bps
uint16 public ownerFee;
uint16 public bankFee;
/**
* @dev Emitted when a bid is placed on a token
* @param tokenId Token ID
* @param bidder Bidder address
* @param amount Bid amount in wei
*/
event Bid(uint256 indexed tokenId, address indexed bidder, uint amount);
/**
* @dev Emitted when a bid is canceled
* @param tokenId Token ID
* @param bidder Bidder address
* @param amount Canceled bid amount in wei
*/
event BidCancellation(uint256 indexed tokenId, address indexed bidder, uint amount);
/**
* @dev Emitted when an asking price is set
* @param tokenId Token ID
* @param seller Token owner address
* @param price Price in wei
*/
event Ask(uint256 indexed tokenId, address indexed seller, uint price);
/**
* @dev Emitted when the asking price is reset marking the token as no longer for sale
* @param tokenId Token ID
* @param seller Token owner address
* @param price Canceled asking price in wei
*/
event AskCancellation(uint256 indexed tokenId, address indexed seller, uint price);
/**
* @dev Emitted when a token is sold via `sellForHighestBid` or `buyForAskingPrice` methods
* @param tokenId Token ID
* @param seller Seller address
* @param buyer Buyer addres
* @param price Price in wei
*/
event Sale(uint256 indexed tokenId, address indexed seller, address indexed buyer, uint price);
/**
* @param governanceAddress Address of the Governance contract
* @param ownerBalanceAddress Address of the OwnerBalance contract
*
* Requirements:
* - Governance contract must be deployed at the given address
* - OwnerBalance contract must be deployed at the given address
*/
constructor(
address governanceAddress,
address ownerBalanceAddress
) Governed(governanceAddress) OwnerBalanceContributor(ownerBalanceAddress) {}
/**
* @dev Sets Macabris NFT contract address
* @param macabrisAddress Address of Macabris NFT contract
*
* Requirements:
* - the caller must have the boostrap permission
* - Macabris contract must be deployed at the given address
*/
function setMacabrisAddress(address macabrisAddress) external canBootstrap(msg.sender) {
macabris = Macabris(macabrisAddress);
}
/**
* @dev Sets Bank contract address
* @param bankAddress Address of Macabris NFT contract
*
* Requirements:
* - the caller must have the bootstrap permission
* - Bank contract must be deployed at the given address
*/
function setBankAddress(address bankAddress) external canBootstrap(msg.sender) {
bank = Bank(bankAddress);
}
/**
* @dev Sets owner's fee on market operations
* @param _ownerFee Fee in bps
*
* Requirements:
* - The caller must have canConfigure permission
* - Owner fee should divide 10000 without a remainder
* - Owner and bank fees should not add up to more than 10000 bps (100%)
*/
function setOwnerFee(uint16 _ownerFee) external canConfigure(msg.sender) {
require(_ownerFee + bankFee < 10000, "The sum of owner and bank fees should be less than 10000 bps");
if (_ownerFee > 0) {
require(10000 % _ownerFee == 0, "Owner fee amount must divide 10000 without a remainder");
}
ownerFee = _ownerFee;
}
/**
* @dev Sets bank's fee on market operations, that goes to the payouts pool
* @param _bankFee Fee in bps
*
* Requirements:
* - The caller must have canConfigure permission
* - Bank fee should divide 10000 without a remainder
* - Owner and bank fees should not add up to more than 10000 bps (100%)
*/
function setBankFee(uint16 _bankFee) external canConfigure(msg.sender) {
require(ownerFee + _bankFee < 10000, "The sum of owner and bank fees should be less than 10000 bps");
if (_bankFee > 0) {
require(10000 % _bankFee == 0, "Bank fee amount must divide 10000 without a remainder");
}
bankFee = _bankFee;
}
/**
* @dev Creates a new bid for a token
* @param tokenId Token ID
*
* Requirements:
* - `tokenId` must exist
* - Bid amount (`msg.value`) must be bigger than 0
* - Bid amount (`msg.value`) must be bigger than the current highest bid
* - Bid amount (`msg.value`) must be lower than the current asking price
* - Sender must not be the token owner
* - Sender must not have an active bid for the token (use `cancelBid` before bidding again)
*
* Emits {Bid} event
*/
function bid(uint256 tokenId) external payable {
require(msg.value > 0, "Bid amount invalid");
require(macabris.exists(tokenId), "Token does not exist");
require(macabris.ownerOf(tokenId) != msg.sender, "Can't bid on owned tokens");
require(bids[msg.sender][tokenId] == 0, "Bid already exists, cancel it before bidding again");
(, uint highestBidAmount) = getHighestBid(tokenId);
require(msg.value > highestBidAmount, "Bid must be larger than the current highest bid");
uint askingPrice = getAskingPrice(tokenId);
require(askingPrice == 0 || msg.value < askingPrice, "Bid must be smaller then the asking price");
bids[msg.sender][tokenId] = msg.value;
nextBidders[tokenId][msg.sender] = highestBidders[tokenId];
prevBidders[tokenId][highestBidders[tokenId]] = msg.sender;
highestBidders[tokenId] = msg.sender;
emit Bid(tokenId, msg.sender, msg.value);
}
/**
* @dev Cancels sender's currently active bid for the given token and returns the Ether
* @param tokenId Token ID
*
* Requirements:
* - `tokenId` must exist
* - Sender must have an active bid for the token
*
* Emits {BidCancellation} event
*/
function cancelBid(uint256 tokenId) public {
require(macabris.exists(tokenId), "Token does not exist");
require(bids[msg.sender][tokenId] > 0, "Bid does not exist");
uint amount = bids[msg.sender][tokenId];
_removeBid(tokenId, msg.sender);
_asyncTransfer(msg.sender, amount);
emit BidCancellation(tokenId, msg.sender, amount);
}
/**
* @dev Removes bid and does required houskeeping to maintain the bid queue
* @param tokenId Token ID
* @param bidder Bidder address
*/
function _removeBid(uint256 tokenId, address bidder) private {
address prevBidder = prevBidders[tokenId][bidder];
address nextBidder = nextBidders[tokenId][bidder];
// If this bid was the highest one, the next one will become the highest
if (prevBidder == address(0)) {
highestBidders[tokenId] = nextBidder;
}
// If there are bigger bids than this, remove the link to this one as the next bid
if (prevBidder != address(0)) {
nextBidders[tokenId][prevBidder] = nextBidder;
}
// If there are smaller bids than this, remove the link to this one as the prev bid
if (nextBidder != address(0)) {
prevBidders[tokenId][nextBidder] = prevBidder;
}
delete bids[bidder][tokenId];
}
/**
* @dev Sets the asking price for the token (enabling instant buy ability)
* @param tokenId Token ID
* @param amount Asking price in wei
*
* Requirements:
* - `tokenId` must exist
* - Sender must be the owner of the token
* - `amount` must be bigger than 0
* - `amount` must be bigger than the highest bid
*
* Emits {Ask} event
*/
function ask(uint256 tokenId, uint amount) external {
// Also checks if the token exists
require(macabris.ownerOf(tokenId) == msg.sender, "Token does not belong to the sender");
require(amount > 0, "Ask amount invalid");
(, uint highestBidAmount) = getHighestBid(tokenId);
require(amount > highestBidAmount, "Ask amount must be larger than the highest bid");
asks[tokenId] = amount;
emit Ask(tokenId, msg.sender, amount);
}
/**
* @dev Removes asking price for the token (disabling instant buy ability)
* @param tokenId Token ID
*
* Requirements:
* - `tokenId` must exist
* - Sender must be the owner of the token
*
* Emits {AskCancellation} event
*/
function cancelAsk(uint256 tokenId) external {
// Also checks if the token exists
require(macabris.ownerOf(tokenId) == msg.sender, "Token does not belong to the sender");
uint askingPrice = asks[tokenId];
delete asks[tokenId];
emit AskCancellation(tokenId, msg.sender, askingPrice);
}
/**
* @dev Sells token to the highest bidder
* @param tokenId Token ID
* @param amount Expected highest bid amount, fails if the actual bid amount does not match it
*
* Requirements:
* - `tokenId` must exist
* - Sender must be the owner of the token
* - There must be at least a single bid for the token
*
* Emits {Sale} event
*/
function sellForHighestBid(uint256 tokenId, uint amount) external {
// Also checks if the token exists
require(macabris.ownerOf(tokenId) == msg.sender, "Token does not belong to the sender");
(address highestBidAddress, uint highestBidAmount) = getHighestBid(tokenId);
require(highestBidAmount > 0, "There are no bids for the token");
require(amount == highestBidAmount, "Highest bid amount does not match given amount value");
delete asks[tokenId];
_removeBid(tokenId, highestBidAddress);
_onSale(tokenId, msg.sender, highestBidAddress, highestBidAmount);
}
/**
* @dev Buys token for the asking price
* @param tokenId Token ID
*
* Requirements:
* - `tokenId` must exist
* - Sender must not be the owner of the token
* - Asking price must be set for the token
* - `msg.value` must match the asking price
*
* Emits {Sale} event
*/
function buyForAskingPrice(uint256 tokenId) external payable {
// Implicitly checks if the token exists
address seller = macabris.ownerOf(tokenId);
require(msg.sender != seller, "Can't buy owned tokens");
uint askingPrice = getAskingPrice(tokenId);
require(askingPrice > 0, "Token is not for sale");
require(msg.value == askingPrice, "Transaction value does not match the asking price");
delete asks[tokenId];
// Cancel any bid to prevent a situation where an owner has a bid on own token
if (getBidAmount(tokenId, msg.sender) > 0) {
cancelBid(tokenId);
}
_onSale(tokenId, seller, msg.sender, askingPrice);
}
/**
* @dev Notifes Macabris about the sale, transfers money to the seller and emits a Sale event
* @param tokenId Token ID
* @param seller Seller address
* @param buyer Buyer address
* @param price Sale price
*
* Emits {Sale} event
*/
function _onSale(uint256 tokenId, address seller, address buyer, uint price) private {
uint ownerFeeAmount = _calculateFeeAmount(price, ownerFee);
uint bankFeeAmount = _calculateFeeAmount(price, bankFee);
uint priceAfterFees = price - ownerFeeAmount - bankFeeAmount;
macabris.onMarketSale(tokenId, seller, buyer);
bank.deposit{value: bankFeeAmount}();
_transferToOwnerBalance(ownerFeeAmount);
_asyncTransfer(seller, priceAfterFees);
emit Sale(tokenId, seller, buyer, price);
}
/**
* @dev Calculates fee amount based on given price and fee in bps
* @param price Price base for calculation
* @param fee Fee in basis points
* @return Fee amount in wei
*/
function _calculateFeeAmount(uint price, uint fee) private pure returns (uint) {
// Fee might be zero, avoiding division by zero
if (fee == 0) {
return 0;
}
// Only using division to make sure there is no overflow of the return value.
// This is the reason why fee must divide 10000 without a remainder, otherwise
// because of integer division fee won't be accurate.
return price / (10000 / fee);
}
/**
* @dev Returns current asking price for which the token can be bought immediately
* @param tokenId Token ID
* @return Amount in wei, 0 if the token is currently not for sale
*/
function getAskingPrice(uint256 tokenId) public view returns (uint) {
return asks[tokenId];
}
/**
* @dev Returns the highest bidder address and the bid amount for the given token
* @param tokenId Token ID
* @return Highest bidder address, 0 if not bid exists
* @return Amount in wei, 0 if no bid exists
*/
function getHighestBid(uint256 tokenId) public view returns (address, uint) {
address highestBidder = highestBidders[tokenId];
return (highestBidder, bids[highestBidder][tokenId]);
}
/**
* @dev Returns bid amount for the given token and bidder address
* @param tokenId Token ID
* @param bidder Bidder address
* @return Amount in wei, 0 if no bid exists
*
* Requirements:
* - `tokenId` must exist
*/
function getBidAmount(uint256 tokenId, address bidder) public view returns (uint) {
require(macabris.exists(tokenId), "Token does not exist");
return bids[bidder][tokenId];
}
}
// SPDX-License-Identifier: UNLICENSED
pragma solidity ^0.8.9;
import './Governed.sol';
import './Bank.sol';
/**
* @title Contract tracking deaths of Macabris tokens
*/
contract Reaper is Governed {
// Bank contract
Bank public bank;
// Mapping from token ID to time of death
mapping (uint256 => int64) private _deaths;
/**
* @dev Emitted when a token is marked as dead
* @param tokenId Token ID
* @param timeOfDeath Time of death (unix timestamp)
*/
event Death(uint256 indexed tokenId, int64 timeOfDeath);
/**
* @dev Emitted when a previosly dead token is marked as alive
* @param tokenId Token ID
*/
event Resurrection(uint256 indexed tokenId);
/**
* @param governanceAddress Address of the Governance contract
*
* Requirements:
* - Governance contract must be deployed at the given address
*/
constructor(address governanceAddress) Governed(governanceAddress) {}
/**
* @dev Sets Bank contract address
* @param bankAddress Address of Bank contract
*
* Requirements:
* - the caller must have the boostrap permission
* - Bank contract must be deployed at the given address
*/
function setBankAddress(address bankAddress) external canBootstrap(msg.sender) {
bank = Bank(bankAddress);
}
/**
* @dev Marks token as dead and sets time of death
* @param tokenId Token ID
* @param timeOfDeath Tome of death (unix timestamp)
*
* Requirements:
* - the caller must have permission to manage deaths
* - `timeOfDeath` can't be 0
*
* Note that tokenId doesn't have to be minted in order to be marked dead.
*
* Emits {Death} event
*/
function markDead(uint256 tokenId, int64 timeOfDeath) external canManageDeaths(msg.sender) {
require(timeOfDeath != 0, "Time of death of 0 represents an alive token");
_deaths[tokenId] = timeOfDeath;
bank.onTokenDeath(tokenId);
emit Death(tokenId, timeOfDeath);
}
/**
* @dev Marks token as alive
* @param tokenId Token ID
*
* Requirements:
* - the caller must have permission to manage deaths
* - `tokenId` must be currently marked as dead
*
* Emits {Resurrection} event
*/
function markAlive(uint256 tokenId) external canManageDeaths(msg.sender) {
require(_deaths[tokenId] != 0, "Token is not dead");
_deaths[tokenId] = 0;
bank.onTokenResurrection(tokenId);
emit Resurrection(tokenId);
}
/**
* @dev Returns token's time of death
* @param tokenId Token ID
* @return Time of death (unix timestamp) or zero, if alive
*
* Note that any tokenId could be marked as dead, even not minted or not existant one.
*/
function getTimeOfDeath(uint256 tokenId) external view returns (int64) {
return _deaths[tokenId];
}
}
// SPDX-License-Identifier: UNLICENSED
pragma solidity ^0.8.9;
import './OwnerBalance.sol';
/**
* @title Allows allocating portion of the contract's funds to the owner balance
*/
abstract contract OwnerBalanceContributor {
// OwnerBalance contract address
address public immutable ownerBalanceAddress;
uint public ownerBalanceDeposits;
/**
* @param _ownerBalanceAddress Address of the OwnerBalance contract
*/
constructor (address _ownerBalanceAddress) {
ownerBalanceAddress = _ownerBalanceAddress;
}
/**
* @dev Assigns given amount of contract funds to the owner's balance
* @param amount Amount in wei
*/
function _transferToOwnerBalance(uint amount) internal {
ownerBalanceDeposits += amount;
}
/**
* @dev Allows OwnerBalance contract to withdraw deposits
* @param ownerAddress Owner address to send funds to
*
* Requirements:
* - caller must be the OwnerBalance contract
*/
function withdrawOwnerBalanceDeposits(address ownerAddress) external {
require(msg.sender == ownerBalanceAddress, 'Caller must be the OwnerBalance contract');
uint currentBalance = ownerBalanceDeposits;
ownerBalanceDeposits = 0;
payable(ownerAddress).transfer(currentBalance);
}
}
// SPDX-License-Identifier: UNLICENSED
pragma solidity ^0.8.9;
import './Governed.sol';
import './OwnerBalanceContributor.sol';
/**
* @title Tracks owner's share of the funds in various Macabris contracts
*/
contract OwnerBalance is Governed {
address public owner;
// All three contracts, that contribute to the owner's balance
OwnerBalanceContributor public release;
OwnerBalanceContributor public bank;
OwnerBalanceContributor public market;
/**
* @param governanceAddress Address of the Governance contract
*
* Requirements:
* - Governance contract must be deployed at the given address
*/
constructor(address governanceAddress) Governed(governanceAddress) {}
/**
* @dev Sets the release contract address
* @param releaseAddress Address of the Release contract
*
* Requirements:
* - the caller must have the bootstrap permission
*/
function setReleaseAddress(address releaseAddress) external canBootstrap(msg.sender) {
release = OwnerBalanceContributor(releaseAddress);
}
/**
* @dev Sets Bank contract address
* @param bankAddress Address of the Bank contract
*
* Requirements:
* - the caller must have the bootstrap permission
*/
function setBankAddress(address bankAddress) external canBootstrap(msg.sender) {
bank = OwnerBalanceContributor(bankAddress);
}
/**
* @dev Sets the market contract address
* @param marketAddress Address of the Market contract
*
* Requirements:
* - the caller must have the bootstrap permission
*/
function setMarketAddress(address marketAddress) external canBootstrap(msg.sender) {
market = OwnerBalanceContributor(marketAddress);
}
/**
* @dev Sets owner address where the funds will be sent during withdrawal
* @param _owner Owner's address
*
* Requirements:
* - sender must have canSetOwnerAddress permission
* - address must not be 0
*/
function setOwner(address _owner) external canSetOwnerAddress(msg.sender) {
require(_owner != address(0), "Empty owner address is not allowed!");
owner = _owner;
}
/**
* @dev Returns total available balance in all contributing contracts
* @return Balance in wei
*/
function getBalance() external view returns (uint) {
uint balance;
balance += release.ownerBalanceDeposits();
balance += bank.ownerBalanceDeposits();
balance += market.ownerBalanceDeposits();
return balance;
}
/**
* @dev Withdraws available balance to the owner address
*
* Requirements:
* - owner address must be set
* - sender must have canTriggerOwnerWithdraw permission
*/
function withdraw() external canTriggerOwnerWithdraw(msg.sender) {
require(owner != address(0), "Owner address is not set");
release.withdrawOwnerBalanceDeposits(owner);
bank.withdrawOwnerBalanceDeposits(owner);
market.withdrawOwnerBalanceDeposits(owner);
}
}
// SPDX-License-Identifier: UNLICENSED
pragma solidity ^0.8.9;
import '@openzeppelin/contracts/token/ERC721/ERC721.sol';
import './Governed.sol';
import './Bank.sol';
contract Macabris is ERC721, Governed {
// Release contract address, used to whitelist calls to `onRelease` method
address public releaseAddress;
// Market contract address, used to whitelist calls to `onMarketSale` method
address public marketAddress;
// Bank contract
Bank public bank;
// Base URI of the token's metadata
string public baseUri;
// Personas sha256 hash (all UTF-8 names with a "\n" char after each name, sorted by token ID)
bytes32 public immutable hash;
/**
* @param _hash Personas sha256 hash (all UTF-8 names with a "\n" char after each name, sorted by token ID)
* @param governanceAddress Address of the Governance contract
*
* Requirements:
* - Governance contract must be deployed at the given address
*/
constructor(
bytes32 _hash,
address governanceAddress
) ERC721('Macabris', 'MCBR') Governed(governanceAddress) {
hash = _hash;
}
/**
* @dev Sets the release contract address
* @param _releaseAddress Address of the Release contract
*
* Requirements:
* - the caller must have the bootstrap permission
*/
function setReleaseAddress(address _releaseAddress) external canBootstrap(msg.sender) {
releaseAddress = _releaseAddress;
}
/**
* @dev Sets the market contract address
* @param _marketAddress Address of the Market contract
*
* Requirements:
* - the caller must have the bootstrap permission
*/
function setMarketAddress(address _marketAddress) external canBootstrap(msg.sender) {
marketAddress = _marketAddress;
}
/**
* @dev Sets Bank contract address
* @param bankAddress Address of the Bank contract
*
* Requirements:
* - the caller must have the bootstrap permission
* - Bank contract must be deployed at the given address
*/
function setBankAddress(address bankAddress) external canBootstrap(msg.sender) {
bank = Bank(bankAddress);
}
/**
* @dev Sets metadata base URI
* @param _baseUri Base URI, token's ID will be appended at the end
*/
function setBaseUri(string memory _baseUri) external canConfigure(msg.sender) {
baseUri = _baseUri;
}
/**
* @dev Checks if the token exists
* @param tokenId Token ID
* @return True if token with given ID has been minted already, false otherwise
*/
function exists(uint256 tokenId) external view returns (bool) {
return _exists(tokenId);
}
/**
* @dev Overwrites to return base URI set by the contract owner
*/
function _baseURI() override internal view returns (string memory) {
return baseUri;
}
function _transfer(address from, address to, uint256 tokenId) override internal {
super._transfer(from, to, tokenId);
bank.onTokenTransfer(tokenId, from, to);
}
function _mint(address to, uint256 tokenId) override internal {
super._mint(to, tokenId);
bank.onTokenTransfer(tokenId, address(0), to);
}
/**
* @dev Registers new token after it's sold and revealed in the Release contract
* @param tokenId Token ID
* @param buyer Buyer address
*
* Requirements:
* - The caller must be the Release contract
* - `tokenId` must not exist
* - Buyer cannot be the zero address
*
* Emits a {Transfer} event.
*/
function onRelease(uint256 tokenId, address buyer) external {
require(msg.sender == releaseAddress, "Caller must be the Release contract");
// Also checks that the token does not exist and that the buyer is not 0 address.
// Using unsafe mint to prevent a situation where a sale could not be revealed in the
// realease contract, because the buyer address does not implement IERC721Receiver.
_mint(buyer, tokenId);
}
/**
* @dev Transfers token ownership after a sale on the Market contract
* @param tokenId Token ID
* @param seller Seller address
* @param buyer Buyer address
*
* Requirements:
* - The caller must be the Market contract
* - `tokenId` must exist
* - `seller` must be the owner of the token
* - `buyer` cannot be the zero address
*
* Emits a {Transfer} event.
*/
function onMarketSale(uint256 tokenId, address seller, address buyer) external {
require(msg.sender == marketAddress, "Caller must be the Market contract");
// Also checks if the token exists, if the seller is the current owner and that the buyer is
// not 0 address.
// Using unsafe transfer to prevent a situation where the token owner can't accept the
// highest bid, because the bidder address does not implement IERC721Receiver.
_transfer(seller, buyer, tokenId);
}
}
// SPDX-License-Identifier: UNLICENSED
pragma solidity ^0.8.9;
import './Governance.sol';
/**
* @title Provides permission check modifiers for child contracts
*/
abstract contract Governed {
// Governance contract
Governance public immutable governance;
/**
* @param governanceAddress Address of the Governance contract
*
* Requirements:
* - Governance contract must be deployed at the given address
*/
constructor (address governanceAddress) {
governance = Governance(governanceAddress);
}
/**
* @dev Throws if given address that doesn't have ManagesDeaths permission
* @param subject Address to check permissions for, usually msg.sender
*/
modifier canManageDeaths(address subject) {
require(
governance.hasPermission(subject, Governance.Actions.ManageDeaths),
"Governance: subject is not allowed to manage deaths"
);
_;
}
/**
* @dev Throws if given address that doesn't have Configure permission
* @param subject Address to check permissions for, usually msg.sender
*/
modifier canConfigure(address subject) {
require(
governance.hasPermission(subject, Governance.Actions.Configure),
"Governance: subject is not allowed to configure contracts"
);
_;
}
/**
* @dev Throws if given address that doesn't have Bootstrap permission
* @param subject Address to check permissions for, usually msg.sender
*/
modifier canBootstrap(address subject) {
require(
governance.hasPermission(subject, Governance.Actions.Bootstrap),
"Governance: subject is not allowed to bootstrap"
);
_;
}
/**
* @dev Throws if given address that doesn't have SetOwnerAddress permission
* @param subject Address to check permissions for, usually msg.sender
*/
modifier canSetOwnerAddress(address subject) {
require(
governance.hasPermission(subject, Governance.Actions.SetOwnerAddress),
"Governance: subject is not allowed to set owner address"
);
_;
}
/**
* @dev Throws if given address that doesn't have TriggerOwnerWithdraw permission
* @param subject Address to check permissions for, usually msg.sender
*/
modifier canTriggerOwnerWithdraw(address subject) {
require(
governance.hasPermission(subject, Governance.Actions.TriggerOwnerWithdraw),
"Governance: subject is not allowed to trigger owner withdraw"
);
_;
}
/**
* @dev Throws if given address that doesn't have StopPayouyts permission
* @param subject Address to check permissions for, usually msg.sender
*/
modifier canStopPayouts(address subject) {
require(
governance.hasPermission(subject, Governance.Actions.StopPayouts),
"Governance: subject is not allowed to stop payouts"
);
_;
}
}
// SPDX-License-Identifier: UNLICENSED
pragma solidity ^0.8.9;
/**
* @title Manages address permissions to act on Macabris contracts
*/
contract Governance {
enum Actions { Vote, Configure, SetOwnerAddress, TriggerOwnerWithdraw, ManageDeaths, StopPayouts, Bootstrap }
// Stores permissions of an address
struct Permissions {
bool canVote;
bool canConfigure;
bool canSetOwnerAddress;
bool canTriggerOwnerWithdraw;
bool canManageDeaths;
bool canStopPayouts;
// Special permission that can't be voted in and only the deploying address receives
bool canBootstrap;
}
// A call for vote to change address permissions
struct CallForVote {
// Address that will be assigned the permissions if the vote passes
address subject;
// Permissions to be assigned if the vote passes
Permissions permissions;
// Total number of votes for and against the permission change
uint128 yeas;
uint128 nays;
}
// A vote in a call for vote
struct Vote {
uint64 callForVoteIndex;
bool yeaOrNay;
}
// Permissions of addresses
mapping(address => Permissions) private permissions;
// List of calls for a vote: callForVoteIndex => CallForVote, callForVoteIndex starts from 1
mapping(uint => CallForVote) private callsForVote;
// Last registered call for vote of every address: address => callForVoteIndex
mapping(address => uint64) private lastRegisteredCallForVote;
// Votes of every address: address => Vote
mapping(address => Vote) private votes;
uint64 public resolvedCallsForVote;
uint64 public totalCallsForVote;
uint64 public totalVoters;
/**
* @dev Emitted when a new call for vote is registered
* @param callForVoteIndex Index of the call for vote (1-based)
* @param subject Subject address to change permissions to if vote passes
* @param canVote Allow subject address to vote
* @param canConfigure Allow subject address to configure prices, fees and base URI
* @param canSetOwnerAddress Allows subject to change owner withdraw address
* @param canTriggerOwnerWithdraw Allow subject address to trigger withdraw from owner's balance
* @param canManageDeaths Allow subject to set tokens as dead or alive
* @param canStopPayouts Allow subject to stop the bank payout schedule early
*/
event CallForVoteRegistered(
uint64 indexed callForVoteIndex,
address indexed caller,
address indexed subject,
bool canVote,
bool canConfigure,
bool canSetOwnerAddress,
bool canTriggerOwnerWithdraw,
bool canManageDeaths,
bool canStopPayouts
);
/**
* @dev Emitted when a call for vote is resolved
* @param callForVoteIndex Index of the call for vote (1-based)
* @param yeas Total yeas for the call after the vote
* @param nays Total nays for the call after the vote
*/
event CallForVoteResolved(
uint64 indexed callForVoteIndex,
uint128 yeas,
uint128 nays
);
/**
* @dev Emitted when a vote is casted
* @param callForVoteIndex Index of the call for vote (1-based)
* @param voter Voter address
* @param yeaOrNay Vote, true if yea, false if nay
* @param totalVoters Total addresses with vote permission at the time of event
* @param yeas Total yeas for the call after the vote
* @param nays Total nays for the call after the vote
*/
event VoteCasted(
uint64 indexed callForVoteIndex,
address indexed voter,
bool yeaOrNay,
uint64 totalVoters,
uint128 yeas,
uint128 nays
);
/**
* @dev Inits the contract and gives the deployer address all permissions
*/
constructor() {
_setPermissions(msg.sender, Permissions({
canVote: true,
canConfigure: true,
canSetOwnerAddress: true,
canTriggerOwnerWithdraw: true,
canManageDeaths: true,
canStopPayouts: true,
canBootstrap: true
}));
}
/**
* @dev Checks if the given address has permission to perform given action
* @param subject Address to check
* @param action Action to check permissions against
* @return True if given address has permission to perform given action
*/
function hasPermission(address subject, Actions action) public view returns (bool) {
if (action == Actions.ManageDeaths) {
return permissions[subject].canManageDeaths;
}
if (action == Actions.Vote) {
return permissions[subject].canVote;
}
if (action == Actions.SetOwnerAddress) {
return permissions[subject].canSetOwnerAddress;
}
if (action == Actions.TriggerOwnerWithdraw) {
return permissions[subject].canTriggerOwnerWithdraw;
}
if (action == Actions.Configure) {
return permissions[subject].canConfigure;
}
if (action == Actions.StopPayouts) {
return permissions[subject].canStopPayouts;
}
if (action == Actions.Bootstrap) {
return permissions[subject].canBootstrap;
}
return false;
}
/**
* Sets permissions for a given address
* @param subject Subject address to set permissions to
* @param _permissions Permissions
*/
function _setPermissions(address subject, Permissions memory _permissions) private {
// Tracks count of total voting addresses to be able to calculate majority
if (permissions[subject].canVote != _permissions.canVote) {
if (_permissions.canVote) {
totalVoters += 1;
} else {
totalVoters -= 1;
// Cleaning up voting-related state for the address
delete votes[subject];
delete lastRegisteredCallForVote[subject];
}
}
permissions[subject] = _permissions;
}
/**
* @dev Registers a new call for vote to change address permissions
* @param subject Subject address to change permissions to if vote passes
* @param canVote Allow subject address to vote
* @param canConfigure Allow subject address to configure prices, fees and base URI
* @param canSetOwnerAddress Allows subject to change owner withdraw address
* @param canTriggerOwnerWithdraw Allow subject address to trigger withdraw from owner's balance
* @param canManageDeaths Allow subject to set tokens as dead or alive
* @param canStopPayouts Allow subject to stop the bank payout schedule early
*
* Requirements:
* - the caller must have the vote permission
* - the caller shouldn't have any unresolved calls for vote
*/
function callForVote(
address subject,
bool canVote,
bool canConfigure,
bool canSetOwnerAddress,
bool canTriggerOwnerWithdraw,
bool canManageDeaths,
bool canStopPayouts
) external {
require(
hasPermission(msg.sender, Actions.Vote),
"Only addresses with vote permission can register a call for vote"
);
// If the sender has previously created a call for vote that hasn't been resolved yet,
// a second call for vote can't be registered. Prevents a denial of service attack, where
// a minority of voters could flood the call for vote queue.
require(
lastRegisteredCallForVote[msg.sender] <= resolvedCallsForVote,
"Only one active call for vote per address is allowed"
);
totalCallsForVote++;
lastRegisteredCallForVote[msg.sender] = totalCallsForVote;
callsForVote[totalCallsForVote] = CallForVote({
subject: subject,
permissions: Permissions({
canVote: canVote,
canConfigure: canConfigure,
canSetOwnerAddress: canSetOwnerAddress,
canTriggerOwnerWithdraw: canTriggerOwnerWithdraw,
canManageDeaths: canManageDeaths,
canStopPayouts: canStopPayouts,
canBootstrap: false
}),
yeas: 0,
nays: 0
});
emit CallForVoteRegistered(
totalCallsForVote,
msg.sender,
subject,
canVote,
canConfigure,
canSetOwnerAddress,
canTriggerOwnerWithdraw,
canManageDeaths,
canStopPayouts
);
}
/**
* @dev Registers a vote
* @param callForVoteIndex Call for vote index
* @param yeaOrNay True to vote yea, false to vote nay
*
* Requirements:
* - unresolved call for vote must exist
* - call for vote index must match the current active call for vote
* - the caller must have the vote permission
*/
function vote(uint64 callForVoteIndex, bool yeaOrNay) external {
require(hasUnresolvedCallForVote(), "No unresolved call for vote exists");
require(
callForVoteIndex == _getCurrenCallForVoteIndex(),
"Call for vote does not exist or is not active"
);
require(
hasPermission(msg.sender, Actions.Vote),
"Sender address does not have vote permission"
);
uint128 yeas = callsForVote[callForVoteIndex].yeas;
uint128 nays = callsForVote[callForVoteIndex].nays;
// If the voter has already voted in this call for vote, undo the last vote
if (votes[msg.sender].callForVoteIndex == callForVoteIndex) {
if (votes[msg.sender].yeaOrNay) {
yeas -= 1;
} else {
nays -= 1;
}
}
if (yeaOrNay) {
yeas += 1;
} else {
nays += 1;
}
emit VoteCasted(callForVoteIndex, msg.sender, yeaOrNay, totalVoters, yeas, nays);
if (yeas == (totalVoters / 2 + 1) || nays == (totalVoters - totalVoters / 2)) {
if (yeas > nays) {
_setPermissions(
callsForVote[callForVoteIndex].subject,
callsForVote[callForVoteIndex].permissions
);
}
resolvedCallsForVote += 1;
// Cleaning up what we can
delete callsForVote[callForVoteIndex];
delete votes[msg.sender];
emit CallForVoteResolved(callForVoteIndex, yeas, nays);
return;
}
votes[msg.sender] = Vote({
callForVoteIndex: callForVoteIndex,
yeaOrNay: yeaOrNay
});
callsForVote[callForVoteIndex].yeas = yeas;
callsForVote[callForVoteIndex].nays = nays;
}
/**
* @dev Returns information about the current unresolved call for vote
* @return callForVoteIndex Call for vote index (1-based)
* @return yeas Total yea votes
* @return nays Total nay votes
*
* Requirements:
* - Unresolved call for vote must exist
*/
function getCurrentCallForVote() public view returns (
uint64 callForVoteIndex,
uint128 yeas,
uint128 nays
) {
require(hasUnresolvedCallForVote(), "No unresolved call for vote exists");
uint64 index = _getCurrenCallForVoteIndex();
return (index, callsForVote[index].yeas, callsForVote[index].nays);
}
/**
* @dev Checks if there is an unresolved call for vote
* @return True if an unresolved call for vote exists
*/
function hasUnresolvedCallForVote() public view returns (bool) {
return totalCallsForVote > resolvedCallsForVote;
}
/**
* @dev Returns current call for vote index
* @return Call for vote index (1-based)
*
* Doesn't check if an unresolved call for vote exists, hasUnresolvedCallForVote should be used
* before using the index that this method returns.
*/
function _getCurrenCallForVoteIndex() private view returns (uint64) {
return resolvedCallsForVote + 1;
}
}
// SPDX-License-Identifier: UNLICENSED
pragma solidity ^0.8.9;
import './Governed.sol';
import './OwnerBalanceContributor.sol';
import './Macabris.sol';
import './Reaper.sol';
/**
* @title Contract tracking payouts to token owners according to predefined schedule
*
* Payout schedule is dived into intervalCount intervals of intervalLength durations, starting at
* startTime timestamp. After each interval, part of the payouts pool is distributed to the owners
* of the tokens that are still alive. After the whole payout schedule is completed, all the funds
* in the payout pool will have been distributed.
*
* There is a possibility of the payout schedule being stopped early. In that case, all of the
* remaining funds will be distributed to the owners of the tokens that were alive at the time of
* the payout schedule stop.
*/
contract Bank is Governed, OwnerBalanceContributor {
// Macabris NFT contract
Macabris public macabris;
// Reaper contract
Reaper public reaper;
// Stores active token count change and deposits for an interval
struct IntervalActivity {
int128 activeTokenChange;
uint128 deposits;
}
// Stores aggregate interval information
struct IntervalTotals {
uint index;
uint deposits;
uint payouts;
uint accountPayouts;
uint activeTokens;
uint accountActiveTokens;
}
// The same as IntervalTotals, but a packed version to keep in the lastWithdrawTotals map.
// Packed versions costs less to store, but the math is then more expensive duo to type
// conversions, so the interval data is packed just before storing, and unpacked after loading.
struct IntervalTotalsPacked {
uint128 deposits;
uint128 payouts;
uint128 accountPayouts;
uint48 activeTokens;
uint48 accountActiveTokens;
uint32 index;
}
// Timestamp of when the first interval starts
uint64 public immutable startTime;
// Timestamp of the moment the payouts have been stopped and the bank contents distributed.
// This should remain 0, if the payout schedule is never stopped manually.
uint64 public stopTime;
// Total number of intervals
uint64 public immutable intervalCount;
// Interval length in seconds
uint64 public immutable intervalLength;
// Activity for each interval
mapping(uint => IntervalActivity) private intervals;
// Active token change for every interval for every address individually
mapping(uint => mapping(address => int)) private individualIntervals;
// Total withdrawn amount fo each address
mapping(address => uint) private withdrawals;
// Totals of the interval before the last withdrawal of an address
mapping(address => IntervalTotalsPacked) private lastWithdrawTotals;
/**
* @param _startTime First interval start unix timestamp
* @param _intervalCount Interval count
* @param _intervalLength Interval length in seconds
* @param governanceAddress Address of the Governance contract
* @param ownerBalanceAddress Address of the OwnerBalance contract
*
* Requirements:
* - interval length must be at least one second (but should be more like a month)
* - interval count must be bigger than zero
* - Governance contract must be deployed at the given address
* - OwnerBalance contract must be deployed at the given address
*/
constructor(
uint64 _startTime,
uint64 _intervalCount,
uint64 _intervalLength,
address governanceAddress,
address ownerBalanceAddress
) Governed(governanceAddress) OwnerBalanceContributor(ownerBalanceAddress) {
require(_intervalLength > 0, "Interval length can't be zero");
require(_intervalCount > 0, "At least one interval is required");
startTime = _startTime;
intervalCount = _intervalCount;
intervalLength = _intervalLength;
}
/**
* @dev Sets Macabris NFT contract address
* @param macabrisAddress Address of Macabris NFT contract
*
* Requirements:
* - the caller must have the bootstrap permission
* - Macabris contract must be deployed at the given address
*/
function setMacabrisAddress(address macabrisAddress) external canBootstrap(msg.sender) {
macabris = Macabris(macabrisAddress);
}
/**
* @dev Sets Reaper contract address
* @param reaperAddress Address of Reaper contract
*
* Requirements:
* - the caller must have the bootstrap permission
* - Reaper contract must be deployed at the given address
*/
function setReaperAddress(address reaperAddress) external canBootstrap(msg.sender) {
reaper = Reaper(reaperAddress);
}
/**
* @dev Stops payouts, distributes remaining funds among alive tokens
*
* Requirements:
* - the caller must have the stop payments permission
* - the payout schedule must not have been stopped previously
* - the payout schedule should not be completed
*/
function stopPayouts() external canStopPayouts(msg.sender) {
require(stopTime == 0, "Payouts are already stopped");
require(block.timestamp < getEndTime(), "Payout schedule is already completed");
stopTime = uint64(block.timestamp);
}
/**
* @dev Checks if the payouts are finished or have been stopped manually
* @return True if finished or stopped
*/
function hasEnded() public view returns (bool) {
return stopTime > 0 || block.timestamp >= getEndTime();
}
/**
* @dev Returns timestamp of the first second after the last interval
* @return Unix timestamp
*/
function getEndTime() public view returns(uint) {
return _getIntervalStartTime(intervalCount);
}
/**
* @dev Returns a timestamp of the first second of the given interval
* @return Unix timestamp
*
* Doesn't make any bound checks for the given interval!
*/
function _getIntervalStartTime(uint interval) private view returns(uint) {
return startTime + interval * intervalLength;
}
/**
* @dev Returns start time of the upcoming interval
* @return Unix timestamp
*/
function getNextIntervalStartTime() public view returns (uint) {
// If the payouts were ended manually, there will be no next interval
if (stopTime > 0) {
return 0;
}
// Returns first intervals start time if the payout schedule hasn't started yet
if (block.timestamp < startTime) {
return startTime;
}
uint currentInterval = _getInterval(block.timestamp);
// There will be no intervals after the last one, return 0
if (currentInterval >= (intervalCount - 1)) {
return 0;
}
// Returns next interval's start time otherwise
return _getIntervalStartTime(currentInterval + 1);
}
/**
* @dev Deposits ether to the common payout pool
*/
function deposit() external payable {
// If the payouts have ended, we don't need to track deposits anymore, everything goes to
// the owner's balance
if (hasEnded()) {
_transferToOwnerBalance(msg.value);
return;
}
require(msg.value <= type(uint128).max, "Deposits bigger than uint128 max value are not allowed!");
uint currentInterval = _getInterval(block.timestamp);
intervals[currentInterval].deposits += uint128(msg.value);
}
/**
* @dev Registers token transfer, minting and burning
* @param tokenId Token ID
* @param from Previous token owner, zero if this is a freshly minted token
* @param to New token owner, zero if the token is being burned
*
* Requirements:
* - the caller must be the Macabris contract
*/
function onTokenTransfer(uint tokenId, address from, address to) external {
require(msg.sender == address(macabris), "Caller must be the Macabris contract");
// If the payouts have ended, we don't need to track transfers anymore
if (hasEnded()) {
return;
}
// If token is already dead, nothing changes in terms of payouts
if (reaper.getTimeOfDeath(tokenId) != 0) {
return;
}
uint currentInterval = _getInterval(block.timestamp);
if (from == address(0)) {
// If the token is freshly minted, increase the total active token count for the period
intervals[currentInterval].activeTokenChange += 1;
} else {
// If the token is transfered, decrease the previous ownner's total for the current interval
individualIntervals[currentInterval][from] -= 1;
}
if (to == address(0)) {
// If the token is burned, decrease the total active token count for the period
intervals[currentInterval].activeTokenChange -= 1;
} else {
// If the token is transfered, add it to the receiver's total for the current interval
individualIntervals[currentInterval][to] += 1;
}
}
/**
* @dev Registers token death
* @param tokenId Token ID
*
* Requirements:
* - the caller must be the Reaper contract
*/
function onTokenDeath(uint tokenId) external {
require(msg.sender == address(reaper), "Caller must be the Reaper contract");
// If the payouts have ended, we don't need to track deaths anymore
if (hasEnded()) {
return;
}
// If the token isn't minted yet, we don't care about it
if (!macabris.exists(tokenId)) {
return;
}
uint currentInterval = _getInterval(block.timestamp);
address owner = macabris.ownerOf(tokenId);
intervals[currentInterval].activeTokenChange -= 1;
individualIntervals[currentInterval][owner] -= 1;
}
/**
* @dev Registers token resurrection
* @param tokenId Token ID
*
* Requirements:
* - the caller must be the Reaper contract
*/
function onTokenResurrection(uint tokenId) external {
require(msg.sender == address(reaper), "Caller must be the Reaper contract");
// If the payouts have ended, we don't need to track deaths anymore
if (hasEnded()) {
return;
}
// If the token isn't minted yet, we don't care about it
if (!macabris.exists(tokenId)) {
return;
}
uint currentInterval = _getInterval(block.timestamp);
address owner = macabris.ownerOf(tokenId);
intervals[currentInterval].activeTokenChange += 1;
individualIntervals[currentInterval][owner] += 1;
}
/**
* Returns current interval index
* @return Interval index (0 for the first interval, intervalCount-1 for the last)
*
* Notes:
* - Returns zero (first interval), if the first interval hasn't started yet
* - Returns the interval at the stop time, if the payouts have been stopped
* - Returns "virtual" interval after the last one, if the payout schedule is completed
*/
function _getCurrentInterval() private view returns(uint) {
// If the payouts have been stopped, return interval after the stopped one
if (stopTime > 0) {
return _getInterval(stopTime);
}
uint intervalIndex = _getInterval(block.timestamp);
// Return "virtual" interval that would come after the last one, if payout schedule is completed
if (intervalIndex > intervalCount) {
return intervalCount;
}
return intervalIndex;
}
/**
* Returns interval index for the given timestamp
* @return Interval index (0 for the first interval, intervalCount-1 for the last)
*
* Notes:
* - Returns zero (first interval), if the first interval hasn't started yet
* - Returns non-exitent interval index, if the timestamp is after the end time
*/
function _getInterval(uint timestamp) private view returns(uint) {
// Time before the payout schedule start is considered to be a part of the first interval
if (timestamp < startTime) {
return 0;
}
return (timestamp - startTime) / intervalLength;
}
/**
* @dev Returns total pool value (deposits - payouts) for the current interval
* @return Current pool value in wei
*/
function getPoolValue() public view returns (uint) {
// If all the payouts are done, pool is empty. In reality, there might something left due to
// last interval pool not dividing equaly between the remaining alive tokens, or if there
// are no alive tokens during the last interval.
if (hasEnded()) {
return 0;
}
uint currentInterval = _getInterval(block.timestamp);
IntervalTotals memory totals = _getIntervalTotals(currentInterval, address(0));
return totals.deposits - totals.payouts;
}
/**
* @dev Returns provisional next payout value per active token of the current interval
* @return Payout in wei, zero if no active tokens exist or all payouts are done
*/
function getNextPayout() external view returns (uint) {
// There is no next payout if the payout schedule has run its course
if (hasEnded()) {
return 0;
}
uint currentInterval = _getInterval(block.timestamp);
IntervalTotals memory totals = _getIntervalTotals(currentInterval, address(0));
return _getPayoutPerToken(totals);
}
/**
* @dev Returns payout amount per token for the given interval
* @param totals Interval totals
* @return Payout value in wei
*
* Notes:
* - Returns zero for the "virtual" interval after the payout schedule end
* - Returns zero if no active tokens exists for the interval
*/
function _getPayoutPerToken(IntervalTotals memory totals) private view returns (uint) {
// If we're calculating next payout for the "virtual" interval after the last one,
// or if there are no active tokens, we would be dividing the pool by zero
if (totals.activeTokens > 0 && totals.index < intervalCount) {
return (totals.deposits - totals.payouts) / (intervalCount - totals.index) / totals.activeTokens;
} else {
return 0;
}
}
/**
* @dev Returns the sum of all payouts made up until this interval
* @return Payouts total in wei
*/
function getPayoutsTotal() external view returns (uint) {
uint interval = _getCurrentInterval();
IntervalTotals memory totals = _getIntervalTotals(interval, address(0));
uint payouts = totals.payouts;
// If the payout schedule has been stopped prematurely, all deposits are distributed.
// If there are no active tokens, the remainder of the pool is never distributed.
if (stopTime > 0 && totals.activeTokens > 0) {
// Remaining pool might not divide equally between the active tokens, calculating
// distributed amount without the remainder
payouts += (totals.deposits - totals.payouts) / totals.activeTokens * totals.activeTokens;
}
return payouts;
}
/**
* @dev Returns the sum of payouts for a particular account
* @param account Account address
* @return Payouts total in wei
*/
function getAccountPayouts(address account) public view returns (uint) {
uint interval = _getCurrentInterval();
IntervalTotals memory totals = _getIntervalTotals(interval, account);
uint accountPayouts = totals.accountPayouts;
// If the payout schedule has been stopped prematurely, all deposits are distributed.
// If there are no active tokens, the remainder of the pool is never distributed.
if (stopTime > 0 && totals.activeTokens > 0) {
accountPayouts += (totals.deposits - totals.payouts) / totals.activeTokens * totals.accountActiveTokens;
}
return accountPayouts;
}
/**
* @dev Returns amount available for withdrawal
* @param account Address to return balance for
* @return Amount int wei
*/
function getBalance(address account) public view returns (uint) {
return getAccountPayouts(account) - withdrawals[account];
}
/**
* @dev Withdraws all available amount
* @param account Address to withdraw for
*
* Note that this method can be called by any address.
*/
function withdraw(address payable account) external {
uint interval = _getCurrentInterval();
// Persists last finished interval totals to avoid having to recalculate them from the
// deltas during the next withdrawal. Totals of the first interval should never be saved
// to the lastWithdrawTotals map (see _getIntervalTotals for explanation).
if (interval > 1) {
IntervalTotals memory totals = _getIntervalTotals(interval - 1, account);
// Converting the totals struct to a packed version before saving to storage to save gas
lastWithdrawTotals[account] = IntervalTotalsPacked({
deposits: uint128(totals.deposits),
payouts: uint128(totals.payouts),
accountPayouts: uint128(totals.accountPayouts),
activeTokens: uint48(totals.activeTokens),
accountActiveTokens: uint48(totals.accountActiveTokens),
index: uint32(totals.index)
});
}
uint balance = getBalance(account);
withdrawals[account] += balance;
account.transfer(balance);
}
/**
* @dev Aggregates active token and deposit change history until the given interval
* @param intervalIndex Interval
* @param account Account for account-specific aggregate values
* @return Aggregate values for the interval
*/
function _getIntervalTotals(uint intervalIndex, address account) private view returns (IntervalTotals memory) {
IntervalTotalsPacked storage packed = lastWithdrawTotals[account];
// Converting packed totals struct back to unpacked one, to avoid having to do type
// conversions in the loop below.
IntervalTotals memory totals = IntervalTotals({
index: packed.index,
deposits: packed.deposits,
payouts: packed.payouts,
accountPayouts: packed.accountPayouts,
activeTokens: packed.activeTokens,
accountActiveTokens: packed.accountActiveTokens
});
uint prevPayout;
uint prevAccountPayout;
uint prevPayoutPerToken;
// If we don't have previous totals, we need to start from intervalIndex 0 to apply the
// active token and deposit changes of the first interval. If we have previous totals, they
// the include all the activity of the interval already, so we start from the next one.
//
// Note that it's assumed all the interval total values will be 0, if the totals.index is 0.
// This means that the totals of the first interval should never be saved to the
// lastWithdrawTotals maps otherwise the deposits and active token changes will be counted twice.
for (uint i = totals.index > 0 ? totals.index + 1 : 0; i <= intervalIndex; i++) {
// Calculating payouts for the last interval data. If this is the first interval and
// there was no previous interval totals, all these values will resolve to 0.
prevPayoutPerToken = _getPayoutPerToken(totals);
prevPayout = prevPayoutPerToken * totals.activeTokens;
prevAccountPayout = totals.accountActiveTokens * prevPayoutPerToken;
// Updating totals to represent the current interval by adding the payouts of the last
// interval and applying changes in active token count and deposits
totals.index = i;
totals.payouts += prevPayout;
totals.accountPayouts += prevAccountPayout;
IntervalActivity storage interval = intervals[i];
totals.deposits += interval.deposits;
// Even though the token change value might be negative, the sum of all the changes
// will never be negative because of the implicit contrains of the contracts (e.g. token
// can't be transfered from an address that does not own it, or already dead token can't
// be marked dead again). Therefore it's safe to convert the result into unsigned value,
// after doing sum of signed values.
totals.activeTokens = uint(int(totals.activeTokens) + interval.activeTokenChange);
totals.accountActiveTokens = uint(int(totals.accountActiveTokens) + individualIntervals[i][account]);
}
return totals;
}
}
// 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 "./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;
import "../../access/Ownable.sol";
import "../Address.sol";
/**
* @title Escrow
* @dev Base escrow contract, holds funds designated for a payee until they
* withdraw them.
*
* 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 owner, and provide public methods redirecting
* to the escrow's deposit and withdraw.
*/
contract Escrow is Ownable {
using Address for address payable;
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 payable virtual onlyOwner {
uint256 amount = msg.value;
_deposits[payee] += amount;
emit Deposited(payee, amount);
}
/**
* @dev Withdraw accumulated balance for a payee, forwarding all gas to the
* recipient.
*
* WARNING: Forwarding all gas opens the door to reentrancy vulnerabilities.
* Make sure you trust the recipient, or are either following the
* checks-effects-interactions pattern or using {ReentrancyGuard}.
*
* @param payee The address whose funds will be withdrawn and transferred to.
*/
function withdraw(address payable payee) public virtual onlyOwner {
uint256 payment = _deposits[payee];
_deposits[payee] = 0;
payee.sendValue(payment);
emit Withdrawn(payee, payment);
}
}
// SPDX-License-Identifier: MIT
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
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
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
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;
/**
* @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 "../../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;
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 {
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.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.0;
import "../utils/escrow/Escrow.sol";
/**
* @dev Simple implementation of a
* https://consensys.github.io/smart-contract-best-practices/recommendations/#favor-pull-over-push-for-external-calls[pull-payment]
* strategy, where the paying contract doesn't interact directly with the
* receiver account, which must withdraw its payments itself.
*
* Pull-payments are often considered the best practice when it comes to sending
* Ether, security-wise. It prevents recipients from blocking execution, and
* eliminates reentrancy concerns.
*
* 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].
*
* To use, derive from the `PullPayment` contract, and use {_asyncTransfer}
* instead of Solidity's `transfer` function. Payees can query their due
* payments with {payments}, and retrieve them with {withdrawPayments}.
*/
abstract contract PullPayment {
Escrow private immutable _escrow;
constructor() {
_escrow = new Escrow();
}
/**
* @dev Withdraw accumulated payments, forwarding all gas to the recipient.
*
* Note that _any_ account can call this function, not just the `payee`.
* This means that contracts unaware of the `PullPayment` protocol can still
* receive funds this way, by having a separate account call
* {withdrawPayments}.
*
* WARNING: Forwarding all gas opens the door to reentrancy vulnerabilities.
* Make sure you trust the recipient, or are either following the
* checks-effects-interactions pattern or using {ReentrancyGuard}.
*
* @param payee Whose payments will be withdrawn.
*/
function withdrawPayments(address payable payee) public virtual {
_escrow.withdraw(payee);
}
/**
* @dev Returns the payments 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.
* Funds sent in this way are stored in an intermediate {Escrow} contract, so
* there is no danger of them being spent before withdrawal.
*
* @param dest The destination address of the funds.
* @param amount The amount to transfer.
*/
function _asyncTransfer(address dest, uint256 amount) internal virtual {
_escrow.deposit{value: amount}(dest);
}
}
// 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() {
_setOwner(_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 {
_setOwner(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");
_setOwner(newOwner);
}
function _setOwner(address newOwner) private {
address oldOwner = _owner;
_owner = newOwner;
emit OwnershipTransferred(oldOwner, newOwner);
}
} | * @dev Returns timestamp of the first second after the last interval @return Unix timestamp/ | function getEndTime() public view returns(uint) {
return _getIntervalStartTime(intervalCount);
}
| 10,435,132 | [
1,
1356,
2858,
434,
326,
1122,
2205,
1839,
326,
1142,
3673,
327,
9480,
2858,
19,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
565,
445,
9968,
950,
1435,
1071,
1476,
1135,
12,
11890,
13,
288,
203,
3639,
327,
389,
588,
4006,
13649,
12,
6624,
1380,
1769,
203,
565,
289,
203,
203,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
] |
// SPDX-License-Identifier: MIT
pragma solidity >=0.4.22 <0.9.0;
import "@openzeppelin/contracts/token/ERC20/IERC20.sol";
import "@openzeppelin/contracts/utils/math/SafeMath.sol";
import "@openzeppelin/contracts/security/ReentrancyGuard.sol";
import "@openzeppelin/contracts/access/Ownable.sol";
/// @title NFPS Staking Farm
/// @author NFP Swap
/// @notice Contract for reward program using NFPS token
contract NfpsTokenFarm is ReentrancyGuard, Ownable {
using SafeMath for uint;
using SafeMath for uint256;
IERC20 private _stakingToken;
uint private _endTime;
uint256 private _rewardRate;
uint256 private _lastUpdateTime;
uint256 private _rewardPerTokenStored;
mapping(address => uint256) private _userRewardPerTokenPaid;
mapping(address => uint256) private _rewards;
uint256 private _totalSupply;
mapping(address => uint256) private _balances;
mapping(address => uint) private _lastStaked;
struct StakeInfo {
uint256 amountStaked;
uint256 earnedAmount;
uint256 rewardRate;
uint256 totalStaked;
uint lastStaked;
}
constructor() {}
/// @notice Fetch the stake information for a given address
function userStakeInfo(address account)
public
view
returns (StakeInfo memory)
{
return
StakeInfo(
_balances[account],
earned(account),
_rewardRate,
_totalSupply,
_lastStaked[account]
);
}
/// @notice Setup farm with token and reward rate
function setUpFarm(address stakingTokenAddress, uint256 startingRewardRate)
public
onlyOwner
{
_stakingToken = IERC20(stakingTokenAddress);
_rewardRate = startingRewardRate;
}
/// @notice Returns the reward rate to calculate rewards
function rewardPerToken() public view returns (uint256) {
if (_totalSupply == 0) {
return 0;
}
uint latestTime = _endTime > 0 ? _endTime : block.timestamp;
return
_rewardPerTokenStored.add(
latestTime.sub(_lastUpdateTime).mul(_rewardRate).mul(1e18).div(
_totalSupply
)
);
}
/// @notice Update reward for a given account
function updateReward(address account) internal {
_rewardPerTokenStored = rewardPerToken();
_lastUpdateTime = block.timestamp;
_rewards[account] = earned(account);
_userRewardPerTokenPaid[account] = _rewardPerTokenStored;
}
/// @notice Allow an amount of NFPS tokens to be staked
function stake(uint256 amount) external nonReentrant {
require(
_endTime == 0 || block.timestamp < _endTime,
"Staking contract has ended"
);
require(amount > 0, "Amount must be greater than 0");
updateReward(msg.sender);
_totalSupply = _totalSupply.add(amount);
_balances[msg.sender] = _balances[msg.sender].add(amount);
_lastStaked[msg.sender] = block.timestamp;
_stakingToken.transferFrom(msg.sender, address(this), amount);
}
/// @notice Allow an amount of NFPS tokens to be unstaked
function unstake(uint256 amount) external {
require(amount > 0, "Amount must be greater than 0");
require(amount <= _balances[msg.sender], "Amount exceeds balance");
require(
_lastStaked[msg.sender] <= block.timestamp.sub(10 days),
"Staking lock period has not expired (10 days)"
);
updateReward(msg.sender);
_totalSupply = _totalSupply.sub(amount);
_balances[msg.sender] = _balances[msg.sender].sub(amount);
uint256 reward = _rewards[msg.sender];
if (reward > 0) {
_rewards[msg.sender] = 0;
amount = amount.add(reward);
}
_stakingToken.transfer(msg.sender, amount);
}
/// @notice Allow rewards to be claimed
function claim() external nonReentrant {
updateReward(msg.sender);
uint256 reward = _rewards[msg.sender];
_rewards[msg.sender] = 0;
_stakingToken.transfer(msg.sender, reward);
}
/// @notice Show the accrued rewards for a given account
function earned(address account) public view returns (uint256) {
if (_balances[account] == 0) {
return 0;
}
return
_balances[account]
.mul(rewardPerToken().sub(_userRewardPerTokenPaid[account]))
.div(1e18)
.add(_rewards[account]);
}
}
// SPDX-License-Identifier: MIT
// 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;
}
}
}
// 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 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);
}
} | @notice Allow an amount of NFPS tokens to be staked | function stake(uint256 amount) external nonReentrant {
require(
_endTime == 0 || block.timestamp < _endTime,
"Staking contract has ended"
);
require(amount > 0, "Amount must be greater than 0");
updateReward(msg.sender);
_totalSupply = _totalSupply.add(amount);
_balances[msg.sender] = _balances[msg.sender].add(amount);
_lastStaked[msg.sender] = block.timestamp;
_stakingToken.transferFrom(msg.sender, address(this), amount);
}
| 1,344,272 | [
1,
7009,
392,
3844,
434,
423,
42,
5857,
2430,
358,
506,
384,
9477,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
565,
445,
384,
911,
12,
11890,
5034,
3844,
13,
3903,
1661,
426,
8230,
970,
288,
203,
3639,
2583,
12,
203,
5411,
389,
409,
950,
422,
374,
747,
1203,
18,
5508,
411,
389,
409,
950,
16,
203,
5411,
315,
510,
6159,
6835,
711,
16926,
6,
203,
3639,
11272,
203,
3639,
2583,
12,
8949,
405,
374,
16,
315,
6275,
1297,
506,
6802,
2353,
374,
8863,
203,
3639,
1089,
17631,
1060,
12,
3576,
18,
15330,
1769,
203,
3639,
389,
4963,
3088,
1283,
273,
389,
4963,
3088,
1283,
18,
1289,
12,
8949,
1769,
203,
3639,
389,
70,
26488,
63,
3576,
18,
15330,
65,
273,
389,
70,
26488,
63,
3576,
18,
15330,
8009,
1289,
12,
8949,
1769,
203,
3639,
389,
2722,
510,
9477,
63,
3576,
18,
15330,
65,
273,
1203,
18,
5508,
31,
203,
3639,
389,
334,
6159,
1345,
18,
13866,
1265,
12,
3576,
18,
15330,
16,
1758,
12,
2211,
3631,
3844,
1769,
203,
565,
289,
203,
203,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
] |
/**
*Submitted for verification at Etherscan.io on 2021-09-23
*/
// SPDX-License-Identifier: MIT
pragma solidity 0.6.12;
pragma experimental ABIEncoderV2;
// Part: IFund
interface IFund {
function underlying() external view returns (address);
function fundManager() external view returns (address);
function relayer() external view returns (address);
function deposit(uint256 amountWei) external;
function depositFor(uint256 amountWei, address holder) external;
function withdraw(uint256 numberOfShares) external;
function getPricePerShare() external view returns (uint256);
function totalValueLocked() external view returns (uint256);
function underlyingBalanceWithInvestmentForHolder(address holder)
external
view
returns (uint256);
}
// Part: IFundProxy
interface IFundProxy {
function implementation() external view returns (address);
}
// Part: IStrategy
interface IStrategy {
function name() external pure returns (string memory);
function version() external pure returns (string memory);
function underlying() external view returns (address);
function fund() external view returns (address);
function creator() external view returns (address);
function withdrawAllToFund() external;
function withdrawToFund(uint256 amount) external;
function investedUnderlyingBalance() external view returns (uint256);
function doHardWork() external;
}
// Part: OpenZeppelin/[email protected]/AddressUpgradeable
/**
* @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);
}
}
}
}
// Part: OpenZeppelin/[email protected]/IERC20Upgradeable
/**
* @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);
}
// Part: OpenZeppelin/[email protected]/MathUpgradeable
/**
* @dev Standard math utilities missing in the Solidity language.
*/
library MathUpgradeable {
/**
* @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);
}
}
// Part: OpenZeppelin/[email protected]/SafeMathUpgradeable
/**
* @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 SafeMathUpgradeable {
/**
* @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;
}
}
// 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]/SafeMath
/**
* @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;
}
}
// Part: SetGetAssembly
contract SetGetAssembly {
// solhint-disable-next-line no-empty-blocks
constructor() public {}
function setAddress(bytes32 slot, address _address) internal {
// solhint-disable-next-line no-inline-assembly
assembly {
sstore(slot, _address)
}
}
function setUint256(bytes32 slot, uint256 _value) internal {
// solhint-disable-next-line no-inline-assembly
assembly {
sstore(slot, _value)
}
}
function setUint8(bytes32 slot, uint8 _value) internal {
// solhint-disable-next-line no-inline-assembly
assembly {
sstore(slot, _value)
}
}
function setBool(bytes32 slot, bool _value) internal {
setUint256(slot, _value ? 1 : 0);
}
function getBool(bytes32 slot) internal view returns (bool) {
return (getUint256(slot) == 1);
}
function getAddress(bytes32 slot) internal view returns (address str) {
// solhint-disable-next-line no-inline-assembly
assembly {
str := sload(slot)
}
}
function getUint256(bytes32 slot) internal view returns (uint256 str) {
// solhint-disable-next-line no-inline-assembly
assembly {
str := sload(slot)
}
}
function getUint8(bytes32 slot) internal view returns (uint8 str) {
// solhint-disable-next-line no-inline-assembly
assembly {
str := sload(slot)
}
}
}
// Part: OpenZeppelin/[email protected]/Initializable
/**
* @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 || _isConstructor() || !_initialized, "Initializable: contract is already 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) {
return !AddressUpgradeable.isContract(address(this));
}
}
// 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 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");
}
}
}
// Part: FundStorage
contract FundStorage is Initializable, SetGetAssembly {
bytes32 internal constant _UNDERLYING_SLOT =
0xe0dc1d429ff8628e5936b3d6a6546947e1cc9ea7415a59d46ce95b3cfa4442b9;
bytes32 internal constant _UNDERLYING_UNIT_SLOT =
0x4840b03aa097a422092d99dc6875c2b69e8f48c9af2563a0447f3b4e4928d962;
bytes32 internal constant _DECIMALS_SLOT =
0x15b9fa1072bc4b2cdb762a49a2c7917b8b3af02283e37ffd41d0fccd4eef0d48;
bytes32 internal constant _FUND_MANAGER_SLOT =
0x670552e214026020a9e6caa820519c7f879b21bd75b5571387d6a9cf8f94bd18;
bytes32 internal constant _RELAYER_SLOT =
0x84e8c6b8f2281d51d9f683d351409724c3caa7848051aeb9d92c106ab36cc24c;
bytes32 internal constant _PLATFORM_REWARDS_SLOT =
0x92260bfe68dd0f8a9f5439b75466781ba1ce44523ed1a3026a73eada49072e65;
bytes32 internal constant _CHANGE_DELAY_SLOT =
0x0391715d0dd26b729c4ba34639ad5bdb0a7feb89f59a1e38f38485ea7f5a1583;
bytes32 internal constant _DEPOSIT_LIMIT_SLOT =
0xca2f8a3e9ea81335bcce793cde55fc0c38129b594f53052d2bb18099ffa72613;
bytes32 internal constant _DEPOSIT_LIMIT_TX_MAX_SLOT =
0x769f312c3790719cf1ea5f75303393f080fd62be88d75fa86726a6be00bb5a24;
bytes32 internal constant _DEPOSIT_LIMIT_TX_MIN_SLOT =
0x9027949576d185c74d79ad3b8a8dbff32126f3a3ee140b346f146beb18234c85;
bytes32 internal constant _PERFORMANCE_FEE_FUND_SLOT =
0x5b8979500398f8fbeb42c36d18f31a76fd0ab30f4338d864e7d8734b340e9bb9;
bytes32 internal constant _PLATFORM_FEE_SLOT =
0x2084059f3bff3cc3fd204df32325dcb05f47c2f590aba5d103ec584523738e7a;
bytes32 internal constant _MAX_INVESTMENT_IN_STRATEGIES_SLOT =
0xe3b5969c9426551aa8f16dbc7b25042b9b9c9869b759c77a85f0b097ac363475;
bytes32 internal constant _TOTAL_WEIGHT_IN_STRATEGIES_SLOT =
0x63177e03c47ab825f04f5f8f2334e312239890e7588db78cabe10d7aec327fd2;
bytes32 internal constant _TOTAL_ACCOUNTED_SLOT =
0xa19f3b8a62465676ae47ab811ee15e3d2b68d88869cb38686d086a11d382f6bb;
bytes32 internal constant _TOTAL_INVESTED_SLOT =
0x49c84685200b42972f845832b2c3da3d71def653c151340801aeae053ce104e9;
bytes32 internal constant _DEPOSITS_PAUSED_SLOT =
0x3cefcfe9774096ac956c0d63992ea27a01fb3884a22b8765ad63c8366f90a9c8;
bytes32 internal constant _SHOULD_REBALANCE_SLOT =
0x7f8e3dfb98485aa419c1d05b6ea089a8cddbafcfcf4491db33f5d0b5fe4f32c7;
bytes32 internal constant _LAST_HARDWORK_TIMESTAMP_SLOT =
0x0260c2bf5555cd32cedf39c0fcb0eab8029c67b3d5137faeb3e24a500db80bc9;
bytes32 internal constant _NEXT_IMPLEMENTATION_SLOT =
0xa7ae0fa763ec3009113ccc5eb9089e1f0028607f5b8198c52cd42366c1ddb17b;
bytes32 internal constant _NEXT_IMPLEMENTATION_TIMESTAMP_SLOT =
0x5e1f7083e1d90c44893f97806d0ec517436a58b85860b28247fd6fd56f5dc897;
constructor() public {
assert(
_UNDERLYING_SLOT ==
bytes32(
uint256(
keccak256("eip1967.mesh.finance.fundStorage.underlying")
) - 1
)
);
assert(
_UNDERLYING_UNIT_SLOT ==
bytes32(
uint256(
keccak256(
"eip1967.mesh.finance.fundStorage.underlyingUnit"
)
) - 1
)
);
assert(
_DECIMALS_SLOT ==
bytes32(
uint256(
keccak256("eip1967.mesh.finance.fundStorage.decimals")
) - 1
)
);
assert(
_FUND_MANAGER_SLOT ==
bytes32(
uint256(
keccak256(
"eip1967.mesh.finance.fundStorage.fundManager"
)
) - 1
)
);
assert(
_RELAYER_SLOT ==
bytes32(
uint256(
keccak256("eip1967.mesh.finance.fundStorage.relayer")
) - 1
)
);
assert(
_PLATFORM_REWARDS_SLOT ==
bytes32(
uint256(
keccak256(
"eip1967.mesh.finance.fundStorage.platformRewards"
)
) - 1
)
);
assert(
_CHANGE_DELAY_SLOT ==
bytes32(
uint256(
keccak256(
"eip1967.mesh.finance.fundStorage.changeDelay"
)
) - 1
)
);
assert(
_DEPOSIT_LIMIT_SLOT ==
bytes32(
uint256(
keccak256(
"eip1967.mesh.finance.fundStorage.depositLimit"
)
) - 1
)
);
assert(
_DEPOSIT_LIMIT_TX_MAX_SLOT ==
bytes32(
uint256(
keccak256(
"eip1967.mesh.finance.fundStorage.depositLimitTxMax"
)
) - 1
)
);
assert(
_DEPOSIT_LIMIT_TX_MIN_SLOT ==
bytes32(
uint256(
keccak256(
"eip1967.mesh.finance.fundStorage.depositLimitTxMin"
)
) - 1
)
);
assert(
_PERFORMANCE_FEE_FUND_SLOT ==
bytes32(
uint256(
keccak256(
"eip1967.mesh.finance.fundStorage.performanceFeeFund"
)
) - 1
)
);
assert(
_PLATFORM_FEE_SLOT ==
bytes32(
uint256(
keccak256(
"eip1967.mesh.finance.fundStorage.platformFee"
)
) - 1
)
);
assert(
_MAX_INVESTMENT_IN_STRATEGIES_SLOT ==
bytes32(
uint256(
keccak256(
"eip1967.mesh.finance.fundStorage.maxInvestmentInStrategies"
)
) - 1
)
);
assert(
_TOTAL_WEIGHT_IN_STRATEGIES_SLOT ==
bytes32(
uint256(
keccak256(
"eip1967.mesh.finance.fundStorage.totalWeightInStrategies"
)
) - 1
)
);
assert(
_TOTAL_ACCOUNTED_SLOT ==
bytes32(
uint256(
keccak256(
"eip1967.mesh.finance.fundStorage.totalAccounted"
)
) - 1
)
);
assert(
_TOTAL_INVESTED_SLOT ==
bytes32(
uint256(
keccak256(
"eip1967.mesh.finance.fundStorage.totalInvested"
)
) - 1
)
);
assert(
_DEPOSITS_PAUSED_SLOT ==
bytes32(
uint256(
keccak256(
"eip1967.mesh.finance.fundStorage.depositsPaused"
)
) - 1
)
);
assert(
_SHOULD_REBALANCE_SLOT ==
bytes32(
uint256(
keccak256(
"eip1967.mesh.finance.fundStorage.shouldRebalance"
)
) - 1
)
);
assert(
_LAST_HARDWORK_TIMESTAMP_SLOT ==
bytes32(
uint256(
keccak256(
"eip1967.mesh.finance.fundStorage.lastHardworkTimestamp"
)
) - 1
)
);
assert(
_NEXT_IMPLEMENTATION_SLOT ==
bytes32(
uint256(
keccak256(
"eip1967.mesh.finance.fundStorage.nextImplementation"
)
) - 1
)
);
assert(
_NEXT_IMPLEMENTATION_TIMESTAMP_SLOT ==
bytes32(
uint256(
keccak256(
"eip1967.mesh.finance.fundStorage.nextImplementationTimestamp"
)
) - 1
)
);
}
function initializeFundStorage(
address _underlying,
uint256 _underlyingUnit,
uint8 _decimals,
address _fundManager,
address _relayer,
address _platformRewards,
uint256 _changeDelay
) public initializer {
_setUnderlying(_underlying);
_setUnderlyingUnit(_underlyingUnit);
_setDecimals(_decimals);
_setFundManager(_fundManager);
_setRelayer(_relayer);
_setPlatformRewards(_platformRewards);
_setChangeDelay(_changeDelay);
_setDepositLimit(0);
_setDepositLimitTxMax(0);
_setDepositLimitTxMin(0);
_setPerformanceFeeFund(0);
_setPlatformFee(0);
_setMaxInvestmentInStrategies(9500); // 9500 BPS (95%) can be accessed by the strategies. This is to keep something in fund for withdrawal.
_setTotalWeightInStrategies(0);
_setTotalAccounted(0);
_setTotalInvested(0);
_setDepositsPaused(false);
_setShouldRebalance(false);
_setLastHardworkTimestamp(0);
_setNextImplementation(address(0));
_setNextImplementationTimestamp(0);
}
function _setUnderlying(address _address) internal {
setAddress(_UNDERLYING_SLOT, _address);
}
function _underlying() internal view returns (address) {
return getAddress(_UNDERLYING_SLOT);
}
function _setUnderlyingUnit(uint256 _value) internal {
setUint256(_UNDERLYING_UNIT_SLOT, _value);
}
function _underlyingUnit() internal view returns (uint256) {
return getUint256(_UNDERLYING_UNIT_SLOT);
}
function _setDecimals(uint8 _value) internal {
setUint8(_DECIMALS_SLOT, _value);
}
function _decimals() internal view returns (uint8) {
return getUint8(_DECIMALS_SLOT);
}
function _setFundManager(address _fundManager) internal {
setAddress(_FUND_MANAGER_SLOT, _fundManager);
}
function _fundManager() internal view returns (address) {
return getAddress(_FUND_MANAGER_SLOT);
}
function _setRelayer(address _relayer) internal {
setAddress(_RELAYER_SLOT, _relayer);
}
function _relayer() internal view returns (address) {
return getAddress(_RELAYER_SLOT);
}
function _setPlatformRewards(address _rewards) internal {
setAddress(_PLATFORM_REWARDS_SLOT, _rewards);
}
function _platformRewards() internal view returns (address) {
return getAddress(_PLATFORM_REWARDS_SLOT);
}
function _setChangeDelay(uint256 _value) internal {
setUint256(_CHANGE_DELAY_SLOT, _value);
}
function _changeDelay() internal view returns (uint256) {
return getUint256(_CHANGE_DELAY_SLOT);
}
function _setDepositLimit(uint256 _value) internal {
setUint256(_DEPOSIT_LIMIT_SLOT, _value);
}
function _depositLimit() internal view returns (uint256) {
return getUint256(_DEPOSIT_LIMIT_SLOT);
}
function _setDepositLimitTxMax(uint256 _value) internal {
setUint256(_DEPOSIT_LIMIT_TX_MAX_SLOT, _value);
}
function _depositLimitTxMax() internal view returns (uint256) {
return getUint256(_DEPOSIT_LIMIT_TX_MAX_SLOT);
}
function _setDepositLimitTxMin(uint256 _value) internal {
setUint256(_DEPOSIT_LIMIT_TX_MIN_SLOT, _value);
}
function _depositLimitTxMin() internal view returns (uint256) {
return getUint256(_DEPOSIT_LIMIT_TX_MIN_SLOT);
}
function _setPerformanceFeeFund(uint256 _value) internal {
setUint256(_PERFORMANCE_FEE_FUND_SLOT, _value);
}
function _performanceFeeFund() internal view returns (uint256) {
return getUint256(_PERFORMANCE_FEE_FUND_SLOT);
}
function _setPlatformFee(uint256 _value) internal {
setUint256(_PLATFORM_FEE_SLOT, _value);
}
function _platformFee() internal view returns (uint256) {
return getUint256(_PLATFORM_FEE_SLOT);
}
function _setMaxInvestmentInStrategies(uint256 _value) internal {
setUint256(_MAX_INVESTMENT_IN_STRATEGIES_SLOT, _value);
}
function _maxInvestmentInStrategies() internal view returns (uint256) {
return getUint256(_MAX_INVESTMENT_IN_STRATEGIES_SLOT);
}
function _setTotalWeightInStrategies(uint256 _value) internal {
setUint256(_TOTAL_WEIGHT_IN_STRATEGIES_SLOT, _value);
}
function _totalWeightInStrategies() internal view returns (uint256) {
return getUint256(_TOTAL_WEIGHT_IN_STRATEGIES_SLOT);
}
function _setTotalAccounted(uint256 _value) internal {
setUint256(_TOTAL_ACCOUNTED_SLOT, _value);
}
function _totalAccounted() internal view returns (uint256) {
return getUint256(_TOTAL_ACCOUNTED_SLOT);
}
function _setTotalInvested(uint256 _value) internal {
setUint256(_TOTAL_INVESTED_SLOT, _value);
}
function _totalInvested() internal view returns (uint256) {
return getUint256(_TOTAL_INVESTED_SLOT);
}
function _setDepositsPaused(bool _value) internal {
setBool(_DEPOSITS_PAUSED_SLOT, _value);
}
function _depositsPaused() internal view returns (bool) {
return getBool(_DEPOSITS_PAUSED_SLOT);
}
function _setShouldRebalance(bool _value) internal {
setBool(_SHOULD_REBALANCE_SLOT, _value);
}
function _shouldRebalance() internal view returns (bool) {
return getBool(_SHOULD_REBALANCE_SLOT);
}
function _setLastHardworkTimestamp(uint256 _value) internal {
setUint256(_LAST_HARDWORK_TIMESTAMP_SLOT, _value);
}
function _lastHardworkTimestamp() internal view returns (uint256) {
return getUint256(_LAST_HARDWORK_TIMESTAMP_SLOT);
}
function _setNextImplementation(address _newImplementation) internal {
setAddress(_NEXT_IMPLEMENTATION_SLOT, _newImplementation);
}
function _nextImplementation() internal view returns (address) {
return getAddress(_NEXT_IMPLEMENTATION_SLOT);
}
function _setNextImplementationTimestamp(uint256 _value) internal {
setUint256(_NEXT_IMPLEMENTATION_TIMESTAMP_SLOT, _value);
}
function _nextImplementationTimestamp() internal view returns (uint256) {
return getUint256(_NEXT_IMPLEMENTATION_TIMESTAMP_SLOT);
}
uint256[50] private bigEmptySlot;
}
// Part: Governable
contract Governable is Initializable, SetGetAssembly {
event GovernanceUpdated(address newGovernance, address oldGovernance);
bytes32 internal constant _GOVERNANCE_SLOT =
0x597f9c7c685b907e823520bd45aeb3d58b505f86b2e41cd5b4cd5b6c72782950;
bytes32 internal constant _PENDING_GOVERNANCE_SLOT =
0xcd77091f18f9504fccf6140ab99e20533c811d470bb9a5a983d0edc0720fbf8c;
modifier onlyGovernance() {
require(_governance() == msg.sender, "Not governance");
_;
}
constructor() public {
assert(
_GOVERNANCE_SLOT ==
bytes32(
uint256(
keccak256("eip1967.mesh.finance.governable.governance")
) - 1
)
);
assert(
_PENDING_GOVERNANCE_SLOT ==
bytes32(
uint256(
keccak256(
"eip1967.mesh.finance.governable.pendingGovernance"
)
) - 1
)
);
}
function initializeGovernance(address _governance) public initializer {
_setGovernance(_governance);
}
function _setGovernance(address _governance) private {
setAddress(_GOVERNANCE_SLOT, _governance);
}
function _setPendingGovernance(address _pendingGovernance) private {
setAddress(_PENDING_GOVERNANCE_SLOT, _pendingGovernance);
}
function updateGovernance(address _newGovernance) public onlyGovernance {
require(
_newGovernance != address(0),
"new governance shouldn't be empty"
);
_setPendingGovernance(_newGovernance);
}
function acceptGovernance() public {
require(_pendingGovernance() == msg.sender, "Not pending governance");
address oldGovernance = _governance();
_setGovernance(msg.sender);
emit GovernanceUpdated(msg.sender, oldGovernance);
}
function _governance() internal view returns (address str) {
return getAddress(_GOVERNANCE_SLOT);
}
function _pendingGovernance() internal view returns (address str) {
return getAddress(_PENDING_GOVERNANCE_SLOT);
}
function governance() public view returns (address) {
return _governance();
}
}
// Part: OpenZeppelin/[email protected]/ContextUpgradeable
/*
* @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 ContextUpgradeable is Initializable {
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;
}
// Part: OpenZeppelin/[email protected]/ReentrancyGuardUpgradeable
/**
* @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 ReentrancyGuardUpgradeable is Initializable {
// 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;
function __ReentrancyGuard_init() internal initializer {
__ReentrancyGuard_init_unchained();
}
function __ReentrancyGuard_init_unchained() internal initializer {
_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;
}
uint256[49] private __gap;
}
// Part: OpenZeppelin/[email protected]/ERC20Upgradeable
/**
* @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 ERC20Upgradeable is Initializable, ContextUpgradeable, IERC20Upgradeable {
using SafeMathUpgradeable 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.
*/
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 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 {_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 virtual 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 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 virtual {
_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: Fund.sol
contract Fund is
ERC20Upgradeable,
ReentrancyGuardUpgradeable,
IFund,
Governable,
FundStorage
{
using SafeERC20 for IERC20;
using AddressUpgradeable for address;
using SafeMathUpgradeable for uint256;
using SafeMathUpgradeable for uint8;
event Withdraw(address indexed beneficiary, uint256 amount);
event Deposit(address indexed beneficiary, uint256 amount);
event InvestInStrategy(address indexed strategy, uint256 amount);
event StrategyRewards(
address indexed strategy,
uint256 profit,
uint256 strategyCreatorFee
);
event FundManagerRewards(uint256 profitTotal, uint256 fundManagerFee);
event PlatformRewards(
uint256 lastBalance,
uint256 timeElapsed,
uint256 platformFee
);
event HardWorkDone(uint256 totalValueLocked, uint256 pricePerShare);
event StrategyAdded(
address indexed strategy,
uint256 weightage,
uint256 performanceFeeStrategy
);
event StrategyWeightageUpdated(
address indexed strategy,
uint256 newWeightage
);
event StrategyPerformanceFeeUpdated(
address indexed strategy,
uint256 newPerformanceFeeStrategy
);
event StrategyRemoved(address indexed strategy);
address internal constant ZERO_ADDRESS = address(0);
uint256 internal constant MAX_BPS = 10000; // 100% in basis points
uint256 internal constant SECS_PER_YEAR = 31556952; // 365.25 days from yearn
uint256 internal constant MAX_PLATFORM_FEE = 500; // 5% (annual on AUM), goes to governance/treasury
uint256 internal constant MAX_PERFORMANCE_FEE_FUND = 1000; // 10% on profits, goes to fund manager
uint256 internal constant MAX_PERFORMANCE_FEE_STRATEGY = 1000; // 10% on profits, goes to strategy creator
uint256 internal constant MAX_ACTIVE_STRATEGIES = 10; // To save on potential out of gas issues
struct StrategyParams {
uint256 weightage; // weightage of total assets in fund this strategy can access (in BPS) (5000 for 50%)
uint256 performanceFeeStrategy; // in BPS, fee on yield of the strategy, goes to strategy creator
uint256 activation; // timestamp when strategy is added
uint256 lastBalance; // balance at last hard work
uint256 indexInList;
}
mapping(address => StrategyParams) public strategies;
address[] public strategyList;
// solhint-disable-next-line no-empty-blocks
constructor() public {}
function initializeFund(
address _governance,
address _underlying,
string memory _name,
string memory _symbol
) external initializer {
require(_governance != ZERO_ADDRESS, "governance must be defined");
require(_underlying != ZERO_ADDRESS, "underlying must be defined");
ERC20Upgradeable.__ERC20_init(_name, _symbol);
__ReentrancyGuard_init();
Governable.initializeGovernance(_governance);
uint8 _decimals = ERC20Upgradeable(_underlying).decimals();
uint256 _underlyingUnit = 10**uint256(_decimals);
uint256 _changeDelay = 12 hours;
FundStorage.initializeFundStorage(
_underlying,
_underlyingUnit,
_decimals,
_governance, // fund manager is initialized as governance
_governance, // relayer is initialized as governance
_governance, // rewards contract is initialized as governance
_changeDelay
);
}
modifier onlyFundManager {
require(_fundManager() == msg.sender, "Not fund manager");
_;
}
modifier onlyFundManagerOrGovernance() {
require(
(_governance() == msg.sender) || (_fundManager() == msg.sender),
"Not governance or fund manager"
);
_;
}
modifier onlyFundManagerOrRelayer() {
require(
(_fundManager() == msg.sender) || (_relayer() == msg.sender),
"Not fund manager or relayer"
);
_;
}
modifier whenDepositsNotPaused() {
require(!_depositsPaused(), "Deposits are paused");
_;
}
function fundManager() external view override returns (address) {
return _fundManager();
}
function relayer() external view override returns (address) {
return _relayer();
}
function underlying() external view override returns (address) {
return _underlying();
}
function underlyingUnit() external view returns (uint256) {
return _underlyingUnit();
}
function decimals() public view virtual override returns (uint8) {
return _decimals();
}
function _getStrategyCount() internal view returns (uint256) {
return strategyList.length;
}
modifier whenStrategyDefined() {
require(_getStrategyCount() > 0, "Strategies must be defined");
_;
}
function getStrategyList() public view returns (address[] memory) {
return strategyList;
}
function getStrategy(address strategy)
public
view
returns (StrategyParams memory)
{
return strategies[strategy];
}
/*
* Returns the underlying balance currently in the fund.
*/
function underlyingBalanceInFund() internal view returns (uint256) {
return IERC20(_underlying()).balanceOf(address(this));
}
/*
* Returns the current underlying (e.g., DAI's) balance together with
* the invested amount (if DAI is invested elsewhere by the strategies).
*/
function underlyingBalanceWithInvestment() internal view returns (uint256) {
uint256 underlyingBalance = underlyingBalanceInFund();
for (uint256 i; i < _getStrategyCount(); i++) {
underlyingBalance = underlyingBalance.add(
IStrategy(strategyList[i]).investedUnderlyingBalance()
);
}
return underlyingBalance;
}
/*
* Returns price per share, scaled by underlying unit (10 ** decimals) to keep everything in uint256.
*/
function _getPricePerShare() internal view returns (uint256) {
return
totalSupply() == 0
? _underlyingUnit()
: _underlyingUnit().mul(underlyingBalanceWithInvestment()).div(
totalSupply()
);
}
function getPricePerShare() external view override returns (uint256) {
return _getPricePerShare();
}
function totalValueLocked() external view override returns (uint256) {
return underlyingBalanceWithInvestment();
}
function underlyingFromShares(uint256 _numShares)
external
view
returns (uint256)
{
return _underlyingFromShares(_numShares);
}
function _underlyingFromShares(uint256 numShares)
internal
view
returns (uint256)
{
return
underlyingBalanceWithInvestment().mul(numShares).div(totalSupply());
}
/*
* get the user's balance (in underlying)
*/
function underlyingBalanceWithInvestmentForHolder(address holder)
external
view
override
returns (uint256)
{
if (totalSupply() == 0) {
return 0;
}
return _underlyingFromShares(balanceOf(holder));
}
function isActiveStrategy(address strategy) internal view returns (bool) {
return strategies[strategy].weightage > 0;
}
function addStrategy(
address newStrategy,
uint256 weightage,
uint256 performanceFeeStrategy
) external onlyFundManager {
require(newStrategy != ZERO_ADDRESS, "new newStrategy cannot be empty");
require(
IStrategy(newStrategy).fund() == address(this),
"The strategy does not belong to this fund"
);
require(
isActiveStrategy(newStrategy) == false,
"This strategy is already active in this fund"
);
require(
_getStrategyCount() + 1 <= MAX_ACTIVE_STRATEGIES,
"Can not add more strategies"
);
require(weightage > 0, "The weightage should be greater than 0");
uint256 totalWeightInStrategies =
_totalWeightInStrategies().add(weightage);
require(
totalWeightInStrategies <= _maxInvestmentInStrategies(),
"Total investment can't be above max allowed"
);
require(
performanceFeeStrategy <= MAX_PERFORMANCE_FEE_STRATEGY,
"Performance fee too high"
);
strategies[newStrategy].weightage = weightage;
_setTotalWeightInStrategies(totalWeightInStrategies);
// solhint-disable-next-line not-rely-on-time
strategies[newStrategy].activation = block.timestamp;
strategies[newStrategy].indexInList = _getStrategyCount();
strategies[newStrategy].performanceFeeStrategy = performanceFeeStrategy;
strategyList.push(newStrategy);
_setShouldRebalance(true);
emit StrategyAdded(newStrategy, weightage, performanceFeeStrategy);
}
function removeStrategy(address activeStrategy)
external
onlyFundManagerOrGovernance
{
require(
activeStrategy != ZERO_ADDRESS,
"current strategy cannot be empty"
);
require(
isActiveStrategy(activeStrategy),
"This strategy is not active in this fund"
);
_setTotalWeightInStrategies(
_totalWeightInStrategies().sub(strategies[activeStrategy].weightage)
);
uint256 totalStrategies = _getStrategyCount();
if (totalStrategies > 1) {
uint256 i = strategies[activeStrategy].indexInList;
if (i != (totalStrategies - 1)) {
strategyList[i] = strategyList[totalStrategies - 1];
strategies[strategyList[i]].indexInList = i;
}
}
strategyList.pop();
delete strategies[activeStrategy];
IStrategy(activeStrategy).withdrawAllToFund();
_setShouldRebalance(true);
emit StrategyRemoved(activeStrategy);
}
function updateStrategyWeightage(
address activeStrategy,
uint256 newWeightage
) external onlyFundManager {
require(
activeStrategy != ZERO_ADDRESS,
"current strategy cannot be empty"
);
require(
isActiveStrategy(activeStrategy),
"This strategy is not active in this fund"
);
require(newWeightage > 0, "The weightage should be greater than 0");
uint256 totalWeightInStrategies =
_totalWeightInStrategies()
.sub(strategies[activeStrategy].weightage)
.add(newWeightage);
require(
totalWeightInStrategies <= _maxInvestmentInStrategies(),
"Total investment can't be above max allowed"
);
_setTotalWeightInStrategies(totalWeightInStrategies);
strategies[activeStrategy].weightage = newWeightage;
_setShouldRebalance(true);
emit StrategyWeightageUpdated(activeStrategy, newWeightage);
}
function updateStrategyPerformanceFee(
address activeStrategy,
uint256 newPerformanceFeeStrategy
) external onlyFundManager {
require(
activeStrategy != ZERO_ADDRESS,
"current strategy cannot be empty"
);
require(
isActiveStrategy(activeStrategy),
"This strategy is not active in this fund"
);
require(
newPerformanceFeeStrategy <= MAX_PERFORMANCE_FEE_STRATEGY,
"Performance fee too high"
);
strategies[activeStrategy]
.performanceFeeStrategy = newPerformanceFeeStrategy;
emit StrategyPerformanceFeeUpdated(
activeStrategy,
newPerformanceFeeStrategy
);
}
/**
*** This checks for all the three fees,
*** strategy creator fee (on profit) for each strategy,
*** fund manager fee (on total fund profit),
*** and platform fee based on assets under management.
*** The fee is calculated in underlying, and disbursed in fund shares.
*** Fund shares are minted for the same using current price per share of the fund.
*** This is same as getting the fee in underlying and
*** then depositing the underlying back in the fund.
**/
function processFees() internal {
uint256 totalStrategies = _getStrategyCount();
uint256[] memory strategyCreatorFees = new uint256[](totalStrategies);
uint256[] memory strategyProfits = new uint256[](totalStrategies);
uint256 profitToFund = 0; // Profit to fund is the profit from each strategy minus the fee paid out to strategy creators.
uint256 totalFee = 0; // This will represent the total fee in underlying and will be used to mint fund shares.
for (uint256 i; i < totalStrategies; i++) {
address strategy = strategyList[i];
uint256 profit = 0; // Profit for this strategy
uint256 strategyCreatorFee = 0;
if (
// If there is profit
IStrategy(strategy).investedUnderlyingBalance() >
strategies[strategy].lastBalance
) {
profit =
IStrategy(strategy).investedUnderlyingBalance() -
strategies[strategy].lastBalance; // Profit for this strategy
strategyCreatorFee = profit
.mul(strategies[strategy].performanceFeeStrategy)
.div(MAX_BPS); // Fee to be paid to the creator based on the profit it made in the last cycle
strategyProfits[i] = profit;
strategyCreatorFees[i] = strategyCreatorFee;
totalFee = totalFee.add(strategyCreatorFee);
profitToFund = profitToFund.add(profit).sub(strategyCreatorFee);
}
strategies[strategy].lastBalance = IStrategy(strategy)
.investedUnderlyingBalance(); // Update the last balance
}
uint256 fundManagerFee =
profitToFund.mul(_performanceFeeFund()).div(MAX_BPS); // Fee to be paid to the fund manager based on the profit fund made in the last cycle
totalFee = totalFee.add(fundManagerFee);
uint256 timeSinceLastHardwork =
// solhint-disable-next-line not-rely-on-time
block.timestamp.sub(_lastHardworkTimestamp()); // The time between 2 hardwork cycles
uint256 totalInvested = _totalInvested(); // Was updated during last cycle of hard work
uint256 platformFee =
totalInvested.mul(timeSinceLastHardwork).mul(_platformFee()).div(
MAX_BPS * SECS_PER_YEAR
); // Platform fee is based on the AUM
totalFee = totalFee.add(platformFee);
uint256 totalFeeInShares =
(totalFee == 0 || totalSupply() == 0)
? totalFee
: totalFee.mul(totalSupply()).div(
underlyingBalanceWithInvestment()
); // If total fee is zero, totalFeeInShares is also 0. Otherwise, go to default share calculation. Similar to deposit.
if (totalFeeInShares > 0) {
_mint(address(this), totalFeeInShares); // Mint all the fee shares once to save on gas and have a consistent price per share for all.
}
// From the total minted shares, each strategy creator, fund manager and platform will get shares in the ratio of the fees.
for (uint256 i; i < totalStrategies; i++) {
if (strategyCreatorFees[i] > 0) {
uint256 strategyCreatorFeeInShares =
totalFeeInShares.mul(strategyCreatorFees[i]).div(totalFee);
if (strategyCreatorFeeInShares > 0) {
address strategy = strategyList[i];
IERC20(address(this)).safeTransfer(
IStrategy(strategy).creator(),
strategyCreatorFeeInShares
); // Transfer the shares to strategy creator
emit StrategyRewards(
strategy,
strategyProfits[i],
strategyCreatorFeeInShares
);
}
}
}
if (fundManagerFee > 0) {
uint256 fundManagerFeeInShares =
totalFeeInShares.mul(fundManagerFee).div(totalFee);
if (fundManagerFeeInShares > 0) {
address fundManagerRewards =
(_fundManager() == _governance())
? _platformRewards()
: _fundManager();
IERC20(address(this)).safeTransfer(
fundManagerRewards,
fundManagerFeeInShares
); // Transfer the shares to fund manager
emit FundManagerRewards(profitToFund, fundManagerFeeInShares);
}
}
if (platformFee > 0) {
uint256 platformFeeInShares =
totalFeeInShares.mul(platformFee).div(totalFee);
emit PlatformRewards(
totalInvested,
timeSinceLastHardwork,
platformFeeInShares
);
}
// transfer the rest including platformFeeInShares and any dust remaining
// (since this contract will never have shares of itself apart from fees.)
uint256 selfBalance = IERC20(address(this)).balanceOf(address(this));
if (selfBalance > 0) {
IERC20(address(this)).safeTransfer(_platformRewards(), selfBalance);
}
}
/*
* Invests the underlying capital to various strategies. Looks for weightage changes.
*/
function doHardWork()
external
nonReentrant
whenStrategyDefined
onlyFundManagerOrRelayer
{
if (_lastHardworkTimestamp() > 0) {
processFees();
}
// ensure that new funds are invested too
if (_shouldRebalance()) {
_setShouldRebalance(false);
doHardWorkWithRebalance();
} else {
doHardWorkWithoutRebalance();
}
// solhint-disable-next-line not-rely-on-time
_setLastHardworkTimestamp(block.timestamp);
emit HardWorkDone(
underlyingBalanceWithInvestment(),
_getPricePerShare()
);
}
function doHardWorkWithoutRebalance() internal {
uint256 totalAccounted = _totalAccounted();
uint256 lastReserve =
totalAccounted > 0 ? totalAccounted.sub(_totalInvested()) : 0;
uint256 availableAmountToInvest =
underlyingBalanceInFund() > lastReserve
? underlyingBalanceInFund().sub(lastReserve)
: 0;
// if (availableAmountToInvest == 0) {
// return;
// }
_setTotalAccounted(totalAccounted.add(availableAmountToInvest));
uint256 totalInvested = 0;
for (uint256 i; i < _getStrategyCount(); i++) {
address strategy = strategyList[i];
uint256 availableAmountForStrategy =
availableAmountToInvest.mul(strategies[strategy].weightage).div(
MAX_BPS
);
if (availableAmountForStrategy > 0) {
IERC20(_underlying()).safeTransfer(
strategy,
availableAmountForStrategy
);
totalInvested = totalInvested.add(availableAmountForStrategy);
emit InvestInStrategy(strategy, availableAmountForStrategy);
}
IStrategy(strategy).doHardWork();
strategies[strategy].lastBalance = IStrategy(strategy)
.investedUnderlyingBalance();
}
_setTotalInvested(totalInvested);
}
function doHardWorkWithRebalance() internal {
uint256 totalUnderlyingWithInvestment =
underlyingBalanceWithInvestment();
_setTotalAccounted(totalUnderlyingWithInvestment);
uint256 totalInvested = 0;
uint256 totalStrategies = _getStrategyCount();
uint256[] memory toDeposit = new uint256[](totalStrategies);
for (uint256 i; i < totalStrategies; i++) {
address strategy = strategyList[i];
uint256 shouldBeInStrategy =
totalUnderlyingWithInvestment
.mul(strategies[strategy].weightage)
.div(MAX_BPS);
totalInvested = totalInvested.add(shouldBeInStrategy);
uint256 currentlyInStrategy =
IStrategy(strategy).investedUnderlyingBalance();
if (currentlyInStrategy > shouldBeInStrategy) {
// withdraw from strategy
IStrategy(strategy).withdrawToFund(
currentlyInStrategy.sub(shouldBeInStrategy)
);
} else if (shouldBeInStrategy > currentlyInStrategy) {
// can not directly deposit here as there might not be enough balance before withdrawing from required strategies
toDeposit[i] = shouldBeInStrategy.sub(currentlyInStrategy);
}
}
_setTotalInvested(totalInvested);
for (uint256 i; i < totalStrategies; i++) {
address strategy = strategyList[i];
if (toDeposit[i] > 0) {
IERC20(_underlying()).safeTransfer(strategy, toDeposit[i]);
emit InvestInStrategy(strategy, toDeposit[i]);
}
IStrategy(strategy).doHardWork();
strategies[strategy].lastBalance = IStrategy(strategy)
.investedUnderlyingBalance();
}
}
function pauseDeposits(bool trigger) external onlyFundManagerOrGovernance {
_setDepositsPaused(trigger);
}
/*
* Allows for depositing the underlying asset in exchange for shares.
* Approval is assumed.
*/
function deposit(uint256 amount)
external
override
nonReentrant
whenDepositsNotPaused
{
_deposit(amount, msg.sender, msg.sender);
}
/*
* Allows for depositing the underlying asset and shares assigned to the holder.
* This facilitates depositing for someone else (e.g. using DepositHelper)
*/
function depositFor(uint256 amount, address holder)
external
override
nonReentrant
whenDepositsNotPaused
{
require(holder != ZERO_ADDRESS, "holder must be defined");
_deposit(amount, msg.sender, holder);
}
function _deposit(
uint256 amount,
address sender,
address beneficiary
) internal {
require(amount > 0, "Cannot deposit 0");
if (_depositLimit() > 0) {
// if deposit limit is 0, then there is no deposit limit
require(
underlyingBalanceWithInvestment().add(amount) <=
_depositLimit(),
"Total deposit limit hit"
);
}
if (_depositLimitTxMax() > 0) {
// if deposit limit is 0, then there is no deposit limit
require(
amount <= _depositLimitTxMax(),
"Maximum transaction deposit limit hit"
);
}
if (_depositLimitTxMin() > 0) {
// if deposit limit is 0, then there is no deposit limit
require(
amount >= _depositLimitTxMin(),
"Minimum transaction deposit limit hit"
);
}
uint256 toMint =
totalSupply() == 0
? amount
: amount.mul(totalSupply()).div(
underlyingBalanceWithInvestment()
);
_mint(beneficiary, toMint);
IERC20(_underlying()).safeTransferFrom(sender, address(this), amount);
emit Deposit(beneficiary, amount);
}
function withdraw(uint256 numberOfShares) external override nonReentrant {
require(totalSupply() > 0, "Fund has no shares");
require(numberOfShares > 0, "numberOfShares must be greater than 0");
uint256 underlyingAmountToWithdraw =
_underlyingFromShares(numberOfShares);
require(underlyingAmountToWithdraw > 0, "Can't withdraw 0");
_burn(msg.sender, numberOfShares);
if (underlyingAmountToWithdraw == underlyingBalanceInFund()) {
_setShouldRebalance(true);
} else if (underlyingAmountToWithdraw > underlyingBalanceInFund()) {
uint256 missing =
underlyingAmountToWithdraw.sub(underlyingBalanceInFund());
uint256 missingCarryOver;
for (uint256 i; i < _getStrategyCount(); i++) {
if (isActiveStrategy(strategyList[i])) {
uint256 balanceBefore = underlyingBalanceInFund();
uint256 weightage = strategies[strategyList[i]].weightage;
uint256 missingforStrategy =
(missing.mul(weightage).div(_totalWeightInStrategies()))
.add(missingCarryOver);
IStrategy(strategyList[i]).withdrawToFund(
missingforStrategy
);
missingCarryOver = missingforStrategy
.add(balanceBefore)
.sub(underlyingBalanceInFund());
}
}
// recalculate to improve accuracy
underlyingAmountToWithdraw = MathUpgradeable.min(
underlyingAmountToWithdraw,
underlyingBalanceInFund()
);
_setShouldRebalance(true);
}
IERC20(_underlying()).safeTransfer(
msg.sender,
underlyingAmountToWithdraw
);
emit Withdraw(msg.sender, underlyingAmountToWithdraw);
}
/**
* Schedules an upgrade for this fund's proxy.
*/
function scheduleUpgrade(address newImplementation)
external
onlyGovernance
{
require(
newImplementation != ZERO_ADDRESS,
"new implementation address can not be zero address"
);
require(
newImplementation != IFundProxy(address(this)).implementation(),
"new implementation address should not be same as current address"
);
_setNextImplementation(newImplementation);
// solhint-disable-next-line not-rely-on-time
_setNextImplementationTimestamp(block.timestamp.add(_changeDelay()));
}
function shouldUpgrade() external view returns (bool, address) {
return (
_nextImplementationTimestamp() != 0 &&
// solhint-disable-next-line not-rely-on-time
block.timestamp > _nextImplementationTimestamp() &&
_nextImplementation() != ZERO_ADDRESS,
_nextImplementation()
);
}
function finalizeUpgrade() external onlyGovernance {
_setNextImplementation(ZERO_ADDRESS);
_setNextImplementationTimestamp(0);
}
function setFundManager(address newFundManager)
external
onlyFundManagerOrGovernance
{
_setFundManager(newFundManager);
}
function setRelayer(address newRelayer) external onlyFundManager {
_setRelayer(newRelayer);
}
function setPlatformRewards(address newRewards) external onlyGovernance {
_setPlatformRewards(newRewards);
}
function setShouldRebalance(bool trigger) external onlyFundManager {
_setShouldRebalance(trigger);
}
function setMaxInvestmentInStrategies(uint256 value)
external
onlyFundManager
{
require(value < MAX_BPS, "Value greater than 100%");
_setMaxInvestmentInStrategies(value);
}
// if limit == 0 then there is no deposit limit
function setDepositLimit(uint256 limit) external onlyFundManager {
_setDepositLimit(limit);
}
function depositLimit() external view returns (uint256) {
return _depositLimit();
}
// if limit == 0 then there is no deposit limit
function setDepositLimitTxMax(uint256 limit) external onlyFundManager {
require(
_depositLimitTxMin() == 0 || limit > _depositLimitTxMin(),
"Max limit greater than min limit"
);
_setDepositLimitTxMax(limit);
}
function depositLimitTxMax() external view returns (uint256) {
return _depositLimitTxMax();
}
// if limit == 0 then there is no deposit limit
function setDepositLimitTxMin(uint256 limit) external onlyFundManager {
require(
_depositLimitTxMax() == 0 || limit < _depositLimitTxMax(),
"Min limit greater than max limit"
);
_setDepositLimitTxMin(limit);
}
function depositLimitTxMin() external view returns (uint256) {
return _depositLimitTxMin();
}
function setPerformanceFeeFund(uint256 fee) external onlyFundManager {
require(fee <= MAX_PERFORMANCE_FEE_FUND, "Fee greater than max limit");
_setPerformanceFeeFund(fee);
}
function performanceFeeFund() external view returns (uint256) {
return _performanceFeeFund();
}
function setPlatformFee(uint256 fee) external onlyGovernance {
require(fee <= MAX_PLATFORM_FEE, "Fee greater than max limit");
_setPlatformFee(fee);
}
function platformFee() external view returns (uint256) {
return _platformFee();
}
// no tokens should ever be stored on this contract. Any tokens that are sent here by mistake are recoverable by governance
function sweep(address _token, address _sweepTo) external onlyGovernance {
require(_token != address(_underlying()), "can not sweep underlying");
require(_sweepTo != ZERO_ADDRESS, "can not sweep to zero");
IERC20(_token).safeTransfer(
_sweepTo,
IERC20(_token).balanceOf(address(this))
);
}
} | withdraw from strategy can not directly deposit here as there might not be enough balance before withdrawing from required strategies | function doHardWorkWithRebalance() internal {
uint256 totalUnderlyingWithInvestment =
underlyingBalanceWithInvestment();
_setTotalAccounted(totalUnderlyingWithInvestment);
uint256 totalInvested = 0;
uint256 totalStrategies = _getStrategyCount();
uint256[] memory toDeposit = new uint256[](totalStrategies);
for (uint256 i; i < totalStrategies; i++) {
address strategy = strategyList[i];
uint256 shouldBeInStrategy =
totalUnderlyingWithInvestment
.mul(strategies[strategy].weightage)
.div(MAX_BPS);
totalInvested = totalInvested.add(shouldBeInStrategy);
uint256 currentlyInStrategy =
IStrategy(strategy).investedUnderlyingBalance();
if (currentlyInStrategy > shouldBeInStrategy) {
IStrategy(strategy).withdrawToFund(
currentlyInStrategy.sub(shouldBeInStrategy)
);
toDeposit[i] = shouldBeInStrategy.sub(currentlyInStrategy);
}
}
_setTotalInvested(totalInvested);
for (uint256 i; i < totalStrategies; i++) {
address strategy = strategyList[i];
if (toDeposit[i] > 0) {
IERC20(_underlying()).safeTransfer(strategy, toDeposit[i]);
emit InvestInStrategy(strategy, toDeposit[i]);
}
IStrategy(strategy).doHardWork();
strategies[strategy].lastBalance = IStrategy(strategy)
.investedUnderlyingBalance();
}
}
| 6,678,142 | [
1,
1918,
9446,
628,
6252,
848,
486,
5122,
443,
1724,
2674,
487,
1915,
4825,
486,
506,
7304,
11013,
1865,
598,
9446,
310,
628,
1931,
20417,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
565,
445,
741,
29601,
2421,
1190,
426,
12296,
1435,
2713,
288,
203,
3639,
2254,
5034,
2078,
14655,
6291,
1190,
3605,
395,
475,
273,
203,
5411,
6808,
13937,
1190,
3605,
395,
475,
5621,
203,
3639,
389,
542,
5269,
3032,
329,
12,
4963,
14655,
6291,
1190,
3605,
395,
475,
1769,
203,
3639,
2254,
5034,
2078,
3605,
3149,
273,
374,
31,
203,
3639,
2254,
5034,
2078,
1585,
15127,
273,
389,
588,
4525,
1380,
5621,
203,
3639,
2254,
5034,
8526,
3778,
358,
758,
1724,
273,
394,
2254,
5034,
8526,
12,
4963,
1585,
15127,
1769,
203,
203,
3639,
364,
261,
11890,
5034,
277,
31,
277,
411,
2078,
1585,
15127,
31,
277,
27245,
288,
203,
5411,
1758,
6252,
273,
6252,
682,
63,
77,
15533,
203,
5411,
2254,
5034,
1410,
1919,
382,
4525,
273,
203,
7734,
2078,
14655,
6291,
1190,
3605,
395,
475,
203,
10792,
263,
16411,
12,
701,
15127,
63,
14914,
8009,
4865,
410,
13,
203,
10792,
263,
2892,
12,
6694,
67,
38,
5857,
1769,
203,
5411,
2078,
3605,
3149,
273,
2078,
3605,
3149,
18,
1289,
12,
13139,
1919,
382,
4525,
1769,
203,
5411,
2254,
5034,
4551,
382,
4525,
273,
203,
7734,
467,
4525,
12,
14914,
2934,
5768,
3149,
14655,
6291,
13937,
5621,
203,
5411,
309,
261,
2972,
715,
382,
4525,
405,
1410,
1919,
382,
4525,
13,
288,
203,
7734,
467,
4525,
12,
14914,
2934,
1918,
9446,
774,
42,
1074,
12,
203,
10792,
4551,
382,
4525,
18,
1717,
12,
13139,
1919,
382,
4525,
13,
203,
7734,
11272,
203,
7734,
358,
758,
1724,
63,
77,
65,
273,
1410,
1919,
382,
4525,
2
] |
./partial_match/1/0xf727413bEdeD1690EE800782917bC0D6098A767f/sources/PEPE.sol | generate the uniswap pair path of token -> weth make the swap | function swapTokensForEth(uint256 tokenAmount) private {
address[] memory path = new address[](2);
path[0] = address(this);
path[1] = uniswapV2Router.WETH();
_approve(address(this), address(uniswapV2Router), tokenAmount);
uniswapV2Router.swapExactTokensForETHSupportingFeeOnTransferTokens(
tokenAmount,
path,
address(this),
block.timestamp
);
}
| 3,911,675 | [
1,
7163,
326,
640,
291,
91,
438,
3082,
589,
434,
1147,
317,
341,
546,
1221,
326,
7720,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
565,
445,
7720,
5157,
1290,
41,
451,
12,
11890,
5034,
1147,
6275,
13,
3238,
288,
203,
7010,
3639,
1758,
8526,
3778,
589,
273,
394,
1758,
8526,
12,
22,
1769,
203,
3639,
589,
63,
20,
65,
273,
1758,
12,
2211,
1769,
203,
3639,
589,
63,
21,
65,
273,
640,
291,
91,
438,
58,
22,
8259,
18,
59,
1584,
44,
5621,
203,
7010,
3639,
389,
12908,
537,
12,
2867,
12,
2211,
3631,
1758,
12,
318,
291,
91,
438,
58,
22,
8259,
3631,
1147,
6275,
1769,
203,
7010,
3639,
640,
291,
91,
438,
58,
22,
8259,
18,
22270,
14332,
5157,
1290,
1584,
44,
6289,
310,
14667,
1398,
5912,
5157,
12,
203,
5411,
1147,
6275,
16,
203,
5411,
589,
16,
203,
5411,
1758,
12,
2211,
3631,
203,
5411,
1203,
18,
5508,
203,
3639,
11272,
203,
7010,
565,
289,
203,
202,
203,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
] |
pragma solidity ^0.4.11;
/**
* @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;
}
}
/**
* @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;
/**
* @dev The Ownable constructor sets the original `owner` of the contract to the sender
* account.
*/
function Ownable() {
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) onlyOwner {
require(newOwner != address(0));
owner = newOwner;
}
}
/**
* @title ERC20Basic
* @dev Simpler version of ERC20 interface
* @dev see https://github.com/ethereum/EIPs/issues/179
*/
contract ERC20Basic {
uint256 public totalSupply;
function balanceOf(address who) constant returns (uint256);
function transfer(address to, uint256 value) 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) constant returns (uint256);
function transferFrom(address from, address to, uint256 value) returns (bool);
function approve(address spender, uint256 value) returns (bool);
event Approval(address indexed owner, address indexed spender, uint256 value);
}
/**
* @title PoSTokenStandard
* @dev the interface of PoSTokenStandard
*/
contract STAKDStandard {
uint256 public stakeStartTime;
uint256 public stakeMinAge;
uint256 public stakeMaxAge;
function mint() returns (bool);
function coinAge() constant returns (uint256);
function annualInterest() constant returns (uint256);
event Mint(address indexed _address, uint _reward);
}
contract STAKDToken is ERC20,STAKDStandard,Ownable {
using SafeMath for uint256;
string public name = "STAKD Token";
string public symbol = "SKD";
uint public decimals = 18;
uint public chainStartTime; //chain start time
uint public chainStartBlockNumber; //chain start block number
uint public stakeStartTime; //stake start time
uint public stakeMinAge = 1 days; // minimum age for coin age: 1D
uint public stakeMaxAge = 90 days; // stake age of full weight: 90D
uint public maxMintProofOfStake = 10**17; // default 10% annual interest
uint public totalSupply;
uint public maxTotalSupply;
uint public totalInitialSupply;
address treasury;
struct transferInStruct{
uint128 amount;
uint64 time;
}
mapping(address => uint256) balances;
mapping(address => mapping (address => uint256)) allowed;
mapping(address => transferInStruct[]) transferIns;
event TreasuryChange(address caller, address treasury);
event Burn(address indexed burner, uint256 value);
/**
* @dev Fix for the ERC20 short address attack.
*/
modifier onlyPayloadSize(uint size) {
require(msg.data.length >= size + 4);
_;
}
modifier onlyTreasury() {
require (msg.sender == treasury);
_;
}
modifier canPoSMint() {
require(totalSupply < maxTotalSupply);
_;
}
function STAKDToken(address _treasury) {
maxTotalSupply = 10**25; // 10 Mil.
totalInitialSupply = 10**24; // 1 Mil.
chainStartTime = now;
chainStartBlockNumber = block.number;
treasury = _treasury;
balances[msg.sender] = totalInitialSupply;
totalSupply = totalInitialSupply;
}
function transfer(address _to, uint256 _value) onlyPayloadSize(2 * 32) returns (bool) {
if(msg.sender == _to) return mint();
balances[msg.sender] = balances[msg.sender].sub(_value);
balances[_to] = balances[_to].add(_value);
Transfer(msg.sender, _to, _value);
if(transferIns[msg.sender].length > 0) delete transferIns[msg.sender];
uint64 _now = uint64(now);
transferIns[msg.sender].push(transferInStruct(uint128(balances[msg.sender]),_now));
transferIns[_to].push(transferInStruct(uint128(_value),_now));
return true;
}
function changeTreasury(address _treasury) public onlyTreasury returns (bool) {
treasury = _treasury;
emit TreasuryChange(msg.sender, treasury);
return true;
}
function balanceOf(address _owner) constant returns (uint256 balance) {
return balances[_owner];
}
function transferFrom(address _from, address _to, uint256 _value) onlyPayloadSize(3 * 32) returns (bool) {
require(_to != address(0));
var _allowance = allowed[_from][msg.sender];
// Check is not needed because sub(_allowance, _value) will already throw if this condition is not met
// require (_value <= _allowance);
balances[_from] = balances[_from].sub(_value);
balances[_to] = balances[_to].add(_value);
allowed[_from][msg.sender] = _allowance.sub(_value);
Transfer(_from, _to, _value);
if(transferIns[_from].length > 0) delete transferIns[_from];
uint64 _now = uint64(now);
transferIns[_from].push(transferInStruct(uint128(balances[_from]),_now));
transferIns[_to].push(transferInStruct(uint128(_value),_now));
return true;
}
function approve(address _spender, uint256 _value) returns (bool) {
require((_value == 0) || (allowed[msg.sender][_spender] == 0));
allowed[msg.sender][_spender] = _value;
Approval(msg.sender, _spender, _value);
return true;
}
function allowance(address _owner, address _spender) constant returns (uint256 remaining) {
return allowed[_owner][_spender];
}
function mint() canPoSMint returns (bool) {
if(balances[msg.sender] <= 0) return false;
if(transferIns[msg.sender].length <= 0) return false;
uint reward = getProofOfStakeReward(msg.sender);
if(reward <= 0) return false;
uint senderReward = (reward * 90).div(100); // 90% goes to the holder, 10% goes to the Treasury
uint treasuryReward = reward - senderReward;
totalSupply = totalSupply.add(reward);
balances[msg.sender] = balances[msg.sender].add(senderReward);
balances[treasury] = balances[treasury].add(treasuryReward);
delete transferIns[msg.sender];
transferIns[msg.sender].push(transferInStruct(uint128(balances[msg.sender]),uint64(now)));
Mint(msg.sender, reward);
return true;
}
function getBlockNumber() returns (uint blockNumber) {
blockNumber = block.number.sub(chainStartBlockNumber);
}
function coinAge() constant returns (uint myCoinAge) {
myCoinAge = getCoinAge(msg.sender,now);
}
function annualInterest() constant returns(uint interest) {
uint _now = now;
interest = maxMintProofOfStake;
if((_now.sub(stakeStartTime)).div(1 years) == 0) {
interest = (770 * maxMintProofOfStake).div(100);
} else if((_now.sub(stakeStartTime)).div(1 years) == 1){
interest = (435 * maxMintProofOfStake).div(100);
}
}
function getProofOfStakeReward(address _address) internal returns (uint) {
require( (now >= stakeStartTime) && (stakeStartTime > 0) );
uint _now = now;
uint _coinAge = getCoinAge(_address, _now);
if(_coinAge <= 0) return 0;
uint interest = maxMintProofOfStake;
// Due to the high interest rate for the first two years, compounding should be taken into account.
// Effective annual interest rate = (1 + (nominal rate / number of compounding periods)) ^ (number of compounding periods) - 1
if((_now.sub(stakeStartTime)).div(1 years) == 0) {
// 1st year effective annual interest rate is 100% when we select the stakeMaxAge (90 days) as the compounding period.
interest = (770 * maxMintProofOfStake).div(100);
} else if((_now.sub(stakeStartTime)).div(1 years) == 1){
// 2nd year effective annual interest rate is 50%
interest = (435 * maxMintProofOfStake).div(100);
}
return (_coinAge * interest).div(365 * (10**decimals));
}
function getCoinAge(address _address, uint _now) internal returns (uint _coinAge) {
if(transferIns[_address].length <= 0) return 0;
for (uint i = 0; i < transferIns[_address].length; i++){
if( _now < uint(transferIns[_address][i].time).add(stakeMinAge) ) continue;
uint nCoinSeconds = _now.sub(uint(transferIns[_address][i].time));
if( nCoinSeconds > stakeMaxAge ) nCoinSeconds = stakeMaxAge;
_coinAge = _coinAge.add(uint(transferIns[_address][i].amount) * nCoinSeconds.div(1 days));
}
}
function ownerSetStakeStartTime(uint timestamp) onlyOwner {
require((stakeStartTime <= 0) && (timestamp >= chainStartTime));
stakeStartTime = timestamp;
}
function ownerBurnToken(uint _value) onlyOwner {
require(_value > 0);
balances[msg.sender] = balances[msg.sender].sub(_value);
delete transferIns[msg.sender];
transferIns[msg.sender].push(transferInStruct(uint128(balances[msg.sender]),uint64(now)));
totalSupply = totalSupply.sub(_value);
totalInitialSupply = totalInitialSupply.sub(_value);
maxTotalSupply = maxTotalSupply.sub(_value*10);
Burn(msg.sender, _value);
}
/* Batch token transfer. Used by contract creator to distribute initial tokens to holders */
function batchTransfer(address[] _recipients, uint[] _values) onlyOwner returns (bool) {
require( _recipients.length > 0 && _recipients.length == _values.length);
uint total = 0;
for(uint i = 0; i < _values.length; i++){
total = total.add(_values[i]);
}
require(total <= balances[msg.sender]);
uint64 _now = uint64(now);
for(uint j = 0; j < _recipients.length; j++){
balances[_recipients[j]] = balances[_recipients[j]].add(_values[j]);
transferIns[_recipients[j]].push(transferInStruct(uint128(_values[j]),_now));
Transfer(msg.sender, _recipients[j], _values[j]);
}
balances[msg.sender] = balances[msg.sender].sub(total);
if(transferIns[msg.sender].length > 0) delete transferIns[msg.sender];
if(balances[msg.sender] > 0) transferIns[msg.sender].push(transferInStruct(uint128(balances[msg.sender]),_now));
return true;
}
} | * @title PoSTokenStandard @dev the interface of PoSTokenStandard/ | contract STAKDStandard {
uint256 public stakeStartTime;
uint256 public stakeMinAge;
uint256 public stakeMaxAge;
function mint() returns (bool);
function coinAge() constant returns (uint256);
function annualInterest() constant returns (uint256);
event Mint(address indexed _address, uint _reward);
}
| 13,920,538 | [
1,
29198,
882,
969,
8336,
225,
326,
1560,
434,
453,
83,
882,
969,
8336,
19,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
16351,
2347,
14607,
40,
8336,
288,
203,
565,
2254,
5034,
1071,
384,
911,
13649,
31,
203,
565,
2254,
5034,
1071,
384,
911,
2930,
9692,
31,
203,
565,
2254,
5034,
1071,
384,
911,
2747,
9692,
31,
203,
565,
445,
312,
474,
1435,
1135,
261,
6430,
1769,
203,
565,
445,
13170,
9692,
1435,
5381,
1135,
261,
11890,
5034,
1769,
203,
565,
445,
8226,
1462,
29281,
1435,
5381,
1135,
261,
11890,
5034,
1769,
203,
565,
871,
490,
474,
12,
2867,
8808,
389,
2867,
16,
2254,
389,
266,
2913,
1769,
203,
97,
203,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
] |
pragma ton-solidity >= 0.53.0;
pragma AbiHeader time;
pragma AbiHeader pubkey;
pragma AbiHeader expire;
import "https://raw.githubusercontent.com/DeShir/everscale-service/8472e40e339e66af81b594d6b66082df8c425c01/src/main/solidity/debot/tezos/ITezosAccountService.sol";
import "https://raw.githubusercontent.com/tonlabs/debots/49eb9ea211c7146ba00895bcbe05b5e76d3c720c/Debot.sol";
import "../interface/_all.sol";
contract TezosWalletInitService is Debot, ITezosAccountServiceMenuItem, ITezosAccountServiceRun {
optional(address) private hostAddr;
/// @notice Entry point function for DeBot.
function start() public override {
}
/// @notice Returns Metadata about DeBot.
function getDebotInfo() public functionID(0xDEB) override view returns (
string name, string version, string publisher, string caption, string author,
address support, string hello, string language, string dabi, bytes icon
) {
name = "Tezos Wallet Init Service";
version = "0.1.0";
publisher = "ShiroKovka(Oba!=)";
caption = "";
author = "ShiroKovka";
support = address.makeAddrStd(0, 0xfe9a76f1a8584fbd8f092b20e917918969fc8a7b1759e9a8c15a7f907e4d72a5);
hello = "Hello";
language = "en";
dabi = m_debotAbi.get();
icon = "";
}
function getRequiredInterfaces() public view override returns (uint256[] interfaces) {
return [Terminal.ID];
}
function menuItem(TezosLibrary.Account request) override external responsible returns(MenuItem) {
return ITezosAccountServiceMenuItem.MenuItem("Input Tezos Wallet Address", "");
}
function run(TezosLibrary.Account request) override external {
hostAddr = msg.sender;
Terminal.input(tvm.functionId(requestAddressCallback), "Input Tezos Wallet Address, please", false);
}
function requestAddressCallback(string value) public {
if(hostAddr.hasValue()) {
ITezosAccountServiceCallback(hostAddr.get()).update(TezosLibrary.Account(value, null));
ITezosAccountServiceCallback(hostAddr.get()).finish();
}
}
}
| @notice Entry point function for DeBot. | function start() public override {
}
| 12,785,996 | [
1,
1622,
1634,
445,
364,
1505,
6522,
18,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
565,
445,
787,
1435,
1071,
3849,
288,
203,
203,
565,
289,
203,
203,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
] |
./full_match/3/0x2423D9D516f2a2E25880dCa4F2B1310eC945C65F/sources/contracts/4_test.sol | Marketing Wallet to recive BNB
| marketingWallet.transfer(newBalance.div(allFee).mul(_marketingFee)); | 8,245,316 | [
1,
3882,
21747,
20126,
358,
1950,
688,
605,
20626,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
3639,
13667,
310,
16936,
18,
13866,
12,
2704,
13937,
18,
2892,
12,
454,
14667,
2934,
16411,
24899,
3355,
21747,
14667,
10019,
225,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
] |
// SPDX-License-Identifier: Apache-2.0
pragma solidity ^0.8.0;
library ProtobufLib {
/// @notice Protobuf wire types.
enum WireType {
Varint,
Bits64,
LengthDelimited,
StartGroup,
EndGroup,
Bits32,
WIRE_TYPE_MAX
}
/// @dev Maximum number of bytes for a varint.
/// @dev 64 bits, in groups of base-128 (7 bits).
uint64 internal constant MAX_VARINT_BYTES = 10;
////////////////////////////////////
// Decoding
////////////////////////////////////
/// @notice Decode key.
/// @dev https://developers.google.com/protocol-buffers/docs/encoding#structure
/// @param p Position
/// @param buf Buffer
/// @return Success
/// @return New position
/// @return Field number
/// @return Wire type
function decode_key(uint64 p, bytes memory buf)
internal
pure
returns (
bool,
uint64,
uint64,
WireType
)
{
// The key is a varint with encoding
// (field_number << 3) | wire_type
(bool success, uint64 pos, uint64 key) = decode_varint(p, buf);
if (!success) {
return (false, pos, 0, WireType.WIRE_TYPE_MAX);
}
uint64 field_number = key >> 3;
uint64 wire_type_val = key & 0x07;
// Check that wire type is bounded
if (wire_type_val >= uint64(WireType.WIRE_TYPE_MAX)) {
return (false, pos, 0, WireType.WIRE_TYPE_MAX);
}
WireType wire_type = WireType(wire_type_val);
// Start and end group types are deprecated, so forbid them
if (wire_type == WireType.StartGroup || wire_type == WireType.EndGroup) {
return (false, pos, 0, WireType.WIRE_TYPE_MAX);
}
return (true, pos, field_number, wire_type);
}
/// @notice Decode varint.
/// @dev https://developers.google.com/protocol-buffers/docs/encoding#varints
/// @param p Position
/// @param buf Buffer
/// @return Success
/// @return New position
/// @return Decoded int
function decode_varint(uint64 p, bytes memory buf)
internal
pure
returns (
bool,
uint64,
uint64
)
{
uint64 val;
uint64 i;
for (i = 0; i < MAX_VARINT_BYTES; i++) {
// Check that index is within bounds
if (i + p >= buf.length) {
return (false, p, 0);
}
// Get byte at offset
uint8 b = uint8(buf[p + i]);
// Highest bit is used to indicate if there are more bytes to come
// Mask to get 7-bit value: 0111 1111
uint8 v = b & 0x7F;
// Groups of 7 bits are ordered least significant first
val |= uint64(v) << uint64(i * 7);
// Mask to get keep going bit: 1000 0000
if (b & 0x80 == 0) {
// [STRICT]
// Check for trailing zeroes if more than one byte is used
// (the value 0 still uses one byte)
if (i > 0 && v == 0) {
return (false, p, 0);
}
break;
}
}
// Check that at most MAX_VARINT_BYTES are used
if (i >= MAX_VARINT_BYTES) {
return (false, p, 0);
}
// [STRICT]
// If all 10 bytes are used, the last byte (most significant 7 bits)
// must be at most 0000 0001, since 7*9 = 63
if (i == MAX_VARINT_BYTES - 1) {
if (uint8(buf[p + i]) > 1) {
return (false, p, 0);
}
}
return (true, p + i + 1, val);
}
/// @notice Decode varint int32.
/// @param p Position
/// @param buf Buffer
/// @return Success
/// @return New position
/// @return Decoded int
function decode_int32(uint64 p, bytes memory buf)
internal
pure
returns (
bool,
uint64,
int32
)
{
(bool success, uint64 pos, uint64 val) = decode_varint(p, buf);
if (!success) {
return (false, pos, 0);
}
// [STRICT]
// Highest 4 bytes must be 0 if positive
if (val >> 63 == 0) {
if (val & 0xFFFFFFFF00000000 != 0) {
return (false, pos, 0);
}
}
return (true, pos, int32(uint32(val)));
}
/// @notice Decode varint int64.
/// @param p Position
/// @param buf Buffer
/// @return Success
/// @return New position
/// @return Decoded int
function decode_int64(uint64 p, bytes memory buf)
internal
pure
returns (
bool,
uint64,
int64
)
{
(bool success, uint64 pos, uint64 val) = decode_varint(p, buf);
if (!success) {
return (false, pos, 0);
}
return (true, pos, int64(val));
}
/// @notice Decode varint uint32.
/// @param p Position
/// @param buf Buffer
/// @return Success
/// @return New position
/// @return Decoded int
function decode_uint32(uint64 p, bytes memory buf)
internal
pure
returns (
bool,
uint64,
uint32
)
{
(bool success, uint64 pos, uint64 val) = decode_varint(p, buf);
if (!success) {
return (false, pos, 0);
}
// [STRICT]
// Highest 4 bytes must be 0
if (val & 0xFFFFFFFF00000000 != 0) {
return (false, pos, 0);
}
return (true, pos, uint32(val));
}
/// @notice Decode varint uint64.
/// @param p Position
/// @param buf Buffer
/// @return Success
/// @return New position
/// @return Decoded int
function decode_uint64(uint64 p, bytes memory buf)
internal
pure
returns (
bool,
uint64,
uint64
)
{
(bool success, uint64 pos, uint64 val) = decode_varint(p, buf);
if (!success) {
return (false, pos, 0);
}
return (true, pos, val);
}
/// @notice Decode varint sint32.
/// @param p Position
/// @param buf Buffer
/// @return Success
/// @return New position
/// @return Decoded int
function decode_sint32(uint64 p, bytes memory buf)
internal
pure
returns (
bool,
uint64,
int32
)
{
(bool success, uint64 pos, uint64 val) = decode_varint(p, buf);
if (!success) {
return (false, pos, 0);
}
// [STRICT]
// Highest 4 bytes must be 0
if (val & 0xFFFFFFFF00000000 != 0) {
return (false, pos, 0);
}
// https://stackoverflow.com/questions/2210923/zig-zag-decoding/2211086#2211086
// Fixed after sol 0.8.0
// prev version: (val >> 1) ^ -(val & 1);
uint64 zigzag_val;
unchecked {
zigzag_val = (val >> 1) - (~(val & 1) + 1);
}
return (true, pos, int32(uint32(zigzag_val)));
}
/// @notice Decode varint sint64.
/// @param p Position
/// @param buf Buffer
/// @return Success
/// @return New position
/// @return Decoded int
function decode_sint64(uint64 p, bytes memory buf)
internal
pure
returns (
bool,
uint64,
int64
)
{
(bool success, uint64 pos, uint64 val) = decode_varint(p, buf);
if (!success) {
return (false, pos, 0);
}
// https://stackoverflow.com/questions/2210923/zig-zag-decoding/2211086#2211086
// Fixed after sol 0.8.0
// prev version: (val >> 1) ^ -(val & 1);
uint64 zigzag_val;
unchecked {
zigzag_val = (val >> 1) - (~(val & 1) + 1);
}
return (true, pos, int64(zigzag_val));
}
/// @notice Decode Boolean.
/// @param p Position
/// @param buf Buffer
/// @return Success
/// @return New position
/// @return Decoded bool
function decode_bool(uint64 p, bytes memory buf)
internal
pure
returns (
bool,
uint64,
bool
)
{
(bool success, uint64 pos, uint64 val) = decode_varint(p, buf);
if (!success) {
return (false, pos, false);
}
// [STRICT]
// Value must be 0 or 1
if (val > 1) {
return (false, pos, false);
}
if (val == 0) {
return (true, pos, false);
}
return (true, pos, true);
}
/// @notice Decode enumeration.
/// @param p Position
/// @param buf Buffer
/// @return Success
/// @return New position
/// @return Decoded enum as raw int
function decode_enum(uint64 p, bytes memory buf)
internal
pure
returns (
bool,
uint64,
int32
)
{
return decode_int32(p, buf);
}
/// @notice Decode fixed 64-bit int.
/// @param p Position
/// @param buf Buffer
/// @return Success
/// @return New position
/// @return Decoded int
function decode_bits64(uint64 p, bytes memory buf)
internal
pure
returns (
bool,
uint64,
uint64
)
{
uint64 val;
// Check that index is within bounds
if (8 + p > buf.length) {
return (false, p, 0);
}
for (uint64 i = 0; i < 8; i++) {
uint8 b = uint8(buf[p + i]);
// Little endian
val |= uint64(b) << uint64(i * 8);
}
return (true, p + 8, val);
}
/// @notice Decode fixed uint64.
/// @param p Position
/// @param buf Buffer
/// @return Success
/// @return New position
/// @return Decoded int
function decode_fixed64(uint64 p, bytes memory buf)
internal
pure
returns (
bool,
uint64,
uint64
)
{
(bool success, uint64 pos, uint64 val) = decode_bits64(p, buf);
if (!success) {
return (false, pos, 0);
}
return (true, pos, val);
}
/// @notice Decode fixed int64.
/// @param p Position
/// @param buf Buffer
/// @return Success
/// @return New position
/// @return Decoded int
function decode_sfixed64(uint64 p, bytes memory buf)
internal
pure
returns (
bool,
uint64,
int64
)
{
(bool success, uint64 pos, uint64 val) = decode_bits64(p, buf);
if (!success) {
return (false, pos, 0);
}
return (true, pos, int64(val));
}
/// @notice Decode fixed 32-bit int.
/// @param p Position
/// @param buf Buffer
/// @return Success
/// @return New position
/// @return Decoded int
function decode_bits32(uint64 p, bytes memory buf)
internal
pure
returns (
bool,
uint64,
uint32
)
{
uint32 val;
// Check that index is within bounds
if (4 + p > buf.length) {
return (false, p, 0);
}
for (uint64 i = 0; i < 4; i++) {
uint8 b = uint8(buf[p + i]);
// Little endian
val |= uint32(b) << uint32(i * 8);
}
return (true, p + 4, val);
}
/// @notice Decode fixed uint32.
/// @param p Position
/// @param buf Buffer
/// @return Success
/// @return New position
/// @return Decoded int
function decode_fixed32(uint64 p, bytes memory buf)
internal
pure
returns (
bool,
uint64,
uint32
)
{
(bool success, uint64 pos, uint32 val) = decode_bits32(p, buf);
if (!success) {
return (false, pos, 0);
}
return (true, pos, val);
}
/// @notice Decode fixed int32.
/// @param p Position
/// @param buf Buffer
/// @return Success
/// @return New position
/// @return Decoded int
function decode_sfixed32(uint64 p, bytes memory buf)
internal
pure
returns (
bool,
uint64,
int32
)
{
(bool success, uint64 pos, uint32 val) = decode_bits32(p, buf);
if (!success) {
return (false, pos, 0);
}
return (true, pos, int32(val));
}
/// @notice Decode length-delimited field.
/// @param p Position
/// @param buf Buffer
/// @return Success
/// @return New position (after size)
/// @return Size in bytes
function decode_length_delimited(uint64 p, bytes memory buf)
internal
pure
returns (
bool,
uint64,
uint64
)
{
// Length-delimited fields begin with a varint of the number of bytes that follow
(bool success, uint64 pos, uint64 size) = decode_varint(p, buf);
if (!success) {
return (false, pos, 0);
}
// Check for overflow
unchecked {
if (pos + size < pos) {
return (false, pos, 0);
}
}
// Check that index is within bounds
if (size + pos > buf.length) {
return (false, pos, 0);
}
return (true, pos, size);
}
/// @notice Decode string.
/// @param p Position
/// @param buf Buffer
/// @return Success
/// @return New position
/// @return Size in bytes
function decode_string(uint64 p, bytes memory buf)
internal
pure
returns (
bool,
uint64,
string memory
)
{
(bool success, uint64 pos, uint64 size) = decode_length_delimited(p, buf);
if (!success) {
return (false, pos, "");
}
bytes memory field = new bytes(size);
for (uint64 i = 0; i < size; i++) {
field[i] = buf[pos + i];
}
return (true, pos + size, string(field));
}
/// @notice Decode bytes array.
/// @param p Position
/// @param buf Buffer
/// @return Success
/// @return New position (after size)
/// @return Size in bytes
function decode_bytes(uint64 p, bytes memory buf)
internal
pure
returns (
bool,
uint64,
uint64
)
{
return decode_length_delimited(p, buf);
}
/// @notice Decode embedded message.
/// @param p Position
/// @param buf Buffer
/// @return Success
/// @return New position (after size)
/// @return Size in bytes
function decode_embedded_message(uint64 p, bytes memory buf)
internal
pure
returns (
bool,
uint64,
uint64
)
{
return decode_length_delimited(p, buf);
}
/// @notice Decode packed repeated field.
/// @param p Position
/// @param buf Buffer
/// @return Success
/// @return New position (after size)
/// @return Size in bytes
function decode_packed_repeated(uint64 p, bytes memory buf)
internal
pure
returns (
bool,
uint64,
uint64
)
{
return decode_length_delimited(p, buf);
}
////////////////////////////////////
// Encoding
////////////////////////////////////
/// @notice Encode key.
/// @dev https://developers.google.com/protocol-buffers/docs/encoding#structure
/// @param field_number Field number
/// @param wire_type Wire type
/// @return Marshaled bytes
function encode_key(uint64 field_number, uint64 wire_type) internal pure returns (bytes memory) {
uint64 key = (field_number << 3) | wire_type;
bytes memory buf = encode_varint(key);
return buf;
}
/// @notice Encode varint.
/// @dev https://developers.google.com/protocol-buffers/docs/encoding#varints
/// @param n Number
/// @return Marshaled bytes
function encode_varint(uint64 n) internal pure returns (bytes memory) {
// Count the number of groups of 7 bits
// We need this pre-processing step since Solidity doesn't allow dynamic memory resizing
uint64 tmp = n;
uint64 num_bytes = 1;
while (tmp > 0x7F) {
tmp = tmp >> 7;
num_bytes += 1;
}
bytes memory buf = new bytes(num_bytes);
tmp = n;
for (uint64 i = 0; i < num_bytes; i++) {
// Set the first bit in the byte for each group of 7 bits
buf[i] = bytes1(0x80 | uint8(tmp & 0x7F));
tmp = tmp >> 7;
}
// Unset the first bit of the last byte
buf[num_bytes - 1] &= 0x7F;
return buf;
}
/// @notice Encode varint int32.
/// @param n Number
/// @return Marshaled bytes
function encode_int32(int32 n) internal pure returns (bytes memory) {
return encode_varint(uint64(int64(n)));
}
/// @notice Decode varint int64.
/// @param n Number
/// @return Marshaled bytes
function encode_int64(int64 n) internal pure returns (bytes memory) {
return encode_varint(uint64(n));
}
/// @notice Encode varint uint32.
/// @param n Number
/// @return Marshaled bytes
function encode_uint32(uint32 n) internal pure returns (bytes memory) {
return encode_varint(n);
}
/// @notice Encode varint uint64.
/// @param n Number
/// @return Marshaled bytes
function encode_uint64(uint64 n) internal pure returns (bytes memory) {
return encode_varint(n);
}
/// @notice Encode varint sint32.
/// @param n Number
/// @return Marshaled bytes
function encode_sint32(int32 n) internal pure returns (bytes memory) {
// https://developers.google.com/protocol-buffers/docs/encoding#signed_integers
uint32 mask = 0;
if (n < 0) {
unchecked {
mask -= 1;
}
}
uint32 zigzag_val = (uint32(n) << 1) ^ mask;
return encode_varint(zigzag_val);
}
/// @notice Encode varint sint64.
/// @param n Number
/// @return Marshaled bytes
function encode_sint64(int64 n) internal pure returns (bytes memory) {
// https://developers.google.com/protocol-buffers/docs/encoding#signed_integers
uint64 mask = 0;
if (n < 0) {
unchecked {
mask -= 1;
}
}
uint64 zigzag_val = (uint64(n) << 1) ^ mask;
return encode_varint(zigzag_val);
}
/// @notice Encode Boolean.
/// @param b Boolean
/// @return Marshaled bytes
function encode_bool(bool b) internal pure returns (bytes memory) {
uint64 n = b ? 1 : 0;
return encode_varint(n);
}
/// @notice Encode enumeration.
/// @param n Number
/// @return Marshaled bytes
function encode_enum(int32 n) internal pure returns (bytes memory) {
return encode_int32(n);
}
/// @notice Encode fixed 64-bit int.
/// @param n Number
/// @return Marshaled bytes
function encode_bits64(uint64 n) internal pure returns (bytes memory) {
bytes memory buf = new bytes(8);
uint64 tmp = n;
for (uint64 i = 0; i < 8; i++) {
// Little endian
buf[i] = bytes1(uint8(tmp & 0xFF));
tmp = tmp >> 8;
}
return buf;
}
/// @notice Encode fixed uint64.
/// @param n Number
/// @return Marshaled bytes
function encode_fixed64(uint64 n) internal pure returns (bytes memory) {
return encode_bits64(n);
}
/// @notice Encode fixed int64.
/// @param n Number
/// @return Marshaled bytes
function encode_sfixed64(int64 n) internal pure returns (bytes memory) {
return encode_bits64(uint64(n));
}
/// @notice Decode fixed 32-bit int.
/// @param n Number
/// @return Marshaled bytes
function encode_bits32(uint32 n) internal pure returns (bytes memory) {
bytes memory buf = new bytes(4);
uint64 tmp = n;
for (uint64 i = 0; i < 4; i++) {
// Little endian
buf[i] = bytes1(uint8(tmp & 0xFF));
tmp = tmp >> 8;
}
return buf;
}
/// @notice Encode fixed uint32.
/// @param n Number
/// @return Marshaled bytes
function encode_fixed32(uint32 n) internal pure returns (bytes memory) {
return encode_bits32(n);
}
/// @notice Encode fixed int32.
/// @param n Number
/// @return Marshaled bytes
function encode_sfixed32(int32 n) internal pure returns (bytes memory) {
return encode_bits32(uint32(n));
}
/// @notice Encode length-delimited field.
/// @param b Bytes
/// @return Marshaled bytes
function encode_length_delimited(bytes memory b) internal pure returns (bytes memory) {
// Length-delimited fields begin with a varint of the number of bytes that follow
bytes memory length_buf = encode_uint64(uint64(b.length));
bytes memory buf = new bytes(b.length + length_buf.length);
for (uint64 i = 0; i < length_buf.length; i++) {
buf[i] = length_buf[i];
}
for (uint64 i = 0; i < b.length; i++) {
buf[i + length_buf.length] = b[i];
}
return buf;
}
/// @notice Encode string.
/// @param s String
/// @return Marshaled bytes
function encode_string(string memory s) internal pure returns (bytes memory) {
return encode_length_delimited(bytes(s));
}
/// @notice Encode bytes array.
/// @param b Bytes
/// @return Marshaled bytes
function encode_bytes(bytes memory b) internal pure returns (bytes memory) {
return encode_length_delimited(b);
}
/// @notice Encode embedded message.
/// @param m Message
/// @return Marshaled bytes
function encode_embedded_message(bytes memory m) internal pure returns (bytes memory) {
return encode_length_delimited(m);
}
/// @notice Encode packed repeated field.
/// @param b Bytes
/// @return Marshaled bytes
function encode_packed_repeated(bytes memory b) internal pure returns (bytes memory) {
return encode_length_delimited(b);
}
}
| ERROR: type should be string, got " https:stackoverflow.com/questions/2210923/zig-zag-decoding/2211086#2211086 Fixed after sol 0.8.0 prev version: (val >> 1) ^ -(val & 1);" | uint64 zigzag_val;
| 1,795,567 | [
1,
4528,
30,
20672,
18,
832,
19,
9758,
19,
3787,
22267,
4366,
19,
94,
360,
17,
94,
346,
17,
323,
2014,
19,
3787,
17506,
5292,
3787,
17506,
5292,
15038,
1839,
3704,
374,
18,
28,
18,
20,
2807,
1177,
30,
261,
1125,
1671,
404,
13,
3602,
300,
12,
1125,
473,
404,
1769,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
3639,
2254,
1105,
998,
360,
94,
346,
67,
1125,
31,
203,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
] |
./partial_match/1/0x88d8fc3F8bD91C4AF80D36ee2860745ec66ef697/sources/ARMarketplace.sol | tokenId => attestation address
| mapping(uint256 => address) public attestations; | 9,238,544 | [
1,
2316,
548,
516,
2403,
395,
367,
1758,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
225,
2874,
12,
11890,
5034,
516,
1758,
13,
1071,
2403,
395,
1012,
31,
225,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
] |
./full_match/1/0x4A20F53E612E6Ab515A46EcA9dd36a290a2287F7/sources/contracts/protocol/core/callable/structs/CallableCreditLine.sol | @notice Returns the tranche index which the given timestamp falls within. @return The tranche index will go 1 beyond the max tranche index to represent the "after loan" period. This is not to be confused with activeCallSubmissionTrancheIndex, which is the tranche for which current call requests should be submitted to. See notes.md for explanation of relationship between principalPeriod, call request period and tranche. | function trancheIndexAtTimestamp(
CallableCreditLine storage cl,
uint256 timestamp
) internal view returns (uint256) {
return cl._paymentSchedule.principalPeriodAt(timestamp);
}
| 9,813,930 | [
1,
1356,
326,
13637,
18706,
770,
1492,
326,
864,
2858,
21714,
3470,
18,
327,
1021,
13637,
18706,
770,
903,
1960,
404,
17940,
326,
943,
13637,
18706,
770,
358,
2406,
326,
315,
5205,
28183,
6,
3879,
18,
540,
1220,
353,
486,
358,
506,
2195,
3668,
598,
2695,
1477,
17865,
17730,
18706,
1016,
16,
1492,
353,
326,
13637,
18706,
364,
1492,
540,
783,
745,
3285,
1410,
506,
9638,
358,
18,
540,
2164,
10913,
18,
1264,
364,
21285,
434,
5232,
3086,
8897,
5027,
16,
745,
590,
3879,
471,
13637,
18706,
18,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
225,
445,
13637,
18706,
1016,
861,
4921,
12,
203,
565,
10464,
16520,
1670,
2502,
927,
16,
203,
565,
2254,
5034,
2858,
203,
225,
262,
2713,
1476,
1135,
261,
11890,
5034,
13,
288,
203,
565,
327,
927,
6315,
9261,
6061,
18,
26138,
5027,
861,
12,
5508,
1769,
203,
225,
289,
203,
203,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
] |
/**
*Submitted for verification at Etherscan.io on 2022-02-08
*/
// SPDX-License-Identifier: GPL-3.0
// File: @openzeppelin/contracts/utils/Strings.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 `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);
}
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.0 (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);
}
}
/**
* @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);
}
/**
* @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;
}
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);
}
contract StakingPool is Ownable{
//last time that tokens where retrieved
mapping(uint => uint256) public checkpoints;
//see how many nfts are being staked
mapping(address => uint256[]) public stakedTokens;
IERC721Enumerable public NFTCollection;
IERC20 public Token;
uint public rewardPerDayBronze = 100000000000000000;
uint public rewardPerDaySilver = 200000000000000000;
uint public rewardPerDayGold = 300000000000000000;
uint public rewardPerDayPlatinum = 400000000000000000;
//dummy address that we use to sign the withdraw transaction to verify the type of nft
address private dummy = address(0xc0A7Ee1ABb27c81ae51d9720a208B80881617e44);
uint[] private tids;
mapping(address => uint256) private balances;
constructor() {
NFTCollection = IERC721Enumerable(0xB62E63c57d63f0812D5f2f583B733e3C5e6848f8);
Token = IERC20(0x5e4Efb364071C64Ee3641fe1E68cB5d2D5558709);
}
modifier onlyValidAccess(uint8 _v, bytes32 _r, bytes32 _s) {
require( isValidAccessMessage(msg.sender,_v,_r,_s), 'Invalid Signature' );
_;
}
//set ERC721Enumerable
function setNFTInterface(address newInterface) public onlyOwner {
NFTCollection = IERC721Enumerable(newInterface);
}
//set ERC20
function setTokenInterface(address newInterface) public onlyOwner {
Token = IERC20(newInterface);
}
/*
* @dev Verifies if message was signed by owner to give access to _add for this contract.
* Assumes Geth signature prefix.
* @param _add Address of agent with access
* @param _v ECDSA signature parameter v.
* @param _r ECDSA signature parameters r.
* @param _s ECDSA signature parameters s.
* @return Validity of access message for a given address.
*/
function isValidAccessMessage(address _add, uint8 _v, bytes32 _r, bytes32 _s) view public returns (bool) {
bytes32 hash = keccak256(abi.encodePacked(address(this), _add));
return dummy == ecrecover(keccak256(abi.encodePacked("\x19Ethereum Signed Message:\n32", hash)), _v, _r, _s);
}
function depositAll() external {
uint balance = NFTCollection.balanceOf(msg.sender);
require(balance > 0, "No tokens to stake!");
delete tids;
for (uint i = 0; i < balance; i++) {
tids.push(NFTCollection.tokenOfOwnerByIndex(msg.sender, i));
}
for (uint i = 0; i < tids.length; i++) {
_deposit(tids[i]);
}
}
function deposit(uint tokenId) public {
//they have to be the owner of tokenID
require(msg.sender == NFTCollection.ownerOf(tokenId), 'Sender must be owner');
_deposit(tokenId);
}
function _deposit(uint tokenId) internal {
//set the time of staking to now
checkpoints[tokenId] = block.timestamp;
//transfer NFT to contract
NFTCollection.transferFrom(msg.sender, address(this), tokenId);
//add to their staked tokens
stakedTokens[msg.sender].push(tokenId);
}
function withdrawAll(uint[] memory types_, uint8 _v, bytes32 _r, bytes32 _s) onlyValidAccess(_v, _r, _s) external {
getAllRewards(types_, _v, _r, _s);
for (uint i = 0; i < stakedTokens[msg.sender].length; i++) {
NFTCollection.transferFrom(address(this), msg.sender, stakedTokens[msg.sender][i]);
//popFromStakedTokens(stakedTokens[msg.sender][i]);
checkpoints[stakedTokens[msg.sender][i]] = block.timestamp;
}
delete stakedTokens[msg.sender];
}
function emergencyWithdrawAll() external {
require(stakedTokens[msg.sender].length > 0, "No tokens staked");
for (uint i = 0; i < stakedTokens[msg.sender].length; i++) {
NFTCollection.transferFrom(address(this), msg.sender, stakedTokens[msg.sender][i]);
//popFromStakedTokens(stakedTokens[msg.sender][i]);
checkpoints[stakedTokens[msg.sender][i]] = block.timestamp;
}
delete stakedTokens[msg.sender];
}
function withdraw(uint tokenId, uint type_, uint8 _v, bytes32 _r, bytes32 _s) onlyValidAccess(_v, _r, _s) public {
bool check = false;
for (uint i = 0; i < stakedTokens[msg.sender].length; i++) {
if (stakedTokens[msg.sender][i] == tokenId) {
check = true;
break;
}
}
require(check == true, 'You have not staked this token!');
_withdraw(tokenId, type_);
popFromStakedTokens(tokenId);
}
function emergencyWithdraw(uint tokenId) external {
bool check = false;
for (uint i = 0; i < stakedTokens[msg.sender].length; i++) {
if (stakedTokens[msg.sender][i] == tokenId) {
check = true;
break;
}
}
require(check == true, 'You have not staked this token!');
NFTCollection.transferFrom(address(this), msg.sender, tokenId);
popFromStakedTokens(tokenId);
checkpoints[tokenId] = block.timestamp;
}
function popFromStakedTokens(uint tokenId) internal {
uint pos = positionInStakedTokens(tokenId);
uint firstValue = stakedTokens[msg.sender][pos];
uint secondValue = stakedTokens[msg.sender][stakedTokens[msg.sender].length - 1];
stakedTokens[msg.sender][pos] = secondValue;
stakedTokens[msg.sender][stakedTokens[msg.sender].length - 1] = firstValue;
stakedTokens[msg.sender].pop();
}
function positionInStakedTokens(uint tokenId) internal view returns(uint) {
uint index;
for (uint i = 0; i < stakedTokens[msg.sender].length; i++) {
if (stakedTokens[msg.sender][i] == tokenId) {
index = i;
break;
}
}
return index;
}
function _withdraw(uint tokenId, uint type_) internal {
collect(tokenId, type_);
NFTCollection.transferFrom(address(this), msg.sender, tokenId);
}
function getReward(uint tokenId, uint type_, uint8 _v, bytes32 _r, bytes32 _s) onlyValidAccess(_v, _r, _s) public {
bool check = false;
for (uint i = 0; i < stakedTokens[msg.sender].length; i++) {
if (stakedTokens[msg.sender][i] == tokenId) {
check = true;
break;
}
}
require(check == true, 'You have not staked this token!');
collect(tokenId, type_);
}
function getAllRewards(uint[] memory types_, uint8 _v, bytes32 _r, bytes32 _s) onlyValidAccess(_v, _r, _s) public {
require(stakedTokens[msg.sender].length > 0, "No tokens staked");
require(types_.length == stakedTokens[msg.sender].length, "Types and Tokens Staked do not match!");
uint rewards = 0;
for (uint i = 0; i < types_.length; i++) {
rewards += calculateReward(stakedTokens[msg.sender][i], types_[i]);
checkpoints[stakedTokens[msg.sender][i]] = block.timestamp;
}
require(rewards <= Token.balanceOf(address(this)), "Staking Contract does not have sufficient funds");
Token.transfer(msg.sender, rewards);
}
function collect(uint tokenId, uint type_) internal {
uint256 reward = calculateReward(tokenId, type_);
//_mint(msg.sender, reward);
require(reward <= Token.balanceOf(address(this)), "Staking Contract does not have sufficient funds");
Token.transfer(msg.sender, reward);
checkpoints[tokenId] = block.timestamp;
}
function calculateAllRewards(uint[] memory types_, address who) public view returns(uint256) {
require(stakedTokens[who].length > 0, "No tokens staked");
require(types_.length == stakedTokens[who].length, "Types and Tokens Staked do not match!");
uint256 total;
for (uint i = 0; i < types_.length; i++) {
total += calculateReward(stakedTokens[who][i], types_[i]);
}
return total;
}
function calculateReward(uint tokenId, uint type_) public view returns(uint256) {
require(type_ >= 0 && type_ < 5, "Invalid Type of Token!");
uint256 checkpoint = checkpoints[tokenId];
if (type_ == 0) {
return 0;
}
else if (type_ == 1) {
return rewardPerDayBronze * ((block.timestamp-checkpoint) / 86400);
}
else if (type_ == 2) {
return rewardPerDaySilver * ((block.timestamp-checkpoint) / 86400);
}
else if (type_ == 3) {
return rewardPerDayGold * ((block.timestamp-checkpoint) / 86400);
}
else {
return rewardPerDayPlatinum * ((block.timestamp-checkpoint) / 86400);
}
}
function seeStakedTokens(address who) public view returns(uint256[] memory) {
return stakedTokens[who];
}
function withdrawKatsumi() external onlyOwner {
uint256 balance = Token.balanceOf(address(this));
require(balance > 0, "No tokens to withdraw!");
Token.transfer(msg.sender, balance);
}
} | they have to be the owner of tokenID | function deposit(uint tokenId) public {
require(msg.sender == NFTCollection.ownerOf(tokenId), 'Sender must be owner');
_deposit(tokenId);
}
| 10,987,918 | [
1,
451,
402,
1240,
358,
506,
326,
3410,
434,
1147,
734,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
565,
445,
443,
1724,
12,
11890,
1147,
548,
13,
1071,
288,
203,
3639,
2583,
12,
3576,
18,
15330,
422,
423,
4464,
2532,
18,
8443,
951,
12,
2316,
548,
3631,
296,
12021,
1297,
506,
3410,
8284,
203,
3639,
389,
323,
1724,
12,
2316,
548,
1769,
203,
540,
203,
565,
289,
203,
203,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
] |
/**
*Submitted for verification at Etherscan.io on 2021-02-27
*/
/**
*Submitted for verification at Etherscan.io on 2020-12-29
*/
pragma solidity =0.6.12;
// SPDX-License-Identifier: MIT
interface PocketSwapV2Pair {
event Approval(address indexed owner, address indexed spender, uint value);
event Transfer(address indexed from, address indexed to, uint value);
function name() external pure returns (string memory);
function symbol() external pure returns (string memory);
function decimals() external pure returns (uint8);
function totalSupply() external view returns (uint);
function balanceOf(address owner) external view returns (uint);
function allowance(address owner, address spender) external view returns (uint);
function approve(address spender, uint value) external returns (bool);
function transfer(address to, uint value) external returns (bool);
function transferFrom(address from, address to, uint value) external returns (bool);
function DOMAIN_SEPARATOR() external view returns (bytes32);
function PERMIT_TYPEHASH() external pure returns (bytes32);
function nonces(address owner) external view returns (uint);
function permit(address owner, address spender, uint value, uint deadline, uint8 v, bytes32 r, bytes32 s) external;
event Mint(address indexed sender, uint amount0, uint amount1);
event Burn(address indexed sender, uint amount0, uint amount1, address indexed to);
event Swap(
address indexed sender,
uint amount0In,
uint amount1In,
uint amount0Out,
uint amount1Out,
address indexed to
);
event Sync(uint112 reserve0, uint112 reserve1);
function MINIMUM_LIQUIDITY() external pure returns (uint);
function factory() external view returns (address);
function token0() external view returns (address);
function token1() external view returns (address);
function getReserves() external view returns (uint112 reserve0, uint112 reserve1, uint32 blockTimestampLast);
function price0CumulativeLast() external view returns (uint);
function price1CumulativeLast() external view returns (uint);
function kLast() external view returns (uint);
function mint(address to) external returns (uint liquidity);
function burn(address to) external returns (uint amount0, uint amount1);
function swap(uint amount0Out, uint amount1Out, address to, bytes calldata data) external;
function skim(address to) external;
function sync() external;
function initialize(address, address) external;
}
library SafeMatswap {
function add(uint x, uint y) internal pure returns (uint z) {
require((z = x + y) >= x, 'ds-math-add-overflow');
}
function sub(uint x, uint y) internal pure returns (uint z) {
require((z = x - y) <= x, 'ds-math-sub-underflow');
}
function mul(uint x, uint y) internal pure returns (uint z) {
require(y == 0 || (z = x * y) / y == x, 'ds-math-mul-overflow');
}
}
library PocketSwapV2Library {
using SafeMatswap for uint;
// returns sorted token addresses, used to handle return values from pairs sorted in this order
function sortTokens(address tokenA, address tokenB) internal pure returns (address token0, address token1) {
require(tokenA != tokenB, 'PocketSwapV2Library: IDENTICAL_ADDRESSES');
(token0, token1) = tokenA < tokenB ? (tokenA, tokenB) : (tokenB, tokenA);
require(token0 != address(0), 'PocketSwapV2Library: ZERO_ADDRESS');
}
// calculates the CREATE2 address for a pair without making any external calls
function pairFor(address factory, address tokenA, address tokenB) internal pure returns (address pair) {
(address token0, address token1) = sortTokens(tokenA, tokenB);
pair = address(uint(keccak256(abi.encodePacked(
hex'ff',
factory,
keccak256(abi.encodePacked(token0, token1)),
hex'769bed9500aa97b61c54bd21d2e876339984fecd50d2a5d78668f8fdb3754b6f' // init code hash
))));
}
// fetches and sorts the reserves for a pair
function getReserves(address factory, address tokenA, address tokenB) internal view returns (uint reserveA, uint reserveB) {
(address token0,) = sortTokens(tokenA, tokenB);
(uint reserve0, uint reserve1,) = PocketSwapV2Pair(pairFor(factory, tokenA, tokenB)).getReserves();
(reserveA, reserveB) = tokenA == token0 ? (reserve0, reserve1) : (reserve1, reserve0);
}
// given some amount of an asset and pair reserves, returns an equivalent amount of the other asset
function quote(uint amountA, uint reserveA, uint reserveB) internal pure returns (uint amountB) {
require(amountA > 0, 'PocketSwapV2Library: INSUFFICIENT_AMOUNT');
require(reserveA > 0 && reserveB > 0, 'PocketSwapV2Library: INSUFFICIENT_LIQUIDITY');
amountB = amountA.mul(reserveB) / reserveA;
}
// given an input amount of an asset and pair reserves, returns the maximum output amount of the other asset
function getAmountOut(uint amountIn, uint reserveIn, uint reserveOut) internal pure returns (uint amountOut) {
require(amountIn > 0, 'PocketSwapV2Library: INSUFFICIENT_INPUT_AMOUNT');
require(reserveIn > 0 && reserveOut > 0, 'PocketSwapV2Library: INSUFFICIENT_LIQUIDITY');
uint amountInWithFee = amountIn.mul(997);
uint numerator = amountInWithFee.mul(reserveOut);
uint denominator = reserveIn.mul(1000).add(amountInWithFee);
amountOut = numerator / denominator;
}
// given an output amount of an asset and pair reserves, returns a required input amount of the other asset
function getAmountIn(uint amountOut, uint reserveIn, uint reserveOut) internal pure returns (uint amountIn) {
require(amountOut > 0, 'PocketSwapV2Library: INSUFFICIENT_OUTPUT_AMOUNT');
require(reserveIn > 0 && reserveOut > 0, 'PocketSwapV2Library: INSUFFICIENT_LIQUIDITY');
uint numerator = reserveIn.mul(amountOut).mul(1000);
uint denominator = reserveOut.sub(amountOut).mul(997);
amountIn = (numerator / denominator).add(1);
}
// performs chained getAmountOut calculations on any number of pairs
function getAmountsOut(address factory, uint amountIn, address[] memory path) internal view returns (uint[] memory amounts) {
require(path.length >= 2, 'PocketSwapV2Library: INVALID_PATH');
amounts = new uint[](path.length);
amounts[0] = amountIn;
for (uint i; i < path.length - 1; i++) {
(uint reserveIn, uint reserveOut) = getReserves(factory, path[i], path[i + 1]);
amounts[i + 1] = getAmountOut(amounts[i], reserveIn, reserveOut);
}
}
// performs chained getAmountIn calculations on any number of pairs
function getAmountsIn(address factory, uint amountOut, address[] memory path) internal view returns (uint[] memory amounts) {
require(path.length >= 2, 'PocketSwapV2Library: INVALID_PATH');
amounts = new uint[](path.length);
amounts[amounts.length - 1] = amountOut;
for (uint i = path.length - 1; i > 0; i--) {
(uint reserveIn, uint reserveOut) = getReserves(factory, path[i - 1], path[i]);
amounts[i - 1] = getAmountIn(amounts[i], reserveIn, reserveOut);
}
}
}
// helper methods for interacting with ERC20 tokens and sending ETH that do not consistently return true/false
library TransferHelper {
function safeApprove(address token, address to, uint value) internal {
// bytes4(keccak256(bytes('approve(address,uint256)')));
(bool success, bytes memory data) = token.call(abi.encodeWithSelector(0x095ea7b3, to, value));
require(success && (data.length == 0 || abi.decode(data, (bool))), 'TransferHelper: APPROVE_FAILED');
}
function safeTransfer(address token, address to, uint value) internal {
// bytes4(keccak256(bytes('transfer(address,uint256)')));
(bool success, bytes memory data) = token.call(abi.encodeWithSelector(0xa9059cbb, to, value));
require(success && (data.length == 0 || abi.decode(data, (bool))), 'TransferHelper: TRANSFER_FAILED');
}
function safeTransferFrom(address token, address from, address to, uint value) internal {
// bytes4(keccak256(bytes('transferFrom(address,address,uint256)')));
(bool success, bytes memory data) = token.call(abi.encodeWithSelector(0x23b872dd, from, to, value));
require(success && (data.length == 0 || abi.decode(data, (bool))), 'TransferHelper: TRANSFER_FROM_FAILED');
}
function safeTransferETH(address to, uint value) internal {
(bool success,) = to.call{value:value}(new bytes(0));
require(success, 'TransferHelper: ETH_TRANSFER_FAILED');
}
}
interface IPocketSwapV2Router01 {
function factory() external pure returns (address);
function WETH() external pure returns (address);
function addLiquidity(
address tokenA,
address tokenB,
uint amountADesired,
uint amountBDesired,
uint amountAMin,
uint amountBMin,
address to,
uint deadline
) external returns (uint amountA, uint amountB, uint liquidity);
function addLiquidityETH(
address token,
uint amountTokenDesired,
uint amountTokenMin,
uint amountETHMin,
address to,
uint deadline
) external payable returns (uint amountToken, uint amountETH, uint liquidity);
function removeLiquidity(
address tokenA,
address tokenB,
uint liquidity,
uint amountAMin,
uint amountBMin,
address to,
uint deadline
) external returns (uint amountA, uint amountB);
function removeLiquidityETH(
address token,
uint liquidity,
uint amountTokenMin,
uint amountETHMin,
address to,
uint deadline
) external returns (uint amountToken, uint amountETH);
function removeLiquidityWithPermit(
address tokenA,
address tokenB,
uint liquidity,
uint amountAMin,
uint amountBMin,
address to,
uint deadline,
bool approveMax, uint8 v, bytes32 r, bytes32 s
) external returns (uint amountA, uint amountB);
function removeLiquidityETHWithPermit(
address token,
uint liquidity,
uint amountTokenMin,
uint amountETHMin,
address to,
uint deadline,
bool approveMax, uint8 v, bytes32 r, bytes32 s
) external returns (uint amountToken, uint amountETH);
function swapExactTokensForTokens(
uint amountIn,
uint amountOutMin,
address[] calldata path,
address to,
uint deadline
) external returns (uint[] memory amounts);
function swapTokensForExactTokens(
uint amountOut,
uint amountInMax,
address[] calldata path,
address to,
uint deadline
) external returns (uint[] memory amounts);
function swapExactETHForTokens(uint amountOutMin, address[] calldata path, address to, uint deadline)
external
payable
returns (uint[] memory amounts);
function swapTokensForExactETH(uint amountOut, uint amountInMax, address[] calldata path, address to, uint deadline)
external
returns (uint[] memory amounts);
function swapExactTokensForETH(uint amountIn, uint amountOutMin, address[] calldata path, address to, uint deadline)
external
returns (uint[] memory amounts);
function swapETHForExactTokens(uint amountOut, address[] calldata path, address to, uint deadline)
external
payable
returns (uint[] memory amounts);
function quote(uint amountA, uint reserveA, uint reserveB) external pure returns (uint amountB);
function getAmountOut(uint amountIn, uint reserveIn, uint reserveOut) external pure returns (uint amountOut);
function getAmountIn(uint amountOut, uint reserveIn, uint reserveOut) external pure returns (uint amountIn);
function getAmountsOut(uint amountIn, address[] calldata path) external view returns (uint[] memory amounts);
function getAmountsIn(uint amountOut, address[] calldata path) external view returns (uint[] memory amounts);
}
interface IPocketSwapV2Router02 is IPocketSwapV2Router01 {
function removeLiquidityETHSupportingFeeOnTransferTokens(
address token,
uint liquidity,
uint amountTokenMin,
uint amountETHMin,
address to,
uint deadline
) external returns (uint amountETH);
function removeLiquidityETHWithPermitSupportingFeeOnTransferTokens(
address token,
uint liquidity,
uint amountTokenMin,
uint amountETHMin,
address to,
uint deadline,
bool approveMax, uint8 v, bytes32 r, bytes32 s
) external returns (uint amountETH);
function swapExactTokensForTokensSupportingFeeOnTransferTokens(
uint amountIn,
uint amountOutMin,
address[] calldata path,
address to,
uint deadline
) external;
function swapExactETHForTokensSupportingFeeOnTransferTokens(
uint amountOutMin,
address[] calldata path,
address to,
uint deadline
) external payable;
function swapExactTokensForETHSupportingFeeOnTransferTokens(
uint amountIn,
uint amountOutMin,
address[] calldata path,
address to,
uint deadline
) external;
}
interface IPocketSwapV2Factory {
event PairCreated(address indexed token0, address indexed token1, address pair, uint);
function feeTo() external view returns (address);
function feeToSetter() external view returns (address);
function getPair(address tokenA, address tokenB) external view returns (address pair);
function allPairs(uint) external view returns (address pair);
function allPairsLength() external view returns (uint);
function createPair(address tokenA, address tokenB) external returns (address pair);
function setFeeTo(address) external;
function setFeeToSetter(address) external;
}
interface IERC20PocketSwap {
event Approval(address indexed owner, address indexed spender, uint value);
event Transfer(address indexed from, address indexed to, uint value);
function name() external view returns (string memory);
function symbol() external view returns (string memory);
function decimals() external view returns (uint8);
function totalSupply() external view returns (uint);
function balanceOf(address owner) external view returns (uint);
function allowance(address owner, address spender) external view returns (uint);
function approve(address spender, uint value) external returns (bool);
function transfer(address to, uint value) external returns (bool);
function transferFrom(address from, address to, uint value) external returns (bool);
}
interface IWETH {
function deposit() external payable;
function transfer(address to, uint value) external returns (bool);
function withdraw(uint) external;
}
contract PocketSwapV2Router02 is IPocketSwapV2Router02 {
using SafeMatswap for uint;
address public immutable override factory;
address public immutable override WETH;
modifier ensure(uint deadline) {
require(deadline >= block.timestamp, 'PocketSwapV2Router: EXPIRED');
_;
}
constructor(address _factory, address _WETH) public {
factory = _factory;
WETH = _WETH;
}
receive() external payable {
assert(msg.sender == WETH); // only accept ETH via fallback from the WETH contract
}
// **** ADD LIQUIDITY ****
function _addLiquidity(
address tokenA,
address tokenB,
uint amountADesired,
uint amountBDesired,
uint amountAMin,
uint amountBMin
) internal virtual returns (uint amountA, uint amountB) {
// create the pair if it doesn't exist yet
if (IPocketSwapV2Factory(factory).getPair(tokenA, tokenB) == address(0)) {
IPocketSwapV2Factory(factory).createPair(tokenA, tokenB);
}
(uint reserveA, uint reserveB) = PocketSwapV2Library.getReserves(factory, tokenA, tokenB);
if (reserveA == 0 && reserveB == 0) {
(amountA, amountB) = (amountADesired, amountBDesired);
} else {
uint amountBOptimal = PocketSwapV2Library.quote(amountADesired, reserveA, reserveB);
if (amountBOptimal <= amountBDesired) {
require(amountBOptimal >= amountBMin, 'PocketSwapV2Router: INSUFFICIENT_B_AMOUNT');
(amountA, amountB) = (amountADesired, amountBOptimal);
} else {
uint amountAOptimal = PocketSwapV2Library.quote(amountBDesired, reserveB, reserveA);
assert(amountAOptimal <= amountADesired);
require(amountAOptimal >= amountAMin, 'PocketSwapV2Router: INSUFFICIENT_A_AMOUNT');
(amountA, amountB) = (amountAOptimal, amountBDesired);
}
}
}
function addLiquidity(
address tokenA,
address tokenB,
uint amountADesired,
uint amountBDesired,
uint amountAMin,
uint amountBMin,
address to,
uint deadline
) external virtual override ensure(deadline) returns (uint amountA, uint amountB, uint liquidity) {
(amountA, amountB) = _addLiquidity(tokenA, tokenB, amountADesired, amountBDesired, amountAMin, amountBMin);
address pair = PocketSwapV2Library.pairFor(factory, tokenA, tokenB);
TransferHelper.safeTransferFrom(tokenA, msg.sender, pair, amountA);
TransferHelper.safeTransferFrom(tokenB, msg.sender, pair, amountB);
liquidity = PocketSwapV2Pair(pair).mint(to);
}
function addLiquidityETH(
address token,
uint amountTokenDesired,
uint amountTokenMin,
uint amountETHMin,
address to,
uint deadline
) external virtual override payable ensure(deadline) returns (uint amountToken, uint amountETH, uint liquidity) {
(amountToken, amountETH) = _addLiquidity(
token,
WETH,
amountTokenDesired,
msg.value,
amountTokenMin,
amountETHMin
);
address pair = PocketSwapV2Library.pairFor(factory, token, WETH);
TransferHelper.safeTransferFrom(token, msg.sender, pair, amountToken);
IWETH(WETH).deposit{value: amountETH}();
assert(IWETH(WETH).transfer(pair, amountETH));
liquidity = PocketSwapV2Pair(pair).mint(to);
// refund dust eth, if any
if (msg.value > amountETH) TransferHelper.safeTransferETH(msg.sender, msg.value - amountETH);
}
// **** REMOVE LIQUIDITY ****
function removeLiquidity(
address tokenA,
address tokenB,
uint liquidity,
uint amountAMin,
uint amountBMin,
address to,
uint deadline
) public virtual override ensure(deadline) returns (uint amountA, uint amountB) {
address pair = PocketSwapV2Library.pairFor(factory, tokenA, tokenB);
PocketSwapV2Pair(pair).transferFrom(msg.sender, pair, liquidity); // send liquidity to pair
(uint amount0, uint amount1) = PocketSwapV2Pair(pair).burn(to);
(address token0,) = PocketSwapV2Library.sortTokens(tokenA, tokenB);
(amountA, amountB) = tokenA == token0 ? (amount0, amount1) : (amount1, amount0);
require(amountA >= amountAMin, 'PocketSwapV2Router: INSUFFICIENT_A_AMOUNT');
require(amountB >= amountBMin, 'PocketSwapV2Router: INSUFFICIENT_B_AMOUNT');
}
function removeLiquidityETH(
address token,
uint liquidity,
uint amountTokenMin,
uint amountETHMin,
address to,
uint deadline
) public virtual override ensure(deadline) returns (uint amountToken, uint amountETH) {
(amountToken, amountETH) = removeLiquidity(
token,
WETH,
liquidity,
amountTokenMin,
amountETHMin,
address(this),
deadline
);
TransferHelper.safeTransfer(token, to, amountToken);
IWETH(WETH).withdraw(amountETH);
TransferHelper.safeTransferETH(to, amountETH);
}
function removeLiquidityWithPermit(
address tokenA,
address tokenB,
uint liquidity,
uint amountAMin,
uint amountBMin,
address to,
uint deadline,
bool approveMax, uint8 v, bytes32 r, bytes32 s
) external virtual override returns (uint amountA, uint amountB) {
address pair = PocketSwapV2Library.pairFor(factory, tokenA, tokenB);
uint value = approveMax ? uint(-1) : liquidity;
PocketSwapV2Pair(pair).permit(msg.sender, address(this), value, deadline, v, r, s);
(amountA, amountB) = removeLiquidity(tokenA, tokenB, liquidity, amountAMin, amountBMin, to, deadline);
}
function removeLiquidityETHWithPermit(
address token,
uint liquidity,
uint amountTokenMin,
uint amountETHMin,
address to,
uint deadline,
bool approveMax, uint8 v, bytes32 r, bytes32 s
) external virtual override returns (uint amountToken, uint amountETH) {
address pair = PocketSwapV2Library.pairFor(factory, token, WETH);
uint value = approveMax ? uint(-1) : liquidity;
PocketSwapV2Pair(pair).permit(msg.sender, address(this), value, deadline, v, r, s);
(amountToken, amountETH) = removeLiquidityETH(token, liquidity, amountTokenMin, amountETHMin, to, deadline);
}
// **** REMOVE LIQUIDITY (supporting fee-on-transfer tokens) ****
function removeLiquidityETHSupportingFeeOnTransferTokens(
address token,
uint liquidity,
uint amountTokenMin,
uint amountETHMin,
address to,
uint deadline
) public virtual override ensure(deadline) returns (uint amountETH) {
(, amountETH) = removeLiquidity(
token,
WETH,
liquidity,
amountTokenMin,
amountETHMin,
address(this),
deadline
);
TransferHelper.safeTransfer(token, to, IERC20PocketSwap(token).balanceOf(address(this)));
IWETH(WETH).withdraw(amountETH);
TransferHelper.safeTransferETH(to, amountETH);
}
function removeLiquidityETHWithPermitSupportingFeeOnTransferTokens(
address token,
uint liquidity,
uint amountTokenMin,
uint amountETHMin,
address to,
uint deadline,
bool approveMax, uint8 v, bytes32 r, bytes32 s
) external virtual override returns (uint amountETH) {
address pair = PocketSwapV2Library.pairFor(factory, token, WETH);
uint value = approveMax ? uint(-1) : liquidity;
PocketSwapV2Pair(pair).permit(msg.sender, address(this), value, deadline, v, r, s);
amountETH = removeLiquidityETHSupportingFeeOnTransferTokens(
token, liquidity, amountTokenMin, amountETHMin, to, deadline
);
}
// **** SWAP ****
// requires the initial amount to have already been sent to the first pair
function _swap(uint[] memory amounts, address[] memory path, address _to) internal virtual {
for (uint i; i < path.length - 1; i++) {
(address input, address output) = (path[i], path[i + 1]);
(address token0,) = PocketSwapV2Library.sortTokens(input, output);
uint amountOut = amounts[i + 1];
(uint amount0Out, uint amount1Out) = input == token0 ? (uint(0), amountOut) : (amountOut, uint(0));
address to = i < path.length - 2 ? PocketSwapV2Library.pairFor(factory, output, path[i + 2]) : _to;
PocketSwapV2Pair(PocketSwapV2Library.pairFor(factory, input, output)).swap(
amount0Out, amount1Out, to, new bytes(0)
);
}
}
function swapExactTokensForTokens(
uint amountIn,
uint amountOutMin,
address[] calldata path,
address to,
uint deadline
) external virtual override ensure(deadline) returns (uint[] memory amounts) {
amounts = PocketSwapV2Library.getAmountsOut(factory, amountIn, path);
require(amounts[amounts.length - 1] >= amountOutMin, 'PocketSwapV2Router: INSUFFICIENT_OUTPUT_AMOUNT');
TransferHelper.safeTransferFrom(
path[0], msg.sender, PocketSwapV2Library.pairFor(factory, path[0], path[1]), amounts[0]
);
_swap(amounts, path, to);
}
function swapTokensForExactTokens(
uint amountOut,
uint amountInMax,
address[] calldata path,
address to,
uint deadline
) external virtual override ensure(deadline) returns (uint[] memory amounts) {
amounts = PocketSwapV2Library.getAmountsIn(factory, amountOut, path);
require(amounts[0] <= amountInMax, 'PocketSwapV2Router: EXCESSIVE_INPUT_AMOUNT');
TransferHelper.safeTransferFrom(
path[0], msg.sender, PocketSwapV2Library.pairFor(factory, path[0], path[1]), amounts[0]
);
_swap(amounts, path, to);
}
function swapExactETHForTokens(uint amountOutMin, address[] calldata path, address to, uint deadline)
external
virtual
override
payable
ensure(deadline)
returns (uint[] memory amounts)
{
require(path[0] == WETH, 'PocketSwapV2Router: INVALID_PATH');
amounts = PocketSwapV2Library.getAmountsOut(factory, msg.value, path);
require(amounts[amounts.length - 1] >= amountOutMin, 'PocketSwapV2Router: INSUFFICIENT_OUTPUT_AMOUNT');
IWETH(WETH).deposit{value: amounts[0]}();
assert(IWETH(WETH).transfer(PocketSwapV2Library.pairFor(factory, path[0], path[1]), amounts[0]));
_swap(amounts, path, to);
}
function swapTokensForExactETH(uint amountOut, uint amountInMax, address[] calldata path, address to, uint deadline)
external
virtual
override
ensure(deadline)
returns (uint[] memory amounts)
{
require(path[path.length - 1] == WETH, 'PocketSwapV2Router: INVALID_PATH');
amounts = PocketSwapV2Library.getAmountsIn(factory, amountOut, path);
require(amounts[0] <= amountInMax, 'PocketSwapV2Router: EXCESSIVE_INPUT_AMOUNT');
TransferHelper.safeTransferFrom(
path[0], msg.sender, PocketSwapV2Library.pairFor(factory, path[0], path[1]), amounts[0]
);
_swap(amounts, path, address(this));
IWETH(WETH).withdraw(amounts[amounts.length - 1]);
TransferHelper.safeTransferETH(to, amounts[amounts.length - 1]);
}
function swapExactTokensForETH(uint amountIn, uint amountOutMin, address[] calldata path, address to, uint deadline)
external
virtual
override
ensure(deadline)
returns (uint[] memory amounts)
{
require(path[path.length - 1] == WETH, 'PocketSwapV2Router: INVALID_PATH');
amounts = PocketSwapV2Library.getAmountsOut(factory, amountIn, path);
require(amounts[amounts.length - 1] >= amountOutMin, 'PocketSwapV2Router: INSUFFICIENT_OUTPUT_AMOUNT');
TransferHelper.safeTransferFrom(
path[0], msg.sender, PocketSwapV2Library.pairFor(factory, path[0], path[1]), amounts[0]
);
_swap(amounts, path, address(this));
IWETH(WETH).withdraw(amounts[amounts.length - 1]);
TransferHelper.safeTransferETH(to, amounts[amounts.length - 1]);
}
function swapETHForExactTokens(uint amountOut, address[] calldata path, address to, uint deadline)
external
virtual
override
payable
ensure(deadline)
returns (uint[] memory amounts)
{
require(path[0] == WETH, 'PocketSwapV2Router: INVALID_PATH');
amounts = PocketSwapV2Library.getAmountsIn(factory, amountOut, path);
require(amounts[0] <= msg.value, 'PocketSwapV2Router: EXCESSIVE_INPUT_AMOUNT');
IWETH(WETH).deposit{value: amounts[0]}();
assert(IWETH(WETH).transfer(PocketSwapV2Library.pairFor(factory, path[0], path[1]), amounts[0]));
_swap(amounts, path, to);
// refund dust eth, if any
if (msg.value > amounts[0]) TransferHelper.safeTransferETH(msg.sender, msg.value - amounts[0]);
}
// **** SWAP (supporting fee-on-transfer tokens) ****
// requires the initial amount to have already been sent to the first pair
function _swapSupportingFeeOnTransferTokens(address[] memory path, address _to) internal virtual {
for (uint i; i < path.length - 1; i++) {
(address input, address output) = (path[i], path[i + 1]);
(address token0,) = PocketSwapV2Library.sortTokens(input, output);
PocketSwapV2Pair pair = PocketSwapV2Pair(PocketSwapV2Library.pairFor(factory, input, output));
uint amountInput;
uint amountOutput;
{ // scope to avoid stack too deep errors
(uint reserve0, uint reserve1,) = pair.getReserves();
(uint reserveInput, uint reserveOutput) = input == token0 ? (reserve0, reserve1) : (reserve1, reserve0);
amountInput = IERC20PocketSwap(input).balanceOf(address(pair)).sub(reserveInput);
amountOutput = PocketSwapV2Library.getAmountOut(amountInput, reserveInput, reserveOutput);
}
(uint amount0Out, uint amount1Out) = input == token0 ? (uint(0), amountOutput) : (amountOutput, uint(0));
address to = i < path.length - 2 ? PocketSwapV2Library.pairFor(factory, output, path[i + 2]) : _to;
pair.swap(amount0Out, amount1Out, to, new bytes(0));
}
}
function swapExactTokensForTokensSupportingFeeOnTransferTokens(
uint amountIn,
uint amountOutMin,
address[] calldata path,
address to,
uint deadline
) external virtual override ensure(deadline) {
TransferHelper.safeTransferFrom(
path[0], msg.sender, PocketSwapV2Library.pairFor(factory, path[0], path[1]), amountIn
);
uint balanceBefore = IERC20PocketSwap(path[path.length - 1]).balanceOf(to);
_swapSupportingFeeOnTransferTokens(path, to);
require(
IERC20PocketSwap(path[path.length - 1]).balanceOf(to).sub(balanceBefore) >= amountOutMin,
'PocketSwapV2Router: INSUFFICIENT_OUTPUT_AMOUNT'
);
}
function swapExactETHForTokensSupportingFeeOnTransferTokens(
uint amountOutMin,
address[] calldata path,
address to,
uint deadline
)
external
virtual
override
payable
ensure(deadline)
{
require(path[0] == WETH, 'PocketSwapV2Router: INVALID_PATH');
uint amountIn = msg.value;
IWETH(WETH).deposit{value: amountIn}();
assert(IWETH(WETH).transfer(PocketSwapV2Library.pairFor(factory, path[0], path[1]), amountIn));
uint balanceBefore = IERC20PocketSwap(path[path.length - 1]).balanceOf(to);
_swapSupportingFeeOnTransferTokens(path, to);
require(
IERC20PocketSwap(path[path.length - 1]).balanceOf(to).sub(balanceBefore) >= amountOutMin,
'PocketSwapV2Router: INSUFFICIENT_OUTPUT_AMOUNT'
);
}
function swapExactTokensForETHSupportingFeeOnTransferTokens(
uint amountIn,
uint amountOutMin,
address[] calldata path,
address to,
uint deadline
)
external
virtual
override
ensure(deadline)
{
require(path[path.length - 1] == WETH, 'PocketSwapV2Router: INVALID_PATH');
TransferHelper.safeTransferFrom(
path[0], msg.sender, PocketSwapV2Library.pairFor(factory, path[0], path[1]), amountIn
);
_swapSupportingFeeOnTransferTokens(path, address(this));
uint amountOut = IERC20PocketSwap(WETH).balanceOf(address(this));
require(amountOut >= amountOutMin, 'PocketSwapV2Router: INSUFFICIENT_OUTPUT_AMOUNT');
IWETH(WETH).withdraw(amountOut);
TransferHelper.safeTransferETH(to, amountOut);
}
// **** LIBRARY FUNCTIONS ****
function quote(uint amountA, uint reserveA, uint reserveB) public pure virtual override returns (uint amountB) {
return PocketSwapV2Library.quote(amountA, reserveA, reserveB);
}
function getAmountOut(uint amountIn, uint reserveIn, uint reserveOut)
public
pure
virtual
override
returns (uint amountOut)
{
return PocketSwapV2Library.getAmountOut(amountIn, reserveIn, reserveOut);
}
function getAmountIn(uint amountOut, uint reserveIn, uint reserveOut)
public
pure
virtual
override
returns (uint amountIn)
{
return PocketSwapV2Library.getAmountIn(amountOut, reserveIn, reserveOut);
}
function getAmountsOut(uint amountIn, address[] memory path)
public
view
virtual
override
returns (uint[] memory amounts)
{
return PocketSwapV2Library.getAmountsOut(factory, amountIn, path);
}
function getAmountsIn(uint amountOut, address[] memory path)
public
view
virtual
override
returns (uint[] memory amounts)
{
return PocketSwapV2Library.getAmountsIn(factory, amountOut, path);
}
} | given some amount of an asset and pair reserves, returns an equivalent amount of the other asset | function quote(uint amountA, uint reserveA, uint reserveB) internal pure returns (uint amountB) {
require(amountA > 0, 'PocketSwapV2Library: INSUFFICIENT_AMOUNT');
require(reserveA > 0 && reserveB > 0, 'PocketSwapV2Library: INSUFFICIENT_LIQUIDITY');
amountB = amountA.mul(reserveB) / reserveA;
}
| 10,566,576 | [
1,
10822,
2690,
3844,
434,
392,
3310,
471,
3082,
400,
264,
3324,
16,
1135,
392,
7680,
3844,
434,
326,
1308,
3310,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
565,
445,
3862,
12,
11890,
3844,
37,
16,
2254,
20501,
37,
16,
2254,
20501,
38,
13,
2713,
16618,
1135,
261,
11890,
3844,
38,
13,
288,
203,
3639,
2583,
12,
8949,
37,
405,
374,
16,
296,
52,
1861,
12521,
58,
22,
9313,
30,
2120,
6639,
42,
1653,
7266,
2222,
67,
2192,
51,
5321,
8284,
203,
3639,
2583,
12,
455,
6527,
37,
405,
374,
597,
20501,
38,
405,
374,
16,
296,
52,
1861,
12521,
58,
22,
9313,
30,
2120,
6639,
42,
1653,
7266,
2222,
67,
2053,
53,
3060,
4107,
8284,
203,
3639,
3844,
38,
273,
3844,
37,
18,
16411,
12,
455,
6527,
38,
13,
342,
20501,
37,
31,
203,
565,
289,
203,
203,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
] |
./partial_match/1/0xd31A9D28d66A1f7e62b5565416ea14607690f788/sources/MainToken.sol | filename: contracts/tokens/FreezableToken.sol* @title FreezableToken @dev Freeze transfer of the specific addresses, if the address is hacked/ | contract FreezableToken is StandardToken, Ownable {
mapping (address => bool) public freezeAddresses;
event FreezableAddressAdded(address indexed addr);
event FreezableAddressRemoved(address indexed addr);
function addFreezableAddresses(address[] memory addrs) public onlyOwner returns(bool success) {
for (uint256 i = 0; i < addrs.length; i++) {
if (addFreezableAddress(addrs[i])) {
success = true;
}
}
}
function addFreezableAddresses(address[] memory addrs) public onlyOwner returns(bool success) {
for (uint256 i = 0; i < addrs.length; i++) {
if (addFreezableAddress(addrs[i])) {
success = true;
}
}
}
function addFreezableAddresses(address[] memory addrs) public onlyOwner returns(bool success) {
for (uint256 i = 0; i < addrs.length; i++) {
if (addFreezableAddress(addrs[i])) {
success = true;
}
}
}
function addFreezableAddress(address addr) public onlyOwner returns(bool success) {
if (!freezeAddresses[addr]) {
freezeAddresses[addr] = true;
emit FreezableAddressAdded(addr);
success = true;
}
}
function addFreezableAddress(address addr) public onlyOwner returns(bool success) {
if (!freezeAddresses[addr]) {
freezeAddresses[addr] = true;
emit FreezableAddressAdded(addr);
success = true;
}
}
function removeFreezableAddresses(address[] memory addrs) public onlyOwner returns(bool success) {
for (uint256 i = 0; i < addrs.length; i++) {
if (removeFreezableAddress(addrs[i])) {
success = true;
}
}
}
function removeFreezableAddresses(address[] memory addrs) public onlyOwner returns(bool success) {
for (uint256 i = 0; i < addrs.length; i++) {
if (removeFreezableAddress(addrs[i])) {
success = true;
}
}
}
function removeFreezableAddresses(address[] memory addrs) public onlyOwner returns(bool success) {
for (uint256 i = 0; i < addrs.length; i++) {
if (removeFreezableAddress(addrs[i])) {
success = true;
}
}
}
function removeFreezableAddress(address addr) public onlyOwner returns(bool success) {
if (freezeAddresses[addr]) {
freezeAddresses[addr] = false;
emit FreezableAddressRemoved(addr);
success = true;
}
}
function removeFreezableAddress(address addr) public onlyOwner returns(bool success) {
if (freezeAddresses[addr]) {
freezeAddresses[addr] = false;
emit FreezableAddressRemoved(addr);
success = true;
}
}
function transferFrom(address _from, address _to, uint256 _value) public returns (bool) {
require(!freezeAddresses[_from]);
require(!freezeAddresses[_to]);
return super.transferFrom(_from, _to, _value);
}
function transfer(address _to, uint256 _value) public returns (bool) {
require(!freezeAddresses[msg.sender]);
require(!freezeAddresses[_to]);
return super.transfer(_to, _value);
}
}
| 9,216,525 | [
1,
3459,
30,
20092,
19,
7860,
19,
9194,
94,
429,
1345,
18,
18281,
225,
15217,
94,
429,
1345,
225,
15217,
8489,
7412,
434,
326,
2923,
6138,
16,
309,
326,
1758,
353,
11769,
329,
19,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
16351,
15217,
94,
429,
1345,
353,
8263,
1345,
16,
14223,
6914,
288,
203,
565,
2874,
261,
2867,
516,
1426,
13,
1071,
16684,
7148,
31,
203,
203,
565,
871,
15217,
94,
429,
1887,
8602,
12,
2867,
8808,
3091,
1769,
203,
565,
871,
15217,
94,
429,
1887,
10026,
12,
2867,
8808,
3091,
1769,
203,
203,
565,
445,
527,
9194,
94,
429,
7148,
12,
2867,
8526,
3778,
11755,
13,
1071,
1338,
5541,
1135,
12,
6430,
2216,
13,
288,
203,
3639,
364,
261,
11890,
5034,
277,
273,
374,
31,
277,
411,
11755,
18,
2469,
31,
277,
27245,
288,
203,
5411,
309,
261,
1289,
9194,
94,
429,
1887,
12,
23305,
63,
77,
22643,
288,
203,
7734,
2216,
273,
638,
31,
203,
5411,
289,
203,
3639,
289,
203,
565,
289,
203,
203,
565,
445,
527,
9194,
94,
429,
7148,
12,
2867,
8526,
3778,
11755,
13,
1071,
1338,
5541,
1135,
12,
6430,
2216,
13,
288,
203,
3639,
364,
261,
11890,
5034,
277,
273,
374,
31,
277,
411,
11755,
18,
2469,
31,
277,
27245,
288,
203,
5411,
309,
261,
1289,
9194,
94,
429,
1887,
12,
23305,
63,
77,
22643,
288,
203,
7734,
2216,
273,
638,
31,
203,
5411,
289,
203,
3639,
289,
203,
565,
289,
203,
203,
565,
445,
527,
9194,
94,
429,
7148,
12,
2867,
8526,
3778,
11755,
13,
1071,
1338,
5541,
1135,
12,
6430,
2216,
13,
288,
203,
3639,
364,
261,
11890,
5034,
277,
273,
374,
31,
277,
411,
11755,
18,
2469,
31,
277,
27245,
288,
203,
5411,
309,
261,
1289,
9194,
94,
429,
1887,
12,
23305,
63,
77,
22643,
2
] |
./full_match/80001/0x36b3Cb222a801411D7dF37E8b819EF15d8896ECB/sources/project_/contracts/PlayerDeposit.sol | Aprovamos Transferimos | function withdrawToken(
address _to,
address _token,
uint256 _amount
) public onlyOwner {
require(_amount > 0, "Invalid withdrawal amount.");
require(_to == address(this), "Invalid withdraw address.");
require(
_amount > 0 && _amount <= IERC20(_token).balanceOf(address(this)),
"Invalid withdraw amount."
);
IERC20(_token).approve(address(this), _amount);
IERC20(_token).transferFrom(address(this), _to, _amount);
}
| 876,124 | [
1,
37,
25529,
301,
538,
12279,
381,
538,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
565,
445,
598,
9446,
1345,
12,
203,
3639,
1758,
389,
869,
16,
203,
3639,
1758,
389,
2316,
16,
203,
3639,
2254,
5034,
389,
8949,
203,
565,
262,
1071,
1338,
5541,
288,
203,
3639,
2583,
24899,
8949,
405,
374,
16,
315,
1941,
598,
9446,
287,
3844,
1199,
1769,
203,
3639,
2583,
24899,
869,
422,
1758,
12,
2211,
3631,
315,
1941,
598,
9446,
1758,
1199,
1769,
203,
3639,
2583,
12,
203,
5411,
389,
8949,
405,
374,
597,
389,
8949,
1648,
467,
654,
39,
3462,
24899,
2316,
2934,
12296,
951,
12,
2867,
12,
2211,
13,
3631,
203,
5411,
315,
1941,
598,
9446,
3844,
1199,
203,
3639,
11272,
203,
203,
3639,
467,
654,
39,
3462,
24899,
2316,
2934,
12908,
537,
12,
2867,
12,
2211,
3631,
389,
8949,
1769,
203,
3639,
467,
654,
39,
3462,
24899,
2316,
2934,
13866,
1265,
12,
2867,
12,
2211,
3631,
389,
869,
16,
389,
8949,
1769,
203,
565,
289,
203,
203,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
] |
./full_match/137/0x8ce6be35426CA317c791335e028505Df2376B598/sources/contracts/HowlToken.sol | Howl Token with Governance. Maximum supply cap (Default value of 100,000) | contract HowlToken is BEP20("Howl Token", "HOWL") {
uint256 public maxSupply = 100000000000000000000000;
function mint(address _to, uint256 _amount) public onlyOwner {
require(maxSupply > totalSupply(), "maxSupply has been reached");
_mint(_to, _amount);
_moveDelegates(address(0), _delegates[_to], _amount);
}
mapping(address => address) internal _delegates;
struct Checkpoint {
uint32 fromBlock;
uint256 votes;
}
keccak256(
"EIP712Domain(string name,uint256 chainId,address verifyingContract)"
);
keccak256("Delegation(address delegatee,uint256 nonce,uint256 expiry)");
address indexed delegator,
address indexed fromDelegate,
address indexed toDelegate
);
address indexed delegate,
uint256 previousBalance,
uint256 newBalance
);
mapping(address => mapping(uint32 => Checkpoint)) public checkpoints;
mapping(address => uint32) public numCheckpoints;
bytes32 public constant DOMAIN_TYPEHASH =
bytes32 public constant DELEGATION_TYPEHASH =
mapping(address => uint256) public nonces;
event DelegateChanged(
event DelegateVotesChanged(
function delegates(address delegator) external view returns (address) {
return _delegates[delegator];
}
function delegate(address delegatee) external {
return _delegate(msg.sender, delegatee);
}
function delegateBySig(
address delegatee,
uint256 nonce,
uint256 expiry,
uint8 v,
bytes32 r,
bytes32 s
) external {
bytes32 domainSeparator = keccak256(
abi.encode(
DOMAIN_TYPEHASH,
keccak256(bytes(name())),
getChainId(),
address(this)
)
);
bytes32 structHash = keccak256(
abi.encode(DELEGATION_TYPEHASH, delegatee, nonce, expiry)
);
bytes32 digest = keccak256(
abi.encodePacked("\x19\x01", domainSeparator, structHash)
);
address signatory = ecrecover(digest, v, r, s);
require(
signatory != address(0),
"HOWL::delegateBySig: invalid signature"
);
require(
nonce == nonces[signatory]++,
"HOWL::delegateBySig: invalid nonce"
);
require(now <= expiry, "HOWL::delegateBySig: signature expired");
return _delegate(signatory, delegatee);
}
function getCurrentVotes(address account) external view returns (uint256) {
uint32 nCheckpoints = numCheckpoints[account];
return
nCheckpoints > 0 ? checkpoints[account][nCheckpoints - 1].votes : 0;
}
function getPriorVotes(address account, uint256 blockNumber)
external
view
returns (uint256)
{
require(
blockNumber < block.number,
"HOWL::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;
}
function getPriorVotes(address account, uint256 blockNumber)
external
view
returns (uint256)
{
require(
blockNumber < block.number,
"HOWL::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;
}
function getPriorVotes(address account, uint256 blockNumber)
external
view
returns (uint256)
{
require(
blockNumber < block.number,
"HOWL::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;
}
function getPriorVotes(address account, uint256 blockNumber)
external
view
returns (uint256)
{
require(
blockNumber < block.number,
"HOWL::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;
}
function getPriorVotes(address account, uint256 blockNumber)
external
view
returns (uint256)
{
require(
blockNumber < block.number,
"HOWL::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;
}
function getPriorVotes(address account, uint256 blockNumber)
external
view
returns (uint256)
{
require(
blockNumber < block.number,
"HOWL::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;
}
} else if (cp.fromBlock < blockNumber) {
} else {
function _delegate(address delegator, address delegatee) internal {
address currentDelegate = _delegates[delegator];
_delegates[delegator] = delegatee;
emit DelegateChanged(delegator, currentDelegate, delegatee);
_moveDelegates(currentDelegate, delegatee, delegatorBalance);
}
function _moveDelegates(
address srcRep,
address dstRep,
uint256 amount
) internal {
if (srcRep != dstRep && amount > 0) {
if (srcRep != address(0)) {
uint32 srcRepNum = numCheckpoints[srcRep];
uint256 srcRepOld = srcRepNum > 0
? checkpoints[srcRep][srcRepNum - 1].votes
: 0;
uint256 srcRepNew = srcRepOld.sub(amount);
_writeCheckpoint(srcRep, srcRepNum, srcRepOld, srcRepNew);
}
if (dstRep != address(0)) {
uint32 dstRepNum = numCheckpoints[dstRep];
uint256 dstRepOld = dstRepNum > 0
? checkpoints[dstRep][dstRepNum - 1].votes
: 0;
uint256 dstRepNew = dstRepOld.add(amount);
_writeCheckpoint(dstRep, dstRepNum, dstRepOld, dstRepNew);
}
}
}
function _moveDelegates(
address srcRep,
address dstRep,
uint256 amount
) internal {
if (srcRep != dstRep && amount > 0) {
if (srcRep != address(0)) {
uint32 srcRepNum = numCheckpoints[srcRep];
uint256 srcRepOld = srcRepNum > 0
? checkpoints[srcRep][srcRepNum - 1].votes
: 0;
uint256 srcRepNew = srcRepOld.sub(amount);
_writeCheckpoint(srcRep, srcRepNum, srcRepOld, srcRepNew);
}
if (dstRep != address(0)) {
uint32 dstRepNum = numCheckpoints[dstRep];
uint256 dstRepOld = dstRepNum > 0
? checkpoints[dstRep][dstRepNum - 1].votes
: 0;
uint256 dstRepNew = dstRepOld.add(amount);
_writeCheckpoint(dstRep, dstRepNum, dstRepOld, dstRepNew);
}
}
}
function _moveDelegates(
address srcRep,
address dstRep,
uint256 amount
) internal {
if (srcRep != dstRep && amount > 0) {
if (srcRep != address(0)) {
uint32 srcRepNum = numCheckpoints[srcRep];
uint256 srcRepOld = srcRepNum > 0
? checkpoints[srcRep][srcRepNum - 1].votes
: 0;
uint256 srcRepNew = srcRepOld.sub(amount);
_writeCheckpoint(srcRep, srcRepNum, srcRepOld, srcRepNew);
}
if (dstRep != address(0)) {
uint32 dstRepNum = numCheckpoints[dstRep];
uint256 dstRepOld = dstRepNum > 0
? checkpoints[dstRep][dstRepNum - 1].votes
: 0;
uint256 dstRepNew = dstRepOld.add(amount);
_writeCheckpoint(dstRep, dstRepNum, dstRepOld, dstRepNew);
}
}
}
function _moveDelegates(
address srcRep,
address dstRep,
uint256 amount
) internal {
if (srcRep != dstRep && amount > 0) {
if (srcRep != address(0)) {
uint32 srcRepNum = numCheckpoints[srcRep];
uint256 srcRepOld = srcRepNum > 0
? checkpoints[srcRep][srcRepNum - 1].votes
: 0;
uint256 srcRepNew = srcRepOld.sub(amount);
_writeCheckpoint(srcRep, srcRepNum, srcRepOld, srcRepNew);
}
if (dstRep != address(0)) {
uint32 dstRepNum = numCheckpoints[dstRep];
uint256 dstRepOld = dstRepNum > 0
? checkpoints[dstRep][dstRepNum - 1].votes
: 0;
uint256 dstRepNew = dstRepOld.add(amount);
_writeCheckpoint(dstRep, dstRepNum, dstRepOld, dstRepNew);
}
}
}
function _writeCheckpoint(
address delegatee,
uint32 nCheckpoints,
uint256 oldVotes,
uint256 newVotes
) internal {
uint32 blockNumber = safe32(
block.number,
"HOWL::_writeCheckpoint: block number exceeds 32 bits"
);
if (
nCheckpoints > 0 &&
checkpoints[delegatee][nCheckpoints - 1].fromBlock == blockNumber
) {
checkpoints[delegatee][nCheckpoints - 1].votes = newVotes;
checkpoints[delegatee][nCheckpoints] = Checkpoint(
blockNumber,
newVotes
);
numCheckpoints[delegatee] = nCheckpoints + 1;
}
emit DelegateVotesChanged(delegatee, oldVotes, newVotes);
}
function _writeCheckpoint(
address delegatee,
uint32 nCheckpoints,
uint256 oldVotes,
uint256 newVotes
) internal {
uint32 blockNumber = safe32(
block.number,
"HOWL::_writeCheckpoint: block number exceeds 32 bits"
);
if (
nCheckpoints > 0 &&
checkpoints[delegatee][nCheckpoints - 1].fromBlock == blockNumber
) {
checkpoints[delegatee][nCheckpoints - 1].votes = newVotes;
checkpoints[delegatee][nCheckpoints] = Checkpoint(
blockNumber,
newVotes
);
numCheckpoints[delegatee] = nCheckpoints + 1;
}
emit DelegateVotesChanged(delegatee, oldVotes, newVotes);
}
} else {
function safe32(uint256 n, string memory errorMessage)
internal
pure
returns (uint32)
{
require(n < 2**32, errorMessage);
return uint32(n);
}
function getChainId() internal pure returns (uint256) {
uint256 chainId;
assembly {
chainId := chainid()
}
return chainId;
}
function getChainId() internal pure returns (uint256) {
uint256 chainId;
assembly {
chainId := chainid()
}
return chainId;
}
}
| 4,732,641 | [
1,
44,
543,
80,
3155,
598,
611,
1643,
82,
1359,
18,
18848,
14467,
3523,
261,
1868,
460,
434,
2130,
16,
3784,
13,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
16351,
9017,
80,
1345,
353,
9722,
52,
3462,
2932,
44,
543,
80,
3155,
3113,
315,
44,
7306,
48,
7923,
288,
203,
565,
2254,
5034,
1071,
943,
3088,
1283,
273,
2130,
12648,
12648,
11706,
31,
203,
203,
565,
445,
312,
474,
12,
2867,
389,
869,
16,
2254,
5034,
389,
8949,
13,
1071,
1338,
5541,
288,
203,
3639,
2583,
12,
1896,
3088,
1283,
405,
2078,
3088,
1283,
9334,
315,
1896,
3088,
1283,
711,
2118,
8675,
8863,
203,
3639,
389,
81,
474,
24899,
869,
16,
389,
8949,
1769,
203,
3639,
389,
8501,
15608,
815,
12,
2867,
12,
20,
3631,
389,
3771,
1332,
815,
63,
67,
869,
6487,
389,
8949,
1769,
203,
565,
289,
203,
203,
203,
203,
565,
2874,
12,
2867,
516,
1758,
13,
2713,
389,
3771,
1332,
815,
31,
203,
565,
1958,
25569,
288,
203,
3639,
2254,
1578,
628,
1768,
31,
203,
3639,
2254,
5034,
19588,
31,
203,
565,
289,
203,
203,
203,
203,
3639,
417,
24410,
581,
5034,
12,
203,
5411,
315,
41,
2579,
27,
2138,
3748,
12,
1080,
508,
16,
11890,
5034,
2687,
548,
16,
2867,
3929,
310,
8924,
2225,
203,
3639,
11272,
203,
203,
3639,
417,
24410,
581,
5034,
2932,
26945,
12,
2867,
7152,
73,
16,
11890,
5034,
7448,
16,
11890,
5034,
10839,
2225,
1769,
203,
203,
203,
3639,
1758,
8808,
11158,
639,
16,
203,
3639,
1758,
8808,
628,
9586,
16,
203,
3639,
1758,
8808,
358,
9586,
203,
565,
11272,
203,
203,
3639,
1758,
8808,
7152,
16,
203,
3639,
2254,
5034,
2416,
13937,
16,
203,
3639,
2254,
5034,
394,
13937,
203,
565,
11272,
2
] |
// SPDX-License-Identifier: MIT
pragma solidity 0.6.12;
pragma experimental ABIEncoderV2;
import "../vendors/interfaces/IUniswapOracle.sol";
import "../vendors/libraries/UniswapV2Library.sol";
import "../vendors/libraries/FixedPoint.sol";
import "../vendors/libraries/SafeMath.sol";
import "../vendors/libraries/UniswapV2OracleLibrary.sol";
// sliding window oracle that uses observations collected over a window to provide moving price averages in the past
// `windowSize` with a precision of `windowSize / granularity`
// note this is a singleton oracle and only needs to be deployed once per desired parameters, which
// differs from the simple oracle which must be deployed once per pair.
contract UniswapOracle is IUniswapOracle {
using FixedPoint for *;
using SafeMath for uint;
struct Observation {
uint timestamp;
uint price0Cumulative;
uint price1Cumulative;
}
address public immutable factory;
address public immutable tokenA; // USDT or BUSD
address public immutable tokenB; // WETH
// address public immutable factory = 0x5C69bEe701ef814a2B6a3EDD4B1652CB9cc5aA6f;
// address public immutable tokenA = 0x4F96Fe3b7A6Cf9725f59d353F723c1bDb64CA6Aa; // DAI
// address public immutable tokenB = 0xd0A1E359811322d97991E03f863a0C30C2cF029C; // WETH
// the desired amount of time over which the moving average should be computed, e.g. 24 hours
uint public immutable windowSize;
// the number of observations stored for each pair, i.e. how many price observations are stored for the window.
// as granularity increases from 1, more frequent updates are needed, but moving averages become more precise.
// averages are computed over intervals with sizes in the range:
// [windowSize - (windowSize / granularity) * 2, windowSize]
// e.g. if the window size is 24 hours, and the granularity is 24, the oracle will return the average price for
// the period:
// [now - [22 hours, 24 hours], now]
uint8 public immutable granularity;
// this is redundant with granularity and windowSize, but stored for gas savings & informational purposes.
uint public immutable periodSize;
// mapping from pair address to a list of price observations of that pair
mapping(address => Observation[]) public pairObservations;
uint256 tmp;
constructor(uint windowSize_, uint8 granularity_ ,address _factory, address _tokenA, address _tokenB) public {
require(granularity_ > 1, 'SlidingWindowOracle: GRANULARITY');
require(
(periodSize = windowSize_ / granularity_) * granularity_ == windowSize_,
'SlidingWindowOracle: WINDOW_NOT_EVENLY_DIVISIBLE'
);
windowSize = windowSize_;
granularity = granularity_;
factory = _factory;
tokenA = _tokenA;
tokenB = _tokenB;
}
// returns the index of the observation corresponding to the given timestamp
function observationIndexOf(uint timestamp) public view returns (uint8 index) {
uint epochPeriod = timestamp / periodSize;
return uint8(epochPeriod % granularity);
}
// returns the observation from the oldest epoch (at the beginning of the window) relative to the current time
function getFirstObservationInWindow(address pair) private view returns (Observation storage firstObservation) {
uint8 observationIndex = observationIndexOf(block.timestamp);
// no overflow issue. if observationIndex + 1 overflows, result is still zero.
uint8 firstObservationIndex = (observationIndex + 1) % granularity;
firstObservation = pairObservations[pair][firstObservationIndex];
}
function getFirstObservationInWindow2(address pair) external view returns (Observation memory firstObservation) {
uint8 observationIndex = observationIndexOf(block.timestamp);
// no overflow issue. if observationIndex + 1 overflows, result is still zero.
uint8 firstObservationIndex = (observationIndex + 1) % granularity;
firstObservation = pairObservations[pair][firstObservationIndex];
}
// update the cumulative price for the observation at the current timestamp. each observation is updated at most
// once per epoch period.
function update() external override {
address pair = UniswapV2Library.pairFor(factory, tokenA, tokenB);
// populate the array with empty observations (first call only)
for (uint i = pairObservations[pair].length; i < granularity; i++) {
pairObservations[pair].push();
}
// get the observation for the current period
uint8 observationIndex = observationIndexOf(block.timestamp);
Observation storage observation = pairObservations[pair][observationIndex];
// we only want to commit updates once per period (i.e. windowSize / granularity)
uint timeElapsed = block.timestamp - observation.timestamp;
if (timeElapsed > periodSize) {
(uint price0Cumulative, uint price1Cumulative,) = UniswapV2OracleLibrary.currentCumulativePrices(pair);
observation.timestamp = block.timestamp;
observation.price0Cumulative = price0Cumulative;
observation.price1Cumulative = price1Cumulative;
}
}
function getPair() external view override returns (address) {
return UniswapV2Library.pairFor(factory, tokenA, tokenB);
}
function getPrice() external view returns (uint,uint) {
address pair = UniswapV2Library.pairFor(factory, tokenA, tokenB);
(uint price0Cumulative, uint price1Cumulative,) = UniswapV2OracleLibrary.currentCumulativePrices(pair);
return (price0Cumulative,price1Cumulative);
}
// given the cumulative prices of the start and end of a period, and the length of the period, compute the average
// price in terms of how much amount out is received for the amount in
function computeAmountOut(
uint priceCumulativeStart, uint priceCumulativeEnd,
uint timeElapsed, uint amountIn
) private pure returns (uint amountOut) {
// overflow is desired.
FixedPoint.uq112x112 memory priceAverage = FixedPoint.uq112x112(
uint224((priceCumulativeEnd - priceCumulativeStart) / timeElapsed)
);
amountOut = priceAverage.mul(amountIn).decode144();
}
// returns the amount out corresponding to the amount in for a given token using the moving average over the time
// range [now - [windowSize, windowSize - periodSize * 2], now]
// update must have been called for the bucket corresponding to timestamp `now - windowSize`
function consult(address tokenIn, uint amountIn, address tokenOut) internal view returns (uint amountOut) {
address pair = UniswapV2Library.pairFor(factory, tokenIn, tokenOut);
Observation storage firstObservation = getFirstObservationInWindow(pair);
uint timeElapsed = block.timestamp - firstObservation.timestamp;
require(timeElapsed <= windowSize, 'SlidingWindowOracle: MISSING_HISTORICAL_OBSERVATION');
// should never happen.
require(timeElapsed >= windowSize - periodSize * 2, 'SlidingWindowOracle: UNEXPECTED_TIME_ELAPSED');
(uint price0Cumulative, uint price1Cumulative,) = UniswapV2OracleLibrary.currentCumulativePrices(pair);
(address token0,) = UniswapV2Library.sortTokens(tokenIn, tokenOut);
if (token0 == tokenIn) {
return computeAmountOut(firstObservation.price0Cumulative, price0Cumulative, timeElapsed, amountIn);
} else {
return computeAmountOut(firstObservation.price1Cumulative, price1Cumulative, timeElapsed, amountIn);
}
}
function consultAB(uint amountIn) external view override returns (uint amountOut){
return consult(tokenA, amountIn, tokenB);
}
function consultBA(uint amountIn) external view override returns (uint amountOut){
return consult(tokenB, amountIn, tokenA);
}
function getTimeElapsed(address tokenIn, address tokenOut) external view override returns (uint) {
address pair = UniswapV2Library.pairFor(factory, tokenIn, tokenOut);
Observation storage firstObservation = getFirstObservationInWindow(pair);
uint timeElapsed = block.timestamp - firstObservation.timestamp;
return timeElapsed;
}
}
// SPDX-License-Identifier: MIT
pragma solidity 0.6.12;
interface IERC20 {
function name() external view returns (string memory);
function symbol() external view returns (string memory);
function decimals() external view returns (uint8);
function totalSupply() external view returns (uint);
function balanceOf(address tokenOwner) external view returns (uint balance);
function allowance(address tokenOwner, address spender) external view returns (uint remaining);
function approve(address spender, uint tokens) external returns (bool success);
function transfer(address to, uint tokens) external returns (bool success);
function transferFrom(address from, address to, uint tokens) external returns (bool success);
event Transfer(address indexed from, address indexed to, uint tokens);
event Approval(address indexed tokenOwner, address indexed spender, uint tokens);
}
// SPDX-License-Identifier: MIT
pragma solidity 0.6.12;
interface IUniswapOracle {
function getPair() external view returns (address);
function update() external;
function getTimeElapsed(address tokenIn, address tokenOut) external view returns (uint);
function consultAB(uint amountIn) external view returns (uint amountOut);
function consultBA(uint amountIn) external view returns (uint amountOut);
}
// SPDX-License-Identifier: MIT
pragma solidity 0.6.12;
import "./IERC20.sol";
interface IUniswapV2ERC20 is IERC20 {
function DOMAIN_SEPARATOR() external view returns (bytes32);
function PERMIT_TYPEHASH() external pure returns (bytes32);
function nonces(address owner) external view returns (uint);
function permit(address owner, address spender, uint value, uint deadline, uint8 v, bytes32 r, bytes32 s) external;
}
// SPDX-License-Identifier: MIT
pragma solidity 0.6.12;
import "./IUniswapV2ERC20.sol";
interface IUniswapV2Pair is IUniswapV2ERC20 {
event Mint(address indexed sender, uint amount0, uint amount1);
event Burn(address indexed sender, uint amount0, uint amount1, address indexed to);
event Swap(
address indexed sender,
uint amount0In,
uint amount1In,
uint amount0Out,
uint amount1Out,
address indexed to
);
event Sync(uint112 reserve0, uint112 reserve1);
function MINIMUM_LIQUIDITY() external pure returns (uint);
function factory() external view returns (address);
function token0() external view returns (address);
function token1() external view returns (address);
function getReserves() external view returns (uint112 reserve0, uint112 reserve1, uint32 blockTimestampLast);
function price0CumulativeLast() external view returns (uint);
function price1CumulativeLast() external view returns (uint);
function kLast() external view returns (uint);
function mint(address to) external returns (uint liquidity);
function burn(address to) external returns (uint amount0, uint amount1);
function swap(uint amount0Out, uint amount1Out, address to, bytes calldata data) external;
function skim(address to) external;
function sync() external;
function initialize(address, address) external;
}
// SPDX-License-Identifier: MIT
pragma solidity 0.6.12;
// computes square roots using the babylonian method
// https://en.wikipedia.org/wiki/Methods_of_computing_square_roots#Babylonian_method
library Babylonian {
// credit for this implementation goes to
// https://github.com/abdk-consulting/abdk-libraries-solidity/blob/master/ABDKMath64x64.sol#L687
function sqrt(uint256 x) internal pure returns (uint256) {
if (x == 0) return 0;
// this block is equivalent to r = uint256(1) << (BitMath.mostSignificantBit(x) / 2);
// however that code costs significantly more gas
uint256 xx = x;
uint256 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
uint256 r1 = x / r;
return (r < r1 ? r : r1);
}
}
// SPDX-License-Identifier: MIT
pragma solidity 0.6.12;
library BitMath {
// returns the 0 indexed position of the most significant bit of the input x
// s.t. x >= 2**msb and x < 2**(msb+1)
function mostSignificantBit(uint256 x) internal pure returns (uint8 r) {
require(x > 0, 'BitMath::mostSignificantBit: zero');
if (x >= 0x100000000000000000000000000000000) {
x >>= 128;
r += 128;
}
if (x >= 0x10000000000000000) {
x >>= 64;
r += 64;
}
if (x >= 0x100000000) {
x >>= 32;
r += 32;
}
if (x >= 0x10000) {
x >>= 16;
r += 16;
}
if (x >= 0x100) {
x >>= 8;
r += 8;
}
if (x >= 0x10) {
x >>= 4;
r += 4;
}
if (x >= 0x4) {
x >>= 2;
r += 2;
}
if (x >= 0x2) r += 1;
}
// returns the 0 indexed position of the least significant bit of the input x
// s.t. (x & 2**lsb) != 0 and (x & (2**(lsb) - 1)) == 0)
// i.e. the bit at the index is set and the mask of all lower bits is 0
function leastSignificantBit(uint256 x) internal pure returns (uint8 r) {
require(x > 0, 'BitMath::leastSignificantBit: zero');
r = 255;
if (x & uint128(-1) > 0) {
r -= 128;
} else {
x >>= 128;
}
if (x & uint64(-1) > 0) {
r -= 64;
} else {
x >>= 64;
}
if (x & uint32(-1) > 0) {
r -= 32;
} else {
x >>= 32;
}
if (x & uint16(-1) > 0) {
r -= 16;
} else {
x >>= 16;
}
if (x & uint8(-1) > 0) {
r -= 8;
} else {
x >>= 8;
}
if (x & 0xf > 0) {
r -= 4;
} else {
x >>= 4;
}
if (x & 0x3 > 0) {
r -= 2;
} else {
x >>= 2;
}
if (x & 0x1 > 0) r -= 1;
}
}
// SPDX-License-Identifier: MIT
pragma solidity 0.6.12;
import './FullMath.sol';
import './Babylonian.sol';
import './BitMath.sol';
// a library for handling binary fixed point numbers (https://en.wikipedia.org/wiki/Q_(number_format))
library FixedPoint {
// range: [0, 2**112 - 1]
// resolution: 1 / 2**112
struct uq112x112 {
uint224 _x;
}
// range: [0, 2**144 - 1]
// resolution: 1 / 2**112
struct uq144x112 {
uint256 _x;
}
uint8 public constant RESOLUTION = 112;
uint256 public constant Q112 = 0x10000000000000000000000000000; // 2**112
uint256 private constant Q224 = 0x100000000000000000000000000000000000000000000000000000000; // 2**224
uint256 private constant LOWER_MASK = 0xffffffffffffffffffffffffffff; // decimal of UQ*x112 (lower 112 bits)
// encode a uint112 as a UQ112x112
function encode(uint112 x) internal pure returns (uq112x112 memory) {
return uq112x112(uint224(x) << RESOLUTION);
}
// encodes a uint144 as a UQ144x112
function encode144(uint144 x) internal pure returns (uq144x112 memory) {
return uq144x112(uint256(x) << RESOLUTION);
}
// decode a UQ112x112 into a uint112 by truncating after the radix point
function decode(uq112x112 memory self) internal pure returns (uint112) {
return uint112(self._x >> RESOLUTION);
}
// decode a UQ144x112 into a uint144 by truncating after the radix point
function decode144(uq144x112 memory self) internal pure returns (uint144) {
return uint144(self._x >> RESOLUTION);
}
// multiply a UQ112x112 by a uint, returning a UQ144x112
// reverts on overflow
function mul(uq112x112 memory self, uint256 y) internal pure returns (uq144x112 memory) {
uint256 z = 0;
require(y == 0 || (z = self._x * y) / y == self._x, 'FixedPoint::mul: overflow');
return uq144x112(z);
}
// multiply a UQ112x112 by an int and decode, returning an int
// reverts on overflow
function muli(uq112x112 memory self, int256 y) internal pure returns (int256) {
uint256 z = FullMath.mulDiv(self._x, uint256(y < 0 ? -y : y), Q112);
require(z < 2**255, 'FixedPoint::muli: overflow');
return y < 0 ? -int256(z) : int256(z);
}
// multiply a UQ112x112 by a UQ112x112, returning a UQ112x112
// lossy
function muluq(uq112x112 memory self, uq112x112 memory other) internal pure returns (uq112x112 memory) {
if (self._x == 0 || other._x == 0) {
return uq112x112(0);
}
uint112 upper_self = uint112(self._x >> RESOLUTION); // * 2^0
uint112 lower_self = uint112(self._x & LOWER_MASK); // * 2^-112
uint112 upper_other = uint112(other._x >> RESOLUTION); // * 2^0
uint112 lower_other = uint112(other._x & LOWER_MASK); // * 2^-112
// partial products
uint224 upper = uint224(upper_self) * upper_other; // * 2^0
uint224 lower = uint224(lower_self) * lower_other; // * 2^-224
uint224 uppers_lowero = uint224(upper_self) * lower_other; // * 2^-112
uint224 uppero_lowers = uint224(upper_other) * lower_self; // * 2^-112
// so the bit shift does not overflow
require(upper <= uint112(-1), 'FixedPoint::muluq: upper overflow');
// this cannot exceed 256 bits, all values are 224 bits
uint256 sum = uint256(upper << RESOLUTION) + uppers_lowero + uppero_lowers + (lower >> RESOLUTION);
// so the cast does not overflow
require(sum <= uint224(-1), 'FixedPoint::muluq: sum overflow');
return uq112x112(uint224(sum));
}
// divide a UQ112x112 by a UQ112x112, returning a UQ112x112
function divuq(uq112x112 memory self, uq112x112 memory other) internal pure returns (uq112x112 memory) {
require(other._x > 0, 'FixedPoint::divuq: division by zero');
if (self._x == other._x) {
return uq112x112(uint224(Q112));
}
if (self._x <= uint144(-1)) {
uint256 value = (uint256(self._x) << RESOLUTION) / other._x;
require(value <= uint224(-1), 'FixedPoint::divuq: overflow');
return uq112x112(uint224(value));
}
uint256 result = FullMath.mulDiv(Q112, self._x, other._x);
require(result <= uint224(-1), 'FixedPoint::divuq: overflow');
return uq112x112(uint224(result));
}
// returns a UQ112x112 which represents the ratio of the numerator to the denominator
// can be lossy
function fraction(uint256 numerator, uint256 denominator) internal pure returns (uq112x112 memory) {
require(denominator > 0, 'FixedPoint::fraction: division by zero');
if (numerator == 0) return FixedPoint.uq112x112(0);
if (numerator <= uint144(-1)) {
uint256 result = (numerator << RESOLUTION) / denominator;
require(result <= uint224(-1), 'FixedPoint::fraction: overflow');
return uq112x112(uint224(result));
} else {
uint256 result = FullMath.mulDiv(numerator, Q112, denominator);
require(result <= uint224(-1), 'FixedPoint::fraction: overflow');
return uq112x112(uint224(result));
}
}
// take the reciprocal of a UQ112x112
// reverts on overflow
// lossy
function reciprocal(uq112x112 memory self) internal pure returns (uq112x112 memory) {
require(self._x != 0, 'FixedPoint::reciprocal: reciprocal of zero');
require(self._x != 1, 'FixedPoint::reciprocal: overflow');
return uq112x112(uint224(Q224 / self._x));
}
// square root of a UQ112x112
// lossy between 0/1 and 40 bits
function sqrt(uq112x112 memory self) internal pure returns (uq112x112 memory) {
if (self._x <= uint144(-1)) {
return uq112x112(uint224(Babylonian.sqrt(uint256(self._x) << 112)));
}
uint8 safeShiftBits = 255 - BitMath.mostSignificantBit(self._x);
safeShiftBits -= safeShiftBits % 2;
return uq112x112(uint224(Babylonian.sqrt(uint256(self._x) << safeShiftBits) << ((112 - safeShiftBits) / 2)));
}
}
// SPDX-License-Identifier: MIT
pragma solidity 0.6.12;
// taken from https://medium.com/coinmonks/math-in-solidity-part-3-percents-and-proportions-4db014e080b1
// license is CC-BY-4.0
library FullMath {
function fullMul(uint256 x, uint256 y) internal pure returns (uint256 l, uint256 h) {
uint256 mm = mulmod(x, y, uint256(-1));
l = x * y;
h = mm - l;
if (mm < l) h -= 1;
}
function fullDiv(
uint256 l,
uint256 h,
uint256 d
) private pure returns (uint256) {
uint256 pow2 = d & -d;
d /= pow2;
l /= pow2;
l += h * ((-pow2) / pow2 + 1);
uint256 r = 1;
r *= 2 - d * r;
r *= 2 - d * r;
r *= 2 - d * r;
r *= 2 - d * r;
r *= 2 - d * r;
r *= 2 - d * r;
r *= 2 - d * r;
r *= 2 - d * r;
return l * r;
}
function mulDiv(
uint256 x,
uint256 y,
uint256 d
) internal pure returns (uint256) {
(uint256 l, uint256 h) = fullMul(x, y);
uint256 mm = mulmod(x, y, d);
if (mm > l) h -= 1;
l -= mm;
if (h == 0) return l / d;
require(h < d, 'FullMath: FULLDIV_OVERFLOW');
return fullDiv(l, h, d);
}
}
// SPDX-License-Identifier: MIT
pragma solidity 0.6.12;
library SafeMath {
function add(uint256 a, uint256 b) internal pure returns (uint256) {
return add(a, b, "SafeMath: Add Overflow");
}
function add(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
uint256 c = a + b;
require(c >= a, errorMessage);// "SafeMath: Add Overflow"
return c;
}
function sub(uint256 a, uint256 b) internal pure returns (uint256) {
return sub(a, b, "SafeMath: Underflow");
}
function sub(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
require(b <= a, errorMessage);
uint256 c = a - b;// "SafeMath: Underflow"
return c;
}
function mul(uint256 a, uint256 b) internal pure returns (uint256) {
return mul(a, b, "SafeMath: Mul Overflow");
}
function mul(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
if (a == 0) {
return 0;
}
uint256 c = a * b;
require(c / a == b, errorMessage);// "SafeMath: Mul Overflow"
return c;
}
function div(uint256 a, uint256 b) internal pure returns (uint256) {
require(b != 0, "SafeMath: division by zero");
uint256 c = a / b;
return c;
}
function mod(uint256 a, uint256 b) internal pure returns (uint256) {
require(b != 0, "SafeMath: modulo by zero");
return a % b;
}
}
// SPDX-License-Identifier: MIT
pragma solidity 0.6.12;
import '../interfaces/IUniswapV2Pair.sol';
import "./SafeMath.sol";
library UniswapV2Library {
using SafeMath for uint;
// returns sorted token addresses, used to handle return values from pairs sorted in this order
function sortTokens(address tokenA, address tokenB) internal pure returns (address token0, address token1) {
require(tokenA != tokenB, 'UniswapV2Library: IDENTICAL_ADDRESSES');
(token0, token1) = tokenA < tokenB ? (tokenA, tokenB) : (tokenB, tokenA);
require(token0 != address(0), 'UniswapV2Library: ZERO_ADDRESS');
}
// calculates the CREATE2 address for a pair without making any external calls
function pairFor(address factory, address tokenA, address tokenB) internal pure returns (address pair) {
(address token0, address token1) = sortTokens(tokenA, tokenB);
pair = address(uint(keccak256(abi.encodePacked(
hex'ff',
factory,
keccak256(abi.encodePacked(token0, token1)),
hex'a7fea0ca09af3ad115eed91f6f5abeff5b69eb113dceedb234968ab0b2fe1216' // init code hash
))));
}
// fetches and sorts the reserves for a pair
function getReserves(address factory, address tokenA, address tokenB) internal view returns (uint reserveA, uint reserveB) {
(address token0,) = sortTokens(tokenA, tokenB);
(uint reserve0, uint reserve1,) = IUniswapV2Pair(pairFor(factory, tokenA, tokenB)).getReserves();
(reserveA, reserveB) = tokenA == token0 ? (reserve0, reserve1) : (reserve1, reserve0);
}
// given some amount of an asset and pair reserves, returns an equivalent amount of the other asset
function quote(uint amountA, uint reserveA, uint reserveB) internal pure returns (uint amountB) {
require(amountA > 0, 'UniswapV2Library: INSUFFICIENT_AMOUNT');
require(reserveA > 0 && reserveB > 0, 'UniswapV2Library: INSUFFICIENT_LIQUIDITY');
amountB = amountA.mul(reserveB) / reserveA;
}
// given an input amount of an asset and pair reserves, returns the maximum output amount of the other asset
function getAmountOut(uint amountIn, uint reserveIn, uint reserveOut) internal pure returns (uint amountOut) {
require(amountIn > 0, 'UniswapV2Library: INSUFFICIENT_INPUT_AMOUNT');
require(reserveIn > 0 && reserveOut > 0, 'UniswapV2Library: INSUFFICIENT_LIQUIDITY');
uint amountInWithFee = amountIn.mul(997);
uint numerator = amountInWithFee.mul(reserveOut);
uint denominator = reserveIn.mul(1000).add(amountInWithFee);
amountOut = numerator / denominator;
}
// given an output amount of an asset and pair reserves, returns a required input amount of the other asset
function getAmountIn(uint amountOut, uint reserveIn, uint reserveOut) internal pure returns (uint amountIn) {
require(amountOut > 0, 'UniswapV2Library: INSUFFICIENT_OUTPUT_AMOUNT');
require(reserveIn > 0 && reserveOut > 0, 'UniswapV2Library: INSUFFICIENT_LIQUIDITY');
uint numerator = reserveIn.mul(amountOut).mul(1000);
uint denominator = reserveOut.sub(amountOut).mul(997);
amountIn = (numerator / denominator).add(1);
}
// performs chained getAmountOut calculations on any number of pairs
function getAmountsOut(address factory, uint amountIn, address[] memory path) internal view returns (uint[] memory amounts) {
require(path.length >= 2, 'UniswapV2Library: INVALID_PATH');
amounts = new uint[](path.length);
amounts[0] = amountIn;
for (uint i; i < path.length - 1; i++) {
(uint reserveIn, uint reserveOut) = getReserves(factory, path[i], path[i + 1]);
amounts[i + 1] = getAmountOut(amounts[i], reserveIn, reserveOut);
}
}
// performs chained getAmountIn calculations on any number of pairs
function getAmountsIn(address factory, uint amountOut, address[] memory path) internal view returns (uint[] memory amounts) {
require(path.length >= 2, 'UniswapV2Library: INVALID_PATH');
amounts = new uint[](path.length);
amounts[amounts.length - 1] = amountOut;
for (uint i = path.length - 1; i > 0; i--) {
(uint reserveIn, uint reserveOut) = getReserves(factory, path[i - 1], path[i]);
amounts[i - 1] = getAmountIn(amounts[i], reserveIn, reserveOut);
}
}
}
// SPDX-License-Identifier: MIT
pragma solidity 0.6.12;
pragma experimental ABIEncoderV2;
import "../interfaces/IUniswapV2Pair.sol";
import "./FixedPoint.sol";
library UniswapV2OracleLibrary {
using FixedPoint for *;
// helper function that returns the current block timestamp within the range of uint32, i.e. [0, 2**32 - 1]
function currentBlockTimestamp() internal view returns (uint32) {
return uint32(block.timestamp % 2 ** 32);
}
// produces the cumulative price using counterfactuals to save gas and avoid a call to sync.
function currentCumulativePrices(
address pair
) internal view returns (uint price0Cumulative, uint price1Cumulative, uint32 blockTimestamp) {
blockTimestamp = currentBlockTimestamp();
price0Cumulative = IUniswapV2Pair(pair).price0CumulativeLast();
price1Cumulative = IUniswapV2Pair(pair).price1CumulativeLast();
// if time has elapsed since the last update on the pair, mock the accumulated price values
(uint112 reserve0, uint112 reserve1, uint32 blockTimestampLast) = IUniswapV2Pair(pair).getReserves();
if (blockTimestampLast != blockTimestamp) {
// subtraction overflow is desired
uint32 timeElapsed = blockTimestamp - blockTimestampLast;
// addition overflow is desired
// counterfactual
price0Cumulative += uint(FixedPoint.fraction(reserve1, reserve0)._x) * timeElapsed;
// counterfactual
price1Cumulative += uint(FixedPoint.fraction(reserve0, reserve1)._x) * timeElapsed;
}
}
}
| "SafeMath: Mul Overflow"
| require(c / a == b, errorMessage); | 109,689 | [
1,
6,
9890,
10477,
30,
21640,
10752,
2426,
6,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
3639,
2583,
12,
71,
342,
279,
422,
324,
16,
9324,
1769,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
] |
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import "@openzeppelin/contracts/utils/cryptography/draft-EIP712.sol";
import "@openzeppelin/contracts/utils/cryptography/ECDSA.sol";
import "@openzeppelin/contracts/utils/Counters.sol";
import "@openzeppelin/contracts/access/Ownable.sol";
import "./OpeningCeremony.sol";
import "hardhat/console.sol";
/**
* Allow verified users to whitelist themselves on the opening ceremony contract
*
* See: https://eips.ethereum.org/EIPS/eip-712
*
* Process is:
* 1. DAO verifies and signs a request off-chain confirming a user has completed the quest
* 2. User then submits a request to be verified, along with the signed request
* 3. If the request to verify matches the signed request, and the request was signed by the DAO, the user can
* whitelist themselves.
*/
contract VerifyQuest is EIP712, Ownable {
using Counters for Counters.Counter;
mapping(address => Counters.Counter) private _nonces;
OpeningCeremony public openingCeremony;
address public verifier;
// solhint-disable-next-line var-name-mixedcase
bytes32 public immutable VERIFY_TYPEHASH = keccak256("Verify(address quester,uint256 nonce)");
/**
* Initializes the {EIP712} domain separator and setting `version` to `"1"`.
*/
constructor(
OpeningCeremony _openingCeremony,
address _verifier
) EIP712("VerifyQuest", "1") {
openingCeremony = _openingCeremony;
verifier = _verifier;
}
function setVerifier(address _verifier) external onlyOwner {
verifier = _verifier;
}
/**
* If verified, add as a verified user to the OpeningCeremony
*/
function verify(uint8 v, bytes32 r, bytes32 s) external {
bytes32 structHash = keccak256(abi.encode(VERIFY_TYPEHASH, msg.sender, _useNonce(msg.sender)));
bytes32 digest = _hashTypedDataV4(structHash);
address signer = ECDSA.recover(digest, v, r, s);
require(signer == verifier, "invalid signature");
openingCeremony.addVerifiedUser(msg.sender);
}
/**
* Generate a digest (to be signed off-chain by the verified private key)
*/
function digestFor(address quester) public view returns(bytes32 digest) {
bytes32 structHash = keccak256(abi.encode(VERIFY_TYPEHASH, quester, nonces(quester)));
digest = _hashTypedDataV4(structHash);
}
/**
* Current nonce for an given
*/
function nonces(address user) public view returns (uint256) {
return _nonces[user].current();
}
/**
* @dev See {IERC20Permit-DOMAIN_SEPARATOR}.
*/
// solhint-disable-next-line func-name-mixedcase
function DOMAIN_SEPARATOR() external view returns (bytes32) {
return _domainSeparatorV4();
}
/**
* @dev "Consume a nonce": return the current value and increment.
*
* _Available since v4.1._
*/
function _useNonce(address user) internal returns (uint256 current) {
Counters.Counter storage nonce = _nonces[user];
current = nonce.current();
nonce.increment();
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import "./ECDSA.sol";
/**
* @dev https://eips.ethereum.org/EIPS/eip-712[EIP 712] is a standard for hashing and signing of typed structured data.
*
* The encoding specified in the EIP is very generic, and such a generic implementation in Solidity is not feasible,
* thus this contract does not implement the encoding itself. Protocols need to implement the type-specific encoding
* they need in their contracts using a combination of `abi.encode` and `keccak256`.
*
* This contract implements the EIP 712 domain separator ({_domainSeparatorV4}) that is used as part of the encoding
* scheme, and the final step of the encoding to obtain the message digest that is then signed via ECDSA
* ({_hashTypedDataV4}).
*
* The implementation of the domain separator was designed to be as efficient as possible while still properly updating
* the chain id to protect against replay attacks on an eventual fork of the chain.
*
* NOTE: This contract implements the version of the encoding known as "v4", as implemented by the JSON RPC method
* https://docs.metamask.io/guide/signing-data.html[`eth_signTypedDataV4` in MetaMask].
*
* _Available since v3.4._
*/
abstract contract EIP712 {
/* solhint-disable var-name-mixedcase */
// Cache the domain separator as an immutable value, but also store the chain id that it corresponds to, in order to
// invalidate the cached domain separator if the chain id changes.
bytes32 private immutable _CACHED_DOMAIN_SEPARATOR;
uint256 private immutable _CACHED_CHAIN_ID;
bytes32 private immutable _HASHED_NAME;
bytes32 private immutable _HASHED_VERSION;
bytes32 private immutable _TYPE_HASH;
/* solhint-enable var-name-mixedcase */
/**
* @dev Initializes the domain separator and parameter caches.
*
* The meaning of `name` and `version` is specified in
* https://eips.ethereum.org/EIPS/eip-712#definition-of-domainseparator[EIP 712]:
*
* - `name`: the user readable name of the signing domain, i.e. the name of the DApp or the protocol.
* - `version`: the current major version of the signing domain.
*
* NOTE: These parameters cannot be changed except through a xref:learn::upgrading-smart-contracts.adoc[smart
* contract upgrade].
*/
constructor(string memory name, string memory version) {
bytes32 hashedName = keccak256(bytes(name));
bytes32 hashedVersion = keccak256(bytes(version));
bytes32 typeHash = keccak256(
"EIP712Domain(string name,string version,uint256 chainId,address verifyingContract)"
);
_HASHED_NAME = hashedName;
_HASHED_VERSION = hashedVersion;
_CACHED_CHAIN_ID = block.chainid;
_CACHED_DOMAIN_SEPARATOR = _buildDomainSeparator(typeHash, hashedName, hashedVersion);
_TYPE_HASH = typeHash;
}
/**
* @dev Returns the domain separator for the current chain.
*/
function _domainSeparatorV4() internal view returns (bytes32) {
if (block.chainid == _CACHED_CHAIN_ID) {
return _CACHED_DOMAIN_SEPARATOR;
} else {
return _buildDomainSeparator(_TYPE_HASH, _HASHED_NAME, _HASHED_VERSION);
}
}
function _buildDomainSeparator(
bytes32 typeHash,
bytes32 nameHash,
bytes32 versionHash
) private view returns (bytes32) {
return keccak256(abi.encode(typeHash, nameHash, versionHash, block.chainid, address(this)));
}
/**
* @dev Given an already https://eips.ethereum.org/EIPS/eip-712#definition-of-hashstruct[hashed struct], this
* function returns the hash of the fully encoded EIP712 message for this domain.
*
* This hash can be used together with {ECDSA-recover} to obtain the signer of a message. For example:
*
* ```solidity
* bytes32 digest = _hashTypedDataV4(keccak256(abi.encode(
* keccak256("Mail(address to,string contents)"),
* mailTo,
* keccak256(bytes(mailContents))
* )));
* address signer = ECDSA.recover(digest, signature);
* ```
*/
function _hashTypedDataV4(bytes32 structHash) internal view virtual returns (bytes32) {
return ECDSA.toTypedDataHash(_domainSeparatorV4(), structHash);
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
/**
* @dev Elliptic Curve Digital Signature Algorithm (ECDSA) operations.
*
* These functions can be used to verify that a message was signed by the holder
* of the private keys of a given address.
*/
library ECDSA {
enum RecoverError {
NoError,
InvalidSignature,
InvalidSignatureLength,
InvalidSignatureS,
InvalidSignatureV
}
function _throwError(RecoverError error) private pure {
if (error == RecoverError.NoError) {
return; // no error: do nothing
} else if (error == RecoverError.InvalidSignature) {
revert("ECDSA: invalid signature");
} else if (error == RecoverError.InvalidSignatureLength) {
revert("ECDSA: invalid signature length");
} else if (error == RecoverError.InvalidSignatureS) {
revert("ECDSA: invalid signature 's' value");
} else if (error == RecoverError.InvalidSignatureV) {
revert("ECDSA: invalid signature 'v' value");
}
}
/**
* @dev Returns the address that signed a hashed message (`hash`) with
* `signature` or error string. This address can then be used for verification purposes.
*
* The `ecrecover` EVM opcode allows for malleable (non-unique) signatures:
* this function rejects them by requiring the `s` value to be in the lower
* half order, and the `v` value to be either 27 or 28.
*
* IMPORTANT: `hash` _must_ be the result of a hash operation for the
* verification to be secure: it is possible to craft signatures that
* recover to arbitrary addresses for non-hashed data. A safe way to ensure
* this is by receiving a hash of the original message (which may otherwise
* be too long), and then calling {toEthSignedMessageHash} on it.
*
* Documentation for signature generation:
* - with https://web3js.readthedocs.io/en/v1.3.4/web3-eth-accounts.html#sign[Web3.js]
* - with https://docs.ethers.io/v5/api/signer/#Signer-signMessage[ethers]
*
* _Available since v4.3._
*/
function tryRecover(bytes32 hash, bytes memory signature) internal pure returns (address, RecoverError) {
// Check the signature length
// - case 65: r,s,v signature (standard)
// - case 64: r,vs signature (cf https://eips.ethereum.org/EIPS/eip-2098) _Available since v4.1._
if (signature.length == 65) {
bytes32 r;
bytes32 s;
uint8 v;
// ecrecover takes the signature parameters, and the only way to get them
// currently is to use assembly.
assembly {
r := mload(add(signature, 0x20))
s := mload(add(signature, 0x40))
v := byte(0, mload(add(signature, 0x60)))
}
return tryRecover(hash, v, r, s);
} else if (signature.length == 64) {
bytes32 r;
bytes32 vs;
// ecrecover takes the signature parameters, and the only way to get them
// currently is to use assembly.
assembly {
r := mload(add(signature, 0x20))
vs := mload(add(signature, 0x40))
}
return tryRecover(hash, r, vs);
} else {
return (address(0), RecoverError.InvalidSignatureLength);
}
}
/**
* @dev Returns the address that signed a hashed message (`hash`) with
* `signature`. This address can then be used for verification purposes.
*
* The `ecrecover` EVM opcode allows for malleable (non-unique) signatures:
* this function rejects them by requiring the `s` value to be in the lower
* half order, and the `v` value to be either 27 or 28.
*
* IMPORTANT: `hash` _must_ be the result of a hash operation for the
* verification to be secure: it is possible to craft signatures that
* recover to arbitrary addresses for non-hashed data. A safe way to ensure
* this is by receiving a hash of the original message (which may otherwise
* be too long), and then calling {toEthSignedMessageHash} on it.
*/
function recover(bytes32 hash, bytes memory signature) internal pure returns (address) {
(address recovered, RecoverError error) = tryRecover(hash, signature);
_throwError(error);
return recovered;
}
/**
* @dev Overload of {ECDSA-tryRecover} that receives the `r` and `vs` short-signature fields separately.
*
* See https://eips.ethereum.org/EIPS/eip-2098[EIP-2098 short signatures]
*
* _Available since v4.3._
*/
function tryRecover(
bytes32 hash,
bytes32 r,
bytes32 vs
) internal pure returns (address, RecoverError) {
bytes32 s;
uint8 v;
assembly {
s := and(vs, 0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff)
v := add(shr(255, vs), 27)
}
return tryRecover(hash, v, r, s);
}
/**
* @dev Overload of {ECDSA-recover} that receives the `r and `vs` short-signature fields separately.
*
* _Available since v4.2._
*/
function recover(
bytes32 hash,
bytes32 r,
bytes32 vs
) internal pure returns (address) {
(address recovered, RecoverError error) = tryRecover(hash, r, vs);
_throwError(error);
return recovered;
}
/**
* @dev Overload of {ECDSA-tryRecover} that receives the `v`,
* `r` and `s` signature fields separately.
*
* _Available since v4.3._
*/
function tryRecover(
bytes32 hash,
uint8 v,
bytes32 r,
bytes32 s
) internal pure returns (address, RecoverError) {
// 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 (301): 0 < s < secp256k1n ÷ 2 + 1, and for v in (302): 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), RecoverError.InvalidSignatureS);
}
if (v != 27 && v != 28) {
return (address(0), RecoverError.InvalidSignatureV);
}
// If the signature is valid (and not malleable), return the signer address
address signer = ecrecover(hash, v, r, s);
if (signer == address(0)) {
return (address(0), RecoverError.InvalidSignature);
}
return (signer, RecoverError.NoError);
}
/**
* @dev Overload of {ECDSA-recover} that receives the `v`,
* `r` and `s` signature fields separately.
*/
function recover(
bytes32 hash,
uint8 v,
bytes32 r,
bytes32 s
) internal pure returns (address) {
(address recovered, RecoverError error) = tryRecover(hash, v, r, s);
_throwError(error);
return recovered;
}
/**
* @dev Returns an Ethereum Signed Message, created from a `hash`. This
* produces hash corresponding to the one signed with the
* https://eth.wiki/json-rpc/API#eth_sign[`eth_sign`]
* JSON-RPC method as part of EIP-191.
*
* See {recover}.
*/
function toEthSignedMessageHash(bytes32 hash) internal pure returns (bytes32) {
// 32 is the length in bytes of hash,
// enforced by the type signature above
return keccak256(abi.encodePacked("\x19Ethereum Signed Message:\n32", hash));
}
/**
* @dev Returns an Ethereum Signed Typed Data, created from a
* `domainSeparator` and a `structHash`. This produces hash corresponding
* to the one signed with the
* https://eips.ethereum.org/EIPS/eip-712[`eth_signTypedData`]
* JSON-RPC method as part of EIP-712.
*
* See {recover}.
*/
function toTypedDataHash(bytes32 domainSeparator, bytes32 structHash) internal pure returns (bytes32) {
return keccak256(abi.encodePacked("\x19\x01", domainSeparator, structHash));
}
}
// SPDX-License-Identifier: MIT
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 "../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() {
_setOwner(_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 {
_setOwner(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");
_setOwner(newOwner);
}
function _setOwner(address newOwner) private {
address oldOwner = _owner;
_owner = newOwner;
emit OwnershipTransferred(oldOwner, newOwner);
}
}
pragma solidity ^0.8.4;
// SPDX-License-Identifier: GPL-3.0-or-later
import "@openzeppelin/contracts/token/ERC20/IERC20.sol";
import "@openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol";
import "@openzeppelin/contracts/access/Ownable.sol";
import "@openzeppelin/contracts/access/AccessControl.sol";
import "./TempleERC20Token.sol";
import "./SandalwoodToken.sol";
import "./TempleTreasury.sol";
import "./TreasuryManagementProxy.sol";
import "./TempleStaking.sol";
import "./PresaleAllocation.sol";
import "./LockedOGTemple.sol";
/**
* Mint and Stake for those who have quested in the Opening Ceremony
*/
contract OpeningCeremony is Ownable, Pausable, AccessControl {
bytes32 public constant CAN_ADD_VERIFIED_USER = keccak256("CAN_ADD_VERIFIED_USER");
uint256 constant SECONDS_IN_DAY = 24 * 60 * 60;
IERC20 public stablecToken; // contract address for stable coin used in treasury
TempleERC20Token public templeToken; // temple ERC20 contract
TempleTreasury public treasury; // temple treasury
TreasuryManagementProxy public treasuryManagement; // temple treasury
TempleStaking public staking; // Staking contract
LockedOGTemple public lockedOGTemple; // contract where OG Temple is locked
uint256 public unlockDelaySeconds = SECONDS_IN_DAY * 7 * 6; // How long after after buying can templars unlock
uint256 public mintMultiple = 6; // presale mint multiple
uint256 public harvestThresholdStablec; // At what mint level do stakers trigger a harvest
uint256 public inviteThresholdStablec; // How much does a verified user have to spend before they can invite others
uint256 public maxInvitesPerVerifiedUser; // How many guests can each verified user invite
// how much to multiple a verified users day 1 mint limit to work out
// their total at a given point in time. So for a user who quests
// on day 1 => 3 day limit will be DAY_ONE_LIMIT * 4 / 1
// on day 2 => 3 day limit will be DAY_ONE_LIMIT * 4 / 2
uint256 public globalDoublingIndex = 1;
uint256 public lastUpdatedTimestamp; // when was the limitFactor last updated
struct Limit {
uint256 guestMax;
uint256 verifiedMax;
uint256 verifiedDayOne;
}
Limit public limitStablec = Limit({guestMax: 10000 * 1e18, verifiedMax: 480000 * 1e18, verifiedDayOne: 30000 * 1e18});
Limit public limitTemple = Limit({guestMax: 10000 * 1e18, verifiedMax: 480000 * 1e18, verifiedDayOne: 30000 * 1e18});
struct Factor {
uint256 numerator;
uint256 denominator;
}
Factor public verifiedBonusFactor; // Factor applied to verified user, to boost APY
Factor public guestBonusFactor; // Factor applied to temple guests, to boost APY
struct User {
bool isVerified;
bool isGuest;
uint8 numInvited;
uint256 doublingIndexAtVerification;
uint256 totalSacrificedStablec;
uint256 totalSacrificedTemple;
}
mapping(address => User) public users;
event MintComplete(address minter, uint256 acceptedStablec, uint256 mintedTemple, uint256 bonusTemple, uint256 mintedOGTemple);
event StakeComplete(address staker, uint256 acceptedTemple, uint256 bonusTemple, uint256 mintedOGTemple);
event VerifiedUserAdded(address user);
constructor(
IERC20 _stablecToken,
TempleERC20Token _templeToken,
TempleStaking _staking,
LockedOGTemple _lockedOGTemple,
TempleTreasury _treasury,
TreasuryManagementProxy _treasuryManagement,
uint256 _harvestThresholdStablec,
uint256 _inviteThresholdStablec,
uint256 _maxInvitesPerVerifiedUser,
Factor memory _verifiedBonusFactor,
Factor memory _guestBonusFactor
) {
stablecToken = _stablecToken;
templeToken = _templeToken;
staking = _staking;
lockedOGTemple = _lockedOGTemple;
treasury = _treasury;
treasuryManagement = _treasuryManagement;
harvestThresholdStablec = _harvestThresholdStablec;
inviteThresholdStablec = _inviteThresholdStablec;
maxInvitesPerVerifiedUser = _maxInvitesPerVerifiedUser;
verifiedBonusFactor = _verifiedBonusFactor;
guestBonusFactor = _guestBonusFactor;
lastUpdatedTimestamp = block.timestamp;
_setupRole(DEFAULT_ADMIN_ROLE, owner());
}
function setUnlockDelay(uint256 _unlockDelaySeconds) external onlyOwner {
unlockDelaySeconds = _unlockDelaySeconds;
}
function setMintMultiple(uint256 _mintMultiple) external onlyOwner {
mintMultiple = _mintMultiple;
}
function setHarvestThreshold(uint256 _harvestThresholdStablec) external onlyOwner {
harvestThresholdStablec = _harvestThresholdStablec;
}
function setInviteThreshold(uint256 _inviteThresholdStablec) external onlyOwner {
inviteThresholdStablec = _inviteThresholdStablec;
}
function setMaxInvitesPerVerifiedUser(uint256 _maxInvitesPerVerifiedUser) external onlyOwner {
maxInvitesPerVerifiedUser = _maxInvitesPerVerifiedUser;
}
function setVerifiedBonusFactor(uint256 _numerator, uint256 _denominator) external onlyOwner {
verifiedBonusFactor.numerator = _numerator;
verifiedBonusFactor.denominator = _denominator;
}
function setGuestBonusFactor(uint256 _numerator, uint256 _denominator) external onlyOwner {
guestBonusFactor.numerator = _numerator;
guestBonusFactor.denominator = _denominator;
}
function setLimitStablec(uint256 guestMax, uint256 verifiedMax, uint256 verifiedDayOne) external onlyOwner {
limitStablec.guestMax = guestMax;
limitStablec.verifiedMax = verifiedMax;
limitStablec.verifiedDayOne = verifiedDayOne;
}
function setLimitTemple(uint256 guestMax, uint256 verifiedMax) external onlyOwner {
limitTemple.guestMax = guestMax;
limitTemple.verifiedMax = verifiedMax;
// unused limitTemple.verifiedDayOne
}
function addVerifier(address account) external onlyOwner {
grantRole(CAN_ADD_VERIFIED_USER, account);
}
function removeVerifier(address account) external onlyOwner {
revokeRole(CAN_ADD_VERIFIED_USER, account);
}
function addVerifiedUser(address userAddress) external {
require(hasRole(CAN_ADD_VERIFIED_USER, msg.sender), "Caller cannot add verified user");
require(!users[userAddress].isVerified, "Address already verified");
users[userAddress].isVerified = true;
users[userAddress].doublingIndexAtVerification = globalDoublingIndex;
emit VerifiedUserAdded(userAddress);
}
function addGuestUser(address userAddress) external {
require(users[msg.sender].isVerified, "only verified users can invite guests");
require(users[msg.sender].totalSacrificedStablec >= inviteThresholdStablec,
"Need to sacrifice more frax before you can invite others");
require(users[msg.sender].numInvited < maxInvitesPerVerifiedUser,
"Exceed maximum number of invites");
users[userAddress].isGuest = true;
users[msg.sender].numInvited += 1;
}
/** mint temple and immediately stake, on behalf of a staker, with a bonus + lockin period */
function mintAndStakeFor(address _staker, uint256 _amountPaidStablec) public whenNotPaused {
User storage userInfo = users[_staker];
// update max limit. This happens before checks, to ensure maxSacrificable
// is correctly calculated.
if ((block.timestamp - lastUpdatedTimestamp) > SECONDS_IN_DAY) {
globalDoublingIndex *= 2;
lastUpdatedTimestamp += SECONDS_IN_DAY;
}
Factor storage bonusFactor;
if (userInfo.isVerified) {
require(
userInfo.totalSacrificedStablec + _amountPaidStablec <= maxSacrificableStablec(userInfo.doublingIndexAtVerification),
"Exceeded max mint limit");
bonusFactor = verifiedBonusFactor;
} else if (userInfo.isGuest) {
require(userInfo.totalSacrificedStablec + _amountPaidStablec <= limitStablec.guestMax, "Exceeded max mint limit");
bonusFactor = guestBonusFactor;
} else {
revert("Only verified templars and their guests can partake in the opening ceremony");
}
(uint256 _stablec, uint256 _temple) = treasury.intrinsicValueRatio();
uint256 _boughtTemple = _amountPaidStablec * _temple / _stablec / mintMultiple;
// Calculate extra temple required to account for bonus APY
uint256 _bonusTemple = _boughtTemple * bonusFactor.numerator / bonusFactor.denominator;
uint256 _totalTemple = _boughtTemple + _bonusTemple;
userInfo.totalSacrificedStablec += _amountPaidStablec;
// pull stablec from staker and immediately transfer back to treasury
SafeERC20.safeTransferFrom(stablecToken, msg.sender, address(treasury), _amountPaidStablec);
// mint temple
templeToken.mint(address(this), _totalTemple);
// Stake both minted and bonus temple. Locking up any OGTemple
SafeERC20.safeIncreaseAllowance(templeToken, address(staking), _totalTemple);
uint256 _amountOgTemple = staking.stake(_totalTemple);
SafeERC20.safeIncreaseAllowance(staking.OG_TEMPLE(), address(lockedOGTemple), _amountOgTemple);
lockedOGTemple.lockFor(_staker, _amountOgTemple, block.timestamp + unlockDelaySeconds);
// Finally, run harvest if amount sacrificed is 10k or greater
if (_amountPaidStablec >= harvestThresholdStablec) {
treasuryManagement.harvest();
}
emit MintComplete(_staker, _amountPaidStablec, _boughtTemple, _bonusTemple, _amountOgTemple);
}
/** mint temple and immediately stake, with a bonus + lockin period */
function mintAndStake(uint256 _amountPaidStablec) external whenNotPaused {
mintAndStakeFor(msg.sender, _amountPaidStablec);
}
/** Stake temple, consuming sandalwood to get bonus APY **/
function stakeFor(address _staker, uint256 _amountTemple) public whenNotPaused {
User storage userInfo = users[_staker];
Factor storage bonusFactor;
if (userInfo.isVerified) {
require(userInfo.totalSacrificedTemple + _amountTemple <= limitTemple.verifiedMax, "exceeded max limit");
bonusFactor = verifiedBonusFactor;
} else if (userInfo.isGuest) {
require(userInfo.totalSacrificedTemple + _amountTemple <= limitTemple.guestMax, "exceeded max limit");
bonusFactor = guestBonusFactor;
} else {
revert("Only verified templars and their guests can partake in the opening ceremony");
}
// Calculate extra temple required to account for bonus APY
uint256 _bonusTemple = _amountTemple * bonusFactor.numerator / bonusFactor.denominator;
uint256 _totalTemple = _amountTemple + _bonusTemple;
userInfo.totalSacrificedTemple += _amountTemple;
// pull temple from caller (to be staked)
SafeERC20.safeTransferFrom(templeToken, msg.sender, address(this), _amountTemple);
// mint bonus APY temple
templeToken.mint(address(this), _bonusTemple);
// Stake both minted and bonus temple. Locking up any OGTemple
SafeERC20.safeIncreaseAllowance(templeToken, address(staking), _totalTemple);
uint256 _amountOgTemple = staking.stake(_totalTemple);
SafeERC20.safeIncreaseAllowance(staking.OG_TEMPLE(), address(lockedOGTemple), _amountOgTemple);
lockedOGTemple.lockFor(_staker, _amountOgTemple, block.timestamp + unlockDelaySeconds);
emit StakeComplete(_staker, _amountTemple, _bonusTemple, _amountOgTemple);
}
/** Stake temple, consuming sandalwood to get bonus APY **/
function stake(uint256 _amountTemple) external whenNotPaused {
stakeFor(msg.sender, _amountTemple);
}
/**
* Pause contract. Either emergency or at the end of presale
*/
function pause() external onlyOwner {
_pause();
}
/**
* Revert pause
*/
function unpause() external onlyOwner {
_unpause();
}
function maxSacrificableStablec(uint256 doublingIndexAtVerification) public view returns(uint256 maxLimit) {
maxLimit = limitStablec.verifiedDayOne * globalDoublingIndex / doublingIndexAtVerification;
if (maxLimit > limitStablec.verifiedMax) {
maxLimit = limitStablec.verifiedMax;
}
}
}
// SPDX-License-Identifier: MIT
pragma solidity >= 0.4.22 <0.9.0;
library console {
address constant CONSOLE_ADDRESS = address(0x000000000000000000636F6e736F6c652e6c6f67);
function _sendLogPayload(bytes memory payload) private view {
uint256 payloadLength = payload.length;
address consoleAddress = CONSOLE_ADDRESS;
assembly {
let payloadStart := add(payload, 32)
let r := staticcall(gas(), consoleAddress, payloadStart, payloadLength, 0, 0)
}
}
function log() internal view {
_sendLogPayload(abi.encodeWithSignature("log()"));
}
function logInt(int p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(int)", p0));
}
function logUint(uint p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint)", p0));
}
function logString(string memory p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string)", p0));
}
function logBool(bool p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool)", p0));
}
function logAddress(address p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address)", p0));
}
function logBytes(bytes memory p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bytes)", p0));
}
function logBytes1(bytes1 p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bytes1)", p0));
}
function logBytes2(bytes2 p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bytes2)", p0));
}
function logBytes3(bytes3 p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bytes3)", p0));
}
function logBytes4(bytes4 p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bytes4)", p0));
}
function logBytes5(bytes5 p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bytes5)", p0));
}
function logBytes6(bytes6 p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bytes6)", p0));
}
function logBytes7(bytes7 p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bytes7)", p0));
}
function logBytes8(bytes8 p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bytes8)", p0));
}
function logBytes9(bytes9 p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bytes9)", p0));
}
function logBytes10(bytes10 p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bytes10)", p0));
}
function logBytes11(bytes11 p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bytes11)", p0));
}
function logBytes12(bytes12 p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bytes12)", p0));
}
function logBytes13(bytes13 p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bytes13)", p0));
}
function logBytes14(bytes14 p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bytes14)", p0));
}
function logBytes15(bytes15 p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bytes15)", p0));
}
function logBytes16(bytes16 p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bytes16)", p0));
}
function logBytes17(bytes17 p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bytes17)", p0));
}
function logBytes18(bytes18 p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bytes18)", p0));
}
function logBytes19(bytes19 p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bytes19)", p0));
}
function logBytes20(bytes20 p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bytes20)", p0));
}
function logBytes21(bytes21 p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bytes21)", p0));
}
function logBytes22(bytes22 p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bytes22)", p0));
}
function logBytes23(bytes23 p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bytes23)", p0));
}
function logBytes24(bytes24 p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bytes24)", p0));
}
function logBytes25(bytes25 p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bytes25)", p0));
}
function logBytes26(bytes26 p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bytes26)", p0));
}
function logBytes27(bytes27 p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bytes27)", p0));
}
function logBytes28(bytes28 p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bytes28)", p0));
}
function logBytes29(bytes29 p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bytes29)", p0));
}
function logBytes30(bytes30 p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bytes30)", p0));
}
function logBytes31(bytes31 p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bytes31)", p0));
}
function logBytes32(bytes32 p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bytes32)", p0));
}
function log(uint p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint)", p0));
}
function log(string memory p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string)", p0));
}
function log(bool p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool)", p0));
}
function log(address p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address)", p0));
}
function log(uint p0, uint p1) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,uint)", p0, p1));
}
function log(uint p0, string memory p1) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,string)", p0, p1));
}
function log(uint p0, bool p1) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,bool)", p0, p1));
}
function log(uint p0, address p1) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,address)", p0, p1));
}
function log(string memory p0, uint p1) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,uint)", p0, p1));
}
function log(string memory p0, string memory p1) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,string)", p0, p1));
}
function log(string memory p0, bool p1) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,bool)", p0, p1));
}
function log(string memory p0, address p1) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,address)", p0, p1));
}
function log(bool p0, uint p1) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,uint)", p0, p1));
}
function log(bool p0, string memory p1) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,string)", p0, p1));
}
function log(bool p0, bool p1) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,bool)", p0, p1));
}
function log(bool p0, address p1) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,address)", p0, p1));
}
function log(address p0, uint p1) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,uint)", p0, p1));
}
function log(address p0, string memory p1) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,string)", p0, p1));
}
function log(address p0, bool p1) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,bool)", p0, p1));
}
function log(address p0, address p1) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,address)", p0, p1));
}
function log(uint p0, uint p1, uint p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,uint,uint)", p0, p1, p2));
}
function log(uint p0, uint p1, string memory p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,uint,string)", p0, p1, p2));
}
function log(uint p0, uint p1, bool p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,uint,bool)", p0, p1, p2));
}
function log(uint p0, uint p1, address p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,uint,address)", p0, p1, p2));
}
function log(uint p0, string memory p1, uint p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,string,uint)", p0, p1, p2));
}
function log(uint p0, string memory p1, string memory p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,string,string)", p0, p1, p2));
}
function log(uint p0, string memory p1, bool p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,string,bool)", p0, p1, p2));
}
function log(uint p0, string memory p1, address p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,string,address)", p0, p1, p2));
}
function log(uint p0, bool p1, uint p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,bool,uint)", p0, p1, p2));
}
function log(uint p0, bool p1, string memory p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,bool,string)", p0, p1, p2));
}
function log(uint p0, bool p1, bool p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,bool,bool)", p0, p1, p2));
}
function log(uint p0, bool p1, address p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,bool,address)", p0, p1, p2));
}
function log(uint p0, address p1, uint p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,address,uint)", p0, p1, p2));
}
function log(uint p0, address p1, string memory p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,address,string)", p0, p1, p2));
}
function log(uint p0, address p1, bool p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,address,bool)", p0, p1, p2));
}
function log(uint p0, address p1, address p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,address,address)", p0, p1, p2));
}
function log(string memory p0, uint p1, uint p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,uint,uint)", p0, p1, p2));
}
function log(string memory p0, uint p1, string memory p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,uint,string)", p0, p1, p2));
}
function log(string memory p0, uint p1, bool p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,uint,bool)", p0, p1, p2));
}
function log(string memory p0, uint p1, address p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,uint,address)", p0, p1, p2));
}
function log(string memory p0, string memory p1, uint p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,string,uint)", p0, p1, p2));
}
function log(string memory p0, string memory p1, string memory p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,string,string)", p0, p1, p2));
}
function log(string memory p0, string memory p1, bool p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,string,bool)", p0, p1, p2));
}
function log(string memory p0, string memory p1, address p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,string,address)", p0, p1, p2));
}
function log(string memory p0, bool p1, uint p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,bool,uint)", p0, p1, p2));
}
function log(string memory p0, bool p1, string memory p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,bool,string)", p0, p1, p2));
}
function log(string memory p0, bool p1, bool p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,bool,bool)", p0, p1, p2));
}
function log(string memory p0, bool p1, address p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,bool,address)", p0, p1, p2));
}
function log(string memory p0, address p1, uint p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,address,uint)", p0, p1, p2));
}
function log(string memory p0, address p1, string memory p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,address,string)", p0, p1, p2));
}
function log(string memory p0, address p1, bool p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,address,bool)", p0, p1, p2));
}
function log(string memory p0, address p1, address p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,address,address)", p0, p1, p2));
}
function log(bool p0, uint p1, uint p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,uint,uint)", p0, p1, p2));
}
function log(bool p0, uint p1, string memory p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,uint,string)", p0, p1, p2));
}
function log(bool p0, uint p1, bool p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,uint,bool)", p0, p1, p2));
}
function log(bool p0, uint p1, address p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,uint,address)", p0, p1, p2));
}
function log(bool p0, string memory p1, uint p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,string,uint)", p0, p1, p2));
}
function log(bool p0, string memory p1, string memory p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,string,string)", p0, p1, p2));
}
function log(bool p0, string memory p1, bool p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,string,bool)", p0, p1, p2));
}
function log(bool p0, string memory p1, address p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,string,address)", p0, p1, p2));
}
function log(bool p0, bool p1, uint p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,bool,uint)", p0, p1, p2));
}
function log(bool p0, bool p1, string memory p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,bool,string)", p0, p1, p2));
}
function log(bool p0, bool p1, bool p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,bool,bool)", p0, p1, p2));
}
function log(bool p0, bool p1, address p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,bool,address)", p0, p1, p2));
}
function log(bool p0, address p1, uint p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,address,uint)", p0, p1, p2));
}
function log(bool p0, address p1, string memory p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,address,string)", p0, p1, p2));
}
function log(bool p0, address p1, bool p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,address,bool)", p0, p1, p2));
}
function log(bool p0, address p1, address p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,address,address)", p0, p1, p2));
}
function log(address p0, uint p1, uint p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,uint,uint)", p0, p1, p2));
}
function log(address p0, uint p1, string memory p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,uint,string)", p0, p1, p2));
}
function log(address p0, uint p1, bool p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,uint,bool)", p0, p1, p2));
}
function log(address p0, uint p1, address p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,uint,address)", p0, p1, p2));
}
function log(address p0, string memory p1, uint p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,string,uint)", p0, p1, p2));
}
function log(address p0, string memory p1, string memory p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,string,string)", p0, p1, p2));
}
function log(address p0, string memory p1, bool p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,string,bool)", p0, p1, p2));
}
function log(address p0, string memory p1, address p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,string,address)", p0, p1, p2));
}
function log(address p0, bool p1, uint p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,bool,uint)", p0, p1, p2));
}
function log(address p0, bool p1, string memory p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,bool,string)", p0, p1, p2));
}
function log(address p0, bool p1, bool p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,bool,bool)", p0, p1, p2));
}
function log(address p0, bool p1, address p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,bool,address)", p0, p1, p2));
}
function log(address p0, address p1, uint p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,address,uint)", p0, p1, p2));
}
function log(address p0, address p1, string memory p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,address,string)", p0, p1, p2));
}
function log(address p0, address p1, bool p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,address,bool)", p0, p1, p2));
}
function log(address p0, address p1, address p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,address,address)", p0, p1, p2));
}
function log(uint p0, uint p1, uint p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,uint,uint,uint)", p0, p1, p2, p3));
}
function log(uint p0, uint p1, uint p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,uint,uint,string)", p0, p1, p2, p3));
}
function log(uint p0, uint p1, uint p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,uint,uint,bool)", p0, p1, p2, p3));
}
function log(uint p0, uint p1, uint p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,uint,uint,address)", p0, p1, p2, p3));
}
function log(uint p0, uint p1, string memory p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,uint,string,uint)", p0, p1, p2, p3));
}
function log(uint p0, uint p1, string memory p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,uint,string,string)", p0, p1, p2, p3));
}
function log(uint p0, uint p1, string memory p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,uint,string,bool)", p0, p1, p2, p3));
}
function log(uint p0, uint p1, string memory p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,uint,string,address)", p0, p1, p2, p3));
}
function log(uint p0, uint p1, bool p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,uint,bool,uint)", p0, p1, p2, p3));
}
function log(uint p0, uint p1, bool p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,uint,bool,string)", p0, p1, p2, p3));
}
function log(uint p0, uint p1, bool p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,uint,bool,bool)", p0, p1, p2, p3));
}
function log(uint p0, uint p1, bool p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,uint,bool,address)", p0, p1, p2, p3));
}
function log(uint p0, uint p1, address p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,uint,address,uint)", p0, p1, p2, p3));
}
function log(uint p0, uint p1, address p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,uint,address,string)", p0, p1, p2, p3));
}
function log(uint p0, uint p1, address p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,uint,address,bool)", p0, p1, p2, p3));
}
function log(uint p0, uint p1, address p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,uint,address,address)", p0, p1, p2, p3));
}
function log(uint p0, string memory p1, uint p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,string,uint,uint)", p0, p1, p2, p3));
}
function log(uint p0, string memory p1, uint p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,string,uint,string)", p0, p1, p2, p3));
}
function log(uint p0, string memory p1, uint p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,string,uint,bool)", p0, p1, p2, p3));
}
function log(uint p0, string memory p1, uint p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,string,uint,address)", p0, p1, p2, p3));
}
function log(uint p0, string memory p1, string memory p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,string,string,uint)", p0, p1, p2, p3));
}
function log(uint p0, string memory p1, string memory p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,string,string,string)", p0, p1, p2, p3));
}
function log(uint p0, string memory p1, string memory p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,string,string,bool)", p0, p1, p2, p3));
}
function log(uint p0, string memory p1, string memory p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,string,string,address)", p0, p1, p2, p3));
}
function log(uint p0, string memory p1, bool p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,string,bool,uint)", p0, p1, p2, p3));
}
function log(uint p0, string memory p1, bool p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,string,bool,string)", p0, p1, p2, p3));
}
function log(uint p0, string memory p1, bool p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,string,bool,bool)", p0, p1, p2, p3));
}
function log(uint p0, string memory p1, bool p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,string,bool,address)", p0, p1, p2, p3));
}
function log(uint p0, string memory p1, address p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,string,address,uint)", p0, p1, p2, p3));
}
function log(uint p0, string memory p1, address p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,string,address,string)", p0, p1, p2, p3));
}
function log(uint p0, string memory p1, address p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,string,address,bool)", p0, p1, p2, p3));
}
function log(uint p0, string memory p1, address p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,string,address,address)", p0, p1, p2, p3));
}
function log(uint p0, bool p1, uint p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,bool,uint,uint)", p0, p1, p2, p3));
}
function log(uint p0, bool p1, uint p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,bool,uint,string)", p0, p1, p2, p3));
}
function log(uint p0, bool p1, uint p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,bool,uint,bool)", p0, p1, p2, p3));
}
function log(uint p0, bool p1, uint p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,bool,uint,address)", p0, p1, p2, p3));
}
function log(uint p0, bool p1, string memory p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,bool,string,uint)", p0, p1, p2, p3));
}
function log(uint p0, bool p1, string memory p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,bool,string,string)", p0, p1, p2, p3));
}
function log(uint p0, bool p1, string memory p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,bool,string,bool)", p0, p1, p2, p3));
}
function log(uint p0, bool p1, string memory p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,bool,string,address)", p0, p1, p2, p3));
}
function log(uint p0, bool p1, bool p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,bool,bool,uint)", p0, p1, p2, p3));
}
function log(uint p0, bool p1, bool p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,bool,bool,string)", p0, p1, p2, p3));
}
function log(uint p0, bool p1, bool p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,bool,bool,bool)", p0, p1, p2, p3));
}
function log(uint p0, bool p1, bool p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,bool,bool,address)", p0, p1, p2, p3));
}
function log(uint p0, bool p1, address p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,bool,address,uint)", p0, p1, p2, p3));
}
function log(uint p0, bool p1, address p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,bool,address,string)", p0, p1, p2, p3));
}
function log(uint p0, bool p1, address p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,bool,address,bool)", p0, p1, p2, p3));
}
function log(uint p0, bool p1, address p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,bool,address,address)", p0, p1, p2, p3));
}
function log(uint p0, address p1, uint p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,address,uint,uint)", p0, p1, p2, p3));
}
function log(uint p0, address p1, uint p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,address,uint,string)", p0, p1, p2, p3));
}
function log(uint p0, address p1, uint p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,address,uint,bool)", p0, p1, p2, p3));
}
function log(uint p0, address p1, uint p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,address,uint,address)", p0, p1, p2, p3));
}
function log(uint p0, address p1, string memory p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,address,string,uint)", p0, p1, p2, p3));
}
function log(uint p0, address p1, string memory p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,address,string,string)", p0, p1, p2, p3));
}
function log(uint p0, address p1, string memory p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,address,string,bool)", p0, p1, p2, p3));
}
function log(uint p0, address p1, string memory p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,address,string,address)", p0, p1, p2, p3));
}
function log(uint p0, address p1, bool p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,address,bool,uint)", p0, p1, p2, p3));
}
function log(uint p0, address p1, bool p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,address,bool,string)", p0, p1, p2, p3));
}
function log(uint p0, address p1, bool p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,address,bool,bool)", p0, p1, p2, p3));
}
function log(uint p0, address p1, bool p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,address,bool,address)", p0, p1, p2, p3));
}
function log(uint p0, address p1, address p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,address,address,uint)", p0, p1, p2, p3));
}
function log(uint p0, address p1, address p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,address,address,string)", p0, p1, p2, p3));
}
function log(uint p0, address p1, address p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,address,address,bool)", p0, p1, p2, p3));
}
function log(uint p0, address p1, address p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,address,address,address)", p0, p1, p2, p3));
}
function log(string memory p0, uint p1, uint p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,uint,uint,uint)", p0, p1, p2, p3));
}
function log(string memory p0, uint p1, uint p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,uint,uint,string)", p0, p1, p2, p3));
}
function log(string memory p0, uint p1, uint p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,uint,uint,bool)", p0, p1, p2, p3));
}
function log(string memory p0, uint p1, uint p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,uint,uint,address)", p0, p1, p2, p3));
}
function log(string memory p0, uint p1, string memory p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,uint,string,uint)", p0, p1, p2, p3));
}
function log(string memory p0, uint p1, string memory p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,uint,string,string)", p0, p1, p2, p3));
}
function log(string memory p0, uint p1, string memory p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,uint,string,bool)", p0, p1, p2, p3));
}
function log(string memory p0, uint p1, string memory p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,uint,string,address)", p0, p1, p2, p3));
}
function log(string memory p0, uint p1, bool p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,uint,bool,uint)", p0, p1, p2, p3));
}
function log(string memory p0, uint p1, bool p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,uint,bool,string)", p0, p1, p2, p3));
}
function log(string memory p0, uint p1, bool p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,uint,bool,bool)", p0, p1, p2, p3));
}
function log(string memory p0, uint p1, bool p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,uint,bool,address)", p0, p1, p2, p3));
}
function log(string memory p0, uint p1, address p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,uint,address,uint)", p0, p1, p2, p3));
}
function log(string memory p0, uint p1, address p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,uint,address,string)", p0, p1, p2, p3));
}
function log(string memory p0, uint p1, address p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,uint,address,bool)", p0, p1, p2, p3));
}
function log(string memory p0, uint p1, address p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,uint,address,address)", p0, p1, p2, p3));
}
function log(string memory p0, string memory p1, uint p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,string,uint,uint)", p0, p1, p2, p3));
}
function log(string memory p0, string memory p1, uint p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,string,uint,string)", p0, p1, p2, p3));
}
function log(string memory p0, string memory p1, uint p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,string,uint,bool)", p0, p1, p2, p3));
}
function log(string memory p0, string memory p1, uint p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,string,uint,address)", p0, p1, p2, p3));
}
function log(string memory p0, string memory p1, string memory p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,string,string,uint)", p0, p1, p2, p3));
}
function log(string memory p0, string memory p1, string memory p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,string,string,string)", p0, p1, p2, p3));
}
function log(string memory p0, string memory p1, string memory p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,string,string,bool)", p0, p1, p2, p3));
}
function log(string memory p0, string memory p1, string memory p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,string,string,address)", p0, p1, p2, p3));
}
function log(string memory p0, string memory p1, bool p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,string,bool,uint)", p0, p1, p2, p3));
}
function log(string memory p0, string memory p1, bool p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,string,bool,string)", p0, p1, p2, p3));
}
function log(string memory p0, string memory p1, bool p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,string,bool,bool)", p0, p1, p2, p3));
}
function log(string memory p0, string memory p1, bool p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,string,bool,address)", p0, p1, p2, p3));
}
function log(string memory p0, string memory p1, address p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,string,address,uint)", p0, p1, p2, p3));
}
function log(string memory p0, string memory p1, address p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,string,address,string)", p0, p1, p2, p3));
}
function log(string memory p0, string memory p1, address p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,string,address,bool)", p0, p1, p2, p3));
}
function log(string memory p0, string memory p1, address p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,string,address,address)", p0, p1, p2, p3));
}
function log(string memory p0, bool p1, uint p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,bool,uint,uint)", p0, p1, p2, p3));
}
function log(string memory p0, bool p1, uint p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,bool,uint,string)", p0, p1, p2, p3));
}
function log(string memory p0, bool p1, uint p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,bool,uint,bool)", p0, p1, p2, p3));
}
function log(string memory p0, bool p1, uint p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,bool,uint,address)", p0, p1, p2, p3));
}
function log(string memory p0, bool p1, string memory p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,bool,string,uint)", p0, p1, p2, p3));
}
function log(string memory p0, bool p1, string memory p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,bool,string,string)", p0, p1, p2, p3));
}
function log(string memory p0, bool p1, string memory p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,bool,string,bool)", p0, p1, p2, p3));
}
function log(string memory p0, bool p1, string memory p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,bool,string,address)", p0, p1, p2, p3));
}
function log(string memory p0, bool p1, bool p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,bool,bool,uint)", p0, p1, p2, p3));
}
function log(string memory p0, bool p1, bool p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,bool,bool,string)", p0, p1, p2, p3));
}
function log(string memory p0, bool p1, bool p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,bool,bool,bool)", p0, p1, p2, p3));
}
function log(string memory p0, bool p1, bool p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,bool,bool,address)", p0, p1, p2, p3));
}
function log(string memory p0, bool p1, address p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,bool,address,uint)", p0, p1, p2, p3));
}
function log(string memory p0, bool p1, address p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,bool,address,string)", p0, p1, p2, p3));
}
function log(string memory p0, bool p1, address p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,bool,address,bool)", p0, p1, p2, p3));
}
function log(string memory p0, bool p1, address p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,bool,address,address)", p0, p1, p2, p3));
}
function log(string memory p0, address p1, uint p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,address,uint,uint)", p0, p1, p2, p3));
}
function log(string memory p0, address p1, uint p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,address,uint,string)", p0, p1, p2, p3));
}
function log(string memory p0, address p1, uint p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,address,uint,bool)", p0, p1, p2, p3));
}
function log(string memory p0, address p1, uint p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,address,uint,address)", p0, p1, p2, p3));
}
function log(string memory p0, address p1, string memory p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,address,string,uint)", p0, p1, p2, p3));
}
function log(string memory p0, address p1, string memory p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,address,string,string)", p0, p1, p2, p3));
}
function log(string memory p0, address p1, string memory p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,address,string,bool)", p0, p1, p2, p3));
}
function log(string memory p0, address p1, string memory p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,address,string,address)", p0, p1, p2, p3));
}
function log(string memory p0, address p1, bool p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,address,bool,uint)", p0, p1, p2, p3));
}
function log(string memory p0, address p1, bool p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,address,bool,string)", p0, p1, p2, p3));
}
function log(string memory p0, address p1, bool p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,address,bool,bool)", p0, p1, p2, p3));
}
function log(string memory p0, address p1, bool p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,address,bool,address)", p0, p1, p2, p3));
}
function log(string memory p0, address p1, address p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,address,address,uint)", p0, p1, p2, p3));
}
function log(string memory p0, address p1, address p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,address,address,string)", p0, p1, p2, p3));
}
function log(string memory p0, address p1, address p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,address,address,bool)", p0, p1, p2, p3));
}
function log(string memory p0, address p1, address p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,address,address,address)", p0, p1, p2, p3));
}
function log(bool p0, uint p1, uint p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,uint,uint,uint)", p0, p1, p2, p3));
}
function log(bool p0, uint p1, uint p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,uint,uint,string)", p0, p1, p2, p3));
}
function log(bool p0, uint p1, uint p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,uint,uint,bool)", p0, p1, p2, p3));
}
function log(bool p0, uint p1, uint p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,uint,uint,address)", p0, p1, p2, p3));
}
function log(bool p0, uint p1, string memory p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,uint,string,uint)", p0, p1, p2, p3));
}
function log(bool p0, uint p1, string memory p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,uint,string,string)", p0, p1, p2, p3));
}
function log(bool p0, uint p1, string memory p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,uint,string,bool)", p0, p1, p2, p3));
}
function log(bool p0, uint p1, string memory p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,uint,string,address)", p0, p1, p2, p3));
}
function log(bool p0, uint p1, bool p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,uint,bool,uint)", p0, p1, p2, p3));
}
function log(bool p0, uint p1, bool p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,uint,bool,string)", p0, p1, p2, p3));
}
function log(bool p0, uint p1, bool p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,uint,bool,bool)", p0, p1, p2, p3));
}
function log(bool p0, uint p1, bool p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,uint,bool,address)", p0, p1, p2, p3));
}
function log(bool p0, uint p1, address p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,uint,address,uint)", p0, p1, p2, p3));
}
function log(bool p0, uint p1, address p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,uint,address,string)", p0, p1, p2, p3));
}
function log(bool p0, uint p1, address p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,uint,address,bool)", p0, p1, p2, p3));
}
function log(bool p0, uint p1, address p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,uint,address,address)", p0, p1, p2, p3));
}
function log(bool p0, string memory p1, uint p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,string,uint,uint)", p0, p1, p2, p3));
}
function log(bool p0, string memory p1, uint p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,string,uint,string)", p0, p1, p2, p3));
}
function log(bool p0, string memory p1, uint p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,string,uint,bool)", p0, p1, p2, p3));
}
function log(bool p0, string memory p1, uint p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,string,uint,address)", p0, p1, p2, p3));
}
function log(bool p0, string memory p1, string memory p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,string,string,uint)", p0, p1, p2, p3));
}
function log(bool p0, string memory p1, string memory p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,string,string,string)", p0, p1, p2, p3));
}
function log(bool p0, string memory p1, string memory p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,string,string,bool)", p0, p1, p2, p3));
}
function log(bool p0, string memory p1, string memory p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,string,string,address)", p0, p1, p2, p3));
}
function log(bool p0, string memory p1, bool p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,string,bool,uint)", p0, p1, p2, p3));
}
function log(bool p0, string memory p1, bool p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,string,bool,string)", p0, p1, p2, p3));
}
function log(bool p0, string memory p1, bool p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,string,bool,bool)", p0, p1, p2, p3));
}
function log(bool p0, string memory p1, bool p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,string,bool,address)", p0, p1, p2, p3));
}
function log(bool p0, string memory p1, address p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,string,address,uint)", p0, p1, p2, p3));
}
function log(bool p0, string memory p1, address p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,string,address,string)", p0, p1, p2, p3));
}
function log(bool p0, string memory p1, address p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,string,address,bool)", p0, p1, p2, p3));
}
function log(bool p0, string memory p1, address p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,string,address,address)", p0, p1, p2, p3));
}
function log(bool p0, bool p1, uint p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,bool,uint,uint)", p0, p1, p2, p3));
}
function log(bool p0, bool p1, uint p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,bool,uint,string)", p0, p1, p2, p3));
}
function log(bool p0, bool p1, uint p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,bool,uint,bool)", p0, p1, p2, p3));
}
function log(bool p0, bool p1, uint p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,bool,uint,address)", p0, p1, p2, p3));
}
function log(bool p0, bool p1, string memory p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,bool,string,uint)", p0, p1, p2, p3));
}
function log(bool p0, bool p1, string memory p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,bool,string,string)", p0, p1, p2, p3));
}
function log(bool p0, bool p1, string memory p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,bool,string,bool)", p0, p1, p2, p3));
}
function log(bool p0, bool p1, string memory p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,bool,string,address)", p0, p1, p2, p3));
}
function log(bool p0, bool p1, bool p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,bool,bool,uint)", p0, p1, p2, p3));
}
function log(bool p0, bool p1, bool p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,bool,bool,string)", p0, p1, p2, p3));
}
function log(bool p0, bool p1, bool p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,bool,bool,bool)", p0, p1, p2, p3));
}
function log(bool p0, bool p1, bool p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,bool,bool,address)", p0, p1, p2, p3));
}
function log(bool p0, bool p1, address p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,bool,address,uint)", p0, p1, p2, p3));
}
function log(bool p0, bool p1, address p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,bool,address,string)", p0, p1, p2, p3));
}
function log(bool p0, bool p1, address p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,bool,address,bool)", p0, p1, p2, p3));
}
function log(bool p0, bool p1, address p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,bool,address,address)", p0, p1, p2, p3));
}
function log(bool p0, address p1, uint p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,address,uint,uint)", p0, p1, p2, p3));
}
function log(bool p0, address p1, uint p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,address,uint,string)", p0, p1, p2, p3));
}
function log(bool p0, address p1, uint p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,address,uint,bool)", p0, p1, p2, p3));
}
function log(bool p0, address p1, uint p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,address,uint,address)", p0, p1, p2, p3));
}
function log(bool p0, address p1, string memory p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,address,string,uint)", p0, p1, p2, p3));
}
function log(bool p0, address p1, string memory p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,address,string,string)", p0, p1, p2, p3));
}
function log(bool p0, address p1, string memory p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,address,string,bool)", p0, p1, p2, p3));
}
function log(bool p0, address p1, string memory p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,address,string,address)", p0, p1, p2, p3));
}
function log(bool p0, address p1, bool p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,address,bool,uint)", p0, p1, p2, p3));
}
function log(bool p0, address p1, bool p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,address,bool,string)", p0, p1, p2, p3));
}
function log(bool p0, address p1, bool p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,address,bool,bool)", p0, p1, p2, p3));
}
function log(bool p0, address p1, bool p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,address,bool,address)", p0, p1, p2, p3));
}
function log(bool p0, address p1, address p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,address,address,uint)", p0, p1, p2, p3));
}
function log(bool p0, address p1, address p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,address,address,string)", p0, p1, p2, p3));
}
function log(bool p0, address p1, address p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,address,address,bool)", p0, p1, p2, p3));
}
function log(bool p0, address p1, address p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,address,address,address)", p0, p1, p2, p3));
}
function log(address p0, uint p1, uint p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,uint,uint,uint)", p0, p1, p2, p3));
}
function log(address p0, uint p1, uint p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,uint,uint,string)", p0, p1, p2, p3));
}
function log(address p0, uint p1, uint p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,uint,uint,bool)", p0, p1, p2, p3));
}
function log(address p0, uint p1, uint p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,uint,uint,address)", p0, p1, p2, p3));
}
function log(address p0, uint p1, string memory p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,uint,string,uint)", p0, p1, p2, p3));
}
function log(address p0, uint p1, string memory p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,uint,string,string)", p0, p1, p2, p3));
}
function log(address p0, uint p1, string memory p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,uint,string,bool)", p0, p1, p2, p3));
}
function log(address p0, uint p1, string memory p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,uint,string,address)", p0, p1, p2, p3));
}
function log(address p0, uint p1, bool p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,uint,bool,uint)", p0, p1, p2, p3));
}
function log(address p0, uint p1, bool p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,uint,bool,string)", p0, p1, p2, p3));
}
function log(address p0, uint p1, bool p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,uint,bool,bool)", p0, p1, p2, p3));
}
function log(address p0, uint p1, bool p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,uint,bool,address)", p0, p1, p2, p3));
}
function log(address p0, uint p1, address p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,uint,address,uint)", p0, p1, p2, p3));
}
function log(address p0, uint p1, address p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,uint,address,string)", p0, p1, p2, p3));
}
function log(address p0, uint p1, address p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,uint,address,bool)", p0, p1, p2, p3));
}
function log(address p0, uint p1, address p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,uint,address,address)", p0, p1, p2, p3));
}
function log(address p0, string memory p1, uint p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,string,uint,uint)", p0, p1, p2, p3));
}
function log(address p0, string memory p1, uint p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,string,uint,string)", p0, p1, p2, p3));
}
function log(address p0, string memory p1, uint p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,string,uint,bool)", p0, p1, p2, p3));
}
function log(address p0, string memory p1, uint p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,string,uint,address)", p0, p1, p2, p3));
}
function log(address p0, string memory p1, string memory p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,string,string,uint)", p0, p1, p2, p3));
}
function log(address p0, string memory p1, string memory p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,string,string,string)", p0, p1, p2, p3));
}
function log(address p0, string memory p1, string memory p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,string,string,bool)", p0, p1, p2, p3));
}
function log(address p0, string memory p1, string memory p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,string,string,address)", p0, p1, p2, p3));
}
function log(address p0, string memory p1, bool p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,string,bool,uint)", p0, p1, p2, p3));
}
function log(address p0, string memory p1, bool p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,string,bool,string)", p0, p1, p2, p3));
}
function log(address p0, string memory p1, bool p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,string,bool,bool)", p0, p1, p2, p3));
}
function log(address p0, string memory p1, bool p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,string,bool,address)", p0, p1, p2, p3));
}
function log(address p0, string memory p1, address p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,string,address,uint)", p0, p1, p2, p3));
}
function log(address p0, string memory p1, address p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,string,address,string)", p0, p1, p2, p3));
}
function log(address p0, string memory p1, address p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,string,address,bool)", p0, p1, p2, p3));
}
function log(address p0, string memory p1, address p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,string,address,address)", p0, p1, p2, p3));
}
function log(address p0, bool p1, uint p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,bool,uint,uint)", p0, p1, p2, p3));
}
function log(address p0, bool p1, uint p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,bool,uint,string)", p0, p1, p2, p3));
}
function log(address p0, bool p1, uint p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,bool,uint,bool)", p0, p1, p2, p3));
}
function log(address p0, bool p1, uint p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,bool,uint,address)", p0, p1, p2, p3));
}
function log(address p0, bool p1, string memory p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,bool,string,uint)", p0, p1, p2, p3));
}
function log(address p0, bool p1, string memory p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,bool,string,string)", p0, p1, p2, p3));
}
function log(address p0, bool p1, string memory p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,bool,string,bool)", p0, p1, p2, p3));
}
function log(address p0, bool p1, string memory p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,bool,string,address)", p0, p1, p2, p3));
}
function log(address p0, bool p1, bool p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,bool,bool,uint)", p0, p1, p2, p3));
}
function log(address p0, bool p1, bool p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,bool,bool,string)", p0, p1, p2, p3));
}
function log(address p0, bool p1, bool p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,bool,bool,bool)", p0, p1, p2, p3));
}
function log(address p0, bool p1, bool p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,bool,bool,address)", p0, p1, p2, p3));
}
function log(address p0, bool p1, address p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,bool,address,uint)", p0, p1, p2, p3));
}
function log(address p0, bool p1, address p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,bool,address,string)", p0, p1, p2, p3));
}
function log(address p0, bool p1, address p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,bool,address,bool)", p0, p1, p2, p3));
}
function log(address p0, bool p1, address p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,bool,address,address)", p0, p1, p2, p3));
}
function log(address p0, address p1, uint p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,address,uint,uint)", p0, p1, p2, p3));
}
function log(address p0, address p1, uint p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,address,uint,string)", p0, p1, p2, p3));
}
function log(address p0, address p1, uint p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,address,uint,bool)", p0, p1, p2, p3));
}
function log(address p0, address p1, uint p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,address,uint,address)", p0, p1, p2, p3));
}
function log(address p0, address p1, string memory p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,address,string,uint)", p0, p1, p2, p3));
}
function log(address p0, address p1, string memory p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,address,string,string)", p0, p1, p2, p3));
}
function log(address p0, address p1, string memory p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,address,string,bool)", p0, p1, p2, p3));
}
function log(address p0, address p1, string memory p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,address,string,address)", p0, p1, p2, p3));
}
function log(address p0, address p1, bool p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,address,bool,uint)", p0, p1, p2, p3));
}
function log(address p0, address p1, bool p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,address,bool,string)", p0, p1, p2, p3));
}
function log(address p0, address p1, bool p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,address,bool,bool)", p0, p1, p2, p3));
}
function log(address p0, address p1, bool p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,address,bool,address)", p0, p1, p2, p3));
}
function log(address p0, address p1, address p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,address,address,uint)", p0, p1, p2, p3));
}
function log(address p0, address p1, address p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,address,address,string)", p0, p1, p2, p3));
}
function log(address p0, address p1, address p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,address,address,bool)", p0, p1, p2, p3));
}
function log(address p0, address p1, address p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,address,address,address)", p0, p1, p2, p3));
}
}
// 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) {
return msg.data;
}
}
// 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;
import "./IAccessControl.sol";
import "../utils/Context.sol";
import "../utils/Strings.sol";
import "../utils/introspection/ERC165.sol";
/**
* @dev Contract module that allows children to implement role-based access
* control mechanisms. This is a lightweight version that doesn't allow enumerating role
* members except through off-chain means by accessing the contract event logs. Some
* applications may benefit from on-chain enumerability, for those cases see
* {AccessControlEnumerable}.
*
* Roles are referred to by their `bytes32` identifier. These should be exposed
* in the external API and be unique. The best way to achieve this is by
* using `public constant` hash digests:
*
* ```
* bytes32 public constant MY_ROLE = keccak256("MY_ROLE");
* ```
*
* Roles can be used to represent a set of permissions. To restrict access to a
* function call, use {hasRole}:
*
* ```
* function foo() public {
* require(hasRole(MY_ROLE, msg.sender));
* ...
* }
* ```
*
* Roles can be granted and revoked dynamically via the {grantRole} and
* {revokeRole} functions. Each role has an associated admin role, and only
* accounts that have a role's admin role can call {grantRole} and {revokeRole}.
*
* By default, the admin role for all roles is `DEFAULT_ADMIN_ROLE`, which means
* that only accounts with this role will be able to grant or revoke other
* roles. More complex role relationships can be created by using
* {_setRoleAdmin}.
*
* WARNING: The `DEFAULT_ADMIN_ROLE` is also its own admin: it has permission to
* grant and revoke this role. Extra precautions should be taken to secure
* accounts that have been granted it.
*/
abstract contract AccessControl is Context, IAccessControl, ERC165 {
struct RoleData {
mapping(address => bool) members;
bytes32 adminRole;
}
mapping(bytes32 => RoleData) private _roles;
bytes32 public constant DEFAULT_ADMIN_ROLE = 0x00;
/**
* @dev Modifier that checks that an account has a specific role. Reverts
* with a standardized message including the required role.
*
* The format of the revert reason is given by the following regular expression:
*
* /^AccessControl: account (0x[0-9a-f]{40}) is missing role (0x[0-9a-f]{64})$/
*
* _Available since v4.1._
*/
modifier onlyRole(bytes32 role) {
_checkRole(role, _msgSender());
_;
}
/**
* @dev See {IERC165-supportsInterface}.
*/
function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) {
return interfaceId == type(IAccessControl).interfaceId || super.supportsInterface(interfaceId);
}
/**
* @dev Returns `true` if `account` has been granted `role`.
*/
function hasRole(bytes32 role, address account) public view override returns (bool) {
return _roles[role].members[account];
}
/**
* @dev Revert with a standard message if `account` is missing `role`.
*
* The format of the revert reason is given by the following regular expression:
*
* /^AccessControl: account (0x[0-9a-f]{40}) is missing role (0x[0-9a-f]{64})$/
*/
function _checkRole(bytes32 role, address account) internal view {
if (!hasRole(role, account)) {
revert(
string(
abi.encodePacked(
"AccessControl: account ",
Strings.toHexString(uint160(account), 20),
" is missing role ",
Strings.toHexString(uint256(role), 32)
)
)
);
}
}
/**
* @dev Returns the admin role that controls `role`. See {grantRole} and
* {revokeRole}.
*
* To change a role's admin, use {_setRoleAdmin}.
*/
function getRoleAdmin(bytes32 role) public view override returns (bytes32) {
return _roles[role].adminRole;
}
/**
* @dev Grants `role` to `account`.
*
* If `account` had not been already granted `role`, emits a {RoleGranted}
* event.
*
* Requirements:
*
* - the caller must have ``role``'s admin role.
*/
function grantRole(bytes32 role, address account) public virtual override onlyRole(getRoleAdmin(role)) {
_grantRole(role, account);
}
/**
* @dev Revokes `role` from `account`.
*
* If `account` had been granted `role`, emits a {RoleRevoked} event.
*
* Requirements:
*
* - the caller must have ``role``'s admin role.
*/
function revokeRole(bytes32 role, address account) public virtual override onlyRole(getRoleAdmin(role)) {
_revokeRole(role, account);
}
/**
* @dev Revokes `role` from the calling account.
*
* Roles are often managed via {grantRole} and {revokeRole}: this function's
* purpose is to provide a mechanism for accounts to lose their privileges
* if they are compromised (such as when a trusted device is misplaced).
*
* If the calling account had been granted `role`, emits a {RoleRevoked}
* event.
*
* Requirements:
*
* - the caller must be `account`.
*/
function renounceRole(bytes32 role, address account) public virtual override {
require(account == _msgSender(), "AccessControl: can only renounce roles for self");
_revokeRole(role, account);
}
/**
* @dev Grants `role` to `account`.
*
* If `account` had not been already granted `role`, emits a {RoleGranted}
* event. Note that unlike {grantRole}, this function doesn't perform any
* checks on the calling account.
*
* [WARNING]
* ====
* This function should only be called from the constructor when setting
* up the initial roles for the system.
*
* Using this function in any other way is effectively circumventing the admin
* system imposed by {AccessControl}.
* ====
*/
function _setupRole(bytes32 role, address account) internal virtual {
_grantRole(role, account);
}
/**
* @dev Sets `adminRole` as ``role``'s admin role.
*
* Emits a {RoleAdminChanged} event.
*/
function _setRoleAdmin(bytes32 role, bytes32 adminRole) internal virtual {
bytes32 previousAdminRole = getRoleAdmin(role);
_roles[role].adminRole = adminRole;
emit RoleAdminChanged(role, previousAdminRole, adminRole);
}
function _grantRole(bytes32 role, address account) private {
if (!hasRole(role, account)) {
_roles[role].members[account] = true;
emit RoleGranted(role, account, _msgSender());
}
}
function _revokeRole(bytes32 role, address account) private {
if (hasRole(role, account)) {
_roles[role].members[account] = false;
emit RoleRevoked(role, account, _msgSender());
}
}
}
pragma solidity ^0.8.4;
// SPDX-License-Identifier: GPL-3.0-or-later
import "@openzeppelin/contracts/token/ERC20/ERC20.sol";
import "@openzeppelin/contracts/token/ERC20/IERC20.sol";
import "@openzeppelin/contracts/token/ERC20/extensions/ERC20Burnable.sol";
import "@openzeppelin/contracts/security/Pausable.sol";
import "@openzeppelin/contracts/access/Ownable.sol";
import "@openzeppelin/contracts/access/AccessControl.sol";
contract TempleERC20Token is ERC20, ERC20Burnable, Ownable, AccessControl {
bytes32 public constant CAN_MINT = keccak256("CAN_MINT");
constructor() ERC20("Temple", "TEMPLE") {
_setupRole(DEFAULT_ADMIN_ROLE, owner());
}
function mint(address to, uint256 amount) external {
require(hasRole(CAN_MINT, msg.sender), "Caller cannot mint");
_mint(to, amount);
}
function addMinter(address account) external onlyOwner {
grantRole(CAN_MINT, account);
}
function removeMinter(address account) external onlyOwner {
revokeRole(CAN_MINT, account);
}
}
pragma solidity ^0.8.4;
// SPDX-License-Identifier: GPL-3.0-or-later
import "@openzeppelin/contracts/token/ERC20/ERC20.sol";
import "@openzeppelin/contracts/token/ERC20/IERC20.sol";
import "@openzeppelin/contracts/token/ERC20/extensions/ERC20Burnable.sol";
import "@openzeppelin/contracts/security/Pausable.sol";
import "@openzeppelin/contracts/access/Ownable.sol";
import "@openzeppelin/contracts/access/AccessControl.sol";
/**
* Sandalwood rewarded as part of the Opening Ceremony quests
*/
contract SandalwoodToken is ERC20, ERC20Burnable {
constructor() ERC20("Sandalwood", "Sandalwood") {
_mint(_msgSender(), 1e12 * 1e18);
}
}
pragma solidity ^0.8.4;
// SPDX-License-Identifier: GPL-3.0-or-later
import "@openzeppelin/contracts/token/ERC20/IERC20.sol";
import "@openzeppelin/contracts/security/Pausable.sol";
import "@openzeppelin/contracts/access/Ownable.sol";
import "@openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol";
import "./TempleERC20Token.sol";
import "./ITreasuryAllocation.sol";
import "./MintAllowance.sol";
import "@openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol";
// import "hardhat/console.sol";
contract TempleTreasury is Ownable {
// Underlying TEMPLE token
TempleERC20Token private TEMPLE;
// underlying stable token we are holding and valuing treasury with
IERC20 private STABLEC;
// Minted temple allocated to various investment contracts
MintAllowance public MINT_ALLOWANCE;
// Ratio of treasury value in stablec to open supply of temple.
struct IntrinsicValueRatio {
uint256 stablec;
uint256 temple;
}
IntrinsicValueRatio public intrinsicValueRatio;
// Temple rewards harvested, and (yet) to be allocated to a pool
uint256 public harvestedRewardsTemple;
// Has treasury been seeded with STABLEC yet (essentially, has seedMint been called)
// this will bootstrap IV
bool public seeded = false;
// all active pools. A pool is anything
// that gets allocated some portion of harvest
address[] public pools;
mapping(address => uint96) public poolHarvestShare;
uint96 public totalHarvestShares;
// Current treasury STABLEC allocations
mapping(ITreasuryAllocation => uint256) public treasuryAllocationsStablec;
uint256 public totalAllocationStablec;
event RewardsHarvested(uint256 _amount);
event HarvestDistributed(address _contract, uint256 _amount);
constructor(TempleERC20Token _TEMPLE, IERC20 _STABLEC) {
TEMPLE = _TEMPLE;
STABLEC = _STABLEC;
MINT_ALLOWANCE = new MintAllowance(_TEMPLE);
}
function numPools() external view returns (uint256) {
return pools.length;
}
/**
* Seed treasury with STABLEC and Temple to bootstrap
*/
function seedMint(uint256 amountStablec, uint256 amountTemple) external onlyOwner {
require(!seeded, "Owner has already seeded treasury");
seeded = true;
// can this go in the constructor?
intrinsicValueRatio.stablec = amountStablec;
intrinsicValueRatio.temple = amountTemple;
SafeERC20.safeTransferFrom(STABLEC, msg.sender, address(this), amountStablec);
TEMPLE.mint(msg.sender, amountTemple);
}
/**
* Harvest rewards.
*
* For auditing, we harvest and allocate in two steps
*/
function harvest(uint256 distributionPercent) external onlyOwner {
require(distributionPercent <= 100, "Scaling factor interpreted as a %, needs to be between 0 (no harvest) and 100 (max harvest)");
uint256 reserveStablec = STABLEC.balanceOf(address(this)) + totalAllocationStablec;
// // Burn any excess temple, that is Any temple over and beyond harvestedRewardsTemple.
// // NOTE: If we don't do this, IV could drop...
if (TEMPLE.balanceOf(address(this)) > harvestedRewardsTemple) {
// NOTE: there isn't a Reentrancy issue as we control the TEMPLE ERC20 contract, and configure
// treasury with an address on contract creation
TEMPLE.burn(TEMPLE.balanceOf(address(this)) - harvestedRewardsTemple);
}
uint256 totalSupplyTemple = TEMPLE.totalSupply() - TEMPLE.balanceOf(address(MINT_ALLOWANCE));
uint256 impliedSupplyAtCurrentIVTemple = reserveStablec * intrinsicValueRatio.temple / intrinsicValueRatio.stablec;
require(impliedSupplyAtCurrentIVTemple >= totalSupplyTemple, "Cannot run harvest when IV drops");
uint256 newHarvestTemple = (impliedSupplyAtCurrentIVTemple - totalSupplyTemple) * distributionPercent / 100;
harvestedRewardsTemple += newHarvestTemple;
intrinsicValueRatio.stablec = reserveStablec;
intrinsicValueRatio.temple = totalSupplyTemple + newHarvestTemple;
TEMPLE.mint(address(this), newHarvestTemple);
emit RewardsHarvested(newHarvestTemple);
}
/**
* ResetIV
*
* Not expected to be used in day to day operations, as opposed to harvest which
* will be called ~ once per epoch.
*
* Only to be called if we have to post a treasury loss, and restart IV growth from
* a new baseline.
*/
function resetIV() external onlyOwner {
uint256 reserveStablec = STABLEC.balanceOf(address(this)) + totalAllocationStablec;
uint256 totalSupplyTemple = TEMPLE.totalSupply() - TEMPLE.balanceOf(address(MINT_ALLOWANCE));
intrinsicValueRatio.stablec = reserveStablec;
intrinsicValueRatio.temple = totalSupplyTemple;
}
/**
* Allocate rewards to each pool.
*/
function distributeHarvest() external onlyOwner {
// transfer rewards as per defined allocation
uint256 totalAllocated = 0;
for (uint256 i = 0; i < pools.length; i++) {
uint256 allocatedRewards = harvestedRewardsTemple * poolHarvestShare[pools[i]] / totalHarvestShares;
// integer rounding may cause the last allocation to exceed harvested
// rewards. Handle gracefully
if ((totalAllocated + allocatedRewards) > harvestedRewardsTemple) {
allocatedRewards = harvestedRewardsTemple - totalAllocated;
}
totalAllocated += allocatedRewards;
SafeERC20.safeTransfer(TEMPLE, pools[i], allocatedRewards);
emit HarvestDistributed(pools[i], allocatedRewards);
}
harvestedRewardsTemple -= totalAllocated;
}
/**
* Mint and Allocate treasury TEMPLE.
*/
function mintAndAllocateTemple(address _contract, uint256 amountTemple) external onlyOwner {
require(amountTemple > 0, "TEMPLE to mint and allocate must be > 0");
// Mint and Allocate TEMPLE via MINT_ALLOWANCE helper
TEMPLE.mint(address(this), amountTemple);
SafeERC20.safeIncreaseAllowance(TEMPLE, address(MINT_ALLOWANCE), amountTemple);
MINT_ALLOWANCE.increaseMintAllowance(_contract, amountTemple);
}
/**
* Burn minted temple associated with a specific contract
*/
function unallocateAndBurnUnusedMintedTemple(address _contract) external onlyOwner {
MINT_ALLOWANCE.burnUnusedMintAllowance(_contract);
}
/**
* Allocate treasury STABLEC.
*/
function allocateTreasuryStablec(ITreasuryAllocation _contract, uint256 amountStablec) external onlyOwner {
require(amountStablec > 0, "STABLEC to allocate must be > 0");
treasuryAllocationsStablec[_contract] += amountStablec;
totalAllocationStablec += amountStablec;
SafeERC20.safeTransfer(STABLEC, address(_contract), amountStablec);
}
/**
* Update treasury with latest mark to market for a given treasury allocation
*/
function updateMarkToMarket(ITreasuryAllocation _contract) external onlyOwner {
uint256 oldReval = treasuryAllocationsStablec[_contract];
uint256 newReval = _contract.reval();
totalAllocationStablec = totalAllocationStablec + newReval - oldReval;
treasuryAllocationsStablec[_contract] = newReval;
}
/**
* Withdraw from a contract.
*
* Expects that pre-withdrawal reval() includes the unwithdrawn allowance, and post withdrawal reval()
* drops by exactly this amount.
*/
function withdraw(ITreasuryAllocation _contract) external onlyOwner {
uint256 preWithdrawlReval = _contract.reval();
uint256 pendingWithdrawal = STABLEC.allowance(address(_contract), address(this));
// NOTE: Reentrancy considered and it's safe STABLEC is a well known unchanging contract
SafeERC20.safeTransferFrom(STABLEC, address(_contract), address(this), pendingWithdrawal);
uint256 postWithdrawlReval = _contract.reval();
totalAllocationStablec = totalAllocationStablec - pendingWithdrawal;
treasuryAllocationsStablec[_contract] -= pendingWithdrawal;
require(postWithdrawlReval + pendingWithdrawal == preWithdrawlReval);
}
/**
* Withdraw from a contract which has some treasury allocation
*
* Ejects a contract out of treasury, pulling in any allowance of STABLEC
* We only expect to use this if (for whatever reason). The booking in
* The given TreasuryAllocation results in withdraw not working.
*
* Precondition, contract given has allocated all of it's Stablec assets
* to be transfered into treasury as an allowance.
*
* This will only ever reduce treasury IV.
*/
function ejectTreasuryAllocation(ITreasuryAllocation _contract) external onlyOwner {
uint256 pendingWithdrawal = STABLEC.allowance(address(_contract), address(this));
totalAllocationStablec -= treasuryAllocationsStablec[_contract];
treasuryAllocationsStablec[_contract] = 0;
SafeERC20.safeTransferFrom(STABLEC, address(_contract), address(this), pendingWithdrawal);
}
/**
* Add or update a pool, and transfer in treasury assets
*/
function upsertPool(address _contract, uint96 _poolHarvestShare) external onlyOwner {
require(_poolHarvestShare > 0, "Harvest share must be > 0");
totalHarvestShares = totalHarvestShares + _poolHarvestShare - poolHarvestShare[_contract];
// first time, add contract to array as well
if (poolHarvestShare[_contract] == 0) {
pools.push(_contract);
}
poolHarvestShare[_contract] = _poolHarvestShare;
}
/**
* Remove a given investment pool.
*/
function removePool(uint256 idx, address _contract) external onlyOwner {
require(idx < pools.length, "No pool at the specified index");
require(pools[idx] == _contract, "Pool at index and passed in address don't match");
pools[idx] = pools[pools.length-1];
pools.pop();
totalHarvestShares -= poolHarvestShare[_contract];
delete poolHarvestShare[_contract];
}
}
pragma solidity ^0.8.4; // SPDX-License-Identifier: GPL-3.0-or-later
import "./TempleTreasury.sol";
import "@openzeppelin/contracts/access/AccessControl.sol";
/**
* Proxy all treasury management methods
*
* Intention is to be deployed as the new treasury owner, a workaround required
* to make harvest publically callable.
*/
contract TreasuryManagementProxy {
TempleTreasury public treasury;
bool public harvestEnabled = true;
address owner;
uint256 public harvestDistributionPercentage = 80;
constructor(address _owner, address _treasury) {
owner = _owner;
treasury = TempleTreasury(_treasury);
}
modifier onlyOwner() {
require(owner == msg.sender, "caller is not the owner");
_;
}
function harvest() external {
if (harvestEnabled) {
treasury.harvest(harvestDistributionPercentage);
}
}
function setHarvestDistributionPercentage(uint256 _harvestDistributionPercentage) external onlyOwner {
harvestDistributionPercentage = _harvestDistributionPercentage;
}
function toggleHarvest() external onlyOwner {
harvestEnabled = !harvestEnabled;
}
function resetIV() external onlyOwner {
treasury.resetIV();
}
function distributeHarvest() external onlyOwner {
treasury.distributeHarvest();
}
function mintAndAllocateTemple(address _contract, uint256 amountTemple) external onlyOwner {
treasury.mintAndAllocateTemple(_contract, amountTemple);
}
function unallocateAndBurnUnusedMintedTemple(address _contract) external onlyOwner {
treasury.unallocateAndBurnUnusedMintedTemple(_contract);
}
function allocateTreasuryStablec(ITreasuryAllocation _contract, uint256 amountStablec) external onlyOwner {
treasury.allocateTreasuryStablec(_contract, amountStablec);
}
function updateMarkToMarket(ITreasuryAllocation _contract) external onlyOwner {
treasury.updateMarkToMarket(_contract);
}
function withdraw(ITreasuryAllocation _contract) external onlyOwner {
treasury.withdraw(_contract);
}
function ejectTreasuryAllocation(ITreasuryAllocation _contract) external onlyOwner {
treasury.ejectTreasuryAllocation(_contract);
}
function upsertPool(address _contract, uint96 _poolHarvestShare) external onlyOwner {
treasury.upsertPool(_contract, _poolHarvestShare);
}
function removePool(uint256 idx, address _contract) external onlyOwner {
treasury.removePool(idx, _contract);
}
// If we want to transfer ownership way from proxy
function transferOwnership(address newOwner) external onlyOwner {
treasury.transferOwnership(newOwner);
}
}
pragma solidity ^0.8.4;
// SPDX-License-Identifier: GPL-3.0-or-later
import "@openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol";
import "@openzeppelin/contracts/access/Ownable.sol";
import "./ABDKMath64x64.sol";
import "./TempleERC20Token.sol";
import "./OGTemple.sol";
import "./ExitQueue.sol";
// import "hardhat/console.sol";
/**
* Mechancics of how a user can stake temple.
*/
contract TempleStaking is Ownable {
using ABDKMath64x64 for int128;
TempleERC20Token immutable public TEMPLE; // The token being staked, for which TEMPLE rewards are generated
OGTemple immutable public OG_TEMPLE; // Token used to redeem staked TEMPLE
ExitQueue public EXIT_QUEUE; // unstake exit queue
// epoch percentage yield, as an ABDKMath64x64
int128 public epy;
// epoch size, in seconds
uint256 public epochSizeSeconds;
// The starting timestamp. from where staking starts
uint256 public startTimestamp;
// epy compounded over every epoch since the contract creation up
// until lastUpdatedEpoch. Represented as an ABDKMath64x64
int128 public accumulationFactor;
// the epoch up to which we have calculated accumulationFactor.
uint256 public lastUpdatedEpoch;
event StakeCompleted(address _staker, uint256 _amount, uint256 _lockedUntil);
event AccumulationFactorUpdated(uint256 _epochsProcessed, uint256 _currentEpoch, uint256 _accumulationFactor);
event UnstakeCompleted(address _staker, uint256 _amount);
constructor(
TempleERC20Token _TEMPLE,
ExitQueue _EXIT_QUEUE,
uint256 _epochSizeSeconds,
uint256 _startTimestamp) {
require(_startTimestamp < block.timestamp, "Start timestamp must be in the past");
require(_startTimestamp > (block.timestamp - (24 * 2 * 60 * 60)), "Start timestamp can't be more than 2 days in the past");
TEMPLE = _TEMPLE;
EXIT_QUEUE = _EXIT_QUEUE;
// Each version of the staking contract needs it's own instance of OGTemple users can use to
// claim back rewards
OG_TEMPLE = new OGTemple();
epochSizeSeconds = _epochSizeSeconds;
startTimestamp = _startTimestamp;
epy = ABDKMath64x64.fromUInt(1);
accumulationFactor = ABDKMath64x64.fromUInt(1);
}
/** Sets epoch percentage yield */
function setExitQueue(ExitQueue _EXIT_QUEUE) external onlyOwner {
EXIT_QUEUE = _EXIT_QUEUE;
}
/** Sets epoch percentage yield */
function setEpy(uint256 _numerator, uint256 _denominator) external onlyOwner {
_updateAccumulationFactor();
epy = ABDKMath64x64.fromUInt(1).add(ABDKMath64x64.divu(_numerator, _denominator));
}
/** Get EPY as uint, scaled up the given factor (for reporting) */
function getEpy(uint256 _scale) external view returns (uint256) {
return epy.sub(ABDKMath64x64.fromUInt(1)).mul(ABDKMath64x64.fromUInt(_scale)).toUInt();
}
function currentEpoch() public view returns (uint256) {
return (block.timestamp - startTimestamp) / epochSizeSeconds;
}
/** Return current accumulation factor, scaled up to account for fractional component */
function getAccumulationFactor(uint256 _scale) external view returns(uint256) {
return _accumulationFactorAt(currentEpoch()).mul(ABDKMath64x64.fromUInt(_scale)).toUInt();
}
/** Calculate the updated accumulation factor, based on the current epoch */
function _accumulationFactorAt(uint256 epoch) private view returns(int128) {
uint256 _nUnupdatedEpochs = epoch - lastUpdatedEpoch;
return accumulationFactor.mul(epy.pow(_nUnupdatedEpochs));
}
/** Balance in TEMPLE for a given amount of OG_TEMPLE */
function balance(uint256 amountOgTemple) public view returns(uint256) {
return _overflowSafeMul1e18(
ABDKMath64x64.divu(amountOgTemple, 1e18).mul(_accumulationFactorAt(currentEpoch()))
);
}
/** updates rewards in pool */
function _updateAccumulationFactor() internal {
uint256 _currentEpoch = currentEpoch();
// still in previous epoch, no action.
// NOTE: should be a pre-condition that _currentEpoch >= lastUpdatedEpoch
// It's possible to end up in this state if we shorten epoch size.
// As such, it's not baked as a precondition
if (_currentEpoch <= lastUpdatedEpoch) {
return;
}
accumulationFactor = _accumulationFactorAt(_currentEpoch);
lastUpdatedEpoch = _currentEpoch;
uint256 _nUnupdatedEpochs = _currentEpoch - lastUpdatedEpoch;
emit AccumulationFactorUpdated(_nUnupdatedEpochs, _currentEpoch, accumulationFactor.mul(10000).toUInt());
}
/** Stake on behalf of a given address. Used by other contracts (like Presale) */
function stakeFor(address _staker, uint256 _amountTemple) public returns(uint256 amountOgTemple) {
require(_amountTemple > 0, "Cannot stake 0 tokens");
_updateAccumulationFactor();
// net past value/genesis value/OG Value for the temple you are putting in.
amountOgTemple = _overflowSafeMul1e18(ABDKMath64x64.divu(_amountTemple, 1e18).div(accumulationFactor));
SafeERC20.safeTransferFrom(TEMPLE, msg.sender, address(this), _amountTemple);
OG_TEMPLE.mint(_staker, amountOgTemple);
emit StakeCompleted(_staker, _amountTemple, 0);
return amountOgTemple;
}
/** Stake temple */
function stake(uint256 _amountTemple) external returns(uint256 amountOgTemple) {
return stakeFor(msg.sender, _amountTemple);
}
/** Unstake temple */
function unstake(uint256 _amountOgTemple) external {
require(OG_TEMPLE.allowance(msg.sender, address(this)) >= _amountOgTemple, 'Insufficient OGTemple allowance. Cannot unstake');
_updateAccumulationFactor();
uint256 unstakeBalanceTemple = balance(_amountOgTemple);
OG_TEMPLE.burnFrom(msg.sender, _amountOgTemple);
SafeERC20.safeIncreaseAllowance(TEMPLE, address(EXIT_QUEUE), unstakeBalanceTemple);
EXIT_QUEUE.join(msg.sender, unstakeBalanceTemple);
emit UnstakeCompleted(msg.sender, _amountOgTemple);
}
function _overflowSafeMul1e18(int128 amountFixedPoint) internal pure returns (uint256) {
uint256 integralDigits = amountFixedPoint.toUInt();
uint256 fractionalDigits = amountFixedPoint.sub(ABDKMath64x64.fromUInt(integralDigits)).mul(ABDKMath64x64.fromUInt(1e18)).toUInt();
return (integralDigits * 1e18) + fractionalDigits;
}
}
pragma solidity ^0.8.4;
// SPDX-License-Identifier: GPL-3.0-or-later
import "@openzeppelin/contracts/token/ERC20/IERC20.sol";
import "@openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol";
import "@openzeppelin/contracts/access/Ownable.sol";
import "./TempleERC20Token.sol";
import "./TempleTreasury.sol";
import "./TempleStaking.sol";
/**
* Who has what allocation in the presale period
*/
contract PresaleAllocation is Ownable {
struct Allocation {
uint256 amount;
uint256 epoch;
}
// maximum stablec each address can buy temple
mapping(address => Allocation) public allocationOf;
function setAllocation(address staker, uint256 amount, uint256 epoch) external onlyOwner {
allocationOf[staker].epoch = epoch;
allocationOf[staker].amount = amount;
}
}
pragma solidity ^0.8.4;
// SPDX-License-Identifier: GPL-3.0-or-later
import "@openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol";
import "./OGTemple.sol";
/**
* Bookkeeping for OGTemple that's locked
*/
contract LockedOGTemple {
struct LockedEntry {
// How many tokens are locked
uint256 BalanceOGTemple;
// WHen can the user unlock these tokens
uint256 LockedUntilTimestamp;
}
// All temple locked for any given user
mapping(address => LockedEntry[]) public locked;
OGTemple public OG_TEMPLE; // The token being staked, for which TEMPLE rewards are generated
event OGTempleLocked(address _staker, uint256 _amount, uint256 _lockedUntil);
event OGTempleWithdraw(address _staker, uint256 _amount);
constructor(OGTemple _OG_TEMPLE) {
OG_TEMPLE = _OG_TEMPLE;
}
function numLocks(address _staker) external view returns(uint256) {
return locked[_staker].length;
}
/** lock up OG */
function lockFor(address _staker, uint256 _amountOGTemple, uint256 _lockedUntilTimestamp) public {
LockedEntry memory lockEntry = LockedEntry({BalanceOGTemple: _amountOGTemple, LockedUntilTimestamp: _lockedUntilTimestamp});
locked[_staker].push(lockEntry);
SafeERC20.safeTransferFrom(OG_TEMPLE, msg.sender, address(this), _amountOGTemple);
emit OGTempleLocked(_staker, _amountOGTemple, _lockedUntilTimestamp);
}
function lock(uint256 _amountOGTemple, uint256 _lockedUntilTimestamp) external {
lockFor(msg.sender, _amountOGTemple, _lockedUntilTimestamp);
}
/** Withdraw a specific locked entry */
function withdrawFor(address _staker, uint256 _idx) public {
LockedEntry[] storage lockedEntries = locked[_staker];
require(_idx < lockedEntries.length, "No lock entry at the specified index");
require(lockedEntries[_idx].LockedUntilTimestamp < block.timestamp, "Specified entry is still locked");
LockedEntry memory entry = lockedEntries[_idx];
lockedEntries[_idx] = lockedEntries[lockedEntries.length-1];
lockedEntries.pop();
SafeERC20.safeTransfer(OG_TEMPLE, _staker, entry.BalanceOGTemple);
emit OGTempleWithdraw(_staker, entry.BalanceOGTemple);
}
function withdraw(uint256 _idx) external {
withdrawFor(msg.sender, _idx);
}
}
// 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: MIT
pragma solidity ^0.8.0;
/**
* @dev External interface of AccessControl declared to support ERC165 detection.
*/
interface IAccessControl {
/**
* @dev Emitted when `newAdminRole` is set as ``role``'s admin role, replacing `previousAdminRole`
*
* `DEFAULT_ADMIN_ROLE` is the starting admin for all roles, despite
* {RoleAdminChanged} not being emitted signaling this.
*
* _Available since v3.1._
*/
event RoleAdminChanged(bytes32 indexed role, bytes32 indexed previousAdminRole, bytes32 indexed newAdminRole);
/**
* @dev Emitted when `account` is granted `role`.
*
* `sender` is the account that originated the contract call, an admin role
* bearer except when using {AccessControl-_setupRole}.
*/
event RoleGranted(bytes32 indexed role, address indexed account, address indexed sender);
/**
* @dev Emitted when `account` is revoked `role`.
*
* `sender` is the account that originated the contract call:
* - if using `revokeRole`, it is the admin role bearer
* - if using `renounceRole`, it is the role bearer (i.e. `account`)
*/
event RoleRevoked(bytes32 indexed role, address indexed account, address indexed sender);
/**
* @dev Returns `true` if `account` has been granted `role`.
*/
function hasRole(bytes32 role, address account) external view returns (bool);
/**
* @dev Returns the admin role that controls `role`. See {grantRole} and
* {revokeRole}.
*
* To change a role's admin, use {AccessControl-_setRoleAdmin}.
*/
function getRoleAdmin(bytes32 role) external view returns (bytes32);
/**
* @dev Grants `role` to `account`.
*
* If `account` had not been already granted `role`, emits a {RoleGranted}
* event.
*
* Requirements:
*
* - the caller must have ``role``'s admin role.
*/
function grantRole(bytes32 role, address account) external;
/**
* @dev Revokes `role` from `account`.
*
* If `account` had been granted `role`, emits a {RoleRevoked} event.
*
* Requirements:
*
* - the caller must have ``role``'s admin role.
*/
function revokeRole(bytes32 role, address account) external;
/**
* @dev Revokes `role` from the calling account.
*
* Roles are often managed via {grantRole} and {revokeRole}: this function's
* purpose is to provide a mechanism for accounts to lose their privileges
* if they are compromised (such as when a trusted device is misplaced).
*
* If the calling account had been granted `role`, emits a {RoleRevoked}
* event.
*
* Requirements:
*
* - the caller must be `account`.
*/
function renounceRole(bytes32 role, address account) external;
}
// SPDX-License-Identifier: MIT
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
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 "./IERC20.sol";
import "./extensions/IERC20Metadata.sol";
import "../../utils/Context.sol";
/**
* @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 Contracts guidelines: functions revert
* instead 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, IERC20Metadata {
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 default value of {decimals} is 18. To select a different value for
* {decimals} you should overload it.
*
* All two of these values are immutable: they can only be set once during
* construction.
*/
constructor(string memory name_, string memory symbol_) {
_name = name_;
_symbol = symbol_;
}
/**
* @dev Returns the name of the token.
*/
function name() public view virtual override returns (string memory) {
return _name;
}
/**
* @dev Returns the symbol of the token, usually a shorter version of the
* name.
*/
function symbol() public view virtual override 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
* overridden;
*
* 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 override 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(_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);
uint256 currentAllowance = _allowances[sender][_msgSender()];
require(currentAllowance >= amount, "ERC20: transfer amount exceeds allowance");
unchecked {
_approve(sender, _msgSender(), 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(_msgSender(), spender, _allowances[_msgSender()][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[_msgSender()][spender];
require(currentAllowance >= subtractedValue, "ERC20: decreased allowance below zero");
unchecked {
_approve(_msgSender(), spender, currentAllowance - subtractedValue);
}
return true;
}
/**
* @dev 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:
*
* - `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");
unchecked {
_balances[sender] = senderBalance - amount;
}
_balances[recipient] += amount;
emit Transfer(sender, recipient, amount);
_afterTokenTransfer(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:
*
* - `account` 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);
_afterTokenTransfer(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");
unchecked {
_balances[account] = accountBalance - amount;
}
_totalSupply -= amount;
emit Transfer(account, address(0), amount);
_afterTokenTransfer(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 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 {}
/**
* @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, `amount` of ``from``'s tokens
* has been transferred to `to`.
* - when `from` is zero, `amount` tokens have been minted for `to`.
* - when `to` is zero, `amount` of ``from``'s tokens have been 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 _afterTokenTransfer(
address from,
address to,
uint256 amount
) internal virtual {}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import "../ERC20.sol";
import "../../../utils/Context.sol";
/**
* @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 {
/**
* @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 currentAllowance = allowance(account, _msgSender());
require(currentAllowance >= amount, "ERC20: burn amount exceeds allowance");
unchecked {
_approve(account, _msgSender(), currentAllowance - amount);
}
_burn(account, amount);
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import "../utils/Context.sol";
/**
* @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() {
_paused = false;
}
/**
* @dev Returns true if the contract is paused, and false otherwise.
*/
function paused() public view virtual 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());
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import "../IERC20.sol";
/**
* @dev Interface for the optional metadata functions from the ERC20 standard.
*
* _Available since v4.1._
*/
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);
}
pragma solidity ^0.8.4;
// SPDX-License-Identifier: GPL-3.0-or-later
/**
* Contract which has treasury allocated from Stablec
*
* Reports back it's mark to market (so DAO can rebalance IV accordingly, from time to time)
*/
interface ITreasuryAllocation {
/**
* mark to market of treasury investment, denominated in Treasury Stablec
*/
function reval() external view returns (uint256);
}
pragma solidity ^0.8.4;
// SPDX-License-Identifier: GPL-3.0-or-later
import "@openzeppelin/contracts/token/ERC20/IERC20.sol";
import "@openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol";
import "@openzeppelin/contracts/access/Ownable.sol";
import "@openzeppelin/contracts/token/ERC20/extensions/ERC20Burnable.sol";
import "./TempleERC20Token.sol";
/**
* Newly minted temple allocated to various temple strategies
*
* Any temple held by this contract is assumed to be unused,
* and hence doesn't effect the intrinsinc value calculation.
*
* It's only considered in circulation once a pool pulls
* it's allowance.
*/
contract MintAllowance is Ownable {
// Temple contract address
TempleERC20Token TEMPLE;
constructor(TempleERC20Token _TEMPLE) {
TEMPLE = _TEMPLE;
}
/**
* Increase mint allowance for the given pool
*
* Atomically pulls amount from treasury before increasing allownance
* as an extra check and balance
*/
function increaseMintAllowance(address _pool, uint256 _amount) external onlyOwner {
SafeERC20.safeTransferFrom(TEMPLE, msg.sender, address(this), _amount);
SafeERC20.safeIncreaseAllowance(TEMPLE, _pool, _amount);
}
/**
* Burn any unused mint allowance for a given pool
*/
function burnUnusedMintAllowance(address _pool) external onlyOwner {
uint256 unusedMintAllowance = TEMPLE.allowance(address(this), _pool);
SafeERC20.safeDecreaseAllowance(TEMPLE, _pool, unusedMintAllowance);
TEMPLE.burn(unusedMintAllowance);
}
}
// SPDX-License-Identifier: BSD-4-Clause
/*
* ABDK Math 64.64 Smart Contract Library. Copyright © 2019 by ABDK Consulting.
* Author: Mikhail Vladimirov <[email protected]>
*/
pragma solidity ^0.8.4;
/**
* Smart contract library of mathematical functions operating with signed
* 64.64-bit fixed point numbers. Signed 64.64-bit fixed point number is
* basically a simple fraction whose numerator is signed 128-bit integer and
* denominator is 2^64. As long as denominator is always the same, there is no
* need to store it, thus in Solidity signed 64.64-bit fixed point numbers are
* represented by int128 type holding only the numerator.
*/
library ABDKMath64x64 {
/*
* Minimum value signed 64.64-bit fixed point number may have.
*/
int128 private constant MIN_64x64 = -0x80000000000000000000000000000000;
/*
* 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) {
unchecked {
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) {
unchecked {
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) {
unchecked {
require (x <= 0x7FFFFFFFFFFFFFFF);
return int128 (int256 (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) {
unchecked {
require (x >= 0);
return uint64 (uint128 (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) {
unchecked {
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) {
unchecked {
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) {
unchecked {
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) {
unchecked {
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) {
unchecked {
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) {
unchecked {
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) {
unchecked {
if (y == 0) return 0;
require (x >= 0);
uint256 lo = (uint256 (int256 (x)) * (y & 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF)) >> 64;
uint256 hi = uint256 (int256 (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) {
unchecked {
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) {
unchecked {
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) {
unchecked {
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) {
unchecked {
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) {
unchecked {
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) {
unchecked {
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) {
unchecked {
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) {
unchecked {
int256 m = int256 (x) * int256 (y);
require (m >= 0);
require (m <
0x4000000000000000000000000000000000000000000000000000000000000000);
return int128 (sqrtu (uint256 (m)));
}
}
/**
* 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) {
unchecked {
bool negative = x < 0 && y & 1 == 1;
uint256 absX = uint128 (x < 0 ? -x : x);
uint256 absResult;
absResult = 0x100000000000000000000000000000000;
if (absX <= 0x10000000000000000) {
absX <<= 63;
while (y != 0) {
if (y & 0x1 != 0) {
absResult = absResult * absX >> 127;
}
absX = absX * absX >> 127;
if (y & 0x2 != 0) {
absResult = absResult * absX >> 127;
}
absX = absX * absX >> 127;
if (y & 0x4 != 0) {
absResult = absResult * absX >> 127;
}
absX = absX * absX >> 127;
if (y & 0x8 != 0) {
absResult = absResult * absX >> 127;
}
absX = absX * absX >> 127;
y >>= 4;
}
absResult >>= 64;
} else {
uint256 absXShift = 63;
if (absX < 0x1000000000000000000000000) { absX <<= 32; absXShift -= 32; }
if (absX < 0x10000000000000000000000000000) { absX <<= 16; absXShift -= 16; }
if (absX < 0x1000000000000000000000000000000) { absX <<= 8; absXShift -= 8; }
if (absX < 0x10000000000000000000000000000000) { absX <<= 4; absXShift -= 4; }
if (absX < 0x40000000000000000000000000000000) { absX <<= 2; absXShift -= 2; }
if (absX < 0x80000000000000000000000000000000) { absX <<= 1; absXShift -= 1; }
uint256 resultShift = 0;
while (y != 0) {
require (absXShift < 64);
if (y & 0x1 != 0) {
absResult = absResult * absX >> 127;
resultShift += absXShift;
if (absResult > 0x100000000000000000000000000000000) {
absResult >>= 1;
resultShift += 1;
}
}
absX = absX * absX >> 127;
absXShift <<= 1;
if (absX >= 0x100000000000000000000000000000000) {
absX >>= 1;
absXShift += 1;
}
y >>= 1;
}
require (resultShift < 64);
absResult >>= 64 - resultShift;
}
int256 result = negative ? -int256 (absResult) : int256 (absResult);
require (result >= MIN_64x64 && result <= MAX_64x64);
return int128 (result);
}
}
/**
* 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) {
unchecked {
require (x >= 0);
return int128 (sqrtu (uint256 (int256 (x)) << 64));
}
}
/**
* 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) {
unchecked {
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 (int256 (x)) << uint256 (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) {
unchecked {
require (x > 0);
return int128 (int256 (
uint256 (int256 (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) {
unchecked {
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 >>= uint256 (int256 (63 - (x >> 64)));
require (result <= uint256 (int256 (MAX_64x64)));
return int128 (int256 (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) {
unchecked {
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) {
unchecked {
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 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) private pure returns (uint128) {
unchecked {
if (x == 0) return 0;
else {
uint256 xx = x;
uint256 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
uint256 r1 = x / r;
return uint128 (r < r1 ? r : r1);
}
}
}
}
pragma solidity ^0.8.4;
// SPDX-License-Identifier: GPL-3.0-or-later
import "@openzeppelin/contracts/token/ERC20/ERC20.sol";
import "@openzeppelin/contracts/token/ERC20/IERC20.sol";
import "@openzeppelin/contracts/token/ERC20/extensions/ERC20Burnable.sol";
import "@openzeppelin/contracts/security/Pausable.sol";
import "@openzeppelin/contracts/access/Ownable.sol";
import "@openzeppelin/contracts/access/AccessControl.sol";
/**
* Created and owned by the staking contract.
*
* It mints and burns OGTemple as users stake/unstake
*/
contract OGTemple is ERC20, ERC20Burnable, Ownable {
constructor() ERC20("OGTemple", "OG_TEMPLE") {}
function mint(address to, uint256 amount) external onlyOwner {
_mint(to, amount);
}
}
pragma solidity ^0.8.4;
// SPDX-License-Identifier: GPL-3.0-or-later
import "@openzeppelin/contracts/token/ERC20/IERC20.sol";
import "@openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol";
import "@openzeppelin/contracts/access/Ownable.sol";
// import "hardhat/console.sol";
/**
* How all exit of TEMPLE rewards are managed.
*/
contract ExitQueue is Ownable {
struct User {
// Total currently in queue
uint256 Amount;
// First epoch for which the user is in the unstake queue
uint256 FirstExitEpoch;
// Last epoch for which the user has a pending unstake
uint256 LastExitEpoch;
// All epochs where the user has an exit allocation
mapping(uint256 => uint256) Exits;
}
// total queued to be exited in a given epoch
mapping(uint256 => uint256) public totalPerEpoch;
// The first unwithdrawn epoch for the user
mapping(address => User) public userData;
IERC20 public TEMPLE; // TEMPLE
// Limit of how much temple can exit per epoch
uint256 public maxPerEpoch;
// Limit of how much temple can exit per address per epoch
uint256 public maxPerAddress;
// epoch size, in blocks
uint256 public epochSize;
// the block we use to work out what epoch we are in
uint256 public firstBlock;
// The next free block on which a user can commence their unstake
uint256 public nextUnallocatedEpoch;
event JoinQueue(address exiter, uint256 amount);
event Withdrawal(address exiter, uint256 amount);
constructor(
address _TEMPLE,
uint256 _maxPerEpoch,
uint256 _maxPerAddress,
uint256 _epochSize) {
TEMPLE = IERC20(_TEMPLE);
maxPerEpoch = _maxPerEpoch;
maxPerAddress = _maxPerAddress;
epochSize = _epochSize;
firstBlock = block.number;
nextUnallocatedEpoch = 0;
}
function setMaxPerEpoch(uint256 _maxPerEpoch) external onlyOwner {
maxPerEpoch = _maxPerEpoch;
}
function setMaxPerAddress(uint256 _maxPerAddress) external onlyOwner {
maxPerAddress = _maxPerAddress;
}
function setEpochSize(uint256 _epochSize) external onlyOwner {
epochSize = _epochSize;
}
function setStartingBlock(uint256 _firstBlock) external onlyOwner {
require(_firstBlock < firstBlock, "Can only move start block back, not forward");
firstBlock = _firstBlock;
}
function currentEpoch() public view returns (uint256) {
return (block.number - firstBlock) / epochSize;
}
function currentEpochAllocation(address _exiter, uint256 _epoch) external view returns (uint256) {
return userData[_exiter].Exits[_epoch];
}
function join(address _exiter, uint256 _amount) external {
require(_amount > 0, "Amount must be > 0");
if (nextUnallocatedEpoch < currentEpoch()) {
nextUnallocatedEpoch = currentEpoch();
}
User storage user = userData[_exiter];
uint256 unallocatedAmount = _amount;
uint256 _nextUnallocatedEpoch = nextUnallocatedEpoch;
uint256 nextAvailableEpochForUser = _nextUnallocatedEpoch;
if (user.LastExitEpoch > nextAvailableEpochForUser) {
nextAvailableEpochForUser = user.LastExitEpoch;
}
while (unallocatedAmount > 0) {
// work out allocation for the next available epoch
uint256 allocationForEpoch = unallocatedAmount;
if (user.Exits[nextAvailableEpochForUser] + allocationForEpoch > maxPerAddress) {
allocationForEpoch = maxPerAddress - user.Exits[nextAvailableEpochForUser];
}
if (totalPerEpoch[nextAvailableEpochForUser] + allocationForEpoch > maxPerEpoch) {
allocationForEpoch = maxPerEpoch - totalPerEpoch[nextAvailableEpochForUser];
}
// Bookkeeping
if (allocationForEpoch > 0) {
if (user.Amount == 0) {
user.FirstExitEpoch = nextAvailableEpochForUser;
}
user.Amount += allocationForEpoch;
user.Exits[nextAvailableEpochForUser] += allocationForEpoch;
totalPerEpoch[nextAvailableEpochForUser] += allocationForEpoch;
user.LastExitEpoch = nextAvailableEpochForUser;
if (totalPerEpoch[nextAvailableEpochForUser] >= maxPerEpoch) {
_nextUnallocatedEpoch = nextAvailableEpochForUser;
}
unallocatedAmount -= allocationForEpoch;
}
nextAvailableEpochForUser += 1;
}
// update outside of main loop, so we spend gas once
nextUnallocatedEpoch = _nextUnallocatedEpoch;
SafeERC20.safeTransferFrom(TEMPLE, msg.sender, address(this), _amount);
emit JoinQueue(_exiter, _amount);
}
/**
* Withdraw processed allowance from a specific epoch
*/
function withdraw(uint256 epoch) external {
require(epoch < currentEpoch(), "Can only withdraw from past epochs");
User storage user = userData[msg.sender];
uint256 amount = user.Exits[epoch];
delete user.Exits[epoch];
totalPerEpoch[epoch] -= amount; // TODO: WHen this goes to 0, is it the same as the data being removed?
user.Amount -= amount;
// Once all allocations on queue have been claimed, reset user state
if (user.Amount == 0) {
// NOTE: triggers ExitQueue.withdraw(uint256) (contracts/ExitQueue.sol #150-167) deletes ExitQueue.User (contracts/ExitQueue.sol#15-27) which contains a mapping
// This is okay as if Amount is 0, we'd expect user.Exits to be empty as well
// TODO: Confirm this via tests
delete userData[msg.sender];
}
SafeERC20.safeTransfer(TEMPLE, msg.sender, amount);
emit Withdrawal(msg.sender, amount);
}
} | The token being staked, for which TEMPLE rewards are generated
| TempleERC20Token immutable public TEMPLE; | 1,660,704 | [
1,
1986,
1147,
3832,
384,
9477,
16,
364,
1492,
24401,
900,
283,
6397,
854,
4374,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
565,
3955,
1802,
654,
39,
3462,
1345,
11732,
1071,
24401,
900,
31,
225,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
] |
pragma solidity ^0.4.4;
contract Token {
/// @return total amount of tokens
function totalSupply() constant returns (uint256 supply) {}
/// @param _owner The address from which the balance will be retrieved
/// @return The balance
function balanceOf(address _owner) constant returns (uint256 balance) {}
/// @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) returns (bool success) {}
/// @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) returns (bool success) {}
/// @notice `msg.sender` approves `_addr` to spend `_value` tokens
/// @param _spender The address of the account able to transfer the tokens
/// @param _value The amount of wei to be approved for transfer
/// @return Whether the approval was successful or not
function approve(address _spender, uint256 _value) returns (bool success) {}
/// @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) constant returns (uint256 remaining) {}
event Transfer(address indexed _from, address indexed _to, uint256 _value);
event Approval(address indexed _owner, address indexed _spender, uint256 _value);
}
contract StandardToken is Token {
function transfer(address _to, uint256 _value) returns (bool success) {
//Default assumes totalSupply can't be over max (2^256 - 1).
//If your token leaves out totalSupply and can issue more tokens as time goes on, you need to check if it doesn't wrap.
//Replace the if with this one instead.
//if (balances[msg.sender] >= _value && balances[_to] + _value > balances[_to]) {
if (balances[msg.sender] >= _value && _value > 0) {
balances[msg.sender] -= _value;
balances[_to] += _value;
Transfer(msg.sender, _to, _value);
return true;
} else { return false; }
}
function transferFrom(address _from, address _to, uint256 _value) returns (bool success) {
//same as above. Replace this line with the following if you want to protect against wrapping uints.
//if (balances[_from] >= _value && allowed[_from][msg.sender] >= _value && balances[_to] + _value > balances[_to]) {
if (balances[_from] >= _value && allowed[_from][msg.sender] >= _value && _value > 0) {
balances[_to] += _value;
balances[_from] -= _value;
allowed[_from][msg.sender] -= _value;
Transfer(_from, _to, _value);
return true;
} else { return false; }
}
function balanceOf(address _owner) constant returns (uint256 balance) {
return balances[_owner];
}
function approve(address _spender, uint256 _value) returns (bool success) {
allowed[msg.sender][_spender] = _value;
Approval(msg.sender, _spender, _value);
return true;
}
function allowance(address _owner, address _spender) constant returns (uint256 remaining) {
return allowed[_owner][_spender];
}
mapping (address => uint256) balances;
mapping (address => mapping (address => uint256)) allowed;
uint256 public totalSupply;
}
//name this contract whatever you'd like
contract BMoreToken is StandardToken {
function () {
//if ether is sent to this address, send it back.
revert();
}
/* Public variables of the token */
/*
NOTE:
The following variables are OPTIONAL vanities. One does not have to include them.
They allow one to customise the token contract & in no way influences the core functionality.
Some wallets/interfaces might not even bother to look at this information.
*/
string public name; //fancy name: eg Simon Bucks
uint8 public decimals; //How many decimals to show. ie. There could 1000 base units with 3 decimals. Meaning 0.980 SBX = 980 base units. It's like comparing 1 wei to 1 ether.
string public symbol; //An identifier: eg SBX
string public version = 'H1.0'; //human 0.1 standard. Just an arbitrary versioning scheme.
//
// CHANGE THESE VALUES FOR YOUR TOKEN
//
//make sure this function name matches the contract name above. So if you're token is called TutorialToken, make sure the //contract name above is also TutorialToken instead of ERC20Token
constructor(
) {
balances[msg.sender] = 394796000000000; // Give the creator all initial tokens (100000 for example)
totalSupply = 394796000000000; // Update total supply (100000 for example)
name = "BMoreToken"; // Set the name for display purposes
decimals = 8; // Amount of decimals for display purposes
symbol = "BALT"; // Set the symbol for display purposes
}
/* Approves and then calls the receiving contract */
function approveAndCall(address _spender, uint256 _value, bytes _extraData) returns (bool success) {
allowed[msg.sender][_spender] = _value;
Approval(msg.sender, _spender, _value);
//call the receiveApproval function on the contract you want to be notified. This crafts the function signature manually so one doesn't have to include a contract in here just for this.
//receiveApproval(address _from, uint256 _value, address _tokenContract, bytes _extraData)
//it is assumed that when does this that the call *should* succeed, otherwise one would use vanilla approve instead.
if(!_spender.call(bytes4(bytes32(sha3("receiveApproval(address,uint256,address,bytes)"))), msg.sender, _value, this, _extraData)) { revert(); }
return true;
}
} | Set the symbol for display purposes
| symbol = "BALT"; | 5,841,935 | [
1,
694,
326,
3273,
364,
2562,
13694,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
3639,
3273,
273,
315,
38,
18255,
14432,
27573,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
] |
./full_match/4/0x84C29C3FAfD1B779794a8A8ca2eD5FcE6b935d7a/sources/contracts/MultiFaucet.sol | @notice Allows super operator to update super operator @param _operator address to update | function updateSuperOperator(address _operator)
external
isSuperOperator
{
address old = superOperator;
superOperator = _operator;
emit SuperOperatorUpdated(old, superOperator);
}
| 12,416,880 | [
1,
19132,
2240,
3726,
358,
1089,
2240,
3726,
225,
389,
9497,
1758,
358,
1089,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
565,
445,
1089,
8051,
5592,
12,
2867,
389,
9497,
13,
7010,
3639,
3903,
7010,
3639,
353,
8051,
5592,
7010,
565,
288,
203,
3639,
1758,
1592,
273,
2240,
5592,
31,
203,
3639,
2240,
5592,
273,
389,
9497,
31,
203,
3639,
3626,
14845,
5592,
7381,
12,
1673,
16,
2240,
5592,
1769,
203,
565,
289,
203,
203,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
] |
./partial_match/1/0xB10daee1FCF62243aE27776D7a92D39dC8740f95/sources/lib/prb-math/src/sd1x18/Casting.sol | @notice Casts an SD1x18 number into UD2x18. - x must be positive. | function intoUD2x18(SD1x18 x) pure returns (UD2x18 result) {
int64 xInt = SD1x18.unwrap(x);
if (xInt < 0) {
revert CastingErrors.PRBMath_SD1x18_ToUD2x18_Underflow(x);
}
result = UD2x18.wrap(uint64(xInt));
}
| 9,308,805 | [
1,
9735,
87,
392,
15951,
21,
92,
2643,
1300,
1368,
587,
40,
22,
92,
2643,
18,
300,
619,
1297,
506,
6895,
18,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
915,
1368,
12587,
22,
92,
2643,
12,
9903,
21,
92,
2643,
619,
13,
16618,
1135,
261,
12587,
22,
92,
2643,
563,
13,
288,
203,
565,
509,
1105,
619,
1702,
273,
15951,
21,
92,
2643,
18,
318,
4113,
12,
92,
1769,
203,
565,
309,
261,
92,
1702,
411,
374,
13,
288,
203,
3639,
15226,
19782,
310,
4229,
18,
8025,
38,
10477,
67,
9903,
21,
92,
2643,
67,
774,
12587,
22,
92,
2643,
67,
14655,
2426,
12,
92,
1769,
203,
565,
289,
203,
565,
563,
273,
587,
40,
22,
92,
2643,
18,
4113,
12,
11890,
1105,
12,
92,
1702,
10019,
203,
97,
203,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
] |
./partial_match/1/0x5CCBf7B7A89eC43Bd83f4B70871d02f700df3335/sources/VestedLPMining.sol | @inheritdoc IVestedLPMining | function deposit(uint256 _pid, uint256 _amount) public override nonReentrant {
_validatePoolId(_pid);
_preventSameTxOriginAndMsgSender();
Pool storage pool = pools[_pid];
User storage user = users[_pid][msg.sender];
_doPoolUpdate(pool);
_vestUserCvp(user, pool.accCvpPerLpt);
if (_amount != 0) {
pool.lpToken.safeTransferFrom(msg.sender, address(this), _amount);
user.lptAmount = user.lptAmount.add(_amount);
}
user.cvpAdjust = _computeCvpAdjustment(user.lptAmount, pool.accCvpPerLpt);
emit Deposit(msg.sender, _pid, _amount);
_doCheckpointVotes(msg.sender);
}
| 10,996,055 | [
1,
36,
10093,
21602,
3149,
14461,
2930,
310,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
225,
445,
443,
1724,
12,
11890,
5034,
389,
6610,
16,
2254,
5034,
389,
8949,
13,
1071,
3849,
1661,
426,
8230,
970,
288,
203,
565,
389,
5662,
25136,
24899,
6610,
1769,
203,
565,
389,
29150,
8650,
4188,
7571,
1876,
3332,
12021,
5621,
203,
203,
565,
8828,
2502,
2845,
273,
16000,
63,
67,
6610,
15533,
203,
565,
2177,
2502,
729,
273,
3677,
63,
67,
6610,
6362,
3576,
18,
15330,
15533,
203,
203,
565,
389,
2896,
2864,
1891,
12,
6011,
1769,
203,
565,
389,
26923,
1299,
39,
20106,
12,
1355,
16,
2845,
18,
8981,
39,
20106,
2173,
48,
337,
1769,
203,
203,
565,
309,
261,
67,
8949,
480,
374,
13,
288,
203,
1377,
2845,
18,
9953,
1345,
18,
4626,
5912,
1265,
12,
3576,
18,
15330,
16,
1758,
12,
2211,
3631,
389,
8949,
1769,
203,
1377,
729,
18,
80,
337,
6275,
273,
729,
18,
80,
337,
6275,
18,
1289,
24899,
8949,
1769,
203,
565,
289,
203,
565,
729,
18,
19774,
84,
10952,
273,
389,
9200,
39,
20106,
19985,
12,
1355,
18,
80,
337,
6275,
16,
2845,
18,
8981,
39,
20106,
2173,
48,
337,
1769,
203,
565,
3626,
4019,
538,
305,
12,
3576,
18,
15330,
16,
389,
6610,
16,
389,
8949,
1769,
203,
203,
565,
389,
2896,
14431,
29637,
12,
3576,
18,
15330,
1769,
203,
225,
289,
203,
203,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
] |
./partial_match/42220/0xd5ab1BA8b2Ec70752068d1d728e728eAd0E19CBA/sources/contracts/OpenSumSwap.sol | * @notice Remove liquidity from the pool all in one token. @param tokenAmount the amount of the lp tokens to burn @param tokenOut the address of the token you want to receive @param minAmount the minimum amount to withdraw, otherwise revert @return amount chosen token that user received/ | function removeLiquidityOneToken(
uint256 tokenAmount,
address tokenOut,
uint256 minAmount
) external returns (uint256) {
uint8 tokenIndex = _getTokenIndex(tokenOut);
uint256 amountOut = _calculateRemoveLiquidityOneToken(
tokenAmount,
tokenOut
);
require(amountOut >= minAmount, "Not enough liquidity to remove");
balances[tokenIndex] = balances[tokenIndex].sub(amountOut);
tokens[tokenIndex].safeTransfer(msg.sender, amountOut);
lpToken.burnFrom(msg.sender, tokenAmount);
emit RemoveLiquidityOne(
msg.sender,
tokenAmount,
lpToken.totalSupply(),
tokenIndex,
amountOut
);
return amountOut;
}
| 3,494,588 | [
1,
3288,
4501,
372,
24237,
628,
326,
2845,
777,
316,
1245,
1147,
18,
225,
1147,
6275,
326,
3844,
434,
326,
12423,
2430,
358,
18305,
225,
1147,
1182,
326,
1758,
434,
326,
1147,
1846,
2545,
358,
6798,
225,
1131,
6275,
326,
5224,
3844,
358,
598,
9446,
16,
3541,
15226,
327,
3844,
10447,
1147,
716,
729,
5079,
19,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
225,
445,
1206,
48,
18988,
24237,
3335,
1345,
12,
203,
565,
2254,
5034,
1147,
6275,
16,
203,
565,
1758,
1147,
1182,
16,
203,
565,
2254,
5034,
1131,
6275,
203,
225,
262,
3903,
1135,
261,
11890,
5034,
13,
288,
203,
565,
2254,
28,
1147,
1016,
273,
389,
588,
1345,
1016,
12,
2316,
1182,
1769,
203,
565,
2254,
5034,
3844,
1182,
273,
389,
11162,
3288,
48,
18988,
24237,
3335,
1345,
12,
203,
1377,
1147,
6275,
16,
203,
1377,
1147,
1182,
203,
565,
11272,
203,
565,
2583,
12,
8949,
1182,
1545,
1131,
6275,
16,
315,
1248,
7304,
4501,
372,
24237,
358,
1206,
8863,
203,
203,
565,
324,
26488,
63,
2316,
1016,
65,
273,
324,
26488,
63,
2316,
1016,
8009,
1717,
12,
8949,
1182,
1769,
203,
565,
2430,
63,
2316,
1016,
8009,
4626,
5912,
12,
3576,
18,
15330,
16,
3844,
1182,
1769,
203,
565,
12423,
1345,
18,
70,
321,
1265,
12,
3576,
18,
15330,
16,
1147,
6275,
1769,
203,
203,
565,
3626,
3581,
48,
18988,
24237,
3335,
12,
203,
1377,
1234,
18,
15330,
16,
203,
1377,
1147,
6275,
16,
203,
1377,
12423,
1345,
18,
4963,
3088,
1283,
9334,
203,
1377,
1147,
1016,
16,
203,
1377,
3844,
1182,
203,
565,
11272,
203,
203,
565,
327,
3844,
1182,
31,
203,
225,
289,
203,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
] |
pragma solidity ^0.4.17;
import "@openzeppelin/contracts/token/ERC20/IERC20.sol";
import "@openzeppelin/contracts/token/ERC20/SafeERC20.sol";
import "@openzeppelin/contracts/utils/EnumerableSet.sol";
import "@openzeppelin/contracts/math/SafeMath.sol";
import "@openzeppelin/contracts/access/Ownable.sol";
import "./OCCToken.sol";
contract Pool {
uint pool = 0;
event Deposit(
address indexed _reserve,
address indexed _user,
uint256 _amount,
uint256 _timestamp,
uint256 sharesCreated
);
event Withdraw(
address indexed _reserve,
address indexed _user,
uint256 _amount,
uint256 _timestamp,
uint256 sharesRemoved
);
struct UserInfo {
uint256 amount; // How many investments the user has provided.
uint256 bonusToken; // Reward for investment (token)?
//
// no metter a user deposits or withdraws shares from a pool:
// 1. The pool share will be updated.
// 2. User's `amount` gets updated.
}
// Info of each pool.
struct PoolInfo {
address poolAddress; // Address of pool contract.
uint256 allocTokens; // How many tokens allocated in this pool
uint256 allocFunds; // How many funds allocated in this pool
uint256 OCCPerShare; // Accumulated OCC per share
}
//States of Pool:
//PoolOpen: Accepting
//PayOut: Withdraw
enum States {
PoolActive, //0
PoolClosed //1
}
States state = States.PoolActive;
//View Status of contract State
function stateOfPool() public view returns(States){
return state;
}
//View Size of pool
function poolSize() public view returns (uint){
return pool;
}
constructor( address _tokenAddress,
uint _tokenPrice) public {
//stakeholderShare[_ADMIN]
//stakeholderShare[POOL_OPERATOR]
setRole_(RR_ADMIN, msg.sender);
setRole_(RR_POOL_OPERATOR, _poolOperatorAddress);
tokenAddress = _tokenAddress;
tokenPrice = _tokenPrice;
}
} | View Status of contract State | function stateOfPool() public view returns(States){
return state;
}
| 7,263,106 | [
1,
1767,
2685,
434,
6835,
3287,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
225,
445,
919,
951,
2864,
1435,
1071,
1476,
1135,
12,
7629,
15329,
203,
1377,
327,
919,
31,
203,
225,
289,
203,
203,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
] |
pragma solidity ^0.4.24;
/**
* @title ERC20Basic
* @dev Simpler version of ERC20 interface
* 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 SafeERC20
* @dev Wrappers around ERC20 operations that throw on failure.
* 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 {
function safeTransfer(ERC20Basic token, address to, uint256 value) internal {
require(token.transfer(to, value));
}
function safeTransferFrom(
ERC20 token,
address from,
address to,
uint256 value
)
internal
{
require(token.transferFrom(from, to, value));
}
function safeApprove(ERC20 token, address spender, uint256 value) internal {
require(token.approve(spender, 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 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;
}
}
/**
* @title Crowdsale
* @dev Crowdsale is a base contract for managing a token crowdsale,
* allowing investors to purchase tokens with ether. This contract implements
* such functionality in its most fundamental form and can be extended to provide additional
* functionality and/or custom behavior.
* The external interface represents the basic interface for purchasing tokens, and conform
* the base architecture for crowdsales. They are *not* intended to be modified / overriden.
* The internal interface conforms the extensible and modifiable surface of crowdsales. Override
* the methods to add functionality. Consider using 'super' where appropiate to concatenate
* behavior.
*/
contract Crowdsale {
using SafeMath for uint256;
using SafeERC20 for ERC20;
// The token being sold
ERC20 public token;
// Address where funds are collected
address public wallet;
// How many token units a buyer gets per wei.
// The rate is the conversion between wei and the smallest and indivisible token unit.
// So, if you are using a rate of 1 with a DetailedERC20 token with 3 decimals called TOK
// 1 wei will give you 1 unit, or 0.001 TOK.
// 14 decimals: 0.00000000000001
uint256 public rate;
// Amount of tokens sold
uint256 public tokenSold;
/**
* Event for token purchase logging
* @param purchaser who paid for the tokens
* @param beneficiary who got the tokens
* @param value weis paid for purchase
* @param amount amount of tokens purchased
*/
event TokenPurchase(
address indexed purchaser,
address indexed beneficiary,
uint256 value,
uint256 amount
);
/**
* @param _rate Number of token units a buyer gets per wei
* @param _wallet Address where collected funds will be forwarded to
* @param _token Address of the token being sold
*/
constructor(uint256 _rate, address _wallet, ERC20 _token) public {
require(_rate > 0);
require(_wallet != address(0));
require(_token != address(0));
rate = _rate;
wallet = _wallet;
token = _token;
}
// -----------------------------------------
// Crowdsale external interface
// -----------------------------------------
/**
* @dev fallback function ***DO NOT OVERRIDE***
*/
function () external payable {
buyTokens(msg.sender, "", "");
}
function getReferrals(address referrer) public view returns (uint256){
return referraltokenamount[referrer];
}
/**
* @dev low level token purchase ***DO NOT OVERRIDE***
* @param _beneficiary Address performing the token purchase
*/
mapping(string => address) referrals;
mapping(address => uint256) referraltokenamount;
function buyTokens(address _beneficiary, string referralemail, string youremail) public payable {
uint256 weiAmount = msg.value;
_preValidatePurchase(_beneficiary, weiAmount);
// calculate token amount to be created
uint256 tokens = _getTokenAmount(weiAmount);
// update state
tokenSold = tokenSold.add(tokens);
if((bytes(referralemail).length != 0) && (referrals[referralemail] != 0)){
address referral = referrals[referralemail];
uint256 referraltokens = tokens.mul(5) / 100;
token.safeTransfer(referral, referraltokens);
referraltokenamount[referral] = referraltokenamount[referral] + tokens;
tokenSold = tokenSold.add(referraltokens);
}
if((bytes(youremail).length != 0) && (referrals[youremail] == 0)){
referrals[youremail] = _beneficiary;
}
_processPurchase(_beneficiary, tokens);
emit TokenPurchase(
msg.sender,
_beneficiary,
weiAmount,
tokens
);
_updatePurchasingState(_beneficiary, weiAmount);
_forwardFunds();
_postValidatePurchase(_beneficiary, weiAmount);
}
// -----------------------------------------
// Internal interface (extensible)
// -----------------------------------------
/**
* @dev Validation of an incoming purchase. Use require statements to revert state when conditions are not met. Use super to concatenate validations.
* @param _beneficiary Address performing the token purchase
* @param _weiAmount Value in wei involved in the purchase
*/
function _preValidatePurchase(
address _beneficiary,
uint256 _weiAmount
)
internal
{
require(_beneficiary != address(0));
require(_weiAmount != 0);
}
/**
* @dev Validation of an executed purchase. Observe state and use revert statements to undo rollback when valid conditions are not met.
* @param _beneficiary Address performing the token purchase
* @param _weiAmount Value in wei involved in the purchase
*/
function _postValidatePurchase(
address _beneficiary,
uint256 _weiAmount
)
internal
{
// optional override
}
/**
* @dev Source of tokens. Override this method to modify the way in which the crowdsale ultimately gets and sends its tokens.
* @param _beneficiary Address performing the token purchase
* @param _tokenAmount Number of tokens to be emitted
*/
function _deliverTokens(
address _beneficiary,
uint256 _tokenAmount
)
internal
{
token.safeTransfer(_beneficiary, _tokenAmount);
}
/**
* @dev Executed when a purchase has been validated and is ready to be executed. Not necessarily emits/sends tokens.
* @param _beneficiary Address receiving the tokens
* @param _tokenAmount Number of tokens to be purchased
*/
function _processPurchase(
address _beneficiary,
uint256 _tokenAmount
)
internal
{
_deliverTokens(_beneficiary, _tokenAmount);
}
/**
* @dev Override for extensions that require an internal state to check for validity (current user contributions, etc.)
* @param _beneficiary Address receiving the tokens
* @param _weiAmount Value in wei involved in the purchase
*/
function _updatePurchasingState(
address _beneficiary,
uint256 _weiAmount
)
internal
{
// optional override
}
/**
* @dev Override to extend the way in which ether is converted to tokens.
* @param _weiAmount Value in wei to be converted into tokens
* @return Number of tokens that can be purchased with the specified _weiAmount
*/
function _getTokenAmount(uint256 _weiAmount)
internal view returns (uint256)
{
return _weiAmount.mul(rate) / 2;
}
/**
* @dev Determines how ETH is stored/forwarded on purchases.
*/
function _forwardFunds() internal {
wallet.transfer(msg.value);
}
} | * @dev Determines how ETH is stored/forwarded on purchases./ | function _forwardFunds() internal {
wallet.transfer(msg.value);
}
| 2,434,494 | [
1,
10114,
3661,
512,
2455,
353,
4041,
19,
1884,
11804,
603,
5405,
343,
3304,
18,
19,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
225,
445,
389,
11565,
42,
19156,
1435,
2713,
288,
203,
565,
9230,
18,
13866,
12,
3576,
18,
1132,
1769,
203,
225,
289,
203,
21281,
203,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
] |
./full_match/4/0x92d03D72e0AFAcBCA98d3a3dF647471b39443ca0/sources/contracts/IDividendPayingToken.sol | @title Dividend-Paying Token Interface @author Roger Wu (https://github.com/roger-wu) @dev An interface for a dividend-paying token contract. | interface IDividendPayingToken {
function dividendOf(address _owner) external view returns(uint256);
function distributeDividends() external payable;
function withdrawDividend() external;
event DividendsDistributed(
address indexed from,
uint256 weiAmount
);
event DividendWithdrawn(
address indexed to,
uint256 weiAmount
);
} | 12,432,939 | [
1,
7244,
26746,
17,
9148,
310,
3155,
6682,
225,
534,
83,
693,
678,
89,
261,
4528,
2207,
6662,
18,
832,
19,
303,
693,
17,
91,
89,
13,
225,
1922,
1560,
364,
279,
31945,
17,
10239,
310,
1147,
6835,
18,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
5831,
1599,
427,
26746,
9148,
310,
1345,
288,
203,
225,
445,
31945,
951,
12,
2867,
389,
8443,
13,
3903,
1476,
1135,
12,
11890,
5034,
1769,
203,
203,
225,
445,
25722,
7244,
350,
5839,
1435,
3903,
8843,
429,
31,
203,
203,
225,
445,
598,
9446,
7244,
26746,
1435,
3903,
31,
203,
203,
225,
871,
21411,
350,
5839,
1669,
11050,
12,
203,
565,
1758,
8808,
628,
16,
203,
565,
2254,
5034,
732,
77,
6275,
203,
225,
11272,
203,
203,
225,
871,
21411,
26746,
1190,
9446,
82,
12,
203,
565,
1758,
8808,
358,
16,
203,
565,
2254,
5034,
732,
77,
6275,
203,
225,
11272,
203,
97,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
] |
// SPDX-License-Identifier: Apache-2.0
pragma solidity ^0.6.8;
import "./ProtoBufRuntime.sol";
import "./GoogleProtobufAny.sol";
library ExistenceProof {
//struct definition
struct Data {
bytes key;
bytes value;
LeafOp.Data leaf;
InnerOp.Data[] path;
}
// Decoder section
/**
* @dev The main decoder for memory
* @param bs The bytes array to be decoded
* @return The decoded struct
*/
function decode(bytes memory bs) internal pure returns (Data memory) {
(Data memory x, ) = _decode(32, bs, bs.length);
return x;
}
/**
* @dev The main decoder for storage
* @param self The in-storage struct
* @param bs The bytes array to be decoded
*/
function decode(Data storage self, bytes memory bs) internal {
(Data memory x, ) = _decode(32, bs, bs.length);
store(x, self);
}
// inner decoder
/**
* @dev The decoder for internal usage
* @param p The offset of bytes array to start decode
* @param bs The bytes array to be decoded
* @param sz The number of bytes expected
* @return The decoded struct
* @return The number of bytes decoded
*/
function _decode(uint256 p, bytes memory bs, uint256 sz)
internal
pure
returns (Data memory, uint)
{
Data memory r;
uint[5] memory counters;
uint256 fieldId;
ProtoBufRuntime.WireType wireType;
uint256 bytesRead;
uint256 offset = p;
uint256 pointer = p;
while (pointer < offset + sz) {
(fieldId, wireType, bytesRead) = ProtoBufRuntime._decode_key(pointer, bs);
pointer += bytesRead;
if (fieldId == 1) {
pointer += _read_key(pointer, bs, r, counters);
}
else if (fieldId == 2) {
pointer += _read_value(pointer, bs, r, counters);
}
else if (fieldId == 3) {
pointer += _read_leaf(pointer, bs, r, counters);
}
else if (fieldId == 4) {
pointer += _read_path(pointer, bs, nil(), counters);
}
else {
if (wireType == ProtoBufRuntime.WireType.Fixed64) {
uint256 size;
(, size) = ProtoBufRuntime._decode_fixed64(pointer, bs);
pointer += size;
}
if (wireType == ProtoBufRuntime.WireType.Fixed32) {
uint256 size;
(, size) = ProtoBufRuntime._decode_fixed32(pointer, bs);
pointer += size;
}
if (wireType == ProtoBufRuntime.WireType.Varint) {
uint256 size;
(, size) = ProtoBufRuntime._decode_varint(pointer, bs);
pointer += size;
}
if (wireType == ProtoBufRuntime.WireType.LengthDelim) {
uint256 size;
(, size) = ProtoBufRuntime._decode_lendelim(pointer, bs);
pointer += size;
}
}
}
pointer = offset;
r.path = new InnerOp.Data[](counters[4]);
while (pointer < offset + sz) {
(fieldId, wireType, bytesRead) = ProtoBufRuntime._decode_key(pointer, bs);
pointer += bytesRead;
if (fieldId == 1) {
pointer += _read_key(pointer, bs, nil(), counters);
}
else if (fieldId == 2) {
pointer += _read_value(pointer, bs, nil(), counters);
}
else if (fieldId == 3) {
pointer += _read_leaf(pointer, bs, nil(), counters);
}
else if (fieldId == 4) {
pointer += _read_path(pointer, bs, r, counters);
}
else {
if (wireType == ProtoBufRuntime.WireType.Fixed64) {
uint256 size;
(, size) = ProtoBufRuntime._decode_fixed64(pointer, bs);
pointer += size;
}
if (wireType == ProtoBufRuntime.WireType.Fixed32) {
uint256 size;
(, size) = ProtoBufRuntime._decode_fixed32(pointer, bs);
pointer += size;
}
if (wireType == ProtoBufRuntime.WireType.Varint) {
uint256 size;
(, size) = ProtoBufRuntime._decode_varint(pointer, bs);
pointer += size;
}
if (wireType == ProtoBufRuntime.WireType.LengthDelim) {
uint256 size;
(, size) = ProtoBufRuntime._decode_lendelim(pointer, bs);
pointer += size;
}
}
}
return (r, sz);
}
// field readers
/**
* @dev The decoder for reading a field
* @param p The offset of bytes array to start decode
* @param bs The bytes array to be decoded
* @param r The in-memory struct
* @param counters The counters for repeated fields
* @return The number of bytes decoded
*/
function _read_key(
uint256 p,
bytes memory bs,
Data memory r,
uint[5] memory counters
) internal pure returns (uint) {
/**
* if `r` is NULL, then only counting the number of fields.
*/
(bytes memory x, uint256 sz) = ProtoBufRuntime._decode_bytes(p, bs);
if (isNil(r)) {
counters[1] += 1;
} else {
r.key = x;
if (counters[1] > 0) counters[1] -= 1;
}
return sz;
}
/**
* @dev The decoder for reading a field
* @param p The offset of bytes array to start decode
* @param bs The bytes array to be decoded
* @param r The in-memory struct
* @param counters The counters for repeated fields
* @return The number of bytes decoded
*/
function _read_value(
uint256 p,
bytes memory bs,
Data memory r,
uint[5] memory counters
) internal pure returns (uint) {
/**
* if `r` is NULL, then only counting the number of fields.
*/
(bytes memory x, uint256 sz) = ProtoBufRuntime._decode_bytes(p, bs);
if (isNil(r)) {
counters[2] += 1;
} else {
r.value = x;
if (counters[2] > 0) counters[2] -= 1;
}
return sz;
}
/**
* @dev The decoder for reading a field
* @param p The offset of bytes array to start decode
* @param bs The bytes array to be decoded
* @param r The in-memory struct
* @param counters The counters for repeated fields
* @return The number of bytes decoded
*/
function _read_leaf(
uint256 p,
bytes memory bs,
Data memory r,
uint[5] memory counters
) internal pure returns (uint) {
/**
* if `r` is NULL, then only counting the number of fields.
*/
(LeafOp.Data memory x, uint256 sz) = _decode_LeafOp(p, bs);
if (isNil(r)) {
counters[3] += 1;
} else {
r.leaf = x;
if (counters[3] > 0) counters[3] -= 1;
}
return sz;
}
/**
* @dev The decoder for reading a field
* @param p The offset of bytes array to start decode
* @param bs The bytes array to be decoded
* @param r The in-memory struct
* @param counters The counters for repeated fields
* @return The number of bytes decoded
*/
function _read_path(
uint256 p,
bytes memory bs,
Data memory r,
uint[5] memory counters
) internal pure returns (uint) {
/**
* if `r` is NULL, then only counting the number of fields.
*/
(InnerOp.Data memory x, uint256 sz) = _decode_InnerOp(p, bs);
if (isNil(r)) {
counters[4] += 1;
} else {
r.path[r.path.length - counters[4]] = x;
if (counters[4] > 0) counters[4] -= 1;
}
return sz;
}
// struct decoder
/**
* @dev The decoder for reading a inner struct field
* @param p The offset of bytes array to start decode
* @param bs The bytes array to be decoded
* @return The decoded inner-struct
* @return The number of bytes used to decode
*/
function _decode_LeafOp(uint256 p, bytes memory bs)
internal
pure
returns (LeafOp.Data memory, uint)
{
uint256 pointer = p;
(uint256 sz, uint256 bytesRead) = ProtoBufRuntime._decode_varint(pointer, bs);
pointer += bytesRead;
(LeafOp.Data memory r, ) = LeafOp._decode(pointer, bs, sz);
return (r, sz + bytesRead);
}
/**
* @dev The decoder for reading a inner struct field
* @param p The offset of bytes array to start decode
* @param bs The bytes array to be decoded
* @return The decoded inner-struct
* @return The number of bytes used to decode
*/
function _decode_InnerOp(uint256 p, bytes memory bs)
internal
pure
returns (InnerOp.Data memory, uint)
{
uint256 pointer = p;
(uint256 sz, uint256 bytesRead) = ProtoBufRuntime._decode_varint(pointer, bs);
pointer += bytesRead;
(InnerOp.Data memory r, ) = InnerOp._decode(pointer, bs, sz);
return (r, sz + bytesRead);
}
// Encoder section
/**
* @dev The main encoder for memory
* @param r The struct to be encoded
* @return The encoded byte array
*/
function encode(Data memory r) internal pure returns (bytes memory) {
bytes memory bs = new bytes(_estimate(r));
uint256 sz = _encode(r, 32, bs);
assembly {
mstore(bs, sz)
}
return bs;
}
// inner encoder
/**
* @dev The encoder for internal usage
* @param r The struct to be encoded
* @param p The offset of bytes array to start decode
* @param bs The bytes array to be decoded
* @return The number of bytes encoded
*/
function _encode(Data memory r, uint256 p, bytes memory bs)
internal
pure
returns (uint)
{
uint256 offset = p;
uint256 pointer = p;
uint256 i;
if (r.key.length != 0) {
pointer += ProtoBufRuntime._encode_key(
1,
ProtoBufRuntime.WireType.LengthDelim,
pointer,
bs
);
pointer += ProtoBufRuntime._encode_bytes(r.key, pointer, bs);
}
if (r.value.length != 0) {
pointer += ProtoBufRuntime._encode_key(
2,
ProtoBufRuntime.WireType.LengthDelim,
pointer,
bs
);
pointer += ProtoBufRuntime._encode_bytes(r.value, pointer, bs);
}
pointer += ProtoBufRuntime._encode_key(
3,
ProtoBufRuntime.WireType.LengthDelim,
pointer,
bs
);
pointer += LeafOp._encode_nested(r.leaf, pointer, bs);
if (r.path.length != 0) {
for(i = 0; i < r.path.length; i++) {
pointer += ProtoBufRuntime._encode_key(
4,
ProtoBufRuntime.WireType.LengthDelim,
pointer,
bs)
;
pointer += InnerOp._encode_nested(r.path[i], pointer, bs);
}
}
return pointer - offset;
}
// nested encoder
/**
* @dev The encoder for inner struct
* @param r The struct to be encoded
* @param p The offset of bytes array to start decode
* @param bs The bytes array to be decoded
* @return The number of bytes encoded
*/
function _encode_nested(Data memory r, uint256 p, bytes memory bs)
internal
pure
returns (uint)
{
/**
* First encoded `r` into a temporary array, and encode the actual size used.
* Then copy the temporary array into `bs`.
*/
uint256 offset = p;
uint256 pointer = p;
bytes memory tmp = new bytes(_estimate(r));
uint256 tmpAddr = ProtoBufRuntime.getMemoryAddress(tmp);
uint256 bsAddr = ProtoBufRuntime.getMemoryAddress(bs);
uint256 size = _encode(r, 32, tmp);
pointer += ProtoBufRuntime._encode_varint(size, pointer, bs);
ProtoBufRuntime.copyBytes(tmpAddr + 32, bsAddr + pointer, size);
pointer += size;
delete tmp;
return pointer - offset;
}
// estimator
/**
* @dev The estimator for a struct
* @param r The struct to be encoded
* @return The number of bytes encoded in estimation
*/
function _estimate(
Data memory r
) internal pure returns (uint) {
uint256 e;uint256 i;
e += 1 + ProtoBufRuntime._sz_lendelim(r.key.length);
e += 1 + ProtoBufRuntime._sz_lendelim(r.value.length);
e += 1 + ProtoBufRuntime._sz_lendelim(LeafOp._estimate(r.leaf));
for(i = 0; i < r.path.length; i++) {
e += 1 + ProtoBufRuntime._sz_lendelim(InnerOp._estimate(r.path[i]));
}
return e;
}
// empty checker
function _empty(
Data memory r
) internal pure returns (bool) {
if (r.key.length != 0) {
return false;
}
if (r.value.length != 0) {
return false;
}
if (r.path.length != 0) {
return false;
}
return true;
}
//store function
/**
* @dev Store in-memory struct to storage
* @param input The in-memory struct
* @param output The in-storage struct
*/
function store(Data memory input, Data storage output) internal {
output.key = input.key;
output.value = input.value;
LeafOp.store(input.leaf, output.leaf);
for(uint256 i4 = 0; i4 < input.path.length; i4++) {
output.path.push(input.path[i4]);
}
}
//array helpers for Path
/**
* @dev Add value to an array
* @param self The in-memory struct
* @param value The value to add
*/
function addPath(Data memory self, InnerOp.Data memory value) internal pure {
/**
* First resize the array. Then add the new element to the end.
*/
InnerOp.Data[] memory tmp = new InnerOp.Data[](self.path.length + 1);
for (uint256 i = 0; i < self.path.length; i++) {
tmp[i] = self.path[i];
}
tmp[self.path.length] = value;
self.path = tmp;
}
//utility functions
/**
* @dev Return an empty struct
* @return r The empty struct
*/
function nil() internal pure returns (Data memory r) {
assembly {
r := 0
}
}
/**
* @dev Test whether a struct is empty
* @param x The struct to be tested
* @return r True if it is empty
*/
function isNil(Data memory x) internal pure returns (bool r) {
assembly {
r := iszero(x)
}
}
}
//library ExistenceProof
library NonExistenceProof {
//struct definition
struct Data {
bytes key;
ExistenceProof.Data left;
ExistenceProof.Data right;
}
// Decoder section
/**
* @dev The main decoder for memory
* @param bs The bytes array to be decoded
* @return The decoded struct
*/
function decode(bytes memory bs) internal pure returns (Data memory) {
(Data memory x, ) = _decode(32, bs, bs.length);
return x;
}
/**
* @dev The main decoder for storage
* @param self The in-storage struct
* @param bs The bytes array to be decoded
*/
function decode(Data storage self, bytes memory bs) internal {
(Data memory x, ) = _decode(32, bs, bs.length);
store(x, self);
}
// inner decoder
/**
* @dev The decoder for internal usage
* @param p The offset of bytes array to start decode
* @param bs The bytes array to be decoded
* @param sz The number of bytes expected
* @return The decoded struct
* @return The number of bytes decoded
*/
function _decode(uint256 p, bytes memory bs, uint256 sz)
internal
pure
returns (Data memory, uint)
{
Data memory r;
uint[4] memory counters;
uint256 fieldId;
ProtoBufRuntime.WireType wireType;
uint256 bytesRead;
uint256 offset = p;
uint256 pointer = p;
while (pointer < offset + sz) {
(fieldId, wireType, bytesRead) = ProtoBufRuntime._decode_key(pointer, bs);
pointer += bytesRead;
if (fieldId == 1) {
pointer += _read_key(pointer, bs, r, counters);
}
else if (fieldId == 2) {
pointer += _read_left(pointer, bs, r, counters);
}
else if (fieldId == 3) {
pointer += _read_right(pointer, bs, r, counters);
}
else {
if (wireType == ProtoBufRuntime.WireType.Fixed64) {
uint256 size;
(, size) = ProtoBufRuntime._decode_fixed64(pointer, bs);
pointer += size;
}
if (wireType == ProtoBufRuntime.WireType.Fixed32) {
uint256 size;
(, size) = ProtoBufRuntime._decode_fixed32(pointer, bs);
pointer += size;
}
if (wireType == ProtoBufRuntime.WireType.Varint) {
uint256 size;
(, size) = ProtoBufRuntime._decode_varint(pointer, bs);
pointer += size;
}
if (wireType == ProtoBufRuntime.WireType.LengthDelim) {
uint256 size;
(, size) = ProtoBufRuntime._decode_lendelim(pointer, bs);
pointer += size;
}
}
}
return (r, sz);
}
// field readers
/**
* @dev The decoder for reading a field
* @param p The offset of bytes array to start decode
* @param bs The bytes array to be decoded
* @param r The in-memory struct
* @param counters The counters for repeated fields
* @return The number of bytes decoded
*/
function _read_key(
uint256 p,
bytes memory bs,
Data memory r,
uint[4] memory counters
) internal pure returns (uint) {
/**
* if `r` is NULL, then only counting the number of fields.
*/
(bytes memory x, uint256 sz) = ProtoBufRuntime._decode_bytes(p, bs);
if (isNil(r)) {
counters[1] += 1;
} else {
r.key = x;
if (counters[1] > 0) counters[1] -= 1;
}
return sz;
}
/**
* @dev The decoder for reading a field
* @param p The offset of bytes array to start decode
* @param bs The bytes array to be decoded
* @param r The in-memory struct
* @param counters The counters for repeated fields
* @return The number of bytes decoded
*/
function _read_left(
uint256 p,
bytes memory bs,
Data memory r,
uint[4] memory counters
) internal pure returns (uint) {
/**
* if `r` is NULL, then only counting the number of fields.
*/
(ExistenceProof.Data memory x, uint256 sz) = _decode_ExistenceProof(p, bs);
if (isNil(r)) {
counters[2] += 1;
} else {
r.left = x;
if (counters[2] > 0) counters[2] -= 1;
}
return sz;
}
/**
* @dev The decoder for reading a field
* @param p The offset of bytes array to start decode
* @param bs The bytes array to be decoded
* @param r The in-memory struct
* @param counters The counters for repeated fields
* @return The number of bytes decoded
*/
function _read_right(
uint256 p,
bytes memory bs,
Data memory r,
uint[4] memory counters
) internal pure returns (uint) {
/**
* if `r` is NULL, then only counting the number of fields.
*/
(ExistenceProof.Data memory x, uint256 sz) = _decode_ExistenceProof(p, bs);
if (isNil(r)) {
counters[3] += 1;
} else {
r.right = x;
if (counters[3] > 0) counters[3] -= 1;
}
return sz;
}
// struct decoder
/**
* @dev The decoder for reading a inner struct field
* @param p The offset of bytes array to start decode
* @param bs The bytes array to be decoded
* @return The decoded inner-struct
* @return The number of bytes used to decode
*/
function _decode_ExistenceProof(uint256 p, bytes memory bs)
internal
pure
returns (ExistenceProof.Data memory, uint)
{
uint256 pointer = p;
(uint256 sz, uint256 bytesRead) = ProtoBufRuntime._decode_varint(pointer, bs);
pointer += bytesRead;
(ExistenceProof.Data memory r, ) = ExistenceProof._decode(pointer, bs, sz);
return (r, sz + bytesRead);
}
// Encoder section
/**
* @dev The main encoder for memory
* @param r The struct to be encoded
* @return The encoded byte array
*/
function encode(Data memory r) internal pure returns (bytes memory) {
bytes memory bs = new bytes(_estimate(r));
uint256 sz = _encode(r, 32, bs);
assembly {
mstore(bs, sz)
}
return bs;
}
// inner encoder
/**
* @dev The encoder for internal usage
* @param r The struct to be encoded
* @param p The offset of bytes array to start decode
* @param bs The bytes array to be decoded
* @return The number of bytes encoded
*/
function _encode(Data memory r, uint256 p, bytes memory bs)
internal
pure
returns (uint)
{
uint256 offset = p;
uint256 pointer = p;
if (r.key.length != 0) {
pointer += ProtoBufRuntime._encode_key(
1,
ProtoBufRuntime.WireType.LengthDelim,
pointer,
bs
);
pointer += ProtoBufRuntime._encode_bytes(r.key, pointer, bs);
}
pointer += ProtoBufRuntime._encode_key(
2,
ProtoBufRuntime.WireType.LengthDelim,
pointer,
bs
);
pointer += ExistenceProof._encode_nested(r.left, pointer, bs);
pointer += ProtoBufRuntime._encode_key(
3,
ProtoBufRuntime.WireType.LengthDelim,
pointer,
bs
);
pointer += ExistenceProof._encode_nested(r.right, pointer, bs);
return pointer - offset;
}
// nested encoder
/**
* @dev The encoder for inner struct
* @param r The struct to be encoded
* @param p The offset of bytes array to start decode
* @param bs The bytes array to be decoded
* @return The number of bytes encoded
*/
function _encode_nested(Data memory r, uint256 p, bytes memory bs)
internal
pure
returns (uint)
{
/**
* First encoded `r` into a temporary array, and encode the actual size used.
* Then copy the temporary array into `bs`.
*/
uint256 offset = p;
uint256 pointer = p;
bytes memory tmp = new bytes(_estimate(r));
uint256 tmpAddr = ProtoBufRuntime.getMemoryAddress(tmp);
uint256 bsAddr = ProtoBufRuntime.getMemoryAddress(bs);
uint256 size = _encode(r, 32, tmp);
pointer += ProtoBufRuntime._encode_varint(size, pointer, bs);
ProtoBufRuntime.copyBytes(tmpAddr + 32, bsAddr + pointer, size);
pointer += size;
delete tmp;
return pointer - offset;
}
// estimator
/**
* @dev The estimator for a struct
* @param r The struct to be encoded
* @return The number of bytes encoded in estimation
*/
function _estimate(
Data memory r
) internal pure returns (uint) {
uint256 e;
e += 1 + ProtoBufRuntime._sz_lendelim(r.key.length);
e += 1 + ProtoBufRuntime._sz_lendelim(ExistenceProof._estimate(r.left));
e += 1 + ProtoBufRuntime._sz_lendelim(ExistenceProof._estimate(r.right));
return e;
}
// empty checker
function _empty(
Data memory r
) internal pure returns (bool) {
if (r.key.length != 0) {
return false;
}
return true;
}
//store function
/**
* @dev Store in-memory struct to storage
* @param input The in-memory struct
* @param output The in-storage struct
*/
function store(Data memory input, Data storage output) internal {
output.key = input.key;
ExistenceProof.store(input.left, output.left);
ExistenceProof.store(input.right, output.right);
}
//utility functions
/**
* @dev Return an empty struct
* @return r The empty struct
*/
function nil() internal pure returns (Data memory r) {
assembly {
r := 0
}
}
/**
* @dev Test whether a struct is empty
* @param x The struct to be tested
* @return r True if it is empty
*/
function isNil(Data memory x) internal pure returns (bool r) {
assembly {
r := iszero(x)
}
}
}
//library NonExistenceProof
library CommitmentProof {
//struct definition
struct Data {
ExistenceProof.Data exist;
NonExistenceProof.Data nonexist;
BatchProof.Data batch;
CompressedBatchProof.Data compressed;
}
// Decoder section
/**
* @dev The main decoder for memory
* @param bs The bytes array to be decoded
* @return The decoded struct
*/
function decode(bytes memory bs) internal pure returns (Data memory) {
(Data memory x, ) = _decode(32, bs, bs.length);
return x;
}
/**
* @dev The main decoder for storage
* @param self The in-storage struct
* @param bs The bytes array to be decoded
*/
function decode(Data storage self, bytes memory bs) internal {
(Data memory x, ) = _decode(32, bs, bs.length);
store(x, self);
}
// inner decoder
/**
* @dev The decoder for internal usage
* @param p The offset of bytes array to start decode
* @param bs The bytes array to be decoded
* @param sz The number of bytes expected
* @return The decoded struct
* @return The number of bytes decoded
*/
function _decode(uint256 p, bytes memory bs, uint256 sz)
internal
pure
returns (Data memory, uint)
{
Data memory r;
uint[5] memory counters;
uint256 fieldId;
ProtoBufRuntime.WireType wireType;
uint256 bytesRead;
uint256 offset = p;
uint256 pointer = p;
while (pointer < offset + sz) {
(fieldId, wireType, bytesRead) = ProtoBufRuntime._decode_key(pointer, bs);
pointer += bytesRead;
if (fieldId == 1) {
pointer += _read_exist(pointer, bs, r, counters);
}
else if (fieldId == 2) {
pointer += _read_nonexist(pointer, bs, r, counters);
}
else if (fieldId == 3) {
pointer += _read_batch(pointer, bs, r, counters);
}
else if (fieldId == 4) {
pointer += _read_compressed(pointer, bs, r, counters);
}
else {
if (wireType == ProtoBufRuntime.WireType.Fixed64) {
uint256 size;
(, size) = ProtoBufRuntime._decode_fixed64(pointer, bs);
pointer += size;
}
if (wireType == ProtoBufRuntime.WireType.Fixed32) {
uint256 size;
(, size) = ProtoBufRuntime._decode_fixed32(pointer, bs);
pointer += size;
}
if (wireType == ProtoBufRuntime.WireType.Varint) {
uint256 size;
(, size) = ProtoBufRuntime._decode_varint(pointer, bs);
pointer += size;
}
if (wireType == ProtoBufRuntime.WireType.LengthDelim) {
uint256 size;
(, size) = ProtoBufRuntime._decode_lendelim(pointer, bs);
pointer += size;
}
}
}
return (r, sz);
}
// field readers
/**
* @dev The decoder for reading a field
* @param p The offset of bytes array to start decode
* @param bs The bytes array to be decoded
* @param r The in-memory struct
* @param counters The counters for repeated fields
* @return The number of bytes decoded
*/
function _read_exist(
uint256 p,
bytes memory bs,
Data memory r,
uint[5] memory counters
) internal pure returns (uint) {
/**
* if `r` is NULL, then only counting the number of fields.
*/
(ExistenceProof.Data memory x, uint256 sz) = _decode_ExistenceProof(p, bs);
if (isNil(r)) {
counters[1] += 1;
} else {
r.exist = x;
if (counters[1] > 0) counters[1] -= 1;
}
return sz;
}
/**
* @dev The decoder for reading a field
* @param p The offset of bytes array to start decode
* @param bs The bytes array to be decoded
* @param r The in-memory struct
* @param counters The counters for repeated fields
* @return The number of bytes decoded
*/
function _read_nonexist(
uint256 p,
bytes memory bs,
Data memory r,
uint[5] memory counters
) internal pure returns (uint) {
/**
* if `r` is NULL, then only counting the number of fields.
*/
(NonExistenceProof.Data memory x, uint256 sz) = _decode_NonExistenceProof(p, bs);
if (isNil(r)) {
counters[2] += 1;
} else {
r.nonexist = x;
if (counters[2] > 0) counters[2] -= 1;
}
return sz;
}
/**
* @dev The decoder for reading a field
* @param p The offset of bytes array to start decode
* @param bs The bytes array to be decoded
* @param r The in-memory struct
* @param counters The counters for repeated fields
* @return The number of bytes decoded
*/
function _read_batch(
uint256 p,
bytes memory bs,
Data memory r,
uint[5] memory counters
) internal pure returns (uint) {
/**
* if `r` is NULL, then only counting the number of fields.
*/
(BatchProof.Data memory x, uint256 sz) = _decode_BatchProof(p, bs);
if (isNil(r)) {
counters[3] += 1;
} else {
r.batch = x;
if (counters[3] > 0) counters[3] -= 1;
}
return sz;
}
/**
* @dev The decoder for reading a field
* @param p The offset of bytes array to start decode
* @param bs The bytes array to be decoded
* @param r The in-memory struct
* @param counters The counters for repeated fields
* @return The number of bytes decoded
*/
function _read_compressed(
uint256 p,
bytes memory bs,
Data memory r,
uint[5] memory counters
) internal pure returns (uint) {
/**
* if `r` is NULL, then only counting the number of fields.
*/
(CompressedBatchProof.Data memory x, uint256 sz) = _decode_CompressedBatchProof(p, bs);
if (isNil(r)) {
counters[4] += 1;
} else {
r.compressed = x;
if (counters[4] > 0) counters[4] -= 1;
}
return sz;
}
// struct decoder
/**
* @dev The decoder for reading a inner struct field
* @param p The offset of bytes array to start decode
* @param bs The bytes array to be decoded
* @return The decoded inner-struct
* @return The number of bytes used to decode
*/
function _decode_ExistenceProof(uint256 p, bytes memory bs)
internal
pure
returns (ExistenceProof.Data memory, uint)
{
uint256 pointer = p;
(uint256 sz, uint256 bytesRead) = ProtoBufRuntime._decode_varint(pointer, bs);
pointer += bytesRead;
(ExistenceProof.Data memory r, ) = ExistenceProof._decode(pointer, bs, sz);
return (r, sz + bytesRead);
}
/**
* @dev The decoder for reading a inner struct field
* @param p The offset of bytes array to start decode
* @param bs The bytes array to be decoded
* @return The decoded inner-struct
* @return The number of bytes used to decode
*/
function _decode_NonExistenceProof(uint256 p, bytes memory bs)
internal
pure
returns (NonExistenceProof.Data memory, uint)
{
uint256 pointer = p;
(uint256 sz, uint256 bytesRead) = ProtoBufRuntime._decode_varint(pointer, bs);
pointer += bytesRead;
(NonExistenceProof.Data memory r, ) = NonExistenceProof._decode(pointer, bs, sz);
return (r, sz + bytesRead);
}
/**
* @dev The decoder for reading a inner struct field
* @param p The offset of bytes array to start decode
* @param bs The bytes array to be decoded
* @return The decoded inner-struct
* @return The number of bytes used to decode
*/
function _decode_BatchProof(uint256 p, bytes memory bs)
internal
pure
returns (BatchProof.Data memory, uint)
{
uint256 pointer = p;
(uint256 sz, uint256 bytesRead) = ProtoBufRuntime._decode_varint(pointer, bs);
pointer += bytesRead;
(BatchProof.Data memory r, ) = BatchProof._decode(pointer, bs, sz);
return (r, sz + bytesRead);
}
/**
* @dev The decoder for reading a inner struct field
* @param p The offset of bytes array to start decode
* @param bs The bytes array to be decoded
* @return The decoded inner-struct
* @return The number of bytes used to decode
*/
function _decode_CompressedBatchProof(uint256 p, bytes memory bs)
internal
pure
returns (CompressedBatchProof.Data memory, uint)
{
uint256 pointer = p;
(uint256 sz, uint256 bytesRead) = ProtoBufRuntime._decode_varint(pointer, bs);
pointer += bytesRead;
(CompressedBatchProof.Data memory r, ) = CompressedBatchProof._decode(pointer, bs, sz);
return (r, sz + bytesRead);
}
// Encoder section
/**
* @dev The main encoder for memory
* @param r The struct to be encoded
* @return The encoded byte array
*/
function encode(Data memory r) internal pure returns (bytes memory) {
bytes memory bs = new bytes(_estimate(r));
uint256 sz = _encode(r, 32, bs);
assembly {
mstore(bs, sz)
}
return bs;
}
// inner encoder
/**
* @dev The encoder for internal usage
* @param r The struct to be encoded
* @param p The offset of bytes array to start decode
* @param bs The bytes array to be decoded
* @return The number of bytes encoded
*/
function _encode(Data memory r, uint256 p, bytes memory bs)
internal
pure
returns (uint)
{
uint256 offset = p;
uint256 pointer = p;
pointer += ProtoBufRuntime._encode_key(
1,
ProtoBufRuntime.WireType.LengthDelim,
pointer,
bs
);
pointer += ExistenceProof._encode_nested(r.exist, pointer, bs);
pointer += ProtoBufRuntime._encode_key(
2,
ProtoBufRuntime.WireType.LengthDelim,
pointer,
bs
);
pointer += NonExistenceProof._encode_nested(r.nonexist, pointer, bs);
pointer += ProtoBufRuntime._encode_key(
3,
ProtoBufRuntime.WireType.LengthDelim,
pointer,
bs
);
pointer += BatchProof._encode_nested(r.batch, pointer, bs);
pointer += ProtoBufRuntime._encode_key(
4,
ProtoBufRuntime.WireType.LengthDelim,
pointer,
bs
);
pointer += CompressedBatchProof._encode_nested(r.compressed, pointer, bs);
return pointer - offset;
}
// nested encoder
/**
* @dev The encoder for inner struct
* @param r The struct to be encoded
* @param p The offset of bytes array to start decode
* @param bs The bytes array to be decoded
* @return The number of bytes encoded
*/
function _encode_nested(Data memory r, uint256 p, bytes memory bs)
internal
pure
returns (uint)
{
/**
* First encoded `r` into a temporary array, and encode the actual size used.
* Then copy the temporary array into `bs`.
*/
uint256 offset = p;
uint256 pointer = p;
bytes memory tmp = new bytes(_estimate(r));
uint256 tmpAddr = ProtoBufRuntime.getMemoryAddress(tmp);
uint256 bsAddr = ProtoBufRuntime.getMemoryAddress(bs);
uint256 size = _encode(r, 32, tmp);
pointer += ProtoBufRuntime._encode_varint(size, pointer, bs);
ProtoBufRuntime.copyBytes(tmpAddr + 32, bsAddr + pointer, size);
pointer += size;
delete tmp;
return pointer - offset;
}
// estimator
/**
* @dev The estimator for a struct
* @param r The struct to be encoded
* @return The number of bytes encoded in estimation
*/
function _estimate(
Data memory r
) internal pure returns (uint) {
uint256 e;
e += 1 + ProtoBufRuntime._sz_lendelim(ExistenceProof._estimate(r.exist));
e += 1 + ProtoBufRuntime._sz_lendelim(NonExistenceProof._estimate(r.nonexist));
e += 1 + ProtoBufRuntime._sz_lendelim(BatchProof._estimate(r.batch));
e += 1 + ProtoBufRuntime._sz_lendelim(CompressedBatchProof._estimate(r.compressed));
return e;
}
// empty checker
function _empty(
Data memory r
) internal pure returns (bool) {
return true;
}
//store function
/**
* @dev Store in-memory struct to storage
* @param input The in-memory struct
* @param output The in-storage struct
*/
function store(Data memory input, Data storage output) internal {
ExistenceProof.store(input.exist, output.exist);
NonExistenceProof.store(input.nonexist, output.nonexist);
BatchProof.store(input.batch, output.batch);
CompressedBatchProof.store(input.compressed, output.compressed);
}
//utility functions
/**
* @dev Return an empty struct
* @return r The empty struct
*/
function nil() internal pure returns (Data memory r) {
assembly {
r := 0
}
}
/**
* @dev Test whether a struct is empty
* @param x The struct to be tested
* @return r True if it is empty
*/
function isNil(Data memory x) internal pure returns (bool r) {
assembly {
r := iszero(x)
}
}
}
//library CommitmentProof
library LeafOp {
//struct definition
struct Data {
PROOFS_PROTO_GLOBAL_ENUMS.HashOp hash;
PROOFS_PROTO_GLOBAL_ENUMS.HashOp prehash_key;
PROOFS_PROTO_GLOBAL_ENUMS.HashOp prehash_value;
PROOFS_PROTO_GLOBAL_ENUMS.LengthOp length;
bytes prefix;
}
// Decoder section
/**
* @dev The main decoder for memory
* @param bs The bytes array to be decoded
* @return The decoded struct
*/
function decode(bytes memory bs) internal pure returns (Data memory) {
(Data memory x, ) = _decode(32, bs, bs.length);
return x;
}
/**
* @dev The main decoder for storage
* @param self The in-storage struct
* @param bs The bytes array to be decoded
*/
function decode(Data storage self, bytes memory bs) internal {
(Data memory x, ) = _decode(32, bs, bs.length);
store(x, self);
}
// inner decoder
/**
* @dev The decoder for internal usage
* @param p The offset of bytes array to start decode
* @param bs The bytes array to be decoded
* @param sz The number of bytes expected
* @return The decoded struct
* @return The number of bytes decoded
*/
function _decode(uint256 p, bytes memory bs, uint256 sz)
internal
pure
returns (Data memory, uint)
{
Data memory r;
uint[6] memory counters;
uint256 fieldId;
ProtoBufRuntime.WireType wireType;
uint256 bytesRead;
uint256 offset = p;
uint256 pointer = p;
while (pointer < offset + sz) {
(fieldId, wireType, bytesRead) = ProtoBufRuntime._decode_key(pointer, bs);
pointer += bytesRead;
if (fieldId == 1) {
pointer += _read_hash(pointer, bs, r, counters);
}
else if (fieldId == 2) {
pointer += _read_prehash_key(pointer, bs, r, counters);
}
else if (fieldId == 3) {
pointer += _read_prehash_value(pointer, bs, r, counters);
}
else if (fieldId == 4) {
pointer += _read_length(pointer, bs, r, counters);
}
else if (fieldId == 5) {
pointer += _read_prefix(pointer, bs, r, counters);
}
else {
if (wireType == ProtoBufRuntime.WireType.Fixed64) {
uint256 size;
(, size) = ProtoBufRuntime._decode_fixed64(pointer, bs);
pointer += size;
}
if (wireType == ProtoBufRuntime.WireType.Fixed32) {
uint256 size;
(, size) = ProtoBufRuntime._decode_fixed32(pointer, bs);
pointer += size;
}
if (wireType == ProtoBufRuntime.WireType.Varint) {
uint256 size;
(, size) = ProtoBufRuntime._decode_varint(pointer, bs);
pointer += size;
}
if (wireType == ProtoBufRuntime.WireType.LengthDelim) {
uint256 size;
(, size) = ProtoBufRuntime._decode_lendelim(pointer, bs);
pointer += size;
}
}
}
return (r, sz);
}
// field readers
/**
* @dev The decoder for reading a field
* @param p The offset of bytes array to start decode
* @param bs The bytes array to be decoded
* @param r The in-memory struct
* @param counters The counters for repeated fields
* @return The number of bytes decoded
*/
function _read_hash(
uint256 p,
bytes memory bs,
Data memory r,
uint[6] memory counters
) internal pure returns (uint) {
/**
* if `r` is NULL, then only counting the number of fields.
*/
(int64 tmp, uint256 sz) = ProtoBufRuntime._decode_enum(p, bs);
PROOFS_PROTO_GLOBAL_ENUMS.HashOp x = PROOFS_PROTO_GLOBAL_ENUMS.decode_HashOp(tmp);
if (isNil(r)) {
counters[1] += 1;
} else {
r.hash = x;
if(counters[1] > 0) counters[1] -= 1;
}
return sz;
}
/**
* @dev The decoder for reading a field
* @param p The offset of bytes array to start decode
* @param bs The bytes array to be decoded
* @param r The in-memory struct
* @param counters The counters for repeated fields
* @return The number of bytes decoded
*/
function _read_prehash_key(
uint256 p,
bytes memory bs,
Data memory r,
uint[6] memory counters
) internal pure returns (uint) {
/**
* if `r` is NULL, then only counting the number of fields.
*/
(int64 tmp, uint256 sz) = ProtoBufRuntime._decode_enum(p, bs);
PROOFS_PROTO_GLOBAL_ENUMS.HashOp x = PROOFS_PROTO_GLOBAL_ENUMS.decode_HashOp(tmp);
if (isNil(r)) {
counters[2] += 1;
} else {
r.prehash_key = x;
if(counters[2] > 0) counters[2] -= 1;
}
return sz;
}
/**
* @dev The decoder for reading a field
* @param p The offset of bytes array to start decode
* @param bs The bytes array to be decoded
* @param r The in-memory struct
* @param counters The counters for repeated fields
* @return The number of bytes decoded
*/
function _read_prehash_value(
uint256 p,
bytes memory bs,
Data memory r,
uint[6] memory counters
) internal pure returns (uint) {
/**
* if `r` is NULL, then only counting the number of fields.
*/
(int64 tmp, uint256 sz) = ProtoBufRuntime._decode_enum(p, bs);
PROOFS_PROTO_GLOBAL_ENUMS.HashOp x = PROOFS_PROTO_GLOBAL_ENUMS.decode_HashOp(tmp);
if (isNil(r)) {
counters[3] += 1;
} else {
r.prehash_value = x;
if(counters[3] > 0) counters[3] -= 1;
}
return sz;
}
/**
* @dev The decoder for reading a field
* @param p The offset of bytes array to start decode
* @param bs The bytes array to be decoded
* @param r The in-memory struct
* @param counters The counters for repeated fields
* @return The number of bytes decoded
*/
function _read_length(
uint256 p,
bytes memory bs,
Data memory r,
uint[6] memory counters
) internal pure returns (uint) {
/**
* if `r` is NULL, then only counting the number of fields.
*/
(int64 tmp, uint256 sz) = ProtoBufRuntime._decode_enum(p, bs);
PROOFS_PROTO_GLOBAL_ENUMS.LengthOp x = PROOFS_PROTO_GLOBAL_ENUMS.decode_LengthOp(tmp);
if (isNil(r)) {
counters[4] += 1;
} else {
r.length = x;
if(counters[4] > 0) counters[4] -= 1;
}
return sz;
}
/**
* @dev The decoder for reading a field
* @param p The offset of bytes array to start decode
* @param bs The bytes array to be decoded
* @param r The in-memory struct
* @param counters The counters for repeated fields
* @return The number of bytes decoded
*/
function _read_prefix(
uint256 p,
bytes memory bs,
Data memory r,
uint[6] memory counters
) internal pure returns (uint) {
/**
* if `r` is NULL, then only counting the number of fields.
*/
(bytes memory x, uint256 sz) = ProtoBufRuntime._decode_bytes(p, bs);
if (isNil(r)) {
counters[5] += 1;
} else {
r.prefix = x;
if (counters[5] > 0) counters[5] -= 1;
}
return sz;
}
// Encoder section
/**
* @dev The main encoder for memory
* @param r The struct to be encoded
* @return The encoded byte array
*/
function encode(Data memory r) internal pure returns (bytes memory) {
bytes memory bs = new bytes(_estimate(r));
uint256 sz = _encode(r, 32, bs);
assembly {
mstore(bs, sz)
}
return bs;
}
// inner encoder
/**
* @dev The encoder for internal usage
* @param r The struct to be encoded
* @param p The offset of bytes array to start decode
* @param bs The bytes array to be decoded
* @return The number of bytes encoded
*/
function _encode(Data memory r, uint256 p, bytes memory bs)
internal
pure
returns (uint)
{
uint256 offset = p;
uint256 pointer = p;
if (uint(r.hash) != 0) {
pointer += ProtoBufRuntime._encode_key(
1,
ProtoBufRuntime.WireType.Varint,
pointer,
bs
);
int32 _enum_hash = PROOFS_PROTO_GLOBAL_ENUMS.encode_HashOp(r.hash);
pointer += ProtoBufRuntime._encode_enum(_enum_hash, pointer, bs);
}
if (uint(r.prehash_key) != 0) {
pointer += ProtoBufRuntime._encode_key(
2,
ProtoBufRuntime.WireType.Varint,
pointer,
bs
);
int32 _enum_prehash_key = PROOFS_PROTO_GLOBAL_ENUMS.encode_HashOp(r.prehash_key);
pointer += ProtoBufRuntime._encode_enum(_enum_prehash_key, pointer, bs);
}
if (uint(r.prehash_value) != 0) {
pointer += ProtoBufRuntime._encode_key(
3,
ProtoBufRuntime.WireType.Varint,
pointer,
bs
);
int32 _enum_prehash_value = PROOFS_PROTO_GLOBAL_ENUMS.encode_HashOp(r.prehash_value);
pointer += ProtoBufRuntime._encode_enum(_enum_prehash_value, pointer, bs);
}
if (uint(r.length) != 0) {
pointer += ProtoBufRuntime._encode_key(
4,
ProtoBufRuntime.WireType.Varint,
pointer,
bs
);
int32 _enum_length = PROOFS_PROTO_GLOBAL_ENUMS.encode_LengthOp(r.length);
pointer += ProtoBufRuntime._encode_enum(_enum_length, pointer, bs);
}
if (r.prefix.length != 0) {
pointer += ProtoBufRuntime._encode_key(
5,
ProtoBufRuntime.WireType.LengthDelim,
pointer,
bs
);
pointer += ProtoBufRuntime._encode_bytes(r.prefix, pointer, bs);
}
return pointer - offset;
}
// nested encoder
/**
* @dev The encoder for inner struct
* @param r The struct to be encoded
* @param p The offset of bytes array to start decode
* @param bs The bytes array to be decoded
* @return The number of bytes encoded
*/
function _encode_nested(Data memory r, uint256 p, bytes memory bs)
internal
pure
returns (uint)
{
/**
* First encoded `r` into a temporary array, and encode the actual size used.
* Then copy the temporary array into `bs`.
*/
uint256 offset = p;
uint256 pointer = p;
bytes memory tmp = new bytes(_estimate(r));
uint256 tmpAddr = ProtoBufRuntime.getMemoryAddress(tmp);
uint256 bsAddr = ProtoBufRuntime.getMemoryAddress(bs);
uint256 size = _encode(r, 32, tmp);
pointer += ProtoBufRuntime._encode_varint(size, pointer, bs);
ProtoBufRuntime.copyBytes(tmpAddr + 32, bsAddr + pointer, size);
pointer += size;
delete tmp;
return pointer - offset;
}
// estimator
/**
* @dev The estimator for a struct
* @param r The struct to be encoded
* @return The number of bytes encoded in estimation
*/
function _estimate(
Data memory r
) internal pure returns (uint) {
uint256 e;
e += 1 + ProtoBufRuntime._sz_enum(PROOFS_PROTO_GLOBAL_ENUMS.encode_HashOp(r.hash));
e += 1 + ProtoBufRuntime._sz_enum(PROOFS_PROTO_GLOBAL_ENUMS.encode_HashOp(r.prehash_key));
e += 1 + ProtoBufRuntime._sz_enum(PROOFS_PROTO_GLOBAL_ENUMS.encode_HashOp(r.prehash_value));
e += 1 + ProtoBufRuntime._sz_enum(PROOFS_PROTO_GLOBAL_ENUMS.encode_LengthOp(r.length));
e += 1 + ProtoBufRuntime._sz_lendelim(r.prefix.length);
return e;
}
// empty checker
function _empty(
Data memory r
) internal pure returns (bool) {
if (uint(r.hash) != 0) {
return false;
}
if (uint(r.prehash_key) != 0) {
return false;
}
if (uint(r.prehash_value) != 0) {
return false;
}
if (uint(r.length) != 0) {
return false;
}
if (r.prefix.length != 0) {
return false;
}
return true;
}
//store function
/**
* @dev Store in-memory struct to storage
* @param input The in-memory struct
* @param output The in-storage struct
*/
function store(Data memory input, Data storage output) internal {
output.hash = input.hash;
output.prehash_key = input.prehash_key;
output.prehash_value = input.prehash_value;
output.length = input.length;
output.prefix = input.prefix;
}
//utility functions
/**
* @dev Return an empty struct
* @return r The empty struct
*/
function nil() internal pure returns (Data memory r) {
assembly {
r := 0
}
}
/**
* @dev Test whether a struct is empty
* @param x The struct to be tested
* @return r True if it is empty
*/
function isNil(Data memory x) internal pure returns (bool r) {
assembly {
r := iszero(x)
}
}
}
//library LeafOp
library InnerOp {
//struct definition
struct Data {
PROOFS_PROTO_GLOBAL_ENUMS.HashOp hash;
bytes prefix;
bytes suffix;
}
// Decoder section
/**
* @dev The main decoder for memory
* @param bs The bytes array to be decoded
* @return The decoded struct
*/
function decode(bytes memory bs) internal pure returns (Data memory) {
(Data memory x, ) = _decode(32, bs, bs.length);
return x;
}
/**
* @dev The main decoder for storage
* @param self The in-storage struct
* @param bs The bytes array to be decoded
*/
function decode(Data storage self, bytes memory bs) internal {
(Data memory x, ) = _decode(32, bs, bs.length);
store(x, self);
}
// inner decoder
/**
* @dev The decoder for internal usage
* @param p The offset of bytes array to start decode
* @param bs The bytes array to be decoded
* @param sz The number of bytes expected
* @return The decoded struct
* @return The number of bytes decoded
*/
function _decode(uint256 p, bytes memory bs, uint256 sz)
internal
pure
returns (Data memory, uint)
{
Data memory r;
uint[4] memory counters;
uint256 fieldId;
ProtoBufRuntime.WireType wireType;
uint256 bytesRead;
uint256 offset = p;
uint256 pointer = p;
while (pointer < offset + sz) {
(fieldId, wireType, bytesRead) = ProtoBufRuntime._decode_key(pointer, bs);
pointer += bytesRead;
if (fieldId == 1) {
pointer += _read_hash(pointer, bs, r, counters);
}
else if (fieldId == 2) {
pointer += _read_prefix(pointer, bs, r, counters);
}
else if (fieldId == 3) {
pointer += _read_suffix(pointer, bs, r, counters);
}
else {
if (wireType == ProtoBufRuntime.WireType.Fixed64) {
uint256 size;
(, size) = ProtoBufRuntime._decode_fixed64(pointer, bs);
pointer += size;
}
if (wireType == ProtoBufRuntime.WireType.Fixed32) {
uint256 size;
(, size) = ProtoBufRuntime._decode_fixed32(pointer, bs);
pointer += size;
}
if (wireType == ProtoBufRuntime.WireType.Varint) {
uint256 size;
(, size) = ProtoBufRuntime._decode_varint(pointer, bs);
pointer += size;
}
if (wireType == ProtoBufRuntime.WireType.LengthDelim) {
uint256 size;
(, size) = ProtoBufRuntime._decode_lendelim(pointer, bs);
pointer += size;
}
}
}
return (r, sz);
}
// field readers
/**
* @dev The decoder for reading a field
* @param p The offset of bytes array to start decode
* @param bs The bytes array to be decoded
* @param r The in-memory struct
* @param counters The counters for repeated fields
* @return The number of bytes decoded
*/
function _read_hash(
uint256 p,
bytes memory bs,
Data memory r,
uint[4] memory counters
) internal pure returns (uint) {
/**
* if `r` is NULL, then only counting the number of fields.
*/
(int64 tmp, uint256 sz) = ProtoBufRuntime._decode_enum(p, bs);
PROOFS_PROTO_GLOBAL_ENUMS.HashOp x = PROOFS_PROTO_GLOBAL_ENUMS.decode_HashOp(tmp);
if (isNil(r)) {
counters[1] += 1;
} else {
r.hash = x;
if(counters[1] > 0) counters[1] -= 1;
}
return sz;
}
/**
* @dev The decoder for reading a field
* @param p The offset of bytes array to start decode
* @param bs The bytes array to be decoded
* @param r The in-memory struct
* @param counters The counters for repeated fields
* @return The number of bytes decoded
*/
function _read_prefix(
uint256 p,
bytes memory bs,
Data memory r,
uint[4] memory counters
) internal pure returns (uint) {
/**
* if `r` is NULL, then only counting the number of fields.
*/
(bytes memory x, uint256 sz) = ProtoBufRuntime._decode_bytes(p, bs);
if (isNil(r)) {
counters[2] += 1;
} else {
r.prefix = x;
if (counters[2] > 0) counters[2] -= 1;
}
return sz;
}
/**
* @dev The decoder for reading a field
* @param p The offset of bytes array to start decode
* @param bs The bytes array to be decoded
* @param r The in-memory struct
* @param counters The counters for repeated fields
* @return The number of bytes decoded
*/
function _read_suffix(
uint256 p,
bytes memory bs,
Data memory r,
uint[4] memory counters
) internal pure returns (uint) {
/**
* if `r` is NULL, then only counting the number of fields.
*/
(bytes memory x, uint256 sz) = ProtoBufRuntime._decode_bytes(p, bs);
if (isNil(r)) {
counters[3] += 1;
} else {
r.suffix = x;
if (counters[3] > 0) counters[3] -= 1;
}
return sz;
}
// Encoder section
/**
* @dev The main encoder for memory
* @param r The struct to be encoded
* @return The encoded byte array
*/
function encode(Data memory r) internal pure returns (bytes memory) {
bytes memory bs = new bytes(_estimate(r));
uint256 sz = _encode(r, 32, bs);
assembly {
mstore(bs, sz)
}
return bs;
}
// inner encoder
/**
* @dev The encoder for internal usage
* @param r The struct to be encoded
* @param p The offset of bytes array to start decode
* @param bs The bytes array to be decoded
* @return The number of bytes encoded
*/
function _encode(Data memory r, uint256 p, bytes memory bs)
internal
pure
returns (uint)
{
uint256 offset = p;
uint256 pointer = p;
if (uint(r.hash) != 0) {
pointer += ProtoBufRuntime._encode_key(
1,
ProtoBufRuntime.WireType.Varint,
pointer,
bs
);
int32 _enum_hash = PROOFS_PROTO_GLOBAL_ENUMS.encode_HashOp(r.hash);
pointer += ProtoBufRuntime._encode_enum(_enum_hash, pointer, bs);
}
if (r.prefix.length != 0) {
pointer += ProtoBufRuntime._encode_key(
2,
ProtoBufRuntime.WireType.LengthDelim,
pointer,
bs
);
pointer += ProtoBufRuntime._encode_bytes(r.prefix, pointer, bs);
}
if (r.suffix.length != 0) {
pointer += ProtoBufRuntime._encode_key(
3,
ProtoBufRuntime.WireType.LengthDelim,
pointer,
bs
);
pointer += ProtoBufRuntime._encode_bytes(r.suffix, pointer, bs);
}
return pointer - offset;
}
// nested encoder
/**
* @dev The encoder for inner struct
* @param r The struct to be encoded
* @param p The offset of bytes array to start decode
* @param bs The bytes array to be decoded
* @return The number of bytes encoded
*/
function _encode_nested(Data memory r, uint256 p, bytes memory bs)
internal
pure
returns (uint)
{
/**
* First encoded `r` into a temporary array, and encode the actual size used.
* Then copy the temporary array into `bs`.
*/
uint256 offset = p;
uint256 pointer = p;
bytes memory tmp = new bytes(_estimate(r));
uint256 tmpAddr = ProtoBufRuntime.getMemoryAddress(tmp);
uint256 bsAddr = ProtoBufRuntime.getMemoryAddress(bs);
uint256 size = _encode(r, 32, tmp);
pointer += ProtoBufRuntime._encode_varint(size, pointer, bs);
ProtoBufRuntime.copyBytes(tmpAddr + 32, bsAddr + pointer, size);
pointer += size;
delete tmp;
return pointer - offset;
}
// estimator
/**
* @dev The estimator for a struct
* @param r The struct to be encoded
* @return The number of bytes encoded in estimation
*/
function _estimate(
Data memory r
) internal pure returns (uint) {
uint256 e;
e += 1 + ProtoBufRuntime._sz_enum(PROOFS_PROTO_GLOBAL_ENUMS.encode_HashOp(r.hash));
e += 1 + ProtoBufRuntime._sz_lendelim(r.prefix.length);
e += 1 + ProtoBufRuntime._sz_lendelim(r.suffix.length);
return e;
}
// empty checker
function _empty(
Data memory r
) internal pure returns (bool) {
if (uint(r.hash) != 0) {
return false;
}
if (r.prefix.length != 0) {
return false;
}
if (r.suffix.length != 0) {
return false;
}
return true;
}
//store function
/**
* @dev Store in-memory struct to storage
* @param input The in-memory struct
* @param output The in-storage struct
*/
function store(Data memory input, Data storage output) internal {
output.hash = input.hash;
output.prefix = input.prefix;
output.suffix = input.suffix;
}
//utility functions
/**
* @dev Return an empty struct
* @return r The empty struct
*/
function nil() internal pure returns (Data memory r) {
assembly {
r := 0
}
}
/**
* @dev Test whether a struct is empty
* @param x The struct to be tested
* @return r True if it is empty
*/
function isNil(Data memory x) internal pure returns (bool r) {
assembly {
r := iszero(x)
}
}
}
//library InnerOp
library ProofSpec {
//struct definition
struct Data {
LeafOp.Data leaf_spec;
InnerSpec.Data inner_spec;
int32 max_depth;
int32 min_depth;
}
// Decoder section
/**
* @dev The main decoder for memory
* @param bs The bytes array to be decoded
* @return The decoded struct
*/
function decode(bytes memory bs) internal pure returns (Data memory) {
(Data memory x, ) = _decode(32, bs, bs.length);
return x;
}
/**
* @dev The main decoder for storage
* @param self The in-storage struct
* @param bs The bytes array to be decoded
*/
function decode(Data storage self, bytes memory bs) internal {
(Data memory x, ) = _decode(32, bs, bs.length);
store(x, self);
}
// inner decoder
/**
* @dev The decoder for internal usage
* @param p The offset of bytes array to start decode
* @param bs The bytes array to be decoded
* @param sz The number of bytes expected
* @return The decoded struct
* @return The number of bytes decoded
*/
function _decode(uint256 p, bytes memory bs, uint256 sz)
internal
pure
returns (Data memory, uint)
{
Data memory r;
uint[5] memory counters;
uint256 fieldId;
ProtoBufRuntime.WireType wireType;
uint256 bytesRead;
uint256 offset = p;
uint256 pointer = p;
while (pointer < offset + sz) {
(fieldId, wireType, bytesRead) = ProtoBufRuntime._decode_key(pointer, bs);
pointer += bytesRead;
if (fieldId == 1) {
pointer += _read_leaf_spec(pointer, bs, r, counters);
}
else if (fieldId == 2) {
pointer += _read_inner_spec(pointer, bs, r, counters);
}
else if (fieldId == 3) {
pointer += _read_max_depth(pointer, bs, r, counters);
}
else if (fieldId == 4) {
pointer += _read_min_depth(pointer, bs, r, counters);
}
else {
if (wireType == ProtoBufRuntime.WireType.Fixed64) {
uint256 size;
(, size) = ProtoBufRuntime._decode_fixed64(pointer, bs);
pointer += size;
}
if (wireType == ProtoBufRuntime.WireType.Fixed32) {
uint256 size;
(, size) = ProtoBufRuntime._decode_fixed32(pointer, bs);
pointer += size;
}
if (wireType == ProtoBufRuntime.WireType.Varint) {
uint256 size;
(, size) = ProtoBufRuntime._decode_varint(pointer, bs);
pointer += size;
}
if (wireType == ProtoBufRuntime.WireType.LengthDelim) {
uint256 size;
(, size) = ProtoBufRuntime._decode_lendelim(pointer, bs);
pointer += size;
}
}
}
return (r, sz);
}
// field readers
/**
* @dev The decoder for reading a field
* @param p The offset of bytes array to start decode
* @param bs The bytes array to be decoded
* @param r The in-memory struct
* @param counters The counters for repeated fields
* @return The number of bytes decoded
*/
function _read_leaf_spec(
uint256 p,
bytes memory bs,
Data memory r,
uint[5] memory counters
) internal pure returns (uint) {
/**
* if `r` is NULL, then only counting the number of fields.
*/
(LeafOp.Data memory x, uint256 sz) = _decode_LeafOp(p, bs);
if (isNil(r)) {
counters[1] += 1;
} else {
r.leaf_spec = x;
if (counters[1] > 0) counters[1] -= 1;
}
return sz;
}
/**
* @dev The decoder for reading a field
* @param p The offset of bytes array to start decode
* @param bs The bytes array to be decoded
* @param r The in-memory struct
* @param counters The counters for repeated fields
* @return The number of bytes decoded
*/
function _read_inner_spec(
uint256 p,
bytes memory bs,
Data memory r,
uint[5] memory counters
) internal pure returns (uint) {
/**
* if `r` is NULL, then only counting the number of fields.
*/
(InnerSpec.Data memory x, uint256 sz) = _decode_InnerSpec(p, bs);
if (isNil(r)) {
counters[2] += 1;
} else {
r.inner_spec = x;
if (counters[2] > 0) counters[2] -= 1;
}
return sz;
}
/**
* @dev The decoder for reading a field
* @param p The offset of bytes array to start decode
* @param bs The bytes array to be decoded
* @param r The in-memory struct
* @param counters The counters for repeated fields
* @return The number of bytes decoded
*/
function _read_max_depth(
uint256 p,
bytes memory bs,
Data memory r,
uint[5] memory counters
) internal pure returns (uint) {
/**
* if `r` is NULL, then only counting the number of fields.
*/
(int32 x, uint256 sz) = ProtoBufRuntime._decode_int32(p, bs);
if (isNil(r)) {
counters[3] += 1;
} else {
r.max_depth = x;
if (counters[3] > 0) counters[3] -= 1;
}
return sz;
}
/**
* @dev The decoder for reading a field
* @param p The offset of bytes array to start decode
* @param bs The bytes array to be decoded
* @param r The in-memory struct
* @param counters The counters for repeated fields
* @return The number of bytes decoded
*/
function _read_min_depth(
uint256 p,
bytes memory bs,
Data memory r,
uint[5] memory counters
) internal pure returns (uint) {
/**
* if `r` is NULL, then only counting the number of fields.
*/
(int32 x, uint256 sz) = ProtoBufRuntime._decode_int32(p, bs);
if (isNil(r)) {
counters[4] += 1;
} else {
r.min_depth = x;
if (counters[4] > 0) counters[4] -= 1;
}
return sz;
}
// struct decoder
/**
* @dev The decoder for reading a inner struct field
* @param p The offset of bytes array to start decode
* @param bs The bytes array to be decoded
* @return The decoded inner-struct
* @return The number of bytes used to decode
*/
function _decode_LeafOp(uint256 p, bytes memory bs)
internal
pure
returns (LeafOp.Data memory, uint)
{
uint256 pointer = p;
(uint256 sz, uint256 bytesRead) = ProtoBufRuntime._decode_varint(pointer, bs);
pointer += bytesRead;
(LeafOp.Data memory r, ) = LeafOp._decode(pointer, bs, sz);
return (r, sz + bytesRead);
}
/**
* @dev The decoder for reading a inner struct field
* @param p The offset of bytes array to start decode
* @param bs The bytes array to be decoded
* @return The decoded inner-struct
* @return The number of bytes used to decode
*/
function _decode_InnerSpec(uint256 p, bytes memory bs)
internal
pure
returns (InnerSpec.Data memory, uint)
{
uint256 pointer = p;
(uint256 sz, uint256 bytesRead) = ProtoBufRuntime._decode_varint(pointer, bs);
pointer += bytesRead;
(InnerSpec.Data memory r, ) = InnerSpec._decode(pointer, bs, sz);
return (r, sz + bytesRead);
}
// Encoder section
/**
* @dev The main encoder for memory
* @param r The struct to be encoded
* @return The encoded byte array
*/
function encode(Data memory r) internal pure returns (bytes memory) {
bytes memory bs = new bytes(_estimate(r));
uint256 sz = _encode(r, 32, bs);
assembly {
mstore(bs, sz)
}
return bs;
}
// inner encoder
/**
* @dev The encoder for internal usage
* @param r The struct to be encoded
* @param p The offset of bytes array to start decode
* @param bs The bytes array to be decoded
* @return The number of bytes encoded
*/
function _encode(Data memory r, uint256 p, bytes memory bs)
internal
pure
returns (uint)
{
uint256 offset = p;
uint256 pointer = p;
pointer += ProtoBufRuntime._encode_key(
1,
ProtoBufRuntime.WireType.LengthDelim,
pointer,
bs
);
pointer += LeafOp._encode_nested(r.leaf_spec, pointer, bs);
pointer += ProtoBufRuntime._encode_key(
2,
ProtoBufRuntime.WireType.LengthDelim,
pointer,
bs
);
pointer += InnerSpec._encode_nested(r.inner_spec, pointer, bs);
if (r.max_depth != 0) {
pointer += ProtoBufRuntime._encode_key(
3,
ProtoBufRuntime.WireType.Varint,
pointer,
bs
);
pointer += ProtoBufRuntime._encode_int32(r.max_depth, pointer, bs);
}
if (r.min_depth != 0) {
pointer += ProtoBufRuntime._encode_key(
4,
ProtoBufRuntime.WireType.Varint,
pointer,
bs
);
pointer += ProtoBufRuntime._encode_int32(r.min_depth, pointer, bs);
}
return pointer - offset;
}
// nested encoder
/**
* @dev The encoder for inner struct
* @param r The struct to be encoded
* @param p The offset of bytes array to start decode
* @param bs The bytes array to be decoded
* @return The number of bytes encoded
*/
function _encode_nested(Data memory r, uint256 p, bytes memory bs)
internal
pure
returns (uint)
{
/**
* First encoded `r` into a temporary array, and encode the actual size used.
* Then copy the temporary array into `bs`.
*/
uint256 offset = p;
uint256 pointer = p;
bytes memory tmp = new bytes(_estimate(r));
uint256 tmpAddr = ProtoBufRuntime.getMemoryAddress(tmp);
uint256 bsAddr = ProtoBufRuntime.getMemoryAddress(bs);
uint256 size = _encode(r, 32, tmp);
pointer += ProtoBufRuntime._encode_varint(size, pointer, bs);
ProtoBufRuntime.copyBytes(tmpAddr + 32, bsAddr + pointer, size);
pointer += size;
delete tmp;
return pointer - offset;
}
// estimator
/**
* @dev The estimator for a struct
* @param r The struct to be encoded
* @return The number of bytes encoded in estimation
*/
function _estimate(
Data memory r
) internal pure returns (uint) {
uint256 e;
e += 1 + ProtoBufRuntime._sz_lendelim(LeafOp._estimate(r.leaf_spec));
e += 1 + ProtoBufRuntime._sz_lendelim(InnerSpec._estimate(r.inner_spec));
e += 1 + ProtoBufRuntime._sz_int32(r.max_depth);
e += 1 + ProtoBufRuntime._sz_int32(r.min_depth);
return e;
}
// empty checker
function _empty(
Data memory r
) internal pure returns (bool) {
if (r.max_depth != 0) {
return false;
}
if (r.min_depth != 0) {
return false;
}
return true;
}
//store function
/**
* @dev Store in-memory struct to storage
* @param input The in-memory struct
* @param output The in-storage struct
*/
function store(Data memory input, Data storage output) internal {
LeafOp.store(input.leaf_spec, output.leaf_spec);
InnerSpec.store(input.inner_spec, output.inner_spec);
output.max_depth = input.max_depth;
output.min_depth = input.min_depth;
}
//utility functions
/**
* @dev Return an empty struct
* @return r The empty struct
*/
function nil() internal pure returns (Data memory r) {
assembly {
r := 0
}
}
/**
* @dev Test whether a struct is empty
* @param x The struct to be tested
* @return r True if it is empty
*/
function isNil(Data memory x) internal pure returns (bool r) {
assembly {
r := iszero(x)
}
}
}
//library ProofSpec
library InnerSpec {
//struct definition
struct Data {
int32[] child_order;
int32 child_size;
int32 min_prefix_length;
int32 max_prefix_length;
bytes empty_child;
PROOFS_PROTO_GLOBAL_ENUMS.HashOp hash;
}
// Decoder section
/**
* @dev The main decoder for memory
* @param bs The bytes array to be decoded
* @return The decoded struct
*/
function decode(bytes memory bs) internal pure returns (Data memory) {
(Data memory x, ) = _decode(32, bs, bs.length);
return x;
}
/**
* @dev The main decoder for storage
* @param self The in-storage struct
* @param bs The bytes array to be decoded
*/
function decode(Data storage self, bytes memory bs) internal {
(Data memory x, ) = _decode(32, bs, bs.length);
store(x, self);
}
// inner decoder
/**
* @dev The decoder for internal usage
* @param p The offset of bytes array to start decode
* @param bs The bytes array to be decoded
* @param sz The number of bytes expected
* @return The decoded struct
* @return The number of bytes decoded
*/
function _decode(uint256 p, bytes memory bs, uint256 sz)
internal
pure
returns (Data memory, uint)
{
Data memory r;
uint[7] memory counters;
uint256 fieldId;
ProtoBufRuntime.WireType wireType;
uint256 bytesRead;
uint256 offset = p;
uint256 pointer = p;
while (pointer < offset + sz) {
(fieldId, wireType, bytesRead) = ProtoBufRuntime._decode_key(pointer, bs);
pointer += bytesRead;
if (fieldId == 1) {
pointer += _read_child_order(pointer, bs, nil(), counters);
}
else if (fieldId == 2) {
pointer += _read_child_size(pointer, bs, r, counters);
}
else if (fieldId == 3) {
pointer += _read_min_prefix_length(pointer, bs, r, counters);
}
else if (fieldId == 4) {
pointer += _read_max_prefix_length(pointer, bs, r, counters);
}
else if (fieldId == 5) {
pointer += _read_empty_child(pointer, bs, r, counters);
}
else if (fieldId == 6) {
pointer += _read_hash(pointer, bs, r, counters);
}
else {
if (wireType == ProtoBufRuntime.WireType.Fixed64) {
uint256 size;
(, size) = ProtoBufRuntime._decode_fixed64(pointer, bs);
pointer += size;
}
if (wireType == ProtoBufRuntime.WireType.Fixed32) {
uint256 size;
(, size) = ProtoBufRuntime._decode_fixed32(pointer, bs);
pointer += size;
}
if (wireType == ProtoBufRuntime.WireType.Varint) {
uint256 size;
(, size) = ProtoBufRuntime._decode_varint(pointer, bs);
pointer += size;
}
if (wireType == ProtoBufRuntime.WireType.LengthDelim) {
uint256 size;
(, size) = ProtoBufRuntime._decode_lendelim(pointer, bs);
pointer += size;
}
}
}
pointer = offset;
r.child_order = new int32[](counters[1]);
while (pointer < offset + sz) {
(fieldId, wireType, bytesRead) = ProtoBufRuntime._decode_key(pointer, bs);
pointer += bytesRead;
if (fieldId == 1) {
pointer += _read_child_order(pointer, bs, r, counters);
}
else if (fieldId == 2) {
pointer += _read_child_size(pointer, bs, nil(), counters);
}
else if (fieldId == 3) {
pointer += _read_min_prefix_length(pointer, bs, nil(), counters);
}
else if (fieldId == 4) {
pointer += _read_max_prefix_length(pointer, bs, nil(), counters);
}
else if (fieldId == 5) {
pointer += _read_empty_child(pointer, bs, nil(), counters);
}
else if (fieldId == 6) {
pointer += _read_hash(pointer, bs, nil(), counters);
}
else {
if (wireType == ProtoBufRuntime.WireType.Fixed64) {
uint256 size;
(, size) = ProtoBufRuntime._decode_fixed64(pointer, bs);
pointer += size;
}
if (wireType == ProtoBufRuntime.WireType.Fixed32) {
uint256 size;
(, size) = ProtoBufRuntime._decode_fixed32(pointer, bs);
pointer += size;
}
if (wireType == ProtoBufRuntime.WireType.Varint) {
uint256 size;
(, size) = ProtoBufRuntime._decode_varint(pointer, bs);
pointer += size;
}
if (wireType == ProtoBufRuntime.WireType.LengthDelim) {
uint256 size;
(, size) = ProtoBufRuntime._decode_lendelim(pointer, bs);
pointer += size;
}
}
}
return (r, sz);
}
// field readers
/**
* @dev The decoder for reading a field
* @param p The offset of bytes array to start decode
* @param bs The bytes array to be decoded
* @param r The in-memory struct
* @param counters The counters for repeated fields
* @return The number of bytes decoded
*/
function _read_child_order(
uint256 p,
bytes memory bs,
Data memory r,
uint[7] memory counters
) internal pure returns (uint) {
/**
* if `r` is NULL, then only counting the number of fields.
*/
(int32 x, uint256 sz) = ProtoBufRuntime._decode_int32(p, bs);
if (isNil(r)) {
counters[1] += 1;
} else {
r.child_order[r.child_order.length - counters[1]] = x;
if (counters[1] > 0) counters[1] -= 1;
}
return sz;
}
/**
* @dev The decoder for reading a field
* @param p The offset of bytes array to start decode
* @param bs The bytes array to be decoded
* @param r The in-memory struct
* @param counters The counters for repeated fields
* @return The number of bytes decoded
*/
function _read_child_size(
uint256 p,
bytes memory bs,
Data memory r,
uint[7] memory counters
) internal pure returns (uint) {
/**
* if `r` is NULL, then only counting the number of fields.
*/
(int32 x, uint256 sz) = ProtoBufRuntime._decode_int32(p, bs);
if (isNil(r)) {
counters[2] += 1;
} else {
r.child_size = x;
if (counters[2] > 0) counters[2] -= 1;
}
return sz;
}
/**
* @dev The decoder for reading a field
* @param p The offset of bytes array to start decode
* @param bs The bytes array to be decoded
* @param r The in-memory struct
* @param counters The counters for repeated fields
* @return The number of bytes decoded
*/
function _read_min_prefix_length(
uint256 p,
bytes memory bs,
Data memory r,
uint[7] memory counters
) internal pure returns (uint) {
/**
* if `r` is NULL, then only counting the number of fields.
*/
(int32 x, uint256 sz) = ProtoBufRuntime._decode_int32(p, bs);
if (isNil(r)) {
counters[3] += 1;
} else {
r.min_prefix_length = x;
if (counters[3] > 0) counters[3] -= 1;
}
return sz;
}
/**
* @dev The decoder for reading a field
* @param p The offset of bytes array to start decode
* @param bs The bytes array to be decoded
* @param r The in-memory struct
* @param counters The counters for repeated fields
* @return The number of bytes decoded
*/
function _read_max_prefix_length(
uint256 p,
bytes memory bs,
Data memory r,
uint[7] memory counters
) internal pure returns (uint) {
/**
* if `r` is NULL, then only counting the number of fields.
*/
(int32 x, uint256 sz) = ProtoBufRuntime._decode_int32(p, bs);
if (isNil(r)) {
counters[4] += 1;
} else {
r.max_prefix_length = x;
if (counters[4] > 0) counters[4] -= 1;
}
return sz;
}
/**
* @dev The decoder for reading a field
* @param p The offset of bytes array to start decode
* @param bs The bytes array to be decoded
* @param r The in-memory struct
* @param counters The counters for repeated fields
* @return The number of bytes decoded
*/
function _read_empty_child(
uint256 p,
bytes memory bs,
Data memory r,
uint[7] memory counters
) internal pure returns (uint) {
/**
* if `r` is NULL, then only counting the number of fields.
*/
(bytes memory x, uint256 sz) = ProtoBufRuntime._decode_bytes(p, bs);
if (isNil(r)) {
counters[5] += 1;
} else {
r.empty_child = x;
if (counters[5] > 0) counters[5] -= 1;
}
return sz;
}
/**
* @dev The decoder for reading a field
* @param p The offset of bytes array to start decode
* @param bs The bytes array to be decoded
* @param r The in-memory struct
* @param counters The counters for repeated fields
* @return The number of bytes decoded
*/
function _read_hash(
uint256 p,
bytes memory bs,
Data memory r,
uint[7] memory counters
) internal pure returns (uint) {
/**
* if `r` is NULL, then only counting the number of fields.
*/
(int64 tmp, uint256 sz) = ProtoBufRuntime._decode_enum(p, bs);
PROOFS_PROTO_GLOBAL_ENUMS.HashOp x = PROOFS_PROTO_GLOBAL_ENUMS.decode_HashOp(tmp);
if (isNil(r)) {
counters[6] += 1;
} else {
r.hash = x;
if(counters[6] > 0) counters[6] -= 1;
}
return sz;
}
// Encoder section
/**
* @dev The main encoder for memory
* @param r The struct to be encoded
* @return The encoded byte array
*/
function encode(Data memory r) internal pure returns (bytes memory) {
bytes memory bs = new bytes(_estimate(r));
uint256 sz = _encode(r, 32, bs);
assembly {
mstore(bs, sz)
}
return bs;
}
// inner encoder
/**
* @dev The encoder for internal usage
* @param r The struct to be encoded
* @param p The offset of bytes array to start decode
* @param bs The bytes array to be decoded
* @return The number of bytes encoded
*/
function _encode(Data memory r, uint256 p, bytes memory bs)
internal
pure
returns (uint)
{
uint256 offset = p;
uint256 pointer = p;
uint256 i;
if (r.child_order.length != 0) {
for(i = 0; i < r.child_order.length; i++) {
pointer += ProtoBufRuntime._encode_key(
1,
ProtoBufRuntime.WireType.Varint,
pointer,
bs)
;
pointer += ProtoBufRuntime._encode_int32(r.child_order[i], pointer, bs);
}
}
if (r.child_size != 0) {
pointer += ProtoBufRuntime._encode_key(
2,
ProtoBufRuntime.WireType.Varint,
pointer,
bs
);
pointer += ProtoBufRuntime._encode_int32(r.child_size, pointer, bs);
}
if (r.min_prefix_length != 0) {
pointer += ProtoBufRuntime._encode_key(
3,
ProtoBufRuntime.WireType.Varint,
pointer,
bs
);
pointer += ProtoBufRuntime._encode_int32(r.min_prefix_length, pointer, bs);
}
if (r.max_prefix_length != 0) {
pointer += ProtoBufRuntime._encode_key(
4,
ProtoBufRuntime.WireType.Varint,
pointer,
bs
);
pointer += ProtoBufRuntime._encode_int32(r.max_prefix_length, pointer, bs);
}
if (r.empty_child.length != 0) {
pointer += ProtoBufRuntime._encode_key(
5,
ProtoBufRuntime.WireType.LengthDelim,
pointer,
bs
);
pointer += ProtoBufRuntime._encode_bytes(r.empty_child, pointer, bs);
}
if (uint(r.hash) != 0) {
pointer += ProtoBufRuntime._encode_key(
6,
ProtoBufRuntime.WireType.Varint,
pointer,
bs
);
int32 _enum_hash = PROOFS_PROTO_GLOBAL_ENUMS.encode_HashOp(r.hash);
pointer += ProtoBufRuntime._encode_enum(_enum_hash, pointer, bs);
}
return pointer - offset;
}
// nested encoder
/**
* @dev The encoder for inner struct
* @param r The struct to be encoded
* @param p The offset of bytes array to start decode
* @param bs The bytes array to be decoded
* @return The number of bytes encoded
*/
function _encode_nested(Data memory r, uint256 p, bytes memory bs)
internal
pure
returns (uint)
{
/**
* First encoded `r` into a temporary array, and encode the actual size used.
* Then copy the temporary array into `bs`.
*/
uint256 offset = p;
uint256 pointer = p;
bytes memory tmp = new bytes(_estimate(r));
uint256 tmpAddr = ProtoBufRuntime.getMemoryAddress(tmp);
uint256 bsAddr = ProtoBufRuntime.getMemoryAddress(bs);
uint256 size = _encode(r, 32, tmp);
pointer += ProtoBufRuntime._encode_varint(size, pointer, bs);
ProtoBufRuntime.copyBytes(tmpAddr + 32, bsAddr + pointer, size);
pointer += size;
delete tmp;
return pointer - offset;
}
// estimator
/**
* @dev The estimator for a struct
* @param r The struct to be encoded
* @return The number of bytes encoded in estimation
*/
function _estimate(
Data memory r
) internal pure returns (uint) {
uint256 e;uint256 i;
for(i = 0; i < r.child_order.length; i++) {
e += 1 + ProtoBufRuntime._sz_int32(r.child_order[i]);
}
e += 1 + ProtoBufRuntime._sz_int32(r.child_size);
e += 1 + ProtoBufRuntime._sz_int32(r.min_prefix_length);
e += 1 + ProtoBufRuntime._sz_int32(r.max_prefix_length);
e += 1 + ProtoBufRuntime._sz_lendelim(r.empty_child.length);
e += 1 + ProtoBufRuntime._sz_enum(PROOFS_PROTO_GLOBAL_ENUMS.encode_HashOp(r.hash));
return e;
}
// empty checker
function _empty(
Data memory r
) internal pure returns (bool) {
if (r.child_order.length != 0) {
return false;
}
if (r.child_size != 0) {
return false;
}
if (r.min_prefix_length != 0) {
return false;
}
if (r.max_prefix_length != 0) {
return false;
}
if (r.empty_child.length != 0) {
return false;
}
if (uint(r.hash) != 0) {
return false;
}
return true;
}
//store function
/**
* @dev Store in-memory struct to storage
* @param input The in-memory struct
* @param output The in-storage struct
*/
function store(Data memory input, Data storage output) internal {
output.child_order = input.child_order;
output.child_size = input.child_size;
output.min_prefix_length = input.min_prefix_length;
output.max_prefix_length = input.max_prefix_length;
output.empty_child = input.empty_child;
output.hash = input.hash;
}
//array helpers for ChildOrder
/**
* @dev Add value to an array
* @param self The in-memory struct
* @param value The value to add
*/
function addChildOrder(Data memory self, int32 value) internal pure {
/**
* First resize the array. Then add the new element to the end.
*/
int32[] memory tmp = new int32[](self.child_order.length + 1);
for (uint256 i = 0; i < self.child_order.length; i++) {
tmp[i] = self.child_order[i];
}
tmp[self.child_order.length] = value;
self.child_order = tmp;
}
//utility functions
/**
* @dev Return an empty struct
* @return r The empty struct
*/
function nil() internal pure returns (Data memory r) {
assembly {
r := 0
}
}
/**
* @dev Test whether a struct is empty
* @param x The struct to be tested
* @return r True if it is empty
*/
function isNil(Data memory x) internal pure returns (bool r) {
assembly {
r := iszero(x)
}
}
}
//library InnerSpec
library BatchProof {
//struct definition
struct Data {
BatchEntry.Data[] entries;
}
// Decoder section
/**
* @dev The main decoder for memory
* @param bs The bytes array to be decoded
* @return The decoded struct
*/
function decode(bytes memory bs) internal pure returns (Data memory) {
(Data memory x, ) = _decode(32, bs, bs.length);
return x;
}
/**
* @dev The main decoder for storage
* @param self The in-storage struct
* @param bs The bytes array to be decoded
*/
function decode(Data storage self, bytes memory bs) internal {
(Data memory x, ) = _decode(32, bs, bs.length);
store(x, self);
}
// inner decoder
/**
* @dev The decoder for internal usage
* @param p The offset of bytes array to start decode
* @param bs The bytes array to be decoded
* @param sz The number of bytes expected
* @return The decoded struct
* @return The number of bytes decoded
*/
function _decode(uint256 p, bytes memory bs, uint256 sz)
internal
pure
returns (Data memory, uint)
{
Data memory r;
uint[2] memory counters;
uint256 fieldId;
ProtoBufRuntime.WireType wireType;
uint256 bytesRead;
uint256 offset = p;
uint256 pointer = p;
while (pointer < offset + sz) {
(fieldId, wireType, bytesRead) = ProtoBufRuntime._decode_key(pointer, bs);
pointer += bytesRead;
if (fieldId == 1) {
pointer += _read_entries(pointer, bs, nil(), counters);
}
else {
if (wireType == ProtoBufRuntime.WireType.Fixed64) {
uint256 size;
(, size) = ProtoBufRuntime._decode_fixed64(pointer, bs);
pointer += size;
}
if (wireType == ProtoBufRuntime.WireType.Fixed32) {
uint256 size;
(, size) = ProtoBufRuntime._decode_fixed32(pointer, bs);
pointer += size;
}
if (wireType == ProtoBufRuntime.WireType.Varint) {
uint256 size;
(, size) = ProtoBufRuntime._decode_varint(pointer, bs);
pointer += size;
}
if (wireType == ProtoBufRuntime.WireType.LengthDelim) {
uint256 size;
(, size) = ProtoBufRuntime._decode_lendelim(pointer, bs);
pointer += size;
}
}
}
pointer = offset;
r.entries = new BatchEntry.Data[](counters[1]);
while (pointer < offset + sz) {
(fieldId, wireType, bytesRead) = ProtoBufRuntime._decode_key(pointer, bs);
pointer += bytesRead;
if (fieldId == 1) {
pointer += _read_entries(pointer, bs, r, counters);
}
else {
if (wireType == ProtoBufRuntime.WireType.Fixed64) {
uint256 size;
(, size) = ProtoBufRuntime._decode_fixed64(pointer, bs);
pointer += size;
}
if (wireType == ProtoBufRuntime.WireType.Fixed32) {
uint256 size;
(, size) = ProtoBufRuntime._decode_fixed32(pointer, bs);
pointer += size;
}
if (wireType == ProtoBufRuntime.WireType.Varint) {
uint256 size;
(, size) = ProtoBufRuntime._decode_varint(pointer, bs);
pointer += size;
}
if (wireType == ProtoBufRuntime.WireType.LengthDelim) {
uint256 size;
(, size) = ProtoBufRuntime._decode_lendelim(pointer, bs);
pointer += size;
}
}
}
return (r, sz);
}
// field readers
/**
* @dev The decoder for reading a field
* @param p The offset of bytes array to start decode
* @param bs The bytes array to be decoded
* @param r The in-memory struct
* @param counters The counters for repeated fields
* @return The number of bytes decoded
*/
function _read_entries(
uint256 p,
bytes memory bs,
Data memory r,
uint[2] memory counters
) internal pure returns (uint) {
/**
* if `r` is NULL, then only counting the number of fields.
*/
(BatchEntry.Data memory x, uint256 sz) = _decode_BatchEntry(p, bs);
if (isNil(r)) {
counters[1] += 1;
} else {
r.entries[r.entries.length - counters[1]] = x;
if (counters[1] > 0) counters[1] -= 1;
}
return sz;
}
// struct decoder
/**
* @dev The decoder for reading a inner struct field
* @param p The offset of bytes array to start decode
* @param bs The bytes array to be decoded
* @return The decoded inner-struct
* @return The number of bytes used to decode
*/
function _decode_BatchEntry(uint256 p, bytes memory bs)
internal
pure
returns (BatchEntry.Data memory, uint)
{
uint256 pointer = p;
(uint256 sz, uint256 bytesRead) = ProtoBufRuntime._decode_varint(pointer, bs);
pointer += bytesRead;
(BatchEntry.Data memory r, ) = BatchEntry._decode(pointer, bs, sz);
return (r, sz + bytesRead);
}
// Encoder section
/**
* @dev The main encoder for memory
* @param r The struct to be encoded
* @return The encoded byte array
*/
function encode(Data memory r) internal pure returns (bytes memory) {
bytes memory bs = new bytes(_estimate(r));
uint256 sz = _encode(r, 32, bs);
assembly {
mstore(bs, sz)
}
return bs;
}
// inner encoder
/**
* @dev The encoder for internal usage
* @param r The struct to be encoded
* @param p The offset of bytes array to start decode
* @param bs The bytes array to be decoded
* @return The number of bytes encoded
*/
function _encode(Data memory r, uint256 p, bytes memory bs)
internal
pure
returns (uint)
{
uint256 offset = p;
uint256 pointer = p;
uint256 i;
if (r.entries.length != 0) {
for(i = 0; i < r.entries.length; i++) {
pointer += ProtoBufRuntime._encode_key(
1,
ProtoBufRuntime.WireType.LengthDelim,
pointer,
bs)
;
pointer += BatchEntry._encode_nested(r.entries[i], pointer, bs);
}
}
return pointer - offset;
}
// nested encoder
/**
* @dev The encoder for inner struct
* @param r The struct to be encoded
* @param p The offset of bytes array to start decode
* @param bs The bytes array to be decoded
* @return The number of bytes encoded
*/
function _encode_nested(Data memory r, uint256 p, bytes memory bs)
internal
pure
returns (uint)
{
/**
* First encoded `r` into a temporary array, and encode the actual size used.
* Then copy the temporary array into `bs`.
*/
uint256 offset = p;
uint256 pointer = p;
bytes memory tmp = new bytes(_estimate(r));
uint256 tmpAddr = ProtoBufRuntime.getMemoryAddress(tmp);
uint256 bsAddr = ProtoBufRuntime.getMemoryAddress(bs);
uint256 size = _encode(r, 32, tmp);
pointer += ProtoBufRuntime._encode_varint(size, pointer, bs);
ProtoBufRuntime.copyBytes(tmpAddr + 32, bsAddr + pointer, size);
pointer += size;
delete tmp;
return pointer - offset;
}
// estimator
/**
* @dev The estimator for a struct
* @param r The struct to be encoded
* @return The number of bytes encoded in estimation
*/
function _estimate(
Data memory r
) internal pure returns (uint) {
uint256 e;uint256 i;
for(i = 0; i < r.entries.length; i++) {
e += 1 + ProtoBufRuntime._sz_lendelim(BatchEntry._estimate(r.entries[i]));
}
return e;
}
// empty checker
function _empty(
Data memory r
) internal pure returns (bool) {
if (r.entries.length != 0) {
return false;
}
return true;
}
//store function
/**
* @dev Store in-memory struct to storage
* @param input The in-memory struct
* @param output The in-storage struct
*/
function store(Data memory input, Data storage output) internal {
for(uint256 i1 = 0; i1 < input.entries.length; i1++) {
output.entries.push(input.entries[i1]);
}
}
//array helpers for Entries
/**
* @dev Add value to an array
* @param self The in-memory struct
* @param value The value to add
*/
function addEntries(Data memory self, BatchEntry.Data memory value) internal pure {
/**
* First resize the array. Then add the new element to the end.
*/
BatchEntry.Data[] memory tmp = new BatchEntry.Data[](self.entries.length + 1);
for (uint256 i = 0; i < self.entries.length; i++) {
tmp[i] = self.entries[i];
}
tmp[self.entries.length] = value;
self.entries = tmp;
}
//utility functions
/**
* @dev Return an empty struct
* @return r The empty struct
*/
function nil() internal pure returns (Data memory r) {
assembly {
r := 0
}
}
/**
* @dev Test whether a struct is empty
* @param x The struct to be tested
* @return r True if it is empty
*/
function isNil(Data memory x) internal pure returns (bool r) {
assembly {
r := iszero(x)
}
}
}
//library BatchProof
library BatchEntry {
//struct definition
struct Data {
ExistenceProof.Data exist;
NonExistenceProof.Data nonexist;
}
// Decoder section
/**
* @dev The main decoder for memory
* @param bs The bytes array to be decoded
* @return The decoded struct
*/
function decode(bytes memory bs) internal pure returns (Data memory) {
(Data memory x, ) = _decode(32, bs, bs.length);
return x;
}
/**
* @dev The main decoder for storage
* @param self The in-storage struct
* @param bs The bytes array to be decoded
*/
function decode(Data storage self, bytes memory bs) internal {
(Data memory x, ) = _decode(32, bs, bs.length);
store(x, self);
}
// inner decoder
/**
* @dev The decoder for internal usage
* @param p The offset of bytes array to start decode
* @param bs The bytes array to be decoded
* @param sz The number of bytes expected
* @return The decoded struct
* @return The number of bytes decoded
*/
function _decode(uint256 p, bytes memory bs, uint256 sz)
internal
pure
returns (Data memory, uint)
{
Data memory r;
uint[3] memory counters;
uint256 fieldId;
ProtoBufRuntime.WireType wireType;
uint256 bytesRead;
uint256 offset = p;
uint256 pointer = p;
while (pointer < offset + sz) {
(fieldId, wireType, bytesRead) = ProtoBufRuntime._decode_key(pointer, bs);
pointer += bytesRead;
if (fieldId == 1) {
pointer += _read_exist(pointer, bs, r, counters);
}
else if (fieldId == 2) {
pointer += _read_nonexist(pointer, bs, r, counters);
}
else {
if (wireType == ProtoBufRuntime.WireType.Fixed64) {
uint256 size;
(, size) = ProtoBufRuntime._decode_fixed64(pointer, bs);
pointer += size;
}
if (wireType == ProtoBufRuntime.WireType.Fixed32) {
uint256 size;
(, size) = ProtoBufRuntime._decode_fixed32(pointer, bs);
pointer += size;
}
if (wireType == ProtoBufRuntime.WireType.Varint) {
uint256 size;
(, size) = ProtoBufRuntime._decode_varint(pointer, bs);
pointer += size;
}
if (wireType == ProtoBufRuntime.WireType.LengthDelim) {
uint256 size;
(, size) = ProtoBufRuntime._decode_lendelim(pointer, bs);
pointer += size;
}
}
}
return (r, sz);
}
// field readers
/**
* @dev The decoder for reading a field
* @param p The offset of bytes array to start decode
* @param bs The bytes array to be decoded
* @param r The in-memory struct
* @param counters The counters for repeated fields
* @return The number of bytes decoded
*/
function _read_exist(
uint256 p,
bytes memory bs,
Data memory r,
uint[3] memory counters
) internal pure returns (uint) {
/**
* if `r` is NULL, then only counting the number of fields.
*/
(ExistenceProof.Data memory x, uint256 sz) = _decode_ExistenceProof(p, bs);
if (isNil(r)) {
counters[1] += 1;
} else {
r.exist = x;
if (counters[1] > 0) counters[1] -= 1;
}
return sz;
}
/**
* @dev The decoder for reading a field
* @param p The offset of bytes array to start decode
* @param bs The bytes array to be decoded
* @param r The in-memory struct
* @param counters The counters for repeated fields
* @return The number of bytes decoded
*/
function _read_nonexist(
uint256 p,
bytes memory bs,
Data memory r,
uint[3] memory counters
) internal pure returns (uint) {
/**
* if `r` is NULL, then only counting the number of fields.
*/
(NonExistenceProof.Data memory x, uint256 sz) = _decode_NonExistenceProof(p, bs);
if (isNil(r)) {
counters[2] += 1;
} else {
r.nonexist = x;
if (counters[2] > 0) counters[2] -= 1;
}
return sz;
}
// struct decoder
/**
* @dev The decoder for reading a inner struct field
* @param p The offset of bytes array to start decode
* @param bs The bytes array to be decoded
* @return The decoded inner-struct
* @return The number of bytes used to decode
*/
function _decode_ExistenceProof(uint256 p, bytes memory bs)
internal
pure
returns (ExistenceProof.Data memory, uint)
{
uint256 pointer = p;
(uint256 sz, uint256 bytesRead) = ProtoBufRuntime._decode_varint(pointer, bs);
pointer += bytesRead;
(ExistenceProof.Data memory r, ) = ExistenceProof._decode(pointer, bs, sz);
return (r, sz + bytesRead);
}
/**
* @dev The decoder for reading a inner struct field
* @param p The offset of bytes array to start decode
* @param bs The bytes array to be decoded
* @return The decoded inner-struct
* @return The number of bytes used to decode
*/
function _decode_NonExistenceProof(uint256 p, bytes memory bs)
internal
pure
returns (NonExistenceProof.Data memory, uint)
{
uint256 pointer = p;
(uint256 sz, uint256 bytesRead) = ProtoBufRuntime._decode_varint(pointer, bs);
pointer += bytesRead;
(NonExistenceProof.Data memory r, ) = NonExistenceProof._decode(pointer, bs, sz);
return (r, sz + bytesRead);
}
// Encoder section
/**
* @dev The main encoder for memory
* @param r The struct to be encoded
* @return The encoded byte array
*/
function encode(Data memory r) internal pure returns (bytes memory) {
bytes memory bs = new bytes(_estimate(r));
uint256 sz = _encode(r, 32, bs);
assembly {
mstore(bs, sz)
}
return bs;
}
// inner encoder
/**
* @dev The encoder for internal usage
* @param r The struct to be encoded
* @param p The offset of bytes array to start decode
* @param bs The bytes array to be decoded
* @return The number of bytes encoded
*/
function _encode(Data memory r, uint256 p, bytes memory bs)
internal
pure
returns (uint)
{
uint256 offset = p;
uint256 pointer = p;
pointer += ProtoBufRuntime._encode_key(
1,
ProtoBufRuntime.WireType.LengthDelim,
pointer,
bs
);
pointer += ExistenceProof._encode_nested(r.exist, pointer, bs);
pointer += ProtoBufRuntime._encode_key(
2,
ProtoBufRuntime.WireType.LengthDelim,
pointer,
bs
);
pointer += NonExistenceProof._encode_nested(r.nonexist, pointer, bs);
return pointer - offset;
}
// nested encoder
/**
* @dev The encoder for inner struct
* @param r The struct to be encoded
* @param p The offset of bytes array to start decode
* @param bs The bytes array to be decoded
* @return The number of bytes encoded
*/
function _encode_nested(Data memory r, uint256 p, bytes memory bs)
internal
pure
returns (uint)
{
/**
* First encoded `r` into a temporary array, and encode the actual size used.
* Then copy the temporary array into `bs`.
*/
uint256 offset = p;
uint256 pointer = p;
bytes memory tmp = new bytes(_estimate(r));
uint256 tmpAddr = ProtoBufRuntime.getMemoryAddress(tmp);
uint256 bsAddr = ProtoBufRuntime.getMemoryAddress(bs);
uint256 size = _encode(r, 32, tmp);
pointer += ProtoBufRuntime._encode_varint(size, pointer, bs);
ProtoBufRuntime.copyBytes(tmpAddr + 32, bsAddr + pointer, size);
pointer += size;
delete tmp;
return pointer - offset;
}
// estimator
/**
* @dev The estimator for a struct
* @param r The struct to be encoded
* @return The number of bytes encoded in estimation
*/
function _estimate(
Data memory r
) internal pure returns (uint) {
uint256 e;
e += 1 + ProtoBufRuntime._sz_lendelim(ExistenceProof._estimate(r.exist));
e += 1 + ProtoBufRuntime._sz_lendelim(NonExistenceProof._estimate(r.nonexist));
return e;
}
// empty checker
function _empty(
Data memory r
) internal pure returns (bool) {
return true;
}
//store function
/**
* @dev Store in-memory struct to storage
* @param input The in-memory struct
* @param output The in-storage struct
*/
function store(Data memory input, Data storage output) internal {
ExistenceProof.store(input.exist, output.exist);
NonExistenceProof.store(input.nonexist, output.nonexist);
}
//utility functions
/**
* @dev Return an empty struct
* @return r The empty struct
*/
function nil() internal pure returns (Data memory r) {
assembly {
r := 0
}
}
/**
* @dev Test whether a struct is empty
* @param x The struct to be tested
* @return r True if it is empty
*/
function isNil(Data memory x) internal pure returns (bool r) {
assembly {
r := iszero(x)
}
}
}
//library BatchEntry
library CompressedBatchProof {
//struct definition
struct Data {
CompressedBatchEntry.Data[] entries;
InnerOp.Data[] lookup_inners;
}
// Decoder section
/**
* @dev The main decoder for memory
* @param bs The bytes array to be decoded
* @return The decoded struct
*/
function decode(bytes memory bs) internal pure returns (Data memory) {
(Data memory x, ) = _decode(32, bs, bs.length);
return x;
}
/**
* @dev The main decoder for storage
* @param self The in-storage struct
* @param bs The bytes array to be decoded
*/
function decode(Data storage self, bytes memory bs) internal {
(Data memory x, ) = _decode(32, bs, bs.length);
store(x, self);
}
// inner decoder
/**
* @dev The decoder for internal usage
* @param p The offset of bytes array to start decode
* @param bs The bytes array to be decoded
* @param sz The number of bytes expected
* @return The decoded struct
* @return The number of bytes decoded
*/
function _decode(uint256 p, bytes memory bs, uint256 sz)
internal
pure
returns (Data memory, uint)
{
Data memory r;
uint[3] memory counters;
uint256 fieldId;
ProtoBufRuntime.WireType wireType;
uint256 bytesRead;
uint256 offset = p;
uint256 pointer = p;
while (pointer < offset + sz) {
(fieldId, wireType, bytesRead) = ProtoBufRuntime._decode_key(pointer, bs);
pointer += bytesRead;
if (fieldId == 1) {
pointer += _read_entries(pointer, bs, nil(), counters);
}
else if (fieldId == 2) {
pointer += _read_lookup_inners(pointer, bs, nil(), counters);
}
else {
if (wireType == ProtoBufRuntime.WireType.Fixed64) {
uint256 size;
(, size) = ProtoBufRuntime._decode_fixed64(pointer, bs);
pointer += size;
}
if (wireType == ProtoBufRuntime.WireType.Fixed32) {
uint256 size;
(, size) = ProtoBufRuntime._decode_fixed32(pointer, bs);
pointer += size;
}
if (wireType == ProtoBufRuntime.WireType.Varint) {
uint256 size;
(, size) = ProtoBufRuntime._decode_varint(pointer, bs);
pointer += size;
}
if (wireType == ProtoBufRuntime.WireType.LengthDelim) {
uint256 size;
(, size) = ProtoBufRuntime._decode_lendelim(pointer, bs);
pointer += size;
}
}
}
pointer = offset;
r.entries = new CompressedBatchEntry.Data[](counters[1]);
r.lookup_inners = new InnerOp.Data[](counters[2]);
while (pointer < offset + sz) {
(fieldId, wireType, bytesRead) = ProtoBufRuntime._decode_key(pointer, bs);
pointer += bytesRead;
if (fieldId == 1) {
pointer += _read_entries(pointer, bs, r, counters);
}
else if (fieldId == 2) {
pointer += _read_lookup_inners(pointer, bs, r, counters);
}
else {
if (wireType == ProtoBufRuntime.WireType.Fixed64) {
uint256 size;
(, size) = ProtoBufRuntime._decode_fixed64(pointer, bs);
pointer += size;
}
if (wireType == ProtoBufRuntime.WireType.Fixed32) {
uint256 size;
(, size) = ProtoBufRuntime._decode_fixed32(pointer, bs);
pointer += size;
}
if (wireType == ProtoBufRuntime.WireType.Varint) {
uint256 size;
(, size) = ProtoBufRuntime._decode_varint(pointer, bs);
pointer += size;
}
if (wireType == ProtoBufRuntime.WireType.LengthDelim) {
uint256 size;
(, size) = ProtoBufRuntime._decode_lendelim(pointer, bs);
pointer += size;
}
}
}
return (r, sz);
}
// field readers
/**
* @dev The decoder for reading a field
* @param p The offset of bytes array to start decode
* @param bs The bytes array to be decoded
* @param r The in-memory struct
* @param counters The counters for repeated fields
* @return The number of bytes decoded
*/
function _read_entries(
uint256 p,
bytes memory bs,
Data memory r,
uint[3] memory counters
) internal pure returns (uint) {
/**
* if `r` is NULL, then only counting the number of fields.
*/
(CompressedBatchEntry.Data memory x, uint256 sz) = _decode_CompressedBatchEntry(p, bs);
if (isNil(r)) {
counters[1] += 1;
} else {
r.entries[r.entries.length - counters[1]] = x;
if (counters[1] > 0) counters[1] -= 1;
}
return sz;
}
/**
* @dev The decoder for reading a field
* @param p The offset of bytes array to start decode
* @param bs The bytes array to be decoded
* @param r The in-memory struct
* @param counters The counters for repeated fields
* @return The number of bytes decoded
*/
function _read_lookup_inners(
uint256 p,
bytes memory bs,
Data memory r,
uint[3] memory counters
) internal pure returns (uint) {
/**
* if `r` is NULL, then only counting the number of fields.
*/
(InnerOp.Data memory x, uint256 sz) = _decode_InnerOp(p, bs);
if (isNil(r)) {
counters[2] += 1;
} else {
r.lookup_inners[r.lookup_inners.length - counters[2]] = x;
if (counters[2] > 0) counters[2] -= 1;
}
return sz;
}
// struct decoder
/**
* @dev The decoder for reading a inner struct field
* @param p The offset of bytes array to start decode
* @param bs The bytes array to be decoded
* @return The decoded inner-struct
* @return The number of bytes used to decode
*/
function _decode_CompressedBatchEntry(uint256 p, bytes memory bs)
internal
pure
returns (CompressedBatchEntry.Data memory, uint)
{
uint256 pointer = p;
(uint256 sz, uint256 bytesRead) = ProtoBufRuntime._decode_varint(pointer, bs);
pointer += bytesRead;
(CompressedBatchEntry.Data memory r, ) = CompressedBatchEntry._decode(pointer, bs, sz);
return (r, sz + bytesRead);
}
/**
* @dev The decoder for reading a inner struct field
* @param p The offset of bytes array to start decode
* @param bs The bytes array to be decoded
* @return The decoded inner-struct
* @return The number of bytes used to decode
*/
function _decode_InnerOp(uint256 p, bytes memory bs)
internal
pure
returns (InnerOp.Data memory, uint)
{
uint256 pointer = p;
(uint256 sz, uint256 bytesRead) = ProtoBufRuntime._decode_varint(pointer, bs);
pointer += bytesRead;
(InnerOp.Data memory r, ) = InnerOp._decode(pointer, bs, sz);
return (r, sz + bytesRead);
}
// Encoder section
/**
* @dev The main encoder for memory
* @param r The struct to be encoded
* @return The encoded byte array
*/
function encode(Data memory r) internal pure returns (bytes memory) {
bytes memory bs = new bytes(_estimate(r));
uint256 sz = _encode(r, 32, bs);
assembly {
mstore(bs, sz)
}
return bs;
}
// inner encoder
/**
* @dev The encoder for internal usage
* @param r The struct to be encoded
* @param p The offset of bytes array to start decode
* @param bs The bytes array to be decoded
* @return The number of bytes encoded
*/
function _encode(Data memory r, uint256 p, bytes memory bs)
internal
pure
returns (uint)
{
uint256 offset = p;
uint256 pointer = p;
uint256 i;
if (r.entries.length != 0) {
for(i = 0; i < r.entries.length; i++) {
pointer += ProtoBufRuntime._encode_key(
1,
ProtoBufRuntime.WireType.LengthDelim,
pointer,
bs)
;
pointer += CompressedBatchEntry._encode_nested(r.entries[i], pointer, bs);
}
}
if (r.lookup_inners.length != 0) {
for(i = 0; i < r.lookup_inners.length; i++) {
pointer += ProtoBufRuntime._encode_key(
2,
ProtoBufRuntime.WireType.LengthDelim,
pointer,
bs)
;
pointer += InnerOp._encode_nested(r.lookup_inners[i], pointer, bs);
}
}
return pointer - offset;
}
// nested encoder
/**
* @dev The encoder for inner struct
* @param r The struct to be encoded
* @param p The offset of bytes array to start decode
* @param bs The bytes array to be decoded
* @return The number of bytes encoded
*/
function _encode_nested(Data memory r, uint256 p, bytes memory bs)
internal
pure
returns (uint)
{
/**
* First encoded `r` into a temporary array, and encode the actual size used.
* Then copy the temporary array into `bs`.
*/
uint256 offset = p;
uint256 pointer = p;
bytes memory tmp = new bytes(_estimate(r));
uint256 tmpAddr = ProtoBufRuntime.getMemoryAddress(tmp);
uint256 bsAddr = ProtoBufRuntime.getMemoryAddress(bs);
uint256 size = _encode(r, 32, tmp);
pointer += ProtoBufRuntime._encode_varint(size, pointer, bs);
ProtoBufRuntime.copyBytes(tmpAddr + 32, bsAddr + pointer, size);
pointer += size;
delete tmp;
return pointer - offset;
}
// estimator
/**
* @dev The estimator for a struct
* @param r The struct to be encoded
* @return The number of bytes encoded in estimation
*/
function _estimate(
Data memory r
) internal pure returns (uint) {
uint256 e;uint256 i;
for(i = 0; i < r.entries.length; i++) {
e += 1 + ProtoBufRuntime._sz_lendelim(CompressedBatchEntry._estimate(r.entries[i]));
}
for(i = 0; i < r.lookup_inners.length; i++) {
e += 1 + ProtoBufRuntime._sz_lendelim(InnerOp._estimate(r.lookup_inners[i]));
}
return e;
}
// empty checker
function _empty(
Data memory r
) internal pure returns (bool) {
if (r.entries.length != 0) {
return false;
}
if (r.lookup_inners.length != 0) {
return false;
}
return true;
}
//store function
/**
* @dev Store in-memory struct to storage
* @param input The in-memory struct
* @param output The in-storage struct
*/
function store(Data memory input, Data storage output) internal {
for(uint256 i1 = 0; i1 < input.entries.length; i1++) {
output.entries.push(input.entries[i1]);
}
for(uint256 i2 = 0; i2 < input.lookup_inners.length; i2++) {
output.lookup_inners.push(input.lookup_inners[i2]);
}
}
//array helpers for Entries
/**
* @dev Add value to an array
* @param self The in-memory struct
* @param value The value to add
*/
function addEntries(Data memory self, CompressedBatchEntry.Data memory value) internal pure {
/**
* First resize the array. Then add the new element to the end.
*/
CompressedBatchEntry.Data[] memory tmp = new CompressedBatchEntry.Data[](self.entries.length + 1);
for (uint256 i = 0; i < self.entries.length; i++) {
tmp[i] = self.entries[i];
}
tmp[self.entries.length] = value;
self.entries = tmp;
}
//array helpers for LookupInners
/**
* @dev Add value to an array
* @param self The in-memory struct
* @param value The value to add
*/
function addLookupInners(Data memory self, InnerOp.Data memory value) internal pure {
/**
* First resize the array. Then add the new element to the end.
*/
InnerOp.Data[] memory tmp = new InnerOp.Data[](self.lookup_inners.length + 1);
for (uint256 i = 0; i < self.lookup_inners.length; i++) {
tmp[i] = self.lookup_inners[i];
}
tmp[self.lookup_inners.length] = value;
self.lookup_inners = tmp;
}
//utility functions
/**
* @dev Return an empty struct
* @return r The empty struct
*/
function nil() internal pure returns (Data memory r) {
assembly {
r := 0
}
}
/**
* @dev Test whether a struct is empty
* @param x The struct to be tested
* @return r True if it is empty
*/
function isNil(Data memory x) internal pure returns (bool r) {
assembly {
r := iszero(x)
}
}
}
//library CompressedBatchProof
library CompressedBatchEntry {
//struct definition
struct Data {
CompressedExistenceProof.Data exist;
CompressedNonExistenceProof.Data nonexist;
}
// Decoder section
/**
* @dev The main decoder for memory
* @param bs The bytes array to be decoded
* @return The decoded struct
*/
function decode(bytes memory bs) internal pure returns (Data memory) {
(Data memory x, ) = _decode(32, bs, bs.length);
return x;
}
/**
* @dev The main decoder for storage
* @param self The in-storage struct
* @param bs The bytes array to be decoded
*/
function decode(Data storage self, bytes memory bs) internal {
(Data memory x, ) = _decode(32, bs, bs.length);
store(x, self);
}
// inner decoder
/**
* @dev The decoder for internal usage
* @param p The offset of bytes array to start decode
* @param bs The bytes array to be decoded
* @param sz The number of bytes expected
* @return The decoded struct
* @return The number of bytes decoded
*/
function _decode(uint256 p, bytes memory bs, uint256 sz)
internal
pure
returns (Data memory, uint)
{
Data memory r;
uint[3] memory counters;
uint256 fieldId;
ProtoBufRuntime.WireType wireType;
uint256 bytesRead;
uint256 offset = p;
uint256 pointer = p;
while (pointer < offset + sz) {
(fieldId, wireType, bytesRead) = ProtoBufRuntime._decode_key(pointer, bs);
pointer += bytesRead;
if (fieldId == 1) {
pointer += _read_exist(pointer, bs, r, counters);
}
else if (fieldId == 2) {
pointer += _read_nonexist(pointer, bs, r, counters);
}
else {
if (wireType == ProtoBufRuntime.WireType.Fixed64) {
uint256 size;
(, size) = ProtoBufRuntime._decode_fixed64(pointer, bs);
pointer += size;
}
if (wireType == ProtoBufRuntime.WireType.Fixed32) {
uint256 size;
(, size) = ProtoBufRuntime._decode_fixed32(pointer, bs);
pointer += size;
}
if (wireType == ProtoBufRuntime.WireType.Varint) {
uint256 size;
(, size) = ProtoBufRuntime._decode_varint(pointer, bs);
pointer += size;
}
if (wireType == ProtoBufRuntime.WireType.LengthDelim) {
uint256 size;
(, size) = ProtoBufRuntime._decode_lendelim(pointer, bs);
pointer += size;
}
}
}
return (r, sz);
}
// field readers
/**
* @dev The decoder for reading a field
* @param p The offset of bytes array to start decode
* @param bs The bytes array to be decoded
* @param r The in-memory struct
* @param counters The counters for repeated fields
* @return The number of bytes decoded
*/
function _read_exist(
uint256 p,
bytes memory bs,
Data memory r,
uint[3] memory counters
) internal pure returns (uint) {
/**
* if `r` is NULL, then only counting the number of fields.
*/
(CompressedExistenceProof.Data memory x, uint256 sz) = _decode_CompressedExistenceProof(p, bs);
if (isNil(r)) {
counters[1] += 1;
} else {
r.exist = x;
if (counters[1] > 0) counters[1] -= 1;
}
return sz;
}
/**
* @dev The decoder for reading a field
* @param p The offset of bytes array to start decode
* @param bs The bytes array to be decoded
* @param r The in-memory struct
* @param counters The counters for repeated fields
* @return The number of bytes decoded
*/
function _read_nonexist(
uint256 p,
bytes memory bs,
Data memory r,
uint[3] memory counters
) internal pure returns (uint) {
/**
* if `r` is NULL, then only counting the number of fields.
*/
(CompressedNonExistenceProof.Data memory x, uint256 sz) = _decode_CompressedNonExistenceProof(p, bs);
if (isNil(r)) {
counters[2] += 1;
} else {
r.nonexist = x;
if (counters[2] > 0) counters[2] -= 1;
}
return sz;
}
// struct decoder
/**
* @dev The decoder for reading a inner struct field
* @param p The offset of bytes array to start decode
* @param bs The bytes array to be decoded
* @return The decoded inner-struct
* @return The number of bytes used to decode
*/
function _decode_CompressedExistenceProof(uint256 p, bytes memory bs)
internal
pure
returns (CompressedExistenceProof.Data memory, uint)
{
uint256 pointer = p;
(uint256 sz, uint256 bytesRead) = ProtoBufRuntime._decode_varint(pointer, bs);
pointer += bytesRead;
(CompressedExistenceProof.Data memory r, ) = CompressedExistenceProof._decode(pointer, bs, sz);
return (r, sz + bytesRead);
}
/**
* @dev The decoder for reading a inner struct field
* @param p The offset of bytes array to start decode
* @param bs The bytes array to be decoded
* @return The decoded inner-struct
* @return The number of bytes used to decode
*/
function _decode_CompressedNonExistenceProof(uint256 p, bytes memory bs)
internal
pure
returns (CompressedNonExistenceProof.Data memory, uint)
{
uint256 pointer = p;
(uint256 sz, uint256 bytesRead) = ProtoBufRuntime._decode_varint(pointer, bs);
pointer += bytesRead;
(CompressedNonExistenceProof.Data memory r, ) = CompressedNonExistenceProof._decode(pointer, bs, sz);
return (r, sz + bytesRead);
}
// Encoder section
/**
* @dev The main encoder for memory
* @param r The struct to be encoded
* @return The encoded byte array
*/
function encode(Data memory r) internal pure returns (bytes memory) {
bytes memory bs = new bytes(_estimate(r));
uint256 sz = _encode(r, 32, bs);
assembly {
mstore(bs, sz)
}
return bs;
}
// inner encoder
/**
* @dev The encoder for internal usage
* @param r The struct to be encoded
* @param p The offset of bytes array to start decode
* @param bs The bytes array to be decoded
* @return The number of bytes encoded
*/
function _encode(Data memory r, uint256 p, bytes memory bs)
internal
pure
returns (uint)
{
uint256 offset = p;
uint256 pointer = p;
pointer += ProtoBufRuntime._encode_key(
1,
ProtoBufRuntime.WireType.LengthDelim,
pointer,
bs
);
pointer += CompressedExistenceProof._encode_nested(r.exist, pointer, bs);
pointer += ProtoBufRuntime._encode_key(
2,
ProtoBufRuntime.WireType.LengthDelim,
pointer,
bs
);
pointer += CompressedNonExistenceProof._encode_nested(r.nonexist, pointer, bs);
return pointer - offset;
}
// nested encoder
/**
* @dev The encoder for inner struct
* @param r The struct to be encoded
* @param p The offset of bytes array to start decode
* @param bs The bytes array to be decoded
* @return The number of bytes encoded
*/
function _encode_nested(Data memory r, uint256 p, bytes memory bs)
internal
pure
returns (uint)
{
/**
* First encoded `r` into a temporary array, and encode the actual size used.
* Then copy the temporary array into `bs`.
*/
uint256 offset = p;
uint256 pointer = p;
bytes memory tmp = new bytes(_estimate(r));
uint256 tmpAddr = ProtoBufRuntime.getMemoryAddress(tmp);
uint256 bsAddr = ProtoBufRuntime.getMemoryAddress(bs);
uint256 size = _encode(r, 32, tmp);
pointer += ProtoBufRuntime._encode_varint(size, pointer, bs);
ProtoBufRuntime.copyBytes(tmpAddr + 32, bsAddr + pointer, size);
pointer += size;
delete tmp;
return pointer - offset;
}
// estimator
/**
* @dev The estimator for a struct
* @param r The struct to be encoded
* @return The number of bytes encoded in estimation
*/
function _estimate(
Data memory r
) internal pure returns (uint) {
uint256 e;
e += 1 + ProtoBufRuntime._sz_lendelim(CompressedExistenceProof._estimate(r.exist));
e += 1 + ProtoBufRuntime._sz_lendelim(CompressedNonExistenceProof._estimate(r.nonexist));
return e;
}
// empty checker
function _empty(
Data memory r
) internal pure returns (bool) {
return true;
}
//store function
/**
* @dev Store in-memory struct to storage
* @param input The in-memory struct
* @param output The in-storage struct
*/
function store(Data memory input, Data storage output) internal {
CompressedExistenceProof.store(input.exist, output.exist);
CompressedNonExistenceProof.store(input.nonexist, output.nonexist);
}
//utility functions
/**
* @dev Return an empty struct
* @return r The empty struct
*/
function nil() internal pure returns (Data memory r) {
assembly {
r := 0
}
}
/**
* @dev Test whether a struct is empty
* @param x The struct to be tested
* @return r True if it is empty
*/
function isNil(Data memory x) internal pure returns (bool r) {
assembly {
r := iszero(x)
}
}
}
//library CompressedBatchEntry
library CompressedExistenceProof {
//struct definition
struct Data {
bytes key;
bytes value;
LeafOp.Data leaf;
int32[] path;
}
// Decoder section
/**
* @dev The main decoder for memory
* @param bs The bytes array to be decoded
* @return The decoded struct
*/
function decode(bytes memory bs) internal pure returns (Data memory) {
(Data memory x, ) = _decode(32, bs, bs.length);
return x;
}
/**
* @dev The main decoder for storage
* @param self The in-storage struct
* @param bs The bytes array to be decoded
*/
function decode(Data storage self, bytes memory bs) internal {
(Data memory x, ) = _decode(32, bs, bs.length);
store(x, self);
}
// inner decoder
/**
* @dev The decoder for internal usage
* @param p The offset of bytes array to start decode
* @param bs The bytes array to be decoded
* @param sz The number of bytes expected
* @return The decoded struct
* @return The number of bytes decoded
*/
function _decode(uint256 p, bytes memory bs, uint256 sz)
internal
pure
returns (Data memory, uint)
{
Data memory r;
uint[5] memory counters;
uint256 fieldId;
ProtoBufRuntime.WireType wireType;
uint256 bytesRead;
uint256 offset = p;
uint256 pointer = p;
while (pointer < offset + sz) {
(fieldId, wireType, bytesRead) = ProtoBufRuntime._decode_key(pointer, bs);
pointer += bytesRead;
if (fieldId == 1) {
pointer += _read_key(pointer, bs, r, counters);
}
else if (fieldId == 2) {
pointer += _read_value(pointer, bs, r, counters);
}
else if (fieldId == 3) {
pointer += _read_leaf(pointer, bs, r, counters);
}
else if (fieldId == 4) {
pointer += _read_path(pointer, bs, nil(), counters);
}
else {
if (wireType == ProtoBufRuntime.WireType.Fixed64) {
uint256 size;
(, size) = ProtoBufRuntime._decode_fixed64(pointer, bs);
pointer += size;
}
if (wireType == ProtoBufRuntime.WireType.Fixed32) {
uint256 size;
(, size) = ProtoBufRuntime._decode_fixed32(pointer, bs);
pointer += size;
}
if (wireType == ProtoBufRuntime.WireType.Varint) {
uint256 size;
(, size) = ProtoBufRuntime._decode_varint(pointer, bs);
pointer += size;
}
if (wireType == ProtoBufRuntime.WireType.LengthDelim) {
uint256 size;
(, size) = ProtoBufRuntime._decode_lendelim(pointer, bs);
pointer += size;
}
}
}
pointer = offset;
r.path = new int32[](counters[4]);
while (pointer < offset + sz) {
(fieldId, wireType, bytesRead) = ProtoBufRuntime._decode_key(pointer, bs);
pointer += bytesRead;
if (fieldId == 1) {
pointer += _read_key(pointer, bs, nil(), counters);
}
else if (fieldId == 2) {
pointer += _read_value(pointer, bs, nil(), counters);
}
else if (fieldId == 3) {
pointer += _read_leaf(pointer, bs, nil(), counters);
}
else if (fieldId == 4) {
pointer += _read_path(pointer, bs, r, counters);
}
else {
if (wireType == ProtoBufRuntime.WireType.Fixed64) {
uint256 size;
(, size) = ProtoBufRuntime._decode_fixed64(pointer, bs);
pointer += size;
}
if (wireType == ProtoBufRuntime.WireType.Fixed32) {
uint256 size;
(, size) = ProtoBufRuntime._decode_fixed32(pointer, bs);
pointer += size;
}
if (wireType == ProtoBufRuntime.WireType.Varint) {
uint256 size;
(, size) = ProtoBufRuntime._decode_varint(pointer, bs);
pointer += size;
}
if (wireType == ProtoBufRuntime.WireType.LengthDelim) {
uint256 size;
(, size) = ProtoBufRuntime._decode_lendelim(pointer, bs);
pointer += size;
}
}
}
return (r, sz);
}
// field readers
/**
* @dev The decoder for reading a field
* @param p The offset of bytes array to start decode
* @param bs The bytes array to be decoded
* @param r The in-memory struct
* @param counters The counters for repeated fields
* @return The number of bytes decoded
*/
function _read_key(
uint256 p,
bytes memory bs,
Data memory r,
uint[5] memory counters
) internal pure returns (uint) {
/**
* if `r` is NULL, then only counting the number of fields.
*/
(bytes memory x, uint256 sz) = ProtoBufRuntime._decode_bytes(p, bs);
if (isNil(r)) {
counters[1] += 1;
} else {
r.key = x;
if (counters[1] > 0) counters[1] -= 1;
}
return sz;
}
/**
* @dev The decoder for reading a field
* @param p The offset of bytes array to start decode
* @param bs The bytes array to be decoded
* @param r The in-memory struct
* @param counters The counters for repeated fields
* @return The number of bytes decoded
*/
function _read_value(
uint256 p,
bytes memory bs,
Data memory r,
uint[5] memory counters
) internal pure returns (uint) {
/**
* if `r` is NULL, then only counting the number of fields.
*/
(bytes memory x, uint256 sz) = ProtoBufRuntime._decode_bytes(p, bs);
if (isNil(r)) {
counters[2] += 1;
} else {
r.value = x;
if (counters[2] > 0) counters[2] -= 1;
}
return sz;
}
/**
* @dev The decoder for reading a field
* @param p The offset of bytes array to start decode
* @param bs The bytes array to be decoded
* @param r The in-memory struct
* @param counters The counters for repeated fields
* @return The number of bytes decoded
*/
function _read_leaf(
uint256 p,
bytes memory bs,
Data memory r,
uint[5] memory counters
) internal pure returns (uint) {
/**
* if `r` is NULL, then only counting the number of fields.
*/
(LeafOp.Data memory x, uint256 sz) = _decode_LeafOp(p, bs);
if (isNil(r)) {
counters[3] += 1;
} else {
r.leaf = x;
if (counters[3] > 0) counters[3] -= 1;
}
return sz;
}
/**
* @dev The decoder for reading a field
* @param p The offset of bytes array to start decode
* @param bs The bytes array to be decoded
* @param r The in-memory struct
* @param counters The counters for repeated fields
* @return The number of bytes decoded
*/
function _read_path(
uint256 p,
bytes memory bs,
Data memory r,
uint[5] memory counters
) internal pure returns (uint) {
/**
* if `r` is NULL, then only counting the number of fields.
*/
(int32 x, uint256 sz) = ProtoBufRuntime._decode_int32(p, bs);
if (isNil(r)) {
counters[4] += 1;
} else {
r.path[r.path.length - counters[4]] = x;
if (counters[4] > 0) counters[4] -= 1;
}
return sz;
}
// struct decoder
/**
* @dev The decoder for reading a inner struct field
* @param p The offset of bytes array to start decode
* @param bs The bytes array to be decoded
* @return The decoded inner-struct
* @return The number of bytes used to decode
*/
function _decode_LeafOp(uint256 p, bytes memory bs)
internal
pure
returns (LeafOp.Data memory, uint)
{
uint256 pointer = p;
(uint256 sz, uint256 bytesRead) = ProtoBufRuntime._decode_varint(pointer, bs);
pointer += bytesRead;
(LeafOp.Data memory r, ) = LeafOp._decode(pointer, bs, sz);
return (r, sz + bytesRead);
}
// Encoder section
/**
* @dev The main encoder for memory
* @param r The struct to be encoded
* @return The encoded byte array
*/
function encode(Data memory r) internal pure returns (bytes memory) {
bytes memory bs = new bytes(_estimate(r));
uint256 sz = _encode(r, 32, bs);
assembly {
mstore(bs, sz)
}
return bs;
}
// inner encoder
/**
* @dev The encoder for internal usage
* @param r The struct to be encoded
* @param p The offset of bytes array to start decode
* @param bs The bytes array to be decoded
* @return The number of bytes encoded
*/
function _encode(Data memory r, uint256 p, bytes memory bs)
internal
pure
returns (uint)
{
uint256 offset = p;
uint256 pointer = p;
uint256 i;
if (r.key.length != 0) {
pointer += ProtoBufRuntime._encode_key(
1,
ProtoBufRuntime.WireType.LengthDelim,
pointer,
bs
);
pointer += ProtoBufRuntime._encode_bytes(r.key, pointer, bs);
}
if (r.value.length != 0) {
pointer += ProtoBufRuntime._encode_key(
2,
ProtoBufRuntime.WireType.LengthDelim,
pointer,
bs
);
pointer += ProtoBufRuntime._encode_bytes(r.value, pointer, bs);
}
pointer += ProtoBufRuntime._encode_key(
3,
ProtoBufRuntime.WireType.LengthDelim,
pointer,
bs
);
pointer += LeafOp._encode_nested(r.leaf, pointer, bs);
if (r.path.length != 0) {
for(i = 0; i < r.path.length; i++) {
pointer += ProtoBufRuntime._encode_key(
4,
ProtoBufRuntime.WireType.Varint,
pointer,
bs)
;
pointer += ProtoBufRuntime._encode_int32(r.path[i], pointer, bs);
}
}
return pointer - offset;
}
// nested encoder
/**
* @dev The encoder for inner struct
* @param r The struct to be encoded
* @param p The offset of bytes array to start decode
* @param bs The bytes array to be decoded
* @return The number of bytes encoded
*/
function _encode_nested(Data memory r, uint256 p, bytes memory bs)
internal
pure
returns (uint)
{
/**
* First encoded `r` into a temporary array, and encode the actual size used.
* Then copy the temporary array into `bs`.
*/
uint256 offset = p;
uint256 pointer = p;
bytes memory tmp = new bytes(_estimate(r));
uint256 tmpAddr = ProtoBufRuntime.getMemoryAddress(tmp);
uint256 bsAddr = ProtoBufRuntime.getMemoryAddress(bs);
uint256 size = _encode(r, 32, tmp);
pointer += ProtoBufRuntime._encode_varint(size, pointer, bs);
ProtoBufRuntime.copyBytes(tmpAddr + 32, bsAddr + pointer, size);
pointer += size;
delete tmp;
return pointer - offset;
}
// estimator
/**
* @dev The estimator for a struct
* @param r The struct to be encoded
* @return The number of bytes encoded in estimation
*/
function _estimate(
Data memory r
) internal pure returns (uint) {
uint256 e;uint256 i;
e += 1 + ProtoBufRuntime._sz_lendelim(r.key.length);
e += 1 + ProtoBufRuntime._sz_lendelim(r.value.length);
e += 1 + ProtoBufRuntime._sz_lendelim(LeafOp._estimate(r.leaf));
for(i = 0; i < r.path.length; i++) {
e += 1 + ProtoBufRuntime._sz_int32(r.path[i]);
}
return e;
}
// empty checker
function _empty(
Data memory r
) internal pure returns (bool) {
if (r.key.length != 0) {
return false;
}
if (r.value.length != 0) {
return false;
}
if (r.path.length != 0) {
return false;
}
return true;
}
//store function
/**
* @dev Store in-memory struct to storage
* @param input The in-memory struct
* @param output The in-storage struct
*/
function store(Data memory input, Data storage output) internal {
output.key = input.key;
output.value = input.value;
LeafOp.store(input.leaf, output.leaf);
output.path = input.path;
}
//array helpers for Path
/**
* @dev Add value to an array
* @param self The in-memory struct
* @param value The value to add
*/
function addPath(Data memory self, int32 value) internal pure {
/**
* First resize the array. Then add the new element to the end.
*/
int32[] memory tmp = new int32[](self.path.length + 1);
for (uint256 i = 0; i < self.path.length; i++) {
tmp[i] = self.path[i];
}
tmp[self.path.length] = value;
self.path = tmp;
}
//utility functions
/**
* @dev Return an empty struct
* @return r The empty struct
*/
function nil() internal pure returns (Data memory r) {
assembly {
r := 0
}
}
/**
* @dev Test whether a struct is empty
* @param x The struct to be tested
* @return r True if it is empty
*/
function isNil(Data memory x) internal pure returns (bool r) {
assembly {
r := iszero(x)
}
}
}
//library CompressedExistenceProof
library CompressedNonExistenceProof {
//struct definition
struct Data {
bytes key;
CompressedExistenceProof.Data left;
CompressedExistenceProof.Data right;
}
// Decoder section
/**
* @dev The main decoder for memory
* @param bs The bytes array to be decoded
* @return The decoded struct
*/
function decode(bytes memory bs) internal pure returns (Data memory) {
(Data memory x, ) = _decode(32, bs, bs.length);
return x;
}
/**
* @dev The main decoder for storage
* @param self The in-storage struct
* @param bs The bytes array to be decoded
*/
function decode(Data storage self, bytes memory bs) internal {
(Data memory x, ) = _decode(32, bs, bs.length);
store(x, self);
}
// inner decoder
/**
* @dev The decoder for internal usage
* @param p The offset of bytes array to start decode
* @param bs The bytes array to be decoded
* @param sz The number of bytes expected
* @return The decoded struct
* @return The number of bytes decoded
*/
function _decode(uint256 p, bytes memory bs, uint256 sz)
internal
pure
returns (Data memory, uint)
{
Data memory r;
uint[4] memory counters;
uint256 fieldId;
ProtoBufRuntime.WireType wireType;
uint256 bytesRead;
uint256 offset = p;
uint256 pointer = p;
while (pointer < offset + sz) {
(fieldId, wireType, bytesRead) = ProtoBufRuntime._decode_key(pointer, bs);
pointer += bytesRead;
if (fieldId == 1) {
pointer += _read_key(pointer, bs, r, counters);
}
else if (fieldId == 2) {
pointer += _read_left(pointer, bs, r, counters);
}
else if (fieldId == 3) {
pointer += _read_right(pointer, bs, r, counters);
}
else {
if (wireType == ProtoBufRuntime.WireType.Fixed64) {
uint256 size;
(, size) = ProtoBufRuntime._decode_fixed64(pointer, bs);
pointer += size;
}
if (wireType == ProtoBufRuntime.WireType.Fixed32) {
uint256 size;
(, size) = ProtoBufRuntime._decode_fixed32(pointer, bs);
pointer += size;
}
if (wireType == ProtoBufRuntime.WireType.Varint) {
uint256 size;
(, size) = ProtoBufRuntime._decode_varint(pointer, bs);
pointer += size;
}
if (wireType == ProtoBufRuntime.WireType.LengthDelim) {
uint256 size;
(, size) = ProtoBufRuntime._decode_lendelim(pointer, bs);
pointer += size;
}
}
}
return (r, sz);
}
// field readers
/**
* @dev The decoder for reading a field
* @param p The offset of bytes array to start decode
* @param bs The bytes array to be decoded
* @param r The in-memory struct
* @param counters The counters for repeated fields
* @return The number of bytes decoded
*/
function _read_key(
uint256 p,
bytes memory bs,
Data memory r,
uint[4] memory counters
) internal pure returns (uint) {
/**
* if `r` is NULL, then only counting the number of fields.
*/
(bytes memory x, uint256 sz) = ProtoBufRuntime._decode_bytes(p, bs);
if (isNil(r)) {
counters[1] += 1;
} else {
r.key = x;
if (counters[1] > 0) counters[1] -= 1;
}
return sz;
}
/**
* @dev The decoder for reading a field
* @param p The offset of bytes array to start decode
* @param bs The bytes array to be decoded
* @param r The in-memory struct
* @param counters The counters for repeated fields
* @return The number of bytes decoded
*/
function _read_left(
uint256 p,
bytes memory bs,
Data memory r,
uint[4] memory counters
) internal pure returns (uint) {
/**
* if `r` is NULL, then only counting the number of fields.
*/
(CompressedExistenceProof.Data memory x, uint256 sz) = _decode_CompressedExistenceProof(p, bs);
if (isNil(r)) {
counters[2] += 1;
} else {
r.left = x;
if (counters[2] > 0) counters[2] -= 1;
}
return sz;
}
/**
* @dev The decoder for reading a field
* @param p The offset of bytes array to start decode
* @param bs The bytes array to be decoded
* @param r The in-memory struct
* @param counters The counters for repeated fields
* @return The number of bytes decoded
*/
function _read_right(
uint256 p,
bytes memory bs,
Data memory r,
uint[4] memory counters
) internal pure returns (uint) {
/**
* if `r` is NULL, then only counting the number of fields.
*/
(CompressedExistenceProof.Data memory x, uint256 sz) = _decode_CompressedExistenceProof(p, bs);
if (isNil(r)) {
counters[3] += 1;
} else {
r.right = x;
if (counters[3] > 0) counters[3] -= 1;
}
return sz;
}
// struct decoder
/**
* @dev The decoder for reading a inner struct field
* @param p The offset of bytes array to start decode
* @param bs The bytes array to be decoded
* @return The decoded inner-struct
* @return The number of bytes used to decode
*/
function _decode_CompressedExistenceProof(uint256 p, bytes memory bs)
internal
pure
returns (CompressedExistenceProof.Data memory, uint)
{
uint256 pointer = p;
(uint256 sz, uint256 bytesRead) = ProtoBufRuntime._decode_varint(pointer, bs);
pointer += bytesRead;
(CompressedExistenceProof.Data memory r, ) = CompressedExistenceProof._decode(pointer, bs, sz);
return (r, sz + bytesRead);
}
// Encoder section
/**
* @dev The main encoder for memory
* @param r The struct to be encoded
* @return The encoded byte array
*/
function encode(Data memory r) internal pure returns (bytes memory) {
bytes memory bs = new bytes(_estimate(r));
uint256 sz = _encode(r, 32, bs);
assembly {
mstore(bs, sz)
}
return bs;
}
// inner encoder
/**
* @dev The encoder for internal usage
* @param r The struct to be encoded
* @param p The offset of bytes array to start decode
* @param bs The bytes array to be decoded
* @return The number of bytes encoded
*/
function _encode(Data memory r, uint256 p, bytes memory bs)
internal
pure
returns (uint)
{
uint256 offset = p;
uint256 pointer = p;
if (r.key.length != 0) {
pointer += ProtoBufRuntime._encode_key(
1,
ProtoBufRuntime.WireType.LengthDelim,
pointer,
bs
);
pointer += ProtoBufRuntime._encode_bytes(r.key, pointer, bs);
}
pointer += ProtoBufRuntime._encode_key(
2,
ProtoBufRuntime.WireType.LengthDelim,
pointer,
bs
);
pointer += CompressedExistenceProof._encode_nested(r.left, pointer, bs);
pointer += ProtoBufRuntime._encode_key(
3,
ProtoBufRuntime.WireType.LengthDelim,
pointer,
bs
);
pointer += CompressedExistenceProof._encode_nested(r.right, pointer, bs);
return pointer - offset;
}
// nested encoder
/**
* @dev The encoder for inner struct
* @param r The struct to be encoded
* @param p The offset of bytes array to start decode
* @param bs The bytes array to be decoded
* @return The number of bytes encoded
*/
function _encode_nested(Data memory r, uint256 p, bytes memory bs)
internal
pure
returns (uint)
{
/**
* First encoded `r` into a temporary array, and encode the actual size used.
* Then copy the temporary array into `bs`.
*/
uint256 offset = p;
uint256 pointer = p;
bytes memory tmp = new bytes(_estimate(r));
uint256 tmpAddr = ProtoBufRuntime.getMemoryAddress(tmp);
uint256 bsAddr = ProtoBufRuntime.getMemoryAddress(bs);
uint256 size = _encode(r, 32, tmp);
pointer += ProtoBufRuntime._encode_varint(size, pointer, bs);
ProtoBufRuntime.copyBytes(tmpAddr + 32, bsAddr + pointer, size);
pointer += size;
delete tmp;
return pointer - offset;
}
// estimator
/**
* @dev The estimator for a struct
* @param r The struct to be encoded
* @return The number of bytes encoded in estimation
*/
function _estimate(
Data memory r
) internal pure returns (uint) {
uint256 e;
e += 1 + ProtoBufRuntime._sz_lendelim(r.key.length);
e += 1 + ProtoBufRuntime._sz_lendelim(CompressedExistenceProof._estimate(r.left));
e += 1 + ProtoBufRuntime._sz_lendelim(CompressedExistenceProof._estimate(r.right));
return e;
}
// empty checker
function _empty(
Data memory r
) internal pure returns (bool) {
if (r.key.length != 0) {
return false;
}
return true;
}
//store function
/**
* @dev Store in-memory struct to storage
* @param input The in-memory struct
* @param output The in-storage struct
*/
function store(Data memory input, Data storage output) internal {
output.key = input.key;
CompressedExistenceProof.store(input.left, output.left);
CompressedExistenceProof.store(input.right, output.right);
}
//utility functions
/**
* @dev Return an empty struct
* @return r The empty struct
*/
function nil() internal pure returns (Data memory r) {
assembly {
r := 0
}
}
/**
* @dev Test whether a struct is empty
* @param x The struct to be tested
* @return r True if it is empty
*/
function isNil(Data memory x) internal pure returns (bool r) {
assembly {
r := iszero(x)
}
}
}
//library CompressedNonExistenceProof
library PROOFS_PROTO_GLOBAL_ENUMS {
//enum definition
// Solidity enum definitions
enum HashOp {
NO_HASH,
SHA256,
SHA512,
KECCAK,
RIPEMD160,
BITCOIN
}
// Solidity enum encoder
function encode_HashOp(HashOp x) internal pure returns (int32) {
if (x == HashOp.NO_HASH) {
return 0;
}
if (x == HashOp.SHA256) {
return 1;
}
if (x == HashOp.SHA512) {
return 2;
}
if (x == HashOp.KECCAK) {
return 3;
}
if (x == HashOp.RIPEMD160) {
return 4;
}
if (x == HashOp.BITCOIN) {
return 5;
}
revert();
}
// Solidity enum decoder
function decode_HashOp(int64 x) internal pure returns (HashOp) {
if (x == 0) {
return HashOp.NO_HASH;
}
if (x == 1) {
return HashOp.SHA256;
}
if (x == 2) {
return HashOp.SHA512;
}
if (x == 3) {
return HashOp.KECCAK;
}
if (x == 4) {
return HashOp.RIPEMD160;
}
if (x == 5) {
return HashOp.BITCOIN;
}
revert();
}
// Solidity enum definitions
enum LengthOp {
NO_PREFIX,
VAR_PROTO,
VAR_RLP,
FIXED32_BIG,
FIXED32_LITTLE,
FIXED64_BIG,
FIXED64_LITTLE,
REQUIRE_32_BYTES,
REQUIRE_64_BYTES
}
// Solidity enum encoder
function encode_LengthOp(LengthOp x) internal pure returns (int32) {
if (x == LengthOp.NO_PREFIX) {
return 0;
}
if (x == LengthOp.VAR_PROTO) {
return 1;
}
if (x == LengthOp.VAR_RLP) {
return 2;
}
if (x == LengthOp.FIXED32_BIG) {
return 3;
}
if (x == LengthOp.FIXED32_LITTLE) {
return 4;
}
if (x == LengthOp.FIXED64_BIG) {
return 5;
}
if (x == LengthOp.FIXED64_LITTLE) {
return 6;
}
if (x == LengthOp.REQUIRE_32_BYTES) {
return 7;
}
if (x == LengthOp.REQUIRE_64_BYTES) {
return 8;
}
revert();
}
// Solidity enum decoder
function decode_LengthOp(int64 x) internal pure returns (LengthOp) {
if (x == 0) {
return LengthOp.NO_PREFIX;
}
if (x == 1) {
return LengthOp.VAR_PROTO;
}
if (x == 2) {
return LengthOp.VAR_RLP;
}
if (x == 3) {
return LengthOp.FIXED32_BIG;
}
if (x == 4) {
return LengthOp.FIXED32_LITTLE;
}
if (x == 5) {
return LengthOp.FIXED64_BIG;
}
if (x == 6) {
return LengthOp.FIXED64_LITTLE;
}
if (x == 7) {
return LengthOp.REQUIRE_32_BYTES;
}
if (x == 8) {
return LengthOp.REQUIRE_64_BYTES;
}
revert();
}
}
//library PROOFS_PROTO_GLOBAL_ENUMS | * @dev The estimator for a struct @param r The struct to be encoded @return The number of bytes encoded in estimation/ | function _estimate(
Data memory r
) internal pure returns (uint) {
uint256 e;
e += 1 + ProtoBufRuntime._sz_lendelim(LeafOp._estimate(r.leaf_spec));
e += 1 + ProtoBufRuntime._sz_lendelim(InnerSpec._estimate(r.inner_spec));
e += 1 + ProtoBufRuntime._sz_int32(r.max_depth);
e += 1 + ProtoBufRuntime._sz_int32(r.min_depth);
return e;
}
| 13,050,329 | [
1,
1986,
14470,
364,
279,
1958,
225,
436,
1021,
1958,
358,
506,
3749,
327,
1021,
1300,
434,
1731,
3749,
316,
29284,
19,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
225,
445,
389,
23562,
12,
203,
565,
1910,
3778,
436,
203,
225,
262,
2713,
16618,
1135,
261,
11890,
13,
288,
203,
565,
2254,
5034,
425,
31,
203,
565,
425,
1011,
404,
397,
7440,
5503,
5576,
6315,
24575,
67,
80,
409,
292,
381,
12,
9858,
3817,
6315,
23562,
12,
86,
18,
12070,
67,
2793,
10019,
203,
565,
425,
1011,
404,
397,
7440,
5503,
5576,
6315,
24575,
67,
80,
409,
292,
381,
12,
2857,
1990,
6315,
23562,
12,
86,
18,
7872,
67,
2793,
10019,
203,
565,
425,
1011,
404,
397,
7440,
5503,
5576,
6315,
24575,
67,
474,
1578,
12,
86,
18,
1896,
67,
5979,
1769,
203,
565,
425,
1011,
404,
397,
7440,
5503,
5576,
6315,
24575,
67,
474,
1578,
12,
86,
18,
1154,
67,
5979,
1769,
203,
565,
327,
425,
31,
203,
225,
289,
203,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
] |
pragma solidity 0.5.16;
interface ierc207 { //inject NONSTANDARD NAMING
function TOTALSUPPLY3() external view returns (uint); //inject NONSTANDARD NAMING
function BALANCEOF6(address ACCOUNT8) external view returns (uint); //inject NONSTANDARD NAMING
function TRANSFER0(address RECIPIENT4, uint AMOUNT10) external returns (bool); //inject NONSTANDARD NAMING
function ALLOWANCE8(address OWNER10, address SPENDER9) external view returns (uint); //inject NONSTANDARD NAMING
function APPROVE6(address SPENDER9, uint AMOUNT10) external returns (bool); //inject NONSTANDARD NAMING
function TRANSFERFROM9(address SENDER7, address RECIPIENT4, uint AMOUNT10) external returns (bool); //inject NONSTANDARD NAMING
event TRANSFER10(address indexed FROM9, address indexed TO4, uint VALUE10); //inject NONSTANDARD NAMING
event APPROVAL6(address indexed OWNER10, address indexed SPENDER9, uint VALUE10); //inject NONSTANDARD NAMING
}
contract context1 { //inject NONSTANDARD NAMING
constructor () internal { }
// solhint-disable-previous-line no-empty-blocks
function _MSGSENDER8() internal view returns (address payable) { //inject NONSTANDARD NAMING
return msg.sender;
}
}
contract erc209 is context1, ierc207 { //inject NONSTANDARD NAMING
using safemath3 for uint;
mapping (address => uint) private _BALANCES7; //inject NONSTANDARD NAMING
mapping (address => mapping (address => uint)) private _ALLOWANCES5; //inject NONSTANDARD NAMING
uint private _TOTALSUPPLY10; //inject NONSTANDARD NAMING
function TOTALSUPPLY3() public view returns (uint) { //inject NONSTANDARD NAMING
return _TOTALSUPPLY10;
}
function BALANCEOF6(address ACCOUNT8) public view returns (uint) { //inject NONSTANDARD NAMING
return _BALANCES7[ACCOUNT8];
}
function TRANSFER0(address RECIPIENT4, uint AMOUNT10) public returns (bool) { //inject NONSTANDARD NAMING
_TRANSFER10(_MSGSENDER8(), RECIPIENT4, AMOUNT10);
return true;
}
function ALLOWANCE8(address OWNER10, address SPENDER9) public view returns (uint) { //inject NONSTANDARD NAMING
return _ALLOWANCES5[OWNER10][SPENDER9];
}
function APPROVE6(address SPENDER9, uint AMOUNT10) public returns (bool) { //inject NONSTANDARD NAMING
_APPROVE9(_MSGSENDER8(), SPENDER9, AMOUNT10);
return true;
}
function TRANSFERFROM9(address SENDER7, address RECIPIENT4, uint AMOUNT10) public returns (bool) { //inject NONSTANDARD NAMING
_TRANSFER10(SENDER7, RECIPIENT4, AMOUNT10);
_APPROVE9(SENDER7, _MSGSENDER8(), _ALLOWANCES5[SENDER7][_MSGSENDER8()].SUB6(AMOUNT10, "ERC20: transfer amount exceeds allowance"));
return true;
}
function INCREASEALLOWANCE7(address SPENDER9, uint ADDEDVALUE4) public returns (bool) { //inject NONSTANDARD NAMING
_APPROVE9(_MSGSENDER8(), SPENDER9, _ALLOWANCES5[_MSGSENDER8()][SPENDER9].ADD8(ADDEDVALUE4));
return true;
}
function DECREASEALLOWANCE8(address SPENDER9, uint SUBTRACTEDVALUE3) public returns (bool) { //inject NONSTANDARD NAMING
_APPROVE9(_MSGSENDER8(), SPENDER9, _ALLOWANCES5[_MSGSENDER8()][SPENDER9].SUB6(SUBTRACTEDVALUE3, "ERC20: decreased allowance below zero"));
return true;
}
function _TRANSFER10(address SENDER7, address RECIPIENT4, uint AMOUNT10) internal { //inject NONSTANDARD NAMING
require(SENDER7 != address(0), "ERC20: transfer from the zero address");
require(RECIPIENT4 != address(0), "ERC20: transfer to the zero address");
_BEFORETOKENTRANSFER5(SENDER7, RECIPIENT4, AMOUNT10);
_BALANCES7[SENDER7] = _BALANCES7[SENDER7].SUB6(AMOUNT10, "ERC20: transfer amount exceeds balance");
_BALANCES7[RECIPIENT4] = _BALANCES7[RECIPIENT4].ADD8(AMOUNT10);
emit TRANSFER10(SENDER7, RECIPIENT4, AMOUNT10);
}
function _MINT8(address ACCOUNT8, uint AMOUNT10) internal { //inject NONSTANDARD NAMING
require(ACCOUNT8 != address(0), "ERC20: mint to the zero address");
_BEFORETOKENTRANSFER5(address(0), ACCOUNT8, AMOUNT10);
_TOTALSUPPLY10 = _TOTALSUPPLY10.ADD8(AMOUNT10);
_BALANCES7[ACCOUNT8] = _BALANCES7[ACCOUNT8].ADD8(AMOUNT10);
emit TRANSFER10(address(0), ACCOUNT8, AMOUNT10);
}
function _BURN2(address ACCOUNT8, uint AMOUNT10) internal { //inject NONSTANDARD NAMING
require(ACCOUNT8 != address(0), "ERC20: burn from the zero address");
_BEFORETOKENTRANSFER5(ACCOUNT8, address(0), AMOUNT10);
_BALANCES7[ACCOUNT8] = _BALANCES7[ACCOUNT8].SUB6(AMOUNT10, "ERC20: burn amount exceeds balance");
_TOTALSUPPLY10 = _TOTALSUPPLY10.SUB6(AMOUNT10);
emit TRANSFER10(ACCOUNT8, address(0), AMOUNT10);
}
function _APPROVE9(address OWNER10, address SPENDER9, uint AMOUNT10) internal { //inject NONSTANDARD NAMING
require(OWNER10 != address(0), "ERC20: approve from the zero address");
require(SPENDER9 != address(0), "ERC20: approve to the zero address");
_ALLOWANCES5[OWNER10][SPENDER9] = AMOUNT10;
emit APPROVAL6(OWNER10, SPENDER9, AMOUNT10);
}
function _BEFORETOKENTRANSFER5(address FROM9, address TO4, uint256 AMOUNT10) internal { } //inject NONSTANDARD NAMING
}
contract erc20detailed3 is ierc207 { //inject NONSTANDARD NAMING
string private _NAME4; //inject NONSTANDARD NAMING
string private _SYMBOL3; //inject NONSTANDARD NAMING
uint8 private _DECIMALS5; //inject NONSTANDARD NAMING
uint256 private _CAP1; //inject NONSTANDARD NAMING
constructor (string memory NAME1, string memory SYMBOL10, uint8 DECIMALS2, uint256 CAP9) public { //inject NONSTANDARD NAMING
_NAME4 = NAME1;
_SYMBOL3 = SYMBOL10;
_DECIMALS5 = DECIMALS2;
_CAP1 = CAP9;
}
function NAME8() public view returns (string memory) { //inject NONSTANDARD NAMING
return _NAME4;
}
function SYMBOL10() public view returns (string memory) { //inject NONSTANDARD NAMING
return _SYMBOL3;
}
function DECIMALS8() public view returns (uint8) { //inject NONSTANDARD NAMING
return _DECIMALS5;
}
function CAP3() public view returns (uint256) { //inject NONSTANDARD NAMING
return _CAP1;
}
}
library safemath3 { //inject NONSTANDARD NAMING
function ADD8(uint A10, uint B3) internal pure returns (uint) { //inject NONSTANDARD NAMING
uint C10 = A10 + B3; //inject NONSTANDARD NAMING
require(C10 >= A10, "SafeMath: addition overflow");
return C10;
}
function SUB6(uint A10, uint B3) internal pure returns (uint) { //inject NONSTANDARD NAMING
return SUB6(A10, B3, "SafeMath: subtraction overflow");
}
function SUB6(uint A10, uint B3, string memory ERRORMESSAGE2) internal pure returns (uint) { //inject NONSTANDARD NAMING
require(B3 <= A10, ERRORMESSAGE2);
uint C10 = A10 - B3; //inject NONSTANDARD NAMING
return C10;
}
function MUL10(uint A10, uint B3) internal pure returns (uint) { //inject NONSTANDARD NAMING
if (A10 == 0) {
return 0;
}
uint C10 = A10 * B3; //inject NONSTANDARD NAMING
require(C10 / A10 == B3, "SafeMath: multiplication overflow");
return C10;
}
function DIV1(uint A10, uint B3) internal pure returns (uint) { //inject NONSTANDARD NAMING
return DIV1(A10, B3, "SafeMath: division by zero");
}
function DIV1(uint A10, uint B3, string memory ERRORMESSAGE2) internal pure returns (uint) { //inject NONSTANDARD NAMING
// Solidity only automatically asserts when dividing by 0
require(B3 > 0, ERRORMESSAGE2);
uint C10 = A10 / B3; //inject NONSTANDARD NAMING
return C10;
}
}
library address8 { //inject NONSTANDARD NAMING
function ISCONTRACT7(address ACCOUNT8) internal view returns (bool) { //inject NONSTANDARD NAMING
bytes32 CODEHASH8; //inject NONSTANDARD NAMING
bytes32 ACCOUNTHASH10 = 0xc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470; //inject NONSTANDARD NAMING
// solhint-disable-next-line no-inline-assembly
assembly { CODEHASH8 := extcodehash(ACCOUNT8) }
return (CODEHASH8 != 0x0 && CODEHASH8 != ACCOUNTHASH10);
}
}
library safeerc207 { //inject NONSTANDARD NAMING
using safemath3 for uint;
using address8 for address;
function SAFETRANSFER0(ierc207 TOKEN3, address TO4, uint VALUE10) internal { //inject NONSTANDARD NAMING
CALLOPTIONALRETURN7(TOKEN3, abi.encodeWithSelector(TOKEN3.TRANSFER0.selector, TO4, VALUE10));
}
function SAFETRANSFERFROM0(ierc207 TOKEN3, address FROM9, address TO4, uint VALUE10) internal { //inject NONSTANDARD NAMING
CALLOPTIONALRETURN7(TOKEN3, abi.encodeWithSelector(TOKEN3.TRANSFERFROM9.selector, FROM9, TO4, VALUE10));
}
function SAFEAPPROVE8(ierc207 TOKEN3, address SPENDER9, uint VALUE10) internal { //inject NONSTANDARD NAMING
require((VALUE10 == 0) || (TOKEN3.ALLOWANCE8(address(this), SPENDER9) == 0),
"SafeERC20: approve from non-zero to non-zero allowance"
);
CALLOPTIONALRETURN7(TOKEN3, abi.encodeWithSelector(TOKEN3.APPROVE6.selector, SPENDER9, VALUE10));
}
function CALLOPTIONALRETURN7(ierc207 TOKEN3, bytes memory DATA10) private { //inject NONSTANDARD NAMING
require(address(TOKEN3).ISCONTRACT7(), "SafeERC20: call to non-contract");
// solhint-disable-next-line avoid-low-level-calls
(bool SUCCESS10, bytes memory RETURNDATA2) = address(TOKEN3).call(DATA10); //inject NONSTANDARD NAMING
require(SUCCESS10, "SafeERC20: low-level call failed");
if (RETURNDATA2.length > 0) { // Return data is optional
// solhint-disable-next-line max-line-length
require(abi.decode(RETURNDATA2, (bool)), "SafeERC20: ERC20 operation did not succeed");
}
}
}
contract hdt1 is erc209, erc20detailed3 { //inject NONSTANDARD NAMING
using safeerc207 for ierc207;
using address8 for address;
using safemath3 for uint;
address public GOVERNANCE4; //inject NONSTANDARD NAMING
address public PENDINGGOV10; //inject NONSTANDARD NAMING
mapping (address => bool) public MINTERS7; //inject NONSTANDARD NAMING
event NEWPENDINGGOV1(address OLDPENDINGGOV6, address NEWPENDINGGOV5); //inject NONSTANDARD NAMING
event NEWGOV0(address OLDGOV6, address NEWGOV3); //inject NONSTANDARD NAMING
// Modifiers
modifier ONLYGOV3() { //inject NONSTANDARD NAMING
require(msg.sender == GOVERNANCE4, "HUB-Token: !governance");
_;
}
constructor () public erc20detailed3("HUB.finance", "HDT", 18, 800000000 * 10 ** 18) {
GOVERNANCE4 = tx.origin;
}
function MINT5(address _ACCOUNT7, uint256 _AMOUNT8) public { //inject NONSTANDARD NAMING
require(MINTERS7[msg.sender], "HUB-Token: !minter");
_MINT8(_ACCOUNT7, _AMOUNT8);
}
function ADDMINTER2(address _MINTER6) public ONLYGOV3 { //inject NONSTANDARD NAMING
MINTERS7[_MINTER6] = true;
}
function REMOVEMINTER6(address _MINTER6) public ONLYGOV3 { //inject NONSTANDARD NAMING
MINTERS7[_MINTER6] = false;
}
function SETPENDINGGOV6(address _PENDINGGOV2) //inject NONSTANDARD NAMING
external
ONLYGOV3
{
address OLDPENDINGGOV6 = PENDINGGOV10; //inject NONSTANDARD NAMING
PENDINGGOV10 = _PENDINGGOV2;
emit NEWPENDINGGOV1(OLDPENDINGGOV6, _PENDINGGOV2);
}
function ACCEPTGOV3() //inject NONSTANDARD NAMING
external {
require(msg.sender == PENDINGGOV10, "HUB-Token: !pending");
address OLDGOV6 = GOVERNANCE4; //inject NONSTANDARD NAMING
GOVERNANCE4 = PENDINGGOV10;
PENDINGGOV10 = address(0);
emit NEWGOV0(OLDGOV6, GOVERNANCE4);
}
function _BEFORETOKENTRANSFER5(address FROM9, address TO4, uint256 AMOUNT10) internal { //inject NONSTANDARD NAMING
super._BEFORETOKENTRANSFER5(FROM9, TO4, AMOUNT10);
if (FROM9 == address(0)) { // When minting tokens
require(TOTALSUPPLY3().ADD8(AMOUNT10) <= CAP3(), "HUB-Token: Cap exceeded");
}
}
} | inject NONSTANDARD NAMING
| contract erc20detailed3 is ierc207 { | 5,469,230 | [
1,
22170,
18708,
882,
18264,
423,
2192,
1360,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
16351,
6445,
71,
3462,
72,
6372,
23,
353,
277,
12610,
3462,
27,
288,
202,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
] |
pragma solidity 0.5.4;
import {Ownable} from "./ownable.sol";
import {Editable} from "./editable.sol";
import {Content} from "./content.sol";
import {Container} from "./container.sol";
import {AccessIndexor} from "./access_indexor.sol";
import "./user_space.sol";
import "./meta_object.sol";
/* -- Revision history --
BaseContent20190221101600ML: First versioned released
BaseContent20190301121900ML: Adds support for getAccessInfo, to replace getAccessCharge (not deprecated yet)
BaseContent20190315175100ML: Migrated to 0.4.24
BaseContent20190321122100ML: accessRequest returns requestID, removed ml_hash from access_complete event
BaseContent20190510151500ML: creation via ContentSpace factory, modified getAccessInfo API
BaseContent20190510151500ML: creation via ContentSpace factory, modified getAccessInfo API
BaseContent20190522154000SS: Changed hash bytes32 to string
BaseContent20190528193400ML: Modified to support non-library containers
BaseContent20190605203200ML: Splits publish and confirm logic
BaseContent20190724203300ML: Enforces access rights in access request
BaseContent20190801141600ML: Fixes the access rights grant for paid content
BaseContent20191029161700ML: Removed debug statements for accessRequest
BaseContent20191219135200ML: Made content object updatable by non-owner
BaseContent20200102165900ML: Enforce visibility driven rights to edit
BaseContent20200107175100ML: Moved Visibility filter from BaseContentObject to Accessible, default it to 0
BaseContent20200129211300ML: Restricts deletion to owner (not editor) or library owner, unless changed by custom contract
BaseContent20200131120200ML: Adds support for default finalize behavior in runFinalize
BaseContent20200205101900ML: Adds support for non-0 runkill codes in contract swap, allows library editors to delete objects
BaseContent20200205142000ML: Closes vulnerability allowing alien external objects to kill a custom contract
BaseContent20200211163800ML: Modified to conform to authV3 API
BaseContent20200212101200ML: Disambiguatea getAccessInfo vs getAccessInfoV3 to reflect API changes
BaseContent20200316135000ML: Leverages inherited hasAccess
BaseContent20200422180500ML: Version update to reflect changes made to editable to fix deletion
BaseContent20200803130000PO: Authv3 changes
BaseContent20200928110000PO: Replace tx.origin with msg.sender in some cases
*/
contract BaseContent is MetaObject, Editable {
bytes32 public version ="BaseContent20200928110000PO"; //class name (max 16), date YYYYMMDD, time HHMMSS and Developer initials XX
address payable public contentType;
address public addressKMS;
address payable public contentContractAddress;
address payable public libraryAddress;
uint256 public accessCharge;
//bool refundable;
int public statusCode; // 0: accessible, - in draft, + in review
// application have discretion to make up their own status codes to represent their workflow
// bytes32 public constant STATUS_PUBLISHED = "Published";
// bytes32 public constant STATUS_DRAFT = "Draft";
// bytes32 public constant STATUS_REVIEW = "Draft in review";
uint256 public requestID = 0;
struct RequestData {
address payable originator; // client address requesting
uint256 amountPaid; // number of token received
int8 status; //0 access requested, 1 access granted, -1 access refused, 2 access completed, -2 access error
uint256 settled; //Amount of the escrowed money (amountPaid) that has been settled (paid to owner or refunded)
}
mapping(uint256 => RequestData) public requestMap;
event ContentObjectCreate(address containingLibrary);
event SetContentType(address contentType, address contentContractAddress);
event LogPayment(uint256 requestNonce, string label, address payee, uint256 amount);
event AccessRequestValue(bytes32 customValue);
event AccessRequestStakeholder(address stakeholder);
event AccessRequest( //For backward compatibility
uint256 requestID,
uint8 level,
string contentHash,
string pkeRequestor,
string pkeAFGH
);
event AccessComplete(uint256 requestID, uint256 scorePct, bool customContractResult);
event AccessCompleteV3(
uint256 requestNonce,
bool customContractResult,
address parentAddress,
bytes32 contextHash,
address accessor, // I've called this 'userAddress' - don't care too much but ideally it's the same name wherever it means the same thing!
uint256 request_timestamp // always millis - either set from context or with blockchain now()
);
event SetContentContract(address contentContractAddress);
event SetAccessCharge(uint256 accessCharge);
event InsufficientFunds(uint256 accessCharge, uint256 amountProvided);
event SetStatusCode(int statusCode);
event Publish(bool requestStatus, int statusCode, string objectHash);
// Debug events
// event InvokeCustomPreHook(address custom_contract);
// event ReturnCustomHook(address custom_contract, uint256 result);
// event InvokeCustomPostHook(address custom_contract);
modifier onlyFromLibrary() {
require(msg.sender == libraryAddress);
_;
}
constructor(address payable content_space, address payable lib, address payable content_type) public payable {
contentSpace = content_space;
libraryAddress = lib;
statusCode = -1;
contentType = content_type;
visibility = 0; //default could be made a function of the library.
indexCategory = 1; // AccessIndexor CATEGORY_CONTENT_OBJECT
emit ContentObjectCreate(libraryAddress);
}
// function statusDescription() public view returns (bytes32) {
// return statusCodeDescription(statusCode);
// }
function setVisibility(uint8 _visibility_code) public onlyEditor {
visibility = _visibility_code;
emit VisibilityChanged(contentSpace, libraryAddress, visibility);
}
// function statusCodeDescription(int status_code) public view returns (bytes32) {
// bytes32 codeDescription = 0x0;
// if (contentContractAddress != 0x0) {
// Content c = Content(contentContractAddress);
// codeDescription = c.runDescribeStatus(status_code);
// }
// if (codeDescription != 0x0) {
// return codeDescription;
// }
// if (status_code == 0) {
// return STATUS_PUBLISHED;
// }
// if (status_code < 0) {
// return STATUS_DRAFT;
// }
// if (status_code > 0) {
// return STATUS_REVIEW;
// }
// return 0;
// }
function setStatusCode(int status_code) public returns (int) {
if ((msg.sender == owner) && ((status_code < 0) || ((status_code > 0) && (statusCode < 0)))) {
//Owner can revert content to draft mode regardless of status (debatable for published, viewable content)
// and owner can move status from draft to in review
statusCode = status_code;
}
if (msg.sender == libraryAddress) {
// Library has full authority to change status, it is assumed entitlement is done there
statusCode = status_code;
}
emit SetStatusCode(statusCode);
return statusCode;
}
function setAddressKMS(address address_KMS) public onlyEditor {
addressKMS = address_KMS;
}
function getKMSInfo(bytes memory prefix) public view returns (string memory, string memory) {
IKmsSpace kmsSpaceObj = IKmsSpace(contentSpace);
if (addressKMS == address(0x0) || kmsSpaceObj.checkKMSAddr(addressKMS) == 0) {
return ("", "");
}
return kmsSpaceObj.getKMSInfo(kmsSpaceObj.getKMSID(addressKMS), prefix);
}
//Owner can change this, unless the contract they are already set it prevent them to do so.
function setContentContractAddress(address payable addr) public onlyEditor {
Content c;
if (contentContractAddress != address(0x0)) {
c = Content(contentContractAddress);
uint killStatus = c.runKillExt();
if ((killStatus == 100) || (killStatus == 1100)) {
c.commandKill();
} else {
require((killStatus == 0) || (killStatus == 1000));
}
}
contentContractAddress = addr;
if (addr != address(0x0)) {
c = Content(addr);
uint createStatus = c.runCreate();
require(createStatus == 0);
}
emit SetContentContract(contentContractAddress);
}
// Visibility codes
// 0 -> visible
// 10 -> content not published
// 100 -> calculation of price exceeds specified cap (accessCharge)
// 255 -> unset
// Access codes
// 0 -> paid for
// 10 -> content not published
// 100 -> content available if paid for
// 255 -> unset
function getWIPAccessInfo(address accessor) private view returns (uint8, uint8, uint256) {
if ((accessor == owner) || (visibility >= CAN_ACCESS) ){
return (0, 0, accessCharge);
}
IUserSpace userSpaceObj = IUserSpace(contentSpace);
address userWallet = userSpaceObj.userWallets(accessor);
if (userWallet != address(0x0)) {
/*
AccessIndexor wallet = AccessIndexor(userWallet);
if (wallet.checkContentObjectRights(address(this), wallet.TYPE_ACCESS()) == true) {
return (0, 0, accessCharge);
}
*/
if (hasAccess(accessor) == true) {
return (0, 0, accessCharge);
}
}
if (Container(libraryAddress).canReview(accessor) == true) { //special case of pre-publish review
return (0, 0, accessCharge);
}
return (10, 10, accessCharge);
}
function getCustomInfo(address accessor, bytes32[] memory customValues, address payable[] memory stakeholders) public view returns (uint8, uint8, uint256) {
uint256 calculatedCharge = accessCharge;
uint8[2] memory codes;
codes[0] = (visibility >= CAN_SEE) ? 0 : 255; // visibilityCode
codes[1] = (visibility >= CAN_ACCESS) ? 0 :255; //accessCode
if (contentContractAddress != address(0x0)) {
uint8 customMask;
uint8 customVisibility;
uint8 customAccess;
uint256 customCharge;
(customMask, customVisibility, customAccess, customCharge) = Content(contentContractAddress).runAccessInfo(customValues, stakeholders, accessor);
if (customCharge > accessCharge) {
codes[0] = 100;
} else {
if ((customMask & 1 /*DEFAULT_SEE*/) == 0) {
codes[0] = customVisibility;
}
if ((customMask & 2 /*DEFAULT_ACCESS*/) == 0) {
codes[1] = customAccess;
}
if ((customMask & 4 /*DEFAULT_CHARGE*/) == 0) {
calculatedCharge = customCharge;
}
}
}
return (codes[0], codes[1], calculatedCharge);
}
function getAccessInfo(uint8, bytes32[] memory customValues, address payable[] memory stakeholders) public view returns (uint8, uint8, uint256) { //legacy
return getAccessInfoV3(msg.sender, customValues, stakeholders);
}
function getAccessInfoV3(address accessor, bytes32[] memory customValues, address payable[] memory stakeholders) public view returns (uint8, uint8, uint256) {
if (statusCode != 0) {
return getWIPAccessInfo(accessor); //broken out to reduce complexity (compiler failed)
}
uint256 calculatedCharge;
uint8 visibilityCode;
uint8 accessCode;
(visibilityCode, accessCode, calculatedCharge) = getCustomInfo(accessor, customValues, stakeholders);//broken out to reduce complexity (compiler failed)
if ((visibilityCode == 255) || (accessCode == 255) ) {
IUserSpace userSpaceObj = IUserSpace(contentSpace);
address payable userWallet = address(uint160(userSpaceObj.userWallets(accessor)));
if (userWallet != address(0x0)) {
if (visibilityCode == 255) { //No custom calculations
if (AccessIndexor(userWallet).checkRights(indexCategory, address(this), 0) /*canSee(accessor)*/ == true) {
visibilityCode = 0;
}
}
if (visibilityCode == 0) { //if content is not visible, no point in checking if it is accessible
if (accessCode == 255) {
if (hasAccess(accessor) == true) {
accessCode = 0;
} else {
accessCode = 100; //content accessible if paid for
}
}
}
/*
AccessIndexor wallet = AccessIndexor(userWallet);
if (visibilityCode == 255) { //No custom calculations
if (wallet.checkContentObjectRights(address(this), wallet.TYPE_SEE()) == true) {
visibilityCode = 0;
}
}
if (visibilityCode == 0) { //if content is not visible, no point in checking if it is accessible
if (accessCode == 255) {
if (wallet.checkContentObjectRights(address(this), wallet.TYPE_ACCESS()) == true) {
accessCode = 0;
} else {
accessCode = 100; //content accessible if paid for
}
}
}
*/
}
}
return (visibilityCode, accessCode, calculatedCharge);
}
function setAccessCharge(uint256 charge) public onlyEditor returns (uint256) {
accessCharge = charge;
emit SetAccessCharge(accessCharge);
return accessCharge;
}
function canPublish() public view returns (bool) {
// need to check the library address first. if canEdit() is called on a library it reverts because the library
// cannot have a wallet.
return (msg.sender == libraryAddress || canEdit());
}
function canCommit() public view returns (bool) {
return canEdit();
}
function canConfirm() public view returns (bool) {
INodeSpace bcs = INodeSpace(contentSpace);
return bcs.canNodePublish(msg.sender);
}
// override from Editable
function parentAddress() public view returns (address) {
return libraryAddress;
}
// TODO: why payable?
function publish() public payable returns (bool) {
require(canEdit());
bool submitStatus = Container(libraryAddress).publish(address(this));
// Log event
emit Publish(submitStatus, statusCode, objectHash); // TODO: confirm?
return submitStatus;
}
function updateStatus(int status_code) public returns (int) {
require(canPublish());
int newStatusCode;
if (contentContractAddress == address(0x0)) {
newStatusCode = status_code;
} else {
Content c = Content(contentContractAddress);
newStatusCode = c.runStatusChange(status_code);
}
statusCode = newStatusCode;
emit SetStatusCode(statusCode);
return statusCode;
}
//this function allows custom content contract to call makeRequestPayment
function processRequestPayment(uint256 requestNonce, address payable payee, string memory label, uint256 amount) public returns (bool) {
require((contentContractAddress != address(0x0)) && (msg.sender == contentContractAddress));
return makeRequestPayment(requestNonce, payee, label, amount);
}
function makeRequestPayment(uint256 requestNonce, address payable payee, string memory label, uint256 amount) private returns (bool) {
RequestData storage r = requestMap[requestNonce];
if ((r.settled + amount) <= r.amountPaid) {
payee.transfer(amount);
r.settled = r.settled + amount;
emit LogPayment(requestNonce, label, payee, amount);
}
return true;
}
function updateRequest() public {
if (contentContractAddress == address(0x0)) {
super.updateRequest();
} else {
Content c = Content(contentContractAddress);
uint editCode = c.runEdit();
if (editCode == 100) {
super.updateRequest();
} else {
require(editCode == 0);
emit UpdateRequest(objectHash);
}
}
}
function accessRequestContext(
uint256 requestNonce,
bytes32 contextHash,
address accessor,
uint256 request_timestamp
) public payable returns (uint256) {
require(msg.sender == addressKMS);
bytes32[] memory emptyVals;
address payable[] memory emptyAddrs;
return accessRequestInternal(requestNonce, emptyVals, emptyAddrs, contextHash, accessor, request_timestamp);
}
function makeNonce(uint256 reqId) private view returns(uint256) {
return uint256(keccak256(abi.encodePacked(reqId, address(this))));
}
function accessRequestV3(
bytes32[] memory customValues,
address payable[] memory stakeholders
) public payable returns (bool) {
requestID = requestID + 1;
uint256 requestNonce = makeNonce(requestID);
accessRequestInternal(requestNonce, customValues, stakeholders, 0x0, msg.sender, now * 1000);
//The 2 next lines could be moved into accessRequest internal to support payment via statechannel
RequestData memory r = RequestData(msg.sender, msg.value, 0, 0);
requestMap[requestNonce] = r;
return true;
}
// level - the security group for which the access request is for
// pkeAFGH - ephemeral public key of the requestor (AFGH)
// customValues - an array of custom values used to convey additional information
// stakeholders - an array of additional address used to provide additional relevant addresses
function accessRequest( //Left for backward compatibility
uint8,
string memory pkeRequestor,
string memory pkeAFGH,
bytes32[] memory customValues,
address payable[] memory stakeholders
)
public payable returns (uint256) {
accessRequestV3(customValues, stakeholders);
emit AccessRequest(requestID, 0, objectHash, pkeRequestor, pkeAFGH);
return requestID;
}
function validateAccess(address accessor, bytes32[] memory custom_values, address payable[] memory stakeholders) internal {
uint256 requiredFund;
uint8 visibilityCode;
uint8 accessCode;
(visibilityCode, accessCode, requiredFund) = getAccessInfoV3(accessor, custom_values, stakeholders);
if (accessCode == 100) { //Check if request is funded, except if user is owner or has paid already
require(msg.value >= uint(requiredFund));
setPaidRights();
accessCode = 0;
}
require(accessCode == 0);
}
function accessRequestInternal(
uint256 requestNonce,
bytes32[] memory custom_values,
address payable[] memory stakeholders,
bytes32 contextHash,
address accessor,
uint256 request_timestamp
)
internal returns (uint256) {
validateAccess(accessor, custom_values, stakeholders);
if (contentContractAddress != address(0x0)) {
Content c = Content(contentContractAddress);
uint result = c.runAccess(requestNonce, custom_values, stakeholders, accessor);
require(result == 0);
}
// Raise Event
emit AccessRequestV3(requestNonce, libraryAddress, contextHash, accessor, request_timestamp);
// Logs custom key/value pairs
uint256 i;
for (i = 0; i < custom_values.length; i++) {
if (custom_values[i] != 0x0) {
emit AccessRequestValue(custom_values[i]);
}
}
for (i = 0; i < stakeholders.length; i++) {
if (stakeholders[i] != address(0x0)) {
emit AccessRequestStakeholder(stakeholders[i]);
}
}
return requestNonce;
}
function accessCompleteInternal(uint256 requestNonce, bytes32[] memory customValues, address[] memory stakeholders) public payable returns (bool) {
bool success = true;
if (contentContractAddress != address(0x0)) {
Content c = Content(contentContractAddress);
uint256 result = c.runFinalize(requestNonce, customValues, stakeholders, msg.sender);
success = (result == 0);
}
return success;
}
function accessCompleteContext(
uint256 _requestNonce,
bytes32 _contextHash,
address _accessor,
uint256 _request_timestamp
) public payable returns (bool) {
require(msg.sender == addressKMS);
bytes32[] memory emptyVals;
address[] memory emptyAddrs;
bool success = accessCompleteInternal(_requestNonce, emptyVals, emptyAddrs);
emit AccessCompleteV3(_requestNonce, success, libraryAddress, _contextHash, _accessor, _request_timestamp);
return success;
}
// sender passes the quality score as pct of best possible (converted to 1-100 scale)
// the fabric provides to this access,
// hash of the version of the ML-computed segment matrix used (stored as a'part'),
// and a maximum credit to a client based on failed SLA (quality)
// score and hash are recorded in an event
// contract has astate variable creditBack
// a credit refund is calculated for the caller (if )
// will true up the charge based on the quality score by transferring tokens back
// to the sender
//
// add a state variable in the contract indicating whether to credit back based on quality score
function accessCompleteV3(uint256 requestNonce, bytes32[] memory customValues, address[] memory stakeholders) public payable returns (bool) {
RequestData storage r = requestMap[requestNonce];
require((r.originator != address(0x0)) && ((msg.sender == r.originator) || (msg.sender == owner)));
bool success = accessCompleteInternal(requestNonce, customValues, stakeholders);
if (msg.sender == r.originator) {//Owner direct call can't modify status to avoid premature clearing of escrow
if (success){
r.status = 2; //access completeted, by default score_pct is not taken into account
} else {
r.status = -2; //access error, only if finalize is returning non-zero code
}
}
// Delete request from map after customContract in case it was needed for execution of custom wrap-up
if (r.settled < r.amountPaid) {
if (r.status <= 0) {
//if access was not granted, payment is returned to originator
makeRequestPayment(requestNonce, r.originator, "refund", r.amountPaid - r.settled);
} else {
//if access was not granted and no error was registered, escrow is released to the owner
makeRequestPayment(requestNonce, owner, "release escrow", r.amountPaid - r.settled);
}
}
delete requestMap[requestNonce];
// record to event
emit AccessCompleteV3(requestNonce, success, libraryAddress, 0x0, msg.sender, now * 1000);
return success;
}
function accessComplete(uint256 request_ID, uint256 score_pct, uint256) public payable returns (bool) {
uint256 requestNonce = makeNonce(requestID);
bytes32[] memory emptyVals;
address[] memory emptyAddrs;
bool success = accessCompleteV3(requestNonce, emptyVals, emptyAddrs);
emit AccessComplete(request_ID, score_pct, success);
return success;
}
function kill() public onlyFromLibrary {
uint canKill = 0;
if (contentContractAddress != address(0x0)) {
canKill = Content(contentContractAddress).runKillExt();
}
require((canKill == 0) || (canKill == 100) || (canKill == 1000) || (canKill == 1100));
// if (canKill < 1000) { //1000 and 1100 imply bypass of normal validation rules
// require(Container(libraryAddress).canEdit());
// }
if ((canKill == 100) || (canKill == 1100)){
Content(contentContractAddress).commandKill();
}
selfdestruct(owner);
}
function setPaidRights() private {
address payable walletAddress = address(uint160(IUserSpace(contentSpace).userWallets(msg.sender)));
AccessIndexor indexor = AccessIndexor(walletAddress);
indexor.setAccessRights();
}
}
| default could be made a function of the library.
| visibility = 0; | 934,861 | [
1,
1886,
3377,
506,
7165,
279,
445,
434,
326,
5313,
18,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
3639,
9478,
273,
374,
31,
225,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
] |
pragma solidity ^0.4.0;
interface ERC20 {
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);
}
// GOO - Crypto Idle Game
// https://ethergoo.io
contract Goo is ERC20 {
string public constant name = "IdleEth";
string public constant symbol = "Goo";
uint8 public constant decimals = 0;
uint256 private roughSupply;
uint256 public totalGooProduction;
address public owner; // Minor management of game
bool public gameStarted;
uint256 public researchDivPercent = 8;
uint256 public gooDepositDivPercent = 2;
uint256 public totalEtherGooResearchPool; // Eth dividends to be split between players' goo production
uint256[] private totalGooProductionSnapshots; // The total goo production for each prior day past
uint256[] private totalGooDepositSnapshots; // The total goo deposited for each prior day past
uint256[] private allocatedGooResearchSnapshots; // Div pot #1 (research eth allocated to each prior day past)
uint256[] private allocatedGooDepositSnapshots; // Div pot #2 (deposit eth allocated to each prior day past)
uint256 public nextSnapshotTime;
// Balances for each player
mapping(address => uint256) private ethBalance;
mapping(address => uint256) private gooBalance;
mapping(address => mapping(uint256 => uint256)) private gooProductionSnapshots; // Store player's goo production for given day (snapshot)
mapping(address => mapping(uint256 => uint256)) private gooDepositSnapshots; // Store player's goo deposited for given day (snapshot)
mapping(address => mapping(uint256 => bool)) private gooProductionZeroedSnapshots; // This isn't great but we need know difference between 0 production and an unused/inactive day.
mapping(address => uint256) private lastGooSaveTime; // Seconds (last time player claimed their produced goo)
mapping(address => uint256) public lastGooProductionUpdate; // Days (last snapshot player updated their production)
mapping(address => uint256) private lastGooResearchFundClaim; // Days (snapshot number)
mapping(address => uint256) private lastGooDepositFundClaim; // Days (snapshot number)
mapping(address => uint256) private battleCooldown; // If user attacks they cannot attack again for short time
// Stuff owned by each player
mapping(address => mapping(uint256 => uint256)) private unitsOwned;
mapping(address => mapping(uint256 => bool)) private upgradesOwned;
mapping(uint256 => address) private rareItemOwner;
mapping(uint256 => uint256) private rareItemPrice;
// Rares & Upgrades (Increase unit's production / attack etc.)
mapping(address => mapping(uint256 => uint256)) private unitGooProductionIncreases; // Adds to the goo per second
mapping(address => mapping(uint256 => uint256)) private unitGooProductionMultiplier; // Multiplies the goo per second
mapping(address => mapping(uint256 => uint256)) private unitAttackIncreases;
mapping(address => mapping(uint256 => uint256)) private unitAttackMultiplier;
mapping(address => mapping(uint256 => uint256)) private unitDefenseIncreases;
mapping(address => mapping(uint256 => uint256)) private unitDefenseMultiplier;
mapping(address => mapping(uint256 => uint256)) private unitGooStealingIncreases;
mapping(address => mapping(uint256 => uint256)) private unitGooStealingMultiplier;
mapping(address => mapping(uint256 => uint256)) private unitMaxCap;
// Mapping of approved ERC20 transfers (by player)
mapping(address => mapping(address => uint256)) private allowed;
mapping(address => bool) private protectedAddresses; // For npc exchanges (requires 0 goo production)
// Raffle structures
struct TicketPurchases {
TicketPurchase[] ticketsBought;
uint256 numPurchases; // Allows us to reset without clearing TicketPurchase[] (avoids potential for gas limit)
uint256 raffleId;
}
// Allows us to query winner without looping (avoiding potential for gas limit)
struct TicketPurchase {
uint256 startId;
uint256 endId;
}
// Raffle tickets
mapping(address => TicketPurchases) private rareItemTicketsBoughtByPlayer;
mapping(uint256 => address[]) private itemRafflePlayers;
// Duplicating for the two raffles is not ideal
mapping(address => TicketPurchases) private rareUnitTicketsBoughtByPlayer;
mapping(uint256 => address[]) private unitRafflePlayers;
// Item raffle info
uint256 private constant RAFFLE_TICKET_BASE_GOO_PRICE = 1000;
uint256 private itemRaffleEndTime;
uint256 private itemRaffleRareId;
uint256 private itemRaffleTicketsBought;
address private itemRaffleWinner; // Address of winner
bool private itemRaffleWinningTicketSelected;
uint256 private itemRaffleTicketThatWon;
// Unit raffle info
uint256 private unitRaffleEndTime;
uint256 private unitRaffleId; // Raffle Id
uint256 private unitRaffleRareId; // Unit Id
uint256 private unitRaffleTicketsBought;
address private unitRaffleWinner; // Address of winner
bool private unitRaffleWinningTicketSelected;
uint256 private unitRaffleTicketThatWon;
// Minor game events
event UnitBought(address player, uint256 unitId, uint256 amount);
event UnitSold(address player, uint256 unitId, uint256 amount);
event PlayerAttacked(address attacker, address target, bool success, uint256 gooStolen);
event ReferalGain(address player, address referal, uint256 amount);
event UpgradeMigration(address player, uint256 upgradeId, uint256 txProof);
GooGameConfig schema = GooGameConfig(0xf925a82b8c26520170c8d51b65a7def6364877b3);
// Constructor
function Goo() public payable {
owner = msg.sender;
}
function() payable {
// Fallback will donate to pot
totalEtherGooResearchPool += msg.value;
}
function beginGame(uint256 firstDivsTime) external payable {
require(msg.sender == owner);
require(!gameStarted);
gameStarted = true; // GO-OOOO!
nextSnapshotTime = firstDivsTime;
totalGooDepositSnapshots.push(0); // Add initial-zero snapshot
totalEtherGooResearchPool = msg.value; // Seed pot
}
// Incase community prefers goo deposit payments over production %, can be tweaked for balance
function tweakDailyDividends(uint256 newResearchPercent, uint256 newGooDepositPercent) external {
require(msg.sender == owner);
require(newResearchPercent > 0 && newResearchPercent <= 10);
require(newGooDepositPercent > 0 && newGooDepositPercent <= 10);
researchDivPercent = newResearchPercent;
gooDepositDivPercent = newGooDepositPercent;
}
function totalSupply() public constant returns(uint256) {
return roughSupply; // Stored goo (rough supply as it ignores earned/unclaimed goo)
}
function balanceOf(address player) public constant returns(uint256) {
return gooBalance[player] + balanceOfUnclaimedGoo(player);
}
function balanceOfUnclaimedGoo(address player) internal constant returns (uint256) {
uint256 lastSave = lastGooSaveTime[player];
if (lastSave > 0 && lastSave < block.timestamp) {
return (getGooProduction(player) * (block.timestamp - lastSave)) / 100;
}
return 0;
}
function etherBalanceOf(address player) public constant returns(uint256) {
return ethBalance[player];
}
function transfer(address recipient, uint256 amount) public returns (bool) {
updatePlayersGoo(msg.sender);
require(amount <= gooBalance[msg.sender]);
gooBalance[msg.sender] -= amount;
gooBalance[recipient] += amount;
emit Transfer(msg.sender, recipient, amount);
return true;
}
function transferFrom(address player, address recipient, uint256 amount) public returns (bool) {
updatePlayersGoo(player);
require(amount <= allowed[player][msg.sender] && amount <= gooBalance[player]);
gooBalance[player] -= amount;
gooBalance[recipient] += amount;
allowed[player][msg.sender] -= amount;
emit Transfer(player, recipient, amount);
return true;
}
function approve(address approvee, uint256 amount) public returns (bool){
allowed[msg.sender][approvee] = amount;
emit Approval(msg.sender, approvee, amount);
return true;
}
function allowance(address player, address approvee) public constant returns(uint256){
return allowed[player][approvee];
}
function getGooProduction(address player) public constant returns (uint256){
return gooProductionSnapshots[player][lastGooProductionUpdate[player]];
}
function updatePlayersGoo(address player) internal {
uint256 gooGain = balanceOfUnclaimedGoo(player);
lastGooSaveTime[player] = block.timestamp;
roughSupply += gooGain;
gooBalance[player] += gooGain;
}
function updatePlayersGooFromPurchase(address player, uint256 purchaseCost) internal {
uint256 unclaimedGoo = balanceOfUnclaimedGoo(player);
if (purchaseCost > unclaimedGoo) {
uint256 gooDecrease = purchaseCost - unclaimedGoo;
require(gooBalance[player] >= gooDecrease);
roughSupply -= gooDecrease;
gooBalance[player] -= gooDecrease;
} else {
uint256 gooGain = unclaimedGoo - purchaseCost;
roughSupply += gooGain;
gooBalance[player] += gooGain;
}
lastGooSaveTime[player] = block.timestamp;
}
function increasePlayersGooProduction(address player, uint256 increase) internal {
gooProductionSnapshots[player][allocatedGooResearchSnapshots.length] = getGooProduction(player) + increase;
lastGooProductionUpdate[player] = allocatedGooResearchSnapshots.length;
totalGooProduction += increase;
}
function reducePlayersGooProduction(address player, uint256 decrease) internal {
uint256 previousProduction = getGooProduction(player);
uint256 newProduction = SafeMath.sub(previousProduction, decrease);
if (newProduction == 0) { // Special case which tangles with "inactive day" snapshots (claiming divs)
gooProductionZeroedSnapshots[player][allocatedGooResearchSnapshots.length] = true;
delete gooProductionSnapshots[player][allocatedGooResearchSnapshots.length]; // 0
} else {
gooProductionSnapshots[player][allocatedGooResearchSnapshots.length] = newProduction;
}
lastGooProductionUpdate[player] = allocatedGooResearchSnapshots.length;
totalGooProduction -= decrease;
}
function buyBasicUnit(uint256 unitId, uint256 amount) external {
uint256 schemaUnitId;
uint256 gooProduction;
uint256 gooCost;
uint256 ethCost;
uint256 existing = unitsOwned[msg.sender][unitId];
(schemaUnitId, gooProduction, gooCost, ethCost) = schema.getUnitInfo(unitId, existing, amount);
require(gameStarted);
require(schemaUnitId > 0); // Valid unit
require(ethCost == 0); // Free unit
uint256 newTotal = SafeMath.add(existing, amount);
if (newTotal > 99) { // Default unit limit
require(newTotal <= unitMaxCap[msg.sender][unitId]); // Housing upgrades (allow more units)
}
// Update players goo
updatePlayersGooFromPurchase(msg.sender, gooCost);
if (gooProduction > 0) {
increasePlayersGooProduction(msg.sender, getUnitsProduction(msg.sender, unitId, amount));
}
unitsOwned[msg.sender][unitId] = newTotal;
emit UnitBought(msg.sender, unitId, amount);
}
function buyEthUnit(uint256 unitId, uint256 amount) external payable {
uint256 schemaUnitId;
uint256 gooProduction;
uint256 gooCost;
uint256 ethCost;
uint256 existing = unitsOwned[msg.sender][unitId];
(schemaUnitId, gooProduction, gooCost, ethCost) = schema.getUnitInfo(unitId, existing, amount);
require(gameStarted);
require(schemaUnitId > 0);
require(ethBalance[msg.sender] + msg.value >= ethCost);
if (ethCost > msg.value) {
ethBalance[msg.sender] -= (ethCost - msg.value);
}
uint256 devFund = ethCost / 50; // 2% fee on purchases (marketing, gameplay & maintenance)
uint256 dividends = (ethCost - devFund) / 4; // 25% goes to pool (75% retained for sale value)
totalEtherGooResearchPool += dividends;
ethBalance[owner] += devFund;
uint256 newTotal = SafeMath.add(existing, amount);
if (newTotal > 99) { // Default unit limit
require(newTotal <= unitMaxCap[msg.sender][unitId]); // Housing upgrades (allow more units)
}
// Update players goo
updatePlayersGooFromPurchase(msg.sender, gooCost);
if (gooProduction > 0) {
increasePlayersGooProduction(msg.sender, getUnitsProduction(msg.sender, unitId, amount));
}
unitsOwned[msg.sender][unitId] += amount;
emit UnitBought(msg.sender, unitId, amount);
}
function sellUnit(uint256 unitId, uint256 amount) external {
uint256 existing = unitsOwned[msg.sender][unitId];
require(existing >= amount && amount > 0);
existing -= amount;
unitsOwned[msg.sender][unitId] = existing;
uint256 schemaUnitId;
uint256 gooProduction;
uint256 gooCost;
uint256 ethCost;
(schemaUnitId, gooProduction, gooCost, ethCost) = schema.getUnitInfo(unitId, existing, amount);
require(schema.unitSellable(unitId));
uint256 gooChange = balanceOfUnclaimedGoo(msg.sender) + ((gooCost * 3) / 4); // Claim unsaved goo whilst here
lastGooSaveTime[msg.sender] = block.timestamp;
roughSupply += gooChange;
gooBalance[msg.sender] += gooChange;
if (gooProduction > 0) {
reducePlayersGooProduction(msg.sender, getUnitsProduction(msg.sender, unitId, amount));
}
if (ethCost > 0) { // Premium units sell for 75% of buy cost
ethBalance[msg.sender] += (ethCost * 3) / 4;
}
emit UnitSold(msg.sender, unitId, amount);
}
function buyUpgrade(uint256 upgradeId) external payable {
uint256 gooCost;
uint256 ethCost;
uint256 upgradeClass;
uint256 unitId;
uint256 upgradeValue;
uint256 prerequisiteUpgrade;
(gooCost, ethCost, upgradeClass, unitId, upgradeValue, prerequisiteUpgrade) = schema.getUpgradeInfo(upgradeId);
require(gameStarted);
require(unitId > 0); // Valid upgrade
require(!upgradesOwned[msg.sender][upgradeId]); // Haven't already purchased
if (prerequisiteUpgrade > 0) {
require(upgradesOwned[msg.sender][prerequisiteUpgrade]);
}
if (ethCost > 0) {
require(ethBalance[msg.sender] + msg.value >= ethCost);
if (ethCost > msg.value) { // They can use their balance instead
ethBalance[msg.sender] -= (ethCost - msg.value);
}
uint256 devFund = ethCost / 50; // 2% fee on purchases (marketing, gameplay & maintenance)
totalEtherGooResearchPool += (ethCost - devFund); // Rest goes to div pool (Can't sell upgrades)
ethBalance[owner] += devFund;
}
// Update players goo
updatePlayersGooFromPurchase(msg.sender, gooCost);
upgradeUnitMultipliers(msg.sender, upgradeClass, unitId, upgradeValue);
upgradesOwned[msg.sender][upgradeId] = true;
}
function upgradeUnitMultipliers(address player, uint256 upgradeClass, uint256 unitId, uint256 upgradeValue) internal {
uint256 productionGain;
if (upgradeClass == 0) {
unitGooProductionIncreases[player][unitId] += upgradeValue;
productionGain = unitsOwned[player][unitId] * upgradeValue * (10 + unitGooProductionMultiplier[player][unitId]);
increasePlayersGooProduction(player, productionGain);
} else if (upgradeClass == 1) {
unitGooProductionMultiplier[player][unitId] += upgradeValue;
productionGain = unitsOwned[player][unitId] * upgradeValue * (schema.unitGooProduction(unitId) + unitGooProductionIncreases[player][unitId]);
increasePlayersGooProduction(player, productionGain);
} else if (upgradeClass == 2) {
unitAttackIncreases[player][unitId] += upgradeValue;
} else if (upgradeClass == 3) {
unitAttackMultiplier[player][unitId] += upgradeValue;
} else if (upgradeClass == 4) {
unitDefenseIncreases[player][unitId] += upgradeValue;
} else if (upgradeClass == 5) {
unitDefenseMultiplier[player][unitId] += upgradeValue;
} else if (upgradeClass == 6) {
unitGooStealingIncreases[player][unitId] += upgradeValue;
} else if (upgradeClass == 7) {
unitGooStealingMultiplier[player][unitId] += upgradeValue;
} else if (upgradeClass == 8) {
unitMaxCap[player][unitId] = upgradeValue; // Housing upgrade (new capacity)
}
}
function removeUnitMultipliers(address player, uint256 upgradeClass, uint256 unitId, uint256 upgradeValue) internal {
uint256 productionLoss;
if (upgradeClass == 0) {
unitGooProductionIncreases[player][unitId] -= upgradeValue;
productionLoss = unitsOwned[player][unitId] * upgradeValue * (10 + unitGooProductionMultiplier[player][unitId]);
reducePlayersGooProduction(player, productionLoss);
} else if (upgradeClass == 1) {
unitGooProductionMultiplier[player][unitId] -= upgradeValue;
productionLoss = unitsOwned[player][unitId] * upgradeValue * (schema.unitGooProduction(unitId) + unitGooProductionIncreases[player][unitId]);
reducePlayersGooProduction(player, productionLoss);
} else if (upgradeClass == 2) {
unitAttackIncreases[player][unitId] -= upgradeValue;
} else if (upgradeClass == 3) {
unitAttackMultiplier[player][unitId] -= upgradeValue;
} else if (upgradeClass == 4) {
unitDefenseIncreases[player][unitId] -= upgradeValue;
} else if (upgradeClass == 5) {
unitDefenseMultiplier[player][unitId] -= upgradeValue;
} else if (upgradeClass == 6) {
unitGooStealingIncreases[player][unitId] -= upgradeValue;
} else if (upgradeClass == 7) {
unitGooStealingMultiplier[player][unitId] -= upgradeValue;
}
}
function buyRareItem(uint256 rareId) external payable {
uint256 upgradeClass;
uint256 unitId;
uint256 upgradeValue;
(upgradeClass, unitId, upgradeValue) = schema.getRareInfo(rareId);
address previousOwner = rareItemOwner[rareId];
require(previousOwner != 0);
require(unitId > 0);
// We have to claim buyer's goo before updating their production values
updatePlayersGoo(msg.sender);
upgradeUnitMultipliers(msg.sender, upgradeClass, unitId, upgradeValue);
// We have to claim seller's goo before reducing their production values
updatePlayersGoo(previousOwner);
removeUnitMultipliers(previousOwner, upgradeClass, unitId, upgradeValue);
uint256 ethCost = rareItemPrice[rareId];
require(ethBalance[msg.sender] + msg.value >= ethCost);
// Splitbid/Overbid
if (ethCost > msg.value) {
// Earlier require() said they can still afford it (so use their ingame balance)
ethBalance[msg.sender] -= (ethCost - msg.value);
} else if (msg.value > ethCost) {
// Store overbid in their balance
ethBalance[msg.sender] += msg.value - ethCost;
}
// Distribute ethCost
uint256 devFund = ethCost / 50; // 2% fee on purchases (marketing, gameplay & maintenance)
uint256 dividends = ethCost / 20; // 5% goes to pool (~93% goes to player)
totalEtherGooResearchPool += dividends;
ethBalance[owner] += devFund;
// Transfer / update rare item
rareItemOwner[rareId] = msg.sender;
rareItemPrice[rareId] = (ethCost * 5) / 4; // 25% price flip increase
ethBalance[previousOwner] += ethCost - (dividends + devFund);
}
function withdrawEther(uint256 amount) external {
require(amount <= ethBalance[msg.sender]);
ethBalance[msg.sender] -= amount;
msg.sender.transfer(amount);
}
function fundGooResearch(uint256 amount) external {
updatePlayersGooFromPurchase(msg.sender, amount);
gooDepositSnapshots[msg.sender][totalGooDepositSnapshots.length - 1] += amount;
totalGooDepositSnapshots[totalGooDepositSnapshots.length - 1] += amount;
}
function claimResearchDividends(address referer, uint256 startSnapshot, uint256 endSnapShot) external {
require(startSnapshot <= endSnapShot);
require(startSnapshot >= lastGooResearchFundClaim[msg.sender]);
require(endSnapShot < allocatedGooResearchSnapshots.length);
uint256 researchShare;
uint256 previousProduction = gooProductionSnapshots[msg.sender][lastGooResearchFundClaim[msg.sender] - 1]; // Underflow won't be a problem as gooProductionSnapshots[][0xffffffffff] = 0;
for (uint256 i = startSnapshot; i <= endSnapShot; i++) {
// Slightly complex things by accounting for days/snapshots when user made no tx's
uint256 productionDuringSnapshot = gooProductionSnapshots[msg.sender][i];
bool soldAllProduction = gooProductionZeroedSnapshots[msg.sender][i];
if (productionDuringSnapshot == 0 && !soldAllProduction) {
productionDuringSnapshot = previousProduction;
} else {
previousProduction = productionDuringSnapshot;
}
researchShare += (allocatedGooResearchSnapshots[i] * productionDuringSnapshot) / totalGooProductionSnapshots[i];
}
if (gooProductionSnapshots[msg.sender][endSnapShot] == 0 && !gooProductionZeroedSnapshots[msg.sender][endSnapShot] && previousProduction > 0) {
gooProductionSnapshots[msg.sender][endSnapShot] = previousProduction; // Checkpoint for next claim
}
lastGooResearchFundClaim[msg.sender] = endSnapShot + 1;
uint256 referalDivs;
if (referer != address(0) && referer != msg.sender) {
referalDivs = researchShare / 100; // 1%
ethBalance[referer] += referalDivs;
emit ReferalGain(referer, msg.sender, referalDivs);
}
ethBalance[msg.sender] += researchShare - referalDivs;
}
function claimGooDepositDividends(address referer, uint256 startSnapshot, uint256 endSnapShot) external {
require(startSnapshot <= endSnapShot);
require(startSnapshot >= lastGooDepositFundClaim[msg.sender]);
require(endSnapShot < allocatedGooDepositSnapshots.length);
uint256 depositShare;
for (uint256 i = startSnapshot; i <= endSnapShot; i++) {
depositShare += (allocatedGooDepositSnapshots[i] * gooDepositSnapshots[msg.sender][i]) / totalGooDepositSnapshots[i];
}
lastGooDepositFundClaim[msg.sender] = endSnapShot + 1;
uint256 referalDivs;
if (referer != address(0) && referer != msg.sender) {
referalDivs = depositShare / 100; // 1%
ethBalance[referer] += referalDivs;
emit ReferalGain(referer, msg.sender, referalDivs);
}
ethBalance[msg.sender] += depositShare - referalDivs;
}
// Allocate pot #1 divs for the day (00:00 cron job)
function snapshotDailyGooResearchFunding() external {
require(msg.sender == owner);
uint256 todaysGooResearchFund = (totalEtherGooResearchPool * researchDivPercent) / 100; // 8% of pool daily
totalEtherGooResearchPool -= todaysGooResearchFund;
totalGooProductionSnapshots.push(totalGooProduction);
allocatedGooResearchSnapshots.push(todaysGooResearchFund);
nextSnapshotTime = block.timestamp + 24 hours;
}
// Allocate pot #2 divs for the day (12:00 cron job)
function snapshotDailyGooDepositFunding() external {
require(msg.sender == owner);
uint256 todaysGooDepositFund = (totalEtherGooResearchPool * gooDepositDivPercent) / 100; // 2% of pool daily
totalEtherGooResearchPool -= todaysGooDepositFund;
totalGooDepositSnapshots.push(0); // Reset for to store next day's deposits
allocatedGooDepositSnapshots.push(todaysGooDepositFund); // Store to payout divs for previous day deposits
}
// Raffle for rare items
function buyItemRaffleTicket(uint256 amount) external {
require(itemRaffleEndTime >= block.timestamp);
require(amount > 0);
uint256 ticketsCost = SafeMath.mul(RAFFLE_TICKET_BASE_GOO_PRICE, amount);
require(balanceOf(msg.sender) >= ticketsCost);
// Update players goo
updatePlayersGooFromPurchase(msg.sender, ticketsCost);
// Handle new tickets
TicketPurchases storage purchases = rareItemTicketsBoughtByPlayer[msg.sender];
// If we need to reset tickets from a previous raffle
if (purchases.raffleId != itemRaffleRareId) {
purchases.numPurchases = 0;
purchases.raffleId = itemRaffleRareId;
itemRafflePlayers[itemRaffleRareId].push(msg.sender); // Add user to raffle
}
// Store new ticket purchase
if (purchases.numPurchases == purchases.ticketsBought.length) {
purchases.ticketsBought.length += 1;
}
purchases.ticketsBought[purchases.numPurchases++] = TicketPurchase(itemRaffleTicketsBought, itemRaffleTicketsBought + (amount - 1)); // (eg: buy 10, get id's 0-9)
// Finally update ticket total
itemRaffleTicketsBought += amount;
}
// Raffle for rare units
function buyUnitRaffleTicket(uint256 amount) external {
require(unitRaffleEndTime >= block.timestamp);
require(amount > 0);
uint256 ticketsCost = SafeMath.mul(RAFFLE_TICKET_BASE_GOO_PRICE, amount);
require(balanceOf(msg.sender) >= ticketsCost);
// Update players goo
updatePlayersGooFromPurchase(msg.sender, ticketsCost);
// Handle new tickets
TicketPurchases storage purchases = rareUnitTicketsBoughtByPlayer[msg.sender];
// If we need to reset tickets from a previous raffle
if (purchases.raffleId != unitRaffleId) {
purchases.numPurchases = 0;
purchases.raffleId = unitRaffleId;
unitRafflePlayers[unitRaffleId].push(msg.sender); // Add user to raffle
}
// Store new ticket purchase
if (purchases.numPurchases == purchases.ticketsBought.length) {
purchases.ticketsBought.length += 1;
}
purchases.ticketsBought[purchases.numPurchases++] = TicketPurchase(unitRaffleTicketsBought, unitRaffleTicketsBought + (amount - 1)); // (eg: buy 10, get id's 0-9)
// Finally update ticket total
unitRaffleTicketsBought += amount;
}
function startItemRaffle(uint256 endTime, uint256 rareId) external {
require(msg.sender == owner);
require(schema.validRareId(rareId));
require(rareItemOwner[rareId] == 0);
require(block.timestamp < endTime);
if (itemRaffleRareId != 0) { // Sanity to assure raffle has ended before next one starts
require(itemRaffleWinner != 0);
}
// Reset previous raffle info
itemRaffleWinningTicketSelected = false;
itemRaffleTicketThatWon = 0;
itemRaffleWinner = 0;
itemRaffleTicketsBought = 0;
// Set current raffle info
itemRaffleEndTime = endTime;
itemRaffleRareId = rareId;
}
function startUnitRaffle(uint256 endTime, uint256 unitId) external {
require(msg.sender == owner);
require(block.timestamp < endTime);
if (unitRaffleRareId != 0) { // Sanity to assure raffle has ended before next one starts
require(unitRaffleWinner != 0);
}
// Reset previous raffle info
unitRaffleWinningTicketSelected = false;
unitRaffleTicketThatWon = 0;
unitRaffleWinner = 0;
unitRaffleTicketsBought = 0;
// Set current raffle info
unitRaffleEndTime = endTime;
unitRaffleRareId = unitId;
unitRaffleId++; // Can't use unitRaffleRareId (as rare units are not unique)
}
function awardItemRafflePrize(address checkWinner, uint256 checkIndex) external {
require(itemRaffleEndTime < block.timestamp);
require(itemRaffleWinner == 0);
require(rareItemOwner[itemRaffleRareId] == 0);
if (!itemRaffleWinningTicketSelected) {
drawRandomItemWinner(); // Ideally do it in one call (gas limit cautious)
}
// Reduce gas by (optionally) offering an address to _check_ for winner
if (checkWinner != 0) {
TicketPurchases storage tickets = rareItemTicketsBoughtByPlayer[checkWinner];
if (tickets.numPurchases > 0 && checkIndex < tickets.numPurchases && tickets.raffleId == itemRaffleRareId) {
TicketPurchase storage checkTicket = tickets.ticketsBought[checkIndex];
if (itemRaffleTicketThatWon >= checkTicket.startId && itemRaffleTicketThatWon <= checkTicket.endId) {
assignItemRafflePrize(checkWinner); // WINNER!
return;
}
}
}
// Otherwise just naively try to find the winner (will work until mass amounts of players)
for (uint256 i = 0; i < itemRafflePlayers[itemRaffleRareId].length; i++) {
address player = itemRafflePlayers[itemRaffleRareId][i];
TicketPurchases storage playersTickets = rareItemTicketsBoughtByPlayer[player];
uint256 endIndex = playersTickets.numPurchases - 1;
// Minor optimization to avoid checking every single player
if (itemRaffleTicketThatWon >= playersTickets.ticketsBought[0].startId && itemRaffleTicketThatWon <= playersTickets.ticketsBought[endIndex].endId) {
for (uint256 j = 0; j < playersTickets.numPurchases; j++) {
TicketPurchase storage playerTicket = playersTickets.ticketsBought[j];
if (itemRaffleTicketThatWon >= playerTicket.startId && itemRaffleTicketThatWon <= playerTicket.endId) {
assignItemRafflePrize(player); // WINNER!
return;
}
}
}
}
}
function awardUnitRafflePrize(address checkWinner, uint256 checkIndex) external {
require(unitRaffleEndTime < block.timestamp);
require(unitRaffleWinner == 0);
if (!unitRaffleWinningTicketSelected) {
drawRandomUnitWinner(); // Ideally do it in one call (gas limit cautious)
}
// Reduce gas by (optionally) offering an address to _check_ for winner
if (checkWinner != 0) {
TicketPurchases storage tickets = rareUnitTicketsBoughtByPlayer[checkWinner];
if (tickets.numPurchases > 0 && checkIndex < tickets.numPurchases && tickets.raffleId == unitRaffleId) {
TicketPurchase storage checkTicket = tickets.ticketsBought[checkIndex];
if (unitRaffleTicketThatWon >= checkTicket.startId && unitRaffleTicketThatWon <= checkTicket.endId) {
assignUnitRafflePrize(checkWinner); // WINNER!
return;
}
}
}
// Otherwise just naively try to find the winner (will work until mass amounts of players)
for (uint256 i = 0; i < unitRafflePlayers[unitRaffleId].length; i++) {
address player = unitRafflePlayers[unitRaffleId][i];
TicketPurchases storage playersTickets = rareUnitTicketsBoughtByPlayer[player];
uint256 endIndex = playersTickets.numPurchases - 1;
// Minor optimization to avoid checking every single player
if (unitRaffleTicketThatWon >= playersTickets.ticketsBought[0].startId && unitRaffleTicketThatWon <= playersTickets.ticketsBought[endIndex].endId) {
for (uint256 j = 0; j < playersTickets.numPurchases; j++) {
TicketPurchase storage playerTicket = playersTickets.ticketsBought[j];
if (unitRaffleTicketThatWon >= playerTicket.startId && unitRaffleTicketThatWon <= playerTicket.endId) {
assignUnitRafflePrize(player); // WINNER!
return;
}
}
}
}
}
function assignItemRafflePrize(address winner) internal {
itemRaffleWinner = winner;
rareItemOwner[itemRaffleRareId] = winner;
rareItemPrice[itemRaffleRareId] = (schema.rareStartPrice(itemRaffleRareId) * 21) / 20; // Buy price slightly higher (Div pool cut)
updatePlayersGoo(winner);
uint256 upgradeClass;
uint256 unitId;
uint256 upgradeValue;
(upgradeClass, unitId, upgradeValue) = schema.getRareInfo(itemRaffleRareId);
upgradeUnitMultipliers(winner, upgradeClass, unitId, upgradeValue);
}
function assignUnitRafflePrize(address winner) internal {
unitRaffleWinner = winner;
updatePlayersGoo(winner);
increasePlayersGooProduction(winner, getUnitsProduction(winner, unitRaffleRareId, 1));
unitsOwned[winner][unitRaffleRareId] += 1;
}
// Random enough for small contests (Owner only to prevent trial & error execution)
function drawRandomItemWinner() public {
require(msg.sender == owner);
require(itemRaffleEndTime < block.timestamp);
require(!itemRaffleWinningTicketSelected);
uint256 seed = itemRaffleTicketsBought + block.timestamp;
itemRaffleTicketThatWon = addmod(uint256(block.blockhash(block.number-1)), seed, itemRaffleTicketsBought);
itemRaffleWinningTicketSelected = true;
}
function drawRandomUnitWinner() public {
require(msg.sender == owner);
require(unitRaffleEndTime < block.timestamp);
require(!unitRaffleWinningTicketSelected);
uint256 seed = unitRaffleTicketsBought + block.timestamp;
unitRaffleTicketThatWon = addmod(uint256(block.blockhash(block.number-1)), seed, unitRaffleTicketsBought);
unitRaffleWinningTicketSelected = true;
}
// Gives players the upgrades they 'previously paid for' (i.e. will be one of same unit/type/value of their v1 purchase)
// Tx of their (prior) purchase is provided so can be validated by anyone for 0 abuse
function migrateV1Upgrades(address[] playerToCredit, uint256[] upgradeIds, uint256[] txProof) external {
require(msg.sender == owner);
require(!gameStarted); // Pre-game migration
for (uint256 i = 0; i < txProof.length; i++) {
address player = playerToCredit[i];
uint256 upgradeId = upgradeIds[i];
uint256 unitId = schema.upgradeUnitId(upgradeId);
if (unitId > 0 && !upgradesOwned[player][upgradeId]) { // Upgrade valid (and haven't already migrated)
uint256 upgradeClass = schema.upgradeClass(upgradeId);
uint256 upgradeValue = schema.upgradeValue(upgradeId);
upgradeUnitMultipliers(player, upgradeClass, unitId, upgradeValue);
upgradesOwned[player][upgradeId] = true;
emit UpgradeMigration(player, upgradeId, txProof[i]);
}
}
}
function protectAddress(address exchange, bool shouldProtect) external {
require(msg.sender == owner);
if (shouldProtect) {
require(getGooProduction(exchange) == 0); // Can't protect actual players
}
protectedAddresses[exchange] = shouldProtect;
}
function attackPlayer(address target) external {
require(battleCooldown[msg.sender] < block.timestamp);
require(target != msg.sender);
require(!protectedAddresses[target]); // Target not whitelisted (i.e. exchange wallets)
uint256 attackingPower;
uint256 defendingPower;
uint256 stealingPower;
(attackingPower, defendingPower, stealingPower) = getPlayersBattlePower(msg.sender, target);
if (battleCooldown[target] > block.timestamp) { // When on battle cooldown you're vulnerable (starting value is 50% normal power)
defendingPower = schema.getWeakenedDefensePower(defendingPower);
}
if (attackingPower > defendingPower) {
battleCooldown[msg.sender] = block.timestamp + 30 minutes;
if (balanceOf(target) > stealingPower) {
// Save all their unclaimed goo, then steal attacker's max capacity (at same time)
uint256 unclaimedGoo = balanceOfUnclaimedGoo(target);
if (stealingPower > unclaimedGoo) {
uint256 gooDecrease = stealingPower - unclaimedGoo;
gooBalance[target] -= gooDecrease;
roughSupply -= gooDecrease;
} else {
uint256 gooGain = unclaimedGoo - stealingPower;
gooBalance[target] += gooGain;
roughSupply += gooGain;
}
gooBalance[msg.sender] += stealingPower;
emit PlayerAttacked(msg.sender, target, true, stealingPower);
} else {
emit PlayerAttacked(msg.sender, target, true, balanceOf(target));
gooBalance[msg.sender] += balanceOf(target);
gooBalance[target] = 0;
}
lastGooSaveTime[target] = block.timestamp;
// We don't need to claim/save msg.sender's goo (as production delta is unchanged)
} else {
battleCooldown[msg.sender] = block.timestamp + 10 minutes;
emit PlayerAttacked(msg.sender, target, false, 0);
}
}
function getPlayersBattlePower(address attacker, address defender) internal constant returns (uint256, uint256, uint256) {
uint256 startId;
uint256 endId;
(startId, endId) = schema.battleUnitIdRange();
uint256 attackingPower;
uint256 defendingPower;
uint256 stealingPower;
// Not ideal but will only be a small number of units (and saves gas when buying units)
while (startId <= endId) {
attackingPower += getUnitsAttack(attacker, startId, unitsOwned[attacker][startId]);
stealingPower += getUnitsStealingCapacity(attacker, startId, unitsOwned[attacker][startId]);
defendingPower += getUnitsDefense(defender, startId, unitsOwned[defender][startId]);
startId++;
}
return (attackingPower, defendingPower, stealingPower);
}
function getPlayersBattleStats(address player) external constant returns (uint256, uint256, uint256, uint256) {
uint256 startId;
uint256 endId;
(startId, endId) = schema.battleUnitIdRange();
uint256 attackingPower;
uint256 defendingPower;
uint256 stealingPower;
// Not ideal but will only be a small number of units (and saves gas when buying units)
while (startId <= endId) {
attackingPower += getUnitsAttack(player, startId, unitsOwned[player][startId]);
stealingPower += getUnitsStealingCapacity(player, startId, unitsOwned[player][startId]);
defendingPower += getUnitsDefense(player, startId, unitsOwned[player][startId]);
startId++;
}
if (battleCooldown[player] > block.timestamp) { // When on battle cooldown you're vulnerable (starting value is 50% normal power)
defendingPower = schema.getWeakenedDefensePower(defendingPower);
}
return (attackingPower, defendingPower, stealingPower, battleCooldown[player]);
}
function getUnitsProduction(address player, uint256 unitId, uint256 amount) internal constant returns (uint256) {
return (amount * (schema.unitGooProduction(unitId) + unitGooProductionIncreases[player][unitId]) * (10 + unitGooProductionMultiplier[player][unitId]));
}
function getUnitsAttack(address player, uint256 unitId, uint256 amount) internal constant returns (uint256) {
return (amount * (schema.unitAttack(unitId) + unitAttackIncreases[player][unitId]) * (10 + unitAttackMultiplier[player][unitId])) / 10;
}
function getUnitsDefense(address player, uint256 unitId, uint256 amount) internal constant returns (uint256) {
return (amount * (schema.unitDefense(unitId) + unitDefenseIncreases[player][unitId]) * (10 + unitDefenseMultiplier[player][unitId])) / 10;
}
function getUnitsStealingCapacity(address player, uint256 unitId, uint256 amount) internal constant returns (uint256) {
return (amount * (schema.unitStealingCapacity(unitId) + unitGooStealingIncreases[player][unitId]) * (10 + unitGooStealingMultiplier[player][unitId])) / 10;
}
// To display on website
function getGameInfo() external constant returns (uint256, uint256, uint256, uint256, uint256, uint256, uint256, uint256, uint256, uint256[], bool[]){
uint256[] memory units = new uint256[](schema.currentNumberOfUnits());
bool[] memory upgrades = new bool[](schema.currentNumberOfUpgrades());
uint256 startId;
uint256 endId;
(startId, endId) = schema.productionUnitIdRange();
uint256 i;
while (startId <= endId) {
units[i] = unitsOwned[msg.sender][startId];
i++;
startId++;
}
(startId, endId) = schema.battleUnitIdRange();
while (startId <= endId) {
units[i] = unitsOwned[msg.sender][startId];
i++;
startId++;
}
// Reset for upgrades
i = 0;
(startId, endId) = schema.upgradeIdRange();
while (startId <= endId) {
upgrades[i] = upgradesOwned[msg.sender][startId];
i++;
startId++;
}
return (block.timestamp, totalEtherGooResearchPool, totalGooProduction, totalGooDepositSnapshots[totalGooDepositSnapshots.length - 1], gooDepositSnapshots[msg.sender][totalGooDepositSnapshots.length - 1],
nextSnapshotTime, balanceOf(msg.sender), ethBalance[msg.sender], getGooProduction(msg.sender), units, upgrades);
}
// To display on website
function getRareItemInfo() external constant returns (address[], uint256[]) {
address[] memory itemOwners = new address[](schema.currentNumberOfRares());
uint256[] memory itemPrices = new uint256[](schema.currentNumberOfRares());
uint256 startId;
uint256 endId;
(startId, endId) = schema.rareIdRange();
uint256 i;
while (startId <= endId) {
itemOwners[i] = rareItemOwner[startId];
itemPrices[i] = rareItemPrice[startId];
i++;
startId++;
}
return (itemOwners, itemPrices);
}
// To display on website
function viewUnclaimedResearchDividends() external constant returns (uint256, uint256, uint256) {
uint256 startSnapshot = lastGooResearchFundClaim[msg.sender];
uint256 latestSnapshot = allocatedGooResearchSnapshots.length - 1; // No snapshots to begin with
uint256 researchShare;
uint256 previousProduction = gooProductionSnapshots[msg.sender][lastGooResearchFundClaim[msg.sender] - 1]; // Underflow won't be a problem as gooProductionSnapshots[][0xfffffffffffff] = 0;
for (uint256 i = startSnapshot; i <= latestSnapshot; i++) {
// Slightly complex things by accounting for days/snapshots when user made no tx's
uint256 productionDuringSnapshot = gooProductionSnapshots[msg.sender][i];
bool soldAllProduction = gooProductionZeroedSnapshots[msg.sender][i];
if (productionDuringSnapshot == 0 && !soldAllProduction) {
productionDuringSnapshot = previousProduction;
} else {
previousProduction = productionDuringSnapshot;
}
researchShare += (allocatedGooResearchSnapshots[i] * productionDuringSnapshot) / totalGooProductionSnapshots[i];
}
return (researchShare, startSnapshot, latestSnapshot);
}
// To display on website
function viewUnclaimedDepositDividends() external constant returns (uint256, uint256, uint256) {
uint256 startSnapshot = lastGooDepositFundClaim[msg.sender];
uint256 latestSnapshot = allocatedGooDepositSnapshots.length - 1; // No snapshots to begin with
uint256 depositShare;
for (uint256 i = startSnapshot; i <= latestSnapshot; i++) {
depositShare += (allocatedGooDepositSnapshots[i] * gooDepositSnapshots[msg.sender][i]) / totalGooDepositSnapshots[i];
}
return (depositShare, startSnapshot, latestSnapshot);
}
// To allow clients to verify contestants
function getItemRafflePlayers(uint256 raffleId) external constant returns (address[]) {
return (itemRafflePlayers[raffleId]);
}
// To allow clients to verify contestants
function getUnitRafflePlayers(uint256 raffleId) external constant returns (address[]) {
return (unitRafflePlayers[raffleId]);
}
// To allow clients to verify contestants
function getPlayersItemTickets(address player) external constant returns (uint256[], uint256[]) {
TicketPurchases storage playersTickets = rareItemTicketsBoughtByPlayer[player];
if (playersTickets.raffleId == itemRaffleRareId) {
uint256[] memory startIds = new uint256[](playersTickets.numPurchases);
uint256[] memory endIds = new uint256[](playersTickets.numPurchases);
for (uint256 i = 0; i < playersTickets.numPurchases; i++) {
startIds[i] = playersTickets.ticketsBought[i].startId;
endIds[i] = playersTickets.ticketsBought[i].endId;
}
}
return (startIds, endIds);
}
// To allow clients to verify contestants
function getPlayersUnitTickets(address player) external constant returns (uint256[], uint256[]) {
TicketPurchases storage playersTickets = rareUnitTicketsBoughtByPlayer[player];
if (playersTickets.raffleId == unitRaffleId) {
uint256[] memory startIds = new uint256[](playersTickets.numPurchases);
uint256[] memory endIds = new uint256[](playersTickets.numPurchases);
for (uint256 i = 0; i < playersTickets.numPurchases; i++) {
startIds[i] = playersTickets.ticketsBought[i].startId;
endIds[i] = playersTickets.ticketsBought[i].endId;
}
}
return (startIds, endIds);
}
// To display on website
function getLatestItemRaffleInfo() external constant returns (uint256, uint256, uint256, address, uint256) {
return (itemRaffleEndTime, itemRaffleRareId, itemRaffleTicketsBought, itemRaffleWinner, itemRaffleTicketThatWon);
}
// To display on website
function getLatestUnitRaffleInfo() external constant returns (uint256, uint256, uint256, address, uint256) {
return (unitRaffleEndTime, unitRaffleRareId, unitRaffleTicketsBought, unitRaffleWinner, unitRaffleTicketThatWon);
}
// New units may be added in future, but check it matches existing schema so no-one can abuse selling.
function updateGooConfig(address newSchemaAddress) external {
require(msg.sender == owner);
GooGameConfig newSchema = GooGameConfig(newSchemaAddress);
requireExistingUnitsSame(newSchema);
requireExistingUpgradesSame(newSchema);
// Finally update config
schema = GooGameConfig(newSchema);
}
function requireExistingUnitsSame(GooGameConfig newSchema) internal constant {
// Requires units eth costs match up or fail execution
uint256 startId;
uint256 endId;
(startId, endId) = schema.productionUnitIdRange();
while (startId <= endId) {
require(schema.unitEthCost(startId) == newSchema.unitEthCost(startId));
require(schema.unitGooProduction(startId) == newSchema.unitGooProduction(startId));
startId++;
}
(startId, endId) = schema.battleUnitIdRange();
while (startId <= endId) {
require(schema.unitEthCost(startId) == newSchema.unitEthCost(startId));
require(schema.unitAttack(startId) == newSchema.unitAttack(startId));
require(schema.unitDefense(startId) == newSchema.unitDefense(startId));
require(schema.unitStealingCapacity(startId) == newSchema.unitStealingCapacity(startId));
startId++;
}
}
function requireExistingUpgradesSame(GooGameConfig newSchema) internal constant {
uint256 startId;
uint256 endId;
// Requires ALL upgrade stats match up or fail execution
(startId, endId) = schema.upgradeIdRange();
while (startId <= endId) {
require(schema.upgradeGooCost(startId) == newSchema.upgradeGooCost(startId));
require(schema.upgradeEthCost(startId) == newSchema.upgradeEthCost(startId));
require(schema.upgradeClass(startId) == newSchema.upgradeClass(startId));
require(schema.upgradeUnitId(startId) == newSchema.upgradeUnitId(startId));
require(schema.upgradeValue(startId) == newSchema.upgradeValue(startId));
startId++;
}
// Requires ALL rare stats match up or fail execution
(startId, endId) = schema.rareIdRange();
while (startId <= endId) {
uint256 oldClass;
uint256 oldUnitId;
uint256 oldValue;
uint256 newClass;
uint256 newUnitId;
uint256 newValue;
(oldClass, oldUnitId, oldValue) = schema.getRareInfo(startId);
(newClass, newUnitId, newValue) = newSchema.getRareInfo(startId);
require(oldClass == newClass);
require(oldUnitId == newUnitId);
require(oldValue == newValue);
startId++;
}
}
}
contract GooGameConfig {
mapping(uint256 => Unit) private unitInfo;
mapping(uint256 => Upgrade) private upgradeInfo;
mapping(uint256 => Rare) private rareInfo;
uint256 public constant currentNumberOfUnits = 15;
uint256 public constant currentNumberOfUpgrades = 210;
uint256 public constant currentNumberOfRares = 2;
address public owner;
struct Unit {
uint256 unitId;
uint256 baseGooCost;
uint256 gooCostIncreaseHalf; // Halfed to make maths slightly less (cancels a 2 out)
uint256 ethCost;
uint256 baseGooProduction;
uint256 attackValue;
uint256 defenseValue;
uint256 gooStealingCapacity;
bool unitSellable; // Rare units (from raffle) not sellable
}
struct Upgrade {
uint256 upgradeId;
uint256 gooCost;
uint256 ethCost;
uint256 upgradeClass;
uint256 unitId;
uint256 upgradeValue;
uint256 prerequisiteUpgrade;
}
struct Rare {
uint256 rareId;
uint256 ethCost;
uint256 rareClass;
uint256 unitId;
uint256 rareValue;
}
function GooGameConfig() public {
owner = msg.sender;
rareInfo[1] = Rare(1, 0.5 ether, 1, 1, 40); // 40 = +400%
rareInfo[2] = Rare(2, 0.5 ether, 0, 2, 35); // +35
unitInfo[1] = Unit(1, 0, 10, 0, 2, 0, 0, 0, true);
unitInfo[2] = Unit(2, 100, 50, 0, 5, 0, 0, 0, true);
unitInfo[3] = Unit(3, 0, 0, 0.01 ether, 100, 0, 0, 0, true);
unitInfo[4] = Unit(4, 200, 100, 0, 10, 0, 0, 0, true);
unitInfo[5] = Unit(5, 500, 250, 0, 20, 0, 0, 0, true);
unitInfo[6] = Unit(6, 1000, 500, 0, 40, 0, 0, 0, true);
unitInfo[7] = Unit(7, 0, 1000, 0.05 ether, 500, 0, 0, 0, true);
unitInfo[8] = Unit(8, 1500, 750, 0, 60, 0, 0, 0, true);
unitInfo[9] = Unit(9, 0, 0, 10 ether, 6000, 0, 0, 0, false); // First secret rare unit from raffle (unsellable)
unitInfo[40] = Unit(40, 50, 25, 0, 0, 10, 10, 10000, true);
unitInfo[41] = Unit(41, 100, 50, 0, 0, 1, 25, 500, true);
unitInfo[42] = Unit(42, 0, 0, 0.01 ether, 0, 200, 10, 50000, true);
unitInfo[43] = Unit(43, 250, 125, 0, 0, 25, 1, 15000, true);
unitInfo[44] = Unit(44, 500, 250, 0, 0, 20, 40, 5000, true);
unitInfo[45] = Unit(45, 0, 2500, 0.02 ether, 0, 0, 0, 100000, true);
}
address allowedConfig;
function setConfigSetupContract(address schema) external {
require(msg.sender == owner);
allowedConfig = schema;
}
function addUpgrade(uint256 id, uint256 goo, uint256 eth, uint256 class, uint256 unit, uint256 value, uint256 prereq) external {
require(msg.sender == allowedConfig);
upgradeInfo[id] = Upgrade(id, goo, eth, class, unit, value, prereq);
}
function getGooCostForUnit(uint256 unitId, uint256 existing, uint256 amount) public constant returns (uint256) {
Unit storage unit = unitInfo[unitId];
if (amount == 1) { // 1
if (existing == 0) {
return unit.baseGooCost;
} else {
return unit.baseGooCost + (existing * unit.gooCostIncreaseHalf * 2);
}
} else if (amount > 1) {
uint256 existingCost;
if (existing > 0) { // Gated by unit limit
existingCost = (unit.baseGooCost * existing) + (existing * (existing - 1) * unit.gooCostIncreaseHalf);
}
existing = SafeMath.add(existing, amount);
return SafeMath.add(SafeMath.mul(unit.baseGooCost, existing), SafeMath.mul(SafeMath.mul(existing, (existing - 1)), unit.gooCostIncreaseHalf)) - existingCost;
}
}
function getWeakenedDefensePower(uint256 defendingPower) external constant returns (uint256) {
return defendingPower / 2;
}
function validRareId(uint256 rareId) external constant returns (bool) {
return (rareId > 0 && rareId < 3);
}
function unitSellable(uint256 unitId) external constant returns (bool) {
return unitInfo[unitId].unitSellable;
}
function unitEthCost(uint256 unitId) external constant returns (uint256) {
return unitInfo[unitId].ethCost;
}
function unitGooProduction(uint256 unitId) external constant returns (uint256) {
return unitInfo[unitId].baseGooProduction;
}
function unitAttack(uint256 unitId) external constant returns (uint256) {
return unitInfo[unitId].attackValue;
}
function unitDefense(uint256 unitId) external constant returns (uint256) {
return unitInfo[unitId].defenseValue;
}
function unitStealingCapacity(uint256 unitId) external constant returns (uint256) {
return unitInfo[unitId].gooStealingCapacity;
}
function rareStartPrice(uint256 rareId) external constant returns (uint256) {
return rareInfo[rareId].ethCost;
}
function upgradeGooCost(uint256 upgradeId) external constant returns (uint256) {
return upgradeInfo[upgradeId].gooCost;
}
function upgradeEthCost(uint256 upgradeId) external constant returns (uint256) {
return upgradeInfo[upgradeId].ethCost;
}
function upgradeClass(uint256 upgradeId) external constant returns (uint256) {
return upgradeInfo[upgradeId].upgradeClass;
}
function upgradeUnitId(uint256 upgradeId) external constant returns (uint256) {
return upgradeInfo[upgradeId].unitId;
}
function upgradeValue(uint256 upgradeId) external constant returns (uint256) {
return upgradeInfo[upgradeId].upgradeValue;
}
function productionUnitIdRange() external constant returns (uint256, uint256) {
return (1, 9);
}
function battleUnitIdRange() external constant returns (uint256, uint256) {
return (40, 45);
}
function upgradeIdRange() external constant returns (uint256, uint256) {
return (1, 210);
}
function rareIdRange() external constant returns (uint256, uint256) {
return (1, 2);
}
function getUpgradeInfo(uint256 upgradeId) external constant returns (uint256, uint256, uint256, uint256, uint256, uint256) {
return (upgradeInfo[upgradeId].gooCost, upgradeInfo[upgradeId].ethCost, upgradeInfo[upgradeId].upgradeClass,
upgradeInfo[upgradeId].unitId, upgradeInfo[upgradeId].upgradeValue, upgradeInfo[upgradeId].prerequisiteUpgrade);
}
function getRareInfo(uint256 rareId) external constant returns (uint256, uint256, uint256) {
return (rareInfo[rareId].rareClass, rareInfo[rareId].unitId, rareInfo[rareId].rareValue);
}
function getUnitInfo(uint256 unitId, uint256 existing, uint256 amount) external constant returns (uint256, uint256, uint256, uint256) {
return (unitInfo[unitId].unitId, unitInfo[unitId].baseGooProduction, getGooCostForUnit(unitId, existing, amount), SafeMath.mul(unitInfo[unitId].ethCost, amount));
}
}
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;
}
} | Div pot #1 (research eth allocated to each prior day past)
| uint256[] private allocatedGooResearchSnapshots; | 1,496,628 | [
1,
7244,
5974,
404,
261,
266,
3072,
13750,
11977,
358,
1517,
6432,
2548,
8854,
13,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
565,
2254,
5034,
8526,
3238,
11977,
43,
5161,
607,
73,
991,
17095,
31,
225,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
] |
./partial_match/1/0x9d08CCeD85A68Bf8A19374ED4B5753aE3Be9F74f/sources/contracts/protocol/integration/lib/AaveV3.sol | * Get setUserUseReserveAsCollateral calldata from SetToken Allows borrower to enable/disable a specific supplied asset as collateral @param _pool Address of the AaveV3 Pool contract @param _asset The address of the underlying asset supplied @param _useAsCollateral true` if the user wants to use the deposit as collateral, `false` otherwise @return address Target contract address @return uint256 Call value @return bytes SetUserUseReserveAsCollateral calldata/ | function getSetUserUseReserveAsCollateralCalldata(
IPool _pool,
address _asset,
bool _useAsCollateral
)
public
pure
returns (address, uint256, bytes memory)
{
bytes memory callData = abi.encodeWithSignature(
"setUserUseReserveAsCollateral(address,bool)",
_asset,
_useAsCollateral
);
return (address(_pool), 0, callData);
}
| 15,718,221 | [
1,
967,
14365,
3727,
607,
6527,
1463,
13535,
2045,
287,
745,
892,
628,
1000,
1345,
25619,
29759,
264,
358,
4237,
19,
8394,
279,
2923,
4580,
3310,
487,
4508,
2045,
287,
225,
389,
6011,
1171,
5267,
434,
326,
432,
836,
58,
23,
8828,
6835,
225,
389,
9406,
7734,
1021,
1758,
434,
326,
6808,
3310,
4580,
225,
389,
1202,
1463,
13535,
2045,
287,
1377,
638,
68,
309,
326,
729,
14805,
358,
999,
326,
443,
1724,
487,
4508,
2045,
287,
16,
1375,
5743,
68,
3541,
327,
1758,
2868,
5916,
6835,
1758,
327,
2254,
5034,
2868,
3049,
460,
327,
1731,
7734,
28112,
3727,
607,
6527,
1463,
13535,
2045,
287,
745,
892,
19,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
565,
445,
336,
694,
1299,
3727,
607,
6527,
1463,
13535,
2045,
287,
1477,
892,
12,
203,
3639,
467,
2864,
389,
6011,
16,
203,
3639,
1758,
389,
9406,
16,
203,
3639,
1426,
389,
1202,
1463,
13535,
2045,
287,
203,
565,
262,
203,
3639,
1071,
203,
3639,
16618,
203,
3639,
1135,
261,
2867,
16,
2254,
5034,
16,
1731,
3778,
13,
203,
565,
288,
203,
3639,
1731,
3778,
745,
751,
273,
24126,
18,
3015,
1190,
5374,
12,
203,
5411,
315,
542,
1299,
3727,
607,
6527,
1463,
13535,
2045,
287,
12,
2867,
16,
6430,
2225,
16,
7010,
5411,
389,
9406,
16,
203,
5411,
389,
1202,
1463,
13535,
2045,
287,
203,
3639,
11272,
203,
540,
203,
3639,
327,
261,
2867,
24899,
6011,
3631,
374,
16,
745,
751,
1769,
203,
565,
289,
203,
203,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
] |
./partial_match/42220/0xaf5D514bB94023C9Af979821F59A5Eecde0986EF/sources/home/eruiz/Projects/celo/celo-monorepo/packages/protocol/contracts/stability/SortedOracles.sol | * @title Maintains a sorted list of oracle exchange rates between CELO and other currencies./ Maps a token address to a sorted list of report values. Maps a token address to a sorted list of report timestamps. `reportExpirySeconds` is the fallback value used to determine reporting frequency. Initially it was the _only_ value but we later introduced the per token mapping in `tokenReportExpirySeconds`. If a token doesn't have a value in the mapping (i.e. it's 0), the fallback is used. See: #getTokenReportExpirySeconds | contract SortedOracles is ISortedOracles, ICeloVersionedContract, Ownable, Initializable {
using SafeMath for uint256;
using AddressSortedLinkedListWithMedian for SortedLinkedListWithMedian.List;
using FixidityLib for FixidityLib.Fraction;
uint256 private constant FIXED1_UINT = 1000000000000000000000000;
mapping(address => SortedLinkedListWithMedian.List) private rates;
mapping(address => SortedLinkedListWithMedian.List) private timestamps;
mapping(address => mapping(address => bool)) public isOracle;
mapping(address => address[]) public oracles;
uint256 public reportExpirySeconds;
mapping(address => uint256) public tokenReportExpirySeconds;
event OracleAdded(address indexed token, address indexed oracleAddress);
event OracleRemoved(address indexed token, address indexed oracleAddress);
event OracleReported(
address indexed token,
address indexed oracle,
uint256 timestamp,
uint256 value
);
event OracleReportRemoved(address indexed token, address indexed oracle);
event MedianUpdated(address indexed token, uint256 value);
event ReportExpirySet(uint256 reportExpiry);
event TokenReportExpirySet(address token, uint256 reportExpiry);
modifier onlyOracle(address token) {
require(isOracle[token][msg.sender], "sender was not an oracle for token addr");
_;
}
function getVersionNumber() external pure returns (uint256, uint256, uint256, uint256) {
return (1, 1, 2, 1);
}
constructor(bool test) public Initializable(test) {}
function initialize(uint256 _reportExpirySeconds) external initializer {
_transferOwnership(msg.sender);
setReportExpiry(_reportExpirySeconds);
}
function setReportExpiry(uint256 _reportExpirySeconds) public onlyOwner {
require(_reportExpirySeconds > 0, "report expiry seconds must be > 0");
require(_reportExpirySeconds != reportExpirySeconds, "reportExpirySeconds hasn't changed");
reportExpirySeconds = _reportExpirySeconds;
emit ReportExpirySet(_reportExpirySeconds);
}
function setTokenReportExpiry(address _token, uint256 _reportExpirySeconds) external onlyOwner {
require(_reportExpirySeconds > 0, "report expiry seconds must be > 0");
require(
_reportExpirySeconds != tokenReportExpirySeconds[_token],
"token reportExpirySeconds hasn't changed"
);
tokenReportExpirySeconds[_token] = _reportExpirySeconds;
emit TokenReportExpirySet(_token, _reportExpirySeconds);
}
function addOracle(address token, address oracleAddress) external onlyOwner {
require(
token != address(0) && oracleAddress != address(0) && !isOracle[token][oracleAddress],
"token addr was null or oracle addr was null or oracle addr is not an oracle for token addr"
);
isOracle[token][oracleAddress] = true;
oracles[token].push(oracleAddress);
emit OracleAdded(token, oracleAddress);
}
function removeOracle(address token, address oracleAddress, uint256 index) external onlyOwner {
require(
token != address(0) &&
oracleAddress != address(0) &&
oracles[token].length > index &&
oracles[token][index] == oracleAddress,
"token addr null or oracle addr null or index of token oracle not mapped to oracle addr"
);
isOracle[token][oracleAddress] = false;
oracles[token][index] = oracles[token][oracles[token].length.sub(1)];
oracles[token].length = oracles[token].length.sub(1);
if (reportExists(token, oracleAddress)) {
removeReport(token, oracleAddress);
}
emit OracleRemoved(token, oracleAddress);
}
function removeOracle(address token, address oracleAddress, uint256 index) external onlyOwner {
require(
token != address(0) &&
oracleAddress != address(0) &&
oracles[token].length > index &&
oracles[token][index] == oracleAddress,
"token addr null or oracle addr null or index of token oracle not mapped to oracle addr"
);
isOracle[token][oracleAddress] = false;
oracles[token][index] = oracles[token][oracles[token].length.sub(1)];
oracles[token].length = oracles[token].length.sub(1);
if (reportExists(token, oracleAddress)) {
removeReport(token, oracleAddress);
}
emit OracleRemoved(token, oracleAddress);
}
function removeExpiredReports(address token, uint256 n) external {
require(
token != address(0) && n < timestamps[token].getNumElements(),
"token addr null or trying to remove too many reports"
);
for (uint256 i = 0; i < n; i = i.add(1)) {
(bool isExpired, address oldestAddress) = isOldestReportExpired(token);
if (isExpired) {
removeReport(token, oldestAddress);
break;
}
}
}
function removeExpiredReports(address token, uint256 n) external {
require(
token != address(0) && n < timestamps[token].getNumElements(),
"token addr null or trying to remove too many reports"
);
for (uint256 i = 0; i < n; i = i.add(1)) {
(bool isExpired, address oldestAddress) = isOldestReportExpired(token);
if (isExpired) {
removeReport(token, oldestAddress);
break;
}
}
}
function removeExpiredReports(address token, uint256 n) external {
require(
token != address(0) && n < timestamps[token].getNumElements(),
"token addr null or trying to remove too many reports"
);
for (uint256 i = 0; i < n; i = i.add(1)) {
(bool isExpired, address oldestAddress) = isOldestReportExpired(token);
if (isExpired) {
removeReport(token, oldestAddress);
break;
}
}
}
} else {
function isOldestReportExpired(address token) public view returns (bool, address) {
require(token != address(0));
address oldest = timestamps[token].getTail();
uint256 timestamp = timestamps[token].getValue(oldest);
if (now.sub(timestamp) >= getTokenReportExpirySeconds(token)) {
return (true, oldest);
}
return (false, oldest);
}
function isOldestReportExpired(address token) public view returns (bool, address) {
require(token != address(0));
address oldest = timestamps[token].getTail();
uint256 timestamp = timestamps[token].getValue(oldest);
if (now.sub(timestamp) >= getTokenReportExpirySeconds(token)) {
return (true, oldest);
}
return (false, oldest);
}
function report(address token, uint256 value, address lesserKey, address greaterKey)
external
onlyOracle(token)
{
uint256 originalMedian = rates[token].getMedianValue();
if (rates[token].contains(msg.sender)) {
rates[token].update(msg.sender, value, lesserKey, greaterKey);
timestamps[token].remove(msg.sender);
rates[token].insert(msg.sender, value, lesserKey, greaterKey);
}
timestamps[token].insert(
msg.sender,
timestamps[token].getHead(),
address(0)
);
emit OracleReported(token, msg.sender, now, value);
uint256 newMedian = rates[token].getMedianValue();
if (newMedian != originalMedian) {
emit MedianUpdated(token, newMedian);
}
}
function report(address token, uint256 value, address lesserKey, address greaterKey)
external
onlyOracle(token)
{
uint256 originalMedian = rates[token].getMedianValue();
if (rates[token].contains(msg.sender)) {
rates[token].update(msg.sender, value, lesserKey, greaterKey);
timestamps[token].remove(msg.sender);
rates[token].insert(msg.sender, value, lesserKey, greaterKey);
}
timestamps[token].insert(
msg.sender,
timestamps[token].getHead(),
address(0)
);
emit OracleReported(token, msg.sender, now, value);
uint256 newMedian = rates[token].getMedianValue();
if (newMedian != originalMedian) {
emit MedianUpdated(token, newMedian);
}
}
} else {
now,
function report(address token, uint256 value, address lesserKey, address greaterKey)
external
onlyOracle(token)
{
uint256 originalMedian = rates[token].getMedianValue();
if (rates[token].contains(msg.sender)) {
rates[token].update(msg.sender, value, lesserKey, greaterKey);
timestamps[token].remove(msg.sender);
rates[token].insert(msg.sender, value, lesserKey, greaterKey);
}
timestamps[token].insert(
msg.sender,
timestamps[token].getHead(),
address(0)
);
emit OracleReported(token, msg.sender, now, value);
uint256 newMedian = rates[token].getMedianValue();
if (newMedian != originalMedian) {
emit MedianUpdated(token, newMedian);
}
}
function numRates(address token) public view returns (uint256) {
return rates[token].getNumElements();
}
function medianRate(address token) external view returns (uint256, uint256) {
return (rates[token].getMedianValue(), numRates(token) == 0 ? 0 : FIXED1_UINT);
}
function getRates(address token)
external
view
returns (address[] memory, uint256[] memory, SortedLinkedListWithMedian.MedianRelation[] memory)
{
return rates[token].getElements();
}
function numTimestamps(address token) public view returns (uint256) {
return timestamps[token].getNumElements();
}
function medianTimestamp(address token) external view returns (uint256) {
return timestamps[token].getMedianValue();
}
function getTimestamps(address token)
external
view
returns (address[] memory, uint256[] memory, SortedLinkedListWithMedian.MedianRelation[] memory)
{
return timestamps[token].getElements();
}
function reportExists(address token, address oracle) internal view returns (bool) {
return rates[token].contains(oracle) && timestamps[token].contains(oracle);
}
function getOracles(address token) external view returns (address[] memory) {
return oracles[token];
}
function getTokenReportExpirySeconds(address token) public view returns (uint256) {
if (tokenReportExpirySeconds[token] == 0) {
return reportExpirySeconds;
}
return tokenReportExpirySeconds[token];
}
function getTokenReportExpirySeconds(address token) public view returns (uint256) {
if (tokenReportExpirySeconds[token] == 0) {
return reportExpirySeconds;
}
return tokenReportExpirySeconds[token];
}
function removeReport(address token, address oracle) private {
if (numTimestamps(token) == 1 && reportExists(token, oracle)) return;
uint256 originalMedian = rates[token].getMedianValue();
rates[token].remove(oracle);
timestamps[token].remove(oracle);
emit OracleReportRemoved(token, oracle);
uint256 newMedian = rates[token].getMedianValue();
if (newMedian != originalMedian) {
emit MedianUpdated(token, newMedian);
}
}
function removeReport(address token, address oracle) private {
if (numTimestamps(token) == 1 && reportExists(token, oracle)) return;
uint256 originalMedian = rates[token].getMedianValue();
rates[token].remove(oracle);
timestamps[token].remove(oracle);
emit OracleReportRemoved(token, oracle);
uint256 newMedian = rates[token].getMedianValue();
if (newMedian != originalMedian) {
emit MedianUpdated(token, newMedian);
}
}
}
| 3,498,885 | [
1,
49,
1598,
4167,
279,
3115,
666,
434,
20865,
7829,
17544,
3086,
29538,
1502,
471,
1308,
19239,
18,
19,
19837,
279,
1147,
1758,
358,
279,
3115,
666,
434,
2605,
924,
18,
19837,
279,
1147,
1758,
358,
279,
3115,
666,
434,
2605,
11267,
18,
1375,
6006,
14633,
6762,
68,
353,
326,
5922,
460,
1399,
358,
4199,
16096,
8670,
18,
4378,
6261,
518,
1703,
326,
389,
3700,
67,
460,
1496,
732,
5137,
26339,
326,
1534,
1147,
2874,
316,
1375,
2316,
4820,
14633,
6762,
8338,
971,
279,
1147,
3302,
1404,
1240,
279,
460,
316,
326,
2874,
261,
77,
18,
73,
18,
518,
1807,
374,
3631,
326,
5922,
353,
1399,
18,
2164,
30,
9162,
4820,
14633,
6762,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
16351,
13717,
51,
354,
9558,
353,
467,
11739,
51,
354,
9558,
16,
26899,
24214,
23676,
8924,
16,
14223,
6914,
16,
10188,
6934,
288,
203,
225,
1450,
14060,
10477,
364,
2254,
5034,
31,
203,
225,
1450,
5267,
11739,
13174,
682,
1190,
13265,
2779,
364,
13717,
13174,
682,
1190,
13265,
2779,
18,
682,
31,
203,
225,
1450,
12139,
24237,
5664,
364,
12139,
24237,
5664,
18,
13724,
31,
203,
203,
225,
2254,
5034,
3238,
5381,
26585,
21,
67,
57,
3217,
273,
2130,
12648,
12648,
9449,
31,
203,
203,
225,
2874,
12,
2867,
516,
13717,
13174,
682,
1190,
13265,
2779,
18,
682,
13,
3238,
17544,
31,
203,
225,
2874,
12,
2867,
516,
13717,
13174,
682,
1190,
13265,
2779,
18,
682,
13,
3238,
11267,
31,
203,
225,
2874,
12,
2867,
516,
2874,
12,
2867,
516,
1426,
3719,
1071,
353,
23601,
31,
203,
225,
2874,
12,
2867,
516,
1758,
63,
5717,
1071,
578,
69,
9558,
31,
203,
203,
225,
2254,
5034,
1071,
2605,
14633,
6762,
31,
203,
225,
2874,
12,
2867,
516,
2254,
5034,
13,
1071,
1147,
4820,
14633,
6762,
31,
203,
203,
225,
871,
28544,
8602,
12,
2867,
8808,
1147,
16,
1758,
8808,
20865,
1887,
1769,
203,
225,
871,
28544,
10026,
12,
2867,
8808,
1147,
16,
1758,
8808,
20865,
1887,
1769,
203,
225,
871,
28544,
426,
1798,
12,
203,
565,
1758,
8808,
1147,
16,
203,
565,
1758,
8808,
20865,
16,
203,
565,
2254,
5034,
2858,
16,
203,
565,
2254,
5034,
460,
203,
225,
11272,
203,
225,
871,
28544,
4820,
10026,
12,
2867,
8808,
1147,
16,
1758,
8808,
20865,
1769,
2
] |
// SPDX-License-Identifier: MIT
pragma solidity >=0.6.0 <0.7.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;
}
}
/**
* @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);
}
/*
* @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;
}
}
/**
* @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;
}
}
interface IPowerKeeper {
function usePower(address master) external returns (uint256);
function power(address master) external view returns (uint256);
function totalPower() external view returns (uint256);
event PowerGained(address indexed master, uint256 amount);
event PowerUsed(address indexed master, uint256 amount);
}
interface IMilker {
function bandits(uint256 percent) external returns (uint256, uint256, uint256);
function sheriffsVaultCommission() external returns (uint256);
function sheriffsPotDistribution() external returns (uint256);
function isWhitelisted(address holder) external view returns (bool);
function getPeriod() external view returns (uint256);
}
contract StableV2 is Ownable, IPowerKeeper {
using SafeMath for uint256;
// Stakeshot contains snapshot of aggregated staking history.
struct Stakeshot {
uint256 block; // number of block stakeshooted
uint256 volume; // amount of tokens in the stable just after the "shoot" moment
uint256 power; // amount of currently accumulated power available at block with number `block`
}
// Contract allowed to spend collected power to create MILK.
IMilker private _milker;
// Staking ERC20 token of the stable (specified once at the contract constraction).
IERC20 private _token;
// Variables used to work properly with inflationary/deflationary tokens.
uint256 private _maxUnits;
uint256 private _tokensToPowerDelimiter;
// Amount of tokens by holders and total amount of tokens in the stable.
mapping(address => uint256) private _tokens;
uint256 private _totalTokens;
// Most actual stakeshots by holders.
mapping(address => Stakeshot) private _stakeshots;
// Total amount of power accumulated in the stable.
uint256 private _totalPower;
uint256 private _totalPowerBlock;
// Staking/claiming events.
event Staked(address indexed holder, uint256 tokens);
event Claimed(address indexed holder, uint256 tokens);
modifier onlyMilker() {
require(address(_milker) == _msgSender(), "StableV2: caller is not the Milker contract");
_;
}
constructor(address milker, address token, uint256 maxUnits, uint256 tokensToPowerDelimiter) public {
require(address(milker) != address(0), "StableV2: Milker contract address cannot be empty");
require(address(token) != address(0), "StableV2: ERC20 token contract address cannot be empty");
require(tokensToPowerDelimiter > 0, "StableV2: delimiter used to convert between tokens and units cannot be zero");
_milker = IMilker(milker);
_token = IERC20(token);
_maxUnits = maxUnits;
_tokensToPowerDelimiter = tokensToPowerDelimiter;
_totalPowerBlock = block.number;
}
function stake(uint256 tokens) external {
address holder = msg.sender;
require(address(_milker) != address(0), "StableV2: Milker contract is not set up");
require(!_milker.isWhitelisted(holder), "StableV2: whitelisted holders cannot stake tokens");
// Recalculate total power and power collected by the holder
_update(holder);
// Transfer provided tokens to the StableV2 contract
bool ok = _token.transferFrom(holder, address(this), tokens);
require(ok, "StableV2: unable to transfer tokens to the StableV2 contract");
// Register staked tokens
uint256 units = _maxUnits != 0 ? tokens.mul(_maxUnits.div(_token.totalSupply())) : tokens;
_tokens[holder] = _tokens[holder].add(units);
_totalTokens = _totalTokens.add(units);
// Update stakeshot's volume
_stakeshots[holder].volume = _tokens[holder];
// Emit event to the logs so can be effectively used later
emit Staked(holder, tokens);
}
function claim(uint256 tokens) external {
address holder = msg.sender;
require(address(_milker) != address(0), "StableV2: Milker contract is not set up");
require(!_milker.isWhitelisted(holder), "StableV2: whitelisted holders cannot claim tokens");
// Recalculate total power and power collected by the holder
_update(holder);
// Transfer requested tokens from the StableV2 contract
bool ok = _token.transfer(holder, tokens);
require(ok, "StableV2: unable to transfer tokens from the StableV2 contract");
// Unregister claimed tokens
uint256 units = _maxUnits != 0 ? tokens.mul(_maxUnits.div(_token.totalSupply())) : tokens;
_tokens[holder] = _tokens[holder].sub(units);
_totalTokens = _totalTokens.sub(units);
// Update stakeshot's volume
_stakeshots[holder].volume = _tokens[holder];
// Emit event to the logs so can be effectively used later
emit Claimed(holder, tokens);
}
function usePower(address holder) external override onlyMilker returns (uint256 powerUsed) {
// Recalculate total power and power collected by the holder
_update(holder);
// Product MILK to the holder according to the accumulated power
powerUsed = _stakeshots[holder].power;
_stakeshots[holder].power = 0;
_totalPower = _totalPower.sub(powerUsed);
// Emit event to the logs so can be effectively used later
emit PowerUsed(holder, powerUsed);
}
function milker() public view returns (address) {
return address(_milker);
}
function token() public view returns (address) {
return address(_token);
}
function tokens(address holder) public view returns (uint256) {
uint256 unitsPerToken = _maxUnits != 0 ? _maxUnits.div(_token.totalSupply()) : 1;
return _tokens[holder].div(unitsPerToken);
}
function totalTokens() public view returns (uint256) {
uint256 unitsPerToken = _maxUnits != 0 ? _maxUnits.div(_token.totalSupply()) : 1;
return _totalTokens.div(unitsPerToken);
}
function power(address holder) public view override returns (uint256) {
Stakeshot storage s = _stakeshots[holder];
uint256 duration = block.number.sub(s.block);
if (s.block > 0 && duration > 0) {
uint256 powerGained = s.volume.div(_tokensToPowerDelimiter).mul(duration);
return s.power.add(powerGained);
}
return s.power;
}
function totalPower() public view override returns (uint256) {
uint256 duration = block.number.sub(_totalPowerBlock);
if (duration > 0) {
uint256 powerGained = _totalTokens.div(_tokensToPowerDelimiter).mul(duration);
return _totalPower.add(powerGained);
}
return _totalPower;
}
function stakeshot(address holder) public view returns (uint256, uint256, uint256) {
uint256 unitsPerToken = _maxUnits != 0 ? _maxUnits.div(_token.totalSupply()) : 1;
Stakeshot storage s = _stakeshots[holder];
return (s.block, s.volume.div(unitsPerToken), s.power);
}
function _update(address holder) private {
// Update the stakeshot
Stakeshot storage s = _stakeshots[holder];
uint256 duration = block.number.sub(s.block);
if (s.block > 0 && duration > 0) {
uint256 powerGained = s.volume.div(_tokensToPowerDelimiter).mul(duration);
s.power = s.power.add(powerGained);
emit PowerGained(holder, powerGained);
}
s.block = block.number;
s.volume = _tokens[holder];
// Update total power counter variables
duration = block.number.sub(_totalPowerBlock);
if (duration > 0) {
uint256 powerGained = _totalTokens.div(_tokensToPowerDelimiter).mul(duration);
_totalPower = _totalPower.add(powerGained);
_totalPowerBlock = block.number;
}
}
} | Most actual stakeshots by holders. | mapping(address => Stakeshot) private _stakeshots;
| 469,393 | [
1,
18714,
3214,
384,
3223,
76,
6968,
635,
366,
4665,
18,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
565,
2874,
12,
2867,
516,
934,
3223,
15224,
13,
3238,
389,
334,
3223,
76,
6968,
31,
203,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
] |
./full_match/44787/0x77B118A5e8a26187800f194caD0FCF9EC6Fce5A9/sources/project_/contracts/LandNFT.sol | Set all NFT information set the tokenId to current landowner collection index update the tokenId index in landowner collection increase total lands owned by address | ) public onlyOwner {
uint256 currentTokenId = _tokenIdCounter.current();
_tokenIdCounter.increment();
_safeMint(to, currentTokenId);
mintedNFTSInfo[currentTokenId].name = name;
mintedNFTSInfo[currentTokenId].identifier = identifier;
mintedNFTSInfo[currentTokenId].landOwner = landOwner;
mintedNFTSInfo[currentTokenId].landOwnerAlias = landOwnerAlias;
mintedNFTSInfo[currentTokenId].decimals = decimals;
mintedNFTSInfo[currentTokenId].size = size;
mintedNFTSInfo[currentTokenId].country = country;
mintedNFTSInfo[currentTokenId].stateOrRegion = stateOrRegion;
mintedNFTSInfo[currentTokenId].city = city;
mintedNFTSInfo[currentTokenId].initialTCO2 = initialTCO2;
mintedNFTSInfo[currentTokenId].currentTCO2 = initialTCO2;
mintedNFTSInfo[currentTokenId].creationDate = block.timestamp;
mintedNFTSInfo[currentTokenId].state = State.Active;
uint256 _landsOwned = _totalLandOwned[landOwner];
ownedLands[to][_landsOwned] = currentTokenId;
landIndex[currentTokenId] = _landsOwned;
_totalLandOwned[to]++;
}
| 13,248,465 | [
1,
694,
777,
423,
4464,
1779,
444,
326,
1147,
548,
358,
783,
19193,
8443,
1849,
770,
1089,
326,
1147,
548,
770,
316,
19193,
8443,
1849,
10929,
2078,
328,
5708,
16199,
635,
1758,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
565,
262,
1071,
1338,
5541,
288,
203,
3639,
2254,
5034,
23719,
548,
273,
389,
2316,
548,
4789,
18,
2972,
5621,
203,
3639,
389,
2316,
548,
4789,
18,
15016,
5621,
203,
3639,
389,
4626,
49,
474,
12,
869,
16,
23719,
548,
1769,
203,
203,
3639,
312,
474,
329,
50,
4464,
55,
966,
63,
2972,
1345,
548,
8009,
529,
273,
508,
31,
203,
3639,
312,
474,
329,
50,
4464,
55,
966,
63,
2972,
1345,
548,
8009,
5644,
273,
2756,
31,
203,
3639,
312,
474,
329,
50,
4464,
55,
966,
63,
2972,
1345,
548,
8009,
15733,
5541,
273,
19193,
5541,
31,
203,
3639,
312,
474,
329,
50,
4464,
55,
966,
63,
2972,
1345,
548,
8009,
15733,
5541,
2936,
273,
19193,
5541,
2936,
31,
203,
3639,
312,
474,
329,
50,
4464,
55,
966,
63,
2972,
1345,
548,
8009,
31734,
273,
15105,
31,
203,
3639,
312,
474,
329,
50,
4464,
55,
966,
63,
2972,
1345,
548,
8009,
1467,
273,
963,
31,
203,
3639,
312,
474,
329,
50,
4464,
55,
966,
63,
2972,
1345,
548,
8009,
9082,
273,
5251,
31,
203,
3639,
312,
474,
329,
50,
4464,
55,
966,
63,
2972,
1345,
548,
8009,
2019,
1162,
5165,
273,
919,
1162,
5165,
31,
203,
3639,
312,
474,
329,
50,
4464,
55,
966,
63,
2972,
1345,
548,
8009,
14240,
273,
12797,
31,
203,
3639,
312,
474,
329,
50,
4464,
55,
966,
63,
2972,
1345,
548,
8009,
6769,
56,
3865,
22,
273,
2172,
56,
3865,
22,
31,
203,
3639,
312,
474,
329,
50,
4464,
55,
966,
63,
2972,
1345,
548,
8009,
2972,
56,
2
] |
./full_match/1/0x9C070027cdC9dc8F82416B2e5314E11DFb4FE3CD/sources/@keep-network/bitcoin-spv-sol/contracts/BTCUtils.sol | @notice Extracts the LE tx input index from the input in a tx @dev 4-byte tx index @param _input The input @return The tx index (little-endian bytes) | function extractTxIndexLE(bytes memory _input) internal pure returns (bytes4) {
return _input.slice4(32);
}
| 4,857,034 | [
1,
12809,
326,
5380,
2229,
810,
770,
628,
326,
810,
316,
279,
2229,
2868,
1059,
17,
7229,
2229,
770,
225,
389,
2630,
565,
1021,
810,
327,
1850,
1021,
2229,
770,
261,
80,
7188,
17,
22910,
1731,
13,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
565,
445,
2608,
4188,
1016,
900,
12,
3890,
3778,
389,
2630,
13,
2713,
16618,
1135,
261,
3890,
24,
13,
288,
203,
3639,
327,
389,
2630,
18,
6665,
24,
12,
1578,
1769,
203,
565,
289,
203,
203,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
] |
pragma solidity ^0.4.15;
contract Token {
/// @return total amount of tokens
// function totalSupply() public constant returns (uint supply);
// `totalSupply` is defined below because the automatically generated
// getter function does not match the abstract function above
uint public totalSupply;
/// @param _owner The address from which the balance will be retrieved
/// @return The balance
function balanceOf(address _owner) public constant returns (uint);
/// @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, uint _value) public returns (bool success);
/// @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, uint _value) public returns (bool success);
/// @notice `msg.sender` approves `_addr` to spend `_value` tokens
/// @param _spender The address of the account able to transfer the tokens
/// @param _value The amount of wei to be approved for transfer
/// @return Whether the approval was successful or not
function approve(address _spender, uint _value) public returns (bool success);
/// @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 constant returns (uint remaining);
event Transfer(address indexed _from, address indexed _to, uint _value);
event Approval(address indexed _owner, address indexed _spender, uint _value);
}
contract StandardToken is Token {
function transfer(address _to, uint _value) public returns (bool success) {
if (balances[msg.sender] >= _value && // Account has sufficient balance
balances[_to] + _value >= balances[_to]) { // Overflow check
balances[msg.sender] -= _value;
balances[_to] += _value;
Transfer(msg.sender, _to, _value);
return true;
} else { throw; }
}
function transferFrom(address _from, address _to, uint _value) public returns (bool success) {
if (balances[_from] >= _value && // Account has sufficient balance
allowed[_from][msg.sender] >= _value && // Amount has been approved
balances[_to] + _value >= balances[_to]) { // Overflow check
balances[_from] -= _value;
allowed[_from][msg.sender] -= _value;
balances[_to] += _value;
Transfer(_from, _to, _value);
return true;
} else { throw; }
}
function balanceOf(address _owner) public constant returns (uint balance) {
return balances[_owner];
}
function approve(address _spender, uint _value) public returns (bool success) {
// 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((_value == 0) || (allowed[msg.sender][_spender] == 0));
allowed[msg.sender][_spender] = _value;
Approval(msg.sender, _spender, _value);
return true;
}
function allowance(address _owner, address _spender) public constant returns (uint remaining) {
return allowed[_owner][_spender];
}
mapping (address => uint) balances;
mapping (address => mapping (address => uint)) allowed;
}
// Based on TokenFactory(https://github.com/ConsenSys/Token-Factory)
contract SnipCoin is StandardToken {
string public constant name = "SnipCoin"; // Token name
string public symbol = "SNIP"; // Token identifier
uint8 public constant decimals = 18; // Decimal points for token
uint public totalEthReceivedInWei; // The total amount of Ether received during the sale in WEI
uint public totalUsdReceived; // The total amount of Ether received during the sale in USD terms
uint public totalUsdValueOfAllTokens; // The total USD value of 100% of tokens
string public version = "1.0"; // Code version
address public saleWalletAddress; // The wallet address where the Ether from the sale will be stored
mapping (address => bool) public uncappedBuyerList; // The list of buyers allowed to participate in the sale without a cap
mapping (address => uint) public cappedBuyerList; // The list of buyers allowed to participate in the sale, with their updated payment sum
uint public snipCoinToEtherExchangeRate = 76250; // This is the ratio of SnipCoin to Ether, could be updated by the owner, change before the sale
bool public isSaleOpen = false; // This opens and closes upon external command
bool public transferable = false; // Tokens are transferable
uint public ethToUsdExchangeRate = 282; // Number of USD in one Eth
address public contractOwner; // Address of the contract owner
// Address of an additional account to manage the sale without risk to the tokens or eth. Change before the sale
address public accountWithUpdatePermissions = 0x6933784a82F5daDEbB600Bed8670667837aD196f;
uint public constant PERCENTAGE_OF_TOKENS_SOLD_IN_SALE = 28; // Percentage of all the tokens being sold in the current sale
uint public constant DECIMALS_MULTIPLIER = 10**uint(decimals); // Multiplier for the decimals
uint public constant SALE_CAP_IN_USD = 8000000; // The total sale cap in USD
uint public constant MINIMUM_PURCHASE_IN_USD = 50; // It is impossible to purchase tokens for more than $50 in the sale.
uint public constant USD_PURCHASE_AMOUNT_REQUIRING_ID = 4500; // Above this purchase amount an ID is required.
modifier onlyPermissioned() {
require((msg.sender == contractOwner) || (msg.sender == accountWithUpdatePermissions));
_;
}
modifier verifySaleNotOver() {
require(isSaleOpen);
require(totalUsdReceived < SALE_CAP_IN_USD); // Make sure that sale isn't over
_;
}
modifier verifyBuyerCanMakePurchase() {
uint currentPurchaseValueInUSD = uint(msg.value / getWeiToUsdExchangeRate()); // The USD worth of tokens sold
uint totalPurchaseIncludingCurrentPayment = currentPurchaseValueInUSD + cappedBuyerList[msg.sender]; // The USD worth of all tokens this buyer bought
require(currentPurchaseValueInUSD > MINIMUM_PURCHASE_IN_USD); // Minimum transfer is of $50
uint EFFECTIVE_MAX_CAP = SALE_CAP_IN_USD + 1000; // This allows for the end of the sale by passing $8M and reaching the cap
require(EFFECTIVE_MAX_CAP - totalUsdReceived > currentPurchaseValueInUSD); // Make sure that there is enough usd left to buy.
if (!uncappedBuyerList[msg.sender]) // If buyer is on uncapped white list then no worries, else need to make sure that they're okay
{
require(cappedBuyerList[msg.sender] > 0); // Check that the sender has been initialized.
require(totalPurchaseIncludingCurrentPayment < USD_PURCHASE_AMOUNT_REQUIRING_ID); // Check that they're not buying too much
}
_;
}
function SnipCoin() public {
initializeSaleWalletAddress();
initializeEthReceived();
initializeUsdReceived();
contractOwner = msg.sender; // The creator of the contract is its owner
totalSupply = 10000000000 * DECIMALS_MULTIPLIER; // In total, 10 billion tokens
balances[contractOwner] = totalSupply; // Initially give owner all of the tokens
Transfer(0x0, contractOwner, totalSupply);
}
function initializeSaleWalletAddress() internal {
saleWalletAddress = 0xb4Ad56E564aAb5409fe8e34637c33A6d3F2a0038; // Change before the sale
}
function initializeEthReceived() internal {
totalEthReceivedInWei = 14018 * 1 ether; // Ether received before public sale. Verify this figure before the sale starts.
}
function initializeUsdReceived() internal {
totalUsdReceived = 3953076; // USD received before public sale. Verify this figure before the sale starts.
totalUsdValueOfAllTokens = totalUsdReceived * 100 / PERCENTAGE_OF_TOKENS_SOLD_IN_SALE; // sold tokens are 28% of all tokens
}
function getWeiToUsdExchangeRate() public constant returns(uint) {
return 1 ether / ethToUsdExchangeRate; // Returns how much Wei one USD is worth
}
function updateEthToUsdExchangeRate(uint newEthToUsdExchangeRate) public onlyPermissioned {
ethToUsdExchangeRate = newEthToUsdExchangeRate; // Change exchange rate to new value, influences the counter of when the sale is over.
}
function updateSnipCoinToEtherExchangeRate(uint newSnipCoinToEtherExchangeRate) public onlyPermissioned {
snipCoinToEtherExchangeRate = newSnipCoinToEtherExchangeRate; // Change the exchange rate to new value, influences tokens received per purchase
}
function openOrCloseSale(bool saleCondition) public onlyPermissioned {
require(!transferable);
isSaleOpen = saleCondition; // Decide if the sale should be open or closed (default: closed)
}
function allowTransfers() public onlyPermissioned {
require(!isSaleOpen);
transferable = true;
}
function addAddressToCappedAddresses(address addr) public onlyPermissioned {
cappedBuyerList[addr] = 1; // Allow a certain address to purchase SnipCoin up to the cap (<4500)
}
function addMultipleAddressesToCappedAddresses(address[] addrList) public onlyPermissioned {
for (uint i = 0; i < addrList.length; i++) {
addAddressToCappedAddresses(addrList[i]); // Allow a certain address to purchase SnipCoin up to the cap (<4500)
}
}
function addAddressToUncappedAddresses(address addr) public onlyPermissioned {
uncappedBuyerList[addr] = true; // Allow a certain address to purchase SnipCoin above the cap (>=$4500)
}
function addMultipleAddressesToUncappedAddresses(address[] addrList) public onlyPermissioned {
for (uint i = 0; i < addrList.length; i++) {
addAddressToUncappedAddresses(addrList[i]); // Allow a certain address to purchase SnipCoin up to the cap (<4500)
}
}
function transfer(address _to, uint _value) public returns (bool success) {
require(transferable);
return super.transfer(_to, _value);
}
function transferFrom(address _from, address _to, uint _value) public returns (bool success) {
require(transferable);
return super.transferFrom(_from, _to, _value);
}
function () public payable verifySaleNotOver verifyBuyerCanMakePurchase {
uint tokens = snipCoinToEtherExchangeRate * msg.value;
balances[contractOwner] -= tokens;
balances[msg.sender] += tokens;
Transfer(contractOwner, msg.sender, tokens);
totalEthReceivedInWei = totalEthReceivedInWei + msg.value; // total eth received counter
uint usdReceivedInCurrentTransaction = uint(msg.value / getWeiToUsdExchangeRate());
totalUsdReceived = totalUsdReceived + usdReceivedInCurrentTransaction; // total usd received counter
totalUsdValueOfAllTokens = totalUsdReceived * 100 / PERCENTAGE_OF_TOKENS_SOLD_IN_SALE; // sold tokens are 28% of all tokens
if (cappedBuyerList[msg.sender] > 0)
{
cappedBuyerList[msg.sender] = cappedBuyerList[msg.sender] + usdReceivedInCurrentTransaction;
}
saleWalletAddress.transfer(msg.value); // Transfer ether to safe sale address
}
} | Change the exchange rate to new value, influences tokens received per purchase
| snipCoinToEtherExchangeRate = newSnipCoinToEtherExchangeRate; | 12,977,094 | [
1,
3043,
326,
7829,
4993,
358,
394,
460,
16,
13947,
89,
2369,
2430,
5079,
1534,
23701,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
3639,
4556,
625,
27055,
774,
41,
1136,
11688,
4727,
273,
394,
10461,
625,
27055,
774,
41,
1136,
11688,
4727,
31,
225,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
] |
./partial_match/1/0x67391801E7564994bdAa80544Ff916A7bCBFCB60/sources/MacroverseUniversalRegistry.sol | * If a token has a possible child for which childIndexOfToken would return the given index, returns that child. Fails otherwise. Index must not be wider than uint16 or it may be truncated./ Set the system field and make it a system token Set the planet field and make it a planet token Child could be a land or moon. The land trixels are first as 0-7 Make it land and set the first trixel Make it a moon | function childTokenAtIndex(uint256 token, uint256 index) public pure returns (uint256) {
uint256 token_type = getTokenType(token);
assert(token_type != TOKEN_TYPE_LAND_MAX);
if (token_type == TOKEN_TYPE_SECTOR) {
return setTokenType(setTokenSystem(token, uint16(index)), TOKEN_TYPE_SYSTEM);
return setTokenType(setTokenPlanet(token, uint16(index)), TOKEN_TYPE_PLANET);
if (index < TOP_TRIXELS) {
return setTokenType(setTokenTrixel(token, 0, uint16(index)), TOKEN_TYPE_LAND_MIN);
return setTokenType(setTokenMoon(token, uint16(index - TOP_TRIXELS)), TOKEN_TYPE_MOON);
}
return setTokenTrixel(setTokenTrixelCount(token, next_trixel + 1), next_trixel, uint16(index));
}
}
| 9,236,644 | [
1,
2047,
279,
1147,
711,
279,
3323,
1151,
364,
1492,
1151,
31985,
1345,
4102,
327,
326,
864,
770,
16,
1135,
716,
1151,
18,
8911,
87,
3541,
18,
3340,
1297,
486,
506,
341,
3585,
2353,
2254,
2313,
578,
518,
2026,
506,
15282,
18,
19,
1000,
326,
2619,
652,
471,
1221,
518,
279,
2619,
1147,
1000,
326,
4995,
278,
652,
471,
1221,
518,
279,
4995,
278,
1147,
7451,
3377,
506,
279,
19193,
578,
7344,
265,
18,
1021,
19193,
433,
3556,
87,
854,
1122,
487,
374,
17,
27,
4344,
518,
19193,
471,
444,
326,
1122,
433,
3556,
4344,
518,
279,
7344,
265,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
565,
445,
1151,
1345,
24499,
12,
11890,
5034,
1147,
16,
2254,
5034,
770,
13,
1071,
16618,
1135,
261,
11890,
5034,
13,
288,
203,
3639,
2254,
5034,
1147,
67,
723,
273,
9162,
559,
12,
2316,
1769,
203,
203,
3639,
1815,
12,
2316,
67,
723,
480,
14275,
67,
2399,
67,
48,
4307,
67,
6694,
1769,
203,
203,
3639,
309,
261,
2316,
67,
723,
422,
14275,
67,
2399,
67,
1090,
22727,
13,
288,
203,
5411,
327,
22629,
559,
12,
542,
1345,
3163,
12,
2316,
16,
2254,
2313,
12,
1615,
13,
3631,
14275,
67,
2399,
67,
14318,
1769,
203,
5411,
327,
22629,
559,
12,
542,
1345,
5365,
278,
12,
2316,
16,
2254,
2313,
12,
1615,
13,
3631,
14275,
67,
2399,
67,
6253,
1258,
1584,
1769,
203,
5411,
309,
261,
1615,
411,
18680,
67,
6566,
60,
2247,
55,
13,
288,
203,
7734,
327,
22629,
559,
12,
542,
1345,
56,
1932,
292,
12,
2316,
16,
374,
16,
2254,
2313,
12,
1615,
13,
3631,
14275,
67,
2399,
67,
48,
4307,
67,
6236,
1769,
203,
7734,
327,
22629,
559,
12,
542,
1345,
16727,
265,
12,
2316,
16,
2254,
2313,
12,
1615,
300,
18680,
67,
6566,
60,
2247,
55,
13,
3631,
14275,
67,
2399,
67,
5980,
673,
1769,
203,
5411,
289,
203,
5411,
327,
22629,
56,
1932,
292,
12,
542,
1345,
56,
1932,
292,
1380,
12,
2316,
16,
1024,
67,
313,
3556,
397,
404,
3631,
1024,
67,
313,
3556,
16,
2254,
2313,
12,
1615,
10019,
203,
3639,
289,
203,
565,
289,
203,
203,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
] |
pragma solidity ^0.6.0;
import "./Roles.sol";
import "./Renounceable.sol";
/**
* @title TwoTiered
* @author Alberto Cuesta Canada
* @notice Implements a two-role Roles
*/
contract TwoTiered is Roles, Renounceable {
bytes32 public constant ADMIN_ROLE_ID = "ADMIN";
bytes32 public constant USER_ROLE_ID = "USER";
/// @dev Create an admin and a user role, and add `root` to the admin role as a member.
constructor (address root) public {
_addMember(root, ADMIN_ROLE_ID);
}
/// @dev Restricted to members of the admin role.
modifier onlyAdmin() {
require(isAdmin(msg.sender), "Restricted to admins.");
_;
}
/// @dev Restricted to members of the user role.
modifier onlyUser() {
require(isUser(msg.sender), "Restricted to users.");
_;
}
/// @dev Return `true` if the account belongs to the admin role.
function isAdmin(address account) public virtual view returns (bool) {
return hasRole(account, ADMIN_ROLE_ID);
}
/// @dev Return `true` if the account belongs to the user role.
function isUser(address account) public virtual view returns (bool) {
return hasRole(account, USER_ROLE_ID);
}
/// @dev Add an account to the user role. Restricted to admins.
function addUser(address account) public virtual onlyAdmin {
_addMember(account, USER_ROLE_ID);
}
/// @dev Add an account to the admin role. Restricted to admins.
function addAdmin(address account) public virtual onlyAdmin {
_addMember(account, ADMIN_ROLE_ID);
}
/// @dev Remove an account from the user role. Restricted to admins.
function removeUser(address account) public virtual onlyAdmin {
_removeMember(account, USER_ROLE_ID);
}
/// @dev Remove oneself from the admin role.
function renounceAdmin() public virtual {
renounceMembership(ADMIN_ROLE_ID);
}
}
| @dev Remove oneself from the admin role. | function renounceAdmin() public virtual {
renounceMembership(ADMIN_ROLE_ID);
}
| 7,319,777 | [
1,
3288,
5945,
19079,
628,
326,
3981,
2478,
18,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
565,
445,
1654,
8386,
4446,
1435,
1071,
5024,
288,
203,
3639,
1654,
8386,
13447,
12,
15468,
67,
16256,
67,
734,
1769,
203,
565,
289,
203,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
] |
/**
*Submitted for verification at Etherscan.io on 2020-02-11
*/
// File: @aragon/os/contracts/common/EtherTokenConstant.sol
/*
* SPDX-License-Identitifer: MIT
*/
pragma solidity ^0.4.24;
// aragonOS and aragon-apps rely on address(0) to denote native ETH, in
// contracts where both tokens and ETH are accepted
contract EtherTokenConstant {
address internal constant ETH = address(0);
}
// File: @aragon/apps-agent/contracts/standards/ERC1271.sol
pragma solidity 0.4.24;
// ERC1271 on Feb 12th, 2019: https://github.com/ethereum/EIPs/blob/a97dc434930d0ccc4461c97d8c7a920dc585adf2/EIPS/eip-1271.md
// Using `isValidSignature(bytes32,bytes)` even though the standard still hasn't been modified
// Rationale: https://github.com/ethereum/EIPs/issues/1271#issuecomment-462719728
contract ERC1271 {
bytes4 constant public ERC1271_INTERFACE_ID = 0xfb855dc9; // this.isValidSignature.selector
bytes4 constant public ERC1271_RETURN_VALID_SIGNATURE = 0x20c13b0b; // TODO: Likely needs to be updated
bytes4 constant public ERC1271_RETURN_INVALID_SIGNATURE = 0x00000000;
/**
* @dev Function must be implemented by deriving contract
* @param _hash Arbitrary length data signed on the behalf of address(this)
* @param _signature Signature byte array associated with _data
* @return A bytes4 magic value 0x20c13b0b if the signature check passes, 0x00000000 if not
*
* MUST NOT modify state (using STATICCALL for solc < 0.5, view modifier for solc > 0.5)
* MUST allow external calls
*/
function isValidSignature(bytes32 _hash, bytes memory _signature) public view returns (bytes4);
function returnIsValidSignatureMagicNumber(bool isValid) internal pure returns (bytes4) {
return isValid ? ERC1271_RETURN_VALID_SIGNATURE : ERC1271_RETURN_INVALID_SIGNATURE;
}
}
contract ERC1271Bytes is ERC1271 {
/**
* @dev Default behavior of `isValidSignature(bytes,bytes)`, can be overloaded for custom validation
* @param _data Arbitrary length data signed on the behalf of address(this)
* @param _signature Signature byte array associated with _data
* @return A bytes4 magic value 0x20c13b0b if the signature check passes, 0x00000000 if not
*
* MUST NOT modify state (using STATICCALL for solc < 0.5, view modifier for solc > 0.5)
* MUST allow external calls
*/
function isValidSignature(bytes _data, bytes _signature) public view returns (bytes4) {
return isValidSignature(keccak256(_data), _signature);
}
}
// File: @aragon/apps-agent/contracts/SignatureValidator.sol
pragma solidity 0.4.24;
// Inspired by https://github.com/horizon-games/multi-token-standard/blob/319740cf2a78b8816269ae49a09c537b3fd7303b/contracts/utils/SignatureValidator.sol
// This should probably be moved into aOS: https://github.com/aragon/aragonOS/pull/442
library SignatureValidator {
enum SignatureMode {
Invalid, // 0x00
EIP712, // 0x01
EthSign, // 0x02
ERC1271, // 0x03
NMode // 0x04, to check if mode is specified, leave at the end
}
// bytes4(keccak256("isValidSignature(bytes,bytes)")
bytes4 public constant ERC1271_RETURN_VALID_SIGNATURE = 0x20c13b0b;
uint256 internal constant ERC1271_ISVALIDSIG_MAX_GAS = 250000;
string private constant ERROR_INVALID_LENGTH_POP_BYTE = "SIGVAL_INVALID_LENGTH_POP_BYTE";
/// @dev Validates that a hash was signed by a specified signer.
/// @param hash Hash which was signed.
/// @param signer Address of the signer.
/// @param signature ECDSA signature along with the mode (0 = Invalid, 1 = EIP712, 2 = EthSign, 3 = ERC1271) {mode}{r}{s}{v}.
/// @return Returns whether signature is from a specified user.
function isValidSignature(bytes32 hash, address signer, bytes signature) internal view returns (bool) {
if (signature.length == 0) {
return false;
}
uint8 modeByte = uint8(signature[0]);
if (modeByte >= uint8(SignatureMode.NMode)) {
return false;
}
SignatureMode mode = SignatureMode(modeByte);
if (mode == SignatureMode.EIP712) {
return ecVerify(hash, signer, signature);
} else if (mode == SignatureMode.EthSign) {
return ecVerify(
keccak256(abi.encodePacked("\x19Ethereum Signed Message:\n32", hash)),
signer,
signature
);
} else if (mode == SignatureMode.ERC1271) {
// Pop the mode byte before sending it down the validation chain
return safeIsValidSignature(signer, hash, popFirstByte(signature));
} else {
return false;
}
}
function ecVerify(bytes32 hash, address signer, bytes memory signature) private pure returns (bool) {
(bool badSig, bytes32 r, bytes32 s, uint8 v) = unpackEcSig(signature);
if (badSig) {
return false;
}
return signer == ecrecover(hash, v, r, s);
}
function unpackEcSig(bytes memory signature) private pure returns (bool badSig, bytes32 r, bytes32 s, uint8 v) {
if (signature.length != 66) {
badSig = true;
return;
}
v = uint8(signature[65]);
assembly {
r := mload(add(signature, 33))
s := mload(add(signature, 65))
}
// Allow signature version to be 0 or 1
if (v < 27) {
v += 27;
}
if (v != 27 && v != 28) {
badSig = true;
}
}
function popFirstByte(bytes memory input) private pure returns (bytes memory output) {
uint256 inputLength = input.length;
require(inputLength > 0, ERROR_INVALID_LENGTH_POP_BYTE);
output = new bytes(inputLength - 1);
if (output.length == 0) {
return output;
}
uint256 inputPointer;
uint256 outputPointer;
assembly {
inputPointer := add(input, 0x21)
outputPointer := add(output, 0x20)
}
memcpy(outputPointer, inputPointer, output.length);
}
function safeIsValidSignature(address validator, bytes32 hash, bytes memory signature) private view returns (bool) {
bytes memory data = abi.encodeWithSelector(ERC1271(validator).isValidSignature.selector, hash, signature);
bytes4 erc1271Return = safeBytes4StaticCall(validator, data, ERC1271_ISVALIDSIG_MAX_GAS);
return erc1271Return == ERC1271_RETURN_VALID_SIGNATURE;
}
function safeBytes4StaticCall(address target, bytes data, uint256 maxGas) private view returns (bytes4 ret) {
uint256 gasLeft = gasleft();
uint256 callGas = gasLeft > maxGas ? maxGas : gasLeft;
bool ok;
assembly {
ok := staticcall(callGas, target, add(data, 0x20), mload(data), 0, 0)
}
if (!ok) {
return;
}
uint256 size;
assembly { size := returndatasize }
if (size != 32) {
return;
}
assembly {
let ptr := mload(0x40) // get next free memory ptr
returndatacopy(ptr, 0, size) // copy return from above `staticcall`
ret := mload(ptr) // read data at ptr and set it to be returned
}
return ret;
}
// From: https://github.com/Arachnid/solidity-stringutils/blob/01e955c1d6/src/strings.sol
function memcpy(uint256 dest, uint256 src, uint256 len) private pure {
// Copy word-length chunks while possible
for (; len >= 32; len -= 32) {
assembly {
mstore(dest, mload(src))
}
dest += 32;
src += 32;
}
// Copy remaining bytes
uint mask = 256 ** (32 - len) - 1;
assembly {
let srcpart := and(mload(src), not(mask))
let destpart := and(mload(dest), mask)
mstore(dest, or(destpart, srcpart))
}
}
}
// File: @aragon/apps-agent/contracts/standards/IERC165.sol
pragma solidity 0.4.24;
interface IERC165 {
function supportsInterface(bytes4 interfaceId) external pure returns (bool);
}
// File: @aragon/os/contracts/common/UnstructuredStorage.sol
/*
* SPDX-License-Identitifer: MIT
*/
pragma solidity ^0.4.24;
library UnstructuredStorage {
function getStorageBool(bytes32 position) internal view returns (bool data) {
assembly { data := sload(position) }
}
function getStorageAddress(bytes32 position) internal view returns (address data) {
assembly { data := sload(position) }
}
function getStorageBytes32(bytes32 position) internal view returns (bytes32 data) {
assembly { data := sload(position) }
}
function getStorageUint256(bytes32 position) internal view returns (uint256 data) {
assembly { data := sload(position) }
}
function setStorageBool(bytes32 position, bool data) internal {
assembly { sstore(position, data) }
}
function setStorageAddress(bytes32 position, address data) internal {
assembly { sstore(position, data) }
}
function setStorageBytes32(bytes32 position, bytes32 data) internal {
assembly { sstore(position, data) }
}
function setStorageUint256(bytes32 position, uint256 data) internal {
assembly { sstore(position, data) }
}
}
// File: @aragon/os/contracts/acl/IACL.sol
/*
* SPDX-License-Identitifer: MIT
*/
pragma solidity ^0.4.24;
interface IACL {
function initialize(address permissionsCreator) external;
// TODO: this should be external
// See https://github.com/ethereum/solidity/issues/4832
function hasPermission(address who, address where, bytes32 what, bytes how) public view returns (bool);
}
// File: @aragon/os/contracts/common/IVaultRecoverable.sol
/*
* SPDX-License-Identitifer: MIT
*/
pragma solidity ^0.4.24;
interface IVaultRecoverable {
event RecoverToVault(address indexed vault, address indexed token, uint256 amount);
function transferToVault(address token) external;
function allowRecoverability(address token) external view returns (bool);
function getRecoveryVault() external view returns (address);
}
// File: @aragon/os/contracts/kernel/IKernel.sol
/*
* SPDX-License-Identitifer: MIT
*/
pragma solidity ^0.4.24;
interface IKernelEvents {
event SetApp(bytes32 indexed namespace, bytes32 indexed appId, address app);
}
// This should be an interface, but interfaces can't inherit yet :(
contract IKernel is IKernelEvents, IVaultRecoverable {
function acl() public view returns (IACL);
function hasPermission(address who, address where, bytes32 what, bytes how) public view returns (bool);
function setApp(bytes32 namespace, bytes32 appId, address app) public;
function getApp(bytes32 namespace, bytes32 appId) public view returns (address);
}
// File: @aragon/os/contracts/apps/AppStorage.sol
/*
* SPDX-License-Identitifer: MIT
*/
pragma solidity ^0.4.24;
contract AppStorage {
using UnstructuredStorage for bytes32;
/* Hardcoded constants to save gas
bytes32 internal constant KERNEL_POSITION = keccak256("aragonOS.appStorage.kernel");
bytes32 internal constant APP_ID_POSITION = keccak256("aragonOS.appStorage.appId");
*/
bytes32 internal constant KERNEL_POSITION = 0x4172f0f7d2289153072b0a6ca36959e0cbe2efc3afe50fc81636caa96338137b;
bytes32 internal constant APP_ID_POSITION = 0xd625496217aa6a3453eecb9c3489dc5a53e6c67b444329ea2b2cbc9ff547639b;
function kernel() public view returns (IKernel) {
return IKernel(KERNEL_POSITION.getStorageAddress());
}
function appId() public view returns (bytes32) {
return APP_ID_POSITION.getStorageBytes32();
}
function setKernel(IKernel _kernel) internal {
KERNEL_POSITION.setStorageAddress(address(_kernel));
}
function setAppId(bytes32 _appId) internal {
APP_ID_POSITION.setStorageBytes32(_appId);
}
}
// File: @aragon/os/contracts/acl/ACLSyntaxSugar.sol
/*
* SPDX-License-Identitifer: MIT
*/
pragma solidity ^0.4.24;
contract ACLSyntaxSugar {
function arr() internal pure returns (uint256[]) {
return new uint256[](0);
}
function arr(bytes32 _a) internal pure returns (uint256[] r) {
return arr(uint256(_a));
}
function arr(bytes32 _a, bytes32 _b) internal pure returns (uint256[] r) {
return arr(uint256(_a), uint256(_b));
}
function arr(address _a) internal pure returns (uint256[] r) {
return arr(uint256(_a));
}
function arr(address _a, address _b) internal pure returns (uint256[] r) {
return arr(uint256(_a), uint256(_b));
}
function arr(address _a, uint256 _b, uint256 _c) internal pure returns (uint256[] r) {
return arr(uint256(_a), _b, _c);
}
function arr(address _a, uint256 _b, uint256 _c, uint256 _d) internal pure returns (uint256[] r) {
return arr(uint256(_a), _b, _c, _d);
}
function arr(address _a, uint256 _b) internal pure returns (uint256[] r) {
return arr(uint256(_a), uint256(_b));
}
function arr(address _a, address _b, uint256 _c, uint256 _d, uint256 _e) internal pure returns (uint256[] r) {
return arr(uint256(_a), uint256(_b), _c, _d, _e);
}
function arr(address _a, address _b, address _c) internal pure returns (uint256[] r) {
return arr(uint256(_a), uint256(_b), uint256(_c));
}
function arr(address _a, address _b, uint256 _c) internal pure returns (uint256[] r) {
return arr(uint256(_a), uint256(_b), uint256(_c));
}
function arr(uint256 _a) internal pure returns (uint256[] r) {
r = new uint256[](1);
r[0] = _a;
}
function arr(uint256 _a, uint256 _b) internal pure returns (uint256[] r) {
r = new uint256[](2);
r[0] = _a;
r[1] = _b;
}
function arr(uint256 _a, uint256 _b, uint256 _c) internal pure returns (uint256[] r) {
r = new uint256[](3);
r[0] = _a;
r[1] = _b;
r[2] = _c;
}
function arr(uint256 _a, uint256 _b, uint256 _c, uint256 _d) internal pure returns (uint256[] r) {
r = new uint256[](4);
r[0] = _a;
r[1] = _b;
r[2] = _c;
r[3] = _d;
}
function arr(uint256 _a, uint256 _b, uint256 _c, uint256 _d, uint256 _e) internal pure returns (uint256[] r) {
r = new uint256[](5);
r[0] = _a;
r[1] = _b;
r[2] = _c;
r[3] = _d;
r[4] = _e;
}
}
contract ACLHelpers {
function decodeParamOp(uint256 _x) internal pure returns (uint8 b) {
return uint8(_x >> (8 * 30));
}
function decodeParamId(uint256 _x) internal pure returns (uint8 b) {
return uint8(_x >> (8 * 31));
}
function decodeParamsList(uint256 _x) internal pure returns (uint32 a, uint32 b, uint32 c) {
a = uint32(_x);
b = uint32(_x >> (8 * 4));
c = uint32(_x >> (8 * 8));
}
}
// File: @aragon/os/contracts/common/Uint256Helpers.sol
pragma solidity ^0.4.24;
library Uint256Helpers {
uint256 private constant MAX_UINT64 = uint64(-1);
string private constant ERROR_NUMBER_TOO_BIG = "UINT64_NUMBER_TOO_BIG";
function toUint64(uint256 a) internal pure returns (uint64) {
require(a <= MAX_UINT64, ERROR_NUMBER_TOO_BIG);
return uint64(a);
}
}
// File: @aragon/os/contracts/common/TimeHelpers.sol
/*
* SPDX-License-Identitifer: MIT
*/
pragma solidity ^0.4.24;
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();
}
}
// File: @aragon/os/contracts/common/Initializable.sol
/*
* SPDX-License-Identitifer: MIT
*/
pragma solidity ^0.4.24;
contract Initializable is TimeHelpers {
using UnstructuredStorage for bytes32;
// keccak256("aragonOS.initializable.initializationBlock")
bytes32 internal constant INITIALIZATION_BLOCK_POSITION = 0xebb05b386a8d34882b8711d156f463690983dc47815980fb82aeeff1aa43579e;
string private constant ERROR_ALREADY_INITIALIZED = "INIT_ALREADY_INITIALIZED";
string private constant ERROR_NOT_INITIALIZED = "INIT_NOT_INITIALIZED";
modifier onlyInit {
require(getInitializationBlock() == 0, ERROR_ALREADY_INITIALIZED);
_;
}
modifier isInitialized {
require(hasInitialized(), ERROR_NOT_INITIALIZED);
_;
}
/**
* @return Block number in which the contract was initialized
*/
function getInitializationBlock() public view returns (uint256) {
return INITIALIZATION_BLOCK_POSITION.getStorageUint256();
}
/**
* @return Whether the contract has been initialized by the time of the current block
*/
function hasInitialized() public view returns (bool) {
uint256 initializationBlock = getInitializationBlock();
return initializationBlock != 0 && getBlockNumber() >= initializationBlock;
}
/**
* @dev Function to be called by top level contract after initialization has finished.
*/
function initialized() internal onlyInit {
INITIALIZATION_BLOCK_POSITION.setStorageUint256(getBlockNumber());
}
/**
* @dev Function to be called by top level contract after initialization to enable the contract
* at a future block number rather than immediately.
*/
function initializedAt(uint256 _blockNumber) internal onlyInit {
INITIALIZATION_BLOCK_POSITION.setStorageUint256(_blockNumber);
}
}
// File: @aragon/os/contracts/common/Petrifiable.sol
/*
* SPDX-License-Identitifer: MIT
*/
pragma solidity ^0.4.24;
contract Petrifiable is Initializable {
// Use block UINT256_MAX (which should be never) as the initializable date
uint256 internal constant PETRIFIED_BLOCK = uint256(-1);
function isPetrified() public view returns (bool) {
return getInitializationBlock() == PETRIFIED_BLOCK;
}
/**
* @dev Function to be called by top level contract to prevent being initialized.
* Useful for freezing base contracts when they're used behind proxies.
*/
function petrify() internal onlyInit {
initializedAt(PETRIFIED_BLOCK);
}
}
// File: @aragon/os/contracts/common/Autopetrified.sol
/*
* SPDX-License-Identitifer: MIT
*/
pragma solidity ^0.4.24;
contract Autopetrified is Petrifiable {
constructor() public {
// Immediately petrify base (non-proxy) instances of inherited contracts on deploy.
// This renders them uninitializable (and unusable without a proxy).
petrify();
}
}
// File: @aragon/os/contracts/common/ConversionHelpers.sol
pragma solidity ^0.4.24;
library ConversionHelpers {
string private constant ERROR_IMPROPER_LENGTH = "CONVERSION_IMPROPER_LENGTH";
function dangerouslyCastUintArrayToBytes(uint256[] memory _input) internal pure returns (bytes memory output) {
// Force cast the uint256[] into a bytes array, by overwriting its length
// Note that the bytes array doesn't need to be initialized as we immediately overwrite it
// with the input and a new length. The input becomes invalid from this point forward.
uint256 byteLength = _input.length * 32;
assembly {
output := _input
mstore(output, byteLength)
}
}
function dangerouslyCastBytesToUintArray(bytes memory _input) internal pure returns (uint256[] memory output) {
// Force cast the bytes array into a uint256[], by overwriting its length
// Note that the uint256[] doesn't need to be initialized as we immediately overwrite it
// with the input and a new length. The input becomes invalid from this point forward.
uint256 intsLength = _input.length / 32;
require(_input.length == intsLength * 32, ERROR_IMPROPER_LENGTH);
assembly {
output := _input
mstore(output, intsLength)
}
}
}
// File: @aragon/os/contracts/common/ReentrancyGuard.sol
/*
* SPDX-License-Identitifer: MIT
*/
pragma solidity ^0.4.24;
contract ReentrancyGuard {
using UnstructuredStorage for bytes32;
/* Hardcoded constants to save gas
bytes32 internal constant REENTRANCY_MUTEX_POSITION = keccak256("aragonOS.reentrancyGuard.mutex");
*/
bytes32 private constant REENTRANCY_MUTEX_POSITION = 0xe855346402235fdd185c890e68d2c4ecad599b88587635ee285bce2fda58dacb;
string private constant ERROR_REENTRANT = "REENTRANCY_REENTRANT_CALL";
modifier nonReentrant() {
// Ensure mutex is unlocked
require(!REENTRANCY_MUTEX_POSITION.getStorageBool(), ERROR_REENTRANT);
// Lock mutex before function call
REENTRANCY_MUTEX_POSITION.setStorageBool(true);
// Perform function call
_;
// Unlock mutex after function call
REENTRANCY_MUTEX_POSITION.setStorageBool(false);
}
}
// File: @aragon/os/contracts/lib/token/ERC20.sol
// See https://github.com/OpenZeppelin/openzeppelin-solidity/blob/a9f910d34f0ab33a1ae5e714f69f9596a02b4d91/contracts/token/ERC20/ERC20.sol
pragma solidity ^0.4.24;
/**
* @title ERC20 interface
* @dev see https://github.com/ethereum/EIPs/issues/20
*/
contract ERC20 {
function totalSupply() public view returns (uint256);
function balanceOf(address _who) public view returns (uint256);
function allowance(address _owner, address _spender)
public view returns (uint256);
function transfer(address _to, uint256 _value) public returns (bool);
function approve(address _spender, uint256 _value)
public returns (bool);
function transferFrom(address _from, address _to, uint256 _value)
public returns (bool);
event Transfer(
address indexed from,
address indexed to,
uint256 value
);
event Approval(
address indexed owner,
address indexed spender,
uint256 value
);
}
// File: @aragon/os/contracts/common/IsContract.sol
/*
* SPDX-License-Identitifer: MIT
*/
pragma solidity ^0.4.24;
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;
}
}
// File: @aragon/os/contracts/common/SafeERC20.sol
// Inspired by AdEx (https://github.com/AdExNetwork/adex-protocol-eth/blob/b9df617829661a7518ee10f4cb6c4108659dd6d5/contracts/libs/SafeERC20.sol)
// and 0x (https://github.com/0xProject/0x-monorepo/blob/737d1dc54d72872e24abce5a1dbe1b66d35fa21a/contracts/protocol/contracts/protocol/AssetProxy/ERC20Proxy.sol#L143)
pragma solidity ^0.4.24;
library SafeERC20 {
// Before 0.5, solidity has a mismatch between `address.transfer()` and `token.transfer()`:
// https://github.com/ethereum/solidity/issues/3544
bytes4 private constant TRANSFER_SELECTOR = 0xa9059cbb;
string private constant ERROR_TOKEN_BALANCE_REVERTED = "SAFE_ERC_20_BALANCE_REVERTED";
string private constant ERROR_TOKEN_ALLOWANCE_REVERTED = "SAFE_ERC_20_ALLOWANCE_REVERTED";
function invokeAndCheckSuccess(address _addr, bytes memory _calldata)
private
returns (bool)
{
bool ret;
assembly {
let ptr := mload(0x40) // free memory pointer
let success := call(
gas, // forward all gas
_addr, // address
0, // no value
add(_calldata, 0x20), // calldata start
mload(_calldata), // calldata length
ptr, // write output over free memory
0x20 // uint256 return
)
if gt(success, 0) {
// Check number of bytes returned from last function call
switch returndatasize
// No bytes returned: assume success
case 0 {
ret := 1
}
// 32 bytes returned: check if non-zero
case 0x20 {
// Only return success if returned data was true
// Already have output in ptr
ret := eq(mload(ptr), 1)
}
// Not sure what was returned: don't mark as success
default { }
}
}
return ret;
}
function staticInvoke(address _addr, bytes memory _calldata)
private
view
returns (bool, uint256)
{
bool success;
uint256 ret;
assembly {
let ptr := mload(0x40) // free memory pointer
success := staticcall(
gas, // forward all gas
_addr, // address
add(_calldata, 0x20), // calldata start
mload(_calldata), // calldata length
ptr, // write output over free memory
0x20 // uint256 return
)
if gt(success, 0) {
ret := mload(ptr)
}
}
return (success, ret);
}
/**
* @dev Same as a standards-compliant ERC20.transfer() that never reverts (returns false).
* Note that this makes an external call to the token.
*/
function safeTransfer(ERC20 _token, address _to, uint256 _amount) internal returns (bool) {
bytes memory transferCallData = abi.encodeWithSelector(
TRANSFER_SELECTOR,
_to,
_amount
);
return invokeAndCheckSuccess(_token, transferCallData);
}
/**
* @dev Same as a standards-compliant ERC20.transferFrom() that never reverts (returns false).
* Note that this makes an external call to the token.
*/
function safeTransferFrom(ERC20 _token, address _from, address _to, uint256 _amount) internal returns (bool) {
bytes memory transferFromCallData = abi.encodeWithSelector(
_token.transferFrom.selector,
_from,
_to,
_amount
);
return invokeAndCheckSuccess(_token, transferFromCallData);
}
/**
* @dev Same as a standards-compliant ERC20.approve() that never reverts (returns false).
* Note that this makes an external call to the token.
*/
function safeApprove(ERC20 _token, address _spender, uint256 _amount) internal returns (bool) {
bytes memory approveCallData = abi.encodeWithSelector(
_token.approve.selector,
_spender,
_amount
);
return invokeAndCheckSuccess(_token, approveCallData);
}
/**
* @dev Static call into ERC20.balanceOf().
* Reverts if the call fails for some reason (should never fail).
*/
function staticBalanceOf(ERC20 _token, address _owner) internal view returns (uint256) {
bytes memory balanceOfCallData = abi.encodeWithSelector(
_token.balanceOf.selector,
_owner
);
(bool success, uint256 tokenBalance) = staticInvoke(_token, balanceOfCallData);
require(success, ERROR_TOKEN_BALANCE_REVERTED);
return tokenBalance;
}
/**
* @dev Static call into ERC20.allowance().
* Reverts if the call fails for some reason (should never fail).
*/
function staticAllowance(ERC20 _token, address _owner, address _spender) internal view returns (uint256) {
bytes memory allowanceCallData = abi.encodeWithSelector(
_token.allowance.selector,
_owner,
_spender
);
(bool success, uint256 allowance) = staticInvoke(_token, allowanceCallData);
require(success, ERROR_TOKEN_ALLOWANCE_REVERTED);
return allowance;
}
}
// File: @aragon/os/contracts/common/VaultRecoverable.sol
/*
* SPDX-License-Identitifer: MIT
*/
pragma solidity ^0.4.24;
contract VaultRecoverable is IVaultRecoverable, EtherTokenConstant, IsContract {
using SafeERC20 for ERC20;
string private constant ERROR_DISALLOWED = "RECOVER_DISALLOWED";
string private constant ERROR_VAULT_NOT_CONTRACT = "RECOVER_VAULT_NOT_CONTRACT";
string private constant ERROR_TOKEN_TRANSFER_FAILED = "RECOVER_TOKEN_TRANSFER_FAILED";
/**
* @notice Send funds to recovery Vault. This contract should never receive funds,
* but in case it does, this function allows one to recover them.
* @param _token Token balance to be sent to recovery vault.
*/
function transferToVault(address _token) external {
require(allowRecoverability(_token), ERROR_DISALLOWED);
address vault = getRecoveryVault();
require(isContract(vault), ERROR_VAULT_NOT_CONTRACT);
uint256 balance;
if (_token == ETH) {
balance = address(this).balance;
vault.transfer(balance);
} else {
ERC20 token = ERC20(_token);
balance = token.staticBalanceOf(this);
require(token.safeTransfer(vault, balance), ERROR_TOKEN_TRANSFER_FAILED);
}
emit RecoverToVault(vault, _token, balance);
}
/**
* @dev By default deriving from AragonApp makes it recoverable
* @param token Token address that would be recovered
* @return bool whether the app allows the recovery
*/
function allowRecoverability(address token) public view returns (bool) {
return true;
}
// Cast non-implemented interface to be public so we can use it internally
function getRecoveryVault() public view returns (address);
}
// File: @aragon/os/contracts/evmscript/IEVMScriptExecutor.sol
/*
* SPDX-License-Identitifer: MIT
*/
pragma solidity ^0.4.24;
interface IEVMScriptExecutor {
function execScript(bytes script, bytes input, address[] blacklist) external returns (bytes);
function executorType() external pure returns (bytes32);
}
// File: @aragon/os/contracts/evmscript/IEVMScriptRegistry.sol
/*
* SPDX-License-Identitifer: MIT
*/
pragma solidity ^0.4.24;
contract EVMScriptRegistryConstants {
/* Hardcoded constants to save gas
bytes32 internal constant EVMSCRIPT_REGISTRY_APP_ID = apmNamehash("evmreg");
*/
bytes32 internal constant EVMSCRIPT_REGISTRY_APP_ID = 0xddbcfd564f642ab5627cf68b9b7d374fb4f8a36e941a75d89c87998cef03bd61;
}
interface IEVMScriptRegistry {
function addScriptExecutor(IEVMScriptExecutor executor) external returns (uint id);
function disableScriptExecutor(uint256 executorId) external;
// TODO: this should be external
// See https://github.com/ethereum/solidity/issues/4832
function getScriptExecutor(bytes script) public view returns (IEVMScriptExecutor);
}
// File: @aragon/os/contracts/kernel/KernelConstants.sol
/*
* SPDX-License-Identitifer: MIT
*/
pragma solidity ^0.4.24;
contract KernelAppIds {
/* Hardcoded constants to save gas
bytes32 internal constant KERNEL_CORE_APP_ID = apmNamehash("kernel");
bytes32 internal constant KERNEL_DEFAULT_ACL_APP_ID = apmNamehash("acl");
bytes32 internal constant KERNEL_DEFAULT_VAULT_APP_ID = apmNamehash("vault");
*/
bytes32 internal constant KERNEL_CORE_APP_ID = 0x3b4bf6bf3ad5000ecf0f989d5befde585c6860fea3e574a4fab4c49d1c177d9c;
bytes32 internal constant KERNEL_DEFAULT_ACL_APP_ID = 0xe3262375f45a6e2026b7e7b18c2b807434f2508fe1a2a3dfb493c7df8f4aad6a;
bytes32 internal constant KERNEL_DEFAULT_VAULT_APP_ID = 0x7e852e0fcfce6551c13800f1e7476f982525c2b5277ba14b24339c68416336d1;
}
contract KernelNamespaceConstants {
/* Hardcoded constants to save gas
bytes32 internal constant KERNEL_CORE_NAMESPACE = keccak256("core");
bytes32 internal constant KERNEL_APP_BASES_NAMESPACE = keccak256("base");
bytes32 internal constant KERNEL_APP_ADDR_NAMESPACE = keccak256("app");
*/
bytes32 internal constant KERNEL_CORE_NAMESPACE = 0xc681a85306374a5ab27f0bbc385296a54bcd314a1948b6cf61c4ea1bc44bb9f8;
bytes32 internal constant KERNEL_APP_BASES_NAMESPACE = 0xf1f3eb40f5bc1ad1344716ced8b8a0431d840b5783aea1fd01786bc26f35ac0f;
bytes32 internal constant KERNEL_APP_ADDR_NAMESPACE = 0xd6f028ca0e8edb4a8c9757ca4fdccab25fa1e0317da1188108f7d2dee14902fb;
}
// File: @aragon/os/contracts/evmscript/EVMScriptRunner.sol
/*
* SPDX-License-Identitifer: MIT
*/
pragma solidity ^0.4.24;
contract EVMScriptRunner is AppStorage, Initializable, EVMScriptRegistryConstants, KernelNamespaceConstants {
string private constant ERROR_EXECUTOR_UNAVAILABLE = "EVMRUN_EXECUTOR_UNAVAILABLE";
string private constant ERROR_PROTECTED_STATE_MODIFIED = "EVMRUN_PROTECTED_STATE_MODIFIED";
/* This is manually crafted in assembly
string private constant ERROR_EXECUTOR_INVALID_RETURN = "EVMRUN_EXECUTOR_INVALID_RETURN";
*/
event ScriptResult(address indexed executor, bytes script, bytes input, bytes returnData);
function getEVMScriptExecutor(bytes _script) public view returns (IEVMScriptExecutor) {
return IEVMScriptExecutor(getEVMScriptRegistry().getScriptExecutor(_script));
}
function getEVMScriptRegistry() public view returns (IEVMScriptRegistry) {
address registryAddr = kernel().getApp(KERNEL_APP_ADDR_NAMESPACE, EVMSCRIPT_REGISTRY_APP_ID);
return IEVMScriptRegistry(registryAddr);
}
function runScript(bytes _script, bytes _input, address[] _blacklist)
internal
isInitialized
protectState
returns (bytes)
{
IEVMScriptExecutor executor = getEVMScriptExecutor(_script);
require(address(executor) != address(0), ERROR_EXECUTOR_UNAVAILABLE);
bytes4 sig = executor.execScript.selector;
bytes memory data = abi.encodeWithSelector(sig, _script, _input, _blacklist);
bytes memory output;
assembly {
let success := delegatecall(
gas, // forward all gas
executor, // address
add(data, 0x20), // calldata start
mload(data), // calldata length
0, // don't write output (we'll handle this ourselves)
0 // don't write output
)
output := mload(0x40) // free mem ptr get
switch success
case 0 {
// If the call errored, forward its full error data
returndatacopy(output, 0, returndatasize)
revert(output, returndatasize)
}
default {
switch gt(returndatasize, 0x3f)
case 0 {
// Need at least 0x40 bytes returned for properly ABI-encoded bytes values,
// revert with "EVMRUN_EXECUTOR_INVALID_RETURN"
// See remix: doing a `revert("EVMRUN_EXECUTOR_INVALID_RETURN")` always results in
// this memory layout
mstore(output, 0x08c379a000000000000000000000000000000000000000000000000000000000) // error identifier
mstore(add(output, 0x04), 0x0000000000000000000000000000000000000000000000000000000000000020) // starting offset
mstore(add(output, 0x24), 0x000000000000000000000000000000000000000000000000000000000000001e) // reason length
mstore(add(output, 0x44), 0x45564d52554e5f4558454355544f525f494e56414c49445f52455455524e0000) // reason
revert(output, 100) // 100 = 4 + 3 * 32 (error identifier + 3 words for the ABI encoded error)
}
default {
// Copy result
//
// Needs to perform an ABI decode for the expected `bytes` return type of
// `executor.execScript()` as solidity will automatically ABI encode the returned bytes as:
// [ position of the first dynamic length return value = 0x20 (32 bytes) ]
// [ output length (32 bytes) ]
// [ output content (N bytes) ]
//
// Perform the ABI decode by ignoring the first 32 bytes of the return data
let copysize := sub(returndatasize, 0x20)
returndatacopy(output, 0x20, copysize)
mstore(0x40, add(output, copysize)) // free mem ptr set
}
}
}
emit ScriptResult(address(executor), _script, _input, output);
return output;
}
modifier protectState {
address preKernel = address(kernel());
bytes32 preAppId = appId();
_; // exec
require(address(kernel()) == preKernel, ERROR_PROTECTED_STATE_MODIFIED);
require(appId() == preAppId, ERROR_PROTECTED_STATE_MODIFIED);
}
}
// File: @aragon/os/contracts/apps/AragonApp.sol
/*
* SPDX-License-Identitifer: MIT
*/
pragma solidity ^0.4.24;
// Contracts inheriting from AragonApp are, by default, immediately petrified upon deployment so
// that they can never be initialized.
// Unless overriden, this behaviour enforces those contracts to be usable only behind an AppProxy.
// ReentrancyGuard, EVMScriptRunner, and ACLSyntaxSugar are not directly used by this contract, but
// are included so that they are automatically usable by subclassing contracts
contract AragonApp is AppStorage, Autopetrified, VaultRecoverable, ReentrancyGuard, EVMScriptRunner, ACLSyntaxSugar {
string private constant ERROR_AUTH_FAILED = "APP_AUTH_FAILED";
modifier auth(bytes32 _role) {
require(canPerform(msg.sender, _role, new uint256[](0)), ERROR_AUTH_FAILED);
_;
}
modifier authP(bytes32 _role, uint256[] _params) {
require(canPerform(msg.sender, _role, _params), ERROR_AUTH_FAILED);
_;
}
/**
* @dev Check whether an action can be performed by a sender for a particular role on this app
* @param _sender Sender of the call
* @param _role Role on this app
* @param _params Permission params for the role
* @return Boolean indicating whether the sender has the permissions to perform the action.
* Always returns false if the app hasn't been initialized yet.
*/
function canPerform(address _sender, bytes32 _role, uint256[] _params) public view returns (bool) {
if (!hasInitialized()) {
return false;
}
IKernel linkedKernel = kernel();
if (address(linkedKernel) == address(0)) {
return false;
}
return linkedKernel.hasPermission(
_sender,
address(this),
_role,
ConversionHelpers.dangerouslyCastUintArrayToBytes(_params)
);
}
/**
* @dev Get the recovery vault for the app
* @return Recovery vault address for the app
*/
function getRecoveryVault() public view returns (address) {
// Funds recovery via a vault is only available when used with a kernel
return kernel().getRecoveryVault(); // if kernel is not set, it will revert
}
}
// File: @aragon/os/contracts/common/DepositableStorage.sol
pragma solidity 0.4.24;
contract DepositableStorage {
using UnstructuredStorage for bytes32;
// keccak256("aragonOS.depositableStorage.depositable")
bytes32 internal constant DEPOSITABLE_POSITION = 0x665fd576fbbe6f247aff98f5c94a561e3f71ec2d3c988d56f12d342396c50cea;
function isDepositable() public view returns (bool) {
return DEPOSITABLE_POSITION.getStorageBool();
}
function setDepositable(bool _depositable) internal {
DEPOSITABLE_POSITION.setStorageBool(_depositable);
}
}
// File: @aragon/apps-vault/contracts/Vault.sol
pragma solidity 0.4.24;
contract Vault is EtherTokenConstant, AragonApp, DepositableStorage {
using SafeERC20 for ERC20;
bytes32 public constant TRANSFER_ROLE = keccak256("TRANSFER_ROLE");
string private constant ERROR_DATA_NON_ZERO = "VAULT_DATA_NON_ZERO";
string private constant ERROR_NOT_DEPOSITABLE = "VAULT_NOT_DEPOSITABLE";
string private constant ERROR_DEPOSIT_VALUE_ZERO = "VAULT_DEPOSIT_VALUE_ZERO";
string private constant ERROR_TRANSFER_VALUE_ZERO = "VAULT_TRANSFER_VALUE_ZERO";
string private constant ERROR_SEND_REVERTED = "VAULT_SEND_REVERTED";
string private constant ERROR_VALUE_MISMATCH = "VAULT_VALUE_MISMATCH";
string private constant ERROR_TOKEN_TRANSFER_FROM_REVERTED = "VAULT_TOKEN_TRANSFER_FROM_REVERT";
string private constant ERROR_TOKEN_TRANSFER_REVERTED = "VAULT_TOKEN_TRANSFER_REVERTED";
event VaultTransfer(address indexed token, address indexed to, uint256 amount);
event VaultDeposit(address indexed token, address indexed sender, uint256 amount);
/**
* @dev On a normal send() or transfer() this fallback is never executed as it will be
* intercepted by the Proxy (see aragonOS#281)
*/
function () external payable isInitialized {
require(msg.data.length == 0, ERROR_DATA_NON_ZERO);
_deposit(ETH, msg.value);
}
/**
* @notice Initialize Vault app
* @dev As an AragonApp it needs to be initialized in order for roles (`auth` and `authP`) to work
*/
function initialize() external onlyInit {
initialized();
setDepositable(true);
}
/**
* @notice Deposit `_value` `_token` to the vault
* @param _token Address of the token being transferred
* @param _value Amount of tokens being transferred
*/
function deposit(address _token, uint256 _value) external payable isInitialized {
_deposit(_token, _value);
}
/**
* @notice Transfer `_value` `_token` from the Vault to `_to`
* @param _token Address of the token being transferred
* @param _to Address of the recipient of tokens
* @param _value Amount of tokens being transferred
*/
/* solium-disable-next-line function-order */
function transfer(address _token, address _to, uint256 _value)
external
authP(TRANSFER_ROLE, arr(_token, _to, _value))
{
require(_value > 0, ERROR_TRANSFER_VALUE_ZERO);
if (_token == ETH) {
require(_to.send(_value), ERROR_SEND_REVERTED);
} else {
require(ERC20(_token).safeTransfer(_to, _value), ERROR_TOKEN_TRANSFER_REVERTED);
}
emit VaultTransfer(_token, _to, _value);
}
function balance(address _token) public view returns (uint256) {
if (_token == ETH) {
return address(this).balance;
} else {
return ERC20(_token).staticBalanceOf(address(this));
}
}
/**
* @dev Disable recovery escape hatch, as it could be used
* maliciously to transfer funds away from the vault
*/
function allowRecoverability(address) public view returns (bool) {
return false;
}
function _deposit(address _token, uint256 _value) internal {
require(isDepositable(), ERROR_NOT_DEPOSITABLE);
require(_value > 0, ERROR_DEPOSIT_VALUE_ZERO);
if (_token == ETH) {
// Deposit is implicit in this case
require(msg.value == _value, ERROR_VALUE_MISMATCH);
} else {
require(
ERC20(_token).safeTransferFrom(msg.sender, address(this), _value),
ERROR_TOKEN_TRANSFER_FROM_REVERTED
);
}
emit VaultDeposit(_token, msg.sender, _value);
}
}
// File: @aragon/os/contracts/common/IForwarder.sol
/*
* SPDX-License-Identitifer: MIT
*/
pragma solidity ^0.4.24;
interface IForwarder {
function isForwarder() external pure returns (bool);
// TODO: this should be external
// See https://github.com/ethereum/solidity/issues/4832
function canForward(address sender, bytes evmCallScript) public view returns (bool);
// TODO: this should be external
// See https://github.com/ethereum/solidity/issues/4832
function forward(bytes evmCallScript) public;
}
// File: @aragon/apps-agent/contracts/Agent.sol
/*
* SPDX-License-Identitifer: GPL-3.0-or-later
*/
pragma solidity 0.4.24;
contract Agent is IERC165, ERC1271Bytes, IForwarder, IsContract, Vault {
/* Hardcoded constants to save gas
bytes32 public constant EXECUTE_ROLE = keccak256("EXECUTE_ROLE");
bytes32 public constant SAFE_EXECUTE_ROLE = keccak256("SAFE_EXECUTE_ROLE");
bytes32 public constant ADD_PROTECTED_TOKEN_ROLE = keccak256("ADD_PROTECTED_TOKEN_ROLE");
bytes32 public constant REMOVE_PROTECTED_TOKEN_ROLE = keccak256("REMOVE_PROTECTED_TOKEN_ROLE");
bytes32 public constant ADD_PRESIGNED_HASH_ROLE = keccak256("ADD_PRESIGNED_HASH_ROLE");
bytes32 public constant DESIGNATE_SIGNER_ROLE = keccak256("DESIGNATE_SIGNER_ROLE");
bytes32 public constant RUN_SCRIPT_ROLE = keccak256("RUN_SCRIPT_ROLE");
*/
bytes32 public constant EXECUTE_ROLE = 0xcebf517aa4440d1d125e0355aae64401211d0848a23c02cc5d29a14822580ba4;
bytes32 public constant SAFE_EXECUTE_ROLE = 0x0a1ad7b87f5846153c6d5a1f761d71c7d0cfd122384f56066cd33239b7933694;
bytes32 public constant ADD_PROTECTED_TOKEN_ROLE = 0x6eb2a499556bfa2872f5aa15812b956cc4a71b4d64eb3553f7073c7e41415aaa;
bytes32 public constant REMOVE_PROTECTED_TOKEN_ROLE = 0x71eee93d500f6f065e38b27d242a756466a00a52a1dbcd6b4260f01a8640402a;
bytes32 public constant ADD_PRESIGNED_HASH_ROLE = 0x0b29780bb523a130b3b01f231ef49ed2fa2781645591a0b0a44ca98f15a5994c;
bytes32 public constant DESIGNATE_SIGNER_ROLE = 0x23ce341656c3f14df6692eebd4757791e33662b7dcf9970c8308303da5472b7c;
bytes32 public constant RUN_SCRIPT_ROLE = 0xb421f7ad7646747f3051c50c0b8e2377839296cd4973e27f63821d73e390338f;
uint256 public constant PROTECTED_TOKENS_CAP = 10;
bytes4 private constant ERC165_INTERFACE_ID = 0x01ffc9a7;
string private constant ERROR_TARGET_PROTECTED = "AGENT_TARGET_PROTECTED";
string private constant ERROR_PROTECTED_TOKENS_MODIFIED = "AGENT_PROTECTED_TOKENS_MODIFIED";
string private constant ERROR_PROTECTED_BALANCE_LOWERED = "AGENT_PROTECTED_BALANCE_LOWERED";
string private constant ERROR_TOKENS_CAP_REACHED = "AGENT_TOKENS_CAP_REACHED";
string private constant ERROR_TOKEN_NOT_ERC20 = "AGENT_TOKEN_NOT_ERC20";
string private constant ERROR_TOKEN_ALREADY_PROTECTED = "AGENT_TOKEN_ALREADY_PROTECTED";
string private constant ERROR_TOKEN_NOT_PROTECTED = "AGENT_TOKEN_NOT_PROTECTED";
string private constant ERROR_DESIGNATED_TO_SELF = "AGENT_DESIGNATED_TO_SELF";
string private constant ERROR_CAN_NOT_FORWARD = "AGENT_CAN_NOT_FORWARD";
mapping (bytes32 => bool) public isPresigned;
address public designatedSigner;
address[] public protectedTokens;
event SafeExecute(address indexed sender, address indexed target, bytes data);
event Execute(address indexed sender, address indexed target, uint256 ethValue, bytes data);
event AddProtectedToken(address indexed token);
event RemoveProtectedToken(address indexed token);
event PresignHash(address indexed sender, bytes32 indexed hash);
event SetDesignatedSigner(address indexed sender, address indexed oldSigner, address indexed newSigner);
/**
* @notice Execute '`@radspec(_target, _data)`' on `_target``_ethValue == 0 ? '' : ' (Sending' + @tokenAmount(0x0000000000000000000000000000000000000000, _ethValue) + ')'`
* @param _target Address where the action is being executed
* @param _ethValue Amount of ETH from the contract that is sent with the action
* @param _data Calldata for the action
* @return Exits call frame forwarding the return data of the executed call (either error or success data)
*/
function execute(address _target, uint256 _ethValue, bytes _data)
external // This function MUST always be external as the function performs a low level return, exiting the Agent app execution context
authP(EXECUTE_ROLE, arr(_target, _ethValue, uint256(_getSig(_data)))) // bytes4 casted as uint256 sets the bytes as the LSBs
{
bool result = _target.call.value(_ethValue)(_data);
if (result) {
emit Execute(msg.sender, _target, _ethValue, _data);
}
assembly {
let ptr := mload(0x40)
returndatacopy(ptr, 0, returndatasize)
// revert instead of invalid() bc if the underlying call failed with invalid() it already wasted gas.
// if the call returned error data, forward it
switch result case 0 { revert(ptr, returndatasize) }
default { return(ptr, returndatasize) }
}
}
/**
* @notice Execute '`@radspec(_target, _data)`' on `_target` ensuring that protected tokens can't be spent
* @param _target Address where the action is being executed
* @param _data Calldata for the action
* @return Exits call frame forwarding the return data of the executed call (either error or success data)
*/
function safeExecute(address _target, bytes _data)
external // This function MUST always be external as the function performs a low level return, exiting the Agent app execution context
authP(SAFE_EXECUTE_ROLE, arr(_target, uint256(_getSig(_data)))) // bytes4 casted as uint256 sets the bytes as the LSBs
{
uint256 protectedTokensLength = protectedTokens.length;
address[] memory protectedTokens_ = new address[](protectedTokensLength);
uint256[] memory balances = new uint256[](protectedTokensLength);
for (uint256 i = 0; i < protectedTokensLength; i++) {
address token = protectedTokens[i];
require(_target != token, ERROR_TARGET_PROTECTED);
// we copy the protected tokens array to check whether the storage array has been modified during the underlying call
protectedTokens_[i] = token;
// we copy the balances to check whether they have been modified during the underlying call
balances[i] = balance(token);
}
bool result = _target.call(_data);
bytes32 ptr;
uint256 size;
assembly {
size := returndatasize
ptr := mload(0x40)
mstore(0x40, add(ptr, returndatasize))
returndatacopy(ptr, 0, returndatasize)
}
if (result) {
// if the underlying call has succeeded, we check that the protected tokens
// and their balances have not been modified and return the call's return data
require(protectedTokens.length == protectedTokensLength, ERROR_PROTECTED_TOKENS_MODIFIED);
for (uint256 j = 0; j < protectedTokensLength; j++) {
require(protectedTokens[j] == protectedTokens_[j], ERROR_PROTECTED_TOKENS_MODIFIED);
require(balance(protectedTokens[j]) >= balances[j], ERROR_PROTECTED_BALANCE_LOWERED);
}
emit SafeExecute(msg.sender, _target, _data);
assembly {
return(ptr, size)
}
} else {
// if the underlying call has failed, we revert and forward returned error data
assembly {
revert(ptr, size)
}
}
}
/**
* @notice Add `_token.symbol(): string` to the list of protected tokens
* @param _token Address of the token to be protected
*/
function addProtectedToken(address _token) external authP(ADD_PROTECTED_TOKEN_ROLE, arr(_token)) {
require(protectedTokens.length < PROTECTED_TOKENS_CAP, ERROR_TOKENS_CAP_REACHED);
require(_isERC20(_token), ERROR_TOKEN_NOT_ERC20);
require(!_tokenIsProtected(_token), ERROR_TOKEN_ALREADY_PROTECTED);
_addProtectedToken(_token);
}
/**
* @notice Remove `_token.symbol(): string` from the list of protected tokens
* @param _token Address of the token to be unprotected
*/
function removeProtectedToken(address _token) external authP(REMOVE_PROTECTED_TOKEN_ROLE, arr(_token)) {
require(_tokenIsProtected(_token), ERROR_TOKEN_NOT_PROTECTED);
_removeProtectedToken(_token);
}
/**
* @notice Pre-sign hash `_hash`
* @param _hash Hash that will be considered signed regardless of the signature checked with 'isValidSignature()'
*/
function presignHash(bytes32 _hash)
external
authP(ADD_PRESIGNED_HASH_ROLE, arr(_hash))
{
isPresigned[_hash] = true;
emit PresignHash(msg.sender, _hash);
}
/**
* @notice Set `_designatedSigner` as the designated signer of the app, which will be able to sign messages on behalf of the app
* @param _designatedSigner Address that will be able to sign messages on behalf of the app
*/
function setDesignatedSigner(address _designatedSigner)
external
authP(DESIGNATE_SIGNER_ROLE, arr(_designatedSigner))
{
// Prevent an infinite loop by setting the app itself as its designated signer.
// An undetectable loop can be created by setting a different contract as the
// designated signer which calls back into `isValidSignature`.
// Given that `isValidSignature` is always called with just 50k gas, the max
// damage of the loop is wasting 50k gas.
require(_designatedSigner != address(this), ERROR_DESIGNATED_TO_SELF);
address oldDesignatedSigner = designatedSigner;
designatedSigner = _designatedSigner;
emit SetDesignatedSigner(msg.sender, oldDesignatedSigner, _designatedSigner);
}
// Forwarding fns
/**
* @notice Tells whether the Agent app is a forwarder or not
* @dev IForwarder interface conformance
* @return Always true
*/
function isForwarder() external pure returns (bool) {
return true;
}
/**
* @notice Execute the script as the Agent app
* @dev IForwarder interface conformance. Forwards any token holder action.
* @param _evmScript Script being executed
*/
function forward(bytes _evmScript) public {
require(canForward(msg.sender, _evmScript), ERROR_CAN_NOT_FORWARD);
bytes memory input = ""; // no input
address[] memory blacklist = new address[](0); // no addr blacklist, can interact with anything
runScript(_evmScript, input, blacklist);
// We don't need to emit an event here as EVMScriptRunner will emit ScriptResult if successful
}
/**
* @notice Tells whether `_sender` can forward actions or not
* @dev IForwarder interface conformance
* @param _sender Address of the account intending to forward an action
* @return True if the given address can run scripts, false otherwise
*/
function canForward(address _sender, bytes _evmScript) public view returns (bool) {
// Note that `canPerform()` implicitly does an initialization check itself
return canPerform(_sender, RUN_SCRIPT_ROLE, arr(_getScriptACLParam(_evmScript)));
}
// ERC-165 conformance
/**
* @notice Tells whether this contract supports a given ERC-165 interface
* @param _interfaceId Interface bytes to check
* @return True if this contract supports the interface
*/
function supportsInterface(bytes4 _interfaceId) external pure returns (bool) {
return
_interfaceId == ERC1271_INTERFACE_ID ||
_interfaceId == ERC165_INTERFACE_ID;
}
// ERC-1271 conformance
/**
* @notice Tells whether a signature is seen as valid by this contract through ERC-1271
* @param _hash Arbitrary length data signed on the behalf of address (this)
* @param _signature Signature byte array associated with _data
* @return The ERC-1271 magic value if the signature is valid
*/
function isValidSignature(bytes32 _hash, bytes _signature) public view returns (bytes4) {
// Short-circuit in case the hash was presigned. Optimization as performing calls
// and ecrecover is more expensive than an SLOAD.
if (isPresigned[_hash]) {
return returnIsValidSignatureMagicNumber(true);
}
bool isValid;
if (designatedSigner == address(0)) {
isValid = false;
} else {
isValid = SignatureValidator.isValidSignature(_hash, designatedSigner, _signature);
}
return returnIsValidSignatureMagicNumber(isValid);
}
// Getters
function getProtectedTokensLength() public view isInitialized returns (uint256) {
return protectedTokens.length;
}
// Internal fns
function _addProtectedToken(address _token) internal {
protectedTokens.push(_token);
emit AddProtectedToken(_token);
}
function _removeProtectedToken(address _token) internal {
protectedTokens[_protectedTokenIndex(_token)] = protectedTokens[protectedTokens.length - 1];
protectedTokens.length--;
emit RemoveProtectedToken(_token);
}
function _isERC20(address _token) internal view returns (bool) {
if (!isContract(_token)) {
return false;
}
// Throwaway sanity check to make sure the token's `balanceOf()` does not error (for now)
balance(_token);
return true;
}
function _protectedTokenIndex(address _token) internal view returns (uint256) {
for (uint i = 0; i < protectedTokens.length; i++) {
if (protectedTokens[i] == _token) {
return i;
}
}
revert(ERROR_TOKEN_NOT_PROTECTED);
}
function _tokenIsProtected(address _token) internal view returns (bool) {
for (uint256 i = 0; i < protectedTokens.length; i++) {
if (protectedTokens[i] == _token) {
return true;
}
}
return false;
}
function _getScriptACLParam(bytes _evmScript) internal pure returns (uint256) {
return uint256(keccak256(abi.encodePacked(_evmScript)));
}
function _getSig(bytes _data) internal pure returns (bytes4 sig) {
if (_data.length < 4) {
return;
}
assembly { sig := mload(add(_data, 0x20)) }
}
}
// File: @aragon/os/contracts/lib/math/SafeMath.sol
// See https://github.com/OpenZeppelin/openzeppelin-solidity/blob/d51e38758e1d985661534534d5c61e27bece5042/contracts/math/SafeMath.sol
// Adapted to use pragma ^0.4.24 and satisfy our linter rules
pragma solidity ^0.4.24;
/**
* @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;
}
}
// File: @aragon/os/contracts/lib/math/SafeMath64.sol
// See https://github.com/OpenZeppelin/openzeppelin-solidity/blob/d51e38758e1d985661534534d5c61e27bece5042/contracts/math/SafeMath.sol
// Adapted for uint64, pragma ^0.4.24, and satisfying our linter rules
// Also optimized the mul() implementation, see https://github.com/aragon/aragonOS/pull/417
pragma solidity ^0.4.24;
/**
* @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;
}
}
// File: @aragon/apps-shared-minime/contracts/ITokenController.sol
pragma solidity ^0.4.24;
/// @dev The token controller contract must implement these functions
interface ITokenController {
/// @notice Called when `_owner` sends ether to the MiniMe Token contract
/// @param _owner The address that sent the ether to create tokens
/// @return True if the ether is accepted, false if it throws
function proxyPayment(address _owner) external payable returns(bool);
/// @notice Notifies the controller about a token transfer allowing the
/// controller to react if desired
/// @param _from The origin of the transfer
/// @param _to The destination of the transfer
/// @param _amount The amount of the transfer
/// @return False if the controller does not authorize the transfer
function onTransfer(address _from, address _to, uint _amount) external returns(bool);
/// @notice Notifies the controller about an approval allowing the
/// controller to react if desired
/// @param _owner The address that calls `approve()`
/// @param _spender The spender in the `approve()` call
/// @param _amount The amount in the `approve()` call
/// @return False if the controller does not authorize the approval
function onApprove(address _owner, address _spender, uint _amount) external returns(bool);
}
// File: @aragon/apps-shared-minime/contracts/MiniMeToken.sol
pragma solidity ^0.4.24;
/*
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 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) onlyController public {
controller = _newController;
}
}
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.1"; //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(
MiniMeTokenFactory _tokenFactory,
MiniMeToken _parentToken,
uint _parentSnapShotBlock,
string _tokenName,
uint8 _decimalUnits,
string _tokenSymbol,
bool _transfersEnabled
) public
{
tokenFactory = _tokenFactory;
name = _tokenName; // Set the name
decimals = _decimalUnits; // Set the decimals
symbol = _tokenSymbol; // Set the symbol
parentToken = _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;
}
// Alerts the token controller of the transfer
if (isContract(controller)) {
// Adding the ` == true` makes the linter shut up so...
require(ITokenController(controller).onTransfer(_from, _to, _amount) == true);
}
// 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));
// Alerts the token controller of the approve function call
if (isContract(controller)) {
// Adding the ` == true` makes the linter shut up so...
require(ITokenController(controller).onApprove(msg.sender, _spender, _amount) == true);
}
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(ApproveAndCallFallBack _spender, uint256 _amount, bytes _extraData) public returns (bool success) {
require(approve(_spender, _amount));
_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(MiniMeToken)
{
uint256 snapshot = _snapshotBlock == 0 ? block.number - 1 : _snapshotBlock;
MiniMeToken cloneToken = tokenFactory.createCloneToken(
this,
snapshot,
_cloneTokenName,
_cloneDecimalUnits,
_cloneTokenSymbol,
_transfersEnabled
);
cloneToken.changeController(msg.sender);
// An event to make the token easy to find on the blockchain
NewCloneToken(address(cloneToken), snapshot);
return 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) onlyController public 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) onlyController public {
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
function min(uint a, uint b) pure internal 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 () external payable {
require(isContract(controller));
// Adding the ` == true` makes the linter shut up so...
require(ITokenController(controller).proxyPayment.value(msg.value)(msg.sender) == true);
}
//////////
// 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) onlyController public {
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(
MiniMeToken _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;
}
}
// File: @aragon/apps-voting/contracts/Voting.sol
/*
* SPDX-License-Identitifer: GPL-3.0-or-later
*/
pragma solidity 0.4.24;
contract Voting is IForwarder, AragonApp {
using SafeMath for uint256;
using SafeMath64 for uint64;
bytes32 public constant CREATE_VOTES_ROLE = keccak256("CREATE_VOTES_ROLE");
bytes32 public constant MODIFY_SUPPORT_ROLE = keccak256("MODIFY_SUPPORT_ROLE");
bytes32 public constant MODIFY_QUORUM_ROLE = keccak256("MODIFY_QUORUM_ROLE");
uint64 public constant PCT_BASE = 10 ** 18; // 0% = 0; 1% = 10^16; 100% = 10^18
string private constant ERROR_NO_VOTE = "VOTING_NO_VOTE";
string private constant ERROR_INIT_PCTS = "VOTING_INIT_PCTS";
string private constant ERROR_CHANGE_SUPPORT_PCTS = "VOTING_CHANGE_SUPPORT_PCTS";
string private constant ERROR_CHANGE_QUORUM_PCTS = "VOTING_CHANGE_QUORUM_PCTS";
string private constant ERROR_INIT_SUPPORT_TOO_BIG = "VOTING_INIT_SUPPORT_TOO_BIG";
string private constant ERROR_CHANGE_SUPPORT_TOO_BIG = "VOTING_CHANGE_SUPP_TOO_BIG";
string private constant ERROR_CAN_NOT_VOTE = "VOTING_CAN_NOT_VOTE";
string private constant ERROR_CAN_NOT_EXECUTE = "VOTING_CAN_NOT_EXECUTE";
string private constant ERROR_CAN_NOT_FORWARD = "VOTING_CAN_NOT_FORWARD";
string private constant ERROR_NO_VOTING_POWER = "VOTING_NO_VOTING_POWER";
enum VoterState { Absent, Yea, Nay }
struct Vote {
bool executed;
uint64 startDate;
uint64 snapshotBlock;
uint64 supportRequiredPct;
uint64 minAcceptQuorumPct;
uint256 yea;
uint256 nay;
uint256 votingPower;
bytes executionScript;
mapping (address => VoterState) voters;
}
MiniMeToken public token;
uint64 public supportRequiredPct;
uint64 public minAcceptQuorumPct;
uint64 public voteTime;
// We are mimicing an array, we use a mapping instead to make app upgrade more graceful
mapping (uint256 => Vote) internal votes;
uint256 public votesLength;
event StartVote(uint256 indexed voteId, address indexed creator, string metadata);
event CastVote(uint256 indexed voteId, address indexed voter, bool supports, uint256 stake);
event ExecuteVote(uint256 indexed voteId);
event ChangeSupportRequired(uint64 supportRequiredPct);
event ChangeMinQuorum(uint64 minAcceptQuorumPct);
modifier voteExists(uint256 _voteId) {
require(_voteId < votesLength, ERROR_NO_VOTE);
_;
}
/**
* @notice Initialize Voting app with `_token.symbol(): string` for governance, minimum support of `@formatPct(_supportRequiredPct)`%, minimum acceptance quorum of `@formatPct(_minAcceptQuorumPct)`%, and a voting duration of `@transformTime(_voteTime)`
* @param _token MiniMeToken Address that will be used as governance token
* @param _supportRequiredPct Percentage of yeas in casted votes for a vote to succeed (expressed as a percentage of 10^18; eg. 10^16 = 1%, 10^18 = 100%)
* @param _minAcceptQuorumPct Percentage of yeas in total possible votes for a vote to succeed (expressed as a percentage of 10^18; eg. 10^16 = 1%, 10^18 = 100%)
* @param _voteTime Seconds that a vote will be open for token holders to vote (unless enough yeas or nays have been cast to make an early decision)
*/
function initialize(
MiniMeToken _token,
uint64 _supportRequiredPct,
uint64 _minAcceptQuorumPct,
uint64 _voteTime
)
external
onlyInit
{
initialized();
require(_minAcceptQuorumPct <= _supportRequiredPct, ERROR_INIT_PCTS);
require(_supportRequiredPct < PCT_BASE, ERROR_INIT_SUPPORT_TOO_BIG);
token = _token;
supportRequiredPct = _supportRequiredPct;
minAcceptQuorumPct = _minAcceptQuorumPct;
voteTime = _voteTime;
}
/**
* @notice Change required support to `@formatPct(_supportRequiredPct)`%
* @param _supportRequiredPct New required support
*/
function changeSupportRequiredPct(uint64 _supportRequiredPct)
external
authP(MODIFY_SUPPORT_ROLE, arr(uint256(_supportRequiredPct), uint256(supportRequiredPct)))
{
require(minAcceptQuorumPct <= _supportRequiredPct, ERROR_CHANGE_SUPPORT_PCTS);
require(_supportRequiredPct < PCT_BASE, ERROR_CHANGE_SUPPORT_TOO_BIG);
supportRequiredPct = _supportRequiredPct;
emit ChangeSupportRequired(_supportRequiredPct);
}
/**
* @notice Change minimum acceptance quorum to `@formatPct(_minAcceptQuorumPct)`%
* @param _minAcceptQuorumPct New acceptance quorum
*/
function changeMinAcceptQuorumPct(uint64 _minAcceptQuorumPct)
external
authP(MODIFY_QUORUM_ROLE, arr(uint256(_minAcceptQuorumPct), uint256(minAcceptQuorumPct)))
{
require(_minAcceptQuorumPct <= supportRequiredPct, ERROR_CHANGE_QUORUM_PCTS);
minAcceptQuorumPct = _minAcceptQuorumPct;
emit ChangeMinQuorum(_minAcceptQuorumPct);
}
/**
* @notice Create a new vote about "`_metadata`"
* @param _executionScript EVM script to be executed on approval
* @param _metadata Vote metadata
* @return voteId Id for newly created vote
*/
function newVote(bytes _executionScript, string _metadata) external auth(CREATE_VOTES_ROLE) returns (uint256 voteId) {
return _newVote(_executionScript, _metadata, true, true);
}
/**
* @notice Create a new vote about "`_metadata`"
* @param _executionScript EVM script to be executed on approval
* @param _metadata Vote metadata
* @param _castVote Whether to also cast newly created vote
* @param _executesIfDecided Whether to also immediately execute newly created vote if decided
* @return voteId id for newly created vote
*/
function newVote(bytes _executionScript, string _metadata, bool _castVote, bool _executesIfDecided)
external
auth(CREATE_VOTES_ROLE)
returns (uint256 voteId)
{
return _newVote(_executionScript, _metadata, _castVote, _executesIfDecided);
}
/**
* @notice Vote `_supports ? 'yes' : 'no'` in vote #`_voteId`
* @dev Initialization check is implicitly provided by `voteExists()` as new votes can only be
* created via `newVote(),` which requires initialization
* @param _voteId Id for vote
* @param _supports Whether voter supports the vote
* @param _executesIfDecided Whether the vote should execute its action if it becomes decided
*/
function vote(uint256 _voteId, bool _supports, bool _executesIfDecided) external voteExists(_voteId) {
require(_canVote(_voteId, msg.sender), ERROR_CAN_NOT_VOTE);
_vote(_voteId, _supports, msg.sender, _executesIfDecided);
}
/**
* @notice Execute vote #`_voteId`
* @dev Initialization check is implicitly provided by `voteExists()` as new votes can only be
* created via `newVote(),` which requires initialization
* @param _voteId Id for vote
*/
function executeVote(uint256 _voteId) external voteExists(_voteId) {
_executeVote(_voteId);
}
// Forwarding fns
function isForwarder() external pure returns (bool) {
return true;
}
/**
* @notice Creates a vote to execute the desired action, and casts a support vote if possible
* @dev IForwarder interface conformance
* @param _evmScript Start vote with script
*/
function forward(bytes _evmScript) public {
require(canForward(msg.sender, _evmScript), ERROR_CAN_NOT_FORWARD);
_newVote(_evmScript, "", true, true);
}
function canForward(address _sender, bytes) public view returns (bool) {
// Note that `canPerform()` implicitly does an initialization check itself
return canPerform(_sender, CREATE_VOTES_ROLE, arr());
}
// Getter fns
/**
* @dev Initialization check is implicitly provided by `voteExists()` as new votes can only be
* created via `newVote(),` which requires initialization
*/
function canExecute(uint256 _voteId) public view voteExists(_voteId) returns (bool) {
return _canExecute(_voteId);
}
/**
* @dev Initialization check is implicitly provided by `voteExists()` as new votes can only be
* created via `newVote(),` which requires initialization
*/
function canVote(uint256 _voteId, address _voter) public view voteExists(_voteId) returns (bool) {
return _canVote(_voteId, _voter);
}
function getVote(uint256 _voteId)
public
view
voteExists(_voteId)
returns (
bool open,
bool executed,
uint64 startDate,
uint64 snapshotBlock,
uint64 supportRequired,
uint64 minAcceptQuorum,
uint256 yea,
uint256 nay,
uint256 votingPower,
bytes script
)
{
Vote storage vote_ = votes[_voteId];
open = _isVoteOpen(vote_);
executed = vote_.executed;
startDate = vote_.startDate;
snapshotBlock = vote_.snapshotBlock;
supportRequired = vote_.supportRequiredPct;
minAcceptQuorum = vote_.minAcceptQuorumPct;
yea = vote_.yea;
nay = vote_.nay;
votingPower = vote_.votingPower;
script = vote_.executionScript;
}
function getVoterState(uint256 _voteId, address _voter) public view voteExists(_voteId) returns (VoterState) {
return votes[_voteId].voters[_voter];
}
// Internal fns
function _newVote(bytes _executionScript, string _metadata, bool _castVote, bool _executesIfDecided)
internal
returns (uint256 voteId)
{
uint64 snapshotBlock = getBlockNumber64() - 1; // avoid double voting in this very block
uint256 votingPower = token.totalSupplyAt(snapshotBlock);
require(votingPower > 0, ERROR_NO_VOTING_POWER);
voteId = votesLength++;
Vote storage vote_ = votes[voteId];
vote_.startDate = getTimestamp64();
vote_.snapshotBlock = snapshotBlock;
vote_.supportRequiredPct = supportRequiredPct;
vote_.minAcceptQuorumPct = minAcceptQuorumPct;
vote_.votingPower = votingPower;
vote_.executionScript = _executionScript;
emit StartVote(voteId, msg.sender, _metadata);
if (_castVote && _canVote(voteId, msg.sender)) {
_vote(voteId, true, msg.sender, _executesIfDecided);
}
}
function _vote(
uint256 _voteId,
bool _supports,
address _voter,
bool _executesIfDecided
) internal
{
Vote storage vote_ = votes[_voteId];
// This could re-enter, though we can assume the governance token is not malicious
uint256 voterStake = token.balanceOfAt(_voter, vote_.snapshotBlock);
VoterState state = vote_.voters[_voter];
// If voter had previously voted, decrease count
if (state == VoterState.Yea) {
vote_.yea = vote_.yea.sub(voterStake);
} else if (state == VoterState.Nay) {
vote_.nay = vote_.nay.sub(voterStake);
}
if (_supports) {
vote_.yea = vote_.yea.add(voterStake);
} else {
vote_.nay = vote_.nay.add(voterStake);
}
vote_.voters[_voter] = _supports ? VoterState.Yea : VoterState.Nay;
emit CastVote(_voteId, _voter, _supports, voterStake);
if (_executesIfDecided && _canExecute(_voteId)) {
// We've already checked if the vote can be executed with `_canExecute()`
_unsafeExecuteVote(_voteId);
}
}
function _executeVote(uint256 _voteId) internal {
require(_canExecute(_voteId), ERROR_CAN_NOT_EXECUTE);
_unsafeExecuteVote(_voteId);
}
/**
* @dev Unsafe version of _executeVote that assumes you have already checked if the vote can be executed
*/
function _unsafeExecuteVote(uint256 _voteId) internal {
Vote storage vote_ = votes[_voteId];
vote_.executed = true;
bytes memory input = new bytes(0); // TODO: Consider input for voting scripts
runScript(vote_.executionScript, input, new address[](0));
emit ExecuteVote(_voteId);
}
function _canExecute(uint256 _voteId) internal view returns (bool) {
Vote storage vote_ = votes[_voteId];
if (vote_.executed) {
return false;
}
// Voting is already decided
if (_isValuePct(vote_.yea, vote_.votingPower, vote_.supportRequiredPct)) {
return true;
}
// Vote ended?
if (_isVoteOpen(vote_)) {
return false;
}
// Has enough support?
uint256 totalVotes = vote_.yea.add(vote_.nay);
if (!_isValuePct(vote_.yea, totalVotes, vote_.supportRequiredPct)) {
return false;
}
// Has min quorum?
if (!_isValuePct(vote_.yea, vote_.votingPower, vote_.minAcceptQuorumPct)) {
return false;
}
return true;
}
function _canVote(uint256 _voteId, address _voter) internal view returns (bool) {
Vote storage vote_ = votes[_voteId];
return _isVoteOpen(vote_) && token.balanceOfAt(_voter, vote_.snapshotBlock) > 0;
}
function _isVoteOpen(Vote storage vote_) internal view returns (bool) {
return getTimestamp64() < vote_.startDate.add(voteTime) && !vote_.executed;
}
/**
* @dev Calculates whether `_value` is more than a percentage `_pct` of `_total`
*/
function _isValuePct(uint256 _value, uint256 _total, uint256 _pct) internal pure returns (bool) {
if (_total == 0) {
return false;
}
uint256 computedPct = _value.mul(PCT_BASE) / _total;
return computedPct > _pct;
}
}
// File: @aragon/ppf-contracts/contracts/IFeed.sol
pragma solidity ^0.4.18;
interface IFeed {
function ratePrecision() external pure returns (uint256);
function get(address base, address quote) external view returns (uint128 xrt, uint64 when);
}
// File: @aragon/apps-finance/contracts/Finance.sol
/*
* SPDX-License-Identitifer: GPL-3.0-or-later
*/
pragma solidity 0.4.24;
contract Finance is EtherTokenConstant, IsContract, AragonApp {
using SafeMath for uint256;
using SafeMath64 for uint64;
using SafeERC20 for ERC20;
bytes32 public constant CREATE_PAYMENTS_ROLE = keccak256("CREATE_PAYMENTS_ROLE");
bytes32 public constant CHANGE_PERIOD_ROLE = keccak256("CHANGE_PERIOD_ROLE");
bytes32 public constant CHANGE_BUDGETS_ROLE = keccak256("CHANGE_BUDGETS_ROLE");
bytes32 public constant EXECUTE_PAYMENTS_ROLE = keccak256("EXECUTE_PAYMENTS_ROLE");
bytes32 public constant MANAGE_PAYMENTS_ROLE = keccak256("MANAGE_PAYMENTS_ROLE");
uint256 internal constant NO_SCHEDULED_PAYMENT = 0;
uint256 internal constant NO_TRANSACTION = 0;
uint256 internal constant MAX_SCHEDULED_PAYMENTS_PER_TX = 20;
uint256 internal constant MAX_UINT256 = uint256(-1);
uint64 internal constant MAX_UINT64 = uint64(-1);
uint64 internal constant MINIMUM_PERIOD = uint64(1 days);
string private constant ERROR_COMPLETE_TRANSITION = "FINANCE_COMPLETE_TRANSITION";
string private constant ERROR_NO_SCHEDULED_PAYMENT = "FINANCE_NO_SCHEDULED_PAYMENT";
string private constant ERROR_NO_TRANSACTION = "FINANCE_NO_TRANSACTION";
string private constant ERROR_NO_PERIOD = "FINANCE_NO_PERIOD";
string private constant ERROR_VAULT_NOT_CONTRACT = "FINANCE_VAULT_NOT_CONTRACT";
string private constant ERROR_SET_PERIOD_TOO_SHORT = "FINANCE_SET_PERIOD_TOO_SHORT";
string private constant ERROR_NEW_PAYMENT_AMOUNT_ZERO = "FINANCE_NEW_PAYMENT_AMOUNT_ZERO";
string private constant ERROR_NEW_PAYMENT_INTERVAL_ZERO = "FINANCE_NEW_PAYMENT_INTRVL_ZERO";
string private constant ERROR_NEW_PAYMENT_EXECS_ZERO = "FINANCE_NEW_PAYMENT_EXECS_ZERO";
string private constant ERROR_NEW_PAYMENT_IMMEDIATE = "FINANCE_NEW_PAYMENT_IMMEDIATE";
string private constant ERROR_RECOVER_AMOUNT_ZERO = "FINANCE_RECOVER_AMOUNT_ZERO";
string private constant ERROR_DEPOSIT_AMOUNT_ZERO = "FINANCE_DEPOSIT_AMOUNT_ZERO";
string private constant ERROR_ETH_VALUE_MISMATCH = "FINANCE_ETH_VALUE_MISMATCH";
string private constant ERROR_BUDGET = "FINANCE_BUDGET";
string private constant ERROR_EXECUTE_PAYMENT_NUM = "FINANCE_EXECUTE_PAYMENT_NUM";
string private constant ERROR_EXECUTE_PAYMENT_TIME = "FINANCE_EXECUTE_PAYMENT_TIME";
string private constant ERROR_PAYMENT_RECEIVER = "FINANCE_PAYMENT_RECEIVER";
string private constant ERROR_TOKEN_TRANSFER_FROM_REVERTED = "FINANCE_TKN_TRANSFER_FROM_REVERT";
string private constant ERROR_TOKEN_APPROVE_FAILED = "FINANCE_TKN_APPROVE_FAILED";
string private constant ERROR_PAYMENT_INACTIVE = "FINANCE_PAYMENT_INACTIVE";
string private constant ERROR_REMAINING_BUDGET = "FINANCE_REMAINING_BUDGET";
// Order optimized for storage
struct ScheduledPayment {
address token;
address receiver;
address createdBy;
bool inactive;
uint256 amount;
uint64 initialPaymentTime;
uint64 interval;
uint64 maxExecutions;
uint64 executions;
}
// Order optimized for storage
struct Transaction {
address token;
address entity;
bool isIncoming;
uint256 amount;
uint256 paymentId;
uint64 paymentExecutionNumber;
uint64 date;
uint64 periodId;
}
struct TokenStatement {
uint256 expenses;
uint256 income;
}
struct Period {
uint64 startTime;
uint64 endTime;
uint256 firstTransactionId;
uint256 lastTransactionId;
mapping (address => TokenStatement) tokenStatement;
}
struct Settings {
uint64 periodDuration;
mapping (address => uint256) budgets;
mapping (address => bool) hasBudget;
}
Vault public vault;
Settings internal settings;
// We are mimicing arrays, we use mappings instead to make app upgrade more graceful
mapping (uint256 => ScheduledPayment) internal scheduledPayments;
// Payments start at index 1, to allow us to use scheduledPayments[0] for transactions that are not
// linked to a scheduled payment
uint256 public paymentsNextIndex;
mapping (uint256 => Transaction) internal transactions;
uint256 public transactionsNextIndex;
mapping (uint64 => Period) internal periods;
uint64 public periodsLength;
event NewPeriod(uint64 indexed periodId, uint64 periodStarts, uint64 periodEnds);
event SetBudget(address indexed token, uint256 amount, bool hasBudget);
event NewPayment(uint256 indexed paymentId, address indexed recipient, uint64 maxExecutions, string reference);
event NewTransaction(uint256 indexed transactionId, bool incoming, address indexed entity, uint256 amount, string reference);
event ChangePaymentState(uint256 indexed paymentId, bool active);
event ChangePeriodDuration(uint64 newDuration);
event PaymentFailure(uint256 paymentId);
// Modifier used by all methods that impact accounting to make sure accounting period
// is changed before the operation if needed
// NOTE: its use **MUST** be accompanied by an initialization check
modifier transitionsPeriod {
bool completeTransition = _tryTransitionAccountingPeriod(getMaxPeriodTransitions());
require(completeTransition, ERROR_COMPLETE_TRANSITION);
_;
}
modifier scheduledPaymentExists(uint256 _paymentId) {
require(_paymentId > 0 && _paymentId < paymentsNextIndex, ERROR_NO_SCHEDULED_PAYMENT);
_;
}
modifier transactionExists(uint256 _transactionId) {
require(_transactionId > 0 && _transactionId < transactionsNextIndex, ERROR_NO_TRANSACTION);
_;
}
modifier periodExists(uint64 _periodId) {
require(_periodId < periodsLength, ERROR_NO_PERIOD);
_;
}
/**
* @notice Deposit ETH to the Vault, to avoid locking them in this Finance app forever
* @dev Send ETH to Vault. Send all the available balance.
*/
function () external payable isInitialized transitionsPeriod {
require(msg.value > 0, ERROR_DEPOSIT_AMOUNT_ZERO);
_deposit(
ETH,
msg.value,
"Ether transfer to Finance app",
msg.sender,
true
);
}
/**
* @notice Initialize Finance app for Vault at `_vault` with period length of `@transformTime(_periodDuration)`
* @param _vault Address of the vault Finance will rely on (non changeable)
* @param _periodDuration Duration in seconds of each period
*/
function initialize(Vault _vault, uint64 _periodDuration) external onlyInit {
initialized();
require(isContract(_vault), ERROR_VAULT_NOT_CONTRACT);
vault = _vault;
require(_periodDuration >= MINIMUM_PERIOD, ERROR_SET_PERIOD_TOO_SHORT);
settings.periodDuration = _periodDuration;
// Reserve the first scheduled payment index as an unused index for transactions not linked
// to a scheduled payment
scheduledPayments[0].inactive = true;
paymentsNextIndex = 1;
// Reserve the first transaction index as an unused index for periods with no transactions
transactionsNextIndex = 1;
// Start the first period
_newPeriod(getTimestamp64());
}
/**
* @notice Deposit `@tokenAmount(_token, _amount)`
* @dev Deposit for approved ERC20 tokens or ETH
* @param _token Address of deposited token
* @param _amount Amount of tokens sent
* @param _reference Reason for payment
*/
function deposit(address _token, uint256 _amount, string _reference) external payable isInitialized transitionsPeriod {
require(_amount > 0, ERROR_DEPOSIT_AMOUNT_ZERO);
if (_token == ETH) {
// Ensure that the ETH sent with the transaction equals the amount in the deposit
require(msg.value == _amount, ERROR_ETH_VALUE_MISMATCH);
}
_deposit(
_token,
_amount,
_reference,
msg.sender,
true
);
}
/**
* @notice Create a new payment of `@tokenAmount(_token, _amount)` to `_receiver` for '`_reference`'
* @dev Note that this function is protected by the `CREATE_PAYMENTS_ROLE` but uses `MAX_UINT256`
* as its interval auth parameter (as a sentinel value for "never repeating").
* While this protects against most cases (you typically want to set a baseline requirement
* for interval time), it does mean users will have to explicitly check for this case when
* granting a permission that includes a upperbound requirement on the interval time.
* @param _token Address of token for payment
* @param _receiver Address that will receive payment
* @param _amount Tokens that are paid every time the payment is due
* @param _reference String detailing payment reason
*/
function newImmediatePayment(address _token, address _receiver, uint256 _amount, string _reference)
external
// Use MAX_UINT256 as the interval parameter, as this payment will never repeat
// Payment time parameter is left as the last param as it was added later
authP(CREATE_PAYMENTS_ROLE, _arr(_token, _receiver, _amount, MAX_UINT256, uint256(1), getTimestamp()))
transitionsPeriod
{
require(_amount > 0, ERROR_NEW_PAYMENT_AMOUNT_ZERO);
_makePaymentTransaction(
_token,
_receiver,
_amount,
NO_SCHEDULED_PAYMENT, // unrelated to any payment id; it isn't created
0, // also unrelated to any payment executions
_reference
);
}
/**
* @notice Create a new payment of `@tokenAmount(_token, _amount)` to `_receiver` for `_reference`, executing `_maxExecutions` times at intervals of `@transformTime(_interval)`
* @dev See `newImmediatePayment()` for limitations on how the interval auth parameter can be used
* @param _token Address of token for payment
* @param _receiver Address that will receive payment
* @param _amount Tokens that are paid every time the payment is due
* @param _initialPaymentTime Timestamp for when the first payment is done
* @param _interval Number of seconds that need to pass between payment transactions
* @param _maxExecutions Maximum instances a payment can be executed
* @param _reference String detailing payment reason
*/
function newScheduledPayment(
address _token,
address _receiver,
uint256 _amount,
uint64 _initialPaymentTime,
uint64 _interval,
uint64 _maxExecutions,
string _reference
)
external
// Payment time parameter is left as the last param as it was added later
authP(CREATE_PAYMENTS_ROLE, _arr(_token, _receiver, _amount, uint256(_interval), uint256(_maxExecutions), uint256(_initialPaymentTime)))
transitionsPeriod
returns (uint256 paymentId)
{
require(_amount > 0, ERROR_NEW_PAYMENT_AMOUNT_ZERO);
require(_interval > 0, ERROR_NEW_PAYMENT_INTERVAL_ZERO);
require(_maxExecutions > 0, ERROR_NEW_PAYMENT_EXECS_ZERO);
// Token budget must not be set at all or allow at least one instance of this payment each period
require(!settings.hasBudget[_token] || settings.budgets[_token] >= _amount, ERROR_BUDGET);
// Don't allow creating single payments that are immediately executable, use `newImmediatePayment()` instead
if (_maxExecutions == 1) {
require(_initialPaymentTime > getTimestamp64(), ERROR_NEW_PAYMENT_IMMEDIATE);
}
paymentId = paymentsNextIndex++;
emit NewPayment(paymentId, _receiver, _maxExecutions, _reference);
ScheduledPayment storage payment = scheduledPayments[paymentId];
payment.token = _token;
payment.receiver = _receiver;
payment.amount = _amount;
payment.initialPaymentTime = _initialPaymentTime;
payment.interval = _interval;
payment.maxExecutions = _maxExecutions;
payment.createdBy = msg.sender;
// We skip checking how many times the new payment was executed to allow creating new
// scheduled payments before having enough vault balance
_executePayment(paymentId);
}
/**
* @notice Change period duration to `@transformTime(_periodDuration)`, effective for next accounting period
* @param _periodDuration Duration in seconds for accounting periods
*/
function setPeriodDuration(uint64 _periodDuration)
external
authP(CHANGE_PERIOD_ROLE, arr(uint256(_periodDuration), uint256(settings.periodDuration)))
transitionsPeriod
{
require(_periodDuration >= MINIMUM_PERIOD, ERROR_SET_PERIOD_TOO_SHORT);
settings.periodDuration = _periodDuration;
emit ChangePeriodDuration(_periodDuration);
}
/**
* @notice Set budget for `_token.symbol(): string` to `@tokenAmount(_token, _amount, false)`, effective immediately
* @param _token Address for token
* @param _amount New budget amount
*/
function setBudget(
address _token,
uint256 _amount
)
external
authP(CHANGE_BUDGETS_ROLE, arr(_token, _amount, settings.budgets[_token], uint256(settings.hasBudget[_token] ? 1 : 0)))
transitionsPeriod
{
settings.budgets[_token] = _amount;
if (!settings.hasBudget[_token]) {
settings.hasBudget[_token] = true;
}
emit SetBudget(_token, _amount, true);
}
/**
* @notice Remove spending limit for `_token.symbol(): string`, effective immediately
* @param _token Address for token
*/
function removeBudget(address _token)
external
authP(CHANGE_BUDGETS_ROLE, arr(_token, uint256(0), settings.budgets[_token], uint256(settings.hasBudget[_token] ? 1 : 0)))
transitionsPeriod
{
settings.budgets[_token] = 0;
settings.hasBudget[_token] = false;
emit SetBudget(_token, 0, false);
}
/**
* @notice Execute pending payment #`_paymentId`
* @dev Executes any payment (requires role)
* @param _paymentId Identifier for payment
*/
function executePayment(uint256 _paymentId)
external
authP(EXECUTE_PAYMENTS_ROLE, arr(_paymentId, scheduledPayments[_paymentId].amount))
scheduledPaymentExists(_paymentId)
transitionsPeriod
{
_executePaymentAtLeastOnce(_paymentId);
}
/**
* @notice Execute pending payment #`_paymentId`
* @dev Always allow receiver of a payment to trigger execution
* Initialization check is implicitly provided by `scheduledPaymentExists()` as new
* scheduled payments can only be created via `newScheduledPayment(),` which requires initialization
* @param _paymentId Identifier for payment
*/
function receiverExecutePayment(uint256 _paymentId) external scheduledPaymentExists(_paymentId) transitionsPeriod {
require(scheduledPayments[_paymentId].receiver == msg.sender, ERROR_PAYMENT_RECEIVER);
_executePaymentAtLeastOnce(_paymentId);
}
/**
* @notice `_active ? 'Activate' : 'Disable'` payment #`_paymentId`
* @dev Note that we do not require this action to transition periods, as it doesn't directly
* impact any accounting periods.
* Not having to transition periods also makes disabling payments easier to prevent funds
* from being pulled out in the event of a breach.
* @param _paymentId Identifier for payment
* @param _active Whether it will be active or inactive
*/
function setPaymentStatus(uint256 _paymentId, bool _active)
external
authP(MANAGE_PAYMENTS_ROLE, arr(_paymentId, uint256(_active ? 1 : 0)))
scheduledPaymentExists(_paymentId)
{
scheduledPayments[_paymentId].inactive = !_active;
emit ChangePaymentState(_paymentId, _active);
}
/**
* @notice Send tokens held in this contract to the Vault
* @dev Allows making a simple payment from this contract to the Vault, to avoid locked tokens.
* This contract should never receive tokens with a simple transfer call, but in case it
* happens, this function allows for their recovery.
* @param _token Token whose balance is going to be transferred.
*/
function recoverToVault(address _token) external isInitialized transitionsPeriod {
uint256 amount = _token == ETH ? address(this).balance : ERC20(_token).staticBalanceOf(address(this));
require(amount > 0, ERROR_RECOVER_AMOUNT_ZERO);
_deposit(
_token,
amount,
"Recover to Vault",
address(this),
false
);
}
/**
* @notice Transition accounting period if needed
* @dev Transitions accounting periods if needed. For preventing OOG attacks, a maxTransitions
* param is provided. If more than the specified number of periods need to be transitioned,
* it will return false.
* @param _maxTransitions Maximum periods that can be transitioned
* @return success Boolean indicating whether the accounting period is the correct one (if false,
* maxTransitions was surpased and another call is needed)
*/
function tryTransitionAccountingPeriod(uint64 _maxTransitions) external isInitialized returns (bool success) {
return _tryTransitionAccountingPeriod(_maxTransitions);
}
// Getter fns
/**
* @dev Disable recovery escape hatch if the app has been initialized, as it could be used
* maliciously to transfer funds in the Finance app to another Vault
* finance#recoverToVault() should be used to recover funds to the Finance's vault
*/
function allowRecoverability(address) public view returns (bool) {
return !hasInitialized();
}
function getPayment(uint256 _paymentId)
public
view
scheduledPaymentExists(_paymentId)
returns (
address token,
address receiver,
uint256 amount,
uint64 initialPaymentTime,
uint64 interval,
uint64 maxExecutions,
bool inactive,
uint64 executions,
address createdBy
)
{
ScheduledPayment storage payment = scheduledPayments[_paymentId];
token = payment.token;
receiver = payment.receiver;
amount = payment.amount;
initialPaymentTime = payment.initialPaymentTime;
interval = payment.interval;
maxExecutions = payment.maxExecutions;
executions = payment.executions;
inactive = payment.inactive;
createdBy = payment.createdBy;
}
function getTransaction(uint256 _transactionId)
public
view
transactionExists(_transactionId)
returns (
uint64 periodId,
uint256 amount,
uint256 paymentId,
uint64 paymentExecutionNumber,
address token,
address entity,
bool isIncoming,
uint64 date
)
{
Transaction storage transaction = transactions[_transactionId];
token = transaction.token;
entity = transaction.entity;
isIncoming = transaction.isIncoming;
date = transaction.date;
periodId = transaction.periodId;
amount = transaction.amount;
paymentId = transaction.paymentId;
paymentExecutionNumber = transaction.paymentExecutionNumber;
}
function getPeriod(uint64 _periodId)
public
view
periodExists(_periodId)
returns (
bool isCurrent,
uint64 startTime,
uint64 endTime,
uint256 firstTransactionId,
uint256 lastTransactionId
)
{
Period storage period = periods[_periodId];
isCurrent = _currentPeriodId() == _periodId;
startTime = period.startTime;
endTime = period.endTime;
firstTransactionId = period.firstTransactionId;
lastTransactionId = period.lastTransactionId;
}
function getPeriodTokenStatement(uint64 _periodId, address _token)
public
view
periodExists(_periodId)
returns (uint256 expenses, uint256 income)
{
TokenStatement storage tokenStatement = periods[_periodId].tokenStatement[_token];
expenses = tokenStatement.expenses;
income = tokenStatement.income;
}
/**
* @dev We have to check for initialization as periods are only valid after initializing
*/
function currentPeriodId() public view isInitialized returns (uint64) {
return _currentPeriodId();
}
/**
* @dev We have to check for initialization as periods are only valid after initializing
*/
function getPeriodDuration() public view isInitialized returns (uint64) {
return settings.periodDuration;
}
/**
* @dev We have to check for initialization as budgets are only valid after initializing
*/
function getBudget(address _token) public view isInitialized returns (uint256 budget, bool hasBudget) {
budget = settings.budgets[_token];
hasBudget = settings.hasBudget[_token];
}
/**
* @dev We have to check for initialization as budgets are only valid after initializing
*/
function getRemainingBudget(address _token) public view isInitialized returns (uint256) {
return _getRemainingBudget(_token);
}
/**
* @dev We have to check for initialization as budgets are only valid after initializing
*/
function canMakePayment(address _token, uint256 _amount) public view isInitialized returns (bool) {
return _canMakePayment(_token, _amount);
}
/**
* @dev Initialization check is implicitly provided by `scheduledPaymentExists()` as new
* scheduled payments can only be created via `newScheduledPayment(),` which requires initialization
*/
function nextPaymentTime(uint256 _paymentId) public view scheduledPaymentExists(_paymentId) returns (uint64) {
return _nextPaymentTime(_paymentId);
}
// Internal fns
function _deposit(address _token, uint256 _amount, string _reference, address _sender, bool _isExternalDeposit) internal {
_recordIncomingTransaction(
_token,
_sender,
_amount,
_reference
);
if (_token == ETH) {
vault.deposit.value(_amount)(ETH, _amount);
} else {
// First, transfer the tokens to Finance if necessary
// External deposit will be false when the assets were already in the Finance app
// and just need to be transferred to the Vault
if (_isExternalDeposit) {
// This assumes the sender has approved the tokens for Finance
require(
ERC20(_token).safeTransferFrom(msg.sender, address(this), _amount),
ERROR_TOKEN_TRANSFER_FROM_REVERTED
);
}
// Approve the tokens for the Vault (it does the actual transferring)
require(ERC20(_token).safeApprove(vault, _amount), ERROR_TOKEN_APPROVE_FAILED);
// Finally, initiate the deposit
vault.deposit(_token, _amount);
}
}
function _executePayment(uint256 _paymentId) internal returns (uint256) {
ScheduledPayment storage payment = scheduledPayments[_paymentId];
require(!payment.inactive, ERROR_PAYMENT_INACTIVE);
uint64 paid = 0;
while (_nextPaymentTime(_paymentId) <= getTimestamp64() && paid < MAX_SCHEDULED_PAYMENTS_PER_TX) {
if (!_canMakePayment(payment.token, payment.amount)) {
emit PaymentFailure(_paymentId);
break;
}
// The while() predicate prevents these two from ever overflowing
payment.executions += 1;
paid += 1;
// We've already checked the remaining budget with `_canMakePayment()`
_unsafeMakePaymentTransaction(
payment.token,
payment.receiver,
payment.amount,
_paymentId,
payment.executions,
""
);
}
return paid;
}
function _executePaymentAtLeastOnce(uint256 _paymentId) internal {
uint256 paid = _executePayment(_paymentId);
if (paid == 0) {
if (_nextPaymentTime(_paymentId) <= getTimestamp64()) {
revert(ERROR_EXECUTE_PAYMENT_NUM);
} else {
revert(ERROR_EXECUTE_PAYMENT_TIME);
}
}
}
function _makePaymentTransaction(
address _token,
address _receiver,
uint256 _amount,
uint256 _paymentId,
uint64 _paymentExecutionNumber,
string _reference
)
internal
{
require(_getRemainingBudget(_token) >= _amount, ERROR_REMAINING_BUDGET);
_unsafeMakePaymentTransaction(_token, _receiver, _amount, _paymentId, _paymentExecutionNumber, _reference);
}
/**
* @dev Unsafe version of _makePaymentTransaction that assumes you have already checked the
* remaining budget
*/
function _unsafeMakePaymentTransaction(
address _token,
address _receiver,
uint256 _amount,
uint256 _paymentId,
uint64 _paymentExecutionNumber,
string _reference
)
internal
{
_recordTransaction(
false,
_token,
_receiver,
_amount,
_paymentId,
_paymentExecutionNumber,
_reference
);
vault.transfer(_token, _receiver, _amount);
}
function _newPeriod(uint64 _startTime) internal returns (Period storage) {
// There should be no way for this to overflow since each period is at least one day
uint64 newPeriodId = periodsLength++;
Period storage period = periods[newPeriodId];
period.startTime = _startTime;
// Be careful here to not overflow; if startTime + periodDuration overflows, we set endTime
// to MAX_UINT64 (let's assume that's the end of time for now).
uint64 endTime = _startTime + settings.periodDuration - 1;
if (endTime < _startTime) { // overflowed
endTime = MAX_UINT64;
}
period.endTime = endTime;
emit NewPeriod(newPeriodId, period.startTime, period.endTime);
return period;
}
function _recordIncomingTransaction(
address _token,
address _sender,
uint256 _amount,
string _reference
)
internal
{
_recordTransaction(
true, // incoming transaction
_token,
_sender,
_amount,
NO_SCHEDULED_PAYMENT, // unrelated to any existing payment
0, // and no payment executions
_reference
);
}
function _recordTransaction(
bool _incoming,
address _token,
address _entity,
uint256 _amount,
uint256 _paymentId,
uint64 _paymentExecutionNumber,
string _reference
)
internal
{
uint64 periodId = _currentPeriodId();
TokenStatement storage tokenStatement = periods[periodId].tokenStatement[_token];
if (_incoming) {
tokenStatement.income = tokenStatement.income.add(_amount);
} else {
tokenStatement.expenses = tokenStatement.expenses.add(_amount);
}
uint256 transactionId = transactionsNextIndex++;
Transaction storage transaction = transactions[transactionId];
transaction.token = _token;
transaction.entity = _entity;
transaction.isIncoming = _incoming;
transaction.amount = _amount;
transaction.paymentId = _paymentId;
transaction.paymentExecutionNumber = _paymentExecutionNumber;
transaction.date = getTimestamp64();
transaction.periodId = periodId;
Period storage period = periods[periodId];
if (period.firstTransactionId == NO_TRANSACTION) {
period.firstTransactionId = transactionId;
}
emit NewTransaction(transactionId, _incoming, _entity, _amount, _reference);
}
function _tryTransitionAccountingPeriod(uint64 _maxTransitions) internal returns (bool success) {
Period storage currentPeriod = periods[_currentPeriodId()];
uint64 timestamp = getTimestamp64();
// Transition periods if necessary
while (timestamp > currentPeriod.endTime) {
if (_maxTransitions == 0) {
// Required number of transitions is over allowed number, return false indicating
// it didn't fully transition
return false;
}
// We're already protected from underflowing above
_maxTransitions -= 1;
// If there were any transactions in period, record which was the last
// In case 0 transactions occured, first and last tx id will be 0
if (currentPeriod.firstTransactionId != NO_TRANSACTION) {
currentPeriod.lastTransactionId = transactionsNextIndex.sub(1);
}
// New period starts at end time + 1
currentPeriod = _newPeriod(currentPeriod.endTime.add(1));
}
return true;
}
function _canMakePayment(address _token, uint256 _amount) internal view returns (bool) {
return _getRemainingBudget(_token) >= _amount && vault.balance(_token) >= _amount;
}
function _currentPeriodId() internal view returns (uint64) {
// There is no way for this to overflow if protected by an initialization check
return periodsLength - 1;
}
function _getRemainingBudget(address _token) internal view returns (uint256) {
if (!settings.hasBudget[_token]) {
return MAX_UINT256;
}
uint256 budget = settings.budgets[_token];
uint256 spent = periods[_currentPeriodId()].tokenStatement[_token].expenses;
// A budget decrease can cause the spent amount to be greater than period budget
// If so, return 0 to not allow more spending during period
if (spent >= budget) {
return 0;
}
// We're already protected from the overflow above
return budget - spent;
}
function _nextPaymentTime(uint256 _paymentId) internal view returns (uint64) {
ScheduledPayment storage payment = scheduledPayments[_paymentId];
if (payment.executions >= payment.maxExecutions) {
return MAX_UINT64; // re-executes in some billions of years time... should not need to worry
}
// Split in multiple lines to circumvent linter warning
uint64 increase = payment.executions.mul(payment.interval);
uint64 nextPayment = payment.initialPaymentTime.add(increase);
return nextPayment;
}
// Syntax sugar
function _arr(address _a, address _b, uint256 _c, uint256 _d, uint256 _e, uint256 _f) internal pure returns (uint256[] r) {
r = new uint256[](6);
r[0] = uint256(_a);
r[1] = uint256(_b);
r[2] = _c;
r[3] = _d;
r[4] = _e;
r[5] = _f;
}
// Mocked fns (overrided during testing)
// Must be view for mocking purposes
function getMaxPeriodTransitions() internal view returns (uint64) { return MAX_UINT64; }
}
// File: @aragon/apps-payroll/contracts/Payroll.sol
pragma solidity 0.4.24;
/**
* @title Payroll in multiple currencies
*/
contract Payroll is EtherTokenConstant, IForwarder, IsContract, AragonApp {
using SafeMath for uint256;
using SafeMath64 for uint64;
/* Hardcoded constants to save gas
* bytes32 constant public ADD_EMPLOYEE_ROLE = keccak256("ADD_EMPLOYEE_ROLE");
* bytes32 constant public TERMINATE_EMPLOYEE_ROLE = keccak256("TERMINATE_EMPLOYEE_ROLE");
* bytes32 constant public SET_EMPLOYEE_SALARY_ROLE = keccak256("SET_EMPLOYEE_SALARY_ROLE");
* bytes32 constant public ADD_BONUS_ROLE = keccak256("ADD_BONUS_ROLE");
* bytes32 constant public ADD_REIMBURSEMENT_ROLE = keccak256("ADD_REIMBURSEMENT_ROLE");
* bytes32 constant public MANAGE_ALLOWED_TOKENS_ROLE = keccak256("MANAGE_ALLOWED_TOKENS_ROLE");
* bytes32 constant public MODIFY_PRICE_FEED_ROLE = keccak256("MODIFY_PRICE_FEED_ROLE");
* bytes32 constant public MODIFY_RATE_EXPIRY_ROLE = keccak256("MODIFY_RATE_EXPIRY_ROLE");
*/
bytes32 constant public ADD_EMPLOYEE_ROLE = 0x9ecdc3c63716b45d0756eece5fe1614cae1889ec5a1ce62b3127c1f1f1615d6e;
bytes32 constant public TERMINATE_EMPLOYEE_ROLE = 0x69c67f914d12b6440e7ddf01961214818d9158fbcb19211e0ff42800fdea9242;
bytes32 constant public SET_EMPLOYEE_SALARY_ROLE = 0xea9ac65018da2421cf419ee2152371440c08267a193a33ccc1e39545d197e44d;
bytes32 constant public ADD_BONUS_ROLE = 0xceca7e2f5eb749a87aaf68f3f76d6b9251aa2f4600f13f93c5a4adf7a72df4ae;
bytes32 constant public ADD_REIMBURSEMENT_ROLE = 0x90698b9d54427f1e41636025017309bdb1b55320da960c8845bab0a504b01a16;
bytes32 constant public MANAGE_ALLOWED_TOKENS_ROLE = 0x0be34987c45700ee3fae8c55e270418ba903337decc6bacb1879504be9331c06;
bytes32 constant public MODIFY_PRICE_FEED_ROLE = 0x74350efbcba8b85341c5bbf70cc34e2a585fc1463524773a12fa0a71d4eb9302;
bytes32 constant public MODIFY_RATE_EXPIRY_ROLE = 0x79fe989a8899060dfbdabb174ebb96616fa9f1d9dadd739f8d814cbab452404e;
uint256 internal constant MAX_ALLOWED_TOKENS = 20; // prevent OOG issues with `payday()`
uint64 internal constant MIN_RATE_EXPIRY = uint64(1 minutes); // 1 min == ~4 block window to mine both a price feed update and a payout
uint256 internal constant MAX_UINT256 = uint256(-1);
uint64 internal constant MAX_UINT64 = uint64(-1);
string private constant ERROR_EMPLOYEE_DOESNT_EXIST = "PAYROLL_EMPLOYEE_DOESNT_EXIST";
string private constant ERROR_NON_ACTIVE_EMPLOYEE = "PAYROLL_NON_ACTIVE_EMPLOYEE";
string private constant ERROR_SENDER_DOES_NOT_MATCH = "PAYROLL_SENDER_DOES_NOT_MATCH";
string private constant ERROR_FINANCE_NOT_CONTRACT = "PAYROLL_FINANCE_NOT_CONTRACT";
string private constant ERROR_TOKEN_ALREADY_SET = "PAYROLL_TOKEN_ALREADY_SET";
string private constant ERROR_MAX_ALLOWED_TOKENS = "PAYROLL_MAX_ALLOWED_TOKENS";
string private constant ERROR_MIN_RATES_MISMATCH = "PAYROLL_MIN_RATES_MISMATCH";
string private constant ERROR_TOKEN_ALLOCATION_MISMATCH = "PAYROLL_TOKEN_ALLOCATION_MISMATCH";
string private constant ERROR_NOT_ALLOWED_TOKEN = "PAYROLL_NOT_ALLOWED_TOKEN";
string private constant ERROR_DISTRIBUTION_NOT_FULL = "PAYROLL_DISTRIBUTION_NOT_FULL";
string private constant ERROR_INVALID_PAYMENT_TYPE = "PAYROLL_INVALID_PAYMENT_TYPE";
string private constant ERROR_NOTHING_PAID = "PAYROLL_NOTHING_PAID";
string private constant ERROR_CAN_NOT_FORWARD = "PAYROLL_CAN_NOT_FORWARD";
string private constant ERROR_EMPLOYEE_NULL_ADDRESS = "PAYROLL_EMPLOYEE_NULL_ADDRESS";
string private constant ERROR_EMPLOYEE_ALREADY_EXIST = "PAYROLL_EMPLOYEE_ALREADY_EXIST";
string private constant ERROR_FEED_NOT_CONTRACT = "PAYROLL_FEED_NOT_CONTRACT";
string private constant ERROR_EXPIRY_TIME_TOO_SHORT = "PAYROLL_EXPIRY_TIME_TOO_SHORT";
string private constant ERROR_PAST_TERMINATION_DATE = "PAYROLL_PAST_TERMINATION_DATE";
string private constant ERROR_EXCHANGE_RATE_TOO_LOW = "PAYROLL_EXCHANGE_RATE_TOO_LOW";
string private constant ERROR_LAST_PAYROLL_DATE_TOO_BIG = "PAYROLL_LAST_DATE_TOO_BIG";
string private constant ERROR_INVALID_REQUESTED_AMOUNT = "PAYROLL_INVALID_REQUESTED_AMT";
enum PaymentType { Payroll, Reimbursement, Bonus }
struct Employee {
address accountAddress; // unique, but can be changed over time
uint256 denominationTokenSalary; // salary per second in denomination Token
uint256 accruedSalary; // keep track of any leftover accrued salary when changing salaries
uint256 bonus;
uint256 reimbursements;
uint64 lastPayroll;
uint64 endDate;
address[] allocationTokenAddresses;
mapping(address => uint256) allocationTokens;
}
Finance public finance;
address public denominationToken;
IFeed public feed;
uint64 public rateExpiryTime;
// Employees start at index 1, to allow us to use employees[0] to check for non-existent employees
uint256 public nextEmployee;
mapping(uint256 => Employee) internal employees; // employee ID -> employee
mapping(address => uint256) internal employeeIds; // employee address -> employee ID
mapping(address => bool) internal allowedTokens;
event AddEmployee(
uint256 indexed employeeId,
address indexed accountAddress,
uint256 initialDenominationSalary,
uint64 startDate,
string role
);
event TerminateEmployee(uint256 indexed employeeId, uint64 endDate);
event SetEmployeeSalary(uint256 indexed employeeId, uint256 denominationSalary);
event AddEmployeeAccruedSalary(uint256 indexed employeeId, uint256 amount);
event AddEmployeeBonus(uint256 indexed employeeId, uint256 amount);
event AddEmployeeReimbursement(uint256 indexed employeeId, uint256 amount);
event ChangeAddressByEmployee(uint256 indexed employeeId, address indexed newAccountAddress, address indexed oldAccountAddress);
event DetermineAllocation(uint256 indexed employeeId);
event SendPayment(
uint256 indexed employeeId,
address indexed accountAddress,
address indexed token,
uint256 amount,
uint256 exchangeRate,
string paymentReference
);
event SetAllowedToken(address indexed token, bool allowed);
event SetPriceFeed(address indexed feed);
event SetRateExpiryTime(uint64 time);
// Check employee exists by ID
modifier employeeIdExists(uint256 _employeeId) {
require(_employeeExists(_employeeId), ERROR_EMPLOYEE_DOESNT_EXIST);
_;
}
// Check employee exists and is still active
modifier employeeActive(uint256 _employeeId) {
// No need to check for existence as _isEmployeeIdActive() is false for non-existent employees
require(_isEmployeeIdActive(_employeeId), ERROR_NON_ACTIVE_EMPLOYEE);
_;
}
// Check sender matches an existing employee
modifier employeeMatches {
require(employees[employeeIds[msg.sender]].accountAddress == msg.sender, ERROR_SENDER_DOES_NOT_MATCH);
_;
}
/**
* @notice Initialize Payroll app for Finance at `_finance` and price feed at `_priceFeed`, setting denomination token to `_token` and exchange rate expiry time to `@transformTime(_rateExpiryTime)`
* @dev Note that we do not require _denominationToken to be a contract, as it may be a "fake"
* address used by the price feed to denominate fiat currencies
* @param _finance Address of the Finance app this Payroll app will rely on for payments (non-changeable)
* @param _denominationToken Address of the denomination token used for salary accounting
* @param _priceFeed Address of the price feed
* @param _rateExpiryTime Acceptable expiry time in seconds for the price feed's exchange rates
*/
function initialize(Finance _finance, address _denominationToken, IFeed _priceFeed, uint64 _rateExpiryTime) external onlyInit {
initialized();
require(isContract(_finance), ERROR_FINANCE_NOT_CONTRACT);
finance = _finance;
denominationToken = _denominationToken;
_setPriceFeed(_priceFeed);
_setRateExpiryTime(_rateExpiryTime);
// Employees start at index 1, to allow us to use employees[0] to check for non-existent employees
nextEmployee = 1;
}
/**
* @notice `_allowed ? 'Add' : 'Remove'` `_token.symbol(): string` `_allowed ? 'to' : 'from'` the set of allowed tokens
* @param _token Address of the token to be added or removed from the list of allowed tokens for payments
* @param _allowed Boolean to tell whether the given token should be added or removed from the list
*/
function setAllowedToken(address _token, bool _allowed) external authP(MANAGE_ALLOWED_TOKENS_ROLE, arr(_token)) {
require(allowedTokens[_token] != _allowed, ERROR_TOKEN_ALREADY_SET);
allowedTokens[_token] = _allowed;
emit SetAllowedToken(_token, _allowed);
}
/**
* @notice Set the price feed for exchange rates to `_feed`
* @param _feed Address of the new price feed instance
*/
function setPriceFeed(IFeed _feed) external authP(MODIFY_PRICE_FEED_ROLE, arr(_feed, feed)) {
_setPriceFeed(_feed);
}
/**
* @notice Set the acceptable expiry time for the price feed's exchange rates to `@transformTime(_time)`
* @dev Exchange rates older than the given value won't be accepted for payments and will cause payouts to revert
* @param _time The expiration time in seconds for exchange rates
*/
function setRateExpiryTime(uint64 _time) external authP(MODIFY_RATE_EXPIRY_ROLE, arr(uint256(_time), uint256(rateExpiryTime))) {
_setRateExpiryTime(_time);
}
/**
* @notice Add employee with address `_accountAddress` to payroll with an salary of `_initialDenominationSalary` per second, starting on `@formatDate(_startDate)`
* @param _accountAddress Employee's address to receive payroll
* @param _initialDenominationSalary Employee's salary, per second in denomination token
* @param _startDate Employee's starting timestamp in seconds (it actually sets their initial lastPayroll value)
* @param _role Employee's role
*/
function addEmployee(address _accountAddress, uint256 _initialDenominationSalary, uint64 _startDate, string _role)
external
authP(ADD_EMPLOYEE_ROLE, arr(_accountAddress, _initialDenominationSalary, uint256(_startDate)))
{
_addEmployee(_accountAddress, _initialDenominationSalary, _startDate, _role);
}
/**
* @notice Add `_amount` to bonus for employee #`_employeeId`
* @param _employeeId Employee's identifier
* @param _amount Amount to be added to the employee's bonuses in denomination token
*/
function addBonus(uint256 _employeeId, uint256 _amount)
external
authP(ADD_BONUS_ROLE, arr(_employeeId, _amount))
employeeActive(_employeeId)
{
_addBonus(_employeeId, _amount);
}
/**
* @notice Add `_amount` to reimbursements for employee #`_employeeId`
* @param _employeeId Employee's identifier
* @param _amount Amount to be added to the employee's reimbursements in denomination token
*/
function addReimbursement(uint256 _employeeId, uint256 _amount)
external
authP(ADD_REIMBURSEMENT_ROLE, arr(_employeeId, _amount))
employeeActive(_employeeId)
{
_addReimbursement(_employeeId, _amount);
}
/**
* @notice Set employee #`_employeeId`'s salary to `_denominationSalary` per second
* @dev This reverts if either the employee's owed salary or accrued salary overflows, to avoid
* losing any accrued salary for an employee due to the employer changing their salary.
* @param _employeeId Employee's identifier
* @param _denominationSalary Employee's new salary, per second in denomination token
*/
function setEmployeeSalary(uint256 _employeeId, uint256 _denominationSalary)
external
authP(SET_EMPLOYEE_SALARY_ROLE, arr(_employeeId, _denominationSalary, employees[_employeeId].denominationTokenSalary))
employeeActive(_employeeId)
{
Employee storage employee = employees[_employeeId];
// Accrue employee's owed salary; don't cap to revert on overflow
uint256 owed = _getOwedSalarySinceLastPayroll(employee, false);
_addAccruedSalary(_employeeId, owed);
// Update employee to track the new salary and payment date
employee.lastPayroll = getTimestamp64();
employee.denominationTokenSalary = _denominationSalary;
emit SetEmployeeSalary(_employeeId, _denominationSalary);
}
/**
* @notice Terminate employee #`_employeeId` on `@formatDate(_endDate)`
* @param _employeeId Employee's identifier
* @param _endDate Termination timestamp in seconds
*/
function terminateEmployee(uint256 _employeeId, uint64 _endDate)
external
authP(TERMINATE_EMPLOYEE_ROLE, arr(_employeeId, uint256(_endDate)))
employeeActive(_employeeId)
{
_terminateEmployee(_employeeId, _endDate);
}
/**
* @notice Change your employee account address to `_newAccountAddress`
* @dev Initialization check is implicitly provided by `employeeMatches` as new employees can
* only be added via `addEmployee(),` which requires initialization.
* As the employee is allowed to call this, we enforce non-reentrancy.
* @param _newAccountAddress New address to receive payments for the requesting employee
*/
function changeAddressByEmployee(address _newAccountAddress) external employeeMatches nonReentrant {
uint256 employeeId = employeeIds[msg.sender];
address oldAddress = employees[employeeId].accountAddress;
_setEmployeeAddress(employeeId, _newAccountAddress);
// Don't delete the old address until after setting the new address to check that the
// employee specified a new address
delete employeeIds[oldAddress];
emit ChangeAddressByEmployee(employeeId, _newAccountAddress, oldAddress);
}
/**
* @notice Set the token distribution for your payments
* @dev Initialization check is implicitly provided by `employeeMatches` as new employees can
* only be added via `addEmployee(),` which requires initialization.
* As the employee is allowed to call this, we enforce non-reentrancy.
* @param _tokens Array of token addresses; they must belong to the list of allowed tokens
* @param _distribution Array with each token's corresponding proportions (must be integers summing to 100)
*/
function determineAllocation(address[] _tokens, uint256[] _distribution) external employeeMatches nonReentrant {
// Check array lengthes match
require(_tokens.length <= MAX_ALLOWED_TOKENS, ERROR_MAX_ALLOWED_TOKENS);
require(_tokens.length == _distribution.length, ERROR_TOKEN_ALLOCATION_MISMATCH);
uint256 employeeId = employeeIds[msg.sender];
Employee storage employee = employees[employeeId];
// Delete previous token allocations
address[] memory previousAllowedTokenAddresses = employee.allocationTokenAddresses;
for (uint256 j = 0; j < previousAllowedTokenAddresses.length; j++) {
delete employee.allocationTokens[previousAllowedTokenAddresses[j]];
}
delete employee.allocationTokenAddresses;
// Set distributions only if given tokens are allowed
for (uint256 i = 0; i < _tokens.length; i++) {
employee.allocationTokenAddresses.push(_tokens[i]);
employee.allocationTokens[_tokens[i]] = _distribution[i];
}
_ensureEmployeeTokenAllocationsIsValid(employee);
emit DetermineAllocation(employeeId);
}
/**
* @notice Request your `_type == 0 ? 'salary' : _type == 1 ? 'reimbursements' : 'bonus'`
* @dev Reverts if no payments were made.
* Initialization check is implicitly provided by `employeeMatches` as new employees can
* only be added via `addEmployee(),` which requires initialization.
* As the employee is allowed to call this, we enforce non-reentrancy.
* @param _type Payment type being requested (Payroll, Reimbursement or Bonus)
* @param _requestedAmount Requested amount to pay for the payment type. Must be less than or equal to total owed amount for the payment type, or zero to request all.
* @param _minRates Array of employee's minimum acceptable rates for their allowed payment tokens
*/
function payday(PaymentType _type, uint256 _requestedAmount, uint256[] _minRates) external employeeMatches nonReentrant {
uint256 paymentAmount;
uint256 employeeId = employeeIds[msg.sender];
Employee storage employee = employees[employeeId];
_ensureEmployeeTokenAllocationsIsValid(employee);
require(_minRates.length == 0 || _minRates.length == employee.allocationTokenAddresses.length, ERROR_MIN_RATES_MISMATCH);
// Do internal employee accounting
if (_type == PaymentType.Payroll) {
// Salary is capped here to avoid reverting at this point if it becomes too big
// (so employees aren't DDOSed if their salaries get too large)
// If we do use a capped value, the employee's lastPayroll date will be adjusted accordingly
uint256 totalOwedSalary = _getTotalOwedCappedSalary(employee);
paymentAmount = _ensurePaymentAmount(totalOwedSalary, _requestedAmount);
_updateEmployeeAccountingBasedOnPaidSalary(employee, paymentAmount);
} else if (_type == PaymentType.Reimbursement) {
uint256 owedReimbursements = employee.reimbursements;
paymentAmount = _ensurePaymentAmount(owedReimbursements, _requestedAmount);
employee.reimbursements = owedReimbursements.sub(paymentAmount);
} else if (_type == PaymentType.Bonus) {
uint256 owedBonusAmount = employee.bonus;
paymentAmount = _ensurePaymentAmount(owedBonusAmount, _requestedAmount);
employee.bonus = owedBonusAmount.sub(paymentAmount);
} else {
revert(ERROR_INVALID_PAYMENT_TYPE);
}
// Actually transfer the owed funds
require(_transferTokensAmount(employeeId, _type, paymentAmount, _minRates), ERROR_NOTHING_PAID);
_removeEmployeeIfTerminatedAndPaidOut(employeeId);
}
// Forwarding fns
/**
* @dev IForwarder interface conformance. Tells whether the Payroll app is a forwarder or not.
* @return Always true
*/
function isForwarder() external pure returns (bool) {
return true;
}
/**
* @notice Execute desired action as an active employee
* @dev IForwarder interface conformance. Allows active employees to run EVMScripts in the context of the Payroll app.
* @param _evmScript Script being executed
*/
function forward(bytes _evmScript) public {
require(canForward(msg.sender, _evmScript), ERROR_CAN_NOT_FORWARD);
bytes memory input = new bytes(0); // TODO: Consider input for this
// Add the Finance app to the blacklist to disallow employees from executing actions on the
// Finance app from Payroll's context (since Payroll requires permissions on Finance)
address[] memory blacklist = new address[](1);
blacklist[0] = address(finance);
runScript(_evmScript, input, blacklist);
}
/**
* @dev IForwarder interface conformance. Tells whether a given address can forward actions or not.
* @param _sender Address of the account intending to forward an action
* @return True if the given address is an active employee, false otherwise
*/
function canForward(address _sender, bytes) public view returns (bool) {
return _isEmployeeIdActive(employeeIds[_sender]);
}
// Getter fns
/**
* @dev Return employee's identifier by their account address
* @param _accountAddress Employee's address to receive payments
* @return Employee's identifier
*/
function getEmployeeIdByAddress(address _accountAddress) public view returns (uint256) {
require(employeeIds[_accountAddress] != uint256(0), ERROR_EMPLOYEE_DOESNT_EXIST);
return employeeIds[_accountAddress];
}
/**
* @dev Return all information for employee by their ID
* @param _employeeId Employee's identifier
* @return Employee's address to receive payments
* @return Employee's salary, per second in denomination token
* @return Employee's accrued salary
* @return Employee's bonus amount
* @return Employee's reimbursements amount
* @return Employee's last payment date
* @return Employee's termination date (max uint64 if none)
* @return Employee's allowed payment tokens
*/
function getEmployee(uint256 _employeeId)
public
view
employeeIdExists(_employeeId)
returns (
address accountAddress,
uint256 denominationSalary,
uint256 accruedSalary,
uint256 bonus,
uint256 reimbursements,
uint64 lastPayroll,
uint64 endDate,
address[] allocationTokens
)
{
Employee storage employee = employees[_employeeId];
accountAddress = employee.accountAddress;
denominationSalary = employee.denominationTokenSalary;
accruedSalary = employee.accruedSalary;
bonus = employee.bonus;
reimbursements = employee.reimbursements;
lastPayroll = employee.lastPayroll;
endDate = employee.endDate;
allocationTokens = employee.allocationTokenAddresses;
}
/**
* @dev Get owed salary since last payroll for an employee. It will take into account the accrued salary as well.
* The result will be capped to max uint256 to avoid having an overflow.
* @return Employee's total owed salary: current owed payroll since the last payroll date, plus the accrued salary.
*/
function getTotalOwedSalary(uint256 _employeeId) public view employeeIdExists(_employeeId) returns (uint256) {
return _getTotalOwedCappedSalary(employees[_employeeId]);
}
/**
* @dev Get an employee's payment allocation for a token
* @param _employeeId Employee's identifier
* @param _token Token to query the payment allocation for
* @return Employee's payment allocation for the token being queried
*/
function getAllocation(uint256 _employeeId, address _token) public view employeeIdExists(_employeeId) returns (uint256) {
return employees[_employeeId].allocationTokens[_token];
}
/**
* @dev Check if a token is allowed to be used for payments
* @param _token Address of the token to be checked
* @return True if the given token is allowed, false otherwise
*/
function isTokenAllowed(address _token) public view isInitialized returns (bool) {
return allowedTokens[_token];
}
// Internal fns
/**
* @dev Set the price feed used for exchange rates
* @param _feed Address of the new price feed instance
*/
function _setPriceFeed(IFeed _feed) internal {
require(isContract(_feed), ERROR_FEED_NOT_CONTRACT);
feed = _feed;
emit SetPriceFeed(feed);
}
/**
* @dev Set the exchange rate expiry time in seconds.
* Exchange rates older than the given value won't be accepted for payments and will cause
* payouts to revert.
* @param _time The expiration time in seconds for exchange rates
*/
function _setRateExpiryTime(uint64 _time) internal {
// Require a sane minimum for the rate expiry time
require(_time >= MIN_RATE_EXPIRY, ERROR_EXPIRY_TIME_TOO_SHORT);
rateExpiryTime = _time;
emit SetRateExpiryTime(rateExpiryTime);
}
/**
* @dev Add a new employee to Payroll
* @param _accountAddress Employee's address to receive payroll
* @param _initialDenominationSalary Employee's salary, per second in denomination token
* @param _startDate Employee's starting timestamp in seconds
* @param _role Employee's role
*/
function _addEmployee(address _accountAddress, uint256 _initialDenominationSalary, uint64 _startDate, string _role) internal {
uint256 employeeId = nextEmployee++;
_setEmployeeAddress(employeeId, _accountAddress);
Employee storage employee = employees[employeeId];
employee.denominationTokenSalary = _initialDenominationSalary;
employee.lastPayroll = _startDate;
employee.endDate = MAX_UINT64;
emit AddEmployee(employeeId, _accountAddress, _initialDenominationSalary, _startDate, _role);
}
/**
* @dev Add amount to an employee's bonuses
* @param _employeeId Employee's identifier
* @param _amount Amount be added to the employee's bonuses in denomination token
*/
function _addBonus(uint256 _employeeId, uint256 _amount) internal {
Employee storage employee = employees[_employeeId];
employee.bonus = employee.bonus.add(_amount);
emit AddEmployeeBonus(_employeeId, _amount);
}
/**
* @dev Add amount to an employee's reimbursements
* @param _employeeId Employee's identifier
* @param _amount Amount be added to the employee's reimbursements in denomination token
*/
function _addReimbursement(uint256 _employeeId, uint256 _amount) internal {
Employee storage employee = employees[_employeeId];
employee.reimbursements = employee.reimbursements.add(_amount);
emit AddEmployeeReimbursement(_employeeId, _amount);
}
/**
* @dev Add amount to an employee's accrued salary
* @param _employeeId Employee's identifier
* @param _amount Amount be added to the employee's accrued salary in denomination token
*/
function _addAccruedSalary(uint256 _employeeId, uint256 _amount) internal {
Employee storage employee = employees[_employeeId];
employee.accruedSalary = employee.accruedSalary.add(_amount);
emit AddEmployeeAccruedSalary(_employeeId, _amount);
}
/**
* @dev Set an employee's account address
* @param _employeeId Employee's identifier
* @param _accountAddress Employee's address to receive payroll
*/
function _setEmployeeAddress(uint256 _employeeId, address _accountAddress) internal {
// Check address is non-null
require(_accountAddress != address(0), ERROR_EMPLOYEE_NULL_ADDRESS);
// Check address isn't already being used
require(employeeIds[_accountAddress] == uint256(0), ERROR_EMPLOYEE_ALREADY_EXIST);
employees[_employeeId].accountAddress = _accountAddress;
// Create IDs mapping
employeeIds[_accountAddress] = _employeeId;
}
/**
* @dev Terminate employee on end date
* @param _employeeId Employee's identifier
* @param _endDate Termination timestamp in seconds
*/
function _terminateEmployee(uint256 _employeeId, uint64 _endDate) internal {
// Prevent past termination dates
require(_endDate >= getTimestamp64(), ERROR_PAST_TERMINATION_DATE);
employees[_employeeId].endDate = _endDate;
emit TerminateEmployee(_employeeId, _endDate);
}
/**
* @dev Loop over allowed tokens to send requested amount to the employee in their desired allocation
* @param _employeeId Employee's identifier
* @param _totalAmount Total amount to be transferred to the employee distributed in accordance to the employee's token allocation.
* @param _type Payment type being transferred (Payroll, Reimbursement or Bonus)
* @param _minRates Array of employee's minimum acceptable rates for their allowed payment tokens
* @return True if there was at least one token transfer
*/
function _transferTokensAmount(uint256 _employeeId, PaymentType _type, uint256 _totalAmount, uint256[] _minRates) internal returns (bool somethingPaid) {
if (_totalAmount == 0) {
return false;
}
Employee storage employee = employees[_employeeId];
address employeeAddress = employee.accountAddress;
string memory paymentReference = _paymentReferenceFor(_type);
address[] storage allocationTokenAddresses = employee.allocationTokenAddresses;
for (uint256 i = 0; i < allocationTokenAddresses.length; i++) {
address token = allocationTokenAddresses[i];
uint256 tokenAllocation = employee.allocationTokens[token];
if (tokenAllocation != uint256(0)) {
// Get the exchange rate for the payout token in denomination token,
// as we do accounting in denomination tokens
uint256 exchangeRate = _getExchangeRateInDenominationToken(token);
require(_minRates.length > 0 ? exchangeRate >= _minRates[i] : exchangeRate > 0, ERROR_EXCHANGE_RATE_TOO_LOW);
// Convert amount (in denomination tokens) to payout token and apply allocation
uint256 tokenAmount = _totalAmount.mul(exchangeRate).mul(tokenAllocation);
// Divide by 100 for the allocation percentage and by the exchange rate precision
tokenAmount = tokenAmount.div(100).div(feed.ratePrecision());
// Finance reverts if the payment wasn't possible
finance.newImmediatePayment(token, employeeAddress, tokenAmount, paymentReference);
emit SendPayment(_employeeId, employeeAddress, token, tokenAmount, exchangeRate, paymentReference);
somethingPaid = true;
}
}
}
/**
* @dev Remove employee if there are no owed funds and employee's end date has been reached
* @param _employeeId Employee's identifier
*/
function _removeEmployeeIfTerminatedAndPaidOut(uint256 _employeeId) internal {
Employee storage employee = employees[_employeeId];
if (
employee.lastPayroll == employee.endDate &&
(employee.accruedSalary == 0 && employee.bonus == 0 && employee.reimbursements == 0)
) {
delete employeeIds[employee.accountAddress];
delete employees[_employeeId];
}
}
/**
* @dev Updates the accrued salary and payroll date of an employee based on a payment amount and
* their currently owed salary since last payroll date
* @param _employee Employee struct in storage
* @param _paymentAmount Amount being paid to the employee
*/
function _updateEmployeeAccountingBasedOnPaidSalary(Employee storage _employee, uint256 _paymentAmount) internal {
uint256 accruedSalary = _employee.accruedSalary;
if (_paymentAmount <= accruedSalary) {
// Employee is only cashing out some previously owed salary so we don't need to update
// their last payroll date
// No need to use SafeMath as we already know _paymentAmount <= accruedSalary
_employee.accruedSalary = accruedSalary - _paymentAmount;
return;
}
// Employee is cashing out some of their currently owed salary so their last payroll date
// needs to be modified based on the amount of salary paid
uint256 currentSalaryPaid = _paymentAmount;
if (accruedSalary > 0) {
// Employee is cashing out a mixed amount between previous and current owed salaries;
// first use up their accrued salary
// No need to use SafeMath here as we already know _paymentAmount > accruedSalary
currentSalaryPaid = _paymentAmount - accruedSalary;
// We finally need to clear their accrued salary
_employee.accruedSalary = 0;
}
uint256 salary = _employee.denominationTokenSalary;
uint256 timeDiff = currentSalaryPaid.div(salary);
// If they're being paid an amount that doesn't match perfectly with the adjusted time
// (up to a seconds' worth of salary), add the second and put the extra remaining salary
// into their accrued salary
uint256 extraSalary = currentSalaryPaid % salary;
if (extraSalary > 0) {
timeDiff = timeDiff.add(1);
_employee.accruedSalary = salary - extraSalary;
}
uint256 lastPayrollDate = uint256(_employee.lastPayroll).add(timeDiff);
// Even though this function should never receive a currentSalaryPaid value that would
// result in the lastPayrollDate being higher than the current time,
// let's double check to be safe
require(lastPayrollDate <= uint256(getTimestamp64()), ERROR_LAST_PAYROLL_DATE_TOO_BIG);
// Already know lastPayrollDate must fit in uint64 from above
_employee.lastPayroll = uint64(lastPayrollDate);
}
/**
* @dev Tell whether an employee is registered in this Payroll or not
* @param _employeeId Employee's identifier
* @return True if the given employee ID belongs to an registered employee, false otherwise
*/
function _employeeExists(uint256 _employeeId) internal view returns (bool) {
return employees[_employeeId].accountAddress != address(0);
}
/**
* @dev Tell whether an employee has a valid token allocation or not.
* A valid allocation is one that sums to 100 and only includes allowed tokens.
* @param _employee Employee struct in storage
* @return Reverts if employee's allocation is invalid
*/
function _ensureEmployeeTokenAllocationsIsValid(Employee storage _employee) internal view {
uint256 sum = 0;
address[] memory allocationTokenAddresses = _employee.allocationTokenAddresses;
for (uint256 i = 0; i < allocationTokenAddresses.length; i++) {
address token = allocationTokenAddresses[i];
require(allowedTokens[token], ERROR_NOT_ALLOWED_TOKEN);
sum = sum.add(_employee.allocationTokens[token]);
}
require(sum == 100, ERROR_DISTRIBUTION_NOT_FULL);
}
/**
* @dev Tell whether an employee is still active or not
* @param _employee Employee struct in storage
* @return True if the employee exists and has an end date that has not been reached yet, false otherwise
*/
function _isEmployeeActive(Employee storage _employee) internal view returns (bool) {
return _employee.endDate >= getTimestamp64();
}
/**
* @dev Tell whether an employee id is still active or not
* @param _employeeId Employee's identifier
* @return True if the employee exists and has an end date that has not been reached yet, false otherwise
*/
function _isEmployeeIdActive(uint256 _employeeId) internal view returns (bool) {
return _isEmployeeActive(employees[_employeeId]);
}
/**
* @dev Get exchange rate for a token based on the denomination token.
* As an example, if the denomination token was USD and ETH's price was 100USD,
* this would return 0.01 * precision rate for ETH.
* @param _token Token to get price of in denomination tokens
* @return Exchange rate (multiplied by the PPF rate precision)
*/
function _getExchangeRateInDenominationToken(address _token) internal view returns (uint256) {
// xrt is the number of `_token` that can be exchanged for one `denominationToken`
(uint128 xrt, uint64 when) = feed.get(
denominationToken, // Base (e.g. USD)
_token // Quote (e.g. ETH)
);
// Check the price feed is recent enough
if (getTimestamp64().sub(when) >= rateExpiryTime) {
return 0;
}
return uint256(xrt);
}
/**
* @dev Get owed salary since last payroll for an employee
* @param _employee Employee struct in storage
* @param _capped Safely cap the owed salary at max uint
* @return Owed salary in denomination tokens since last payroll for the employee.
* If _capped is false, it reverts in case of an overflow.
*/
function _getOwedSalarySinceLastPayroll(Employee storage _employee, bool _capped) internal view returns (uint256) {
uint256 timeDiff = _getOwedPayrollPeriod(_employee);
if (timeDiff == 0) {
return 0;
}
uint256 salary = _employee.denominationTokenSalary;
if (_capped) {
// Return max uint if the result overflows
uint256 result = salary * timeDiff;
return (result / timeDiff != salary) ? MAX_UINT256 : result;
} else {
return salary.mul(timeDiff);
}
}
/**
* @dev Get owed payroll period for an employee
* @param _employee Employee struct in storage
* @return Owed time in seconds since the employee's last payroll date
*/
function _getOwedPayrollPeriod(Employee storage _employee) internal view returns (uint256) {
// Get the min of current date and termination date
uint64 date = _isEmployeeActive(_employee) ? getTimestamp64() : _employee.endDate;
// Make sure we don't revert if we try to get the owed salary for an employee whose last
// payroll date is now or in the future
// This can happen either by adding new employees with start dates in the future, to allow
// us to change their salary before their start date, or by terminating an employee and
// paying out their full owed salary
if (date <= _employee.lastPayroll) {
return 0;
}
// Return time diff in seconds, no need to use SafeMath as the underflow was covered by the previous check
return uint256(date - _employee.lastPayroll);
}
/**
* @dev Get owed salary since last payroll for an employee. It will take into account the accrued salary as well.
* The result will be capped to max uint256 to avoid having an overflow.
* @param _employee Employee struct in storage
* @return Employee's total owed salary: current owed payroll since the last payroll date, plus the accrued salary.
*/
function _getTotalOwedCappedSalary(Employee storage _employee) internal view returns (uint256) {
uint256 currentOwedSalary = _getOwedSalarySinceLastPayroll(_employee, true); // cap amount
uint256 totalOwedSalary = currentOwedSalary + _employee.accruedSalary;
if (totalOwedSalary < currentOwedSalary) {
totalOwedSalary = MAX_UINT256;
}
return totalOwedSalary;
}
/**
* @dev Get payment reference for a given payment type
* @param _type Payment type to query the reference of
* @return Payment reference for the given payment type
*/
function _paymentReferenceFor(PaymentType _type) internal pure returns (string memory) {
if (_type == PaymentType.Payroll) {
return "Employee salary";
} else if (_type == PaymentType.Reimbursement) {
return "Employee reimbursement";
} if (_type == PaymentType.Bonus) {
return "Employee bonus";
}
revert(ERROR_INVALID_PAYMENT_TYPE);
}
function _ensurePaymentAmount(uint256 _owedAmount, uint256 _requestedAmount) private pure returns (uint256) {
require(_owedAmount > 0, ERROR_NOTHING_PAID);
require(_owedAmount >= _requestedAmount, ERROR_INVALID_REQUESTED_AMOUNT);
return _requestedAmount > 0 ? _requestedAmount : _owedAmount;
}
}
// File: @aragon/apps-token-manager/contracts/TokenManager.sol
/*
* SPDX-License-Identitifer: GPL-3.0-or-later
*/
/* solium-disable function-order */
pragma solidity 0.4.24;
contract TokenManager is ITokenController, IForwarder, AragonApp {
using SafeMath for uint256;
bytes32 public constant MINT_ROLE = keccak256("MINT_ROLE");
bytes32 public constant ISSUE_ROLE = keccak256("ISSUE_ROLE");
bytes32 public constant ASSIGN_ROLE = keccak256("ASSIGN_ROLE");
bytes32 public constant REVOKE_VESTINGS_ROLE = keccak256("REVOKE_VESTINGS_ROLE");
bytes32 public constant BURN_ROLE = keccak256("BURN_ROLE");
uint256 public constant MAX_VESTINGS_PER_ADDRESS = 50;
string private constant ERROR_CALLER_NOT_TOKEN = "TM_CALLER_NOT_TOKEN";
string private constant ERROR_NO_VESTING = "TM_NO_VESTING";
string private constant ERROR_TOKEN_CONTROLLER = "TM_TOKEN_CONTROLLER";
string private constant ERROR_MINT_RECEIVER_IS_TM = "TM_MINT_RECEIVER_IS_TM";
string private constant ERROR_VESTING_TO_TM = "TM_VESTING_TO_TM";
string private constant ERROR_TOO_MANY_VESTINGS = "TM_TOO_MANY_VESTINGS";
string private constant ERROR_WRONG_CLIFF_DATE = "TM_WRONG_CLIFF_DATE";
string private constant ERROR_VESTING_NOT_REVOKABLE = "TM_VESTING_NOT_REVOKABLE";
string private constant ERROR_REVOKE_TRANSFER_FROM_REVERTED = "TM_REVOKE_TRANSFER_FROM_REVERTED";
string private constant ERROR_CAN_NOT_FORWARD = "TM_CAN_NOT_FORWARD";
string private constant ERROR_BALANCE_INCREASE_NOT_ALLOWED = "TM_BALANCE_INC_NOT_ALLOWED";
string private constant ERROR_ASSIGN_TRANSFER_FROM_REVERTED = "TM_ASSIGN_TRANSFER_FROM_REVERTED";
struct TokenVesting {
uint256 amount;
uint64 start;
uint64 cliff;
uint64 vesting;
bool revokable;
}
// Note that we COMPLETELY trust this MiniMeToken to not be malicious for proper operation of this contract
MiniMeToken public token;
uint256 public maxAccountTokens;
// We are mimicing an array in the inner mapping, we use a mapping instead to make app upgrade more graceful
mapping (address => mapping (uint256 => TokenVesting)) internal vestings;
mapping (address => uint256) public vestingsLengths;
// Other token specific events can be watched on the token address directly (avoids duplication)
event NewVesting(address indexed receiver, uint256 vestingId, uint256 amount);
event RevokeVesting(address indexed receiver, uint256 vestingId, uint256 nonVestedAmount);
modifier onlyToken() {
require(msg.sender == address(token), ERROR_CALLER_NOT_TOKEN);
_;
}
modifier vestingExists(address _holder, uint256 _vestingId) {
// TODO: it's not checking for gaps that may appear because of deletes in revokeVesting function
require(_vestingId < vestingsLengths[_holder], ERROR_NO_VESTING);
_;
}
/**
* @notice Initialize Token Manager for `_token.symbol(): string`, whose tokens are `transferable ? 'not' : ''` transferable`_maxAccountTokens > 0 ? ' and limited to a maximum of ' + @tokenAmount(_token, _maxAccountTokens, false) + ' per account' : ''`
* @param _token MiniMeToken address for the managed token (Token Manager instance must be already set as the token controller)
* @param _transferable whether the token can be transferred by holders
* @param _maxAccountTokens Maximum amount of tokens an account can have (0 for infinite tokens)
*/
function initialize(
MiniMeToken _token,
bool _transferable,
uint256 _maxAccountTokens
)
external
onlyInit
{
initialized();
require(_token.controller() == address(this), ERROR_TOKEN_CONTROLLER);
token = _token;
maxAccountTokens = _maxAccountTokens == 0 ? uint256(-1) : _maxAccountTokens;
if (token.transfersEnabled() != _transferable) {
token.enableTransfers(_transferable);
}
}
/**
* @notice Mint `@tokenAmount(self.token(): address, _amount, false)` tokens for `_receiver`
* @param _receiver The address receiving the tokens, cannot be the Token Manager itself (use `issue()` instead)
* @param _amount Number of tokens minted
*/
function mint(address _receiver, uint256 _amount) external authP(MINT_ROLE, arr(_receiver, _amount)) {
require(_receiver != address(this), ERROR_MINT_RECEIVER_IS_TM);
_mint(_receiver, _amount);
}
/**
* @notice Mint `@tokenAmount(self.token(): address, _amount, false)` tokens for the Token Manager
* @param _amount Number of tokens minted
*/
function issue(uint256 _amount) external authP(ISSUE_ROLE, arr(_amount)) {
_mint(address(this), _amount);
}
/**
* @notice Assign `@tokenAmount(self.token(): address, _amount, false)` tokens to `_receiver` from the Token Manager's holdings
* @param _receiver The address receiving the tokens
* @param _amount Number of tokens transferred
*/
function assign(address _receiver, uint256 _amount) external authP(ASSIGN_ROLE, arr(_receiver, _amount)) {
_assign(_receiver, _amount);
}
/**
* @notice Burn `@tokenAmount(self.token(): address, _amount, false)` tokens from `_holder`
* @param _holder Holder of tokens being burned
* @param _amount Number of tokens being burned
*/
function burn(address _holder, uint256 _amount) external authP(BURN_ROLE, arr(_holder, _amount)) {
// minime.destroyTokens() never returns false, only reverts on failure
token.destroyTokens(_holder, _amount);
}
/**
* @notice Assign `@tokenAmount(self.token(): address, _amount, false)` tokens to `_receiver` from the Token Manager's holdings with a `_revokable : 'revokable' : ''` vesting starting at `@formatDate(_start)`, cliff at `@formatDate(_cliff)` (first portion of tokens transferable), and completed vesting at `@formatDate(_vested)` (all tokens transferable)
* @param _receiver The address receiving the tokens, cannot be Token Manager itself
* @param _amount Number of tokens vested
* @param _start Date the vesting calculations start
* @param _cliff Date when the initial portion of tokens are transferable
* @param _vested Date when all tokens are transferable
* @param _revokable Whether the vesting can be revoked by the Token Manager
*/
function assignVested(
address _receiver,
uint256 _amount,
uint64 _start,
uint64 _cliff,
uint64 _vested,
bool _revokable
)
external
authP(ASSIGN_ROLE, arr(_receiver, _amount))
returns (uint256)
{
require(_receiver != address(this), ERROR_VESTING_TO_TM);
require(vestingsLengths[_receiver] < MAX_VESTINGS_PER_ADDRESS, ERROR_TOO_MANY_VESTINGS);
require(_start <= _cliff && _cliff <= _vested, ERROR_WRONG_CLIFF_DATE);
uint256 vestingId = vestingsLengths[_receiver]++;
vestings[_receiver][vestingId] = TokenVesting(
_amount,
_start,
_cliff,
_vested,
_revokable
);
_assign(_receiver, _amount);
emit NewVesting(_receiver, vestingId, _amount);
return vestingId;
}
/**
* @notice Revoke vesting #`_vestingId` from `_holder`, returning unvested tokens to the Token Manager
* @param _holder Address whose vesting to revoke
* @param _vestingId Numeric id of the vesting
*/
function revokeVesting(address _holder, uint256 _vestingId)
external
authP(REVOKE_VESTINGS_ROLE, arr(_holder))
vestingExists(_holder, _vestingId)
{
TokenVesting storage v = vestings[_holder][_vestingId];
require(v.revokable, ERROR_VESTING_NOT_REVOKABLE);
uint256 nonVested = _calculateNonVestedTokens(
v.amount,
getTimestamp(),
v.start,
v.cliff,
v.vesting
);
// To make vestingIds immutable over time, we just zero out the revoked vesting
// Clearing this out also allows the token transfer back to the Token Manager to succeed
delete vestings[_holder][_vestingId];
// transferFrom always works as controller
// onTransfer hook always allows if transfering to token controller
require(token.transferFrom(_holder, address(this), nonVested), ERROR_REVOKE_TRANSFER_FROM_REVERTED);
emit RevokeVesting(_holder, _vestingId, nonVested);
}
// ITokenController fns
// `onTransfer()`, `onApprove()`, and `proxyPayment()` are callbacks from the MiniMe token
// contract and are only meant to be called through the managed MiniMe token that gets assigned
// during initialization.
/*
* @dev Notifies the controller about a token transfer allowing the controller to decide whether
* to allow it or react if desired (only callable from the token).
* Initialization check is implicitly provided by `onlyToken()`.
* @param _from The origin of the transfer
* @param _to The destination of the transfer
* @param _amount The amount of the transfer
* @return False if the controller does not authorize the transfer
*/
function onTransfer(address _from, address _to, uint256 _amount) external onlyToken returns (bool) {
return _isBalanceIncreaseAllowed(_to, _amount) && _transferableBalance(_from, getTimestamp()) >= _amount;
}
/**
* @dev Notifies the controller about an approval allowing the controller to react if desired
* Initialization check is implicitly provided by `onlyToken()`.
* @return False if the controller does not authorize the approval
*/
function onApprove(address, address, uint) external onlyToken returns (bool) {
return true;
}
/**
* @dev Called when ether is sent to the MiniMe Token contract
* Initialization check is implicitly provided by `onlyToken()`.
* @return True if the ether is accepted, false for it to throw
*/
function proxyPayment(address) external payable onlyToken returns (bool) {
return false;
}
// Forwarding fns
function isForwarder() external pure returns (bool) {
return true;
}
/**
* @notice Execute desired action as a token holder
* @dev IForwarder interface conformance. Forwards any token holder action.
* @param _evmScript Script being executed
*/
function forward(bytes _evmScript) public {
require(canForward(msg.sender, _evmScript), ERROR_CAN_NOT_FORWARD);
bytes memory input = new bytes(0); // TODO: Consider input for this
// Add the managed token to the blacklist to disallow a token holder from executing actions
// on the token controller's (this contract) behalf
address[] memory blacklist = new address[](1);
blacklist[0] = address(token);
runScript(_evmScript, input, blacklist);
}
function canForward(address _sender, bytes) public view returns (bool) {
return hasInitialized() && token.balanceOf(_sender) > 0;
}
// Getter fns
function getVesting(
address _recipient,
uint256 _vestingId
)
public
view
vestingExists(_recipient, _vestingId)
returns (
uint256 amount,
uint64 start,
uint64 cliff,
uint64 vesting,
bool revokable
)
{
TokenVesting storage tokenVesting = vestings[_recipient][_vestingId];
amount = tokenVesting.amount;
start = tokenVesting.start;
cliff = tokenVesting.cliff;
vesting = tokenVesting.vesting;
revokable = tokenVesting.revokable;
}
function spendableBalanceOf(address _holder) public view isInitialized returns (uint256) {
return _transferableBalance(_holder, getTimestamp());
}
function transferableBalance(address _holder, uint256 _time) public view isInitialized returns (uint256) {
return _transferableBalance(_holder, _time);
}
/**
* @dev Disable recovery escape hatch for own token,
* as the it has the concept of issuing tokens without assigning them
*/
function allowRecoverability(address _token) public view returns (bool) {
return _token != address(token);
}
// Internal fns
function _assign(address _receiver, uint256 _amount) internal {
require(_isBalanceIncreaseAllowed(_receiver, _amount), ERROR_BALANCE_INCREASE_NOT_ALLOWED);
// Must use transferFrom() as transfer() does not give the token controller full control
require(token.transferFrom(address(this), _receiver, _amount), ERROR_ASSIGN_TRANSFER_FROM_REVERTED);
}
function _mint(address _receiver, uint256 _amount) internal {
require(_isBalanceIncreaseAllowed(_receiver, _amount), ERROR_BALANCE_INCREASE_NOT_ALLOWED);
token.generateTokens(_receiver, _amount); // minime.generateTokens() never returns false
}
function _isBalanceIncreaseAllowed(address _receiver, uint256 _inc) internal view returns (bool) {
// Max balance doesn't apply to the token manager itself
if (_receiver == address(this)) {
return true;
}
return token.balanceOf(_receiver).add(_inc) <= maxAccountTokens;
}
/**
* @dev Calculate amount of non-vested tokens at a specifc time
* @param tokens The total amount of tokens vested
* @param time The time at which to check
* @param start The date vesting started
* @param cliff The cliff period
* @param vested The fully vested date
* @return The amount of non-vested tokens of a specific grant
* transferableTokens
* | _/-------- vestedTokens rect
* | _/
* | _/
* | _/
* | _/
* | /
* | .|
* | . |
* | . |
* | . |
* | . |
* | . |
* +===+===========+---------+----------> time
* Start Cliff Vested
*/
function _calculateNonVestedTokens(
uint256 tokens,
uint256 time,
uint256 start,
uint256 cliff,
uint256 vested
)
private
pure
returns (uint256)
{
// Shortcuts for before cliff and after vested cases.
if (time >= vested) {
return 0;
}
if (time < cliff) {
return tokens;
}
// Interpolate all vested tokens.
// As before cliff the shortcut returns 0, we can just calculate a value
// in the vesting rect (as shown in above's figure)
// vestedTokens = tokens * (time - start) / (vested - start)
// In assignVesting we enforce start <= cliff <= vested
// Here we shortcut time >= vested and time < cliff,
// so no division by 0 is possible
uint256 vestedTokens = tokens.mul(time.sub(start)) / vested.sub(start);
// tokens - vestedTokens
return tokens.sub(vestedTokens);
}
function _transferableBalance(address _holder, uint256 _time) internal view returns (uint256) {
uint256 transferable = token.balanceOf(_holder);
// This check is not strictly necessary for the current version of this contract, as
// Token Managers now cannot assign vestings to themselves.
// However, this was a possibility in the past, so in case there were vestings assigned to
// themselves, this will still return the correct value (entire balance, as the Token
// Manager does not have a spending limit on its own balance).
if (_holder != address(this)) {
uint256 vestingsCount = vestingsLengths[_holder];
for (uint256 i = 0; i < vestingsCount; i++) {
TokenVesting storage v = vestings[_holder][i];
uint256 nonTransferable = _calculateNonVestedTokens(
v.amount,
_time,
v.start,
v.cliff,
v.vesting
);
transferable = transferable.sub(nonTransferable);
}
}
return transferable;
}
}
// File: @aragon/apps-survey/contracts/Survey.sol
/*
* SPDX-License-Identitifer: GPL-3.0-or-later
*/
pragma solidity 0.4.24;
contract Survey is AragonApp {
using SafeMath for uint256;
using SafeMath64 for uint64;
bytes32 public constant CREATE_SURVEYS_ROLE = keccak256("CREATE_SURVEYS_ROLE");
bytes32 public constant MODIFY_PARTICIPATION_ROLE = keccak256("MODIFY_PARTICIPATION_ROLE");
uint64 public constant PCT_BASE = 10 ** 18; // 0% = 0; 1% = 10^16; 100% = 10^18
uint256 public constant ABSTAIN_VOTE = 0;
string private constant ERROR_MIN_PARTICIPATION = "SURVEY_MIN_PARTICIPATION";
string private constant ERROR_NO_SURVEY = "SURVEY_NO_SURVEY";
string private constant ERROR_NO_VOTING_POWER = "SURVEY_NO_VOTING_POWER";
string private constant ERROR_CAN_NOT_VOTE = "SURVEY_CAN_NOT_VOTE";
string private constant ERROR_VOTE_WRONG_INPUT = "SURVEY_VOTE_WRONG_INPUT";
string private constant ERROR_VOTE_WRONG_OPTION = "SURVEY_VOTE_WRONG_OPTION";
string private constant ERROR_NO_STAKE = "SURVEY_NO_STAKE";
string private constant ERROR_OPTIONS_NOT_ORDERED = "SURVEY_OPTIONS_NOT_ORDERED";
string private constant ERROR_NO_OPTION = "SURVEY_NO_OPTION";
struct OptionCast {
uint256 optionId;
uint256 stake;
}
/* Allows for multiple option votes.
* Index 0 is always used for the ABSTAIN_VOTE option, that's calculated automatically by the
* contract.
*/
struct MultiOptionVote {
uint256 optionsCastedLength;
// `castedVotes` simulates an array
// Each OptionCast in `castedVotes` must be ordered by ascending option IDs
mapping (uint256 => OptionCast) castedVotes;
}
struct SurveyStruct {
uint64 startDate;
uint64 snapshotBlock;
uint64 minParticipationPct;
uint256 options;
uint256 votingPower; // total tokens that can cast a vote
uint256 participation; // tokens that casted a vote
// Note that option IDs are from 1 to `options`, due to ABSTAIN_VOTE taking 0
mapping (uint256 => uint256) optionPower; // option ID -> voting power for option
mapping (address => MultiOptionVote) votes; // voter -> options voted, with its stakes
}
MiniMeToken public token;
uint64 public minParticipationPct;
uint64 public surveyTime;
// We are mimicing an array, we use a mapping instead to make app upgrade more graceful
mapping (uint256 => SurveyStruct) internal surveys;
uint256 public surveysLength;
event StartSurvey(uint256 indexed surveyId, address indexed creator, string metadata);
event CastVote(uint256 indexed surveyId, address indexed voter, uint256 option, uint256 stake, uint256 optionPower);
event ResetVote(uint256 indexed surveyId, address indexed voter, uint256 option, uint256 previousStake, uint256 optionPower);
event ChangeMinParticipation(uint64 minParticipationPct);
modifier acceptableMinParticipationPct(uint64 _minParticipationPct) {
require(_minParticipationPct > 0 && _minParticipationPct <= PCT_BASE, ERROR_MIN_PARTICIPATION);
_;
}
modifier surveyExists(uint256 _surveyId) {
require(_surveyId < surveysLength, ERROR_NO_SURVEY);
_;
}
/**
* @notice Initialize Survey app with `_token.symbol(): string` for governance, minimum acceptance participation of `@formatPct(_minParticipationPct)`%, and a voting duration of `@transformTime(_surveyTime)`
* @param _token MiniMeToken address that will be used as governance token
* @param _minParticipationPct Percentage of total voting power that must participate in a survey for it to be taken into account (expressed as a 10^18 percentage, (eg 10^16 = 1%, 10^18 = 100%)
* @param _surveyTime Seconds that a survey will be open for token holders to vote
*/
function initialize(
MiniMeToken _token,
uint64 _minParticipationPct,
uint64 _surveyTime
)
external
onlyInit
acceptableMinParticipationPct(_minParticipationPct)
{
initialized();
token = _token;
minParticipationPct = _minParticipationPct;
surveyTime = _surveyTime;
}
/**
* @notice Change minimum acceptance participation to `@formatPct(_minParticipationPct)`%
* @param _minParticipationPct New acceptance participation
*/
function changeMinAcceptParticipationPct(uint64 _minParticipationPct)
external
authP(MODIFY_PARTICIPATION_ROLE, arr(uint256(_minParticipationPct), uint256(minParticipationPct)))
acceptableMinParticipationPct(_minParticipationPct)
{
minParticipationPct = _minParticipationPct;
emit ChangeMinParticipation(_minParticipationPct);
}
/**
* @notice Create a new non-binding survey about "`_metadata`"
* @param _metadata Survey metadata
* @param _options Number of options voters can decide between
* @return surveyId id for newly created survey
*/
function newSurvey(string _metadata, uint256 _options) external auth(CREATE_SURVEYS_ROLE) returns (uint256 surveyId) {
uint64 snapshotBlock = getBlockNumber64() - 1; // avoid double voting in this very block
uint256 votingPower = token.totalSupplyAt(snapshotBlock);
require(votingPower > 0, ERROR_NO_VOTING_POWER);
surveyId = surveysLength++;
SurveyStruct storage survey = surveys[surveyId];
survey.startDate = getTimestamp64();
survey.snapshotBlock = snapshotBlock; // avoid double voting in this very block
survey.minParticipationPct = minParticipationPct;
survey.options = _options;
survey.votingPower = votingPower;
emit StartSurvey(surveyId, msg.sender, _metadata);
}
/**
* @notice Reset previously casted vote in survey #`_surveyId`, if any.
* @dev Initialization check is implicitly provided by `surveyExists()` as new surveys can only
* be created via `newSurvey(),` which requires initialization
* @param _surveyId Id for survey
*/
function resetVote(uint256 _surveyId) external surveyExists(_surveyId) {
require(canVote(_surveyId, msg.sender), ERROR_CAN_NOT_VOTE);
_resetVote(_surveyId);
}
/**
* @notice Vote for multiple options in survey #`_surveyId`.
* @dev Initialization check is implicitly provided by `surveyExists()` as new surveys can only
* be created via `newSurvey(),` which requires initialization
* @param _surveyId Id for survey
* @param _optionIds Array with indexes of supported options
* @param _stakes Number of tokens assigned to each option
*/
function voteOptions(uint256 _surveyId, uint256[] _optionIds, uint256[] _stakes)
external
surveyExists(_surveyId)
{
require(_optionIds.length == _stakes.length && _optionIds.length > 0, ERROR_VOTE_WRONG_INPUT);
require(canVote(_surveyId, msg.sender), ERROR_CAN_NOT_VOTE);
_voteOptions(_surveyId, _optionIds, _stakes);
}
/**
* @notice Vote option #`_optionId` in survey #`_surveyId`.
* @dev Initialization check is implicitly provided by `surveyExists()` as new surveys can only
* be created via `newSurvey(),` which requires initialization
* @dev It will use the whole balance.
* @param _surveyId Id for survey
* @param _optionId Index of supported option
*/
function voteOption(uint256 _surveyId, uint256 _optionId) external surveyExists(_surveyId) {
require(canVote(_surveyId, msg.sender), ERROR_CAN_NOT_VOTE);
SurveyStruct storage survey = surveys[_surveyId];
// This could re-enter, though we can asume the governance token is not maliciuous
uint256 voterStake = token.balanceOfAt(msg.sender, survey.snapshotBlock);
uint256[] memory options = new uint256[](1);
uint256[] memory stakes = new uint256[](1);
options[0] = _optionId;
stakes[0] = voterStake;
_voteOptions(_surveyId, options, stakes);
}
// Getter fns
function canVote(uint256 _surveyId, address _voter) public view surveyExists(_surveyId) returns (bool) {
SurveyStruct storage survey = surveys[_surveyId];
return _isSurveyOpen(survey) && token.balanceOfAt(_voter, survey.snapshotBlock) > 0;
}
function getSurvey(uint256 _surveyId)
public
view
surveyExists(_surveyId)
returns (
bool open,
uint64 startDate,
uint64 snapshotBlock,
uint64 minParticipation,
uint256 votingPower,
uint256 participation,
uint256 options
)
{
SurveyStruct storage survey = surveys[_surveyId];
open = _isSurveyOpen(survey);
startDate = survey.startDate;
snapshotBlock = survey.snapshotBlock;
minParticipation = survey.minParticipationPct;
votingPower = survey.votingPower;
participation = survey.participation;
options = survey.options;
}
/**
* @dev This is not meant to be used on-chain
*/
/* solium-disable-next-line function-order */
function getVoterState(uint256 _surveyId, address _voter)
external
view
surveyExists(_surveyId)
returns (uint256[] options, uint256[] stakes)
{
MultiOptionVote storage vote = surveys[_surveyId].votes[_voter];
if (vote.optionsCastedLength == 0) {
return (new uint256[](0), new uint256[](0));
}
options = new uint256[](vote.optionsCastedLength + 1);
stakes = new uint256[](vote.optionsCastedLength + 1);
for (uint256 i = 0; i <= vote.optionsCastedLength; i++) {
options[i] = vote.castedVotes[i].optionId;
stakes[i] = vote.castedVotes[i].stake;
}
}
function getOptionPower(uint256 _surveyId, uint256 _optionId) public view surveyExists(_surveyId) returns (uint256) {
SurveyStruct storage survey = surveys[_surveyId];
require(_optionId <= survey.options, ERROR_NO_OPTION);
return survey.optionPower[_optionId];
}
function isParticipationAchieved(uint256 _surveyId) public view surveyExists(_surveyId) returns (bool) {
SurveyStruct storage survey = surveys[_surveyId];
// votingPower is always > 0
uint256 participationPct = survey.participation.mul(PCT_BASE) / survey.votingPower;
return participationPct >= survey.minParticipationPct;
}
// Internal fns
/*
* @dev Assumes the survey exists and that msg.sender can vote
*/
function _resetVote(uint256 _surveyId) internal {
SurveyStruct storage survey = surveys[_surveyId];
MultiOptionVote storage previousVote = survey.votes[msg.sender];
if (previousVote.optionsCastedLength > 0) {
// Voter removes their vote (index 0 is the abstain vote)
for (uint256 i = 1; i <= previousVote.optionsCastedLength; i++) {
OptionCast storage previousOptionCast = previousVote.castedVotes[i];
uint256 previousOptionPower = survey.optionPower[previousOptionCast.optionId];
uint256 currentOptionPower = previousOptionPower.sub(previousOptionCast.stake);
survey.optionPower[previousOptionCast.optionId] = currentOptionPower;
emit ResetVote(_surveyId, msg.sender, previousOptionCast.optionId, previousOptionCast.stake, currentOptionPower);
}
// Compute previously casted votes (i.e. substract non-used tokens from stake)
uint256 voterStake = token.balanceOfAt(msg.sender, survey.snapshotBlock);
uint256 previousParticipation = voterStake.sub(previousVote.castedVotes[0].stake);
// And remove it from total participation
survey.participation = survey.participation.sub(previousParticipation);
// Reset previously voted options
delete survey.votes[msg.sender];
}
}
/*
* @dev Assumes the survey exists and that msg.sender can vote
*/
function _voteOptions(uint256 _surveyId, uint256[] _optionIds, uint256[] _stakes) internal {
SurveyStruct storage survey = surveys[_surveyId];
MultiOptionVote storage senderVotes = survey.votes[msg.sender];
// Revert previous votes, if any
_resetVote(_surveyId);
uint256 totalVoted = 0;
// Reserve first index for ABSTAIN_VOTE
senderVotes.castedVotes[0] = OptionCast({ optionId: ABSTAIN_VOTE, stake: 0 });
for (uint256 optionIndex = 1; optionIndex <= _optionIds.length; optionIndex++) {
// Voters don't specify that they're abstaining,
// but we still keep track of this by reserving the first index of a survey's votes.
// We subtract 1 from the indexes of the arrays passed in by the voter to account for this.
uint256 optionId = _optionIds[optionIndex - 1];
uint256 stake = _stakes[optionIndex - 1];
require(optionId != ABSTAIN_VOTE && optionId <= survey.options, ERROR_VOTE_WRONG_OPTION);
require(stake > 0, ERROR_NO_STAKE);
// Let's avoid repeating an option by making sure that ascending order is preserved in
// the options array by checking that the current optionId is larger than the last one
// we added
require(senderVotes.castedVotes[optionIndex - 1].optionId < optionId, ERROR_OPTIONS_NOT_ORDERED);
// Register voter amount
senderVotes.castedVotes[optionIndex] = OptionCast({ optionId: optionId, stake: stake });
// Add to total option support
survey.optionPower[optionId] = survey.optionPower[optionId].add(stake);
// Keep track of stake used so far
totalVoted = totalVoted.add(stake);
emit CastVote(_surveyId, msg.sender, optionId, stake, survey.optionPower[optionId]);
}
// Compute and register non used tokens
// Implictly we are doing require(totalVoted <= voterStake) too
// (as stated before, index 0 is for ABSTAIN_VOTE option)
uint256 voterStake = token.balanceOfAt(msg.sender, survey.snapshotBlock);
senderVotes.castedVotes[0].stake = voterStake.sub(totalVoted);
// Register number of options voted
senderVotes.optionsCastedLength = _optionIds.length;
// Add voter tokens to participation
survey.participation = survey.participation.add(totalVoted);
assert(survey.participation <= survey.votingPower);
}
function _isSurveyOpen(SurveyStruct storage _survey) internal view returns (bool) {
return getTimestamp64() < _survey.startDate.add(surveyTime);
}
}
// File: @aragon/os/contracts/acl/IACLOracle.sol
/*
* SPDX-License-Identitifer: MIT
*/
pragma solidity ^0.4.24;
interface IACLOracle {
function canPerform(address who, address where, bytes32 what, uint256[] how) external view returns (bool);
}
// File: @aragon/os/contracts/acl/ACL.sol
pragma solidity 0.4.24;
/* solium-disable function-order */
// Allow public initialize() to be first
contract ACL is IACL, TimeHelpers, AragonApp, ACLHelpers {
/* Hardcoded constants to save gas
bytes32 public constant CREATE_PERMISSIONS_ROLE = keccak256("CREATE_PERMISSIONS_ROLE");
*/
bytes32 public constant CREATE_PERMISSIONS_ROLE = 0x0b719b33c83b8e5d300c521cb8b54ae9bd933996a14bef8c2f4e0285d2d2400a;
enum Op { NONE, EQ, NEQ, GT, LT, GTE, LTE, RET, NOT, AND, OR, XOR, IF_ELSE } // op types
struct Param {
uint8 id;
uint8 op;
uint240 value; // even though value is an uint240 it can store addresses
// in the case of 32 byte hashes losing 2 bytes precision isn't a huge deal
// op and id take less than 1 byte each so it can be kept in 1 sstore
}
uint8 internal constant BLOCK_NUMBER_PARAM_ID = 200;
uint8 internal constant TIMESTAMP_PARAM_ID = 201;
// 202 is unused
uint8 internal constant ORACLE_PARAM_ID = 203;
uint8 internal constant LOGIC_OP_PARAM_ID = 204;
uint8 internal constant PARAM_VALUE_PARAM_ID = 205;
// TODO: Add execution times param type?
/* Hardcoded constant to save gas
bytes32 public constant EMPTY_PARAM_HASH = keccak256(uint256(0));
*/
bytes32 public constant EMPTY_PARAM_HASH = 0x290decd9548b62a8d60345a988386fc84ba6bc95484008f6362f93160ef3e563;
bytes32 public constant NO_PERMISSION = bytes32(0);
address public constant ANY_ENTITY = address(-1);
address public constant BURN_ENTITY = address(1); // address(0) is already used as "no permission manager"
uint256 internal constant ORACLE_CHECK_GAS = 30000;
string private constant ERROR_AUTH_INIT_KERNEL = "ACL_AUTH_INIT_KERNEL";
string private constant ERROR_AUTH_NO_MANAGER = "ACL_AUTH_NO_MANAGER";
string private constant ERROR_EXISTENT_MANAGER = "ACL_EXISTENT_MANAGER";
// Whether someone has a permission
mapping (bytes32 => bytes32) internal permissions; // permissions hash => params hash
mapping (bytes32 => Param[]) internal permissionParams; // params hash => params
// Who is the manager of a permission
mapping (bytes32 => address) internal permissionManager;
event SetPermission(address indexed entity, address indexed app, bytes32 indexed role, bool allowed);
event SetPermissionParams(address indexed entity, address indexed app, bytes32 indexed role, bytes32 paramsHash);
event ChangePermissionManager(address indexed app, bytes32 indexed role, address indexed manager);
modifier onlyPermissionManager(address _app, bytes32 _role) {
require(msg.sender == getPermissionManager(_app, _role), ERROR_AUTH_NO_MANAGER);
_;
}
modifier noPermissionManager(address _app, bytes32 _role) {
// only allow permission creation (or re-creation) when there is no manager
require(getPermissionManager(_app, _role) == address(0), ERROR_EXISTENT_MANAGER);
_;
}
/**
* @dev Initialize can only be called once. It saves the block number in which it was initialized.
* @notice Initialize an ACL instance and set `_permissionsCreator` as the entity that can create other permissions
* @param _permissionsCreator Entity that will be given permission over createPermission
*/
function initialize(address _permissionsCreator) public onlyInit {
initialized();
require(msg.sender == address(kernel()), ERROR_AUTH_INIT_KERNEL);
_createPermission(_permissionsCreator, this, CREATE_PERMISSIONS_ROLE, _permissionsCreator);
}
/**
* @dev Creates a permission that wasn't previously set and managed.
* If a created permission is removed it is possible to reset it with createPermission.
* This is the **ONLY** way to create permissions and set managers to permissions that don't
* have a manager.
* In terms of the ACL being initialized, this function implicitly protects all the other
* state-changing external functions, as they all require the sender to be a manager.
* @notice Create a new permission granting `_entity` the ability to perform actions requiring `_role` on `_app`, setting `_manager` as the permission's manager
* @param _entity Address of the whitelisted entity that will be able to perform the role
* @param _app Address of the app in which the role will be allowed (requires app to depend on kernel for ACL)
* @param _role Identifier for the group of actions in app given access to perform
* @param _manager Address of the entity that will be able to grant and revoke the permission further.
*/
function createPermission(address _entity, address _app, bytes32 _role, address _manager)
external
auth(CREATE_PERMISSIONS_ROLE)
noPermissionManager(_app, _role)
{
_createPermission(_entity, _app, _role, _manager);
}
/**
* @dev Grants permission if allowed. This requires `msg.sender` to be the permission manager
* @notice Grant `_entity` the ability to perform actions requiring `_role` on `_app`
* @param _entity Address of the whitelisted entity that will be able to perform the role
* @param _app Address of the app in which the role will be allowed (requires app to depend on kernel for ACL)
* @param _role Identifier for the group of actions in app given access to perform
*/
function grantPermission(address _entity, address _app, bytes32 _role)
external
{
grantPermissionP(_entity, _app, _role, new uint256[](0));
}
/**
* @dev Grants a permission with parameters if allowed. This requires `msg.sender` to be the permission manager
* @notice Grant `_entity` the ability to perform actions requiring `_role` on `_app`
* @param _entity Address of the whitelisted entity that will be able to perform the role
* @param _app Address of the app in which the role will be allowed (requires app to depend on kernel for ACL)
* @param _role Identifier for the group of actions in app given access to perform
* @param _params Permission parameters
*/
function grantPermissionP(address _entity, address _app, bytes32 _role, uint256[] _params)
public
onlyPermissionManager(_app, _role)
{
bytes32 paramsHash = _params.length > 0 ? _saveParams(_params) : EMPTY_PARAM_HASH;
_setPermission(_entity, _app, _role, paramsHash);
}
/**
* @dev Revokes permission if allowed. This requires `msg.sender` to be the the permission manager
* @notice Revoke from `_entity` the ability to perform actions requiring `_role` on `_app`
* @param _entity Address of the whitelisted entity to revoke access from
* @param _app Address of the app in which the role will be revoked
* @param _role Identifier for the group of actions in app being revoked
*/
function revokePermission(address _entity, address _app, bytes32 _role)
external
onlyPermissionManager(_app, _role)
{
_setPermission(_entity, _app, _role, NO_PERMISSION);
}
/**
* @notice Set `_newManager` as the manager of `_role` in `_app`
* @param _newManager Address for the new manager
* @param _app Address of the app in which the permission management is being transferred
* @param _role Identifier for the group of actions being transferred
*/
function setPermissionManager(address _newManager, address _app, bytes32 _role)
external
onlyPermissionManager(_app, _role)
{
_setPermissionManager(_newManager, _app, _role);
}
/**
* @notice Remove the manager of `_role` in `_app`
* @param _app Address of the app in which the permission is being unmanaged
* @param _role Identifier for the group of actions being unmanaged
*/
function removePermissionManager(address _app, bytes32 _role)
external
onlyPermissionManager(_app, _role)
{
_setPermissionManager(address(0), _app, _role);
}
/**
* @notice Burn non-existent `_role` in `_app`, so no modification can be made to it (grant, revoke, permission manager)
* @param _app Address of the app in which the permission is being burned
* @param _role Identifier for the group of actions being burned
*/
function createBurnedPermission(address _app, bytes32 _role)
external
auth(CREATE_PERMISSIONS_ROLE)
noPermissionManager(_app, _role)
{
_setPermissionManager(BURN_ENTITY, _app, _role);
}
/**
* @notice Burn `_role` in `_app`, so no modification can be made to it (grant, revoke, permission manager)
* @param _app Address of the app in which the permission is being burned
* @param _role Identifier for the group of actions being burned
*/
function burnPermissionManager(address _app, bytes32 _role)
external
onlyPermissionManager(_app, _role)
{
_setPermissionManager(BURN_ENTITY, _app, _role);
}
/**
* @notice Get parameters for permission array length
* @param _entity Address of the whitelisted entity that will be able to perform the role
* @param _app Address of the app
* @param _role Identifier for a group of actions in app
* @return Length of the array
*/
function getPermissionParamsLength(address _entity, address _app, bytes32 _role) external view returns (uint) {
return permissionParams[permissions[permissionHash(_entity, _app, _role)]].length;
}
/**
* @notice Get parameter for permission
* @param _entity Address of the whitelisted entity that will be able to perform the role
* @param _app Address of the app
* @param _role Identifier for a group of actions in app
* @param _index Index of parameter in the array
* @return Parameter (id, op, value)
*/
function getPermissionParam(address _entity, address _app, bytes32 _role, uint _index)
external
view
returns (uint8, uint8, uint240)
{
Param storage param = permissionParams[permissions[permissionHash(_entity, _app, _role)]][_index];
return (param.id, param.op, param.value);
}
/**
* @dev Get manager for permission
* @param _app Address of the app
* @param _role Identifier for a group of actions in app
* @return address of the manager for the permission
*/
function getPermissionManager(address _app, bytes32 _role) public view returns (address) {
return permissionManager[roleHash(_app, _role)];
}
/**
* @dev Function called by apps to check ACL on kernel or to check permission statu
* @param _who Sender of the original call
* @param _where Address of the app
* @param _where Identifier for a group of actions in app
* @param _how Permission parameters
* @return boolean indicating whether the ACL allows the role or not
*/
function hasPermission(address _who, address _where, bytes32 _what, bytes memory _how) public view returns (bool) {
return hasPermission(_who, _where, _what, ConversionHelpers.dangerouslyCastBytesToUintArray(_how));
}
function hasPermission(address _who, address _where, bytes32 _what, uint256[] memory _how) public view returns (bool) {
bytes32 whoParams = permissions[permissionHash(_who, _where, _what)];
if (whoParams != NO_PERMISSION && evalParams(whoParams, _who, _where, _what, _how)) {
return true;
}
bytes32 anyParams = permissions[permissionHash(ANY_ENTITY, _where, _what)];
if (anyParams != NO_PERMISSION && evalParams(anyParams, ANY_ENTITY, _where, _what, _how)) {
return true;
}
return false;
}
function hasPermission(address _who, address _where, bytes32 _what) public view returns (bool) {
uint256[] memory empty = new uint256[](0);
return hasPermission(_who, _where, _what, empty);
}
function evalParams(
bytes32 _paramsHash,
address _who,
address _where,
bytes32 _what,
uint256[] _how
) public view returns (bool)
{
if (_paramsHash == EMPTY_PARAM_HASH) {
return true;
}
return _evalParam(_paramsHash, 0, _who, _where, _what, _how);
}
/**
* @dev Internal createPermission for access inside the kernel (on instantiation)
*/
function _createPermission(address _entity, address _app, bytes32 _role, address _manager) internal {
_setPermission(_entity, _app, _role, EMPTY_PARAM_HASH);
_setPermissionManager(_manager, _app, _role);
}
/**
* @dev Internal function called to actually save the permission
*/
function _setPermission(address _entity, address _app, bytes32 _role, bytes32 _paramsHash) internal {
permissions[permissionHash(_entity, _app, _role)] = _paramsHash;
bool entityHasPermission = _paramsHash != NO_PERMISSION;
bool permissionHasParams = entityHasPermission && _paramsHash != EMPTY_PARAM_HASH;
emit SetPermission(_entity, _app, _role, entityHasPermission);
if (permissionHasParams) {
emit SetPermissionParams(_entity, _app, _role, _paramsHash);
}
}
function _saveParams(uint256[] _encodedParams) internal returns (bytes32) {
bytes32 paramHash = keccak256(abi.encodePacked(_encodedParams));
Param[] storage params = permissionParams[paramHash];
if (params.length == 0) { // params not saved before
for (uint256 i = 0; i < _encodedParams.length; i++) {
uint256 encodedParam = _encodedParams[i];
Param memory param = Param(decodeParamId(encodedParam), decodeParamOp(encodedParam), uint240(encodedParam));
params.push(param);
}
}
return paramHash;
}
function _evalParam(
bytes32 _paramsHash,
uint32 _paramId,
address _who,
address _where,
bytes32 _what,
uint256[] _how
) internal view returns (bool)
{
if (_paramId >= permissionParams[_paramsHash].length) {
return false; // out of bounds
}
Param memory param = permissionParams[_paramsHash][_paramId];
if (param.id == LOGIC_OP_PARAM_ID) {
return _evalLogic(param, _paramsHash, _who, _where, _what, _how);
}
uint256 value;
uint256 comparedTo = uint256(param.value);
// get value
if (param.id == ORACLE_PARAM_ID) {
value = checkOracle(IACLOracle(param.value), _who, _where, _what, _how) ? 1 : 0;
comparedTo = 1;
} else if (param.id == BLOCK_NUMBER_PARAM_ID) {
value = getBlockNumber();
} else if (param.id == TIMESTAMP_PARAM_ID) {
value = getTimestamp();
} else if (param.id == PARAM_VALUE_PARAM_ID) {
value = uint256(param.value);
} else {
if (param.id >= _how.length) {
return false;
}
value = uint256(uint240(_how[param.id])); // force lost precision
}
if (Op(param.op) == Op.RET) {
return uint256(value) > 0;
}
return compare(value, Op(param.op), comparedTo);
}
function _evalLogic(Param _param, bytes32 _paramsHash, address _who, address _where, bytes32 _what, uint256[] _how)
internal
view
returns (bool)
{
if (Op(_param.op) == Op.IF_ELSE) {
uint32 conditionParam;
uint32 successParam;
uint32 failureParam;
(conditionParam, successParam, failureParam) = decodeParamsList(uint256(_param.value));
bool result = _evalParam(_paramsHash, conditionParam, _who, _where, _what, _how);
return _evalParam(_paramsHash, result ? successParam : failureParam, _who, _where, _what, _how);
}
uint32 param1;
uint32 param2;
(param1, param2,) = decodeParamsList(uint256(_param.value));
bool r1 = _evalParam(_paramsHash, param1, _who, _where, _what, _how);
if (Op(_param.op) == Op.NOT) {
return !r1;
}
if (r1 && Op(_param.op) == Op.OR) {
return true;
}
if (!r1 && Op(_param.op) == Op.AND) {
return false;
}
bool r2 = _evalParam(_paramsHash, param2, _who, _where, _what, _how);
if (Op(_param.op) == Op.XOR) {
return r1 != r2;
}
return r2; // both or and and depend on result of r2 after checks
}
function compare(uint256 _a, Op _op, uint256 _b) internal pure returns (bool) {
if (_op == Op.EQ) return _a == _b; // solium-disable-line lbrace
if (_op == Op.NEQ) return _a != _b; // solium-disable-line lbrace
if (_op == Op.GT) return _a > _b; // solium-disable-line lbrace
if (_op == Op.LT) return _a < _b; // solium-disable-line lbrace
if (_op == Op.GTE) return _a >= _b; // solium-disable-line lbrace
if (_op == Op.LTE) return _a <= _b; // solium-disable-line lbrace
return false;
}
function checkOracle(IACLOracle _oracleAddr, address _who, address _where, bytes32 _what, uint256[] _how) internal view returns (bool) {
bytes4 sig = _oracleAddr.canPerform.selector;
// a raw call is required so we can return false if the call reverts, rather than reverting
bytes memory checkCalldata = abi.encodeWithSelector(sig, _who, _where, _what, _how);
uint256 oracleCheckGas = ORACLE_CHECK_GAS;
bool ok;
assembly {
ok := staticcall(oracleCheckGas, _oracleAddr, add(checkCalldata, 0x20), mload(checkCalldata), 0, 0)
}
if (!ok) {
return false;
}
uint256 size;
assembly { size := returndatasize }
if (size != 32) {
return false;
}
bool result;
assembly {
let ptr := mload(0x40) // get next free memory ptr
returndatacopy(ptr, 0, size) // copy return from above `staticcall`
result := mload(ptr) // read data at ptr and set it to result
mstore(ptr, 0) // set pointer memory to 0 so it still is the next free ptr
}
return result;
}
/**
* @dev Internal function that sets management
*/
function _setPermissionManager(address _newManager, address _app, bytes32 _role) internal {
permissionManager[roleHash(_app, _role)] = _newManager;
emit ChangePermissionManager(_app, _role, _newManager);
}
function roleHash(address _where, bytes32 _what) internal pure returns (bytes32) {
return keccak256(abi.encodePacked("ROLE", _where, _what));
}
function permissionHash(address _who, address _where, bytes32 _what) internal pure returns (bytes32) {
return keccak256(abi.encodePacked("PERMISSION", _who, _where, _what));
}
}
// File: @aragon/os/contracts/apm/Repo.sol
pragma solidity 0.4.24;
/* solium-disable function-order */
// Allow public initialize() to be first
contract Repo is AragonApp {
/* Hardcoded constants to save gas
bytes32 public constant CREATE_VERSION_ROLE = keccak256("CREATE_VERSION_ROLE");
*/
bytes32 public constant CREATE_VERSION_ROLE = 0x1f56cfecd3595a2e6cc1a7e6cb0b20df84cdbd92eff2fee554e70e4e45a9a7d8;
string private constant ERROR_INVALID_BUMP = "REPO_INVALID_BUMP";
string private constant ERROR_INVALID_VERSION = "REPO_INVALID_VERSION";
string private constant ERROR_INEXISTENT_VERSION = "REPO_INEXISTENT_VERSION";
struct Version {
uint16[3] semanticVersion;
address contractAddress;
bytes contentURI;
}
uint256 internal versionsNextIndex;
mapping (uint256 => Version) internal versions;
mapping (bytes32 => uint256) internal versionIdForSemantic;
mapping (address => uint256) internal latestVersionIdForContract;
event NewVersion(uint256 versionId, uint16[3] semanticVersion);
/**
* @dev Initialize can only be called once. It saves the block number in which it was initialized.
* @notice Initialize this Repo
*/
function initialize() public onlyInit {
initialized();
versionsNextIndex = 1;
}
/**
* @notice Create new version with contract `_contractAddress` and content `@fromHex(_contentURI)`
* @param _newSemanticVersion Semantic version for new repo version
* @param _contractAddress address for smart contract logic for version (if set to 0, it uses last versions' contractAddress)
* @param _contentURI External URI for fetching new version's content
*/
function newVersion(
uint16[3] _newSemanticVersion,
address _contractAddress,
bytes _contentURI
) public auth(CREATE_VERSION_ROLE)
{
address contractAddress = _contractAddress;
uint256 lastVersionIndex = versionsNextIndex - 1;
uint16[3] memory lastSematicVersion;
if (lastVersionIndex > 0) {
Version storage lastVersion = versions[lastVersionIndex];
lastSematicVersion = lastVersion.semanticVersion;
if (contractAddress == address(0)) {
contractAddress = lastVersion.contractAddress;
}
// Only allows smart contract change on major version bumps
require(
lastVersion.contractAddress == contractAddress || _newSemanticVersion[0] > lastVersion.semanticVersion[0],
ERROR_INVALID_VERSION
);
}
require(isValidBump(lastSematicVersion, _newSemanticVersion), ERROR_INVALID_BUMP);
uint256 versionId = versionsNextIndex++;
versions[versionId] = Version(_newSemanticVersion, contractAddress, _contentURI);
versionIdForSemantic[semanticVersionHash(_newSemanticVersion)] = versionId;
latestVersionIdForContract[contractAddress] = versionId;
emit NewVersion(versionId, _newSemanticVersion);
}
function getLatest() public view returns (uint16[3] semanticVersion, address contractAddress, bytes contentURI) {
return getByVersionId(versionsNextIndex - 1);
}
function getLatestForContractAddress(address _contractAddress)
public
view
returns (uint16[3] semanticVersion, address contractAddress, bytes contentURI)
{
return getByVersionId(latestVersionIdForContract[_contractAddress]);
}
function getBySemanticVersion(uint16[3] _semanticVersion)
public
view
returns (uint16[3] semanticVersion, address contractAddress, bytes contentURI)
{
return getByVersionId(versionIdForSemantic[semanticVersionHash(_semanticVersion)]);
}
function getByVersionId(uint _versionId) public view returns (uint16[3] semanticVersion, address contractAddress, bytes contentURI) {
require(_versionId > 0 && _versionId < versionsNextIndex, ERROR_INEXISTENT_VERSION);
Version storage version = versions[_versionId];
return (version.semanticVersion, version.contractAddress, version.contentURI);
}
function getVersionsCount() public view returns (uint256) {
return versionsNextIndex - 1;
}
function isValidBump(uint16[3] _oldVersion, uint16[3] _newVersion) public pure returns (bool) {
bool hasBumped;
uint i = 0;
while (i < 3) {
if (hasBumped) {
if (_newVersion[i] != 0) {
return false;
}
} else if (_newVersion[i] != _oldVersion[i]) {
if (_oldVersion[i] > _newVersion[i] || _newVersion[i] - _oldVersion[i] != 1) {
return false;
}
hasBumped = true;
}
i++;
}
return hasBumped;
}
function semanticVersionHash(uint16[3] version) internal pure returns (bytes32) {
return keccak256(abi.encodePacked(version[0], version[1], version[2]));
}
}
// File: @aragon/os/contracts/apm/APMNamehash.sol
/*
* SPDX-License-Identitifer: MIT
*/
pragma solidity ^0.4.24;
contract APMNamehash {
/* Hardcoded constants to save gas
bytes32 internal constant APM_NODE = keccak256(abi.encodePacked(ETH_TLD_NODE, keccak256(abi.encodePacked("aragonpm"))));
*/
bytes32 internal constant APM_NODE = 0x9065c3e7f7b7ef1ef4e53d2d0b8e0cef02874ab020c1ece79d5f0d3d0111c0ba;
function apmNamehash(string name) internal pure returns (bytes32) {
return keccak256(abi.encodePacked(APM_NODE, keccak256(bytes(name))));
}
}
// File: @aragon/os/contracts/kernel/KernelStorage.sol
pragma solidity 0.4.24;
contract KernelStorage {
// namespace => app id => address
mapping (bytes32 => mapping (bytes32 => address)) public apps;
bytes32 public recoveryVaultAppId;
}
// File: @aragon/os/contracts/lib/misc/ERCProxy.sol
/*
* SPDX-License-Identitifer: MIT
*/
pragma solidity ^0.4.24;
contract ERCProxy {
uint256 internal constant FORWARDING = 1;
uint256 internal constant UPGRADEABLE = 2;
function proxyType() public pure returns (uint256 proxyTypeId);
function implementation() public view returns (address codeAddr);
}
// File: @aragon/os/contracts/common/DelegateProxy.sol
pragma solidity 0.4.24;
contract DelegateProxy is ERCProxy, IsContract {
uint256 internal constant FWD_GAS_LIMIT = 10000;
/**
* @dev Performs a delegatecall and returns whatever the delegatecall returned (entire context execution will return!)
* @param _dst Destination address to perform the delegatecall
* @param _calldata Calldata for the delegatecall
*/
function delegatedFwd(address _dst, bytes _calldata) internal {
require(isContract(_dst));
uint256 fwdGasLimit = FWD_GAS_LIMIT;
assembly {
let result := delegatecall(sub(gas, fwdGasLimit), _dst, add(_calldata, 0x20), mload(_calldata), 0, 0)
let size := returndatasize
let ptr := mload(0x40)
returndatacopy(ptr, 0, size)
// revert instead of invalid() bc if the underlying call failed with invalid() it already wasted gas.
// if the call returned error data, forward it
switch result case 0 { revert(ptr, size) }
default { return(ptr, size) }
}
}
}
// File: @aragon/os/contracts/common/DepositableDelegateProxy.sol
pragma solidity 0.4.24;
contract DepositableDelegateProxy is DepositableStorage, DelegateProxy {
event ProxyDeposit(address sender, uint256 value);
function () external payable {
// send / transfer
if (gasleft() < FWD_GAS_LIMIT) {
require(msg.value > 0 && msg.data.length == 0);
require(isDepositable());
emit ProxyDeposit(msg.sender, msg.value);
} else { // all calls except for send or transfer
address target = implementation();
delegatedFwd(target, msg.data);
}
}
}
// File: @aragon/os/contracts/apps/AppProxyBase.sol
pragma solidity 0.4.24;
contract AppProxyBase is AppStorage, DepositableDelegateProxy, KernelNamespaceConstants {
/**
* @dev Initialize AppProxy
* @param _kernel Reference to organization kernel for the app
* @param _appId Identifier for app
* @param _initializePayload Payload for call to be made after setup to initialize
*/
constructor(IKernel _kernel, bytes32 _appId, bytes _initializePayload) public {
setKernel(_kernel);
setAppId(_appId);
// Implicit check that kernel is actually a Kernel
// The EVM doesn't actually provide a way for us to make sure, but we can force a revert to
// occur if the kernel is set to 0x0 or a non-code address when we try to call a method on
// it.
address appCode = getAppBase(_appId);
// If initialize payload is provided, it will be executed
if (_initializePayload.length > 0) {
require(isContract(appCode));
// Cannot make delegatecall as a delegateproxy.delegatedFwd as it
// returns ending execution context and halts contract deployment
require(appCode.delegatecall(_initializePayload));
}
}
function getAppBase(bytes32 _appId) internal view returns (address) {
return kernel().getApp(KERNEL_APP_BASES_NAMESPACE, _appId);
}
}
// File: @aragon/os/contracts/apps/AppProxyUpgradeable.sol
pragma solidity 0.4.24;
contract AppProxyUpgradeable is AppProxyBase {
/**
* @dev Initialize AppProxyUpgradeable (makes it an upgradeable Aragon app)
* @param _kernel Reference to organization kernel for the app
* @param _appId Identifier for app
* @param _initializePayload Payload for call to be made after setup to initialize
*/
constructor(IKernel _kernel, bytes32 _appId, bytes _initializePayload)
AppProxyBase(_kernel, _appId, _initializePayload)
public // solium-disable-line visibility-first
{
// solium-disable-previous-line no-empty-blocks
}
/**
* @dev ERC897, the address the proxy would delegate calls to
*/
function implementation() public view returns (address) {
return getAppBase(appId());
}
/**
* @dev ERC897, whether it is a forwarding (1) or an upgradeable (2) proxy
*/
function proxyType() public pure returns (uint256 proxyTypeId) {
return UPGRADEABLE;
}
}
// File: @aragon/os/contracts/apps/AppProxyPinned.sol
pragma solidity 0.4.24;
contract AppProxyPinned is IsContract, AppProxyBase {
using UnstructuredStorage for bytes32;
// keccak256("aragonOS.appStorage.pinnedCode")
bytes32 internal constant PINNED_CODE_POSITION = 0xdee64df20d65e53d7f51cb6ab6d921a0a6a638a91e942e1d8d02df28e31c038e;
/**
* @dev Initialize AppProxyPinned (makes it an un-upgradeable Aragon app)
* @param _kernel Reference to organization kernel for the app
* @param _appId Identifier for app
* @param _initializePayload Payload for call to be made after setup to initialize
*/
constructor(IKernel _kernel, bytes32 _appId, bytes _initializePayload)
AppProxyBase(_kernel, _appId, _initializePayload)
public // solium-disable-line visibility-first
{
setPinnedCode(getAppBase(_appId));
require(isContract(pinnedCode()));
}
/**
* @dev ERC897, the address the proxy would delegate calls to
*/
function implementation() public view returns (address) {
return pinnedCode();
}
/**
* @dev ERC897, whether it is a forwarding (1) or an upgradeable (2) proxy
*/
function proxyType() public pure returns (uint256 proxyTypeId) {
return FORWARDING;
}
function setPinnedCode(address _pinnedCode) internal {
PINNED_CODE_POSITION.setStorageAddress(_pinnedCode);
}
function pinnedCode() internal view returns (address) {
return PINNED_CODE_POSITION.getStorageAddress();
}
}
// File: @aragon/os/contracts/factory/AppProxyFactory.sol
pragma solidity 0.4.24;
contract AppProxyFactory {
event NewAppProxy(address proxy, bool isUpgradeable, bytes32 appId);
/**
* @notice Create a new upgradeable app instance on `_kernel` with identifier `_appId`
* @param _kernel App's Kernel reference
* @param _appId Identifier for app
* @return AppProxyUpgradeable
*/
function newAppProxy(IKernel _kernel, bytes32 _appId) public returns (AppProxyUpgradeable) {
return newAppProxy(_kernel, _appId, new bytes(0));
}
/**
* @notice Create a new upgradeable app instance on `_kernel` with identifier `_appId` and initialization payload `_initializePayload`
* @param _kernel App's Kernel reference
* @param _appId Identifier for app
* @return AppProxyUpgradeable
*/
function newAppProxy(IKernel _kernel, bytes32 _appId, bytes _initializePayload) public returns (AppProxyUpgradeable) {
AppProxyUpgradeable proxy = new AppProxyUpgradeable(_kernel, _appId, _initializePayload);
emit NewAppProxy(address(proxy), true, _appId);
return proxy;
}
/**
* @notice Create a new pinned app instance on `_kernel` with identifier `_appId`
* @param _kernel App's Kernel reference
* @param _appId Identifier for app
* @return AppProxyPinned
*/
function newAppProxyPinned(IKernel _kernel, bytes32 _appId) public returns (AppProxyPinned) {
return newAppProxyPinned(_kernel, _appId, new bytes(0));
}
/**
* @notice Create a new pinned app instance on `_kernel` with identifier `_appId` and initialization payload `_initializePayload`
* @param _kernel App's Kernel reference
* @param _appId Identifier for app
* @param _initializePayload Proxy initialization payload
* @return AppProxyPinned
*/
function newAppProxyPinned(IKernel _kernel, bytes32 _appId, bytes _initializePayload) public returns (AppProxyPinned) {
AppProxyPinned proxy = new AppProxyPinned(_kernel, _appId, _initializePayload);
emit NewAppProxy(address(proxy), false, _appId);
return proxy;
}
}
// File: @aragon/os/contracts/kernel/Kernel.sol
pragma solidity 0.4.24;
// solium-disable-next-line max-len
contract Kernel is IKernel, KernelStorage, KernelAppIds, KernelNamespaceConstants, Petrifiable, IsContract, VaultRecoverable, AppProxyFactory, ACLSyntaxSugar {
/* Hardcoded constants to save gas
bytes32 public constant APP_MANAGER_ROLE = keccak256("APP_MANAGER_ROLE");
*/
bytes32 public constant APP_MANAGER_ROLE = 0xb6d92708f3d4817afc106147d969e229ced5c46e65e0a5002a0d391287762bd0;
string private constant ERROR_APP_NOT_CONTRACT = "KERNEL_APP_NOT_CONTRACT";
string private constant ERROR_INVALID_APP_CHANGE = "KERNEL_INVALID_APP_CHANGE";
string private constant ERROR_AUTH_FAILED = "KERNEL_AUTH_FAILED";
/**
* @dev Constructor that allows the deployer to choose if the base instance should be petrified immediately.
* @param _shouldPetrify Immediately petrify this instance so that it can never be initialized
*/
constructor(bool _shouldPetrify) public {
if (_shouldPetrify) {
petrify();
}
}
/**
* @dev Initialize can only be called once. It saves the block number in which it was initialized.
* @notice Initialize this kernel instance along with its ACL and set `_permissionsCreator` as the entity that can create other permissions
* @param _baseAcl Address of base ACL app
* @param _permissionsCreator Entity that will be given permission over createPermission
*/
function initialize(IACL _baseAcl, address _permissionsCreator) public onlyInit {
initialized();
// Set ACL base
_setApp(KERNEL_APP_BASES_NAMESPACE, KERNEL_DEFAULT_ACL_APP_ID, _baseAcl);
// Create ACL instance and attach it as the default ACL app
IACL acl = IACL(newAppProxy(this, KERNEL_DEFAULT_ACL_APP_ID));
acl.initialize(_permissionsCreator);
_setApp(KERNEL_APP_ADDR_NAMESPACE, KERNEL_DEFAULT_ACL_APP_ID, acl);
recoveryVaultAppId = KERNEL_DEFAULT_VAULT_APP_ID;
}
/**
* @dev Create a new instance of an app linked to this kernel
* @notice Create a new upgradeable instance of `_appId` app linked to the Kernel, setting its code to `_appBase`
* @param _appId Identifier for app
* @param _appBase Address of the app's base implementation
* @return AppProxy instance
*/
function newAppInstance(bytes32 _appId, address _appBase)
public
auth(APP_MANAGER_ROLE, arr(KERNEL_APP_BASES_NAMESPACE, _appId))
returns (ERCProxy appProxy)
{
return newAppInstance(_appId, _appBase, new bytes(0), false);
}
/**
* @dev Create a new instance of an app linked to this kernel and set its base
* implementation if it was not already set
* @notice Create a new upgradeable instance of `_appId` app linked to the Kernel, setting its code to `_appBase`. `_setDefault ? 'Also sets it as the default app instance.':''`
* @param _appId Identifier for app
* @param _appBase Address of the app's base implementation
* @param _initializePayload Payload for call made by the proxy during its construction to initialize
* @param _setDefault Whether the app proxy app is the default one.
* Useful when the Kernel needs to know of an instance of a particular app,
* like Vault for escape hatch mechanism.
* @return AppProxy instance
*/
function newAppInstance(bytes32 _appId, address _appBase, bytes _initializePayload, bool _setDefault)
public
auth(APP_MANAGER_ROLE, arr(KERNEL_APP_BASES_NAMESPACE, _appId))
returns (ERCProxy appProxy)
{
_setAppIfNew(KERNEL_APP_BASES_NAMESPACE, _appId, _appBase);
appProxy = newAppProxy(this, _appId, _initializePayload);
// By calling setApp directly and not the internal functions, we make sure the params are checked
// and it will only succeed if sender has permissions to set something to the namespace.
if (_setDefault) {
setApp(KERNEL_APP_ADDR_NAMESPACE, _appId, appProxy);
}
}
/**
* @dev Create a new pinned instance of an app linked to this kernel
* @notice Create a new non-upgradeable instance of `_appId` app linked to the Kernel, setting its code to `_appBase`.
* @param _appId Identifier for app
* @param _appBase Address of the app's base implementation
* @return AppProxy instance
*/
function newPinnedAppInstance(bytes32 _appId, address _appBase)
public
auth(APP_MANAGER_ROLE, arr(KERNEL_APP_BASES_NAMESPACE, _appId))
returns (ERCProxy appProxy)
{
return newPinnedAppInstance(_appId, _appBase, new bytes(0), false);
}
/**
* @dev Create a new pinned instance of an app linked to this kernel and set
* its base implementation if it was not already set
* @notice Create a new non-upgradeable instance of `_appId` app linked to the Kernel, setting its code to `_appBase`. `_setDefault ? 'Also sets it as the default app instance.':''`
* @param _appId Identifier for app
* @param _appBase Address of the app's base implementation
* @param _initializePayload Payload for call made by the proxy during its construction to initialize
* @param _setDefault Whether the app proxy app is the default one.
* Useful when the Kernel needs to know of an instance of a particular app,
* like Vault for escape hatch mechanism.
* @return AppProxy instance
*/
function newPinnedAppInstance(bytes32 _appId, address _appBase, bytes _initializePayload, bool _setDefault)
public
auth(APP_MANAGER_ROLE, arr(KERNEL_APP_BASES_NAMESPACE, _appId))
returns (ERCProxy appProxy)
{
_setAppIfNew(KERNEL_APP_BASES_NAMESPACE, _appId, _appBase);
appProxy = newAppProxyPinned(this, _appId, _initializePayload);
// By calling setApp directly and not the internal functions, we make sure the params are checked
// and it will only succeed if sender has permissions to set something to the namespace.
if (_setDefault) {
setApp(KERNEL_APP_ADDR_NAMESPACE, _appId, appProxy);
}
}
/**
* @dev Set the resolving address of an app instance or base implementation
* @notice Set the resolving address of `_appId` in namespace `_namespace` to `_app`
* @param _namespace App namespace to use
* @param _appId Identifier for app
* @param _app Address of the app instance or base implementation
* @return ID of app
*/
function setApp(bytes32 _namespace, bytes32 _appId, address _app)
public
auth(APP_MANAGER_ROLE, arr(_namespace, _appId))
{
_setApp(_namespace, _appId, _app);
}
/**
* @dev Set the default vault id for the escape hatch mechanism
* @param _recoveryVaultAppId Identifier of the recovery vault app
*/
function setRecoveryVaultAppId(bytes32 _recoveryVaultAppId)
public
auth(APP_MANAGER_ROLE, arr(KERNEL_APP_ADDR_NAMESPACE, _recoveryVaultAppId))
{
recoveryVaultAppId = _recoveryVaultAppId;
}
// External access to default app id and namespace constants to mimic default getters for constants
/* solium-disable function-order, mixedcase */
function CORE_NAMESPACE() external pure returns (bytes32) { return KERNEL_CORE_NAMESPACE; }
function APP_BASES_NAMESPACE() external pure returns (bytes32) { return KERNEL_APP_BASES_NAMESPACE; }
function APP_ADDR_NAMESPACE() external pure returns (bytes32) { return KERNEL_APP_ADDR_NAMESPACE; }
function KERNEL_APP_ID() external pure returns (bytes32) { return KERNEL_CORE_APP_ID; }
function DEFAULT_ACL_APP_ID() external pure returns (bytes32) { return KERNEL_DEFAULT_ACL_APP_ID; }
/* solium-enable function-order, mixedcase */
/**
* @dev Get the address of an app instance or base implementation
* @param _namespace App namespace to use
* @param _appId Identifier for app
* @return Address of the app
*/
function getApp(bytes32 _namespace, bytes32 _appId) public view returns (address) {
return apps[_namespace][_appId];
}
/**
* @dev Get the address of the recovery Vault instance (to recover funds)
* @return Address of the Vault
*/
function getRecoveryVault() public view returns (address) {
return apps[KERNEL_APP_ADDR_NAMESPACE][recoveryVaultAppId];
}
/**
* @dev Get the installed ACL app
* @return ACL app
*/
function acl() public view returns (IACL) {
return IACL(getApp(KERNEL_APP_ADDR_NAMESPACE, KERNEL_DEFAULT_ACL_APP_ID));
}
/**
* @dev Function called by apps to check ACL on kernel or to check permission status
* @param _who Sender of the original call
* @param _where Address of the app
* @param _what Identifier for a group of actions in app
* @param _how Extra data for ACL auth
* @return Boolean indicating whether the ACL allows the role or not.
* Always returns false if the kernel hasn't been initialized yet.
*/
function hasPermission(address _who, address _where, bytes32 _what, bytes _how) public view returns (bool) {
IACL defaultAcl = acl();
return address(defaultAcl) != address(0) && // Poor man's initialization check (saves gas)
defaultAcl.hasPermission(_who, _where, _what, _how);
}
function _setApp(bytes32 _namespace, bytes32 _appId, address _app) internal {
require(isContract(_app), ERROR_APP_NOT_CONTRACT);
apps[_namespace][_appId] = _app;
emit SetApp(_namespace, _appId, _app);
}
function _setAppIfNew(bytes32 _namespace, bytes32 _appId, address _app) internal {
address app = getApp(_namespace, _appId);
if (app != address(0)) {
// The only way to set an app is if it passes the isContract check, so no need to check it again
require(app == _app, ERROR_INVALID_APP_CHANGE);
} else {
_setApp(_namespace, _appId, _app);
}
}
modifier auth(bytes32 _role, uint256[] memory _params) {
require(
hasPermission(msg.sender, address(this), _role, ConversionHelpers.dangerouslyCastUintArrayToBytes(_params)),
ERROR_AUTH_FAILED
);
_;
}
}
// File: @aragon/os/contracts/lib/ens/AbstractENS.sol
// See https://github.com/ensdomains/ens/blob/7e377df83f/contracts/AbstractENS.sol
pragma solidity ^0.4.15;
interface AbstractENS {
function owner(bytes32 _node) public constant returns (address);
function resolver(bytes32 _node) public constant returns (address);
function ttl(bytes32 _node) public constant returns (uint64);
function setOwner(bytes32 _node, address _owner) public;
function setSubnodeOwner(bytes32 _node, bytes32 label, address _owner) public;
function setResolver(bytes32 _node, address _resolver) public;
function setTTL(bytes32 _node, uint64 _ttl) public;
// Logged when the owner of a node assigns a new owner to a subnode.
event NewOwner(bytes32 indexed _node, bytes32 indexed _label, address _owner);
// Logged when the owner of a node transfers ownership to a new account.
event Transfer(bytes32 indexed _node, address _owner);
// Logged when the resolver for a node changes.
event NewResolver(bytes32 indexed _node, address _resolver);
// Logged when the TTL of a node changes
event NewTTL(bytes32 indexed _node, uint64 _ttl);
}
// File: @aragon/os/contracts/lib/ens/ENS.sol
// See https://github.com/ensdomains/ens/blob/7e377df83f/contracts/ENS.sol
pragma solidity ^0.4.0;
/**
* The ENS registry contract.
*/
contract ENS is AbstractENS {
struct Record {
address owner;
address resolver;
uint64 ttl;
}
mapping(bytes32=>Record) records;
// Permits modifications only by the owner of the specified node.
modifier only_owner(bytes32 node) {
if (records[node].owner != msg.sender) throw;
_;
}
/**
* Constructs a new ENS registrar.
*/
function ENS() public {
records[0].owner = msg.sender;
}
/**
* Returns the address that owns the specified node.
*/
function owner(bytes32 node) public constant returns (address) {
return records[node].owner;
}
/**
* Returns the address of the resolver for the specified node.
*/
function resolver(bytes32 node) public constant returns (address) {
return records[node].resolver;
}
/**
* Returns the TTL of a node, and any records associated with it.
*/
function ttl(bytes32 node) public constant returns (uint64) {
return records[node].ttl;
}
/**
* Transfers ownership of a node to a new address. May only be called by the current
* owner of the node.
* @param node The node to transfer ownership of.
* @param owner The address of the new owner.
*/
function setOwner(bytes32 node, address owner) only_owner(node) public {
Transfer(node, owner);
records[node].owner = owner;
}
/**
* Transfers ownership of a subnode keccak256(node, label) to a new address. May only be
* called by the owner of the parent node.
* @param node The parent node.
* @param label The hash of the label specifying the subnode.
* @param owner The address of the new owner.
*/
function setSubnodeOwner(bytes32 node, bytes32 label, address owner) only_owner(node) public {
var subnode = keccak256(node, label);
NewOwner(node, label, owner);
records[subnode].owner = owner;
}
/**
* Sets the resolver address for the specified node.
* @param node The node to update.
* @param resolver The address of the resolver.
*/
function setResolver(bytes32 node, address resolver) only_owner(node) public {
NewResolver(node, resolver);
records[node].resolver = resolver;
}
/**
* Sets the TTL for the specified node.
* @param node The node to update.
* @param ttl The TTL in seconds.
*/
function setTTL(bytes32 node, uint64 ttl) only_owner(node) public {
NewTTL(node, ttl);
records[node].ttl = ttl;
}
}
// File: @aragon/os/contracts/lib/ens/PublicResolver.sol
// See https://github.com/ensdomains/ens/blob/7e377df83f/contracts/PublicResolver.sol
pragma solidity ^0.4.0;
/**
* A simple resolver anyone can use; only allows the owner of a node to set its
* address.
*/
contract PublicResolver {
bytes4 constant INTERFACE_META_ID = 0x01ffc9a7;
bytes4 constant ADDR_INTERFACE_ID = 0x3b3b57de;
bytes4 constant CONTENT_INTERFACE_ID = 0xd8389dc5;
bytes4 constant NAME_INTERFACE_ID = 0x691f3431;
bytes4 constant ABI_INTERFACE_ID = 0x2203ab56;
bytes4 constant PUBKEY_INTERFACE_ID = 0xc8690233;
bytes4 constant TEXT_INTERFACE_ID = 0x59d1d43c;
event AddrChanged(bytes32 indexed node, address a);
event ContentChanged(bytes32 indexed node, bytes32 hash);
event NameChanged(bytes32 indexed node, string name);
event ABIChanged(bytes32 indexed node, uint256 indexed contentType);
event PubkeyChanged(bytes32 indexed node, bytes32 x, bytes32 y);
event TextChanged(bytes32 indexed node, string indexed indexedKey, string key);
struct PublicKey {
bytes32 x;
bytes32 y;
}
struct Record {
address addr;
bytes32 content;
string name;
PublicKey pubkey;
mapping(string=>string) text;
mapping(uint256=>bytes) abis;
}
AbstractENS ens;
mapping(bytes32=>Record) records;
modifier only_owner(bytes32 node) {
if (ens.owner(node) != msg.sender) throw;
_;
}
/**
* Constructor.
* @param ensAddr The ENS registrar contract.
*/
function PublicResolver(AbstractENS ensAddr) public {
ens = ensAddr;
}
/**
* Returns true if the resolver implements the interface specified by the provided hash.
* @param interfaceID The ID of the interface to check for.
* @return True if the contract implements the requested interface.
*/
function supportsInterface(bytes4 interfaceID) public pure returns (bool) {
return interfaceID == ADDR_INTERFACE_ID ||
interfaceID == CONTENT_INTERFACE_ID ||
interfaceID == NAME_INTERFACE_ID ||
interfaceID == ABI_INTERFACE_ID ||
interfaceID == PUBKEY_INTERFACE_ID ||
interfaceID == TEXT_INTERFACE_ID ||
interfaceID == INTERFACE_META_ID;
}
/**
* Returns the address associated with an ENS node.
* @param node The ENS node to query.
* @return The associated address.
*/
function addr(bytes32 node) public constant returns (address ret) {
ret = records[node].addr;
}
/**
* Sets the address associated with an ENS node.
* May only be called by the owner of that node in the ENS registry.
* @param node The node to update.
* @param addr The address to set.
*/
function setAddr(bytes32 node, address addr) only_owner(node) public {
records[node].addr = addr;
AddrChanged(node, addr);
}
/**
* Returns the content hash associated with an ENS node.
* Note that this resource type is not standardized, and will likely change
* in future to a resource type based on multihash.
* @param node The ENS node to query.
* @return The associated content hash.
*/
function content(bytes32 node) public constant returns (bytes32 ret) {
ret = records[node].content;
}
/**
* Sets the content hash associated with an ENS node.
* May only be called by the owner of that node in the ENS registry.
* Note that this resource type is not standardized, and will likely change
* in future to a resource type based on multihash.
* @param node The node to update.
* @param hash The content hash to set
*/
function setContent(bytes32 node, bytes32 hash) only_owner(node) public {
records[node].content = hash;
ContentChanged(node, hash);
}
/**
* Returns the name associated with an ENS node, for reverse records.
* Defined in EIP181.
* @param node The ENS node to query.
* @return The associated name.
*/
function name(bytes32 node) public constant returns (string ret) {
ret = records[node].name;
}
/**
* Sets the name associated with an ENS node, for reverse records.
* May only be called by the owner of that node in the ENS registry.
* @param node The node to update.
* @param name The name to set.
*/
function setName(bytes32 node, string name) only_owner(node) public {
records[node].name = name;
NameChanged(node, name);
}
/**
* Returns the ABI associated with an ENS node.
* Defined in EIP205.
* @param node The ENS node to query
* @param contentTypes A bitwise OR of the ABI formats accepted by the caller.
* @return contentType The content type of the return value
* @return data The ABI data
*/
function ABI(bytes32 node, uint256 contentTypes) public constant returns (uint256 contentType, bytes data) {
var record = records[node];
for(contentType = 1; contentType <= contentTypes; contentType <<= 1) {
if ((contentType & contentTypes) != 0 && record.abis[contentType].length > 0) {
data = record.abis[contentType];
return;
}
}
contentType = 0;
}
/**
* Sets the ABI associated with an ENS node.
* Nodes may have one ABI of each content type. To remove an ABI, set it to
* the empty string.
* @param node The node to update.
* @param contentType The content type of the ABI
* @param data The ABI data.
*/
function setABI(bytes32 node, uint256 contentType, bytes data) only_owner(node) public {
// Content types must be powers of 2
if (((contentType - 1) & contentType) != 0) throw;
records[node].abis[contentType] = data;
ABIChanged(node, contentType);
}
/**
* Returns the SECP256k1 public key associated with an ENS node.
* Defined in EIP 619.
* @param node The ENS node to query
* @return x, y the X and Y coordinates of the curve point for the public key.
*/
function pubkey(bytes32 node) public constant returns (bytes32 x, bytes32 y) {
return (records[node].pubkey.x, records[node].pubkey.y);
}
/**
* Sets the SECP256k1 public key associated with an ENS node.
* @param node The ENS node to query
* @param x the X coordinate of the curve point for the public key.
* @param y the Y coordinate of the curve point for the public key.
*/
function setPubkey(bytes32 node, bytes32 x, bytes32 y) only_owner(node) public {
records[node].pubkey = PublicKey(x, y);
PubkeyChanged(node, x, y);
}
/**
* Returns the text data associated with an ENS node and key.
* @param node The ENS node to query.
* @param key The text data key to query.
* @return The associated text data.
*/
function text(bytes32 node, string key) public constant returns (string ret) {
ret = records[node].text[key];
}
/**
* Sets the text data associated with an ENS node and key.
* May only be called by the owner of that node in the ENS registry.
* @param node The node to update.
* @param key The key to set.
* @param value The text data value to set.
*/
function setText(bytes32 node, string key, string value) only_owner(node) public {
records[node].text[key] = value;
TextChanged(node, key, key);
}
}
// File: @aragon/os/contracts/kernel/KernelProxy.sol
pragma solidity 0.4.24;
contract KernelProxy is IKernelEvents, KernelStorage, KernelAppIds, KernelNamespaceConstants, IsContract, DepositableDelegateProxy {
/**
* @dev KernelProxy is a proxy contract to a kernel implementation. The implementation
* can update the reference, which effectively upgrades the contract
* @param _kernelImpl Address of the contract used as implementation for kernel
*/
constructor(IKernel _kernelImpl) public {
require(isContract(address(_kernelImpl)));
apps[KERNEL_CORE_NAMESPACE][KERNEL_CORE_APP_ID] = _kernelImpl;
// Note that emitting this event is important for verifying that a KernelProxy instance
// was never upgraded to a malicious Kernel logic contract over its lifespan.
// This starts the "chain of trust", that can be followed through later SetApp() events
// emitted during kernel upgrades.
emit SetApp(KERNEL_CORE_NAMESPACE, KERNEL_CORE_APP_ID, _kernelImpl);
}
/**
* @dev ERC897, whether it is a forwarding (1) or an upgradeable (2) proxy
*/
function proxyType() public pure returns (uint256 proxyTypeId) {
return UPGRADEABLE;
}
/**
* @dev ERC897, the address the proxy would delegate calls to
*/
function implementation() public view returns (address) {
return apps[KERNEL_CORE_NAMESPACE][KERNEL_CORE_APP_ID];
}
}
// File: @aragon/os/contracts/evmscript/ScriptHelpers.sol
/*
* SPDX-License-Identitifer: MIT
*/
pragma solidity ^0.4.24;
library ScriptHelpers {
function getSpecId(bytes _script) internal pure returns (uint32) {
return uint32At(_script, 0);
}
function uint256At(bytes _data, uint256 _location) internal pure returns (uint256 result) {
assembly {
result := mload(add(_data, add(0x20, _location)))
}
}
function addressAt(bytes _data, uint256 _location) internal pure returns (address result) {
uint256 word = uint256At(_data, _location);
assembly {
result := div(and(word, 0xffffffffffffffffffffffffffffffffffffffff000000000000000000000000),
0x1000000000000000000000000)
}
}
function uint32At(bytes _data, uint256 _location) internal pure returns (uint32 result) {
uint256 word = uint256At(_data, _location);
assembly {
result := div(and(word, 0xffffffff00000000000000000000000000000000000000000000000000000000),
0x100000000000000000000000000000000000000000000000000000000)
}
}
function locationOf(bytes _data, uint256 _location) internal pure returns (uint256 result) {
assembly {
result := add(_data, add(0x20, _location))
}
}
function toBytes(bytes4 _sig) internal pure returns (bytes) {
bytes memory payload = new bytes(4);
assembly { mstore(add(payload, 0x20), _sig) }
return payload;
}
}
// File: @aragon/os/contracts/evmscript/EVMScriptRegistry.sol
pragma solidity 0.4.24;
/* solium-disable function-order */
// Allow public initialize() to be first
contract EVMScriptRegistry is IEVMScriptRegistry, EVMScriptRegistryConstants, AragonApp {
using ScriptHelpers for bytes;
/* Hardcoded constants to save gas
bytes32 public constant REGISTRY_ADD_EXECUTOR_ROLE = keccak256("REGISTRY_ADD_EXECUTOR_ROLE");
bytes32 public constant REGISTRY_MANAGER_ROLE = keccak256("REGISTRY_MANAGER_ROLE");
*/
bytes32 public constant REGISTRY_ADD_EXECUTOR_ROLE = 0xc4e90f38eea8c4212a009ca7b8947943ba4d4a58d19b683417f65291d1cd9ed2;
// WARN: Manager can censor all votes and the like happening in an org
bytes32 public constant REGISTRY_MANAGER_ROLE = 0xf7a450ef335e1892cb42c8ca72e7242359d7711924b75db5717410da3f614aa3;
uint256 internal constant SCRIPT_START_LOCATION = 4;
string private constant ERROR_INEXISTENT_EXECUTOR = "EVMREG_INEXISTENT_EXECUTOR";
string private constant ERROR_EXECUTOR_ENABLED = "EVMREG_EXECUTOR_ENABLED";
string private constant ERROR_EXECUTOR_DISABLED = "EVMREG_EXECUTOR_DISABLED";
string private constant ERROR_SCRIPT_LENGTH_TOO_SHORT = "EVMREG_SCRIPT_LENGTH_TOO_SHORT";
struct ExecutorEntry {
IEVMScriptExecutor executor;
bool enabled;
}
uint256 private executorsNextIndex;
mapping (uint256 => ExecutorEntry) public executors;
event EnableExecutor(uint256 indexed executorId, address indexed executorAddress);
event DisableExecutor(uint256 indexed executorId, address indexed executorAddress);
modifier executorExists(uint256 _executorId) {
require(_executorId > 0 && _executorId < executorsNextIndex, ERROR_INEXISTENT_EXECUTOR);
_;
}
/**
* @notice Initialize the registry
*/
function initialize() public onlyInit {
initialized();
// Create empty record to begin executor IDs at 1
executorsNextIndex = 1;
}
/**
* @notice Add a new script executor with address `_executor` to the registry
* @param _executor Address of the IEVMScriptExecutor that will be added to the registry
* @return id Identifier of the executor in the registry
*/
function addScriptExecutor(IEVMScriptExecutor _executor) external auth(REGISTRY_ADD_EXECUTOR_ROLE) returns (uint256 id) {
uint256 executorId = executorsNextIndex++;
executors[executorId] = ExecutorEntry(_executor, true);
emit EnableExecutor(executorId, _executor);
return executorId;
}
/**
* @notice Disable script executor with ID `_executorId`
* @param _executorId Identifier of the executor in the registry
*/
function disableScriptExecutor(uint256 _executorId)
external
authP(REGISTRY_MANAGER_ROLE, arr(_executorId))
{
// Note that we don't need to check for an executor's existence in this case, as only
// existing executors can be enabled
ExecutorEntry storage executorEntry = executors[_executorId];
require(executorEntry.enabled, ERROR_EXECUTOR_DISABLED);
executorEntry.enabled = false;
emit DisableExecutor(_executorId, executorEntry.executor);
}
/**
* @notice Enable script executor with ID `_executorId`
* @param _executorId Identifier of the executor in the registry
*/
function enableScriptExecutor(uint256 _executorId)
external
authP(REGISTRY_MANAGER_ROLE, arr(_executorId))
executorExists(_executorId)
{
ExecutorEntry storage executorEntry = executors[_executorId];
require(!executorEntry.enabled, ERROR_EXECUTOR_ENABLED);
executorEntry.enabled = true;
emit EnableExecutor(_executorId, executorEntry.executor);
}
/**
* @dev Get the script executor that can execute a particular script based on its first 4 bytes
* @param _script EVMScript being inspected
*/
function getScriptExecutor(bytes _script) public view returns (IEVMScriptExecutor) {
require(_script.length >= SCRIPT_START_LOCATION, ERROR_SCRIPT_LENGTH_TOO_SHORT);
uint256 id = _script.getSpecId();
// Note that we don't need to check for an executor's existence in this case, as only
// existing executors can be enabled
ExecutorEntry storage entry = executors[id];
return entry.enabled ? entry.executor : IEVMScriptExecutor(0);
}
}
// File: @aragon/os/contracts/evmscript/executors/BaseEVMScriptExecutor.sol
/*
* SPDX-License-Identitifer: MIT
*/
pragma solidity ^0.4.24;
contract BaseEVMScriptExecutor is IEVMScriptExecutor, Autopetrified {
uint256 internal constant SCRIPT_START_LOCATION = 4;
}
// File: @aragon/os/contracts/evmscript/executors/CallsScript.sol
pragma solidity 0.4.24;
// Inspired by https://github.com/reverendus/tx-manager
contract CallsScript is BaseEVMScriptExecutor {
using ScriptHelpers for bytes;
/* Hardcoded constants to save gas
bytes32 internal constant EXECUTOR_TYPE = keccak256("CALLS_SCRIPT");
*/
bytes32 internal constant EXECUTOR_TYPE = 0x2dc858a00f3e417be1394b87c07158e989ec681ce8cc68a9093680ac1a870302;
string private constant ERROR_BLACKLISTED_CALL = "EVMCALLS_BLACKLISTED_CALL";
string private constant ERROR_INVALID_LENGTH = "EVMCALLS_INVALID_LENGTH";
/* This is manually crafted in assembly
string private constant ERROR_CALL_REVERTED = "EVMCALLS_CALL_REVERTED";
*/
event LogScriptCall(address indexed sender, address indexed src, address indexed dst);
/**
* @notice Executes a number of call scripts
* @param _script [ specId (uint32) ] many calls with this structure ->
* [ to (address: 20 bytes) ] [ calldataLength (uint32: 4 bytes) ] [ calldata (calldataLength bytes) ]
* @param _blacklist Addresses the script cannot call to, or will revert.
* @return Always returns empty byte array
*/
function execScript(bytes _script, bytes, address[] _blacklist) external isInitialized returns (bytes) {
uint256 location = SCRIPT_START_LOCATION; // first 32 bits are spec id
while (location < _script.length) {
// Check there's at least address + calldataLength available
require(_script.length - location >= 0x18, ERROR_INVALID_LENGTH);
address contractAddress = _script.addressAt(location);
// Check address being called is not blacklist
for (uint256 i = 0; i < _blacklist.length; i++) {
require(contractAddress != _blacklist[i], ERROR_BLACKLISTED_CALL);
}
// logged before execution to ensure event ordering in receipt
// if failed entire execution is reverted regardless
emit LogScriptCall(msg.sender, address(this), contractAddress);
uint256 calldataLength = uint256(_script.uint32At(location + 0x14));
uint256 startOffset = location + 0x14 + 0x04;
uint256 calldataStart = _script.locationOf(startOffset);
// compute end of script / next location
location = startOffset + calldataLength;
require(location <= _script.length, ERROR_INVALID_LENGTH);
bool success;
assembly {
success := call(
sub(gas, 5000), // forward gas left - 5000
contractAddress, // address
0, // no value
calldataStart, // calldata start
calldataLength, // calldata length
0, // don't write output
0 // don't write output
)
switch success
case 0 {
let ptr := mload(0x40)
switch returndatasize
case 0 {
// No error data was returned, revert with "EVMCALLS_CALL_REVERTED"
// See remix: doing a `revert("EVMCALLS_CALL_REVERTED")` always results in
// this memory layout
mstore(ptr, 0x08c379a000000000000000000000000000000000000000000000000000000000) // error identifier
mstore(add(ptr, 0x04), 0x0000000000000000000000000000000000000000000000000000000000000020) // starting offset
mstore(add(ptr, 0x24), 0x0000000000000000000000000000000000000000000000000000000000000016) // reason length
mstore(add(ptr, 0x44), 0x45564d43414c4c535f43414c4c5f524556455254454400000000000000000000) // reason
revert(ptr, 100) // 100 = 4 + 3 * 32 (error identifier + 3 words for the ABI encoded error)
}
default {
// Forward the full error data
returndatacopy(ptr, 0, returndatasize)
revert(ptr, returndatasize)
}
}
default { }
}
}
// No need to allocate empty bytes for the return as this can only be called via an delegatecall
// (due to the isInitialized modifier)
}
function executorType() external pure returns (bytes32) {
return EXECUTOR_TYPE;
}
}
// File: @aragon/os/contracts/factory/EVMScriptRegistryFactory.sol
pragma solidity 0.4.24;
contract EVMScriptRegistryFactory is EVMScriptRegistryConstants {
EVMScriptRegistry public baseReg;
IEVMScriptExecutor public baseCallScript;
/**
* @notice Create a new EVMScriptRegistryFactory.
*/
constructor() public {
baseReg = new EVMScriptRegistry();
baseCallScript = IEVMScriptExecutor(new CallsScript());
}
/**
* @notice Install a new pinned instance of EVMScriptRegistry on `_dao`.
* @param _dao Kernel
* @return Installed EVMScriptRegistry
*/
function newEVMScriptRegistry(Kernel _dao) public returns (EVMScriptRegistry reg) {
bytes memory initPayload = abi.encodeWithSelector(reg.initialize.selector);
reg = EVMScriptRegistry(_dao.newPinnedAppInstance(EVMSCRIPT_REGISTRY_APP_ID, baseReg, initPayload, true));
ACL acl = ACL(_dao.acl());
acl.createPermission(this, reg, reg.REGISTRY_ADD_EXECUTOR_ROLE(), this);
reg.addScriptExecutor(baseCallScript); // spec 1 = CallsScript
// Clean up the permissions
acl.revokePermission(this, reg, reg.REGISTRY_ADD_EXECUTOR_ROLE());
acl.removePermissionManager(reg, reg.REGISTRY_ADD_EXECUTOR_ROLE());
return reg;
}
}
// File: @aragon/os/contracts/factory/DAOFactory.sol
pragma solidity 0.4.24;
contract DAOFactory {
IKernel public baseKernel;
IACL public baseACL;
EVMScriptRegistryFactory public regFactory;
event DeployDAO(address dao);
event DeployEVMScriptRegistry(address reg);
/**
* @notice Create a new DAOFactory, creating DAOs with Kernels proxied to `_baseKernel`, ACLs proxied to `_baseACL`, and new EVMScriptRegistries created from `_regFactory`.
* @param _baseKernel Base Kernel
* @param _baseACL Base ACL
* @param _regFactory EVMScriptRegistry factory
*/
constructor(IKernel _baseKernel, IACL _baseACL, EVMScriptRegistryFactory _regFactory) public {
// No need to init as it cannot be killed by devops199
if (address(_regFactory) != address(0)) {
regFactory = _regFactory;
}
baseKernel = _baseKernel;
baseACL = _baseACL;
}
/**
* @notice Create a new DAO with `_root` set as the initial admin
* @param _root Address that will be granted control to setup DAO permissions
* @return Newly created DAO
*/
function newDAO(address _root) public returns (Kernel) {
Kernel dao = Kernel(new KernelProxy(baseKernel));
if (address(regFactory) == address(0)) {
dao.initialize(baseACL, _root);
} else {
dao.initialize(baseACL, this);
ACL acl = ACL(dao.acl());
bytes32 permRole = acl.CREATE_PERMISSIONS_ROLE();
bytes32 appManagerRole = dao.APP_MANAGER_ROLE();
acl.grantPermission(regFactory, acl, permRole);
acl.createPermission(regFactory, dao, appManagerRole, this);
EVMScriptRegistry reg = regFactory.newEVMScriptRegistry(dao);
emit DeployEVMScriptRegistry(address(reg));
// Clean up permissions
// First, completely reset the APP_MANAGER_ROLE
acl.revokePermission(regFactory, dao, appManagerRole);
acl.removePermissionManager(dao, appManagerRole);
// Then, make root the only holder and manager of CREATE_PERMISSIONS_ROLE
acl.revokePermission(regFactory, acl, permRole);
acl.revokePermission(this, acl, permRole);
acl.grantPermission(_root, acl, permRole);
acl.setPermissionManager(_root, acl, permRole);
}
emit DeployDAO(address(dao));
return dao;
}
}
// File: @aragon/id/contracts/ens/IPublicResolver.sol
pragma solidity ^0.4.0;
interface IPublicResolver {
function supportsInterface(bytes4 interfaceID) constant returns (bool);
function addr(bytes32 node) constant returns (address ret);
function setAddr(bytes32 node, address addr);
function hash(bytes32 node) constant returns (bytes32 ret);
function setHash(bytes32 node, bytes32 hash);
}
// File: @aragon/id/contracts/IFIFSResolvingRegistrar.sol
pragma solidity 0.4.24;
interface IFIFSResolvingRegistrar {
function register(bytes32 _subnode, address _owner) external;
function registerWithResolver(bytes32 _subnode, address _owner, IPublicResolver _resolver) public;
}
// File: @aragon/templates-shared/contracts/BaseTemplate.sol
pragma solidity 0.4.24;
contract BaseTemplate is APMNamehash, IsContract {
using Uint256Helpers for uint256;
/* Hardcoded constant to save gas
* bytes32 constant internal AGENT_APP_ID = apmNamehash("agent"); // agent.aragonpm.eth
* bytes32 constant internal VAULT_APP_ID = apmNamehash("vault"); // vault.aragonpm.eth
* bytes32 constant internal VOTING_APP_ID = apmNamehash("voting"); // voting.aragonpm.eth
* bytes32 constant internal SURVEY_APP_ID = apmNamehash("survey"); // survey.aragonpm.eth
* bytes32 constant internal PAYROLL_APP_ID = apmNamehash("payroll"); // payroll.aragonpm.eth
* bytes32 constant internal FINANCE_APP_ID = apmNamehash("finance"); // finance.aragonpm.eth
* bytes32 constant internal TOKEN_MANAGER_APP_ID = apmNamehash("token-manager"); // token-manager.aragonpm.eth
*/
bytes32 constant internal AGENT_APP_ID = 0x9ac98dc5f995bf0211ed589ef022719d1487e5cb2bab505676f0d084c07cf89a;
bytes32 constant internal VAULT_APP_ID = 0x7e852e0fcfce6551c13800f1e7476f982525c2b5277ba14b24339c68416336d1;
bytes32 constant internal VOTING_APP_ID = 0x9fa3927f639745e587912d4b0fea7ef9013bf93fb907d29faeab57417ba6e1d4;
bytes32 constant internal PAYROLL_APP_ID = 0x463f596a96d808cb28b5d080181e4a398bc793df2c222f6445189eb801001991;
bytes32 constant internal FINANCE_APP_ID = 0xbf8491150dafc5dcaee5b861414dca922de09ccffa344964ae167212e8c673ae;
bytes32 constant internal TOKEN_MANAGER_APP_ID = 0x6b20a3010614eeebf2138ccec99f028a61c811b3b1a3343b6ff635985c75c91f;
bytes32 constant internal SURVEY_APP_ID = 0x030b2ab880b88e228f2da5a3d19a2a31bc10dbf91fb1143776a6de489389471e;
string constant private ERROR_ENS_NOT_CONTRACT = "TEMPLATE_ENS_NOT_CONTRACT";
string constant private ERROR_DAO_FACTORY_NOT_CONTRACT = "TEMPLATE_DAO_FAC_NOT_CONTRACT";
string constant private ERROR_ARAGON_ID_NOT_PROVIDED = "TEMPLATE_ARAGON_ID_NOT_PROVIDED";
string constant private ERROR_ARAGON_ID_NOT_CONTRACT = "TEMPLATE_ARAGON_ID_NOT_CONTRACT";
string constant private ERROR_MINIME_FACTORY_NOT_PROVIDED = "TEMPLATE_MINIME_FAC_NOT_PROVIDED";
string constant private ERROR_MINIME_FACTORY_NOT_CONTRACT = "TEMPLATE_MINIME_FAC_NOT_CONTRACT";
string constant private ERROR_CANNOT_CAST_VALUE_TO_ADDRESS = "TEMPLATE_CANNOT_CAST_VALUE_TO_ADDRESS";
string constant private ERROR_INVALID_ID = "TEMPLATE_INVALID_ID";
ENS internal ens;
DAOFactory internal daoFactory;
MiniMeTokenFactory internal miniMeFactory;
IFIFSResolvingRegistrar internal aragonID;
event DeployDao(address dao);
event SetupDao(address dao);
event DeployToken(address token);
event InstalledApp(address appProxy, bytes32 appId);
constructor(DAOFactory _daoFactory, ENS _ens, MiniMeTokenFactory _miniMeFactory, IFIFSResolvingRegistrar _aragonID) public {
require(isContract(address(_ens)), ERROR_ENS_NOT_CONTRACT);
require(isContract(address(_daoFactory)), ERROR_DAO_FACTORY_NOT_CONTRACT);
ens = _ens;
aragonID = _aragonID;
daoFactory = _daoFactory;
miniMeFactory = _miniMeFactory;
}
/**
* @dev Create a DAO using the DAO Factory and grant the template root permissions so it has full
* control during setup. Once the DAO setup has finished, it is recommended to call the
* `_transferRootPermissionsFromTemplateAndFinalizeDAO()` helper to transfer the root
* permissions to the end entity in control of the organization.
*/
function _createDAO() internal returns (Kernel dao, ACL acl) {
dao = daoFactory.newDAO(this);
emit DeployDao(address(dao));
acl = ACL(dao.acl());
_createPermissionForTemplate(acl, dao, dao.APP_MANAGER_ROLE());
}
/* ACL */
function _createPermissions(ACL _acl, address[] memory _grantees, address _app, bytes32 _permission, address _manager) internal {
_acl.createPermission(_grantees[0], _app, _permission, address(this));
for (uint256 i = 1; i < _grantees.length; i++) {
_acl.grantPermission(_grantees[i], _app, _permission);
}
_acl.revokePermission(address(this), _app, _permission);
_acl.setPermissionManager(_manager, _app, _permission);
}
function _createPermissionForTemplate(ACL _acl, address _app, bytes32 _permission) internal {
_acl.createPermission(address(this), _app, _permission, address(this));
}
function _removePermissionFromTemplate(ACL _acl, address _app, bytes32 _permission) internal {
_acl.revokePermission(address(this), _app, _permission);
_acl.removePermissionManager(_app, _permission);
}
function _transferRootPermissionsFromTemplateAndFinalizeDAO(Kernel _dao, address _to) internal {
_transferRootPermissionsFromTemplateAndFinalizeDAO(_dao, _to, _to);
}
function _transferRootPermissionsFromTemplateAndFinalizeDAO(Kernel _dao, address _to, address _manager) internal {
ACL _acl = ACL(_dao.acl());
_transferPermissionFromTemplate(_acl, _dao, _to, _dao.APP_MANAGER_ROLE(), _manager);
_transferPermissionFromTemplate(_acl, _acl, _to, _acl.CREATE_PERMISSIONS_ROLE(), _manager);
emit SetupDao(_dao);
}
function _transferPermissionFromTemplate(ACL _acl, address _app, address _to, bytes32 _permission, address _manager) internal {
_acl.grantPermission(_to, _app, _permission);
_acl.revokePermission(address(this), _app, _permission);
_acl.setPermissionManager(_manager, _app, _permission);
}
/* AGENT */
function _installDefaultAgentApp(Kernel _dao) internal returns (Agent) {
bytes memory initializeData = abi.encodeWithSelector(Agent(0).initialize.selector);
Agent agent = Agent(_installDefaultApp(_dao, AGENT_APP_ID, initializeData));
// We assume that installing the Agent app as a default app means the DAO should have its
// Vault replaced by the Agent. Thus, we also set the DAO's recovery app to the Agent.
_dao.setRecoveryVaultAppId(AGENT_APP_ID);
return agent;
}
function _installNonDefaultAgentApp(Kernel _dao) internal returns (Agent) {
bytes memory initializeData = abi.encodeWithSelector(Agent(0).initialize.selector);
return Agent(_installNonDefaultApp(_dao, AGENT_APP_ID, initializeData));
}
function _createAgentPermissions(ACL _acl, Agent _agent, address _grantee, address _manager) internal {
_acl.createPermission(_grantee, _agent, _agent.EXECUTE_ROLE(), _manager);
_acl.createPermission(_grantee, _agent, _agent.RUN_SCRIPT_ROLE(), _manager);
}
/* VAULT */
function _installVaultApp(Kernel _dao) internal returns (Vault) {
bytes memory initializeData = abi.encodeWithSelector(Vault(0).initialize.selector);
return Vault(_installDefaultApp(_dao, VAULT_APP_ID, initializeData));
}
function _createVaultPermissions(ACL _acl, Vault _vault, address _grantee, address _manager) internal {
_acl.createPermission(_grantee, _vault, _vault.TRANSFER_ROLE(), _manager);
}
/* VOTING */
function _installVotingApp(Kernel _dao, MiniMeToken _token, uint64[3] memory _votingSettings) internal returns (Voting) {
return _installVotingApp(_dao, _token, _votingSettings[0], _votingSettings[1], _votingSettings[2]);
}
function _installVotingApp(
Kernel _dao,
MiniMeToken _token,
uint64 _support,
uint64 _acceptance,
uint64 _duration
)
internal returns (Voting)
{
bytes memory initializeData = abi.encodeWithSelector(Voting(0).initialize.selector, _token, _support, _acceptance, _duration);
return Voting(_installNonDefaultApp(_dao, VOTING_APP_ID, initializeData));
}
function _createVotingPermissions(
ACL _acl,
Voting _voting,
address _settingsGrantee,
address _createVotesGrantee,
address _manager
)
internal
{
_acl.createPermission(_settingsGrantee, _voting, _voting.MODIFY_QUORUM_ROLE(), _manager);
_acl.createPermission(_settingsGrantee, _voting, _voting.MODIFY_SUPPORT_ROLE(), _manager);
_acl.createPermission(_createVotesGrantee, _voting, _voting.CREATE_VOTES_ROLE(), _manager);
}
/* SURVEY */
function _installSurveyApp(Kernel _dao, MiniMeToken _token, uint64 _minParticipationPct, uint64 _surveyTime) internal returns (Survey) {
bytes memory initializeData = abi.encodeWithSelector(Survey(0).initialize.selector, _token, _minParticipationPct, _surveyTime);
return Survey(_installNonDefaultApp(_dao, SURVEY_APP_ID, initializeData));
}
function _createSurveyPermissions(ACL _acl, Survey _survey, address _grantee, address _manager) internal {
_acl.createPermission(_grantee, _survey, _survey.CREATE_SURVEYS_ROLE(), _manager);
_acl.createPermission(_grantee, _survey, _survey.MODIFY_PARTICIPATION_ROLE(), _manager);
}
/* PAYROLL */
function _installPayrollApp(
Kernel _dao,
Finance _finance,
address _denominationToken,
IFeed _priceFeed,
uint64 _rateExpiryTime
)
internal returns (Payroll)
{
bytes memory initializeData = abi.encodeWithSelector(
Payroll(0).initialize.selector,
_finance,
_denominationToken,
_priceFeed,
_rateExpiryTime
);
return Payroll(_installNonDefaultApp(_dao, PAYROLL_APP_ID, initializeData));
}
/**
* @dev Internal function to configure payroll permissions. Note that we allow defining different managers for
* payroll since it may be useful to have one control the payroll settings (rate expiration, price feed,
* and allowed tokens), and another one to control the employee functionality (bonuses, salaries,
* reimbursements, employees, etc).
* @param _acl ACL instance being configured
* @param _acl Payroll app being configured
* @param _employeeManager Address that will receive permissions to handle employee payroll functionality
* @param _settingsManager Address that will receive permissions to manage payroll settings
* @param _permissionsManager Address that will be the ACL manager for the payroll permissions
*/
function _createPayrollPermissions(
ACL _acl,
Payroll _payroll,
address _employeeManager,
address _settingsManager,
address _permissionsManager
)
internal
{
_acl.createPermission(_employeeManager, _payroll, _payroll.ADD_BONUS_ROLE(), _permissionsManager);
_acl.createPermission(_employeeManager, _payroll, _payroll.ADD_EMPLOYEE_ROLE(), _permissionsManager);
_acl.createPermission(_employeeManager, _payroll, _payroll.ADD_REIMBURSEMENT_ROLE(), _permissionsManager);
_acl.createPermission(_employeeManager, _payroll, _payroll.TERMINATE_EMPLOYEE_ROLE(), _permissionsManager);
_acl.createPermission(_employeeManager, _payroll, _payroll.SET_EMPLOYEE_SALARY_ROLE(), _permissionsManager);
_acl.createPermission(_settingsManager, _payroll, _payroll.MODIFY_PRICE_FEED_ROLE(), _permissionsManager);
_acl.createPermission(_settingsManager, _payroll, _payroll.MODIFY_RATE_EXPIRY_ROLE(), _permissionsManager);
_acl.createPermission(_settingsManager, _payroll, _payroll.MANAGE_ALLOWED_TOKENS_ROLE(), _permissionsManager);
}
function _unwrapPayrollSettings(
uint256[4] memory _payrollSettings
)
internal pure returns (address denominationToken, IFeed priceFeed, uint64 rateExpiryTime, address employeeManager)
{
denominationToken = _toAddress(_payrollSettings[0]);
priceFeed = IFeed(_toAddress(_payrollSettings[1]));
rateExpiryTime = _payrollSettings[2].toUint64();
employeeManager = _toAddress(_payrollSettings[3]);
}
/* FINANCE */
function _installFinanceApp(Kernel _dao, Vault _vault, uint64 _periodDuration) internal returns (Finance) {
bytes memory initializeData = abi.encodeWithSelector(Finance(0).initialize.selector, _vault, _periodDuration);
return Finance(_installNonDefaultApp(_dao, FINANCE_APP_ID, initializeData));
}
function _createFinancePermissions(ACL _acl, Finance _finance, address _grantee, address _manager) internal {
_acl.createPermission(_grantee, _finance, _finance.EXECUTE_PAYMENTS_ROLE(), _manager);
_acl.createPermission(_grantee, _finance, _finance.MANAGE_PAYMENTS_ROLE(), _manager);
}
function _createFinanceCreatePaymentsPermission(ACL _acl, Finance _finance, address _grantee, address _manager) internal {
_acl.createPermission(_grantee, _finance, _finance.CREATE_PAYMENTS_ROLE(), _manager);
}
function _grantCreatePaymentPermission(ACL _acl, Finance _finance, address _to) internal {
_acl.grantPermission(_to, _finance, _finance.CREATE_PAYMENTS_ROLE());
}
function _transferCreatePaymentManagerFromTemplate(ACL _acl, Finance _finance, address _manager) internal {
_acl.setPermissionManager(_manager, _finance, _finance.CREATE_PAYMENTS_ROLE());
}
/* TOKEN MANAGER */
function _installTokenManagerApp(
Kernel _dao,
MiniMeToken _token,
bool _transferable,
uint256 _maxAccountTokens
)
internal returns (TokenManager)
{
TokenManager tokenManager = TokenManager(_installNonDefaultApp(_dao, TOKEN_MANAGER_APP_ID));
_token.changeController(tokenManager);
tokenManager.initialize(_token, _transferable, _maxAccountTokens);
return tokenManager;
}
function _createTokenManagerPermissions(ACL _acl, TokenManager _tokenManager, address _grantee, address _manager) internal {
_acl.createPermission(_grantee, _tokenManager, _tokenManager.MINT_ROLE(), _manager);
_acl.createPermission(_grantee, _tokenManager, _tokenManager.BURN_ROLE(), _manager);
}
function _mintTokens(ACL _acl, TokenManager _tokenManager, address[] memory _holders, uint256[] memory _stakes) internal {
_createPermissionForTemplate(_acl, _tokenManager, _tokenManager.MINT_ROLE());
for (uint256 i = 0; i < _holders.length; i++) {
_tokenManager.mint(_holders[i], _stakes[i]);
}
_removePermissionFromTemplate(_acl, _tokenManager, _tokenManager.MINT_ROLE());
}
function _mintTokens(ACL _acl, TokenManager _tokenManager, address[] memory _holders, uint256 _stake) internal {
_createPermissionForTemplate(_acl, _tokenManager, _tokenManager.MINT_ROLE());
for (uint256 i = 0; i < _holders.length; i++) {
_tokenManager.mint(_holders[i], _stake);
}
_removePermissionFromTemplate(_acl, _tokenManager, _tokenManager.MINT_ROLE());
}
function _mintTokens(ACL _acl, TokenManager _tokenManager, address _holder, uint256 _stake) internal {
_createPermissionForTemplate(_acl, _tokenManager, _tokenManager.MINT_ROLE());
_tokenManager.mint(_holder, _stake);
_removePermissionFromTemplate(_acl, _tokenManager, _tokenManager.MINT_ROLE());
}
/* EVM SCRIPTS */
function _createEvmScriptsRegistryPermissions(ACL _acl, address _grantee, address _manager) internal {
EVMScriptRegistry registry = EVMScriptRegistry(_acl.getEVMScriptRegistry());
_acl.createPermission(_grantee, registry, registry.REGISTRY_MANAGER_ROLE(), _manager);
_acl.createPermission(_grantee, registry, registry.REGISTRY_ADD_EXECUTOR_ROLE(), _manager);
}
/* APPS */
function _installNonDefaultApp(Kernel _dao, bytes32 _appId) internal returns (address) {
return _installNonDefaultApp(_dao, _appId, new bytes(0));
}
function _installNonDefaultApp(Kernel _dao, bytes32 _appId, bytes memory _initializeData) internal returns (address) {
return _installApp(_dao, _appId, _initializeData, false);
}
function _installDefaultApp(Kernel _dao, bytes32 _appId) internal returns (address) {
return _installDefaultApp(_dao, _appId, new bytes(0));
}
function _installDefaultApp(Kernel _dao, bytes32 _appId, bytes memory _initializeData) internal returns (address) {
return _installApp(_dao, _appId, _initializeData, true);
}
function _installApp(Kernel _dao, bytes32 _appId, bytes memory _initializeData, bool _setDefault) internal returns (address) {
address latestBaseAppAddress = _latestVersionAppBase(_appId);
address instance = address(_dao.newAppInstance(_appId, latestBaseAppAddress, _initializeData, _setDefault));
emit InstalledApp(instance, _appId);
return instance;
}
function _latestVersionAppBase(bytes32 _appId) internal view returns (address base) {
Repo repo = Repo(PublicResolver(ens.resolver(_appId)).addr(_appId));
(,base,) = repo.getLatest();
}
/* TOKEN */
function _createToken(string memory _name, string memory _symbol, uint8 _decimals) internal returns (MiniMeToken) {
require(address(miniMeFactory) != address(0), ERROR_MINIME_FACTORY_NOT_PROVIDED);
MiniMeToken token = miniMeFactory.createCloneToken(MiniMeToken(address(0)), 0, _name, _decimals, _symbol, true);
emit DeployToken(address(token));
return token;
}
function _ensureMiniMeFactoryIsValid(address _miniMeFactory) internal view {
require(isContract(address(_miniMeFactory)), ERROR_MINIME_FACTORY_NOT_CONTRACT);
}
/* IDS */
function _validateId(string memory _id) internal pure {
require(bytes(_id).length > 0, ERROR_INVALID_ID);
}
function _registerID(string memory _name, address _owner) internal {
require(address(aragonID) != address(0), ERROR_ARAGON_ID_NOT_PROVIDED);
aragonID.register(keccak256(abi.encodePacked(_name)), _owner);
}
function _ensureAragonIdIsValid(address _aragonID) internal view {
require(isContract(address(_aragonID)), ERROR_ARAGON_ID_NOT_CONTRACT);
}
/* HELPERS */
function _toAddress(uint256 _value) private pure returns (address) {
require(_value <= uint160(-1), ERROR_CANNOT_CAST_VALUE_TO_ADDRESS);
return address(_value);
}
}
// File: @ablack/fundraising-bancor-formula/contracts/interfaces/IBancorFormula.sol
pragma solidity 0.4.24;
/*
Bancor Formula interface
*/
contract IBancorFormula {
function calculatePurchaseReturn(uint256 _supply, uint256 _connectorBalance, uint32 _connectorWeight, uint256 _depositAmount) public view returns (uint256);
function calculateSaleReturn(uint256 _supply, uint256 _connectorBalance, uint32 _connectorWeight, uint256 _sellAmount) public view returns (uint256);
function calculateCrossConnectorReturn(uint256 _fromConnectorBalance, uint32 _fromConnectorWeight, uint256 _toConnectorBalance, uint32 _toConnectorWeight, uint256 _amount) public view returns (uint256);
}
// File: @ablack/fundraising-bancor-formula/contracts/utility/Utils.sol
pragma solidity 0.4.24;
/*
Utilities & Common Modifiers
*/
contract Utils {
/**
constructor
*/
constructor() public {
}
// verifies that an amount is greater than zero
modifier greaterThanZero(uint256 _amount) {
require(_amount > 0);
_;
}
// validates an address - currently only checks that it isn't null
modifier validAddress(address _address) {
require(_address != address(0));
_;
}
// verifies that the address is different than this contract address
modifier notThis(address _address) {
require(_address != address(this));
_;
}
}
// File: @ablack/fundraising-bancor-formula/contracts/BancorFormula.sol
pragma solidity 0.4.24;
contract BancorFormula is IBancorFormula, Utils {
using SafeMath for uint256;
string public version = '0.3';
uint256 private constant ONE = 1;
uint32 private constant MAX_WEIGHT = 1000000;
uint8 private constant MIN_PRECISION = 32;
uint8 private constant MAX_PRECISION = 127;
/**
Auto-generated via 'PrintIntScalingFactors.py'
*/
uint256 private constant FIXED_1 = 0x080000000000000000000000000000000;
uint256 private constant FIXED_2 = 0x100000000000000000000000000000000;
uint256 private constant MAX_NUM = 0x200000000000000000000000000000000;
/**
Auto-generated via 'PrintLn2ScalingFactors.py'
*/
uint256 private constant LN2_NUMERATOR = 0x3f80fe03f80fe03f80fe03f80fe03f8;
uint256 private constant LN2_DENOMINATOR = 0x5b9de1d10bf4103d647b0955897ba80;
/**
Auto-generated via 'PrintFunctionOptimalLog.py' and 'PrintFunctionOptimalExp.py'
*/
uint256 private constant OPT_LOG_MAX_VAL = 0x15bf0a8b1457695355fb8ac404e7a79e3;
uint256 private constant OPT_EXP_MAX_VAL = 0x800000000000000000000000000000000;
/**
Auto-generated via 'PrintFunctionConstructor.py'
*/
uint256[128] private maxExpArray;
constructor() public {
// maxExpArray[ 0] = 0x6bffffffffffffffffffffffffffffffff;
// maxExpArray[ 1] = 0x67ffffffffffffffffffffffffffffffff;
// maxExpArray[ 2] = 0x637fffffffffffffffffffffffffffffff;
// maxExpArray[ 3] = 0x5f6fffffffffffffffffffffffffffffff;
// maxExpArray[ 4] = 0x5b77ffffffffffffffffffffffffffffff;
// maxExpArray[ 5] = 0x57b3ffffffffffffffffffffffffffffff;
// maxExpArray[ 6] = 0x5419ffffffffffffffffffffffffffffff;
// maxExpArray[ 7] = 0x50a2ffffffffffffffffffffffffffffff;
// maxExpArray[ 8] = 0x4d517fffffffffffffffffffffffffffff;
// maxExpArray[ 9] = 0x4a233fffffffffffffffffffffffffffff;
// maxExpArray[ 10] = 0x47165fffffffffffffffffffffffffffff;
// maxExpArray[ 11] = 0x4429afffffffffffffffffffffffffffff;
// maxExpArray[ 12] = 0x415bc7ffffffffffffffffffffffffffff;
// maxExpArray[ 13] = 0x3eab73ffffffffffffffffffffffffffff;
// maxExpArray[ 14] = 0x3c1771ffffffffffffffffffffffffffff;
// maxExpArray[ 15] = 0x399e96ffffffffffffffffffffffffffff;
// maxExpArray[ 16] = 0x373fc47fffffffffffffffffffffffffff;
// maxExpArray[ 17] = 0x34f9e8ffffffffffffffffffffffffffff;
// maxExpArray[ 18] = 0x32cbfd5fffffffffffffffffffffffffff;
// maxExpArray[ 19] = 0x30b5057fffffffffffffffffffffffffff;
// maxExpArray[ 20] = 0x2eb40f9fffffffffffffffffffffffffff;
// maxExpArray[ 21] = 0x2cc8340fffffffffffffffffffffffffff;
// maxExpArray[ 22] = 0x2af09481ffffffffffffffffffffffffff;
// maxExpArray[ 23] = 0x292c5bddffffffffffffffffffffffffff;
// maxExpArray[ 24] = 0x277abdcdffffffffffffffffffffffffff;
// maxExpArray[ 25] = 0x25daf6657fffffffffffffffffffffffff;
// maxExpArray[ 26] = 0x244c49c65fffffffffffffffffffffffff;
// maxExpArray[ 27] = 0x22ce03cd5fffffffffffffffffffffffff;
// maxExpArray[ 28] = 0x215f77c047ffffffffffffffffffffffff;
// maxExpArray[ 29] = 0x1fffffffffffffffffffffffffffffffff;
// maxExpArray[ 30] = 0x1eaefdbdabffffffffffffffffffffffff;
// maxExpArray[ 31] = 0x1d6bd8b2ebffffffffffffffffffffffff;
maxExpArray[ 32] = 0x1c35fedd14ffffffffffffffffffffffff;
maxExpArray[ 33] = 0x1b0ce43b323fffffffffffffffffffffff;
maxExpArray[ 34] = 0x19f0028ec1ffffffffffffffffffffffff;
maxExpArray[ 35] = 0x18ded91f0e7fffffffffffffffffffffff;
maxExpArray[ 36] = 0x17d8ec7f0417ffffffffffffffffffffff;
maxExpArray[ 37] = 0x16ddc6556cdbffffffffffffffffffffff;
maxExpArray[ 38] = 0x15ecf52776a1ffffffffffffffffffffff;
maxExpArray[ 39] = 0x15060c256cb2ffffffffffffffffffffff;
maxExpArray[ 40] = 0x1428a2f98d72ffffffffffffffffffffff;
maxExpArray[ 41] = 0x13545598e5c23fffffffffffffffffffff;
maxExpArray[ 42] = 0x1288c4161ce1dfffffffffffffffffffff;
maxExpArray[ 43] = 0x11c592761c666fffffffffffffffffffff;
maxExpArray[ 44] = 0x110a688680a757ffffffffffffffffffff;
maxExpArray[ 45] = 0x1056f1b5bedf77ffffffffffffffffffff;
maxExpArray[ 46] = 0x0faadceceeff8bffffffffffffffffffff;
maxExpArray[ 47] = 0x0f05dc6b27edadffffffffffffffffffff;
maxExpArray[ 48] = 0x0e67a5a25da4107fffffffffffffffffff;
maxExpArray[ 49] = 0x0dcff115b14eedffffffffffffffffffff;
maxExpArray[ 50] = 0x0d3e7a392431239fffffffffffffffffff;
maxExpArray[ 51] = 0x0cb2ff529eb71e4fffffffffffffffffff;
maxExpArray[ 52] = 0x0c2d415c3db974afffffffffffffffffff;
maxExpArray[ 53] = 0x0bad03e7d883f69bffffffffffffffffff;
maxExpArray[ 54] = 0x0b320d03b2c343d5ffffffffffffffffff;
maxExpArray[ 55] = 0x0abc25204e02828dffffffffffffffffff;
maxExpArray[ 56] = 0x0a4b16f74ee4bb207fffffffffffffffff;
maxExpArray[ 57] = 0x09deaf736ac1f569ffffffffffffffffff;
maxExpArray[ 58] = 0x0976bd9952c7aa957fffffffffffffffff;
maxExpArray[ 59] = 0x09131271922eaa606fffffffffffffffff;
maxExpArray[ 60] = 0x08b380f3558668c46fffffffffffffffff;
maxExpArray[ 61] = 0x0857ddf0117efa215bffffffffffffffff;
maxExpArray[ 62] = 0x07ffffffffffffffffffffffffffffffff;
maxExpArray[ 63] = 0x07abbf6f6abb9d087fffffffffffffffff;
maxExpArray[ 64] = 0x075af62cbac95f7dfa7fffffffffffffff;
maxExpArray[ 65] = 0x070d7fb7452e187ac13fffffffffffffff;
maxExpArray[ 66] = 0x06c3390ecc8af379295fffffffffffffff;
maxExpArray[ 67] = 0x067c00a3b07ffc01fd6fffffffffffffff;
maxExpArray[ 68] = 0x0637b647c39cbb9d3d27ffffffffffffff;
maxExpArray[ 69] = 0x05f63b1fc104dbd39587ffffffffffffff;
maxExpArray[ 70] = 0x05b771955b36e12f7235ffffffffffffff;
maxExpArray[ 71] = 0x057b3d49dda84556d6f6ffffffffffffff;
maxExpArray[ 72] = 0x054183095b2c8ececf30ffffffffffffff;
maxExpArray[ 73] = 0x050a28be635ca2b888f77fffffffffffff;
maxExpArray[ 74] = 0x04d5156639708c9db33c3fffffffffffff;
maxExpArray[ 75] = 0x04a23105873875bd52dfdfffffffffffff;
maxExpArray[ 76] = 0x0471649d87199aa990756fffffffffffff;
maxExpArray[ 77] = 0x04429a21a029d4c1457cfbffffffffffff;
maxExpArray[ 78] = 0x0415bc6d6fb7dd71af2cb3ffffffffffff;
maxExpArray[ 79] = 0x03eab73b3bbfe282243ce1ffffffffffff;
maxExpArray[ 80] = 0x03c1771ac9fb6b4c18e229ffffffffffff;
maxExpArray[ 81] = 0x0399e96897690418f785257fffffffffff;
maxExpArray[ 82] = 0x0373fc456c53bb779bf0ea9fffffffffff;
maxExpArray[ 83] = 0x034f9e8e490c48e67e6ab8bfffffffffff;
maxExpArray[ 84] = 0x032cbfd4a7adc790560b3337ffffffffff;
maxExpArray[ 85] = 0x030b50570f6e5d2acca94613ffffffffff;
maxExpArray[ 86] = 0x02eb40f9f620fda6b56c2861ffffffffff;
maxExpArray[ 87] = 0x02cc8340ecb0d0f520a6af58ffffffffff;
maxExpArray[ 88] = 0x02af09481380a0a35cf1ba02ffffffffff;
maxExpArray[ 89] = 0x0292c5bdd3b92ec810287b1b3fffffffff;
maxExpArray[ 90] = 0x0277abdcdab07d5a77ac6d6b9fffffffff;
maxExpArray[ 91] = 0x025daf6654b1eaa55fd64df5efffffffff;
maxExpArray[ 92] = 0x0244c49c648baa98192dce88b7ffffffff;
maxExpArray[ 93] = 0x022ce03cd5619a311b2471268bffffffff;
maxExpArray[ 94] = 0x0215f77c045fbe885654a44a0fffffffff;
maxExpArray[ 95] = 0x01ffffffffffffffffffffffffffffffff;
maxExpArray[ 96] = 0x01eaefdbdaaee7421fc4d3ede5ffffffff;
maxExpArray[ 97] = 0x01d6bd8b2eb257df7e8ca57b09bfffffff;
maxExpArray[ 98] = 0x01c35fedd14b861eb0443f7f133fffffff;
maxExpArray[ 99] = 0x01b0ce43b322bcde4a56e8ada5afffffff;
maxExpArray[100] = 0x019f0028ec1fff007f5a195a39dfffffff;
maxExpArray[101] = 0x018ded91f0e72ee74f49b15ba527ffffff;
maxExpArray[102] = 0x017d8ec7f04136f4e5615fd41a63ffffff;
maxExpArray[103] = 0x016ddc6556cdb84bdc8d12d22e6fffffff;
maxExpArray[104] = 0x015ecf52776a1155b5bd8395814f7fffff;
maxExpArray[105] = 0x015060c256cb23b3b3cc3754cf40ffffff;
maxExpArray[106] = 0x01428a2f98d728ae223ddab715be3fffff;
maxExpArray[107] = 0x013545598e5c23276ccf0ede68034fffff;
maxExpArray[108] = 0x01288c4161ce1d6f54b7f61081194fffff;
maxExpArray[109] = 0x011c592761c666aa641d5a01a40f17ffff;
maxExpArray[110] = 0x0110a688680a7530515f3e6e6cfdcdffff;
maxExpArray[111] = 0x01056f1b5bedf75c6bcb2ce8aed428ffff;
maxExpArray[112] = 0x00faadceceeff8a0890f3875f008277fff;
maxExpArray[113] = 0x00f05dc6b27edad306388a600f6ba0bfff;
maxExpArray[114] = 0x00e67a5a25da41063de1495d5b18cdbfff;
maxExpArray[115] = 0x00dcff115b14eedde6fc3aa5353f2e4fff;
maxExpArray[116] = 0x00d3e7a3924312399f9aae2e0f868f8fff;
maxExpArray[117] = 0x00cb2ff529eb71e41582cccd5a1ee26fff;
maxExpArray[118] = 0x00c2d415c3db974ab32a51840c0b67edff;
maxExpArray[119] = 0x00bad03e7d883f69ad5b0a186184e06bff;
maxExpArray[120] = 0x00b320d03b2c343d4829abd6075f0cc5ff;
maxExpArray[121] = 0x00abc25204e02828d73c6e80bcdb1a95bf;
maxExpArray[122] = 0x00a4b16f74ee4bb2040a1ec6c15fbbf2df;
maxExpArray[123] = 0x009deaf736ac1f569deb1b5ae3f36c130f;
maxExpArray[124] = 0x00976bd9952c7aa957f5937d790ef65037;
maxExpArray[125] = 0x009131271922eaa6064b73a22d0bd4f2bf;
maxExpArray[126] = 0x008b380f3558668c46c91c49a2f8e967b9;
maxExpArray[127] = 0x00857ddf0117efa215952912839f6473e6;
}
/**
@dev given a token supply, connector balance, weight and a deposit amount (in the connector token),
calculates the return for a given conversion (in the main token)
Formula:
Return = _supply * ((1 + _depositAmount / _connectorBalance) ^ (_connectorWeight / 1000000) - 1)
@param _supply token total supply
@param _connectorBalance total connector balance
@param _connectorWeight connector weight, represented in ppm, 1-1000000
@param _depositAmount deposit amount, in connector token
@return purchase return amount
*/
function calculatePurchaseReturn(uint256 _supply, uint256 _connectorBalance, uint32 _connectorWeight, uint256 _depositAmount) public view returns (uint256) {
// validate input
require(_supply > 0 && _connectorBalance > 0 && _connectorWeight > 0 && _connectorWeight <= MAX_WEIGHT);
// special case for 0 deposit amount
if (_depositAmount == 0)
return 0;
// special case if the weight = 100%
if (_connectorWeight == MAX_WEIGHT)
return _supply.mul(_depositAmount) / _connectorBalance;
uint256 result;
uint8 precision;
uint256 baseN = _depositAmount.add(_connectorBalance);
(result, precision) = power(baseN, _connectorBalance, _connectorWeight, MAX_WEIGHT);
uint256 temp = _supply.mul(result) >> precision;
return temp - _supply;
}
/**
@dev given a token supply, connector balance, weight and a sell amount (in the main token),
calculates the return for a given conversion (in the connector token)
Formula:
Return = _connectorBalance * (1 - (1 - _sellAmount / _supply) ^ (1 / (_connectorWeight / 1000000)))
@param _supply token total supply
@param _connectorBalance total connector
@param _connectorWeight constant connector Weight, represented in ppm, 1-1000000
@param _sellAmount sell amount, in the token itself
@return sale return amount
*/
function calculateSaleReturn(uint256 _supply, uint256 _connectorBalance, uint32 _connectorWeight, uint256 _sellAmount) public view returns (uint256) {
// validate input
require(_supply > 0 && _connectorBalance > 0 && _connectorWeight > 0 && _connectorWeight <= MAX_WEIGHT && _sellAmount <= _supply);
// special case for 0 sell amount
if (_sellAmount == 0)
return 0;
// special case for selling the entire supply
if (_sellAmount == _supply)
return _connectorBalance;
// special case if the weight = 100%
if (_connectorWeight == MAX_WEIGHT)
return _connectorBalance.mul(_sellAmount) / _supply;
uint256 result;
uint8 precision;
uint256 baseD = _supply - _sellAmount;
(result, precision) = power(_supply, baseD, MAX_WEIGHT, _connectorWeight);
uint256 temp1 = _connectorBalance.mul(result);
uint256 temp2 = _connectorBalance << precision;
return (temp1 - temp2) / result;
}
/**
@dev given two connector balances/weights and a sell amount (in the first connector token),
calculates the return for a conversion from the first connector token to the second connector token (in the second connector token)
Formula:
Return = _toConnectorBalance * (1 - (_fromConnectorBalance / (_fromConnectorBalance + _amount)) ^ (_fromConnectorWeight / _toConnectorWeight))
@param _fromConnectorBalance input connector balance
@param _fromConnectorWeight input connector weight, represented in ppm, 1-1000000
@param _toConnectorBalance output connector balance
@param _toConnectorWeight output connector weight, represented in ppm, 1-1000000
@param _amount input connector amount
@return second connector amount
*/
function calculateCrossConnectorReturn(uint256 _fromConnectorBalance, uint32 _fromConnectorWeight, uint256 _toConnectorBalance, uint32 _toConnectorWeight, uint256 _amount) public view returns (uint256) {
// validate input
require(_fromConnectorBalance > 0 && _fromConnectorWeight > 0 && _fromConnectorWeight <= MAX_WEIGHT && _toConnectorBalance > 0 && _toConnectorWeight > 0 && _toConnectorWeight <= MAX_WEIGHT);
// special case for equal weights
if (_fromConnectorWeight == _toConnectorWeight)
return _toConnectorBalance.mul(_amount) / _fromConnectorBalance.add(_amount);
uint256 result;
uint8 precision;
uint256 baseN = _fromConnectorBalance.add(_amount);
(result, precision) = power(baseN, _fromConnectorBalance, _fromConnectorWeight, _toConnectorWeight);
uint256 temp1 = _toConnectorBalance.mul(result);
uint256 temp2 = _toConnectorBalance << precision;
return (temp1 - temp2) / result;
}
/**
General Description:
Determine a value of precision.
Calculate an integer approximation of (_baseN / _baseD) ^ (_expN / _expD) * 2 ^ precision.
Return the result along with the precision used.
Detailed Description:
Instead of calculating "base ^ exp", we calculate "e ^ (log(base) * exp)".
The value of "log(base)" is represented with an integer slightly smaller than "log(base) * 2 ^ precision".
The larger "precision" is, the more accurately this value represents the real value.
However, the larger "precision" is, the more bits are required in order to store this value.
And the exponentiation function, which takes "x" and calculates "e ^ x", is limited to a maximum exponent (maximum value of "x").
This maximum exponent depends on the "precision" used, and it is given by "maxExpArray[precision] >> (MAX_PRECISION - precision)".
Hence we need to determine the highest precision which can be used for the given input, before calling the exponentiation function.
This allows us to compute "base ^ exp" with maximum accuracy and without exceeding 256 bits in any of the intermediate computations.
This functions assumes that "_expN < 2 ^ 256 / log(MAX_NUM - 1)", otherwise the multiplication should be replaced with a "safeMul".
*/
function power(uint256 _baseN, uint256 _baseD, uint32 _expN, uint32 _expD) internal view returns (uint256, uint8) {
require(_baseN < MAX_NUM);
uint256 baseLog;
uint256 base = _baseN * FIXED_1 / _baseD;
if (base < OPT_LOG_MAX_VAL) {
baseLog = optimalLog(base);
}
else {
baseLog = generalLog(base);
}
uint256 baseLogTimesExp = baseLog * _expN / _expD;
if (baseLogTimesExp < OPT_EXP_MAX_VAL) {
return (optimalExp(baseLogTimesExp), MAX_PRECISION);
}
else {
uint8 precision = findPositionInMaxExpArray(baseLogTimesExp);
return (generalExp(baseLogTimesExp >> (MAX_PRECISION - precision), precision), precision);
}
}
/**
Compute log(x / FIXED_1) * FIXED_1.
This functions assumes that "x >= FIXED_1", because the output would be negative otherwise.
*/
function generalLog(uint256 x) internal pure returns (uint256) {
uint256 res = 0;
// If x >= 2, then we compute the integer part of log2(x), which is larger than 0.
if (x >= FIXED_2) {
uint8 count = floorLog2(x / FIXED_1);
x >>= count; // now x < 2
res = count * FIXED_1;
}
// If x > 1, then we compute the fraction part of log2(x), which is larger than 0.
if (x > FIXED_1) {
for (uint8 i = MAX_PRECISION; i > 0; --i) {
x = (x * x) / FIXED_1; // now 1 < x < 4
if (x >= FIXED_2) {
x >>= 1; // now 1 < x < 2
res += ONE << (i - 1);
}
}
}
return res * LN2_NUMERATOR / LN2_DENOMINATOR;
}
/**
Compute the largest integer smaller than or equal to the binary logarithm of the input.
*/
function floorLog2(uint256 _n) internal pure returns (uint8) {
uint8 res = 0;
if (_n < 256) {
// At most 8 iterations
while (_n > 1) {
_n >>= 1;
res += 1;
}
}
else {
// Exactly 8 iterations
for (uint8 s = 128; s > 0; s >>= 1) {
if (_n >= (ONE << s)) {
_n >>= s;
res |= s;
}
}
}
return res;
}
/**
The global "maxExpArray" is sorted in descending order, and therefore the following statements are equivalent:
- This function finds the position of [the smallest value in "maxExpArray" larger than or equal to "x"]
- This function finds the highest position of [a value in "maxExpArray" larger than or equal to "x"]
*/
function findPositionInMaxExpArray(uint256 _x) internal view returns (uint8) {
uint8 lo = MIN_PRECISION;
uint8 hi = MAX_PRECISION;
while (lo + 1 < hi) {
uint8 mid = (lo + hi) / 2;
if (maxExpArray[mid] >= _x)
lo = mid;
else
hi = mid;
}
if (maxExpArray[hi] >= _x)
return hi;
if (maxExpArray[lo] >= _x)
return lo;
require(false);
return 0;
}
/**
This function can be auto-generated by the script 'PrintFunctionGeneralExp.py'.
It approximates "e ^ x" via maclaurin summation: "(x^0)/0! + (x^1)/1! + ... + (x^n)/n!".
It returns "e ^ (x / 2 ^ precision) * 2 ^ precision", that is, the result is upshifted for accuracy.
The global "maxExpArray" maps each "precision" to "((maximumExponent + 1) << (MAX_PRECISION - precision)) - 1".
The maximum permitted value for "x" is therefore given by "maxExpArray[precision] >> (MAX_PRECISION - precision)".
*/
function generalExp(uint256 _x, uint8 _precision) internal pure returns (uint256) {
uint256 xi = _x;
uint256 res = 0;
xi = (xi * _x) >> _precision; res += xi * 0x3442c4e6074a82f1797f72ac0000000; // add x^02 * (33! / 02!)
xi = (xi * _x) >> _precision; res += xi * 0x116b96f757c380fb287fd0e40000000; // add x^03 * (33! / 03!)
xi = (xi * _x) >> _precision; res += xi * 0x045ae5bdd5f0e03eca1ff4390000000; // add x^04 * (33! / 04!)
xi = (xi * _x) >> _precision; res += xi * 0x00defabf91302cd95b9ffda50000000; // add x^05 * (33! / 05!)
xi = (xi * _x) >> _precision; res += xi * 0x002529ca9832b22439efff9b8000000; // add x^06 * (33! / 06!)
xi = (xi * _x) >> _precision; res += xi * 0x00054f1cf12bd04e516b6da88000000; // add x^07 * (33! / 07!)
xi = (xi * _x) >> _precision; res += xi * 0x0000a9e39e257a09ca2d6db51000000; // add x^08 * (33! / 08!)
xi = (xi * _x) >> _precision; res += xi * 0x000012e066e7b839fa050c309000000; // add x^09 * (33! / 09!)
xi = (xi * _x) >> _precision; res += xi * 0x000001e33d7d926c329a1ad1a800000; // add x^10 * (33! / 10!)
xi = (xi * _x) >> _precision; res += xi * 0x0000002bee513bdb4a6b19b5f800000; // add x^11 * (33! / 11!)
xi = (xi * _x) >> _precision; res += xi * 0x00000003a9316fa79b88eccf2a00000; // add x^12 * (33! / 12!)
xi = (xi * _x) >> _precision; res += xi * 0x0000000048177ebe1fa812375200000; // add x^13 * (33! / 13!)
xi = (xi * _x) >> _precision; res += xi * 0x0000000005263fe90242dcbacf00000; // add x^14 * (33! / 14!)
xi = (xi * _x) >> _precision; res += xi * 0x000000000057e22099c030d94100000; // add x^15 * (33! / 15!)
xi = (xi * _x) >> _precision; res += xi * 0x0000000000057e22099c030d9410000; // add x^16 * (33! / 16!)
xi = (xi * _x) >> _precision; res += xi * 0x00000000000052b6b54569976310000; // add x^17 * (33! / 17!)
xi = (xi * _x) >> _precision; res += xi * 0x00000000000004985f67696bf748000; // add x^18 * (33! / 18!)
xi = (xi * _x) >> _precision; res += xi * 0x000000000000003dea12ea99e498000; // add x^19 * (33! / 19!)
xi = (xi * _x) >> _precision; res += xi * 0x00000000000000031880f2214b6e000; // add x^20 * (33! / 20!)
xi = (xi * _x) >> _precision; res += xi * 0x000000000000000025bcff56eb36000; // add x^21 * (33! / 21!)
xi = (xi * _x) >> _precision; res += xi * 0x000000000000000001b722e10ab1000; // add x^22 * (33! / 22!)
xi = (xi * _x) >> _precision; res += xi * 0x0000000000000000001317c70077000; // add x^23 * (33! / 23!)
xi = (xi * _x) >> _precision; res += xi * 0x00000000000000000000cba84aafa00; // add x^24 * (33! / 24!)
xi = (xi * _x) >> _precision; res += xi * 0x00000000000000000000082573a0a00; // add x^25 * (33! / 25!)
xi = (xi * _x) >> _precision; res += xi * 0x00000000000000000000005035ad900; // add x^26 * (33! / 26!)
xi = (xi * _x) >> _precision; res += xi * 0x000000000000000000000002f881b00; // add x^27 * (33! / 27!)
xi = (xi * _x) >> _precision; res += xi * 0x0000000000000000000000001b29340; // add x^28 * (33! / 28!)
xi = (xi * _x) >> _precision; res += xi * 0x00000000000000000000000000efc40; // add x^29 * (33! / 29!)
xi = (xi * _x) >> _precision; res += xi * 0x0000000000000000000000000007fe0; // add x^30 * (33! / 30!)
xi = (xi * _x) >> _precision; res += xi * 0x0000000000000000000000000000420; // add x^31 * (33! / 31!)
xi = (xi * _x) >> _precision; res += xi * 0x0000000000000000000000000000021; // add x^32 * (33! / 32!)
xi = (xi * _x) >> _precision; res += xi * 0x0000000000000000000000000000001; // add x^33 * (33! / 33!)
return res / 0x688589cc0e9505e2f2fee5580000000 + _x + (ONE << _precision); // divide by 33! and then add x^1 / 1! + x^0 / 0!
}
/**
Return log(x / FIXED_1) * FIXED_1
Input range: FIXED_1 <= x <= LOG_EXP_MAX_VAL - 1
Auto-generated via 'PrintFunctionOptimalLog.py'
Detailed description:
- Rewrite the input as a product of natural exponents and a single residual r, such that 1 < r < 2
- The natural logarithm of each (pre-calculated) exponent is the degree of the exponent
- The natural logarithm of r is calculated via Taylor series for log(1 + x), where x = r - 1
- The natural logarithm of the input is calculated by summing up the intermediate results above
- For example: log(250) = log(e^4 * e^1 * e^0.5 * 1.021692859) = 4 + 1 + 0.5 + log(1 + 0.021692859)
*/
function optimalLog(uint256 x) internal pure returns (uint256) {
uint256 res = 0;
uint256 y;
uint256 z;
uint256 w;
if (x >= 0xd3094c70f034de4b96ff7d5b6f99fcd8) {res += 0x40000000000000000000000000000000; x = x * FIXED_1 / 0xd3094c70f034de4b96ff7d5b6f99fcd8;} // add 1 / 2^1
if (x >= 0xa45af1e1f40c333b3de1db4dd55f29a7) {res += 0x20000000000000000000000000000000; x = x * FIXED_1 / 0xa45af1e1f40c333b3de1db4dd55f29a7;} // add 1 / 2^2
if (x >= 0x910b022db7ae67ce76b441c27035c6a1) {res += 0x10000000000000000000000000000000; x = x * FIXED_1 / 0x910b022db7ae67ce76b441c27035c6a1;} // add 1 / 2^3
if (x >= 0x88415abbe9a76bead8d00cf112e4d4a8) {res += 0x08000000000000000000000000000000; x = x * FIXED_1 / 0x88415abbe9a76bead8d00cf112e4d4a8;} // add 1 / 2^4
if (x >= 0x84102b00893f64c705e841d5d4064bd3) {res += 0x04000000000000000000000000000000; x = x * FIXED_1 / 0x84102b00893f64c705e841d5d4064bd3;} // add 1 / 2^5
if (x >= 0x8204055aaef1c8bd5c3259f4822735a2) {res += 0x02000000000000000000000000000000; x = x * FIXED_1 / 0x8204055aaef1c8bd5c3259f4822735a2;} // add 1 / 2^6
if (x >= 0x810100ab00222d861931c15e39b44e99) {res += 0x01000000000000000000000000000000; x = x * FIXED_1 / 0x810100ab00222d861931c15e39b44e99;} // add 1 / 2^7
if (x >= 0x808040155aabbbe9451521693554f733) {res += 0x00800000000000000000000000000000; x = x * FIXED_1 / 0x808040155aabbbe9451521693554f733;} // add 1 / 2^8
z = y = x - FIXED_1;
w = y * y / FIXED_1;
res += z * (0x100000000000000000000000000000000 - y) / 0x100000000000000000000000000000000; z = z * w / FIXED_1; // add y^01 / 01 - y^02 / 02
res += z * (0x0aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa - y) / 0x200000000000000000000000000000000; z = z * w / FIXED_1; // add y^03 / 03 - y^04 / 04
res += z * (0x099999999999999999999999999999999 - y) / 0x300000000000000000000000000000000; z = z * w / FIXED_1; // add y^05 / 05 - y^06 / 06
res += z * (0x092492492492492492492492492492492 - y) / 0x400000000000000000000000000000000; z = z * w / FIXED_1; // add y^07 / 07 - y^08 / 08
res += z * (0x08e38e38e38e38e38e38e38e38e38e38e - y) / 0x500000000000000000000000000000000; z = z * w / FIXED_1; // add y^09 / 09 - y^10 / 10
res += z * (0x08ba2e8ba2e8ba2e8ba2e8ba2e8ba2e8b - y) / 0x600000000000000000000000000000000; z = z * w / FIXED_1; // add y^11 / 11 - y^12 / 12
res += z * (0x089d89d89d89d89d89d89d89d89d89d89 - y) / 0x700000000000000000000000000000000; z = z * w / FIXED_1; // add y^13 / 13 - y^14 / 14
res += z * (0x088888888888888888888888888888888 - y) / 0x800000000000000000000000000000000; // add y^15 / 15 - y^16 / 16
return res;
}
/**
Return e ^ (x / FIXED_1) * FIXED_1
Input range: 0 <= x <= OPT_EXP_MAX_VAL - 1
Auto-generated via 'PrintFunctionOptimalExp.py'
Detailed description:
- Rewrite the input as a sum of binary exponents and a single residual r, as small as possible
- The exponentiation of each binary exponent is given (pre-calculated)
- The exponentiation of r is calculated via Taylor series for e^x, where x = r
- The exponentiation of the input is calculated by multiplying the intermediate results above
- For example: e^5.521692859 = e^(4 + 1 + 0.5 + 0.021692859) = e^4 * e^1 * e^0.5 * e^0.021692859
*/
function optimalExp(uint256 x) internal pure returns (uint256) {
uint256 res = 0;
uint256 y;
uint256 z;
z = y = x % 0x10000000000000000000000000000000; // get the input modulo 2^(-3)
z = z * y / FIXED_1; res += z * 0x10e1b3be415a0000; // add y^02 * (20! / 02!)
z = z * y / FIXED_1; res += z * 0x05a0913f6b1e0000; // add y^03 * (20! / 03!)
z = z * y / FIXED_1; res += z * 0x0168244fdac78000; // add y^04 * (20! / 04!)
z = z * y / FIXED_1; res += z * 0x004807432bc18000; // add y^05 * (20! / 05!)
z = z * y / FIXED_1; res += z * 0x000c0135dca04000; // add y^06 * (20! / 06!)
z = z * y / FIXED_1; res += z * 0x0001b707b1cdc000; // add y^07 * (20! / 07!)
z = z * y / FIXED_1; res += z * 0x000036e0f639b800; // add y^08 * (20! / 08!)
z = z * y / FIXED_1; res += z * 0x00000618fee9f800; // add y^09 * (20! / 09!)
z = z * y / FIXED_1; res += z * 0x0000009c197dcc00; // add y^10 * (20! / 10!)
z = z * y / FIXED_1; res += z * 0x0000000e30dce400; // add y^11 * (20! / 11!)
z = z * y / FIXED_1; res += z * 0x000000012ebd1300; // add y^12 * (20! / 12!)
z = z * y / FIXED_1; res += z * 0x0000000017499f00; // add y^13 * (20! / 13!)
z = z * y / FIXED_1; res += z * 0x0000000001a9d480; // add y^14 * (20! / 14!)
z = z * y / FIXED_1; res += z * 0x00000000001c6380; // add y^15 * (20! / 15!)
z = z * y / FIXED_1; res += z * 0x000000000001c638; // add y^16 * (20! / 16!)
z = z * y / FIXED_1; res += z * 0x0000000000001ab8; // add y^17 * (20! / 17!)
z = z * y / FIXED_1; res += z * 0x000000000000017c; // add y^18 * (20! / 18!)
z = z * y / FIXED_1; res += z * 0x0000000000000014; // add y^19 * (20! / 19!)
z = z * y / FIXED_1; res += z * 0x0000000000000001; // add y^20 * (20! / 20!)
res = res / 0x21c3677c82b40000 + y + FIXED_1; // divide by 20! and then add y^1 / 1! + y^0 / 0!
if ((x & 0x010000000000000000000000000000000) != 0) res = res * 0x1c3d6a24ed82218787d624d3e5eba95f9 / 0x18ebef9eac820ae8682b9793ac6d1e776; // multiply by e^2^(-3)
if ((x & 0x020000000000000000000000000000000) != 0) res = res * 0x18ebef9eac820ae8682b9793ac6d1e778 / 0x1368b2fc6f9609fe7aceb46aa619baed4; // multiply by e^2^(-2)
if ((x & 0x040000000000000000000000000000000) != 0) res = res * 0x1368b2fc6f9609fe7aceb46aa619baed5 / 0x0bc5ab1b16779be3575bd8f0520a9f21f; // multiply by e^2^(-1)
if ((x & 0x080000000000000000000000000000000) != 0) res = res * 0x0bc5ab1b16779be3575bd8f0520a9f21e / 0x0454aaa8efe072e7f6ddbab84b40a55c9; // multiply by e^2^(+0)
if ((x & 0x100000000000000000000000000000000) != 0) res = res * 0x0454aaa8efe072e7f6ddbab84b40a55c5 / 0x00960aadc109e7a3bf4578099615711ea; // multiply by e^2^(+1)
if ((x & 0x200000000000000000000000000000000) != 0) res = res * 0x00960aadc109e7a3bf4578099615711d7 / 0x0002bf84208204f5977f9a8cf01fdce3d; // multiply by e^2^(+2)
if ((x & 0x400000000000000000000000000000000) != 0) res = res * 0x0002bf84208204f5977f9a8cf01fdc307 / 0x0000003c6ab775dd0b95b4cbee7e65d11; // multiply by e^2^(+3)
return res;
}
}
// File: @ablack/fundraising-shared-interfaces/contracts/IAragonFundraisingController.sol
pragma solidity 0.4.24;
contract IAragonFundraisingController {
function openTrading() external;
function updateTappedAmount(address _token) external;
function collateralsToBeClaimed(address _collateral) public view returns (uint256);
function balanceOf(address _who, address _token) public view returns (uint256);
}
// File: @ablack/fundraising-batched-bancor-market-maker/contracts/BatchedBancorMarketMaker.sol
pragma solidity 0.4.24;
contract BatchedBancorMarketMaker is EtherTokenConstant, IsContract, AragonApp {
using SafeERC20 for ERC20;
using SafeMath for uint256;
/**
Hardcoded constants to save gas
bytes32 public constant OPEN_ROLE = keccak256("OPEN_ROLE");
bytes32 public constant UPDATE_FORMULA_ROLE = keccak256("UPDATE_FORMULA_ROLE");
bytes32 public constant UPDATE_BENEFICIARY_ROLE = keccak256("UPDATE_BENEFICIARY_ROLE");
bytes32 public constant UPDATE_FEES_ROLE = keccak256("UPDATE_FEES_ROLE");
bytes32 public constant ADD_COLLATERAL_TOKEN_ROLE = keccak256("ADD_COLLATERAL_TOKEN_ROLE");
bytes32 public constant REMOVE_COLLATERAL_TOKEN_ROLE = keccak256("REMOVE_COLLATERAL_TOKEN_ROLE");
bytes32 public constant UPDATE_COLLATERAL_TOKEN_ROLE = keccak256("UPDATE_COLLATERAL_TOKEN_ROLE");
bytes32 public constant OPEN_BUY_ORDER_ROLE = keccak256("OPEN_BUY_ORDER_ROLE");
bytes32 public constant OPEN_SELL_ORDER_ROLE = keccak256("OPEN_SELL_ORDER_ROLE");
*/
bytes32 public constant OPEN_ROLE = 0xefa06053e2ca99a43c97c4a4f3d8a394ee3323a8ff237e625fba09fe30ceb0a4;
bytes32 public constant UPDATE_FORMULA_ROLE = 0xbfb76d8d43f55efe58544ea32af187792a7bdb983850d8fed33478266eec3cbb;
bytes32 public constant UPDATE_BENEFICIARY_ROLE = 0xf7ea2b80c7b6a2cab2c11d2290cb005c3748397358a25e17113658c83b732593;
bytes32 public constant UPDATE_FEES_ROLE = 0x5f9be2932ed3a723f295a763be1804c7ebfd1a41c1348fb8bdf5be1c5cdca822;
bytes32 public constant ADD_COLLATERAL_TOKEN_ROLE = 0x217b79cb2bc7760defc88529853ef81ab33ae5bb315408ce9f5af09c8776662d;
bytes32 public constant REMOVE_COLLATERAL_TOKEN_ROLE = 0x2044e56de223845e4be7d0a6f4e9a29b635547f16413a6d1327c58d9db438ee2;
bytes32 public constant UPDATE_COLLATERAL_TOKEN_ROLE = 0xe0565c2c43e0d841e206bb36a37f12f22584b4652ccee6f9e0c071b697a2e13d;
bytes32 public constant OPEN_BUY_ORDER_ROLE = 0xa589c8f284b76fc8d510d9d553485c47dbef1b0745ae00e0f3fd4e28fcd77ea7;
bytes32 public constant OPEN_SELL_ORDER_ROLE = 0xd68ba2b769fa37a2a7bd4bed9241b448bc99eca41f519ef037406386a8f291c0;
uint256 public constant PCT_BASE = 10 ** 18; // 0% = 0; 1% = 10 ** 16; 100% = 10 ** 18
uint32 public constant PPM = 1000000;
string private constant ERROR_CONTRACT_IS_EOA = "MM_CONTRACT_IS_EOA";
string private constant ERROR_INVALID_BENEFICIARY = "MM_INVALID_BENEFICIARY";
string private constant ERROR_INVALID_BATCH_BLOCKS = "MM_INVALID_BATCH_BLOCKS";
string private constant ERROR_INVALID_PERCENTAGE = "MM_INVALID_PERCENTAGE";
string private constant ERROR_INVALID_RESERVE_RATIO = "MM_INVALID_RESERVE_RATIO";
string private constant ERROR_INVALID_TM_SETTING = "MM_INVALID_TM_SETTING";
string private constant ERROR_INVALID_COLLATERAL = "MM_INVALID_COLLATERAL";
string private constant ERROR_INVALID_COLLATERAL_VALUE = "MM_INVALID_COLLATERAL_VALUE";
string private constant ERROR_INVALID_BOND_AMOUNT = "MM_INVALID_BOND_AMOUNT";
string private constant ERROR_ALREADY_OPEN = "MM_ALREADY_OPEN";
string private constant ERROR_NOT_OPEN = "MM_NOT_OPEN";
string private constant ERROR_COLLATERAL_ALREADY_WHITELISTED = "MM_COLLATERAL_ALREADY_WHITELISTED";
string private constant ERROR_COLLATERAL_NOT_WHITELISTED = "MM_COLLATERAL_NOT_WHITELISTED";
string private constant ERROR_NOTHING_TO_CLAIM = "MM_NOTHING_TO_CLAIM";
string private constant ERROR_BATCH_NOT_OVER = "MM_BATCH_NOT_OVER";
string private constant ERROR_BATCH_CANCELLED = "MM_BATCH_CANCELLED";
string private constant ERROR_BATCH_NOT_CANCELLED = "MM_BATCH_NOT_CANCELLED";
string private constant ERROR_SLIPPAGE_EXCEEDS_LIMIT = "MM_SLIPPAGE_EXCEEDS_LIMIT";
string private constant ERROR_INSUFFICIENT_POOL_BALANCE = "MM_INSUFFICIENT_POOL_BALANCE";
string private constant ERROR_TRANSFER_FROM_FAILED = "MM_TRANSFER_FROM_FAILED";
struct Collateral {
bool whitelisted;
uint256 virtualSupply;
uint256 virtualBalance;
uint32 reserveRatio;
uint256 slippage;
}
struct MetaBatch {
bool initialized;
uint256 realSupply;
uint256 buyFeePct;
uint256 sellFeePct;
IBancorFormula formula;
mapping(address => Batch) batches;
}
struct Batch {
bool initialized;
bool cancelled;
uint256 supply;
uint256 balance;
uint32 reserveRatio;
uint256 slippage;
uint256 totalBuySpend;
uint256 totalBuyReturn;
uint256 totalSellSpend;
uint256 totalSellReturn;
mapping(address => uint256) buyers;
mapping(address => uint256) sellers;
}
IAragonFundraisingController public controller;
TokenManager public tokenManager;
ERC20 public token;
Vault public reserve;
address public beneficiary;
IBancorFormula public formula;
uint256 public batchBlocks;
uint256 public buyFeePct;
uint256 public sellFeePct;
bool public isOpen;
uint256 public tokensToBeMinted;
mapping(address => uint256) public collateralsToBeClaimed;
mapping(address => Collateral) public collaterals;
mapping(uint256 => MetaBatch) public metaBatches;
event UpdateBeneficiary (address indexed beneficiary);
event UpdateFormula (address indexed formula);
event UpdateFees (uint256 buyFeePct, uint256 sellFeePct);
event NewMetaBatch (uint256 indexed id, uint256 supply, uint256 buyFeePct, uint256 sellFeePct, address formula);
event NewBatch (
uint256 indexed id,
address indexed collateral,
uint256 supply,
uint256 balance,
uint32 reserveRatio,
uint256 slippage)
;
event CancelBatch (uint256 indexed id, address indexed collateral);
event AddCollateralToken (
address indexed collateral,
uint256 virtualSupply,
uint256 virtualBalance,
uint32 reserveRatio,
uint256 slippage
);
event RemoveCollateralToken (address indexed collateral);
event UpdateCollateralToken (
address indexed collateral,
uint256 virtualSupply,
uint256 virtualBalance,
uint32 reserveRatio,
uint256 slippage
);
event Open ();
event OpenBuyOrder (address indexed buyer, uint256 indexed batchId, address indexed collateral, uint256 fee, uint256 value);
event OpenSellOrder (address indexed seller, uint256 indexed batchId, address indexed collateral, uint256 amount);
event ClaimBuyOrder (address indexed buyer, uint256 indexed batchId, address indexed collateral, uint256 amount);
event ClaimSellOrder (address indexed seller, uint256 indexed batchId, address indexed collateral, uint256 fee, uint256 value);
event ClaimCancelledBuyOrder (address indexed buyer, uint256 indexed batchId, address indexed collateral, uint256 value);
event ClaimCancelledSellOrder(address indexed seller, uint256 indexed batchId, address indexed collateral, uint256 amount);
event UpdatePricing (
uint256 indexed batchId,
address indexed collateral,
uint256 totalBuySpend,
uint256 totalBuyReturn,
uint256 totalSellSpend,
uint256 totalSellReturn
);
/***** external function *****/
/**
* @notice Initialize market maker
* @param _controller The address of the controller contract
* @param _tokenManager The address of the [bonded token] token manager contract
* @param _reserve The address of the reserve [pool] contract
* @param _beneficiary The address of the beneficiary [to whom fees are to be sent]
* @param _formula The address of the BancorFormula [computation] contract
* @param _batchBlocks The number of blocks batches are to last
* @param _buyFeePct The fee to be deducted from buy orders [in PCT_BASE]
* @param _sellFeePct The fee to be deducted from sell orders [in PCT_BASE]
*/
function initialize(
IAragonFundraisingController _controller,
TokenManager _tokenManager,
IBancorFormula _formula,
Vault _reserve,
address _beneficiary,
uint256 _batchBlocks,
uint256 _buyFeePct,
uint256 _sellFeePct
)
external
onlyInit
{
initialized();
require(isContract(_controller), ERROR_CONTRACT_IS_EOA);
require(isContract(_tokenManager), ERROR_CONTRACT_IS_EOA);
require(isContract(_formula), ERROR_CONTRACT_IS_EOA);
require(isContract(_reserve), ERROR_CONTRACT_IS_EOA);
require(_beneficiaryIsValid(_beneficiary), ERROR_INVALID_BENEFICIARY);
require(_batchBlocks > 0, ERROR_INVALID_BATCH_BLOCKS);
require(_feeIsValid(_buyFeePct) && _feeIsValid(_sellFeePct), ERROR_INVALID_PERCENTAGE);
require(_tokenManagerSettingIsValid(_tokenManager), ERROR_INVALID_TM_SETTING);
controller = _controller;
tokenManager = _tokenManager;
token = ERC20(tokenManager.token());
formula = _formula;
reserve = _reserve;
beneficiary = _beneficiary;
batchBlocks = _batchBlocks;
buyFeePct = _buyFeePct;
sellFeePct = _sellFeePct;
}
/* generic settings related function */
/**
* @notice Open market making [enabling users to open buy and sell orders]
*/
function open() external auth(OPEN_ROLE) {
require(!isOpen, ERROR_ALREADY_OPEN);
_open();
}
/**
* @notice Update formula to `_formula`
* @param _formula The address of the new BancorFormula [computation] contract
*/
function updateFormula(IBancorFormula _formula) external auth(UPDATE_FORMULA_ROLE) {
require(isContract(_formula), ERROR_CONTRACT_IS_EOA);
_updateFormula(_formula);
}
/**
* @notice Update beneficiary to `_beneficiary`
* @param _beneficiary The address of the new beneficiary [to whom fees are to be sent]
*/
function updateBeneficiary(address _beneficiary) external auth(UPDATE_BENEFICIARY_ROLE) {
require(_beneficiaryIsValid(_beneficiary), ERROR_INVALID_BENEFICIARY);
_updateBeneficiary(_beneficiary);
}
/**
* @notice Update fees deducted from buy and sell orders to respectively `@formatPct(_buyFeePct)`% and `@formatPct(_sellFeePct)`%
* @param _buyFeePct The new fee to be deducted from buy orders [in PCT_BASE]
* @param _sellFeePct The new fee to be deducted from sell orders [in PCT_BASE]
*/
function updateFees(uint256 _buyFeePct, uint256 _sellFeePct) external auth(UPDATE_FEES_ROLE) {
require(_feeIsValid(_buyFeePct) && _feeIsValid(_sellFeePct), ERROR_INVALID_PERCENTAGE);
_updateFees(_buyFeePct, _sellFeePct);
}
/* collateral tokens related functions */
/**
* @notice Add `_collateral.symbol(): string` as a whitelisted collateral token
* @param _collateral The address of the collateral token to be whitelisted
* @param _virtualSupply The virtual supply to be used for that collateral token [in wei]
* @param _virtualBalance The virtual balance to be used for that collateral token [in wei]
* @param _reserveRatio The reserve ratio to be used for that collateral token [in PPM]
* @param _slippage The price slippage below which each batch is to be kept for that collateral token [in PCT_BASE]
*/
function addCollateralToken(address _collateral, uint256 _virtualSupply, uint256 _virtualBalance, uint32 _reserveRatio, uint256 _slippage)
external
auth(ADD_COLLATERAL_TOKEN_ROLE)
{
require(isContract(_collateral) || _collateral == ETH, ERROR_INVALID_COLLATERAL);
require(!_collateralIsWhitelisted(_collateral), ERROR_COLLATERAL_ALREADY_WHITELISTED);
require(_reserveRatioIsValid(_reserveRatio), ERROR_INVALID_RESERVE_RATIO);
_addCollateralToken(_collateral, _virtualSupply, _virtualBalance, _reserveRatio, _slippage);
}
/**
* @notice Remove `_collateral.symbol(): string` as a whitelisted collateral token
* @param _collateral The address of the collateral token to be un-whitelisted
*/
function removeCollateralToken(address _collateral) external auth(REMOVE_COLLATERAL_TOKEN_ROLE) {
require(_collateralIsWhitelisted(_collateral), ERROR_COLLATERAL_NOT_WHITELISTED);
_removeCollateralToken(_collateral);
}
/**
* @notice Update `_collateral.symbol(): string` collateralization settings
* @param _collateral The address of the collateral token whose collateralization settings are to be updated
* @param _virtualSupply The new virtual supply to be used for that collateral token [in wei]
* @param _virtualBalance The new virtual balance to be used for that collateral token [in wei]
* @param _reserveRatio The new reserve ratio to be used for that collateral token [in PPM]
* @param _slippage The new price slippage below which each batch is to be kept for that collateral token [in PCT_BASE]
*/
function updateCollateralToken(address _collateral, uint256 _virtualSupply, uint256 _virtualBalance, uint32 _reserveRatio, uint256 _slippage)
external
auth(UPDATE_COLLATERAL_TOKEN_ROLE)
{
require(_collateralIsWhitelisted(_collateral), ERROR_COLLATERAL_NOT_WHITELISTED);
require(_reserveRatioIsValid(_reserveRatio), ERROR_INVALID_RESERVE_RATIO);
_updateCollateralToken(_collateral, _virtualSupply, _virtualBalance, _reserveRatio, _slippage);
}
/* market making related functions */
/**
* @notice Open a buy order worth `@tokenAmount(_collateral, _value)`
* @param _buyer The address of the buyer
* @param _collateral The address of the collateral token to be spent
* @param _value The amount of collateral token to be spent
*/
function openBuyOrder(address _buyer, address _collateral, uint256 _value) external payable auth(OPEN_BUY_ORDER_ROLE) {
require(isOpen, ERROR_NOT_OPEN);
require(_collateralIsWhitelisted(_collateral), ERROR_COLLATERAL_NOT_WHITELISTED);
require(!_batchIsCancelled(_currentBatchId(), _collateral), ERROR_BATCH_CANCELLED);
require(_collateralValueIsValid(_buyer, _collateral, _value, msg.value), ERROR_INVALID_COLLATERAL_VALUE);
_openBuyOrder(_buyer, _collateral, _value);
}
/**
* @notice Open a sell order worth `@tokenAmount(self.token(): address, _amount)` against `_collateral.symbol(): string`
* @param _seller The address of the seller
* @param _collateral The address of the collateral token to be returned
* @param _amount The amount of bonded token to be spent
*/
function openSellOrder(address _seller, address _collateral, uint256 _amount) external auth(OPEN_SELL_ORDER_ROLE) {
require(isOpen, ERROR_NOT_OPEN);
require(_collateralIsWhitelisted(_collateral), ERROR_COLLATERAL_NOT_WHITELISTED);
require(!_batchIsCancelled(_currentBatchId(), _collateral), ERROR_BATCH_CANCELLED);
require(_bondAmountIsValid(_seller, _amount), ERROR_INVALID_BOND_AMOUNT);
_openSellOrder(_seller, _collateral, _amount);
}
/**
* @notice Claim the results of `_buyer`'s `_collateral.symbol(): string` buy orders from batch #`_batchId`
* @param _buyer The address of the user whose buy orders are to be claimed
* @param _batchId The id of the batch in which buy orders are to be claimed
* @param _collateral The address of the collateral token against which buy orders are to be claimed
*/
function claimBuyOrder(address _buyer, uint256 _batchId, address _collateral) external nonReentrant isInitialized {
require(_collateralIsWhitelisted(_collateral), ERROR_COLLATERAL_NOT_WHITELISTED);
require(_batchIsOver(_batchId), ERROR_BATCH_NOT_OVER);
require(!_batchIsCancelled(_batchId, _collateral), ERROR_BATCH_CANCELLED);
require(_userIsBuyer(_batchId, _collateral, _buyer), ERROR_NOTHING_TO_CLAIM);
_claimBuyOrder(_buyer, _batchId, _collateral);
}
/**
* @notice Claim the results of `_seller`'s `_collateral.symbol(): string` sell orders from batch #`_batchId`
* @param _seller The address of the user whose sell orders are to be claimed
* @param _batchId The id of the batch in which sell orders are to be claimed
* @param _collateral The address of the collateral token against which sell orders are to be claimed
*/
function claimSellOrder(address _seller, uint256 _batchId, address _collateral) external nonReentrant isInitialized {
require(_collateralIsWhitelisted(_collateral), ERROR_COLLATERAL_NOT_WHITELISTED);
require(_batchIsOver(_batchId), ERROR_BATCH_NOT_OVER);
require(!_batchIsCancelled(_batchId, _collateral), ERROR_BATCH_CANCELLED);
require(_userIsSeller(_batchId, _collateral, _seller), ERROR_NOTHING_TO_CLAIM);
_claimSellOrder(_seller, _batchId, _collateral);
}
/**
* @notice Claim the investments of `_buyer`'s `_collateral.symbol(): string` buy orders from cancelled batch #`_batchId`
* @param _buyer The address of the user whose cancelled buy orders are to be claimed
* @param _batchId The id of the batch in which cancelled buy orders are to be claimed
* @param _collateral The address of the collateral token against which cancelled buy orders are to be claimed
*/
function claimCancelledBuyOrder(address _buyer, uint256 _batchId, address _collateral) external nonReentrant isInitialized {
require(_batchIsCancelled(_batchId, _collateral), ERROR_BATCH_NOT_CANCELLED);
require(_userIsBuyer(_batchId, _collateral, _buyer), ERROR_NOTHING_TO_CLAIM);
_claimCancelledBuyOrder(_buyer, _batchId, _collateral);
}
/**
* @notice Claim the investments of `_seller`'s `_collateral.symbol(): string` sell orders from cancelled batch #`_batchId`
* @param _seller The address of the user whose cancelled sell orders are to be claimed
* @param _batchId The id of the batch in which cancelled sell orders are to be claimed
* @param _collateral The address of the collateral token against which cancelled sell orders are to be claimed
*/
function claimCancelledSellOrder(address _seller, uint256 _batchId, address _collateral) external nonReentrant isInitialized {
require(_batchIsCancelled(_batchId, _collateral), ERROR_BATCH_NOT_CANCELLED);
require(_userIsSeller(_batchId, _collateral, _seller), ERROR_NOTHING_TO_CLAIM);
_claimCancelledSellOrder(_seller, _batchId, _collateral);
}
/***** public view functions *****/
function getCurrentBatchId() public view isInitialized returns (uint256) {
return _currentBatchId();
}
function getCollateralToken(address _collateral) public view isInitialized returns (bool, uint256, uint256, uint32, uint256) {
Collateral storage collateral = collaterals[_collateral];
return (collateral.whitelisted, collateral.virtualSupply, collateral.virtualBalance, collateral.reserveRatio, collateral.slippage);
}
function getBatch(uint256 _batchId, address _collateral)
public view isInitialized
returns (bool, bool, uint256, uint256, uint32, uint256, uint256, uint256, uint256, uint256)
{
Batch storage batch = metaBatches[_batchId].batches[_collateral];
return (
batch.initialized,
batch.cancelled,
batch.supply,
batch.balance,
batch.reserveRatio,
batch.slippage,
batch.totalBuySpend,
batch.totalBuyReturn,
batch.totalSellSpend,
batch.totalSellReturn
);
}
function getStaticPricePPM(uint256 _supply, uint256 _balance, uint32 _reserveRatio) public view isInitialized returns (uint256) {
return _staticPricePPM(_supply, _balance, _reserveRatio);
}
/***** internal functions *****/
/* computation functions */
function _staticPricePPM(uint256 _supply, uint256 _balance, uint32 _reserveRatio) internal pure returns (uint256) {
return uint256(PPM).mul(uint256(PPM)).mul(_balance).div(_supply.mul(uint256(_reserveRatio)));
}
function _currentBatchId() internal view returns (uint256) {
return (block.number.div(batchBlocks)).mul(batchBlocks);
}
/* check functions */
function _beneficiaryIsValid(address _beneficiary) internal pure returns (bool) {
return _beneficiary != address(0);
}
function _feeIsValid(uint256 _fee) internal pure returns (bool) {
return _fee < PCT_BASE;
}
function _reserveRatioIsValid(uint32 _reserveRatio) internal pure returns (bool) {
return _reserveRatio <= PPM;
}
function _tokenManagerSettingIsValid(TokenManager _tokenManager) internal view returns (bool) {
return _tokenManager.maxAccountTokens() == uint256(-1);
}
function _collateralValueIsValid(address _buyer, address _collateral, uint256 _value, uint256 _msgValue) internal view returns (bool) {
if (_value == 0) {
return false;
}
if (_collateral == ETH) {
return _msgValue == _value;
}
return (
_msgValue == 0 &&
controller.balanceOf(_buyer, _collateral) >= _value &&
ERC20(_collateral).allowance(_buyer, address(this)) >= _value
);
}
function _bondAmountIsValid(address _seller, uint256 _amount) internal view returns (bool) {
return _amount != 0 && tokenManager.spendableBalanceOf(_seller) >= _amount;
}
function _collateralIsWhitelisted(address _collateral) internal view returns (bool) {
return collaterals[_collateral].whitelisted;
}
function _batchIsOver(uint256 _batchId) internal view returns (bool) {
return _batchId < _currentBatchId();
}
function _batchIsCancelled(uint256 _batchId, address _collateral) internal view returns (bool) {
return metaBatches[_batchId].batches[_collateral].cancelled;
}
function _userIsBuyer(uint256 _batchId, address _collateral, address _user) internal view returns (bool) {
Batch storage batch = metaBatches[_batchId].batches[_collateral];
return batch.buyers[_user] > 0;
}
function _userIsSeller(uint256 _batchId, address _collateral, address _user) internal view returns (bool) {
Batch storage batch = metaBatches[_batchId].batches[_collateral];
return batch.sellers[_user] > 0;
}
function _poolBalanceIsSufficient(address _collateral) internal view returns (bool) {
return controller.balanceOf(address(reserve), _collateral) >= collateralsToBeClaimed[_collateral];
}
function _slippageIsValid(Batch storage _batch, address _collateral) internal view returns (bool) {
uint256 staticPricePPM = _staticPricePPM(_batch.supply, _batch.balance, _batch.reserveRatio);
uint256 maximumSlippage = _batch.slippage;
// if static price is zero let's consider that every slippage is valid
if (staticPricePPM == 0) {
return true;
}
return _buySlippageIsValid(_batch, staticPricePPM, maximumSlippage) && _sellSlippageIsValid(_batch, staticPricePPM, maximumSlippage);
}
function _buySlippageIsValid(Batch storage _batch, uint256 _startingPricePPM, uint256 _maximumSlippage) internal view returns (bool) {
/**
* NOTE
* the case where starting price is zero is handled
* in the meta function _slippageIsValid()
*/
/**
* NOTE
* slippage is valid if:
* totalBuyReturn >= totalBuySpend / (startingPrice * (1 + maxSlippage))
* totalBuyReturn >= totalBuySpend / ((startingPricePPM / PPM) * (1 + maximumSlippage / PCT_BASE))
* totalBuyReturn >= totalBuySpend / ((startingPricePPM / PPM) * (1 + maximumSlippage / PCT_BASE))
* totalBuyReturn >= totalBuySpend / ((startingPricePPM / PPM) * (PCT + maximumSlippage) / PCT_BASE)
* totalBuyReturn * startingPrice * ( PCT + maximumSlippage) >= totalBuySpend * PCT_BASE * PPM
*/
if (
_batch.totalBuyReturn.mul(_startingPricePPM).mul(PCT_BASE.add(_maximumSlippage)) >=
_batch.totalBuySpend.mul(PCT_BASE).mul(uint256(PPM))
) {
return true;
}
return false;
}
function _sellSlippageIsValid(Batch storage _batch, uint256 _startingPricePPM, uint256 _maximumSlippage) internal view returns (bool) {
/**
* NOTE
* the case where starting price is zero is handled
* in the meta function _slippageIsValid()
*/
// if allowed sell slippage >= 100%
// then any sell slippage is valid
if (_maximumSlippage >= PCT_BASE) {
return true;
}
/**
* NOTE
* slippage is valid if
* totalSellReturn >= startingPrice * (1 - maxSlippage) * totalBuySpend
* totalSellReturn >= (startingPricePPM / PPM) * (1 - maximumSlippage / PCT_BASE) * totalBuySpend
* totalSellReturn >= (startingPricePPM / PPM) * (PCT_BASE - maximumSlippage) * totalBuySpend / PCT_BASE
* totalSellReturn * PCT_BASE * PPM = startingPricePPM * (PCT_BASE - maximumSlippage) * totalBuySpend
*/
if (
_batch.totalSellReturn.mul(PCT_BASE).mul(uint256(PPM)) >=
_startingPricePPM.mul(PCT_BASE.sub(_maximumSlippage)).mul(_batch.totalSellSpend)
) {
return true;
}
return false;
}
/* initialization functions */
function _currentBatch(address _collateral) internal returns (uint256, Batch storage) {
uint256 batchId = _currentBatchId();
MetaBatch storage metaBatch = metaBatches[batchId];
Batch storage batch = metaBatch.batches[_collateral];
if (!metaBatch.initialized) {
/**
* NOTE
* all collateral batches should be initialized with the same supply to
* avoid price manipulation between different collaterals in the same meta-batch
* we don't need to do the same with collateral balances as orders against one collateral
* can't affect the pool's balance against another collateral and tap is a step-function
* of the meta-batch duration
*/
/**
* NOTE
* realSupply(metaBatch) = totalSupply(metaBatchInitialization) + tokensToBeMinted(metaBatchInitialization)
* 1. buy and sell orders incoming during the current meta-batch and affecting totalSupply or tokensToBeMinted
* should not be taken into account in the price computation [they are already a part of the batched pricing computation]
* 2. the only way for totalSupply to be modified during a meta-batch [outside of incoming buy and sell orders]
* is for buy orders from previous meta-batches to be claimed [and tokens to be minted]:
* as such totalSupply(metaBatch) + tokenToBeMinted(metaBatch) will always equal totalSupply(metaBatchInitialization) + tokenToBeMinted(metaBatchInitialization)
*/
metaBatch.realSupply = token.totalSupply().add(tokensToBeMinted);
metaBatch.buyFeePct = buyFeePct;
metaBatch.sellFeePct = sellFeePct;
metaBatch.formula = formula;
metaBatch.initialized = true;
emit NewMetaBatch(batchId, metaBatch.realSupply, metaBatch.buyFeePct, metaBatch.sellFeePct, metaBatch.formula);
}
if (!batch.initialized) {
/**
* NOTE
* supply(batch) = realSupply(metaBatch) + virtualSupply(batchInitialization)
* virtualSupply can technically be updated during a batch: the on-going batch will still use
* its value at the time of initialization [it's up to the updater to act wisely]
*/
/**
* NOTE
* balance(batch) = poolBalance(batchInitialization) - collateralsToBeClaimed(batchInitialization) + virtualBalance(metaBatchInitialization)
* 1. buy and sell orders incoming during the current batch and affecting poolBalance or collateralsToBeClaimed
* should not be taken into account in the price computation [they are already a part of the batched price computation]
* 2. the only way for poolBalance to be modified during a batch [outside of incoming buy and sell orders]
* is for sell orders from previous meta-batches to be claimed [and collateral to be transfered] as the tap is a step-function of the meta-batch duration:
* as such poolBalance(batch) - collateralsToBeClaimed(batch) will always equal poolBalance(batchInitialization) - collateralsToBeClaimed(batchInitialization)
* 3. virtualBalance can technically be updated during a batch: the on-going batch will still use
* its value at the time of initialization [it's up to the updater to act wisely]
*/
controller.updateTappedAmount(_collateral);
batch.supply = metaBatch.realSupply.add(collaterals[_collateral].virtualSupply);
batch.balance = controller.balanceOf(address(reserve), _collateral).add(collaterals[_collateral].virtualBalance).sub(collateralsToBeClaimed[_collateral]);
batch.reserveRatio = collaterals[_collateral].reserveRatio;
batch.slippage = collaterals[_collateral].slippage;
batch.initialized = true;
emit NewBatch(batchId, _collateral, batch.supply, batch.balance, batch.reserveRatio, batch.slippage);
}
return (batchId, batch);
}
/* state modifiying functions */
function _open() internal {
isOpen = true;
emit Open();
}
function _updateBeneficiary(address _beneficiary) internal {
beneficiary = _beneficiary;
emit UpdateBeneficiary(_beneficiary);
}
function _updateFormula(IBancorFormula _formula) internal {
formula = _formula;
emit UpdateFormula(address(_formula));
}
function _updateFees(uint256 _buyFeePct, uint256 _sellFeePct) internal {
buyFeePct = _buyFeePct;
sellFeePct = _sellFeePct;
emit UpdateFees(_buyFeePct, _sellFeePct);
}
function _cancelCurrentBatch(address _collateral) internal {
(uint256 batchId, Batch storage batch) = _currentBatch(_collateral);
if (!batch.cancelled) {
batch.cancelled = true;
// bought bonds are cancelled but sold bonds are due back
// bought collaterals are cancelled but sold collaterals are due back
tokensToBeMinted = tokensToBeMinted.sub(batch.totalBuyReturn).add(batch.totalSellSpend);
collateralsToBeClaimed[_collateral] = collateralsToBeClaimed[_collateral].add(batch.totalBuySpend).sub(batch.totalSellReturn);
emit CancelBatch(batchId, _collateral);
}
}
function _addCollateralToken(address _collateral, uint256 _virtualSupply, uint256 _virtualBalance, uint32 _reserveRatio, uint256 _slippage)
internal
{
collaterals[_collateral].whitelisted = true;
collaterals[_collateral].virtualSupply = _virtualSupply;
collaterals[_collateral].virtualBalance = _virtualBalance;
collaterals[_collateral].reserveRatio = _reserveRatio;
collaterals[_collateral].slippage = _slippage;
emit AddCollateralToken(_collateral, _virtualSupply, _virtualBalance, _reserveRatio, _slippage);
}
function _removeCollateralToken(address _collateral) internal {
_cancelCurrentBatch(_collateral);
Collateral storage collateral = collaterals[_collateral];
delete collateral.whitelisted;
delete collateral.virtualSupply;
delete collateral.virtualBalance;
delete collateral.reserveRatio;
delete collateral.slippage;
emit RemoveCollateralToken(_collateral);
}
function _updateCollateralToken(
address _collateral,
uint256 _virtualSupply,
uint256 _virtualBalance,
uint32 _reserveRatio,
uint256 _slippage
)
internal
{
collaterals[_collateral].virtualSupply = _virtualSupply;
collaterals[_collateral].virtualBalance = _virtualBalance;
collaterals[_collateral].reserveRatio = _reserveRatio;
collaterals[_collateral].slippage = _slippage;
emit UpdateCollateralToken(_collateral, _virtualSupply, _virtualBalance, _reserveRatio, _slippage);
}
function _openBuyOrder(address _buyer, address _collateral, uint256 _value) internal {
(uint256 batchId, Batch storage batch) = _currentBatch(_collateral);
// deduct fee
uint256 fee = _value.mul(metaBatches[batchId].buyFeePct).div(PCT_BASE);
uint256 value = _value.sub(fee);
// collect fee and collateral
if (fee > 0) {
_transfer(_buyer, beneficiary, _collateral, fee);
}
_transfer(_buyer, address(reserve), _collateral, value);
// save batch
uint256 deprecatedBuyReturn = batch.totalBuyReturn;
uint256 deprecatedSellReturn = batch.totalSellReturn;
// update batch
batch.totalBuySpend = batch.totalBuySpend.add(value);
batch.buyers[_buyer] = batch.buyers[_buyer].add(value);
// update pricing
_updatePricing(batch, batchId, _collateral);
// update the amount of tokens to be minted and collaterals to be claimed
tokensToBeMinted = tokensToBeMinted.sub(deprecatedBuyReturn).add(batch.totalBuyReturn);
collateralsToBeClaimed[_collateral] = collateralsToBeClaimed[_collateral].sub(deprecatedSellReturn).add(batch.totalSellReturn);
// sanity checks
require(_slippageIsValid(batch, _collateral), ERROR_SLIPPAGE_EXCEEDS_LIMIT);
emit OpenBuyOrder(_buyer, batchId, _collateral, fee, value);
}
function _openSellOrder(address _seller, address _collateral, uint256 _amount) internal {
(uint256 batchId, Batch storage batch) = _currentBatch(_collateral);
// burn bonds
tokenManager.burn(_seller, _amount);
// save batch
uint256 deprecatedBuyReturn = batch.totalBuyReturn;
uint256 deprecatedSellReturn = batch.totalSellReturn;
// update batch
batch.totalSellSpend = batch.totalSellSpend.add(_amount);
batch.sellers[_seller] = batch.sellers[_seller].add(_amount);
// update pricing
_updatePricing(batch, batchId, _collateral);
// update the amount of tokens to be minted and collaterals to be claimed
tokensToBeMinted = tokensToBeMinted.sub(deprecatedBuyReturn).add(batch.totalBuyReturn);
collateralsToBeClaimed[_collateral] = collateralsToBeClaimed[_collateral].sub(deprecatedSellReturn).add(batch.totalSellReturn);
// sanity checks
require(_slippageIsValid(batch, _collateral), ERROR_SLIPPAGE_EXCEEDS_LIMIT);
require(_poolBalanceIsSufficient(_collateral), ERROR_INSUFFICIENT_POOL_BALANCE);
emit OpenSellOrder(_seller, batchId, _collateral, _amount);
}
function _claimBuyOrder(address _buyer, uint256 _batchId, address _collateral) internal {
Batch storage batch = metaBatches[_batchId].batches[_collateral];
uint256 buyReturn = (batch.buyers[_buyer].mul(batch.totalBuyReturn)).div(batch.totalBuySpend);
batch.buyers[_buyer] = 0;
if (buyReturn > 0) {
tokensToBeMinted = tokensToBeMinted.sub(buyReturn);
tokenManager.mint(_buyer, buyReturn);
}
emit ClaimBuyOrder(_buyer, _batchId, _collateral, buyReturn);
}
function _claimSellOrder(address _seller, uint256 _batchId, address _collateral) internal {
Batch storage batch = metaBatches[_batchId].batches[_collateral];
uint256 saleReturn = (batch.sellers[_seller].mul(batch.totalSellReturn)).div(batch.totalSellSpend);
uint256 fee = saleReturn.mul(metaBatches[_batchId].sellFeePct).div(PCT_BASE);
uint256 value = saleReturn.sub(fee);
batch.sellers[_seller] = 0;
if (value > 0) {
collateralsToBeClaimed[_collateral] = collateralsToBeClaimed[_collateral].sub(saleReturn);
reserve.transfer(_collateral, _seller, value);
}
if (fee > 0) {
reserve.transfer(_collateral, beneficiary, fee);
}
emit ClaimSellOrder(_seller, _batchId, _collateral, fee, value);
}
function _claimCancelledBuyOrder(address _buyer, uint256 _batchId, address _collateral) internal {
Batch storage batch = metaBatches[_batchId].batches[_collateral];
uint256 value = batch.buyers[_buyer];
batch.buyers[_buyer] = 0;
if (value > 0) {
collateralsToBeClaimed[_collateral] = collateralsToBeClaimed[_collateral].sub(value);
reserve.transfer(_collateral, _buyer, value);
}
emit ClaimCancelledBuyOrder(_buyer, _batchId, _collateral, value);
}
function _claimCancelledSellOrder(address _seller, uint256 _batchId, address _collateral) internal {
Batch storage batch = metaBatches[_batchId].batches[_collateral];
uint256 amount = batch.sellers[_seller];
batch.sellers[_seller] = 0;
if (amount > 0) {
tokensToBeMinted = tokensToBeMinted.sub(amount);
tokenManager.mint(_seller, amount);
}
emit ClaimCancelledSellOrder(_seller, _batchId, _collateral, amount);
}
function _updatePricing(Batch storage batch, uint256 _batchId, address _collateral) internal {
// the situation where there are no buy nor sell orders can't happen [keep commented]
// if (batch.totalSellSpend == 0 && batch.totalBuySpend == 0)
// return;
// static price is the current exact price in collateral
// per token according to the initial state of the batch
// [expressed in PPM for precision sake]
uint256 staticPricePPM = _staticPricePPM(batch.supply, batch.balance, batch.reserveRatio);
// [NOTE]
// if staticPrice is zero then resultOfSell [= 0] <= batch.totalBuySpend
// so totalSellReturn will be zero and totalBuyReturn will be
// computed normally along the formula
// 1. we want to find out if buy orders are worth more sell orders [or vice-versa]
// 2. we thus check the return of sell orders at the current exact price
// 3. if the return of sell orders is larger than the pending buys,
// there are more sells than buys [and vice-versa]
uint256 resultOfSell = batch.totalSellSpend.mul(staticPricePPM).div(uint256(PPM));
if (resultOfSell > batch.totalBuySpend) {
// >> sell orders are worth more than buy orders
// 1. first we execute all pending buy orders at the current exact
// price because there is at least one sell order for each buy order
// 2. then the final sell return is the addition of this first
// matched return with the remaining bonding curve return
// the number of tokens bought as a result of all buy orders matched at the
// current exact price [which is less than the total amount of tokens to be sold]
batch.totalBuyReturn = batch.totalBuySpend.mul(uint256(PPM)).div(staticPricePPM);
// the number of tokens left over to be sold along the curve which is the difference
// between the original total sell order and the result of all the buy orders
uint256 remainingSell = batch.totalSellSpend.sub(batch.totalBuyReturn);
// the amount of collateral generated by selling tokens left over to be sold
// along the bonding curve in the batch initial state [as if the buy orders
// never existed and the sell order was just smaller than originally thought]
uint256 remainingSellReturn = metaBatches[_batchId].formula.calculateSaleReturn(batch.supply, batch.balance, batch.reserveRatio, remainingSell);
// the total result of all sells is the original amount of buys which were matched
// plus the remaining sells which were executed along the bonding curve
batch.totalSellReturn = batch.totalBuySpend.add(remainingSellReturn);
} else {
// >> buy orders are worth more than sell orders
// 1. first we execute all pending sell orders at the current exact
// price because there is at least one buy order for each sell order
// 2. then the final buy return is the addition of this first
// matched return with the remaining bonding curve return
// the number of collaterals bought as a result of all sell orders matched at the
// current exact price [which is less than the total amount of collateral to be spent]
batch.totalSellReturn = resultOfSell;
// the number of collaterals left over to be spent along the curve which is the difference
// between the original total buy order and the result of all the sell orders
uint256 remainingBuy = batch.totalBuySpend.sub(resultOfSell);
// the amount of tokens generated by selling collaterals left over to be spent
// along the bonding curve in the batch initial state [as if the sell orders
// never existed and the buy order was just smaller than originally thought]
uint256 remainingBuyReturn = metaBatches[_batchId].formula.calculatePurchaseReturn(batch.supply, batch.balance, batch.reserveRatio, remainingBuy);
// the total result of all buys is the original amount of buys which were matched
// plus the remaining buys which were executed along the bonding curve
batch.totalBuyReturn = batch.totalSellSpend.add(remainingBuyReturn);
}
emit UpdatePricing(_batchId, _collateral, batch.totalBuySpend, batch.totalBuyReturn, batch.totalSellSpend, batch.totalSellReturn);
}
function _transfer(address _from, address _to, address _collateralToken, uint256 _amount) internal {
if (_collateralToken == ETH) {
_to.transfer(_amount);
} else {
require(ERC20(_collateralToken).safeTransferFrom(_from, _to, _amount), ERROR_TRANSFER_FROM_FAILED);
}
}
}
// File: @ablack/fundraising-shared-interfaces/contracts/IPresale.sol
pragma solidity 0.4.24;
contract IPresale {
function open() external;
function close() external;
function contribute(address _contributor, uint256 _value) external payable;
function refund(address _contributor, uint256 _vestedPurchaseId) external;
function contributionToTokens(uint256 _value) public view returns (uint256);
function contributionToken() public view returns (address);
}
// File: @ablack/fundraising-shared-interfaces/contracts/ITap.sol
pragma solidity 0.4.24;
contract ITap {
function updateBeneficiary(address _beneficiary) external;
function updateMaximumTapRateIncreasePct(uint256 _maximumTapRateIncreasePct) external;
function updateMaximumTapFloorDecreasePct(uint256 _maximumTapFloorDecreasePct) external;
function addTappedToken(address _token, uint256 _rate, uint256 _floor) external;
function updateTappedToken(address _token, uint256 _rate, uint256 _floor) external;
function resetTappedToken(address _token) external;
function updateTappedAmount(address _token) external;
function withdraw(address _token) external;
function getMaximumWithdrawal(address _token) public view returns (uint256);
function rates(address _token) public view returns (uint256);
}
// File: @ablack/fundraising-aragon-fundraising/contracts/AragonFundraisingController.sol
pragma solidity 0.4.24;
contract AragonFundraisingController is EtherTokenConstant, IsContract, IAragonFundraisingController, AragonApp {
using SafeERC20 for ERC20;
using SafeMath for uint256;
/**
Hardcoded constants to save gas
bytes32 public constant UPDATE_BENEFICIARY_ROLE = keccak256("UPDATE_BENEFICIARY_ROLE");
bytes32 public constant UPDATE_FEES_ROLE = keccak256("UPDATE_FEES_ROLE");
bytes32 public constant ADD_COLLATERAL_TOKEN_ROLE = keccak256("ADD_COLLATERAL_TOKEN_ROLE");
bytes32 public constant REMOVE_COLLATERAL_TOKEN_ROLE = keccak256("REMOVE_COLLATERAL_TOKEN_ROLE");
bytes32 public constant UPDATE_COLLATERAL_TOKEN_ROLE = keccak256("UPDATE_COLLATERAL_TOKEN_ROLE");
bytes32 public constant UPDATE_MAXIMUM_TAP_RATE_INCREASE_PCT_ROLE = keccak256("UPDATE_MAXIMUM_TAP_RATE_INCREASE_PCT_ROLE");
bytes32 public constant UPDATE_MAXIMUM_TAP_FLOOR_DECREASE_PCT_ROLE = keccak256("UPDATE_MAXIMUM_TAP_FLOOR_DECREASE_PCT_ROLE");
bytes32 public constant ADD_TOKEN_TAP_ROLE = keccak256("ADD_TOKEN_TAP_ROLE");
bytes32 public constant UPDATE_TOKEN_TAP_ROLE = keccak256("UPDATE_TOKEN_TAP_ROLE");
bytes32 public constant OPEN_PRESALE_ROLE = keccak256("OPEN_PRESALE_ROLE");
bytes32 public constant OPEN_TRADING_ROLE = keccak256("OPEN_TRADING_ROLE");
bytes32 public constant CONTRIBUTE_ROLE = keccak256("CONTRIBUTE_ROLE");
bytes32 public constant OPEN_BUY_ORDER_ROLE = keccak256("OPEN_BUY_ORDER_ROLE");
bytes32 public constant OPEN_SELL_ORDER_ROLE = keccak256("OPEN_SELL_ORDER_ROLE");
bytes32 public constant WITHDRAW_ROLE = keccak256("WITHDRAW_ROLE");
*/
bytes32 public constant UPDATE_BENEFICIARY_ROLE = 0xf7ea2b80c7b6a2cab2c11d2290cb005c3748397358a25e17113658c83b732593;
bytes32 public constant UPDATE_FEES_ROLE = 0x5f9be2932ed3a723f295a763be1804c7ebfd1a41c1348fb8bdf5be1c5cdca822;
bytes32 public constant ADD_COLLATERAL_TOKEN_ROLE = 0x217b79cb2bc7760defc88529853ef81ab33ae5bb315408ce9f5af09c8776662d;
bytes32 public constant REMOVE_COLLATERAL_TOKEN_ROLE = 0x2044e56de223845e4be7d0a6f4e9a29b635547f16413a6d1327c58d9db438ee2;
bytes32 public constant UPDATE_COLLATERAL_TOKEN_ROLE = 0xe0565c2c43e0d841e206bb36a37f12f22584b4652ccee6f9e0c071b697a2e13d;
bytes32 public constant UPDATE_MAXIMUM_TAP_RATE_INCREASE_PCT_ROLE = 0x5d94de7e429250eee4ff97e30ab9f383bea3cd564d6780e0a9e965b1add1d207;
bytes32 public constant UPDATE_MAXIMUM_TAP_FLOOR_DECREASE_PCT_ROLE = 0x57c9c67896cf0a4ffe92cbea66c2f7c34380af06bf14215dabb078cf8a6d99e1;
bytes32 public constant ADD_TOKEN_TAP_ROLE = 0xbc9cb5e3f7ce81c4fd021d86a4bcb193dee9df315b540808c3ed59a81e596207;
bytes32 public constant UPDATE_TOKEN_TAP_ROLE = 0xdb8c88bedbc61ea0f92e1ce46da0b7a915affbd46d1c76c4bbac9a209e4a8416;
bytes32 public constant OPEN_PRESALE_ROLE = 0xf323aa41eef4850a8ae7ebd047d4c89f01ce49c781f3308be67303db9cdd48c2;
bytes32 public constant OPEN_TRADING_ROLE = 0x26ce034204208c0bbca4c8a793d17b99e546009b1dd31d3c1ef761f66372caf6;
bytes32 public constant CONTRIBUTE_ROLE = 0x9ccaca4edf2127f20c425fdd86af1ba178b9e5bee280cd70d88ac5f6874c4f07;
bytes32 public constant OPEN_BUY_ORDER_ROLE = 0xa589c8f284b76fc8d510d9d553485c47dbef1b0745ae00e0f3fd4e28fcd77ea7;
bytes32 public constant OPEN_SELL_ORDER_ROLE = 0xd68ba2b769fa37a2a7bd4bed9241b448bc99eca41f519ef037406386a8f291c0;
bytes32 public constant WITHDRAW_ROLE = 0x5d8e12c39142ff96d79d04d15d1ba1269e4fe57bb9d26f43523628b34ba108ec;
uint256 public constant TO_RESET_CAP = 10;
string private constant ERROR_CONTRACT_IS_EOA = "FUNDRAISING_CONTRACT_IS_EOA";
string private constant ERROR_INVALID_TOKENS = "FUNDRAISING_INVALID_TOKENS";
IPresale public presale;
BatchedBancorMarketMaker public marketMaker;
Agent public reserve;
ITap public tap;
address[] public toReset;
/***** external functions *****/
/**
* @notice Initialize Aragon Fundraising controller
* @param _presale The address of the presale contract
* @param _marketMaker The address of the market maker contract
* @param _reserve The address of the reserve [pool] contract
* @param _tap The address of the tap contract
* @param _toReset The addresses of the tokens whose tap timestamps are to be reset [when presale is closed and trading is open]
*/
function initialize(
IPresale _presale,
BatchedBancorMarketMaker _marketMaker,
Agent _reserve,
ITap _tap,
address[] _toReset
)
external
onlyInit
{
require(isContract(_presale), ERROR_CONTRACT_IS_EOA);
require(isContract(_marketMaker), ERROR_CONTRACT_IS_EOA);
require(isContract(_reserve), ERROR_CONTRACT_IS_EOA);
require(isContract(_tap), ERROR_CONTRACT_IS_EOA);
require(_toReset.length < TO_RESET_CAP, ERROR_INVALID_TOKENS);
initialized();
presale = _presale;
marketMaker = _marketMaker;
reserve = _reserve;
tap = _tap;
for (uint256 i = 0; i < _toReset.length; i++) {
require(_tokenIsContractOrETH(_toReset[i]), ERROR_INVALID_TOKENS);
toReset.push(_toReset[i]);
}
}
/* generic settings related function */
/**
* @notice Update beneficiary to `_beneficiary`
* @param _beneficiary The address of the new beneficiary
*/
function updateBeneficiary(address _beneficiary) external auth(UPDATE_BENEFICIARY_ROLE) {
marketMaker.updateBeneficiary(_beneficiary);
tap.updateBeneficiary(_beneficiary);
}
/**
* @notice Update fees deducted from buy and sell orders to respectively `@formatPct(_buyFeePct)`% and `@formatPct(_sellFeePct)`%
* @param _buyFeePct The new fee to be deducted from buy orders [in PCT_BASE]
* @param _sellFeePct The new fee to be deducted from sell orders [in PCT_BASE]
*/
function updateFees(uint256 _buyFeePct, uint256 _sellFeePct) external auth(UPDATE_FEES_ROLE) {
marketMaker.updateFees(_buyFeePct, _sellFeePct);
}
/* presale related functions */
/**
* @notice Open presale
*/
function openPresale() external auth(OPEN_PRESALE_ROLE) {
presale.open();
}
/**
* @notice Close presale and open trading
*/
function closePresale() external isInitialized {
presale.close();
}
/**
* @notice Contribute to the presale up to `@tokenAmount(self.contributionToken(): address, _value)`
* @param _value The amount of contribution token to be spent
*/
function contribute(uint256 _value) external payable auth(CONTRIBUTE_ROLE) {
presale.contribute.value(msg.value)(msg.sender, _value);
}
/**
* @notice Refund `_contributor`'s presale contribution #`_vestedPurchaseId`
* @param _contributor The address of the contributor whose presale contribution is to be refunded
* @param _vestedPurchaseId The id of the contribution to be refunded
*/
function refund(address _contributor, uint256 _vestedPurchaseId) external isInitialized {
presale.refund(_contributor, _vestedPurchaseId);
}
/* market making related functions */
/**
* @notice Open trading [enabling users to open buy and sell orders]
*/
function openTrading() external auth(OPEN_TRADING_ROLE) {
for (uint256 i = 0; i < toReset.length; i++) {
if (tap.rates(toReset[i]) != uint256(0)) {
tap.resetTappedToken(toReset[i]);
}
}
marketMaker.open();
}
/**
* @notice Open a buy order worth `@tokenAmount(_collateral, _value)`
* @param _collateral The address of the collateral token to be spent
* @param _value The amount of collateral token to be spent
*/
function openBuyOrder(address _collateral, uint256 _value) external payable auth(OPEN_BUY_ORDER_ROLE) {
marketMaker.openBuyOrder.value(msg.value)(msg.sender, _collateral, _value);
}
/**
* @notice Open a sell order worth `@tokenAmount(self.token(): address, _amount)` against `_collateral.symbol(): string`
* @param _collateral The address of the collateral token to be returned
* @param _amount The amount of bonded token to be spent
*/
function openSellOrder(address _collateral, uint256 _amount) external auth(OPEN_SELL_ORDER_ROLE) {
marketMaker.openSellOrder(msg.sender, _collateral, _amount);
}
/**
* @notice Claim the results of `_collateral.symbol(): string` buy orders from batch #`_batchId`
* @param _buyer The address of the user whose buy orders are to be claimed
* @param _batchId The id of the batch in which buy orders are to be claimed
* @param _collateral The address of the collateral token against which buy orders are to be claimed
*/
function claimBuyOrder(address _buyer, uint256 _batchId, address _collateral) external isInitialized {
marketMaker.claimBuyOrder(_buyer, _batchId, _collateral);
}
/**
* @notice Claim the results of `_collateral.symbol(): string` sell orders from batch #`_batchId`
* @param _seller The address of the user whose sell orders are to be claimed
* @param _batchId The id of the batch in which sell orders are to be claimed
* @param _collateral The address of the collateral token against which sell orders are to be claimed
*/
function claimSellOrder(address _seller, uint256 _batchId, address _collateral) external isInitialized {
marketMaker.claimSellOrder(_seller, _batchId, _collateral);
}
/* collateral tokens related functions */
/**
* @notice Add `_collateral.symbol(): string` as a whitelisted collateral token
* @param _collateral The address of the collateral token to be whitelisted
* @param _virtualSupply The virtual supply to be used for that collateral token [in wei]
* @param _virtualBalance The virtual balance to be used for that collateral token [in wei]
* @param _reserveRatio The reserve ratio to be used for that collateral token [in PPM]
* @param _slippage The price slippage below which each market making batch is to be kept for that collateral token [in PCT_BASE]
* @param _rate The rate at which that token is to be tapped [in wei / block]
* @param _floor The floor above which the reserve [pool] balance for that token is to be kept [in wei]
*/
function addCollateralToken(
address _collateral,
uint256 _virtualSupply,
uint256 _virtualBalance,
uint32 _reserveRatio,
uint256 _slippage,
uint256 _rate,
uint256 _floor
)
external
auth(ADD_COLLATERAL_TOKEN_ROLE)
{
marketMaker.addCollateralToken(_collateral, _virtualSupply, _virtualBalance, _reserveRatio, _slippage);
if (_collateral != ETH) {
reserve.addProtectedToken(_collateral);
}
if (_rate > 0) {
tap.addTappedToken(_collateral, _rate, _floor);
}
}
/**
* @notice Re-add `_collateral.symbol(): string` as a whitelisted collateral token [if it has been un-whitelisted in the past]
* @param _collateral The address of the collateral token to be whitelisted
* @param _virtualSupply The virtual supply to be used for that collateral token [in wei]
* @param _virtualBalance The virtual balance to be used for that collateral token [in wei]
* @param _reserveRatio The reserve ratio to be used for that collateral token [in PPM]
* @param _slippage The price slippage below which each market making batch is to be kept for that collateral token [in PCT_BASE]
*/
function reAddCollateralToken(
address _collateral,
uint256 _virtualSupply,
uint256 _virtualBalance,
uint32 _reserveRatio,
uint256 _slippage
)
external
auth(ADD_COLLATERAL_TOKEN_ROLE)
{
marketMaker.addCollateralToken(_collateral, _virtualSupply, _virtualBalance, _reserveRatio, _slippage);
}
/**
* @notice Remove `_collateral.symbol(): string` as a whitelisted collateral token
* @param _collateral The address of the collateral token to be un-whitelisted
*/
function removeCollateralToken(address _collateral) external auth(REMOVE_COLLATERAL_TOKEN_ROLE) {
marketMaker.removeCollateralToken(_collateral);
// the token should still be tapped to avoid being locked
// the token should still be protected to avoid being spent
}
/**
* @notice Update `_collateral.symbol(): string` collateralization settings
* @param _collateral The address of the collateral token whose collateralization settings are to be updated
* @param _virtualSupply The new virtual supply to be used for that collateral token [in wei]
* @param _virtualBalance The new virtual balance to be used for that collateral token [in wei]
* @param _reserveRatio The new reserve ratio to be used for that collateral token [in PPM]
* @param _slippage The new price slippage below which each market making batch is to be kept for that collateral token [in PCT_BASE]
*/
function updateCollateralToken(
address _collateral,
uint256 _virtualSupply,
uint256 _virtualBalance,
uint32 _reserveRatio,
uint256 _slippage
)
external
auth(UPDATE_COLLATERAL_TOKEN_ROLE)
{
marketMaker.updateCollateralToken(_collateral, _virtualSupply, _virtualBalance, _reserveRatio, _slippage);
}
/* tap related functions */
/**
* @notice Update maximum tap rate increase percentage to `@formatPct(_maximumTapRateIncreasePct)`%
* @param _maximumTapRateIncreasePct The new maximum tap rate increase percentage to be allowed [in PCT_BASE]
*/
function updateMaximumTapRateIncreasePct(uint256 _maximumTapRateIncreasePct) external auth(UPDATE_MAXIMUM_TAP_RATE_INCREASE_PCT_ROLE) {
tap.updateMaximumTapRateIncreasePct(_maximumTapRateIncreasePct);
}
/**
* @notice Update maximum tap floor decrease percentage to `@formatPct(_maximumTapFloorDecreasePct)`%
* @param _maximumTapFloorDecreasePct The new maximum tap floor decrease percentage to be allowed [in PCT_BASE]
*/
function updateMaximumTapFloorDecreasePct(uint256 _maximumTapFloorDecreasePct) external auth(UPDATE_MAXIMUM_TAP_FLOOR_DECREASE_PCT_ROLE) {
tap.updateMaximumTapFloorDecreasePct(_maximumTapFloorDecreasePct);
}
/**
* @notice Add tap for `_token.symbol(): string` with a rate of `@tokenAmount(_token, _rate)` per block and a floor of `@tokenAmount(_token, _floor)`
* @param _token The address of the token to be tapped
* @param _rate The rate at which that token is to be tapped [in wei / block]
* @param _floor The floor above which the reserve [pool] balance for that token is to be kept [in wei]
*/
function addTokenTap(address _token, uint256 _rate, uint256 _floor) external auth(ADD_TOKEN_TAP_ROLE) {
tap.addTappedToken(_token, _rate, _floor);
}
/**
* @notice Update tap for `_token.symbol(): string` with a rate of about `@tokenAmount(_token, 4 * 60 * 24 * 30 * _rate)` per month and a floor of `@tokenAmount(_token, _floor)`
* @param _token The address of the token whose tap is to be updated
* @param _rate The new rate at which that token is to be tapped [in wei / block]
* @param _floor The new floor above which the reserve [pool] balance for that token is to be kept [in wei]
*/
function updateTokenTap(address _token, uint256 _rate, uint256 _floor) external auth(UPDATE_TOKEN_TAP_ROLE) {
tap.updateTappedToken(_token, _rate, _floor);
}
/**
* @notice Update tapped amount for `_token.symbol(): string`
* @param _token The address of the token whose tapped amount is to be updated
*/
function updateTappedAmount(address _token) external {
tap.updateTappedAmount(_token);
}
/**
* @notice Transfer about `@tokenAmount(_token, self.getMaximumWithdrawal(_token): uint256)` from the reserve to the beneficiary
* @param _token The address of the token to be transfered from the reserve to the beneficiary
*/
function withdraw(address _token) external auth(WITHDRAW_ROLE) {
tap.withdraw(_token);
}
/***** public view functions *****/
function token() public view isInitialized returns (address) {
return marketMaker.token();
}
function contributionToken() public view isInitialized returns (address) {
return presale.contributionToken();
}
function getMaximumWithdrawal(address _token) public view isInitialized returns (uint256) {
return tap.getMaximumWithdrawal(_token);
}
function collateralsToBeClaimed(address _collateral) public view isInitialized returns (uint256) {
return marketMaker.collateralsToBeClaimed(_collateral);
}
function balanceOf(address _who, address _token) public view isInitialized returns (uint256) {
uint256 balance = _token == ETH ? _who.balance : ERC20(_token).staticBalanceOf(_who);
if (_who == address(reserve)) {
return balance.sub(tap.getMaximumWithdrawal(_token));
} else {
return balance;
}
}
/***** internal functions *****/
function _tokenIsContractOrETH(address _token) internal view returns (bool) {
return isContract(_token) || _token == ETH;
}
}
// File: @ablack/fundraising-presale/contracts/Presale.sol
pragma solidity ^0.4.24;
contract Presale is IPresale, EtherTokenConstant, IsContract, AragonApp {
using SafeERC20 for ERC20;
using SafeMath for uint256;
using SafeMath64 for uint64;
/**
Hardcoded constants to save gas
bytes32 public constant OPEN_ROLE = keccak256("OPEN_ROLE");
bytes32 public constant CONTRIBUTE_ROLE = keccak256("CONTRIBUTE_ROLE");
*/
bytes32 public constant OPEN_ROLE = 0xefa06053e2ca99a43c97c4a4f3d8a394ee3323a8ff237e625fba09fe30ceb0a4;
bytes32 public constant CONTRIBUTE_ROLE = 0x9ccaca4edf2127f20c425fdd86af1ba178b9e5bee280cd70d88ac5f6874c4f07;
uint256 public constant PPM = 1000000; // 0% = 0 * 10 ** 4; 1% = 1 * 10 ** 4; 100% = 100 * 10 ** 4
string private constant ERROR_CONTRACT_IS_EOA = "PRESALE_CONTRACT_IS_EOA";
string private constant ERROR_INVALID_BENEFICIARY = "PRESALE_INVALID_BENEFICIARY";
string private constant ERROR_INVALID_CONTRIBUTE_TOKEN = "PRESALE_INVALID_CONTRIBUTE_TOKEN";
string private constant ERROR_INVALID_GOAL = "PRESALE_INVALID_GOAL";
string private constant ERROR_INVALID_EXCHANGE_RATE = "PRESALE_INVALID_EXCHANGE_RATE";
string private constant ERROR_INVALID_TIME_PERIOD = "PRESALE_INVALID_TIME_PERIOD";
string private constant ERROR_INVALID_PCT = "PRESALE_INVALID_PCT";
string private constant ERROR_INVALID_STATE = "PRESALE_INVALID_STATE";
string private constant ERROR_INVALID_CONTRIBUTE_VALUE = "PRESALE_INVALID_CONTRIBUTE_VALUE";
string private constant ERROR_INSUFFICIENT_BALANCE = "PRESALE_INSUFFICIENT_BALANCE";
string private constant ERROR_INSUFFICIENT_ALLOWANCE = "PRESALE_INSUFFICIENT_ALLOWANCE";
string private constant ERROR_NOTHING_TO_REFUND = "PRESALE_NOTHING_TO_REFUND";
string private constant ERROR_TOKEN_TRANSFER_REVERTED = "PRESALE_TOKEN_TRANSFER_REVERTED";
enum State {
Pending, // presale is idle and pending to be started
Funding, // presale has started and contributors can purchase tokens
Refunding, // presale has not reached goal within period and contributors can claim refunds
GoalReached, // presale has reached goal within period and trading is ready to be open
Closed // presale has reached goal within period, has been closed and trading has been open
}
IAragonFundraisingController public controller;
TokenManager public tokenManager;
ERC20 public token;
address public reserve;
address public beneficiary;
address public contributionToken;
uint256 public goal;
uint64 public period;
uint256 public exchangeRate;
uint64 public vestingCliffPeriod;
uint64 public vestingCompletePeriod;
uint256 public supplyOfferedPct;
uint256 public fundingForBeneficiaryPct;
uint64 public openDate;
bool public isClosed;
uint64 public vestingCliffDate;
uint64 public vestingCompleteDate;
uint256 public totalRaised;
mapping(address => mapping(uint256 => uint256)) public contributions; // contributor => (vestedPurchaseId => tokensSpent)
event SetOpenDate (uint64 date);
event Close ();
event Contribute (address indexed contributor, uint256 value, uint256 amount, uint256 vestedPurchaseId);
event Refund (address indexed contributor, uint256 value, uint256 amount, uint256 vestedPurchaseId);
/***** external function *****/
/**
* @notice Initialize presale
* @param _controller The address of the controller contract
* @param _tokenManager The address of the [bonded] token manager contract
* @param _reserve The address of the reserve [pool] contract
* @param _beneficiary The address of the beneficiary [to whom a percentage of the raised funds is be to be sent]
* @param _contributionToken The address of the token to be used to contribute
* @param _goal The goal to be reached by the end of that presale [in contribution token wei]
* @param _period The period within which to accept contribution for that presale
* @param _exchangeRate The exchangeRate [= 1/price] at which [bonded] tokens are to be purchased for that presale [in PPM]
* @param _vestingCliffPeriod The period during which purchased [bonded] tokens are to be cliffed
* @param _vestingCompletePeriod The complete period during which purchased [bonded] tokens are to be vested
* @param _supplyOfferedPct The percentage of the initial supply of [bonded] tokens to be offered during that presale [in PPM]
* @param _fundingForBeneficiaryPct The percentage of the raised contribution tokens to be sent to the beneficiary [instead of the fundraising reserve] when that presale is closed [in PPM]
* @param _openDate The date upon which that presale is to be open [ignored if 0]
*/
function initialize(
IAragonFundraisingController _controller,
TokenManager _tokenManager,
address _reserve,
address _beneficiary,
address _contributionToken,
uint256 _goal,
uint64 _period,
uint256 _exchangeRate,
uint64 _vestingCliffPeriod,
uint64 _vestingCompletePeriod,
uint256 _supplyOfferedPct,
uint256 _fundingForBeneficiaryPct,
uint64 _openDate
)
external
onlyInit
{
require(isContract(_controller), ERROR_CONTRACT_IS_EOA);
require(isContract(_tokenManager), ERROR_CONTRACT_IS_EOA);
require(isContract(_reserve), ERROR_CONTRACT_IS_EOA);
require(_beneficiary != address(0), ERROR_INVALID_BENEFICIARY);
require(isContract(_contributionToken) || _contributionToken == ETH, ERROR_INVALID_CONTRIBUTE_TOKEN);
require(_goal > 0, ERROR_INVALID_GOAL);
require(_period > 0, ERROR_INVALID_TIME_PERIOD);
require(_exchangeRate > 0, ERROR_INVALID_EXCHANGE_RATE);
require(_vestingCliffPeriod > _period, ERROR_INVALID_TIME_PERIOD);
require(_vestingCompletePeriod > _vestingCliffPeriod, ERROR_INVALID_TIME_PERIOD);
require(_supplyOfferedPct > 0 && _supplyOfferedPct <= PPM, ERROR_INVALID_PCT);
require(_fundingForBeneficiaryPct >= 0 && _fundingForBeneficiaryPct <= PPM, ERROR_INVALID_PCT);
initialized();
controller = _controller;
tokenManager = _tokenManager;
token = ERC20(_tokenManager.token());
reserve = _reserve;
beneficiary = _beneficiary;
contributionToken = _contributionToken;
goal = _goal;
period = _period;
exchangeRate = _exchangeRate;
vestingCliffPeriod = _vestingCliffPeriod;
vestingCompletePeriod = _vestingCompletePeriod;
supplyOfferedPct = _supplyOfferedPct;
fundingForBeneficiaryPct = _fundingForBeneficiaryPct;
if (_openDate != 0) {
_setOpenDate(_openDate);
}
}
/**
* @notice Open presale [enabling users to contribute]
*/
function open() external auth(OPEN_ROLE) {
require(state() == State.Pending, ERROR_INVALID_STATE);
require(openDate == 0, ERROR_INVALID_STATE);
_open();
}
/**
* @notice Contribute to the presale up to `@tokenAmount(self.contributionToken(): address, _value)`
* @param _contributor The address of the contributor
* @param _value The amount of contribution token to be spent
*/
function contribute(address _contributor, uint256 _value) external payable nonReentrant auth(CONTRIBUTE_ROLE) {
require(state() == State.Funding, ERROR_INVALID_STATE);
require(_value != 0, ERROR_INVALID_CONTRIBUTE_VALUE);
if (contributionToken == ETH) {
require(msg.value == _value, ERROR_INVALID_CONTRIBUTE_VALUE);
} else {
require(msg.value == 0, ERROR_INVALID_CONTRIBUTE_VALUE);
}
_contribute(_contributor, _value);
}
/**
* @notice Refund `_contributor`'s presale contribution #`_vestedPurchaseId`
* @param _contributor The address of the contributor whose presale contribution is to be refunded
* @param _vestedPurchaseId The id of the contribution to be refunded
*/
function refund(address _contributor, uint256 _vestedPurchaseId) external nonReentrant isInitialized {
require(state() == State.Refunding, ERROR_INVALID_STATE);
_refund(_contributor, _vestedPurchaseId);
}
/**
* @notice Close presale and open trading
*/
function close() external nonReentrant isInitialized {
require(state() == State.GoalReached, ERROR_INVALID_STATE);
_close();
}
/***** public view functions *****/
/**
* @notice Computes the amount of [bonded] tokens that would be purchased for `@tokenAmount(self.contributionToken(): address, _value)`
* @param _value The amount of contribution tokens to be used in that computation
*/
function contributionToTokens(uint256 _value) public view isInitialized returns (uint256) {
return _value.mul(exchangeRate).div(PPM);
}
function contributionToken() public view isInitialized returns (address) {
return contributionToken;
}
/**
* @notice Returns the current state of that presale
*/
function state() public view isInitialized returns (State) {
if (openDate == 0 || openDate > getTimestamp64()) {
return State.Pending;
}
if (totalRaised >= goal) {
if (isClosed) {
return State.Closed;
} else {
return State.GoalReached;
}
}
if (_timeSinceOpen() < period) {
return State.Funding;
} else {
return State.Refunding;
}
}
/***** internal functions *****/
function _timeSinceOpen() internal view returns (uint64) {
if (openDate == 0) {
return 0;
} else {
return getTimestamp64().sub(openDate);
}
}
function _setOpenDate(uint64 _date) internal {
require(_date >= getTimestamp64(), ERROR_INVALID_TIME_PERIOD);
openDate = _date;
_setVestingDatesWhenOpenDateIsKnown();
emit SetOpenDate(_date);
}
function _setVestingDatesWhenOpenDateIsKnown() internal {
vestingCliffDate = openDate.add(vestingCliffPeriod);
vestingCompleteDate = openDate.add(vestingCompletePeriod);
}
function _open() internal {
_setOpenDate(getTimestamp64());
}
function _contribute(address _contributor, uint256 _value) internal {
uint256 value = totalRaised.add(_value) > goal ? goal.sub(totalRaised) : _value;
if (contributionToken == ETH && _value > value) {
msg.sender.transfer(_value.sub(value));
}
// (contributor) ~~~> contribution tokens ~~~> (presale)
if (contributionToken != ETH) {
require(ERC20(contributionToken).balanceOf(_contributor) >= value, ERROR_INSUFFICIENT_BALANCE);
require(ERC20(contributionToken).allowance(_contributor, address(this)) >= value, ERROR_INSUFFICIENT_ALLOWANCE);
_transfer(contributionToken, _contributor, address(this), value);
}
// (mint ✨) ~~~> project tokens ~~~> (contributor)
uint256 tokensToSell = contributionToTokens(value);
tokenManager.issue(tokensToSell);
uint256 vestedPurchaseId = tokenManager.assignVested(
_contributor,
tokensToSell,
openDate,
vestingCliffDate,
vestingCompleteDate,
true /* revokable */
);
totalRaised = totalRaised.add(value);
// register contribution tokens spent in this purchase for a possible upcoming refund
contributions[_contributor][vestedPurchaseId] = value;
emit Contribute(_contributor, value, tokensToSell, vestedPurchaseId);
}
function _refund(address _contributor, uint256 _vestedPurchaseId) internal {
// recall how much contribution tokens are to be refund for this purchase
uint256 tokensToRefund = contributions[_contributor][_vestedPurchaseId];
require(tokensToRefund > 0, ERROR_NOTHING_TO_REFUND);
contributions[_contributor][_vestedPurchaseId] = 0;
// (presale) ~~~> contribution tokens ~~~> (contributor)
_transfer(contributionToken, address(this), _contributor, tokensToRefund);
/**
* NOTE
* the following lines assume that _contributor has not transfered any of its vested tokens
* for now TokenManager does not handle switching the transferrable status of its underlying token
* there is thus no way to enforce non-transferrability during the presale phase only
* this will be updated in a later version
*/
// (contributor) ~~~> project tokens ~~~> (token manager)
(uint256 tokensSold,,,,) = tokenManager.getVesting(_contributor, _vestedPurchaseId);
tokenManager.revokeVesting(_contributor, _vestedPurchaseId);
// (token manager) ~~~> project tokens ~~~> (burn 💥)
tokenManager.burn(address(tokenManager), tokensSold);
emit Refund(_contributor, tokensToRefund, tokensSold, _vestedPurchaseId);
}
function _close() internal {
isClosed = true;
// (presale) ~~~> contribution tokens ~~~> (beneficiary)
uint256 fundsForBeneficiary = totalRaised.mul(fundingForBeneficiaryPct).div(PPM);
if (fundsForBeneficiary > 0) {
_transfer(contributionToken, address(this), beneficiary, fundsForBeneficiary);
}
// (presale) ~~~> contribution tokens ~~~> (reserve)
uint256 tokensForReserve = contributionToken == ETH ? address(this).balance : ERC20(contributionToken).balanceOf(address(this));
_transfer(contributionToken, address(this), reserve, tokensForReserve);
// (mint ✨) ~~~> project tokens ~~~> (beneficiary)
uint256 tokensForBeneficiary = token.totalSupply().mul(PPM.sub(supplyOfferedPct)).div(supplyOfferedPct);
tokenManager.issue(tokensForBeneficiary);
tokenManager.assignVested(
beneficiary,
tokensForBeneficiary,
openDate,
vestingCliffDate,
vestingCompleteDate,
false /* revokable */
);
// open trading
controller.openTrading();
emit Close();
}
function _transfer(address _token, address _from, address _to, uint256 _amount) internal {
if (_token == ETH) {
require(_from == address(this), ERROR_TOKEN_TRANSFER_REVERTED);
require(_to != address(this), ERROR_TOKEN_TRANSFER_REVERTED);
_to.transfer(_amount);
} else {
if (_from == address(this)) {
require(ERC20(_token).safeTransfer(_to, _amount), ERROR_TOKEN_TRANSFER_REVERTED);
} else {
require(ERC20(_token).safeTransferFrom(_from, _to, _amount), ERROR_TOKEN_TRANSFER_REVERTED);
}
}
}
}
// File: @ablack/fundraising-tap/contracts/Tap.sol
pragma solidity 0.4.24;
contract Tap is ITap, TimeHelpers, EtherTokenConstant, IsContract, AragonApp {
using SafeERC20 for ERC20;
using SafeMath for uint256;
/**
Hardcoded constants to save gas
bytes32 public constant UPDATE_CONTROLLER_ROLE = keccak256("UPDATE_CONTROLLER_ROLE");
bytes32 public constant UPDATE_RESERVE_ROLE = keccak256("UPDATE_RESERVE_ROLE");
bytes32 public constant UPDATE_BENEFICIARY_ROLE = keccak256("UPDATE_BENEFICIARY_ROLE");
bytes32 public constant UPDATE_MAXIMUM_TAP_RATE_INCREASE_PCT_ROLE = keccak256("UPDATE_MAXIMUM_TAP_RATE_INCREASE_PCT_ROLE");
bytes32 public constant UPDATE_MAXIMUM_TAP_FLOOR_DECREASE_PCT_ROLE = keccak256("UPDATE_MAXIMUM_TAP_FLOOR_DECREASE_PCT_ROLE");
bytes32 public constant ADD_TAPPED_TOKEN_ROLE = keccak256("ADD_TAPPED_TOKEN_ROLE");
bytes32 public constant REMOVE_TAPPED_TOKEN_ROLE = keccak256("REMOVE_TAPPED_TOKEN_ROLE");
bytes32 public constant UPDATE_TAPPED_TOKEN_ROLE = keccak256("UPDATE_TAPPED_TOKEN_ROLE");
bytes32 public constant RESET_TAPPED_TOKEN_ROLE = keccak256("RESET_TAPPED_TOKEN_ROLE");
bytes32 public constant WITHDRAW_ROLE = keccak256("WITHDRAW_ROLE");
*/
bytes32 public constant UPDATE_CONTROLLER_ROLE = 0x454b5d0dbb74f012faf1d3722ea441689f97dc957dd3ca5335b4969586e5dc30;
bytes32 public constant UPDATE_RESERVE_ROLE = 0x7984c050833e1db850f5aa7476710412fd2983fcec34da049502835ad7aed4f7;
bytes32 public constant UPDATE_BENEFICIARY_ROLE = 0xf7ea2b80c7b6a2cab2c11d2290cb005c3748397358a25e17113658c83b732593;
bytes32 public constant UPDATE_MAXIMUM_TAP_RATE_INCREASE_PCT_ROLE = 0x5d94de7e429250eee4ff97e30ab9f383bea3cd564d6780e0a9e965b1add1d207;
bytes32 public constant UPDATE_MAXIMUM_TAP_FLOOR_DECREASE_PCT_ROLE = 0x57c9c67896cf0a4ffe92cbea66c2f7c34380af06bf14215dabb078cf8a6d99e1;
bytes32 public constant ADD_TAPPED_TOKEN_ROLE = 0x5bc3b608e6be93b75a1c472a4a5bea3d31eabae46bf968e4bc4c7701562114dc;
bytes32 public constant REMOVE_TAPPED_TOKEN_ROLE = 0xd76960be78bfedc5b40ce4fa64a2f8308f39dd2cbb1f9676dbc4ce87b817befd;
bytes32 public constant UPDATE_TAPPED_TOKEN_ROLE = 0x83201394534c53ae0b4696fd49a933082d3e0525aa5a3d0a14a2f51e12213288;
bytes32 public constant RESET_TAPPED_TOKEN_ROLE = 0x294bf52c518669359157a9fe826e510dfc3dbd200d44bf77ec9536bff34bc29e;
bytes32 public constant WITHDRAW_ROLE = 0x5d8e12c39142ff96d79d04d15d1ba1269e4fe57bb9d26f43523628b34ba108ec;
uint256 public constant PCT_BASE = 10 ** 18; // 0% = 0; 1% = 10 ** 16; 100% = 10 ** 18
string private constant ERROR_CONTRACT_IS_EOA = "TAP_CONTRACT_IS_EOA";
string private constant ERROR_INVALID_BENEFICIARY = "TAP_INVALID_BENEFICIARY";
string private constant ERROR_INVALID_BATCH_BLOCKS = "TAP_INVALID_BATCH_BLOCKS";
string private constant ERROR_INVALID_FLOOR_DECREASE_PCT = "TAP_INVALID_FLOOR_DECREASE_PCT";
string private constant ERROR_INVALID_TOKEN = "TAP_INVALID_TOKEN";
string private constant ERROR_INVALID_TAP_RATE = "TAP_INVALID_TAP_RATE";
string private constant ERROR_INVALID_TAP_UPDATE = "TAP_INVALID_TAP_UPDATE";
string private constant ERROR_TOKEN_ALREADY_TAPPED = "TAP_TOKEN_ALREADY_TAPPED";
string private constant ERROR_TOKEN_NOT_TAPPED = "TAP_TOKEN_NOT_TAPPED";
string private constant ERROR_WITHDRAWAL_AMOUNT_ZERO = "TAP_WITHDRAWAL_AMOUNT_ZERO";
IAragonFundraisingController public controller;
Vault public reserve;
address public beneficiary;
uint256 public batchBlocks;
uint256 public maximumTapRateIncreasePct;
uint256 public maximumTapFloorDecreasePct;
mapping (address => uint256) public tappedAmounts;
mapping (address => uint256) public rates;
mapping (address => uint256) public floors;
mapping (address => uint256) public lastTappedAmountUpdates; // batch ids [block numbers]
mapping (address => uint256) public lastTapUpdates; // timestamps
event UpdateBeneficiary (address indexed beneficiary);
event UpdateMaximumTapRateIncreasePct (uint256 maximumTapRateIncreasePct);
event UpdateMaximumTapFloorDecreasePct(uint256 maximumTapFloorDecreasePct);
event AddTappedToken (address indexed token, uint256 rate, uint256 floor);
event RemoveTappedToken (address indexed token);
event UpdateTappedToken (address indexed token, uint256 rate, uint256 floor);
event ResetTappedToken (address indexed token);
event UpdateTappedAmount (address indexed token, uint256 tappedAmount);
event Withdraw (address indexed token, uint256 amount);
/***** external functions *****/
/**
* @notice Initialize tap
* @param _controller The address of the controller contract
* @param _reserve The address of the reserve [pool] contract
* @param _beneficiary The address of the beneficiary [to whom funds are to be withdrawn]
* @param _batchBlocks The number of blocks batches are to last
* @param _maximumTapRateIncreasePct The maximum tap rate increase percentage allowed [in PCT_BASE]
* @param _maximumTapFloorDecreasePct The maximum tap floor decrease percentage allowed [in PCT_BASE]
*/
function initialize(
IAragonFundraisingController _controller,
Vault _reserve,
address _beneficiary,
uint256 _batchBlocks,
uint256 _maximumTapRateIncreasePct,
uint256 _maximumTapFloorDecreasePct
)
external
onlyInit
{
require(isContract(_controller), ERROR_CONTRACT_IS_EOA);
require(isContract(_reserve), ERROR_CONTRACT_IS_EOA);
require(_beneficiaryIsValid(_beneficiary), ERROR_INVALID_BENEFICIARY);
require(_batchBlocks != 0, ERROR_INVALID_BATCH_BLOCKS);
require(_maximumTapFloorDecreasePctIsValid(_maximumTapFloorDecreasePct), ERROR_INVALID_FLOOR_DECREASE_PCT);
initialized();
controller = _controller;
reserve = _reserve;
beneficiary = _beneficiary;
batchBlocks = _batchBlocks;
maximumTapRateIncreasePct = _maximumTapRateIncreasePct;
maximumTapFloorDecreasePct = _maximumTapFloorDecreasePct;
}
/**
* @notice Update beneficiary to `_beneficiary`
* @param _beneficiary The address of the new beneficiary [to whom funds are to be withdrawn]
*/
function updateBeneficiary(address _beneficiary) external auth(UPDATE_BENEFICIARY_ROLE) {
require(_beneficiaryIsValid(_beneficiary), ERROR_INVALID_BENEFICIARY);
_updateBeneficiary(_beneficiary);
}
/**
* @notice Update maximum tap rate increase percentage to `@formatPct(_maximumTapRateIncreasePct)`%
* @param _maximumTapRateIncreasePct The new maximum tap rate increase percentage to be allowed [in PCT_BASE]
*/
function updateMaximumTapRateIncreasePct(uint256 _maximumTapRateIncreasePct) external auth(UPDATE_MAXIMUM_TAP_RATE_INCREASE_PCT_ROLE) {
_updateMaximumTapRateIncreasePct(_maximumTapRateIncreasePct);
}
/**
* @notice Update maximum tap floor decrease percentage to `@formatPct(_maximumTapFloorDecreasePct)`%
* @param _maximumTapFloorDecreasePct The new maximum tap floor decrease percentage to be allowed [in PCT_BASE]
*/
function updateMaximumTapFloorDecreasePct(uint256 _maximumTapFloorDecreasePct) external auth(UPDATE_MAXIMUM_TAP_FLOOR_DECREASE_PCT_ROLE) {
require(_maximumTapFloorDecreasePctIsValid(_maximumTapFloorDecreasePct), ERROR_INVALID_FLOOR_DECREASE_PCT);
_updateMaximumTapFloorDecreasePct(_maximumTapFloorDecreasePct);
}
/**
* @notice Add tap for `_token.symbol(): string` with a rate of `@tokenAmount(_token, _rate)` per block and a floor of `@tokenAmount(_token, _floor)`
* @param _token The address of the token to be tapped
* @param _rate The rate at which that token is to be tapped [in wei / block]
* @param _floor The floor above which the reserve [pool] balance for that token is to be kept [in wei]
*/
function addTappedToken(address _token, uint256 _rate, uint256 _floor) external auth(ADD_TAPPED_TOKEN_ROLE) {
require(_tokenIsContractOrETH(_token), ERROR_INVALID_TOKEN);
require(!_tokenIsTapped(_token), ERROR_TOKEN_ALREADY_TAPPED);
require(_tapRateIsValid(_rate), ERROR_INVALID_TAP_RATE);
_addTappedToken(_token, _rate, _floor);
}
/**
* @notice Remove tap for `_token.symbol(): string`
* @param _token The address of the token to be un-tapped
*/
function removeTappedToken(address _token) external auth(REMOVE_TAPPED_TOKEN_ROLE) {
require(_tokenIsTapped(_token), ERROR_TOKEN_NOT_TAPPED);
_removeTappedToken(_token);
}
/**
* @notice Update tap for `_token.symbol(): string` with a rate of `@tokenAmount(_token, _rate)` per block and a floor of `@tokenAmount(_token, _floor)`
* @param _token The address of the token whose tap is to be updated
* @param _rate The new rate at which that token is to be tapped [in wei / block]
* @param _floor The new floor above which the reserve [pool] balance for that token is to be kept [in wei]
*/
function updateTappedToken(address _token, uint256 _rate, uint256 _floor) external auth(UPDATE_TAPPED_TOKEN_ROLE) {
require(_tokenIsTapped(_token), ERROR_TOKEN_NOT_TAPPED);
require(_tapRateIsValid(_rate), ERROR_INVALID_TAP_RATE);
require(_tapUpdateIsValid(_token, _rate, _floor), ERROR_INVALID_TAP_UPDATE);
_updateTappedToken(_token, _rate, _floor);
}
/**
* @notice Reset tap timestamps for `_token.symbol(): string`
* @param _token The address of the token whose tap timestamps are to be reset
*/
function resetTappedToken(address _token) external auth(RESET_TAPPED_TOKEN_ROLE) {
require(_tokenIsTapped(_token), ERROR_TOKEN_NOT_TAPPED);
_resetTappedToken(_token);
}
/**
* @notice Update tapped amount for `_token.symbol(): string`
* @param _token The address of the token whose tapped amount is to be updated
*/
function updateTappedAmount(address _token) external {
require(_tokenIsTapped(_token), ERROR_TOKEN_NOT_TAPPED);
_updateTappedAmount(_token);
}
/**
* @notice Transfer about `@tokenAmount(_token, self.getMaximalWithdrawal(_token): uint256)` from `self.reserve()` to `self.beneficiary()`
* @param _token The address of the token to be transfered
*/
function withdraw(address _token) external auth(WITHDRAW_ROLE) {
require(_tokenIsTapped(_token), ERROR_TOKEN_NOT_TAPPED);
uint256 amount = _updateTappedAmount(_token);
require(amount > 0, ERROR_WITHDRAWAL_AMOUNT_ZERO);
_withdraw(_token, amount);
}
/***** public view functions *****/
function getMaximumWithdrawal(address _token) public view isInitialized returns (uint256) {
return _tappedAmount(_token);
}
function rates(address _token) public view isInitialized returns (uint256) {
return rates[_token];
}
/***** internal functions *****/
/* computation functions */
function _currentBatchId() internal view returns (uint256) {
return (block.number.div(batchBlocks)).mul(batchBlocks);
}
function _tappedAmount(address _token) internal view returns (uint256) {
uint256 toBeKept = controller.collateralsToBeClaimed(_token).add(floors[_token]);
uint256 balance = _token == ETH ? address(reserve).balance : ERC20(_token).staticBalanceOf(reserve);
uint256 flow = (_currentBatchId().sub(lastTappedAmountUpdates[_token])).mul(rates[_token]);
uint256 tappedAmount = tappedAmounts[_token].add(flow);
/**
* whatever happens enough collateral should be
* kept in the reserve pool to guarantee that
* its balance is kept above the floor once
* all pending sell orders are claimed
*/
/**
* the reserve's balance is already below the balance to be kept
* the tapped amount should be reset to zero
*/
if (balance <= toBeKept) {
return 0;
}
/**
* the reserve's balance minus the upcoming tap flow would be below the balance to be kept
* the flow should be reduced to balance - toBeKept
*/
if (balance <= toBeKept.add(tappedAmount)) {
return balance.sub(toBeKept);
}
/**
* the reserve's balance minus the upcoming flow is above the balance to be kept
* the flow can be added to the tapped amount
*/
return tappedAmount;
}
/* check functions */
function _beneficiaryIsValid(address _beneficiary) internal pure returns (bool) {
return _beneficiary != address(0);
}
function _maximumTapFloorDecreasePctIsValid(uint256 _maximumTapFloorDecreasePct) internal pure returns (bool) {
return _maximumTapFloorDecreasePct <= PCT_BASE;
}
function _tokenIsContractOrETH(address _token) internal view returns (bool) {
return isContract(_token) || _token == ETH;
}
function _tokenIsTapped(address _token) internal view returns (bool) {
return rates[_token] != uint256(0);
}
function _tapRateIsValid(uint256 _rate) internal pure returns (bool) {
return _rate != 0;
}
function _tapUpdateIsValid(address _token, uint256 _rate, uint256 _floor) internal view returns (bool) {
return _tapRateUpdateIsValid(_token, _rate) && _tapFloorUpdateIsValid(_token, _floor);
}
function _tapRateUpdateIsValid(address _token, uint256 _rate) internal view returns (bool) {
uint256 rate = rates[_token];
if (_rate <= rate) {
return true;
}
if (getTimestamp() < lastTapUpdates[_token] + 30 days) {
return false;
}
if (_rate.mul(PCT_BASE) <= rate.mul(PCT_BASE.add(maximumTapRateIncreasePct))) {
return true;
}
return false;
}
function _tapFloorUpdateIsValid(address _token, uint256 _floor) internal view returns (bool) {
uint256 floor = floors[_token];
if (_floor >= floor) {
return true;
}
if (getTimestamp() < lastTapUpdates[_token] + 30 days) {
return false;
}
if (maximumTapFloorDecreasePct >= PCT_BASE) {
return true;
}
if (_floor.mul(PCT_BASE) >= floor.mul(PCT_BASE.sub(maximumTapFloorDecreasePct))) {
return true;
}
return false;
}
/* state modifying functions */
function _updateTappedAmount(address _token) internal returns (uint256) {
uint256 tappedAmount = _tappedAmount(_token);
lastTappedAmountUpdates[_token] = _currentBatchId();
tappedAmounts[_token] = tappedAmount;
emit UpdateTappedAmount(_token, tappedAmount);
return tappedAmount;
}
function _updateBeneficiary(address _beneficiary) internal {
beneficiary = _beneficiary;
emit UpdateBeneficiary(_beneficiary);
}
function _updateMaximumTapRateIncreasePct(uint256 _maximumTapRateIncreasePct) internal {
maximumTapRateIncreasePct = _maximumTapRateIncreasePct;
emit UpdateMaximumTapRateIncreasePct(_maximumTapRateIncreasePct);
}
function _updateMaximumTapFloorDecreasePct(uint256 _maximumTapFloorDecreasePct) internal {
maximumTapFloorDecreasePct = _maximumTapFloorDecreasePct;
emit UpdateMaximumTapFloorDecreasePct(_maximumTapFloorDecreasePct);
}
function _addTappedToken(address _token, uint256 _rate, uint256 _floor) internal {
/**
* NOTE
* 1. if _token is tapped in the middle of a batch it will
* reach the next batch faster than what it normally takes
* to go through a batch [e.g. one block later]
* 2. this will allow for a higher withdrawal than expected
* a few blocks after _token is tapped
* 3. this is not a problem because this extra amount is
* static [at most rates[_token] * batchBlocks] and does
* not increase in time
*/
rates[_token] = _rate;
floors[_token] = _floor;
lastTappedAmountUpdates[_token] = _currentBatchId();
lastTapUpdates[_token] = getTimestamp();
emit AddTappedToken(_token, _rate, _floor);
}
function _removeTappedToken(address _token) internal {
delete tappedAmounts[_token];
delete rates[_token];
delete floors[_token];
delete lastTappedAmountUpdates[_token];
delete lastTapUpdates[_token];
emit RemoveTappedToken(_token);
}
function _updateTappedToken(address _token, uint256 _rate, uint256 _floor) internal {
/**
* NOTE
* withdraw before updating to keep the reserve
* actual balance [balance - virtual withdrawal]
* continuous in time [though a floor update can
* still break this continuity]
*/
uint256 amount = _updateTappedAmount(_token);
if (amount > 0) {
_withdraw(_token, amount);
}
rates[_token] = _rate;
floors[_token] = _floor;
lastTapUpdates[_token] = getTimestamp();
emit UpdateTappedToken(_token, _rate, _floor);
}
function _resetTappedToken(address _token) internal {
tappedAmounts[_token] = 0;
lastTappedAmountUpdates[_token] = _currentBatchId();
lastTapUpdates[_token] = getTimestamp();
emit ResetTappedToken(_token);
}
function _withdraw(address _token, uint256 _amount) internal {
tappedAmounts[_token] = tappedAmounts[_token].sub(_amount);
reserve.transfer(_token, beneficiary, _amount); // vault contract's transfer method already reverts on error
emit Withdraw(_token, _amount);
}
}
// File: contracts/AavegotchiTBCTemplate.sol
pragma solidity 0.4.24;
contract AavegotchiTBCTemplate is EtherTokenConstant, BaseTemplate {
string private constant ERROR_BAD_SETTINGS = "FM_BAD_SETTINGS";
string private constant ERROR_MISSING_CACHE = "FM_MISSING_CACHE";
bool private constant BOARD_TRANSFERABLE = false;
uint8 private constant BOARD_TOKEN_DECIMALS = uint8(0);
uint256 private constant BOARD_MAX_PER_ACCOUNT = uint256(1);
bool private constant SHARE_TRANSFERABLE = true;
uint8 private constant SHARE_TOKEN_DECIMALS = uint8(18);
uint256 private constant SHARE_MAX_PER_ACCOUNT = uint256(0);
uint64 private constant DEFAULT_FINANCE_PERIOD = uint64(30 days);
uint256 private constant BUY_FEE_PCT = 0;
uint256 private constant SELL_FEE_PCT = 0;
uint32 private constant DAI_RESERVE_RATIO = 333333; // 33%
uint32 private constant ANT_RESERVE_RATIO = 10000; // 1%
bytes32 private constant BANCOR_FORMULA_ID = 0xd71dde5e4bea1928026c1779bde7ed27bd7ef3d0ce9802e4117631eb6fa4ed7d;
bytes32 private constant PRESALE_ID = 0x5de9bbdeaf6584c220c7b7f1922383bcd8bbcd4b48832080afd9d5ebf9a04df5;
bytes32 private constant MARKET_MAKER_ID = 0xc2bb88ab974c474221f15f691ed9da38be2f5d37364180cec05403c656981bf0;
bytes32 private constant ARAGON_FUNDRAISING_ID = 0x668ac370eed7e5861234d1c0a1e512686f53594fcb887e5bcecc35675a4becac;
bytes32 private constant TAP_ID = 0x82967efab7144b764bc9bca2f31a721269b6618c0ff4e50545737700a5e9c9dc;
struct Cache {
address dao;
address boardTokenManager;
address boardVoting;
address vault;
address finance;
address shareVoting;
address shareTokenManager;
address reserve;
address presale;
address marketMaker;
address tap;
address controller;
}
address[] public collaterals;
mapping (address => Cache) private cache;
constructor(
DAOFactory _daoFactory,
ENS _ens,
MiniMeTokenFactory _miniMeFactory,
IFIFSResolvingRegistrar _aragonID,
address _dai,
address _ant
)
BaseTemplate(_daoFactory, _ens, _miniMeFactory, _aragonID)
public
{
_ensureAragonIdIsValid(_aragonID);
_ensureMiniMeFactoryIsValid(_miniMeFactory);
require(isContract(_dai), ERROR_BAD_SETTINGS);
require(isContract(_ant), ERROR_BAD_SETTINGS);
require(_dai != _ant, ERROR_BAD_SETTINGS);
collaterals.push(_dai);
collaterals.push(_ant);
}
/***** external functions *****/
function prepareInstance(
string _boardTokenName,
string _boardTokenSymbol,
address[] _boardMembers,
uint64[3] _boardVotingSettings,
uint64 _financePeriod
)
external
{
require(_boardMembers.length > 0, ERROR_BAD_SETTINGS);
require(_boardVotingSettings.length == 3, ERROR_BAD_SETTINGS);
// deploy DAO
(Kernel dao, ACL acl) = _createDAO();
// deploy board token
MiniMeToken boardToken = _createToken(_boardTokenName, _boardTokenSymbol, BOARD_TOKEN_DECIMALS);
// install board apps
TokenManager tm = _installBoardApps(dao, boardToken, _boardVotingSettings, _financePeriod);
// mint board tokens
_mintTokens(acl, tm, _boardMembers, 1);
// cache DAO
_cacheDao(dao);
}
function installShareApps(
string _shareTokenName,
string _shareTokenSymbol,
uint64[3] _shareVotingSettings
)
external
{
require(_shareVotingSettings.length == 3, ERROR_BAD_SETTINGS);
_ensureBoardAppsCache();
Kernel dao = _daoCache();
// deploy share token
MiniMeToken shareToken = _createToken(_shareTokenName, _shareTokenSymbol, SHARE_TOKEN_DECIMALS);
// install share apps
_installShareApps(dao, shareToken, _shareVotingSettings);
// setup board apps permissions [now that share apps have been installed]
_setupBoardPermissions(dao);
}
function installFundraisingApps(
uint256 _goal,
uint64 _period,
uint256 _exchangeRate,
uint64 _vestingCliffPeriod,
uint64 _vestingCompletePeriod,
uint256 _supplyOfferedPct,
uint256 _fundingForBeneficiaryPct,
uint64 _openDate,
uint256 _batchBlocks,
uint256 _maxTapRateIncreasePct,
uint256 _maxTapFloorDecreasePct
)
external
{
_ensureShareAppsCache();
Kernel dao = _daoCache();
// install fundraising apps
_installFundraisingApps(
dao,
_goal,
_period,
_exchangeRate,
_vestingCliffPeriod,
_vestingCompletePeriod,
_supplyOfferedPct,
_fundingForBeneficiaryPct,
_openDate,
_batchBlocks,
_maxTapRateIncreasePct,
_maxTapFloorDecreasePct
);
// setup share apps permissions [now that fundraising apps have been installed]
_setupSharePermissions(dao);
// setup fundraising apps permissions
_setupFundraisingPermissions(dao);
}
function finalizeInstance(
string _id,
uint256[2] _virtualSupplies,
uint256[2] _virtualBalances,
uint256[2] _slippages,
uint256 _rateDAI,
uint256 _floorDAI
)
external
{
require(bytes(_id).length > 0, ERROR_BAD_SETTINGS);
require(_virtualSupplies.length == 2, ERROR_BAD_SETTINGS);
require(_virtualBalances.length == 2, ERROR_BAD_SETTINGS);
require(_slippages.length == 2, ERROR_BAD_SETTINGS);
_ensureFundraisingAppsCache();
Kernel dao = _daoCache();
ACL acl = ACL(dao.acl());
(, Voting shareVoting) = _shareAppsCache();
// setup collaterals
_setupCollaterals(dao, _virtualSupplies, _virtualBalances, _slippages, _rateDAI, _floorDAI);
// setup EVM script registry permissions
_createEvmScriptsRegistryPermissions(acl, shareVoting, shareVoting);
// clear DAO permissions
_transferRootPermissionsFromTemplateAndFinalizeDAO(dao, shareVoting, shareVoting);
// register id
_registerID(_id, address(dao));
// clear cache
_clearCache();
}
/***** internal apps installation functions *****/
function _installBoardApps(Kernel _dao, MiniMeToken _token, uint64[3] _votingSettings, uint64 _financePeriod)
internal
returns (TokenManager)
{
TokenManager tm = _installTokenManagerApp(_dao, _token, BOARD_TRANSFERABLE, BOARD_MAX_PER_ACCOUNT);
Voting voting = _installVotingApp(_dao, _token, _votingSettings);
Vault vault = _installVaultApp(_dao);
Finance finance = _installFinanceApp(_dao, vault, _financePeriod == 0 ? DEFAULT_FINANCE_PERIOD : _financePeriod);
_cacheBoardApps(tm, voting, vault, finance);
return tm;
}
function _installShareApps(Kernel _dao, MiniMeToken _shareToken, uint64[3] _shareVotingSettings)
internal
{
TokenManager tm = _installTokenManagerApp(_dao, _shareToken, SHARE_TRANSFERABLE, SHARE_MAX_PER_ACCOUNT);
Voting voting = _installVotingApp(_dao, _shareToken, _shareVotingSettings);
_cacheShareApps(tm, voting);
}
function _installFundraisingApps(
Kernel _dao,
uint256 _goal,
uint64 _period,
uint256 _exchangeRate,
uint64 _vestingCliffPeriod,
uint64 _vestingCompletePeriod,
uint256 _supplyOfferedPct,
uint256 _fundingForBeneficiaryPct,
uint64 _openDate,
uint256 _batchBlocks,
uint256 _maxTapRateIncreasePct,
uint256 _maxTapFloorDecreasePct
)
internal
{
_proxifyFundraisingApps(_dao);
_initializePresale(
_goal,
_period,
_exchangeRate,
_vestingCliffPeriod,
_vestingCompletePeriod,
_supplyOfferedPct,
_fundingForBeneficiaryPct,
_openDate
);
_initializeMarketMaker(_batchBlocks);
_initializeTap(_batchBlocks, _maxTapRateIncreasePct, _maxTapFloorDecreasePct);
_initializeController();
}
function _proxifyFundraisingApps(Kernel _dao) internal {
Agent reserve = _installNonDefaultAgentApp(_dao);
Presale presale = Presale(_registerApp(_dao, PRESALE_ID));
BatchedBancorMarketMaker marketMaker = BatchedBancorMarketMaker(_registerApp(_dao, MARKET_MAKER_ID));
Tap tap = Tap(_registerApp(_dao, TAP_ID));
AragonFundraisingController controller = AragonFundraisingController(_registerApp(_dao, ARAGON_FUNDRAISING_ID));
_cacheFundraisingApps(reserve, presale, marketMaker, tap, controller);
}
/***** internal apps initialization functions *****/
function _initializePresale(
uint256 _goal,
uint64 _period,
uint256 _exchangeRate,
uint64 _vestingCliffPeriod,
uint64 _vestingCompletePeriod,
uint256 _supplyOfferedPct,
uint256 _fundingForBeneficiaryPct,
uint64 _openDate
)
internal
{
_presaleCache().initialize(
_controllerCache(),
_shareTMCache(),
_reserveCache(),
_vaultCache(),
collaterals[0],
_goal,
_period,
_exchangeRate,
_vestingCliffPeriod,
_vestingCompletePeriod,
_supplyOfferedPct,
_fundingForBeneficiaryPct,
_openDate
);
}
function _initializeMarketMaker(uint256 _batchBlocks) internal {
IBancorFormula bancorFormula = IBancorFormula(_latestVersionAppBase(BANCOR_FORMULA_ID));
(,, Vault beneficiary,) = _boardAppsCache();
(TokenManager shareTM,) = _shareAppsCache();
(Agent reserve,, BatchedBancorMarketMaker marketMaker,, AragonFundraisingController controller) = _fundraisingAppsCache();
marketMaker.initialize(controller, shareTM, bancorFormula, reserve, beneficiary, _batchBlocks, BUY_FEE_PCT, SELL_FEE_PCT);
}
function _initializeTap(uint256 _batchBlocks, uint256 _maxTapRateIncreasePct, uint256 _maxTapFloorDecreasePct) internal {
(,, Vault beneficiary,) = _boardAppsCache();
(Agent reserve,,, Tap tap, AragonFundraisingController controller) = _fundraisingAppsCache();
tap.initialize(controller, reserve, beneficiary, _batchBlocks, _maxTapRateIncreasePct, _maxTapFloorDecreasePct);
}
function _initializeController() internal {
(Agent reserve, Presale presale, BatchedBancorMarketMaker marketMaker, Tap tap, AragonFundraisingController controller) = _fundraisingAppsCache();
address[] memory toReset = new address[](1);
toReset[0] = collaterals[0];
controller.initialize(presale, marketMaker, reserve, tap, toReset);
}
/***** internal setup functions *****/
function _setupCollaterals(
Kernel _dao,
uint256[2] _virtualSupplies,
uint256[2] _virtualBalances,
uint256[2] _slippages,
uint256 _rateDAI,
uint256 _floorDAI
)
internal
{
ACL acl = ACL(_dao.acl());
(, Voting shareVoting) = _shareAppsCache();
(,,,, AragonFundraisingController controller) = _fundraisingAppsCache();
// create and grant ADD_COLLATERAL_TOKEN_ROLE to this template
_createPermissionForTemplate(acl, address(controller), controller.ADD_COLLATERAL_TOKEN_ROLE());
// add DAI both as a protected collateral and a tapped token
controller.addCollateralToken(
collaterals[0],
_virtualSupplies[0],
_virtualBalances[0],
DAI_RESERVE_RATIO,
_slippages[0],
_rateDAI,
_floorDAI
);
// add ANT as a protected collateral [but not as a tapped token]
controller.addCollateralToken(
collaterals[1],
_virtualSupplies[1],
_virtualBalances[1],
ANT_RESERVE_RATIO,
_slippages[1],
0,
0
);
// transfer ADD_COLLATERAL_TOKEN_ROLE
_transferPermissionFromTemplate(acl, controller, shareVoting, controller.ADD_COLLATERAL_TOKEN_ROLE(), shareVoting);
}
/***** internal permissions functions *****/
function _setupBoardPermissions(Kernel _dao) internal {
ACL acl = ACL(_dao.acl());
(TokenManager boardTM, Voting boardVoting, Vault vault, Finance finance) = _boardAppsCache();
(, Voting shareVoting) = _shareAppsCache();
// token manager
_createTokenManagerPermissions(acl, boardTM, boardVoting, shareVoting);
// voting
_createVotingPermissions(acl, boardVoting, boardVoting, boardTM, shareVoting);
// vault
_createVaultPermissions(acl, vault, finance, shareVoting);
// finance
_createFinancePermissions(acl, finance, boardVoting, shareVoting);
_createFinanceCreatePaymentsPermission(acl, finance, boardVoting, shareVoting);
}
function _setupSharePermissions(Kernel _dao) internal {
ACL acl = ACL(_dao.acl());
(TokenManager boardTM,,,) = _boardAppsCache();
(TokenManager shareTM, Voting shareVoting) = _shareAppsCache();
(, Presale presale, BatchedBancorMarketMaker marketMaker,,) = _fundraisingAppsCache();
// token manager
address[] memory grantees = new address[](2);
grantees[0] = address(marketMaker);
grantees[1] = address(presale);
acl.createPermission(marketMaker, shareTM, shareTM.MINT_ROLE(),shareVoting);
acl.createPermission(presale, shareTM, shareTM.ISSUE_ROLE(),shareVoting);
acl.createPermission(presale, shareTM, shareTM.ASSIGN_ROLE(),shareVoting);
acl.createPermission(presale, shareTM, shareTM.REVOKE_VESTINGS_ROLE(), shareVoting);
_createPermissions(acl, grantees, shareTM, shareTM.BURN_ROLE(), shareVoting);
// voting
_createVotingPermissions(acl, shareVoting, shareVoting, boardTM, shareVoting);
}
function _setupFundraisingPermissions(Kernel _dao) internal {
ACL acl = ACL(_dao.acl());
(, Voting boardVoting,,) = _boardAppsCache();
(, Voting shareVoting) = _shareAppsCache();
(Agent reserve, Presale presale, BatchedBancorMarketMaker marketMaker, Tap tap, AragonFundraisingController controller) = _fundraisingAppsCache();
// reserve
address[] memory grantees = new address[](2);
grantees[0] = address(tap);
grantees[1] = address(marketMaker);
acl.createPermission(shareVoting, reserve, reserve.SAFE_EXECUTE_ROLE(), shareVoting);
acl.createPermission(controller, reserve, reserve.ADD_PROTECTED_TOKEN_ROLE(), shareVoting);
_createPermissions(acl, grantees, reserve, reserve.TRANSFER_ROLE(), shareVoting);
// presale
acl.createPermission(controller, presale, presale.OPEN_ROLE(), shareVoting);
acl.createPermission(controller, presale, presale.CONTRIBUTE_ROLE(), shareVoting);
// market maker
acl.createPermission(controller, marketMaker, marketMaker.OPEN_ROLE(), shareVoting);
acl.createPermission(controller, marketMaker, marketMaker.UPDATE_BENEFICIARY_ROLE(), shareVoting);
acl.createPermission(controller, marketMaker, marketMaker.UPDATE_FEES_ROLE(), shareVoting);
acl.createPermission(controller, marketMaker, marketMaker.ADD_COLLATERAL_TOKEN_ROLE(), shareVoting);
acl.createPermission(controller, marketMaker, marketMaker.REMOVE_COLLATERAL_TOKEN_ROLE(), shareVoting);
acl.createPermission(controller, marketMaker, marketMaker.UPDATE_COLLATERAL_TOKEN_ROLE(), shareVoting);
acl.createPermission(controller, marketMaker, marketMaker.OPEN_BUY_ORDER_ROLE(), shareVoting);
acl.createPermission(controller, marketMaker, marketMaker.OPEN_SELL_ORDER_ROLE(), shareVoting);
// tap
acl.createPermission(controller, tap, tap.UPDATE_BENEFICIARY_ROLE(), shareVoting);
acl.createPermission(controller, tap, tap.UPDATE_MAXIMUM_TAP_RATE_INCREASE_PCT_ROLE(), shareVoting);
acl.createPermission(controller, tap, tap.UPDATE_MAXIMUM_TAP_FLOOR_DECREASE_PCT_ROLE(), shareVoting);
acl.createPermission(controller, tap, tap.ADD_TAPPED_TOKEN_ROLE(), shareVoting);
acl.createPermission(controller, tap, tap.UPDATE_TAPPED_TOKEN_ROLE(), shareVoting);
acl.createPermission(controller, tap, tap.RESET_TAPPED_TOKEN_ROLE(), shareVoting);
acl.createPermission(controller, tap, tap.WITHDRAW_ROLE(), shareVoting);
// controller
// ADD_COLLATERAL_TOKEN_ROLE is handled later [after collaterals have been added]
acl.createPermission(shareVoting, controller, controller.UPDATE_BENEFICIARY_ROLE(), shareVoting);
acl.createPermission(shareVoting, controller, controller.UPDATE_FEES_ROLE(), shareVoting);
// acl.createPermission(shareVoting, controller, controller.ADD_COLLATERAL_TOKEN_ROLE(), shareVoting);
acl.createPermission(shareVoting, controller, controller.REMOVE_COLLATERAL_TOKEN_ROLE(), shareVoting);
acl.createPermission(shareVoting, controller, controller.UPDATE_COLLATERAL_TOKEN_ROLE(), shareVoting);
acl.createPermission(shareVoting, controller, controller.UPDATE_MAXIMUM_TAP_RATE_INCREASE_PCT_ROLE(), shareVoting);
acl.createPermission(shareVoting, controller, controller.UPDATE_MAXIMUM_TAP_FLOOR_DECREASE_PCT_ROLE(), shareVoting);
acl.createPermission(shareVoting, controller, controller.ADD_TOKEN_TAP_ROLE(), shareVoting);
acl.createPermission(shareVoting, controller, controller.UPDATE_TOKEN_TAP_ROLE(), shareVoting);
acl.createPermission(boardVoting, controller, controller.OPEN_PRESALE_ROLE(), shareVoting);
acl.createPermission(presale, controller, controller.OPEN_TRADING_ROLE(), shareVoting);
acl.createPermission(address(-1), controller, controller.CONTRIBUTE_ROLE(), shareVoting);
acl.createPermission(address(-1), controller, controller.OPEN_BUY_ORDER_ROLE(), shareVoting);
acl.createPermission(address(-1), controller, controller.OPEN_SELL_ORDER_ROLE(), shareVoting);
acl.createPermission(address(-1), controller, controller.WITHDRAW_ROLE(), shareVoting);
}
/***** internal cache functions *****/
function _cacheDao(Kernel _dao) internal {
Cache storage c = cache[msg.sender];
c.dao = address(_dao);
}
function _cacheBoardApps(TokenManager _boardTM, Voting _boardVoting, Vault _vault, Finance _finance) internal {
Cache storage c = cache[msg.sender];
c.boardTokenManager = address(_boardTM);
c.boardVoting = address(_boardVoting);
c.vault = address(_vault);
c.finance = address(_finance);
}
function _cacheShareApps(TokenManager _shareTM, Voting _shareVoting) internal {
Cache storage c = cache[msg.sender];
c.shareTokenManager = address(_shareTM);
c.shareVoting = address(_shareVoting);
}
function _cacheFundraisingApps(Agent _reserve, Presale _presale, BatchedBancorMarketMaker _marketMaker, Tap _tap, AragonFundraisingController _controller) internal {
Cache storage c = cache[msg.sender];
c.reserve = address(_reserve);
c.presale = address(_presale);
c.marketMaker = address(_marketMaker);
c.tap = address(_tap);
c.controller = address(_controller);
}
function _daoCache() internal view returns (Kernel dao) {
Cache storage c = cache[msg.sender];
dao = Kernel(c.dao);
}
function _boardAppsCache() internal view returns (TokenManager boardTM, Voting boardVoting, Vault vault, Finance finance) {
Cache storage c = cache[msg.sender];
boardTM = TokenManager(c.boardTokenManager);
boardVoting = Voting(c.boardVoting);
vault = Vault(c.vault);
finance = Finance(c.finance);
}
function _shareAppsCache() internal view returns (TokenManager shareTM, Voting shareVoting) {
Cache storage c = cache[msg.sender];
shareTM = TokenManager(c.shareTokenManager);
shareVoting = Voting(c.shareVoting);
}
function _fundraisingAppsCache() internal view returns (
Agent reserve,
Presale presale,
BatchedBancorMarketMaker marketMaker,
Tap tap,
AragonFundraisingController controller
)
{
Cache storage c = cache[msg.sender];
reserve = Agent(c.reserve);
presale = Presale(c.presale);
marketMaker = BatchedBancorMarketMaker(c.marketMaker);
tap = Tap(c.tap);
controller = AragonFundraisingController(c.controller);
}
function _clearCache() internal {
Cache storage c = cache[msg.sender];
delete c.dao;
delete c.boardTokenManager;
delete c.boardVoting;
delete c.vault;
delete c.finance;
delete c.shareVoting;
delete c.shareTokenManager;
delete c.reserve;
delete c.presale;
delete c.marketMaker;
delete c.tap;
delete c.controller;
}
/**
* NOTE
* the following functions are only needed for the presale
* initialization function [which we can't compile otherwise
* because of a `stack too deep` error]
*/
function _vaultCache() internal view returns (Vault vault) {
Cache storage c = cache[msg.sender];
vault = Vault(c.vault);
}
function _shareTMCache() internal view returns (TokenManager shareTM) {
Cache storage c = cache[msg.sender];
shareTM = TokenManager(c.shareTokenManager);
}
function _reserveCache() internal view returns (Agent reserve) {
Cache storage c = cache[msg.sender];
reserve = Agent(c.reserve);
}
function _presaleCache() internal view returns (Presale presale) {
Cache storage c = cache[msg.sender];
presale = Presale(c.presale);
}
function _controllerCache() internal view returns (AragonFundraisingController controller) {
Cache storage c = cache[msg.sender];
controller = AragonFundraisingController(c.controller);
}
/***** internal check functions *****/
function _ensureBoardAppsCache() internal view {
Cache storage c = cache[msg.sender];
require(
c.boardTokenManager != address(0) &&
c.boardVoting != address(0) &&
c.vault != address(0) &&
c.finance != address(0),
ERROR_MISSING_CACHE
);
}
function _ensureShareAppsCache() internal view {
Cache storage c = cache[msg.sender];
require(
c.shareTokenManager != address(0) &&
c.shareVoting != address(0),
ERROR_MISSING_CACHE
);
}
function _ensureFundraisingAppsCache() internal view {
Cache storage c = cache[msg.sender];
require(
c.reserve != address(0) &&
c.presale != address(0) &&
c.marketMaker != address(0) &&
c.tap != address(0) &&
c.controller != address(0),
ERROR_MISSING_CACHE
);
}
/***** internal utils functions *****/
function _registerApp(Kernel _dao, bytes32 _appId) internal returns (address) {
address proxy = _dao.newAppInstance(_appId, _latestVersionAppBase(_appId));
emit InstalledApp(proxy, _appId);
return proxy;
}
} | TODO: this should be external See https:github.com/ethereum/solidity/issues/4832 TODO: this should be external See https:github.com/ethereum/solidity/issues/4832 | interface IForwarder {
function isForwarder() external pure returns (bool);
function canForward(address sender, bytes evmCallScript) public view returns (bool);
function forward(bytes evmCallScript) public;
}
| 450,901 | [
1,
6241,
30,
333,
1410,
506,
3903,
2164,
2333,
30,
6662,
18,
832,
19,
546,
822,
379,
19,
30205,
560,
19,
9618,
19,
8875,
1578,
2660,
30,
333,
1410,
506,
3903,
2164,
2333,
30,
6662,
18,
832,
19,
546,
822,
379,
19,
30205,
560,
19,
9618,
19,
8875,
1578,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
5831,
467,
30839,
288,
203,
565,
445,
353,
30839,
1435,
3903,
16618,
1135,
261,
6430,
1769,
203,
203,
565,
445,
848,
8514,
12,
2867,
5793,
16,
1731,
2113,
81,
1477,
3651,
13,
1071,
1476,
1135,
261,
6430,
1769,
203,
203,
565,
445,
5104,
12,
3890,
2113,
81,
1477,
3651,
13,
1071,
31,
203,
203,
203,
97,
203,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
] |
pragma solidity ^0.8.10;
contract Token{//inspired by https://www.youtube.com/watch?v=Q_wK6N9GtS8
mapping(address=>uint)public balances;
mapping(address =>mapping(address=>uint)) public allowance;
uint public totalSuply =1000000*10**18;
string public name ="Test Token";
string public symbol = "TST";
uint8 public decimals = 18;
event Transfer(address indexed from, address indexed to,uint value);
event Approval(address indexed owner,address indexed spender,uint value);
constructor(){
balances[msg.sender] = totalSuply;
}
function balanceOf(address owner)public view returns(uint){
return balances[owner];
}
function transfer(address to, uint value)public returns(bool){
require(balanceOf(msg.sender)>=value,'balance is too low');
balances[to]+=value-(value/50);//2% fee(2% from every transaction will be destroyed)
balances[msg.sender]-=value;
emit Transfer(msg.sender,to,value);
return true;
}
function transferFrom(address from, address to, uint value)public returns(bool){//transactions on behalf of someone else will have zero fees(this type of transactions are mainly used by exchanges)
require(balanceOf(from)>=value,'balance is too low');
require(allowance[from][msg.sender]>=value,'permission denied');
balances[to]+=value;
balances[from]-=value;
emit Transfer(from,to,value);
return true;
}
function approve(address spender, uint value) public returns(bool){
allowance[msg.sender][spender]=value;
emit Approval(msg.sender,spender,value);
return true;
}
}
| 2% fee(2% from every transaction will be destroyed)
| balances[to]+=value-(value/50); | 1,780,127 | [
1,
22,
9,
14036,
12,
22,
9,
628,
3614,
2492,
903,
506,
17689,
13,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
3639,
324,
26488,
63,
869,
3737,
33,
1132,
17,
12,
1132,
19,
3361,
1769,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
] |
./full_match/137/0xE45d523E93C9C5Ceb3cB1fdfa90e2bbEE9DCc324/sources/ForgeToken.sol | * @dev Implementation of the {IERC165} interface. Contracts may inherit from this and call {_registerInterface} to declare their support of an interface./ | abstract contract ERC165 is IERC165 {
bytes4 private constant _INTERFACE_ID_ERC165 = 0x01ffc9a7;
mapping(bytes4 => bool) private _supportedInterfaces;
}
constructor() {
_registerInterface(_INTERFACE_ID_ERC165);
}
function supportsInterface(bytes4 interfaceId)
public
view
virtual
override
returns (bool)
{
return _supportedInterfaces[interfaceId];
}
function _registerInterface(bytes4 interfaceId) internal virtual {
require(interfaceId != 0xffffffff, "ERC165: invalid interface id");
_supportedInterfaces[interfaceId] = true;
}
}
| 4,771,119 | [
1,
13621,
434,
326,
288,
45,
654,
39,
28275,
97,
1560,
18,
30131,
2026,
6811,
628,
333,
471,
745,
288,
67,
4861,
1358,
97,
358,
14196,
3675,
2865,
434,
392,
1560,
18,
19,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
17801,
6835,
4232,
39,
28275,
353,
467,
654,
39,
28275,
288,
203,
565,
1731,
24,
3238,
5381,
389,
18865,
67,
734,
67,
654,
39,
28275,
273,
374,
92,
1611,
1403,
71,
29,
69,
27,
31,
203,
203,
565,
2874,
12,
3890,
24,
516,
1426,
13,
3238,
389,
4127,
10273,
31,
203,
203,
97,
203,
565,
3885,
1435,
288,
203,
3639,
389,
4861,
1358,
24899,
18865,
67,
734,
67,
654,
39,
28275,
1769,
203,
565,
289,
203,
203,
565,
445,
6146,
1358,
12,
3890,
24,
1560,
548,
13,
203,
3639,
1071,
203,
3639,
1476,
203,
3639,
5024,
203,
3639,
3849,
203,
3639,
1135,
261,
6430,
13,
203,
565,
288,
203,
3639,
327,
389,
4127,
10273,
63,
5831,
548,
15533,
203,
565,
289,
203,
203,
565,
445,
389,
4861,
1358,
12,
3890,
24,
1560,
548,
13,
2713,
5024,
288,
203,
3639,
2583,
12,
5831,
548,
480,
374,
28857,
16,
315,
654,
39,
28275,
30,
2057,
1560,
612,
8863,
203,
3639,
389,
4127,
10273,
63,
5831,
548,
65,
273,
638,
31,
203,
565,
289,
203,
97,
203,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
] |
pragma solidity ^0.4.18;
import "../node_modules/zeppelin-solidity/contracts/ownership/Ownable.sol";
/*
This contract will hold all tokens that were unsold during ICO.
*/
contract UACUnsold is Ownable{
// It disallows to send money directly to this contract
function()
public
payable
{
revert();
}
}
| / It disallows to send money directly to this contract | contract UACUnsold is Ownable{
function()
public
payable
This contract will hold all tokens that were unsold during ICO.
{
revert();
}
}
| 12,656,568 | [
1,
19,
2597,
29176,
87,
358,
1366,
15601,
5122,
358,
333,
6835,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
16351,
587,
2226,
984,
87,
1673,
353,
14223,
6914,
95,
203,
203,
565,
445,
1435,
203,
565,
1071,
203,
565,
8843,
429,
203,
565,
1220,
6835,
903,
6887,
777,
2430,
716,
4591,
16804,
1673,
4982,
467,
3865,
18,
203,
565,
288,
203,
3639,
15226,
5621,
203,
565,
289,
203,
97,
203,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
] |
// SPDX-License-Identifier: MIT
pragma solidity >=0.4.25 <0.7.0;
import "@openzeppelin/contracts/access/AccessControl.sol";
import "@openzeppelin/contracts/math/SafeMath.sol";
import "./interfaces/IToken.sol";
contract Token is IToken, AccessControl {
using SafeMath for uint256;
mapping(address => uint256) balances;
mapping (address => mapping (address => uint256)) private _allowances;
mapping(address => mapping (address => uint256)) allowed;
bytes32 private constant MINTER_ROLE = keccak256("MINTER_ROLE");
bytes32 private constant SETTER_ROLE = keccak256("SETTER_ROLE");
uint internal constant _burnTransferPercent = 2; // .02% in basis points
uint internal constant _uniPercent = 7500; // 75% in basis points
uint internal constant _devPercent = 500; // 5% in basis points
uint internal constant _webPercent = 500; // 5% in basis points
uint internal constant _writerPercent = 500; // 5% in basis points
uint internal constant _marketingPercent = 1000; // 10% in basis points
event Transfer(address indexed from, address indexed to, uint tokens);
event Burn(address indexed from, uint256 value);
event Mint(address indexed _address, uint _reward);
uint internal _swapPremine = 20000000000e18; // 20b coins
uint internal _teamPremine = 5000000000e18; // 3b coins
uint internal _devPremine = 5000000000e18; // 5b coins
uint internal _uniPremine = 90000000000e18; // 90b coins
uint internal _uniPayout;
uint internal _devPayout;
uint internal _webPayout;
uint internal _writerPayout;
uint internal _marketingPayout;
address payable uniPresale = 0x709A3c46A75D4ff480b0dfb338b28cBc44Df357a;
address payable devPresale = 0xEfB349d5DCe3171f753E997Cdd779D42d0d060e2;
address payable webPresale = 0x998a96345BC259bD401354975c00592612aBd2ec;
address payable writerPresale = 0x991591ad6a7377Ec487e51f3f6504EE09B7b531C;
address payable marketingPresale = 0x991591ad6a7377Ec487e51f3f6504EE09B7b531C;
// Set the sale state
bool public sale;
modifier onlyMinter() {
require(hasRole(MINTER_ROLE, _msgSender()), "Caller is not a minter");
_;
}
modifier onlySetter() {
require(hasRole(SETTER_ROLE, _msgSender()), "Caller is not a setter");
_;
}
constructor(
string memory _name,
string memory _symbol,
address _setter,
address _swap,
address _team,
address _dev,
address _uni
) public {
_setupRole(SETTER_ROLE, _setter);
_setupRole(MINTER_ROLE, msg.sender);
mint(_swap, _swapPremine);
mint(_team, _teamPremine);
mint(_dev, _devPremine);
mint(_uni, _uniPremine);
sale == false;
}
function init(address[] calldata instances) external onlySetter {
require(instances.length == 5, "wrong instances number");
for (uint256 index = 0; index < instances.length; index++) {
_setupRole(MINTER_ROLE, instances[index]);
}
renounceRole(SETTER_ROLE, _msgSender());
}
function getMinterRole() external pure returns (bytes32) {
return MINTER_ROLE;
}
function getSetterRole() external pure returns (bytes32) {
return SETTER_ROLE;
}
function purchase() public payable {
require(sale == true, "Purchasing Tokens in not avaiable right now.");
require(msg.value > 5e17, "Must send more than .5eth");
require(msg.value < 3e18, "Must send less than 3eth");
uint256 tokens;
_uniPayout = msg.value.mul(_uniPercent).div(100);
_devPayout = msg.value.mul(_devPercent).div(100);
_marketingPayout = msg.value.mul(_marketingPercent).div(100);
_webPayout = msg.value.mul(_webPercent).div(100);
_writerPayout = msg.value.mul(_writerPercent).div(100);
uniPresale.transfer(_uniPayout);
devPresale.transfer(_devPayout);
webPresale.transfer(_webPayout);
writerPresale.transfer(_writerPayout);
marketingPresale.transfer(_marketingPayout);
mint(msg.sender, tokens);
}
function balanceOf(address account) public override view returns (uint256) {
return balances[account];
}
function burn(address account, uint256 amount) public override {
require(account != address(0), "ERC20: burn from the zero address");
_beforeTokenTransfer(account, address(0), amount);
require(balances[account] >= amount, "ERC20: burn amount exceeds balance");
balances[account] -= amount;
//_totalSupply -= amount;
emit Transfer(account, address(0), amount);
}
function mint(address account, uint256 amount) public override {
require(account != address(0), "ERC20: mint to the zero address");
require(hasRole(MINTER_ROLE, msg.sender), "Caller is not a minter");
_beforeTokenTransfer(address(0), account, amount);
//_totalSupply += amount;
balances[account] += amount;
emit Transfer(address(0), account, amount);
}
function transfer(address recipient, uint256 amount) public override returns (bool) {
uint256 finalAmount;
uint256 amountToBurn = amount.mul(_burnTransferPercent).div(10000);
burn(msg.sender, amountToBurn);
finalAmount = amount.sub(amountToBurn);
_beforeTokenTransfer(msg.sender, recipient, finalAmount);
balances[msg.sender] = balances[msg.sender].sub(finalAmount, "ERC20: transfer amount exceeds balance");
balances[recipient] = balances[recipient].add(finalAmount);
emit Transfer(msg.sender, recipient, finalAmount);
}
function transferFrom(address owner, address buyer, uint256 amount) public override returns (bool) {
require(amount <= balances[owner]);
require(amount <= allowed[owner][msg.sender]);
balances[owner] = balances[owner].sub(amount);
allowed[owner][msg.sender] = allowed[owner][msg.sender].sub(amount);
balances[buyer] = balances[buyer].add(amount);
emit Transfer(owner, buyer, amount);
return true;
}
function allowance(address owner, address delegate) public override view returns (uint) {
return allowed[owner][delegate];
}
function approve(address delegate, uint256 amount) public override returns (bool) {
allowed[msg.sender][delegate] = amount;
emit Approval(msg.sender, delegate, amount);
return true;
}
function _beforeTokenTransfer(address from, address to, uint256 amount) internal virtual { }
// Helpers
function getNow() external view returns (uint256) {
return now;
}
}
| 5% in basis points
| uint internal constant _webPercent = 500; | 1,782,284 | [
1,
25,
9,
316,
10853,
3143,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
565,
2254,
2713,
5381,
389,
4875,
8410,
273,
6604,
31,
225,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
] |
/**
*Submitted for verification at Etherscan.io on 2021-04-18
*/
pragma solidity 0.6.6;
/*
* @title Multisignature wallet - Allows multiple parties to agree on transactions before execution.
* @author Stefan George - <[email protected]>
*/
contract MultiSigWallet {
/*
* Events
*/
event Confirmation(address indexed sender, uint indexed transactionId);
event Revocation(address indexed sender, uint indexed transactionId);
event Submission(uint indexed transactionId);
event Execution(uint indexed transactionId);
event ExecutionFailure(uint indexed transactionId);
event Deposit(address indexed sender, uint value);
event OwnerAddition(address indexed owner);
event OwnerRemoval(address indexed owner);
event RequirementChange(uint required);
uint constant public MAX_OWNER_COUNT = 50;
bytes32 constant internal projectHash = keccak256(abi.encodePacked("CLAIM"));
mapping (uint => Transaction) public transactions;
mapping (uint => mapping (address => bool)) public confirmations;
mapping (address => bool) public isOwner;
address[] public owners;
uint public required;
uint public transactionCount;
struct Transaction {
address destination;
uint value;
bytes data;
bool executed;
uint submitTime;
}
/*
* Modifiers
*/
modifier onlyWallet() {
require(msg.sender == address(this), "msg.sender != address(this)");
_;
}
modifier ownerDoesNotExist(address owner) {
require(!isOwner[owner], "is already owner");
_;
}
modifier ownerExists(address owner) {
require(isOwner[owner],"is not owner");
_;
}
modifier transactionExists(uint transactionId) {
require(transactions[transactionId].destination != address(0),"transactionId is not exists");
_;
}
modifier confirmed(uint transactionId, address owner) {
require(confirmations[transactionId][owner],"is not confirmed");
_;
}
modifier notConfirmed(uint transactionId, address owner) {
require(!confirmations[transactionId][owner],"already confirmed");
_;
}
modifier notExecuted(uint transactionId) {
require(!transactions[transactionId].executed,"already executed");
_;
}
modifier notNull(address _address) {
require(_address != address(0),"_address == address(0)");
_;
}
modifier validRequirement(uint ownerCount, uint _required) {
require(ownerCount <= MAX_OWNER_COUNT
&& _required <= ownerCount
&& _required != 0
&& ownerCount != 0,"error: validRequirement()");
_;
}
/// @dev Fallback function allows to deposit ether.
fallback() external {
}
receive() external payable {
if (msg.value > 0)
emit Deposit(msg.sender, msg.value);
}
/*
* Public functions
*/
/// @dev Contract constructor sets initial owners and required number of confirmations.
/// @param _owners List of initial owners.
/// @param _required Number of required confirmations.
constructor(address[] memory _owners, uint _required)
public
validRequirement(_owners.length, _required)
{
for (uint i=0; i<_owners.length; i++) {
require(!isOwner[_owners[i]] && _owners[i] != address(0));
isOwner[_owners[i]] = true;
}
owners = _owners;
required = _required;
}
/// @dev Allows to add a new owner. Transaction has to be sent by wallet.
/// @param owner Address of new owner.
function addOwner(address owner)
public
onlyWallet
ownerDoesNotExist(owner)
notNull(owner)
validRequirement(owners.length + 1, required)
{
isOwner[owner] = true;
owners.push(owner);
OwnerAddition(owner);
}
/// @dev Allows to remove an owner. Transaction has to be sent by wallet.
/// @param owner Address of owner.
function removeOwner(address owner)
public
onlyWallet
ownerExists(owner)
{
isOwner[owner] = false;
for (uint i=0; i<owners.length - 1; i++)
if (owners[i] == owner) {
owners[i] = owners[owners.length - 1];
break;
}
if (required > (owners.length - 1))
changeRequirement(owners.length - 1);
OwnerRemoval(owner);
}
/// @dev Allows to replace an owner with a new owner. Transaction has to be sent by wallet.
/// @param owner Address of owner to be replaced.
/// @param newOwner Address of new owner.
function replaceOwner(address owner, address newOwner)
public
onlyWallet
ownerExists(owner)
ownerDoesNotExist(newOwner)
{
for (uint i=0; i<owners.length; i++)
if (owners[i] == owner) {
owners[i] = newOwner;
break;
}
isOwner[owner] = false;
isOwner[newOwner] = true;
OwnerRemoval(owner);
OwnerAddition(newOwner);
}
/// @dev Allows to change the number of required confirmations. Transaction has to be sent by wallet.
/// @param _required Number of required confirmations.
function changeRequirement(uint _required)
public
onlyWallet
validRequirement(owners.length, _required)
{
required = _required;
RequirementChange(_required);
}
/*@dev Allows an owner to submit and confirm a transaction.
@param destination Transaction target address.
@param value Transaction ether value.
@param data Transaction data payload.
@return Returns transaction ID.*/
function submitTransaction(address destination, uint value, bytes memory data)
public
returns (uint transactionId)
{
transactionId = addTransaction(destination, value, data);
confirmTransaction(transactionId);
}
/// @dev Allows an owner to batch confirm transactions.
/// @param transactionIdArray Transaction ID array.
function batchConfirmTransaction(uint[] memory transactionIdArray) public
{
for(uint i = 0; i < transactionIdArray.length; i++ ) {
confirmTransaction(transactionIdArray[i]);
}
}
/// @dev Allows an owner to confirm a transaction.
/// @param transactionId Transaction ID.
function confirmTransaction(uint transactionId)
public
ownerExists(msg.sender)
transactionExists(transactionId)
notConfirmed(transactionId, msg.sender)
{
confirmations[transactionId][msg.sender] = true;
Confirmation(msg.sender, transactionId);
executeTransaction(transactionId);
}
/// @dev Allows an owner to revoke a confirmation for a transaction.
/// @param transactionId Transaction ID.
function revokeConfirmation(uint transactionId)
public
ownerExists(msg.sender)
confirmed(transactionId, msg.sender)
notExecuted(transactionId)
{
confirmations[transactionId][msg.sender] = false;
Revocation(msg.sender, transactionId);
}
/// @dev Allows anyone to execute a confirmed transaction.
/// @param transactionId Transaction ID.
function executeTransaction(uint transactionId)
public
ownerExists(msg.sender)
confirmed(transactionId, msg.sender)
notExecuted(transactionId)
{
if (isConfirmed(transactionId)) {
Transaction storage txn = transactions[transactionId];
txn.executed = true;
// address(txn.destination).call(abi.encodeWithSignature(txn.data))
(bool success, bytes memory data) = txn.destination.call{value: txn.value}(txn.data);
if (success)
emit Execution(transactionId);
else {
emit ExecutionFailure(transactionId);
txn.executed = false;
}
}
}
/// @dev Returns the confirmation status of a transaction.
/// @param transactionId Transaction ID.
/// @return Confirmation status.
function isConfirmed(uint transactionId)
public
view
returns (bool)
{
uint count = 0;
for (uint i=0; i<owners.length; i++) {
if (confirmations[transactionId][owners[i]])
count += 1;
if (count == required)
return true;
}
return false;
}
/*
* Internal functions
*/
/*@dev Adds a new transaction to the transaction mapping, if transaction does not exist yet.
@param destination Transaction target address.
@param value Transaction ether value.
@param data Transaction data payload.
@return Returns transaction ID.*/
function addTransaction(address destination, uint value, bytes memory data)
internal
notNull(destination)
returns (uint transactionId)
{
transactionId = transactionCount;
transactions[transactionId] = Transaction({
destination: destination,
value: value,
data: data,
executed: false,
submitTime: block.timestamp
});
transactionCount += 1;
Submission(transactionId);
}
/*
* Web3 call functions
*/
/*@dev Returns number of confirmations of a transaction.
@param transactionId Transaction ID.
@return Number of confirmations.*/
function getConfirmationCount(uint transactionId)
public
view
returns (uint count)
{
count = 0;
for (uint i=0; i<owners.length; i++)
if (confirmations[transactionId][owners[i]])
count += 1;
}
/*@dev Returns total number of transactions after filers are applied.
@param pending Include pending transactions.
@param executed Include executed transactions.
@return Total number of transactions after filters are applied.*/
function getTransactionCount(bool pending, bool executed)
public
view
returns (uint count)
{
count = 0;
for (uint i=0; i<transactionCount; i++)
if ( pending && !transactions[i].executed
|| executed && transactions[i].executed)
count += 1;
}
/// @dev Returns list of owners.
/// @return List of owner addresses.
function getOwners()
public
view
returns (address[] memory)
{
return owners;
}
/*@dev Returns array with owner addresses, which confirmed transaction.
@param transactionId Transaction ID.
@return Returns array of owner addresses.*/
function getConfirmations(uint transactionId)
public
view
returns (address[] memory _confirmations)
{
address[] memory confirmationsTemp = new address[](owners.length);
uint count = 0;
uint i;
for (i=0; i<owners.length; i++)
if (confirmations[transactionId][owners[i]]) {
confirmationsTemp[count] = owners[i];
count += 1;
}
_confirmations = new address[](count);
for (i=0; i<count; i++)
_confirmations[i] = confirmationsTemp[i];
}
/*@dev Returns list of transaction IDs in defined range.
@param from Index start position of transaction array.
@param to Index end position of transaction array.
@param pending Include pending transactions.
@param executed Include executed transactions.
@return Returns array of transaction IDs.*/
function getTransactionIds(uint from, uint to, bool pending, bool executed)
public
view
returns (uint[] memory _transactionIds)
{
uint[] memory transactionIdsTemp = new uint[](transactionCount);
uint count = 0;
uint i;
for (i=0; i<transactionCount; i++)
if ( pending && !transactions[i].executed
|| executed && transactions[i].executed)
{
transactionIdsTemp[count] = i;
count += 1;
}
_transactionIds = new uint[](to - from);
for (i=from; i<to; i++)
_transactionIds[i - from] = transactionIdsTemp[i];
}
function getBlockTimestamp() view internal returns (uint) {
return block.timestamp;
}
} | @dev Allows anyone to execute a confirmed transaction. @param transactionId Transaction ID. address(txn.destination).call(abi.encodeWithSignature(txn.data)) | function executeTransaction(uint transactionId)
public
ownerExists(msg.sender)
confirmed(transactionId, msg.sender)
notExecuted(transactionId)
{
if (isConfirmed(transactionId)) {
Transaction storage txn = transactions[transactionId];
txn.executed = true;
if (success)
emit Execution(transactionId);
else {
emit ExecutionFailure(transactionId);
txn.executed = false;
}
}
}
| 7,941,304 | [
1,
19132,
1281,
476,
358,
1836,
279,
19979,
2492,
18,
225,
24112,
5947,
1599,
18,
1758,
12,
24790,
18,
10590,
2934,
1991,
12,
21457,
18,
3015,
1190,
5374,
12,
24790,
18,
892,
3719,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
565,
445,
1836,
3342,
12,
11890,
24112,
13,
203,
3639,
1071,
203,
3639,
3410,
4002,
12,
3576,
18,
15330,
13,
203,
3639,
19979,
12,
7958,
548,
16,
1234,
18,
15330,
13,
203,
3639,
486,
23839,
12,
7958,
548,
13,
203,
565,
288,
203,
3639,
309,
261,
291,
3976,
11222,
12,
7958,
548,
3719,
288,
203,
5411,
5947,
2502,
7827,
273,
8938,
63,
7958,
548,
15533,
203,
5411,
7827,
18,
4177,
4817,
273,
638,
31,
203,
5411,
309,
261,
4768,
13,
203,
7734,
3626,
8687,
12,
7958,
548,
1769,
203,
5411,
469,
288,
203,
7734,
3626,
8687,
5247,
12,
7958,
548,
1769,
203,
7734,
7827,
18,
4177,
4817,
273,
629,
31,
203,
5411,
289,
203,
3639,
289,
203,
565,
289,
203,
203,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
] |
// SPDX-License-Identifier: MIT
// File: contracts/MerkleProof.sol
// OpenZeppelin Contracts (last updated v4.5.0) (utils/cryptography/MerkleProof.sol)
pragma solidity ^0.8.0;
/**
* @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) {
return processProof(proof, leaf) == root;
}
/**
* @dev Returns the rebuilt hash obtained by traversing a Merklee tree up
* from `leaf` using `proof`. A `proof` is valid if and only if the rebuilt
* hash matches the root of the tree. When processing the proof, the pairs
* of leafs & pre-images are assumed to be sorted.
*
* _Available since v4.4._
*/
function processProof(bytes32[] memory proof, bytes32 leaf) internal pure returns (bytes32) {
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 = _efficientHash(computedHash, proofElement);
} else {
// Hash(current element of the proof + current computed hash)
computedHash = _efficientHash(proofElement, computedHash);
}
}
return computedHash;
}
function _efficientHash(bytes32 a, bytes32 b) private pure returns (bytes32 value) {
assembly {
mstore(0x00, a)
mstore(0x20, b)
value := keccak256(0x00, 0x40)
}
}
}
// File: contracts/IWhitelistable.sol
/**
* Author: Lambdalf the White
* Edit : Squeebo
*/
pragma solidity 0.8.10;
abstract contract IWhitelistable {
// Errors
error IWhitelistable_NOT_SET();
error IWhitelistable_CONSUMED();
error IWhitelistable_FORBIDDEN();
error IWhitelistable_NO_ALLOWANCE();
bytes32 private _root;
mapping( address => uint256 ) private _consumed;
modifier isWhitelisted( address account_, bytes32[] memory proof_, uint256 passMax_, uint256 qty_ ) {
if ( qty_ > passMax_ ) {
revert IWhitelistable_FORBIDDEN();
}
uint256 _allowed_ = _checkWhitelistAllowance( account_, proof_, passMax_ );
if ( _allowed_ < qty_ ) {
revert IWhitelistable_FORBIDDEN();
}
_;
}
/**
* @dev Sets the pass to protect the whitelist.
*/
function _setWhitelist( bytes32 root_ ) internal virtual {
_root = root_;
}
/**
* @dev Returns the amount that `account_` is allowed to access from the whitelist.
*
* Requirements:
*
* - `_root` must be set.
*
* See {IWhitelistable-_consumeWhitelist}.
*/
function _checkWhitelistAllowance( address account_, bytes32[] memory proof_, uint256 passMax_ ) internal view returns ( uint256 ) {
if ( _root == 0 ) {
revert IWhitelistable_NOT_SET();
}
if ( _consumed[ account_ ] >= passMax_ ) {
revert IWhitelistable_CONSUMED();
}
if ( ! _computeProof( account_, proof_ ) ) {
revert IWhitelistable_FORBIDDEN();
}
uint256 _res_;
unchecked {
_res_ = passMax_ - _consumed[ account_ ];
}
return _res_;
}
function _computeProof( address account_, bytes32[] memory proof_ ) private view returns ( bool ) {
bytes32 leaf = keccak256(abi.encodePacked(account_));
return MerkleProof.processProof( proof_, leaf ) == _root;
}
/**
* @dev Consumes `amount_` pass passes from `account_`.
*
* Note: Before calling this function, eligibility should be checked through {IWhitelistable-checkWhitelistAllowance}.
*/
function _consumeWhitelist( address account_, uint256 qty_ ) internal {
unchecked {
_consumed[ account_ ] += qty_;
}
}
}
// File: contracts/ITradable.sol
/**
* Author: Lambdalf the White
*/
pragma solidity 0.8.10;
contract OwnableDelegateProxy {}
contract ProxyRegistry {
mapping( address => OwnableDelegateProxy ) public proxies;
}
abstract contract ITradable {
// OpenSea proxy registry address
address[] internal _proxyRegistries;
function _setProxyRegistry( address proxyRegistryAddress_ ) internal {
_proxyRegistries.push( proxyRegistryAddress_ );
}
/**
* @dev Checks if `operator_` is the registered proxy for `tokenOwner_`.
*
* Note: Use this function to allow whitelisting of registered proxy.
*/
function _isRegisteredProxy( address tokenOwner_, address operator_ ) internal view returns ( bool ) {
for ( uint256 i; i < _proxyRegistries.length; i++ ) {
ProxyRegistry _proxyRegistry_ = ProxyRegistry( _proxyRegistries[ i ] );
if ( address( _proxyRegistry_.proxies( tokenOwner_ ) ) == operator_ ) {
return true;
}
}
return false;
}
}
// File: contracts/IPausable.sol
/**
* Author: Lambdalf the White
*/
pragma solidity 0.8.10;
abstract contract IPausable {
// Errors
error IPausable_SALE_NOT_CLOSED();
error IPausable_SALE_NOT_OPEN();
error IPausable_PRESALE_NOT_OPEN();
// Enum to represent the sale state, defaults to ``CLOSED``.
enum SaleState { CLOSED, PRESALE, SALE }
// The current state of the contract
SaleState public saleState;
/**
* @dev Emitted when the sale state changes
*/
event SaleStateChanged( SaleState indexed previousState, SaleState indexed newState );
/**
* @dev Sale state can have one of 3 values, ``CLOSED``, ``PRESALE``, or ``SALE``.
*/
function _setSaleState( SaleState newState_ ) internal virtual {
SaleState _previousState_ = saleState;
saleState = newState_;
emit SaleStateChanged( _previousState_, newState_ );
}
/**
* @dev Throws if sale state is not ``CLOSED``.
*/
modifier saleClosed {
if ( saleState != SaleState.CLOSED ) {
revert IPausable_SALE_NOT_CLOSED();
}
_;
}
/**
* @dev Throws if sale state is not ``SALE``.
*/
modifier saleOpen {
if ( saleState != SaleState.SALE ) {
revert IPausable_SALE_NOT_OPEN();
}
_;
}
/**
* @dev Throws if sale state is not ``PRESALE``.
*/
modifier presaleOpen {
if ( saleState != SaleState.PRESALE ) {
revert IPausable_PRESALE_NOT_OPEN();
}
_;
}
}
// File: contracts/IOwnable.sol
/**
* Author: Lambdalf the White
*/
pragma solidity 0.8.10;
/**
* @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 IOwnable {
// Errors
error IOwnable_NOT_OWNER();
// The owner of the contract
address private _owner;
/**
* @dev Emitted when contract ownership changes.
*/
event OwnershipTransferred( address indexed previousOwner, address indexed newOwner );
/**
* @dev Initializes the contract setting the deployer as the initial owner.
*/
function _initIOwnable( address owner_ ) internal {
_owner = owner_;
}
/**
* @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() {
if ( owner() != msg.sender ) {
revert IOwnable_NOT_OWNER();
}
_;
}
/**
* @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 {
address _oldOwner_ = _owner;
_owner = newOwner_;
emit OwnershipTransferred( _oldOwner_, newOwner_ );
}
}
// File: contracts/IERC2981.sol
pragma solidity 0.8.10;
interface IERC2981 {
/**
* @dev ERC165 bytes to add to interface array - set in parent contract
* implementing this standard
*
* bytes4(keccak256("royaltyInfo(uint256,uint256)")) == 0x2a55205a
* bytes4 private constant _INTERFACE_ID_ERC2981 = 0x2a55205a;
* _registerInterface(_INTERFACE_ID_ERC2981);
*
* @notice Called with the sale price to determine how much royalty
* is owed and to whom.
* @param _tokenId - the NFT asset queried for royalty information
* @param _salePrice - the sale price of the NFT asset specified by _tokenId
* @return receiver - address of who should be sent the royalty payment
* @return royaltyAmount - the royalty payment amount for _salePrice
*/
function royaltyInfo(uint256 _tokenId, uint256 _salePrice) external view returns (address receiver, uint256 royaltyAmount);
}
// File: contracts/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: contracts/IERC721Receiver.sol
// 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);
}
// File: contracts/IERC165.sol
// OpenZeppelin Contracts v4.4.1 (utils/introspection/IERC165.sol)
pragma solidity 0.8.10;
/**
* @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);
}
// File: contracts/ERC2981Base.sol
/**
* Author: Lambdalf the White
*/
pragma solidity 0.8.10;
abstract contract ERC2981Base is IERC165, IERC2981 {
// Errors
error IERC2981_INVALID_ROYALTIES();
// Royalty rate is stored out of 10,000 instead of a percentage to allow for
// up to two digits below the unit such as 2.5% or 1.25%.
uint private constant ROYALTY_BASE = 10000;
// Represents the percentage of royalties on each sale on secondary markets.
// Set to 0 to have no royalties.
uint256 private _royaltyRate;
// Address of the recipient of the royalties.
address private _royaltyRecipient;
function _initERC2981Base( address royaltyRecipient_, uint256 royaltyRate_ ) internal {
_setRoyaltyInfo( royaltyRecipient_, royaltyRate_ );
}
/**
* @dev See {IERC2981-royaltyInfo}.
*
* Note: This function should be overriden to revert on a query for non existent token.
*/
function royaltyInfo( uint256, uint256 salePrice_ ) public view virtual override returns ( address, uint256 ) {
if ( salePrice_ == 0 || _royaltyRate == 0 ) {
return ( _royaltyRecipient, 0 );
}
uint256 _royaltyAmount_ = _royaltyRate * salePrice_ / ROYALTY_BASE;
return ( _royaltyRecipient, _royaltyAmount_ );
}
/**
* @dev Sets the royalty rate to `royaltyRate_` and the royalty recipient to `royaltyRecipient_`.
*
* Requirements:
*
* - `royaltyRate_` cannot be higher than `ROYALTY_BASE`;
*/
function _setRoyaltyInfo( address royaltyRecipient_, uint256 royaltyRate_ ) internal virtual {
if ( royaltyRate_ > ROYALTY_BASE ) {
revert IERC2981_INVALID_ROYALTIES();
}
_royaltyRate = royaltyRate_;
_royaltyRecipient = royaltyRecipient_;
}
/**
* @dev See {IERC165-supportsInterface}.
*/
function supportsInterface( bytes4 interfaceId_ ) public view virtual override returns ( bool ) {
return
interfaceId_ == type( IERC2981 ).interfaceId ||
interfaceId_ == type( IERC165 ).interfaceId;
}
}
// File: contracts/IERC721.sol
// OpenZeppelin Contracts v4.4.1 (token/ERC721/IERC721.sol)
pragma solidity ^0.8.0;
/**
* @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;
}
// File: contracts/IERC721Metadata.sol
// OpenZeppelin Contracts v4.4.1 (token/ERC721/extensions/IERC721Metadata.sol)
pragma solidity ^0.8.0;
/**
* @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);
}
// File: contracts/ERC721Batch.sol
/**
* Author: Lambdalf the White
*/
pragma solidity 0.8.10;
/**
* @dev Required interface of an ERC721 compliant contract.
*/
abstract contract ERC721Batch is Context, IERC721Metadata {
// Errors
error IERC721_APPROVE_OWNER();
error IERC721_APPROVE_CALLER();
error IERC721_CALLER_NOT_APPROVED();
error IERC721_NONEXISTANT_TOKEN();
error IERC721_NON_ERC721_RECEIVER();
error IERC721_NULL_ADDRESS_BALANCE();
error IERC721_NULL_ADDRESS_TRANSFER();
// Token name
string private _name;
// Token symbol
string private _symbol;
// Token Base URI
string private _baseURI;
// Token IDs
uint256 private _numTokens;
// List of owner addresses
mapping( uint256 => address ) private _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 Ensures the token exist.
* A token exists if it has been minted and is not owned by the null address.
*
* @param tokenId_ uint256 ID of the token to verify
*/
modifier exists( uint256 tokenId_ ) {
if ( ! _exists( tokenId_ ) ) {
revert IERC721_NONEXISTANT_TOKEN();
}
_;
}
// **************************************
// ***** INTERNAL *****
// **************************************
/**
* @dev Internal function returning the number of tokens in `tokenOwner_`'s account.
*/
function _balanceOf( address tokenOwner_ ) internal view virtual returns ( uint256 ) {
if ( tokenOwner_ == address( 0 ) ) {
return 0;
}
uint256 _supplyMinted_ = _supplyMinted();
uint256 _count_ = 0;
address _currentTokenOwner_;
for ( uint256 i; i < _supplyMinted_; i++ ) {
if ( _owners[ i ] != address( 0 ) ) {
_currentTokenOwner_ = _owners[ i ];
}
if ( tokenOwner_ == _currentTokenOwner_ ) {
_count_++;
}
}
return _count_;
}
/**
* @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_ ) internal virtual 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.
//
// IMPORTANT
// It is unsafe to assume that an address not flagged by this method
// is an externally-owned account (EOA) and not a contract.
//
// Among others, the following types of addresses will not be flagged:
//
// - 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
uint256 _size_;
assembly {
_size_ := extcodesize( to_ )
}
// If address is a contract, check that it is aware of how to handle ERC721 tokens
if ( _size_ > 0 ) {
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 IERC721_NON_ERC721_RECEIVER();
}
else {
assembly {
revert( add( 32, reason ), mload( reason ) )
}
}
}
}
else {
return true;
}
}
/**
* @dev Internal function returning whether a token exists.
* A token exists if it has been minted and is not owned by the null address.
*
* @param tokenId_ uint256 ID of the token to verify
*
* @return bool whether the token exists
*/
function _exists( uint256 tokenId_ ) internal view virtual returns ( bool ) {
return tokenId_ < _numTokens;
}
/**
* @dev Initializes the contract by setting a `name` and a `symbol` to the token collection.
*/
function _initERC721BatchMetadata( string memory name_, string memory symbol_ ) internal {
_name = name_;
_symbol = symbol_;
}
/**
* @dev Internal function returning whether `operator_` is allowed
* to manage tokens on behalf of `tokenOwner_`.
*
* @param tokenOwner_ address that owns tokens
* @param operator_ address that tries to manage tokens
*
* @return bool whether `operator_` is allowed to handle the token
*/
function _isApprovedForAll( address tokenOwner_, address operator_ ) internal view virtual returns ( bool ) {
return _operatorApprovals[ tokenOwner_ ][ operator_ ];
}
/**
* @dev Internal function returning whether `operator_` is allowed to handle `tokenId_`
*
* Note: To avoid multiple checks for the same data, it is assumed that existence of `tokeId_`
* has been verified prior via {_exists}
* If it hasn't been verified, this function might panic
*
* @param operator_ address that tries to handle the token
* @param tokenId_ uint256 ID of the token to be handled
*
* @return bool whether `operator_` is allowed to handle the token
*/
function _isApprovedOrOwner( address tokenOwner_, address operator_, uint256 tokenId_ ) internal view virtual returns ( bool ) {
bool _isApproved_ = operator_ == tokenOwner_ ||
operator_ == _tokenApprovals[ tokenId_ ] ||
_isApprovedForAll( tokenOwner_, operator_ );
return _isApproved_;
}
/**
* @dev Mints `qty_` tokens and transfers them to `to_`.
*
* This internal function can be used to perform token minting.
*
* Emits a {ConsecutiveTransfer} event.
*/
function _mint( address to_, uint256 qty_ ) internal virtual {
uint256 _firstToken_ = _numTokens;
uint256 _lastToken_ = _firstToken_ + qty_ - 1;
_owners[ _firstToken_ ] = to_;
if ( _lastToken_ > _firstToken_ ) {
_owners[ _lastToken_ ] = to_;
}
for ( uint256 i; i < qty_; i ++ ) {
emit Transfer( address( 0 ), to_, _firstToken_ + i );
}
_numTokens = _lastToken_ + 1;
}
/**
* @dev Internal function returning the owner of the `tokenId_` token.
*
* @param tokenId_ uint256 ID of the token to verify
*
* @return address the address of the token owner
*/
function _ownerOf( uint256 tokenId_ ) internal view virtual returns ( address ) {
uint256 _tokenId_ = tokenId_;
address _tokenOwner_ = _owners[ _tokenId_ ];
while ( _tokenOwner_ == address( 0 ) ) {
_tokenId_ --;
_tokenOwner_ = _owners[ _tokenId_ ];
}
return _tokenOwner_;
}
/**
* @dev Internal function used to set the base URI of the collection.
*/
function _setBaseURI( string memory baseURI_ ) internal virtual {
_baseURI = baseURI_;
}
/**
* @dev Internal function returning the total number of tokens minted
*
* @return uint256 the number of tokens that have been minted so far
*/
function _supplyMinted() internal view virtual returns ( uint256 ) {
return _numTokens;
}
/**
* @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 Transfers `tokenId_` from `from_` to `to_`.
*
* This internal function can be used to implement alternative mechanisms to perform
* token transfer, such as signature-based, or token burning.
*
* Emits a {Transfer} event.
*/
function _transfer( address from_, address to_, uint256 tokenId_ ) internal virtual {
_tokenApprovals[ tokenId_ ] = address( 0 );
uint256 _previousId_ = tokenId_ > 0 ? tokenId_ - 1 : 0;
uint256 _nextId_ = tokenId_ + 1;
bool _previousShouldUpdate_ = _previousId_ < tokenId_ &&
_exists( _previousId_ ) &&
_owners[ _previousId_ ] == address( 0 );
bool _nextShouldUpdate_ = _exists( _nextId_ ) &&
_owners[ _nextId_ ] == address( 0 );
if ( _previousShouldUpdate_ ) {
_owners[ _previousId_ ] = from_;
}
if ( _nextShouldUpdate_ ) {
_owners[ _nextId_ ] = from_;
}
_owners[ tokenId_ ] = to_;
emit Transfer( from_, to_, tokenId_ );
}
// **************************************
// ***** PUBLIC *****
// **************************************
/**
* @dev See {IERC721-approve}.
*/
function approve( address to_, uint256 tokenId_ ) external virtual exists( tokenId_ ) {
address _operator_ = _msgSender();
address _tokenOwner_ = _ownerOf( tokenId_ );
bool _isApproved_ = _isApprovedOrOwner( _tokenOwner_, _operator_, tokenId_ );
if ( ! _isApproved_ ) {
revert IERC721_CALLER_NOT_APPROVED();
}
if ( to_ == _tokenOwner_ ) {
revert IERC721_APPROVE_OWNER();
}
_tokenApprovals[ tokenId_ ] = to_;
emit Approval( _tokenOwner_, to_, tokenId_ );
}
/**
* @dev See {IERC721-safeTransferFrom}.
*
* Note: We can ignore `from_` as we can compare everything to the actual token owner,
* but we cannot remove this parameter to stay in conformity with IERC721
*/
function safeTransferFrom( address, address to_, uint256 tokenId_ ) external virtual exists( tokenId_ ) {
address _operator_ = _msgSender();
address _tokenOwner_ = _ownerOf( tokenId_ );
bool _isApproved_ = _isApprovedOrOwner( _tokenOwner_, _operator_, tokenId_ );
if ( ! _isApproved_ ) {
revert IERC721_CALLER_NOT_APPROVED();
}
if ( to_ == address( 0 ) ) {
revert IERC721_NULL_ADDRESS_TRANSFER();
}
_transfer( _tokenOwner_, to_, tokenId_ );
if ( ! _checkOnERC721Received( _tokenOwner_, to_, tokenId_, "" ) ) {
revert IERC721_NON_ERC721_RECEIVER();
}
}
/**
* @dev See {IERC721-safeTransferFrom}.
*
* Note: We can ignore `from_` as we can compare everything to the actual token owner,
* but we cannot remove this parameter to stay in conformity with IERC721
*/
function safeTransferFrom( address, address to_, uint256 tokenId_, bytes calldata data_ ) external virtual exists( tokenId_ ) {
address _operator_ = _msgSender();
address _tokenOwner_ = _ownerOf( tokenId_ );
bool _isApproved_ = _isApprovedOrOwner( _tokenOwner_, _operator_, tokenId_ );
if ( ! _isApproved_ ) {
revert IERC721_CALLER_NOT_APPROVED();
}
if ( to_ == address( 0 ) ) {
revert IERC721_NULL_ADDRESS_TRANSFER();
}
_transfer( _tokenOwner_, to_, tokenId_ );
if ( ! _checkOnERC721Received( _tokenOwner_, to_, tokenId_, data_ ) ) {
revert IERC721_NON_ERC721_RECEIVER();
}
}
/**
* @dev See {IERC721-setApprovalForAll}.
*/
function setApprovalForAll( address operator_, bool approved_ ) public virtual override {
address _account_ = _msgSender();
if ( operator_ == _account_ ) {
revert IERC721_APPROVE_CALLER();
}
_operatorApprovals[ _account_ ][ operator_ ] = approved_;
emit ApprovalForAll( _account_, operator_, approved_ );
}
/**
* @dev See {IERC721-transferFrom}.
*
* Note: We can ignore `from_` as we can compare everything to the actual token owner,
* but we cannot remove this parameter to stay in conformity with IERC721
*/
function transferFrom( address, address to_, uint256 tokenId_ ) external virtual exists( tokenId_ ) {
address _operator_ = _msgSender();
address _tokenOwner_ = _ownerOf( tokenId_ );
bool _isApproved_ = _isApprovedOrOwner( _tokenOwner_, _operator_, tokenId_ );
if ( ! _isApproved_ ) {
revert IERC721_CALLER_NOT_APPROVED();
}
if ( to_ == address( 0 ) ) {
revert IERC721_NULL_ADDRESS_TRANSFER();
}
_transfer( _tokenOwner_, to_, tokenId_ );
}
// **************************************
// ***** VIEW *****
// **************************************
/**
* @dev Returns the number of tokens in `tokenOwner_`'s account.
*/
function balanceOf( address tokenOwner_ ) external view virtual returns ( uint256 ) {
return _balanceOf( tokenOwner_ );
}
/**
* @dev Returns the account approved for `tokenId_` token.
*
* Requirements:
*
* - `tokenId_` must exist.
*/
function getApproved( uint256 tokenId_ ) external view virtual exists( tokenId_ ) returns ( address ) {
return _tokenApprovals[ tokenId_ ];
}
/**
* @dev Returns if the `operator_` is allowed to manage all of the assets of `tokenOwner_`.
*
* See {setApprovalForAll}
*/
function isApprovedForAll( address tokenOwner_, address operator_ ) external view virtual returns ( bool ) {
return _isApprovedForAll( tokenOwner_, operator_ );
}
/**
* @dev See {IERC721Metadata-name}.
*/
function name() public view virtual override returns ( string memory ) {
return _name;
}
/**
* @dev Returns the owner of the `tokenId_` token.
*
* Requirements:
*
* - `tokenId_` must exist.
*/
function ownerOf( uint256 tokenId_ ) external view virtual exists( tokenId_ ) returns ( address ) {
return _ownerOf( tokenId_ );
}
/**
* @dev See {IERC165-supportsInterface}.
*/
function supportsInterface( bytes4 interfaceId_ ) public view virtual override returns ( bool ) {
return
interfaceId_ == type( IERC721Metadata ).interfaceId ||
interfaceId_ == type( IERC721 ).interfaceId ||
interfaceId_ == type( IERC165 ).interfaceId;
}
/**
* @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 exists( tokenId_ ) returns ( string memory ) {
return bytes( _baseURI ).length > 0 ? string( abi.encodePacked( _baseURI, _toString( tokenId_ ) ) ) : _toString( tokenId_ );
}
}
// File: contracts/ERC721BatchStakable.sol
/**
* Author: Lambdalf the White
*/
pragma solidity 0.8.10;
/**
* @dev Implementation of https://eips.ethereum.org/EIPS/eip-721[ERC721] Non-Fungible Token Standard, including
* the Metadata extension and the Enumerable extension.
*
* Note: This implementation is only compatible with a sequential order of tokens minted.
* If you need to mint tokens in a random order, you will need to override the following functions:
* Note also that this implementations is fairly inefficient and as such,
* those functions should be avoided inside non-view functions.
*/
abstract contract ERC721BatchStakable is ERC721Batch, IERC721Receiver {
// Mapping of tokenId to stakeholder address
mapping( uint256 => address ) internal _stakedOwners;
// **************************************
// ***** INTERNAL *****
// **************************************
/**
* @dev Internal function returning the number of tokens staked by `tokenOwner_`.
*/
function _balanceOfStaked( address tokenOwner_ ) internal view virtual returns ( uint256 ) {
if ( tokenOwner_ == address( 0 ) ) {
return 0;
}
uint256 _supplyMinted_ = _supplyMinted();
uint256 _count_ = 0;
for ( uint256 i; i < _supplyMinted_; i++ ) {
if ( _stakedOwners[ i ] == tokenOwner_ ) {
_count_++;
}
}
return _count_;
}
/**
* @dev Internal function that mints `qtyMinted_` tokens and stakes `qtyStaked_` of them to the count of `tokenOwner_`.
*/
function _mintAndStake( address tokenOwner_, uint256 qtyMinted_, uint256 qtyStaked_ ) internal {
uint256 _qtyNotStaked_;
uint256 _qtyStaked_ = qtyStaked_;
if ( qtyStaked_ > qtyMinted_ ) {
_qtyStaked_ = qtyMinted_;
}
else if ( qtyStaked_ < qtyMinted_ ) {
_qtyNotStaked_ = qtyMinted_ - qtyStaked_;
}
if ( _qtyStaked_ > 0 ) {
_mintInContract( tokenOwner_, _qtyStaked_ );
}
if ( _qtyNotStaked_ > 0 ) {
_mint( tokenOwner_, _qtyNotStaked_ );
}
}
/**
* @dev Internal function that mints `qtyStaked_` tokens and stakes them to the count of `tokenOwner_`.
*/
function _mintInContract( address tokenOwner_, uint256 qtyStaked_ ) internal {
uint256 _currentToken_ = _supplyMinted();
uint256 _lastToken_ = _currentToken_ + qtyStaked_ - 1;
while ( _currentToken_ <= _lastToken_ ) {
_stakedOwners[ _currentToken_ ] = tokenOwner_;
_currentToken_ ++;
}
_mint( address( this ), qtyStaked_ );
}
/**
* @dev Internal function returning the owner of the staked token number `tokenId_`.
*
* Requirements:
*
* - `tokenId_` must exist.
*/
function _ownerOfStaked( uint256 tokenId_ ) internal view virtual returns ( address ) {
return _stakedOwners[ tokenId_ ];
}
/**
* @dev Internal function that stakes the token number `tokenId_` to the count of `tokenOwner_`.
*/
function _stake( address tokenOwner_, uint256 tokenId_ ) internal {
_stakedOwners[ tokenId_ ] = tokenOwner_;
_transfer( tokenOwner_, address( this ), tokenId_ );
}
/**
* @dev Internal function that unstakes the token `tokenId_` and transfers it back to `tokenOwner_`.
*/
function _unstake( address tokenOwner_, uint256 tokenId_ ) internal {
_transfer( address( this ), tokenOwner_, tokenId_ );
delete _stakedOwners[ tokenId_ ];
}
// **************************************
// **************************************
// ***** PUBLIC *****
// **************************************
/**
* @dev Stakes the token `tokenId_` to the count of its owner.
*
* Requirements:
*
* - Caller must be allowed to manage `tokenId_` or its owner's tokens.
* - `tokenId_` must exist.
*/
function stake( uint256 tokenId_ ) external exists( tokenId_ ) {
address _operator_ = _msgSender();
address _tokenOwner_ = _ownerOf( tokenId_ );
bool _isApproved_ = _isApprovedOrOwner( _tokenOwner_, _operator_, tokenId_ );
if ( ! _isApproved_ ) {
revert IERC721_CALLER_NOT_APPROVED();
}
_stake( _tokenOwner_, tokenId_ );
}
/**
* @dev Unstakes the token `tokenId_` and returns it to its owner.
*
* Requirements:
*
* - Caller must be allowed to manage `tokenId_` or its owner's tokens.
* - `tokenId_` must exist.
*/
function unstake( uint256 tokenId_ ) external exists( tokenId_ ) {
address _operator_ = _msgSender();
address _tokenOwner_ = _ownerOfStaked( tokenId_ );
bool _isApproved_ = _isApprovedOrOwner( _tokenOwner_, _operator_, tokenId_ );
if ( ! _isApproved_ ) {
revert IERC721_CALLER_NOT_APPROVED();
}
_unstake( _tokenOwner_, tokenId_ );
}
// **************************************
// **************************************
// ***** VIEW *****
// **************************************
/**
* @dev Returns the number of tokens owned by `tokenOwner_`.
*/
function balanceOf( address tokenOwner_ ) public view virtual override returns ( uint256 balance ) {
return _balanceOfStaked( tokenOwner_ ) + _balanceOf( tokenOwner_ );
}
/**
* @dev Returns the number of tokens staked by `tokenOwner_`.
*/
function balanceOfStaked( address tokenOwner_ ) public view virtual returns ( uint256 ) {
return _balanceOfStaked( tokenOwner_ );
}
/**
* @dev Returns the owner of token number `tokenId_`.
*
* Requirements:
*
* - `tokenId_` must exist.
*/
function ownerOf( uint256 tokenId_ ) public view virtual override exists( tokenId_ ) returns ( address ) {
address _tokenOwner_ = _ownerOf( tokenId_ );
if ( _tokenOwner_ == address( this ) ) {
return _ownerOfStaked( tokenId_ );
}
return _tokenOwner_;
}
/**
* @dev Returns the owner of staked token number `tokenId_`.
*
* Requirements:
*
* - `tokenId_` must exist.
*/
function ownerOfStaked( uint256 tokenId_ ) public view virtual exists( tokenId_ ) returns ( address ) {
return _ownerOfStaked( tokenId_ );
}
// **************************************
// **************************************
// ***** PURE *****
// **************************************
/**
* @dev Signals that this contract knows how to handle ERC721 tokens.
*/
function onERC721Received( address, address, uint256, bytes memory ) public override pure returns ( bytes4 ) {
return type( IERC721Receiver ).interfaceId;
}
// **************************************
}
// File: contracts/IERC721Enumerable.sol
// OpenZeppelin Contracts (last updated v4.5.0) (token/ERC721/extensions/IERC721Enumerable.sol)
pragma solidity ^0.8.0;
/**
* @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);
}
// File: contracts/ERC721BatchEnumerable.sol
/**
* Author: Lambdalf the White
*/
pragma solidity 0.8.10;
/**
* @dev Implementation of https://eips.ethereum.org/EIPS/eip-721[ERC721] Non-Fungible Token Standard, including
* the Metadata extension and the Enumerable extension.
*
* Note: This implementation is only compatible with a sequential order of tokens minted.
* If you need to mint tokens in a random order, you will need to override the following functions:
* Note also that this implementations is fairly inefficient and as such,
* those functions should be avoided inside non-view functions.
*/
abstract contract ERC721BatchEnumerable is ERC721Batch, IERC721Enumerable {
// Errors
error IERC721Enumerable_OWNER_INDEX_OUT_OF_BOUNDS();
error IERC721Enumerable_INDEX_OUT_OF_BOUNDS();
/**
* @dev See {IERC165-supportsInterface}.
*/
function supportsInterface( bytes4 interfaceId_ ) public view virtual override(IERC165, ERC721Batch) returns ( bool ) {
return
interfaceId_ == type( IERC721Enumerable ).interfaceId ||
super.supportsInterface( interfaceId_ );
}
/**
* @dev See {IERC721Enumerable-tokenByIndex}.
*/
function tokenByIndex( uint256 index_ ) public view virtual override returns ( uint256 ) {
if ( index_ >= _supplyMinted() ) {
revert IERC721Enumerable_INDEX_OUT_OF_BOUNDS();
}
return index_;
}
/**
* @dev See {IERC721Enumerable-tokenOfOwnerByIndex}.
*/
function tokenOfOwnerByIndex( address tokenOwner_, uint256 index_ ) public view virtual override returns ( uint256 tokenId ) {
uint256 _supplyMinted_ = _supplyMinted();
if ( index_ >= _balanceOf( tokenOwner_ ) ) {
revert IERC721Enumerable_OWNER_INDEX_OUT_OF_BOUNDS();
}
uint256 _count_ = 0;
for ( uint256 i = 0; i < _supplyMinted_; i++ ) {
if ( _exists( i ) && tokenOwner_ == _ownerOf( i ) ) {
if ( index_ == _count_ ) {
return i;
}
_count_++;
}
}
}
/**
* @dev See {IERC721Enumerable-totalSupply}.
*/
function totalSupply() public view virtual override returns ( uint256 ) {
uint256 _supplyMinted_ = _supplyMinted();
uint256 _count_ = 0;
for ( uint256 i; i < _supplyMinted_; i++ ) {
if ( _exists( i ) ) {
_count_++;
}
}
return _count_;
}
}
// File: contracts/CCFoundersKeys.sol
/**
* Author: Lambdalf the White
*/
pragma solidity 0.8.10;
contract CCFoundersKeys is ERC721BatchEnumerable, ERC721BatchStakable, ERC2981Base, IOwnable, IPausable, ITradable, IWhitelistable {
// Events
event PaymentReleased( address indexed from, address[] indexed tos, uint256[] indexed amounts );
// Errors
error CCFoundersKeys_ARRAY_LENGTH_MISMATCH();
error CCFoundersKeys_FORBIDDEN();
error CCFoundersKeys_INCORRECT_PRICE();
error CCFoundersKeys_INSUFFICIENT_KEY_BALANCE();
error CCFoundersKeys_MAX_BATCH();
error CCFoundersKeys_MAX_RESERVE();
error CCFoundersKeys_MAX_SUPPLY();
error CCFoundersKeys_NO_ETHER_BALANCE();
error CCFoundersKeys_TRANSFER_FAIL();
// Founders Key whitelist mint price
uint public immutable WL_MINT_PRICE; // = 0.069 ether;
// Founders Key public mint price
uint public immutable PUBLIC_MINT_PRICE; // = 0.1 ether;
// Max supply
uint public immutable MAX_SUPPLY;
// Max TX
uint public immutable MAX_BATCH;
// 2C Safe wallet ~ 90%
address private immutable _CC_SAFE;
// 2C Operations wallet ~ 5%
address private immutable _CC_CHARITY;
// 2C Founders wallet ~ 2.5%
address private immutable _CC_FOUNDERS;
// 2C Community wallet ~ 2.5%
address private immutable _CC_COMMUNITY;
// Mapping of Anon holders to amount of free key claimable
mapping( address => uint256 ) public anonClaimList;
uint256 private _reserve;
constructor(
uint256 reserve_,
uint256 maxBatch_,
uint256 maxSupply_,
uint256 royaltyRate_,
uint256 wlMintPrice_,
uint256 publicMintPrice_,
string memory name_,
string memory symbol_,
string memory baseURI_,
// address devAddress_,
address[] memory wallets_
) {
address _contractOwner_ = _msgSender();
_initIOwnable( _contractOwner_ );
_initERC2981Base( _contractOwner_, royaltyRate_ );
_initERC721BatchMetadata( name_, symbol_ );
_setBaseURI( baseURI_ );
_CC_SAFE = wallets_[ 0 ];
_CC_CHARITY = wallets_[ 1 ];
_CC_FOUNDERS = wallets_[ 2 ];
_CC_COMMUNITY = wallets_[ 3 ];
_reserve = reserve_;
MAX_BATCH = maxBatch_;
MAX_SUPPLY = maxSupply_;
WL_MINT_PRICE = wlMintPrice_;
PUBLIC_MINT_PRICE = publicMintPrice_;
// _mintAndStake( devAddress_, 5 );
}
// **************************************
// ***** INTERNAL *****
// **************************************
/**
* @dev Internal function returning whether `operator_` is allowed to manage tokens on behalf of `tokenOwner_`.
*
* @param tokenOwner_ address that owns tokens
* @param operator_ address that tries to manage tokens
*
* @return bool whether `operator_` is allowed to manage the token
*/
function _isApprovedForAll( address tokenOwner_, address operator_ ) internal view virtual override returns ( bool ) {
return _isRegisteredProxy( tokenOwner_, operator_ ) ||
super._isApprovedForAll( tokenOwner_, operator_ );
}
/**
* @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 {
if ( address( this ).balance < amount_ ) {
revert CCFoundersKeys_INCORRECT_PRICE();
}
( bool _success_, ) = recipient_.call{ value: amount_ }( "" );
if ( ! _success_ ) {
revert CCFoundersKeys_TRANSFER_FAIL();
}
}
// **************************************
// **************************************
// ***** PUBLIC *****
// **************************************
/**
* @dev Mints `qty_` tokens and transfers them to the caller.
*
* Requirements:
*
* - Sale state must be {SaleState.PRESALE}.
* - There must be enough tokens left to mint outside of the reserve.
* - Caller must be whitelisted.
*/
function claim( uint256 qty_ ) external presaleOpen {
address _account_ = _msgSender();
if ( qty_ > anonClaimList[ _account_ ] ) {
revert CCFoundersKeys_FORBIDDEN();
}
uint256 _endSupply_ = _supplyMinted() + qty_;
if ( _endSupply_ > MAX_SUPPLY - _reserve ) {
revert CCFoundersKeys_MAX_SUPPLY();
}
unchecked {
anonClaimList[ _account_ ] -= qty_;
}
_mint( _account_, qty_ );
}
/**
* @dev Mints `qty_` tokens, stakes `qtyStaked_` of them to the count of the caller, and transfers the remaining to them.
*
* Requirements:
*
* - Sale state must be {SaleState.PRESALE}.
* - There must be enough tokens left to mint outside of the reserve.
* - Caller must be whitelisted.
* - If `qtyStaked_` is higher than `qty_`, only `qty_` tokens are staked.
*/
function claimAndStake( uint256 qty_, uint256 qtyStaked_ ) external presaleOpen {
address _account_ = _msgSender();
if ( qty_ > anonClaimList[ _account_ ] ) {
revert CCFoundersKeys_FORBIDDEN();
}
uint256 _endSupply_ = _supplyMinted() + qty_;
if ( _endSupply_ > MAX_SUPPLY - _reserve ) {
revert CCFoundersKeys_MAX_SUPPLY();
}
unchecked {
anonClaimList[ _account_ ] -= qty_;
}
_mintAndStake( _account_, qty_, qtyStaked_ );
}
/**
* @dev Mints a token and transfers it to the caller.
*
* Requirements:
*
* - Sale state must be {SaleState.PRESALE}.
* - There must be enough tokens left to mint outside of the reserve.
* - Caller must send enough ether to pay for 1 token at presale price.
* - Caller must be whitelisted.
*/
function mintPreSale( bytes32[] memory proof_ ) external payable presaleOpen isWhitelisted( _msgSender(), proof_, 1, 1 ) {
if ( _supplyMinted() + 1 > MAX_SUPPLY - _reserve ) {
revert CCFoundersKeys_MAX_SUPPLY();
}
if ( WL_MINT_PRICE != msg.value ) {
revert CCFoundersKeys_INCORRECT_PRICE();
}
address _account_ = _msgSender();
_consumeWhitelist( _account_, 1 );
_mint( _account_, 1 );
}
/**
* @dev Mints a token and stakes it to the count of the caller.
*
* Requirements:
*
* - Sale state must be {SaleState.PRESALE}.
* - There must be enough tokens left to mint outside of the reserve.
* - Caller must send enough ether to pay for 1 token at presale price.
* - Caller must be whitelisted.
*/
function mintPreSaleAndStake( bytes32[] memory proof_ ) external payable presaleOpen isWhitelisted( _msgSender(), proof_, 1, 1 ) {
if ( _supplyMinted() + 1 > MAX_SUPPLY - _reserve ) {
revert CCFoundersKeys_MAX_SUPPLY();
}
if ( WL_MINT_PRICE != msg.value ) {
revert CCFoundersKeys_INCORRECT_PRICE();
}
address _account_ = _msgSender();
_consumeWhitelist( _account_, 1 );
_mintAndStake( _account_, 1, 1 );
}
/**
* @dev Mints `qty_` tokens and transfers them to the caller.
*
* Requirements:
*
* - Sale state must be {SaleState.SALE}.
* - There must be enough tokens left to mint outside of the reserve.
* - Caller must send enough ether to pay for `qty_` tokens at public sale price.
*/
function mint( uint256 qty_ ) external payable saleOpen {
if ( qty_ > MAX_BATCH ) {
revert CCFoundersKeys_MAX_BATCH();
}
uint256 _endSupply_ = _supplyMinted() + qty_;
if ( _endSupply_ > MAX_SUPPLY - _reserve ) {
revert CCFoundersKeys_MAX_SUPPLY();
}
if ( qty_ * PUBLIC_MINT_PRICE != msg.value ) {
revert CCFoundersKeys_INCORRECT_PRICE();
}
address _account_ = _msgSender();
_mint( _account_, qty_ );
}
/**
* @dev Mints `qty_` tokens, stakes `qtyStaked_` of them to the count of the caller, and transfers the remaining to them.
*
* Requirements:
*
* - Sale state must be {SaleState.SALE}.
* - There must be enough tokens left to mint outside of the reserve.
* - Caller must send enough ether to pay for `qty_` tokens at public sale price.
* - If `qtyStaked_` is higher than `qty_`, only `qty_` tokens are staked.
*/
function mintAndStake( uint256 qty_, uint256 qtyStaked_ ) external payable saleOpen {
if ( qty_ > MAX_BATCH ) {
revert CCFoundersKeys_MAX_BATCH();
}
uint256 _endSupply_ = _supplyMinted() + qty_;
if ( _endSupply_ > MAX_SUPPLY - _reserve ) {
revert CCFoundersKeys_MAX_SUPPLY();
}
if ( qty_ * PUBLIC_MINT_PRICE != msg.value ) {
revert CCFoundersKeys_INCORRECT_PRICE();
}
address _account_ = _msgSender();
_mintAndStake( _account_, qty_, qtyStaked_ );
}
// **************************************
// **************************************
// ***** CONTRACT_OWNER *****
// **************************************
/**
* @dev Mints `amounts_` tokens and transfers them to `accounts_`.
*
* Requirements:
*
* - Caller must be the contract owner.
* - `accounts_` and `amounts_` must have the same length.
* - There must be enough tokens left in the reserve.
*/
function airdrop( address[] memory accounts_, uint256[] memory amounts_ ) external onlyOwner {
uint256 _len_ = amounts_.length;
if ( _len_ != accounts_.length ) {
revert CCFoundersKeys_ARRAY_LENGTH_MISMATCH();
}
uint _totalQty_;
for ( uint256 i = _len_; i > 0; i -- ) {
_totalQty_ += amounts_[ i - 1 ];
}
if ( _totalQty_ > _reserve ) {
revert CCFoundersKeys_MAX_RESERVE();
}
unchecked {
_reserve -= _totalQty_;
}
for ( uint256 i = _len_; i > 0; i -- ) {
_mint( accounts_[ i - 1], amounts_[ i - 1] );
}
}
/**
* @dev Saves `accounts_` in the anon claim list.
*
* Requirements:
*
* - Caller must be the contract owner.
* - Sale state must be {SaleState.CLOSED}.
* - `accounts_` and `amounts_` must have the same length.
*/
function setAnonClaimList( address[] memory accounts_, uint256[] memory amounts_ ) external onlyOwner saleClosed {
uint256 _len_ = amounts_.length;
if ( _len_ != accounts_.length ) {
revert CCFoundersKeys_ARRAY_LENGTH_MISMATCH();
}
for ( uint256 i; i < _len_; i ++ ) {
anonClaimList[ accounts_[ i ] ] = amounts_[ i ];
}
}
/**
* @dev See {ITradable-setProxyRegistry}.
*
* Requirements:
*
* - Caller must be the contract owner.
*/
function setProxyRegistry( address proxyRegistryAddress_ ) external onlyOwner {
_setProxyRegistry( proxyRegistryAddress_ );
}
/**
* @dev Updates the royalty recipient and rate.
*
* Requirements:
*
* - Caller must be the contract owner.
*/
function setRoyaltyInfo( address royaltyRecipient_, uint256 royaltyRate_ ) external onlyOwner {
_setRoyaltyInfo( royaltyRecipient_, royaltyRate_ );
}
/**
* @dev See {IPausable-setSaleState}.
*
* Requirements:
*
* - Caller must be the contract owner.
*/
function setSaleState( SaleState newState_ ) external onlyOwner {
_setSaleState( newState_ );
}
/**
* @dev See {IWhitelistable-setWhitelist}.
*
* Requirements:
*
* - Caller must be the contract owner.
* - Sale state must be {SaleState.CLOSED}.
*/
function setWhitelist( bytes32 root_ ) external onlyOwner saleClosed {
_setWhitelist( root_ );
}
/**
* @dev Withdraws all the money stored in the contract and splits it amongst the set wallets.
*
* Requirements:
*
* - Caller must be the contract owner.
*/
function withdraw() external onlyOwner {
uint256 _balance_ = address(this).balance;
if ( _balance_ == 0 ) {
revert CCFoundersKeys_NO_ETHER_BALANCE();
}
uint256 _safeShare_ = _balance_ * 900 / 1000;
uint256 _charityShare_ = _balance_ * 50 / 1000;
uint256 _othersShare_ = _charityShare_ / 2;
_sendValue( payable( _CC_COMMUNITY ), _othersShare_ );
_sendValue( payable( _CC_FOUNDERS ), _othersShare_ );
_sendValue( payable( _CC_CHARITY ), _charityShare_ );
_sendValue( payable( _CC_SAFE ), _safeShare_ );
address[] memory _tos_ = new address[]( 4 );
_tos_[ 0 ] = _CC_COMMUNITY;
_tos_[ 1 ] = _CC_FOUNDERS;
_tos_[ 2 ] = _CC_CHARITY;
_tos_[ 3 ] = _CC_SAFE;
uint256[] memory _amounts_ = new uint256[]( 4 );
_amounts_[ 0 ] = _othersShare_;
_amounts_[ 1 ] = _othersShare_;
_amounts_[ 2 ] = _charityShare_;
_amounts_[ 3 ] = _safeShare_;
emit PaymentReleased( address( this ), _tos_, _amounts_ );
}
// **************************************
// **************************************
// ***** VIEW *****
// **************************************
/**
* @dev Returns the number of tokens owned by `tokenOwner_`.
*/
function balanceOf( address tokenOwner_ ) public view virtual override(ERC721Batch, ERC721BatchStakable) returns ( uint256 balance ) {
return ERC721BatchStakable.balanceOf( tokenOwner_ );
}
/**
* @dev Returns the owner of token number `tokenId_`.
*
* Requirements:
*
* - `tokenId_` must exist.
*/
function ownerOf( uint256 tokenId_ ) public view virtual override(ERC721Batch, ERC721BatchStakable) exists( tokenId_ ) returns ( address ) {
return ERC721BatchStakable.ownerOf( tokenId_ );
}
/**
* @dev See {IERC2981-royaltyInfo}.
*
* Requirements:
*
* - `tokenId_` must exist.
*/
function royaltyInfo( uint256 tokenId_, uint256 salePrice_ ) public view virtual override exists( tokenId_ ) returns ( address, uint256 ) {
return super.royaltyInfo( tokenId_, salePrice_ );
}
/**
* @dev See {IERC165-supportsInterface}.
*/
function supportsInterface( bytes4 interfaceId_ ) public view virtual override(ERC721BatchEnumerable, ERC721Batch, ERC2981Base) returns ( bool ) {
return
interfaceId_ == type( IERC2981 ).interfaceId ||
ERC721Batch.supportsInterface( interfaceId_ ) ||
ERC721BatchEnumerable.supportsInterface( interfaceId_ );
}
// **************************************
} | * @dev Throws if sale state is not ``SALE``./ | modifier saleOpen {
if ( saleState != SaleState.SALE ) {
revert IPausable_SALE_NOT_OPEN();
}
_;
}
| 14,920,108 | [
1,
21845,
309,
272,
5349,
919,
353,
486,
12176,
5233,
900,
68,
8338,
19,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
202,
20597,
272,
5349,
3678,
288,
203,
202,
202,
430,
261,
272,
5349,
1119,
480,
348,
5349,
1119,
18,
5233,
900,
262,
288,
203,
1082,
202,
266,
1097,
2971,
69,
16665,
67,
5233,
900,
67,
4400,
67,
11437,
5621,
203,
202,
202,
97,
203,
202,
202,
67,
31,
203,
202,
97,
203,
203,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
] |
// SPDX-License-Identifier: MIT
// 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/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/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) {
// This method relies in 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");
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: contracts/Pausable.sol
pragma solidity 0.6.12;
/**
* @dev Contract module which allows children to implement an emergency stop
* mechanism that can be triggered by an authorized account.
*
*/
contract Pausable is Context {
event Paused(address account);
event Shutdown(address account);
event Unpaused(address account);
event Open(address account);
bool public paused;
bool public stopEverything;
modifier whenNotPaused() {
require(!paused, "Pausable: paused");
_;
}
modifier whenPaused() {
require(paused, "Pausable: not paused");
_;
}
modifier whenNotShutdown() {
require(!stopEverything, "Pausable: shutdown");
_;
}
modifier whenShutdown() {
require(stopEverything, "Pausable: not shutdown");
_;
}
/// @dev Pause contract operations, if contract is not paused.
function _pause() internal virtual whenNotPaused {
paused = true;
emit Paused(_msgSender());
}
/// @dev Unpause contract operations, allow only if contract is paused and not shutdown.
function _unpause() internal virtual whenPaused whenNotShutdown {
paused = false;
emit Unpaused(_msgSender());
}
/// @dev Shutdown contract operations, if not already shutdown.
function _shutdown() internal virtual whenNotShutdown {
stopEverything = true;
paused = true;
emit Shutdown(_msgSender());
}
/// @dev Open contract operations, if contract is in shutdown state
function _open() internal virtual whenShutdown {
stopEverything = false;
emit Open(_msgSender());
}
}
// File: contracts/interfaces/aave/IAaveV2.sol
pragma solidity 0.6.12;
interface AaveLendingPoolAddressesProvider {
function getLendingPool() external view returns (address);
function getAddress(bytes32 id) external view returns (address);
}
interface AaveLendingPool {
function deposit(
address asset,
uint256 amount,
address onBehalfOf,
uint16 referralCode
) external;
function withdraw(
address asset,
uint256 amount,
address to
) external returns (uint256);
}
interface AaveProtocolDataProvider {
function getReserveTokensAddresses(address asset)
external
view
returns (
address aTokenAddress,
address stableDebtTokenAddress,
address variableDebtTokenAddress
);
}
// File: contracts/interfaces/maker/IMakerDAO.sol
pragma solidity 0.6.12;
interface ManagerLike {
function cdpCan(
address,
uint256,
address
) external view returns (uint256);
function ilks(uint256) external view returns (bytes32);
function owns(uint256) external view returns (address);
function urns(uint256) external view returns (address);
function vat() external view returns (address);
function open(bytes32, address) external returns (uint256);
function give(uint256, address) external;
function cdpAllow(
uint256,
address,
uint256
) external;
function urnAllow(address, uint256) external;
function frob(
uint256,
int256,
int256
) external;
function flux(
uint256,
address,
uint256
) external;
function move(
uint256,
address,
uint256
) external;
function exit(
address,
uint256,
address,
uint256
) external;
function quit(uint256, address) external;
function enter(address, uint256) external;
function shift(uint256, uint256) external;
}
interface VatLike {
function can(address, address) external view returns (uint256);
function ilks(bytes32)
external
view
returns (
uint256,
uint256,
uint256,
uint256,
uint256
);
function dai(address) external view returns (uint256);
function urns(bytes32, address) external view returns (uint256, uint256);
function frob(
bytes32,
address,
address,
address,
int256,
int256
) external;
function hope(address) external;
function nope(address) external;
function move(
address,
address,
uint256
) external;
}
interface GemJoinLike {
function dec() external view returns (uint256);
function gem() external view returns (address);
function ilk() external view returns (bytes32);
function join(address, uint256) external payable;
function exit(address, uint256) external;
}
interface DaiJoinLike {
function vat() external returns (VatLike);
function dai() external view returns (address);
function join(address, uint256) external payable;
function exit(address, uint256) external;
}
interface JugLike {
function drip(bytes32) external returns (uint256);
}
interface SpotterLike {
function ilks(bytes32) external view returns (address, uint256);
}
// File: contracts/interfaces/vesper/ICollateralManager.sol
pragma solidity 0.6.12;
interface ICollateralManager {
function addGemJoin(address[] calldata gemJoins) external;
function mcdManager() external view returns (address);
function borrow(uint256 vaultNum, uint256 amount) external;
function depositCollateral(uint256 vaultNum, uint256 amount) external;
function getVaultBalance(uint256 vaultNum) external view returns (uint256 collateralLocked);
function getVaultDebt(uint256 vaultNum) external view returns (uint256 daiDebt);
function getVaultInfo(uint256 vaultNum)
external
view
returns (
uint256 collateralLocked,
uint256 daiDebt,
uint256 collateralUsdRate,
uint256 collateralRatio,
uint256 minimumDebt
);
function payback(uint256 vaultNum, uint256 amount) external;
function registerVault(uint256 vaultNum, bytes32 collateralType) external;
function vaultOwner(uint256 vaultNum) external returns (address owner);
function whatWouldWithdrawDo(uint256 vaultNum, uint256 amount)
external
view
returns (
uint256 collateralLocked,
uint256 daiDebt,
uint256 collateralUsdRate,
uint256 collateralRatio,
uint256 minimumDebt
);
function withdrawCollateral(uint256 vaultNum, uint256 amount) external;
}
// File: contracts/interfaces/vesper/IController.sol
pragma solidity 0.6.12;
interface IController {
function aaveReferralCode() external view returns (uint16);
function feeCollector(address) external view returns (address);
function founderFee() external view returns (uint256);
function founderVault() external view returns (address);
function interestFee(address) external view returns (uint256);
function isPool(address) external view returns (bool);
function pools() external view returns (address);
function strategy(address) external view returns (address);
function rebalanceFriction(address) external view returns (uint256);
function poolRewards(address) external view returns (address);
function treasuryPool() external view returns (address);
function uniswapRouter() external view returns (address);
function withdrawFee(address) external view returns (uint256);
}
// File: contracts/interfaces/vesper/IStrategy.sol
pragma solidity 0.6.12;
interface IStrategy {
function rebalance() external;
function deposit(uint256 amount) external;
function beforeWithdraw() external;
function withdraw(uint256 amount) external;
function withdrawAll() external;
function isUpgradable() external view returns (bool);
function isReservedToken(address _token) external view returns (bool);
function token() external view returns (address);
function pool() external view returns (address);
function totalLocked() external view returns (uint256);
//Lifecycle functions
function pause() external;
function unpause() external;
}
// File: contracts/interfaces/vesper/IVesperPool.sol
pragma solidity 0.6.12;
interface IVesperPool is IERC20 {
function approveToken() external;
function deposit() external payable;
function deposit(uint256) external;
function multiTransfer(uint256[] memory) external returns (bool);
function permit(
address,
address,
uint256,
uint256,
uint8,
bytes32,
bytes32
) external;
function rebalance() external;
function resetApproval() external;
function sweepErc20(address) external;
function withdraw(uint256) external;
function withdrawETH(uint256) external;
function withdrawByStrategy(uint256) external;
function feeCollector() external view returns (address);
function getPricePerShare() external view returns (uint256);
function token() external view returns (address);
function tokensHere() external view returns (uint256);
function totalValue() external view returns (uint256);
function withdrawFee() external view returns (uint256);
}
// File: contracts/interfaces/uniswap/IUniswapV2Router01.sol
pragma solidity 0.6.12;
interface IUniswapV2Router01 {
function factory() external pure returns (address);
function WETH() external pure returns (address);
function swapExactTokensForTokens(
uint256 amountIn,
uint256 amountOutMin,
address[] calldata path,
address to,
uint256 deadline
) external returns (uint256[] memory amounts);
function swapTokensForExactTokens(
uint256 amountOut,
uint256 amountInMax,
address[] calldata path,
address to,
uint256 deadline
) external returns (uint256[] memory amounts);
function swapExactETHForTokens(
uint256 amountOutMin,
address[] calldata path,
address to,
uint256 deadline
) external payable returns (uint256[] memory amounts);
function swapTokensForExactETH(
uint256 amountOut,
uint256 amountInMax,
address[] calldata path,
address to,
uint256 deadline
) external returns (uint256[] memory amounts);
function swapExactTokensForETH(
uint256 amountIn,
uint256 amountOutMin,
address[] calldata path,
address to,
uint256 deadline
) external returns (uint256[] memory amounts);
function swapETHForExactTokens(
uint256 amountOut,
address[] calldata path,
address to,
uint256 deadline
) external payable returns (uint256[] memory amounts);
function quote(
uint256 amountA,
uint256 reserveA,
uint256 reserveB
) external pure returns (uint256 amountB);
function getAmountOut(
uint256 amountIn,
uint256 reserveIn,
uint256 reserveOut
) external pure returns (uint256 amountOut);
function getAmountIn(
uint256 amountOut,
uint256 reserveIn,
uint256 reserveOut
) external pure returns (uint256 amountIn);
function getAmountsOut(uint256 amountIn, address[] calldata path)
external
view
returns (uint256[] memory amounts);
function getAmountsIn(uint256 amountOut, address[] calldata path)
external
view
returns (uint256[] memory amounts);
}
// File: contracts/interfaces/uniswap/IUniswapV2Router02.sol
pragma solidity 0.6.12;
interface IUniswapV2Router02 is IUniswapV2Router01 {
function swapExactTokensForTokensSupportingFeeOnTransferTokens(
uint256 amountIn,
uint256 amountOutMin,
address[] calldata path,
address to,
uint256 deadline
) external;
function swapExactETHForTokensSupportingFeeOnTransferTokens(
uint256 amountOutMin,
address[] calldata path,
address to,
uint256 deadline
) external payable;
function swapExactTokensForETHSupportingFeeOnTransferTokens(
uint256 amountIn,
uint256 amountOutMin,
address[] calldata path,
address to,
uint256 deadline
) external;
}
// File: contracts/strategies/AaveV2MakerStrategy.sol
pragma solidity 0.6.12;
/// @dev This strategy will deposit collateral token in Maker and borrow DAI
/// and deposit borrowed DAI in Aave to earn interest on it.
abstract contract AaveV2MakerStrategy is IStrategy, Pausable {
using SafeERC20 for IERC20;
using SafeMath for uint256;
address public constant WETH = 0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2;
address public constant DAI = 0x6B175474E89094C44Da98b954EedeAC495271d0F;
//solhint-disable-next-line const-name-snakecase
AaveLendingPoolAddressesProvider public constant aaveAddressesProvider =
AaveLendingPoolAddressesProvider(0xB53C1a33016B2DC2fF3653530bfF1848a515c8c5);
ICollateralManager public immutable cm;
IController public immutable controller;
IERC20 public immutable collateralToken;
bytes32 public immutable collateralType;
uint256 public immutable vaultNum;
address public immutable override pool;
uint256 public lastRebalanceBlock;
uint256 public highWater;
uint256 public lowWater;
uint256 internal constant MAX_UINT_VALUE = uint256(-1);
uint256 private constant WAT = 10**16;
IERC20 private immutable aToken;
mapping(address => bool) private reservedToken;
constructor(
address _controller,
address _pool,
address _collateralToken,
address _cm,
bytes32 _collateralType
) public {
require(_controller != address(0), "Controller address is zero");
require(IController(_controller).isPool(_pool), "Not a valid pool");
controller = IController(_controller);
collateralType = _collateralType;
vaultNum = _createVault(_collateralType, _cm);
pool = _pool;
collateralToken = IERC20(_collateralToken);
cm = ICollateralManager(_cm);
address aTokenAddress = _getToken();
aToken = IERC20(aTokenAddress);
reservedToken[_collateralToken] = true;
reservedToken[aTokenAddress] = true;
reservedToken[DAI] = true;
}
modifier live() {
require(!paused || _msgSender() == address(controller), "Contract has paused");
_;
}
modifier onlyAuthorized() {
require(
_msgSender() == address(controller) || _msgSender() == pool,
"Caller is not authorized"
);
_;
}
modifier onlyController() {
require(_msgSender() == address(controller), "Caller is not the controller");
_;
}
modifier onlyPool() {
require(_msgSender() == pool, "Caller is not pool");
_;
}
function pause() external override onlyController {
_pause();
}
function unpause() external override onlyController {
_unpause();
}
/// @dev Approve Dai and collateralToken to collateral manager
function approveToken() external onlyController {
IERC20(DAI).safeApprove(address(cm), MAX_UINT_VALUE);
collateralToken.safeApprove(address(cm), MAX_UINT_VALUE);
}
/// @dev Reset Dai and collateralToken approval of collateral manager
function resetApproval() external onlyController {
IERC20(DAI).safeApprove(address(cm), 0);
collateralToken.safeApprove(address(cm), 0);
}
/**
* @dev Deposit collateral token into Maker vault.
* @param _amount Amount of collateral token
*/
function deposit(uint256 _amount) external override onlyPool {
_deposit(_amount);
}
/**
* @dev Called during withdrawal process.
* Withdraw is not allowed if pool in underwater.
* If pool is underwater, calling resurface() will bring pool above water.
* It will impact share price in pool and that's why it has to be called before withdraw.
*/
function beforeWithdraw() external override onlyPool {
if (isUnderwater()) {
_resurface();
}
}
/**
* @dev Withdraw collateral token from Maker and in order to do that strategy
* has to withdraw Dai from Aave and payback Dai in Maker.
* @param _amount Amount of collateral token to be withdrawn
*/
function withdraw(uint256 _amount) external override onlyAuthorized {
_withdraw(_amount);
}
/**
* @dev Rebalance earning and withdraw all collateral.
* Controller only function, called when migrating strategy.
*/
function withdrawAllWithRebalance() external onlyController {
_rebalanceEarned();
_withdrawAll();
}
/**
* @dev Withdraw all collateral. No rebalance earning.
* Controller only function, called when migrating strategy.
*/
function withdrawAll() external override onlyController {
_withdrawAll();
}
/**
* @dev Wrapper function for rebalanceEarned and rebalanceCollateral
* Anyone can call it except when paused.
*/
function rebalance() external override live {
_rebalanceEarned();
_rebalanceCollateral();
}
/**
* @dev Rebalance collateral and debt in Maker.
* Based on defined risk parameter either borrow more DAI from Maker or
* payback some DAI in Maker. It will try to mitigate risk of liquidation.
* Anyone can call it except when paused.
*/
function rebalanceCollateral() external live {
_rebalanceCollateral();
}
/**
* @dev Convert earned DAI from Aave to collateral token
* Also calculate interest fee on earning from Aave and transfer fee to fee collector.
* Anyone can call it except when paused.
*/
function rebalanceEarned() external live {
_rebalanceEarned();
}
/**
* @dev If pool is underwater this function will resolve underwater condition.
* If Debt in Maker is greater than aDAI balance in Aave then pool in underwater.
* Lowering DAI debt in Maker will resolve underwater condtion.
* Resolve: Calculate required collateral token to lower DAI debt. Withdraw required
* collateral token from pool and/or Maker and convert those to DAI via Uniswap.
* Finally payback debt in Maker using DAI.
*/
function resurface() external live {
_resurface();
}
/// @dev sweep given ERC20 token to vesper pool
function sweepErc20(address _fromToken) external {
uint256 amount = IERC20(_fromToken).balanceOf(address(this));
IERC20(_fromToken).safeTransfer(pool, amount);
}
function updateBalancingFactor(uint256 _highWater, uint256 _lowWater) external onlyController {
require(_lowWater != 0, "Value is zero");
require(_highWater > _lowWater, "highWater <= lowWater");
highWater = _highWater.mul(WAT);
lowWater = _lowWater.mul(WAT);
}
/**
* @notice Returns interest earned since last rebalance.
* @dev Make sure to return value in collateral token and in order to do that
* we are using Uniswap to get collateral amount for earned DAI.
*/
function interestEarned() external view returns (uint256) {
uint256 aDaiBalance = aToken.balanceOf(pool);
uint256 debt = cm.getVaultDebt(vaultNum);
if (aDaiBalance > debt) {
uint256 daiEarned = aDaiBalance.sub(debt);
IUniswapV2Router02 uniswapRouter = IUniswapV2Router02(controller.uniswapRouter());
address[] memory path = _getPath(DAI, address(collateralToken));
return uniswapRouter.getAmountsOut(daiEarned, path)[path.length - 1];
}
return 0;
}
/// @dev Returns true if strategy can be upgraded.
function isUpgradable() external view override returns (bool) {
return totalLocked() == 0;
}
function isReservedToken(address _token) external view override returns (bool) {
return reservedToken[_token];
}
/// @dev Address of Aave DAI token
function token() external view override returns (address) {
return address(aToken);
}
/// @dev Check if pool is underwater i.e. debt is greater than aDai in Aave
function isUnderwater() public view returns (bool) {
return cm.getVaultDebt(vaultNum) > aToken.balanceOf(pool);
}
/// @dev Returns total collateral locked in Maker vault
function totalLocked() public view override returns (uint256) {
return convertFrom18(cm.getVaultBalance(vaultNum));
}
/// @dev Convert from 18 decimals to token defined decimals. Default no conversion.
function convertFrom18(uint256 _amount) public pure virtual returns (uint256) {
return _amount;
}
/// @dev Create new Maker vault
function _createVault(bytes32 _collateralType, address _cm) internal returns (uint256 vaultId) {
address mcdManager = ICollateralManager(_cm).mcdManager();
ManagerLike manager = ManagerLike(mcdManager);
vaultId = manager.open(_collateralType, address(this));
manager.cdpAllow(vaultId, address(this), 1);
//hope and cpdAllow on vat for collateralManager's address
VatLike(manager.vat()).hope(_cm);
manager.cdpAllow(vaultId, _cm, 1);
//Register vault with collateral Manager
ICollateralManager(_cm).registerVault(vaultId, _collateralType);
}
function _deposit(uint256 _amount) internal {
collateralToken.safeTransferFrom(pool, address(this), _amount);
cm.depositCollateral(vaultNum, _amount);
}
function _depositDaiToAave(uint256 _amount) internal {
address _aaveLendingPool = aaveAddressesProvider.getLendingPool();
IERC20(DAI).safeApprove(_aaveLendingPool, 0);
IERC20(DAI).safeApprove(_aaveLendingPool, _amount);
AaveLendingPool(_aaveLendingPool).deposit(
DAI,
_amount,
pool,
controller.aaveReferralCode()
);
}
/**
* @dev Deposit fee into Vesper pool to get Vesper pool shares.
* Transfer fee, Vesper pool shares, to fee collector.
*/
function _handleFee(uint256 fee) internal {
if (fee != 0) {
collateralToken.safeApprove(pool, 0);
collateralToken.safeApprove(pool, fee);
IVesperPool(pool).deposit(fee);
uint256 feeInShare = IERC20(pool).balanceOf(address(this));
IERC20(pool).safeTransfer(controller.feeCollector(pool), feeInShare);
}
}
function _moveDaiToMaker(uint256 _amount) internal {
if (_amount != 0) {
_withdrawDaiFromAave(_amount);
cm.payback(vaultNum, _amount);
}
}
function _moveDaiFromMaker(uint256 _amount) internal {
cm.borrow(vaultNum, _amount);
_depositDaiToAave(_amount);
}
function _rebalanceCollateral() internal {
_deposit(collateralToken.balanceOf(pool));
(
uint256 collateralLocked,
uint256 debt,
uint256 collateralUsdRate,
uint256 collateralRatio,
uint256 minimumDebt
) = cm.getVaultInfo(vaultNum);
uint256 maxDebt = collateralLocked.mul(collateralUsdRate).div(highWater);
if (maxDebt < minimumDebt) {
// Dusting scenario. Payback all DAI
_moveDaiToMaker(debt);
} else {
if (collateralRatio > highWater) {
require(!isUnderwater(), "Pool is underwater");
_moveDaiFromMaker(maxDebt.sub(debt));
} else if (collateralRatio < lowWater) {
// Redeem DAI from Aave and deposit in maker
_moveDaiToMaker(debt.sub(maxDebt));
}
}
}
function _rebalanceEarned() internal {
require(
(block.number - lastRebalanceBlock) >= controller.rebalanceFriction(pool),
"Can not rebalance"
);
lastRebalanceBlock = block.number;
uint256 debt = cm.getVaultDebt(vaultNum);
_withdrawExcessDaiFromAave(debt);
uint256 balance = IERC20(DAI).balanceOf(address(this));
if (balance != 0) {
IUniswapV2Router02 uniswapRouter = IUniswapV2Router02(controller.uniswapRouter());
IERC20(DAI).safeApprove(address(uniswapRouter), 0);
IERC20(DAI).safeApprove(address(uniswapRouter), balance);
address[] memory path = _getPath(DAI, address(collateralToken));
// Swap and get collateralToken here.
// It is possible that amount out resolves to 0
// Which will cause the swap to fail
uint256 tokenAmountOut = uniswapRouter.getAmountsOut(balance, path)[0];
if (tokenAmountOut != 0) {
uniswapRouter.swapExactTokensForTokens(balance, 1, path, address(this), now + 30);
uint256 collateralBalance = collateralToken.balanceOf(address(this));
uint256 fee = collateralBalance.mul(controller.interestFee(pool)).div(1e18);
collateralToken.safeTransfer(pool, collateralBalance.sub(fee));
_handleFee(fee);
}
}
}
function _resurface() internal {
uint256 earnBalance = aToken.balanceOf(pool);
uint256 debt = cm.getVaultDebt(vaultNum);
require(debt > earnBalance, "Pool is above water");
uint256 shortAmount = debt.sub(earnBalance);
IUniswapV2Router02 uniswapRouter = IUniswapV2Router02(controller.uniswapRouter());
address[] memory path = _getPath(address(collateralToken), DAI);
uint256 tokenNeeded = uniswapRouter.getAmountsIn(shortAmount, path)[0];
uint256 balance = collateralToken.balanceOf(pool);
// If pool has more balance than tokenNeeded, get what needed from pool
// else get pool balance from pool and remaining from Maker vault
if (balance >= tokenNeeded) {
collateralToken.safeTransferFrom(pool, address(this), tokenNeeded);
} else {
cm.withdrawCollateral(vaultNum, tokenNeeded.sub(balance));
collateralToken.safeTransferFrom(pool, address(this), balance);
}
collateralToken.safeApprove(address(uniswapRouter), 0);
collateralToken.safeApprove(address(uniswapRouter), tokenNeeded);
uniswapRouter.swapExactTokensForTokens(tokenNeeded, 1, path, address(this), now + 30);
uint256 daiBalance = IERC20(DAI).balanceOf(address(this));
cm.payback(vaultNum, daiBalance);
// If Uniswap operation leave any collateral dust then send it to pool
uint256 _collateralbalance = collateralToken.balanceOf(address(this));
if (_collateralbalance != 0) {
collateralToken.safeTransfer(pool, _collateralbalance);
}
}
function _withdrawDaiFromAave(uint256 _amount) internal {
IERC20(address(aToken)).safeTransferFrom(pool, address(this), _amount);
address _aaveLendingPool = aaveAddressesProvider.getLendingPool();
AaveLendingPool(_aaveLendingPool).withdraw(DAI, _amount, address(this));
}
function _withdrawExcessDaiFromAave(uint256 _base) internal {
uint256 _balance = aToken.balanceOf(pool);
if (_balance > _base) {
uint256 _amount = _balance.sub(_base);
IERC20(address(aToken)).safeTransferFrom(pool, address(this), _amount);
address _aaveLendingPool = aaveAddressesProvider.getLendingPool();
AaveLendingPool(_aaveLendingPool).withdraw(DAI, _amount, address(this));
}
}
function _withdraw(uint256 _amount) internal {
(
uint256 collateralLocked,
uint256 debt,
uint256 collateralUsdRate,
uint256 collateralRatio,
uint256 minimumDebt
) = cm.whatWouldWithdrawDo(vaultNum, _amount);
if (debt != 0 && collateralRatio < lowWater) {
// If this withdraw results in Low Water scenario.
uint256 maxDebt = collateralLocked.mul(collateralUsdRate).div(highWater);
if (maxDebt < minimumDebt) {
// This is Dusting scenario
_moveDaiToMaker(debt);
} else if (maxDebt < debt) {
_moveDaiToMaker(debt.sub(maxDebt));
}
}
cm.withdrawCollateral(vaultNum, _amount);
collateralToken.safeTransfer(pool, collateralToken.balanceOf(address(this)));
}
function _withdrawAll() internal {
_moveDaiToMaker(cm.getVaultDebt(vaultNum));
require(cm.getVaultDebt(vaultNum) == 0, "Debt should be 0");
cm.withdrawCollateral(vaultNum, totalLocked());
collateralToken.safeTransfer(pool, collateralToken.balanceOf(address(this)));
}
/// @dev Get aToken address
function _getToken() internal view returns (address) {
bytes32 providerId = 0x0100000000000000000000000000000000000000000000000000000000000000;
address aaveProtocolDataProvider = aaveAddressesProvider.getAddress(providerId);
(address aTokenAddress, , ) =
AaveProtocolDataProvider(aaveProtocolDataProvider).getReserveTokensAddresses(DAI);
return aTokenAddress;
}
function _getPath(address _from, address _to) internal pure returns (address[] memory) {
address[] memory path;
if (_from == WETH || _to == WETH) {
path = new address[](2);
path[0] = _from;
path[1] = _to;
} else {
path = new address[](3);
path[0] = _from;
path[1] = WETH;
path[2] = _to;
}
return path;
}
}
// File: contracts/strategies/AaveV2MakerStrategyETH.sol
pragma solidity 0.6.12;
//solhint-disable no-empty-blocks
contract AaveV2MakerStrategyETH is AaveV2MakerStrategy {
string public constant NAME = "Strategy-AaveV2Maker-ETH";
string public constant VERSION = "2.0.2";
constructor(
address _controller,
address _pool,
address _cm
)
public
AaveV2MakerStrategy(
_controller,
_pool,
0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2,
_cm,
"ETH-A"
)
{}
} | * @dev Deposit collateral token into Maker vault. @param _amount Amount of collateral token/ | function deposit(uint256 _amount) external override onlyPool {
_deposit(_amount);
}
| 14,813,436 | [
1,
758,
1724,
4508,
2045,
287,
1147,
1368,
490,
6388,
9229,
18,
225,
389,
8949,
16811,
434,
4508,
2045,
287,
1147,
19,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
565,
445,
443,
1724,
12,
11890,
5034,
389,
8949,
13,
3903,
3849,
1338,
2864,
288,
203,
3639,
389,
323,
1724,
24899,
8949,
1769,
203,
565,
289,
203,
203,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
] |
/**
*Submitted for verification at Etherscan.io on 2020-04-27
*/
pragma solidity 0.5.7;
contract PHCMath {
function add(uint256 x, uint256 y) internal pure returns (uint256 z) {
require((z = x + y) >= x, "phc-math-add");
}
function sub(uint256 x, uint256 y) internal pure returns (uint256 z) {
require((z = x - y) <= x, "phc-math-sub");
}
function mul(uint256 x, uint256 y) internal pure returns (uint256 z) {
require(y == 0 || (z = x * y) / y == x, "phc-math-mul");
}
function min(uint256 x, uint256 y) internal pure returns (uint256 z) {
return x <= y ? x : y;
}
function max(uint256 x, uint256 y) internal pure returns (uint256 z) {
return x >= y ? x : y;
}
function imin(int x, int y) internal pure returns (int z) {
return x <= y ? x : y;
}
function imax(int x, int y) internal pure returns (int z) {
return x >= y ? x : y;
}
uint256 constant WAD = 10 ** 18;
uint256 constant RAY = 10 ** 27;
function wmul(uint256 x, uint256 y) internal pure returns (uint256 z) {
z = add(mul(x, y), WAD / 2) / WAD;
}
function rmul(uint256 x, uint256 y) internal pure returns (uint256 z) {
z = add(mul(x, y), RAY / 2) / RAY;
}
function wdiv(uint256 x, uint256 y) internal pure returns (uint256 z) {
z = add(mul(x, WAD), y / 2) / y;
}
function rdiv(uint256 x, uint256 y) internal pure returns (uint256 z) {
z = add(mul(x, RAY), y / 2) / y;
}
function rpow(uint256 x, uint256 n) internal pure returns (uint256 z) {
z = n % 2 != 0 ? x : RAY;
for (n /= 2; n != 0; n /= 2) {
x = rmul(x, x);
if (n % 2 != 0) {
z = rmul(z, x);
}
}
}
}
contract ERC20Events {
event Approval(address indexed src, address indexed guy, uint256 wad);
event Transfer(address indexed src, address indexed dst, uint256 wad);
}
contract ERC20 is ERC20Events {
function totalSupply() public view returns (uint256);
function balanceOf(address guy) public view returns (uint256);
function allowance(address src, address guy) public view returns (uint256);
function approve(address guy, uint256 wad) public returns (bool);
function transfer(address dst, uint256 wad) public returns (bool);
function transferFrom(
address src, address dst, uint256 wad
) public returns (bool);
}
contract PHCTokenBase is ERC20, PHCMath {
mapping (address => uint256) _balances;
mapping (address => mapping (address => uint256)) _approvals;
uint256 constant _supply = (2000000000) * (10**18);
constructor() public {
_balances[msg.sender] = _supply;
}
function totalSupply() public view returns (uint256) {
return _supply; //inject NONPUBLIC VAR ACCESSD BY PUBLIC FUNC
}
function balanceOf(address src) public view returns (uint256) {
return _balances[src]; //inject NONPUBLIC VAR ACCESSD BY PUBLIC FUNC
}
function allowance(address src, address guy) public view returns (uint256) {
return _approvals[src][guy]; //inject NONPUBLIC VAR ACCESSD BY PUBLIC FUNC
}
function transfer(address dst, uint256 wad) public returns (bool) {
return transferFrom(msg.sender, dst, wad);
}
function transferFrom(address src, address dst, uint256 wad)
public
returns (bool)
{
if (src != msg.sender) {
require(_approvals[src][msg.sender] >= wad, "phc-token-insufficient-approval"); //inject NONPUBLIC VAR ACCESSD BY PUBLIC FUNC
_approvals[src][msg.sender] = sub(_approvals[src][msg.sender], wad); //inject NONPUBLIC VAR ACCESSD BY PUBLIC FUNC
}
require(_balances[src] >= wad, "phc-token-insufficient-balance"); //inject NONPUBLIC VAR ACCESSD BY PUBLIC FUNC
_balances[src] = sub(_balances[src], wad); //inject NONPUBLIC VAR ACCESSD BY PUBLIC FUNC
_balances[dst] = add(_balances[dst], wad); //inject NONPUBLIC VAR ACCESSD BY PUBLIC FUNC
emit Transfer(src, dst, wad);
return true;
}
function approve(address guy, uint256 wad) public returns (bool) {
_approvals[msg.sender][guy] = wad; //inject NONPUBLIC VAR ACCESSD BY PUBLIC FUNC
emit Approval(msg.sender, guy, wad);
return true;
}
}
contract PHCNote {
event LogNote(
bytes4 indexed sig,
address indexed guy,
bytes32 indexed foo,
bytes32 indexed bar,
uint256 wad,
bytes fax
) anonymous;
modifier note {
bytes32 foo;
bytes32 bar;
assembly {
foo := calldataload(4)
bar := calldataload(36)
}
emit LogNote(msg.sig, msg.sender, foo, bar, msg.value, msg.data);
_;
}
}
contract PHCAuthority {
function canCall(
address src, address dst, bytes4 sig
) public view returns (bool);
}
contract PHCAuthEvents {
event LogSetAuthority (address indexed authority);
event LogSetOwner (address indexed owner);
}
contract PHCAuth is PHCAuthEvents {
PHCAuthority internal authority;
address internal owner;
constructor() public {
owner = msg.sender;
emit LogSetOwner(msg.sender);
}
function setOwner(address owner_)
public
auth
{
owner = owner_; //inject NONPUBLIC VAR ACCESSD BY PUBLIC FUNC
emit LogSetOwner(owner); //inject NONPUBLIC VAR ACCESSD BY PUBLIC FUNC
}
function setAuthority(PHCAuthority authority_)
public
auth
{
authority = authority_; //inject NONPUBLIC VAR ACCESSD BY PUBLIC FUNC
emit LogSetAuthority(address(authority)); //inject NONPUBLIC VAR ACCESSD BY PUBLIC FUNC
}
modifier auth {
require(isAuthorized(msg.sender, msg.sig));
_;
}
function isAuthorized(address src, bytes4 sig) internal view returns (bool) {
if (src == address(this)) {
return true;
} else if (src == owner) {
return true;
} else if (authority == PHCAuthority(0)) {
return false;
} else {
return authority.canCall(src, address(this), sig);
}
}
}
contract PHCStop is PHCNote, PHCAuth {
bool internal stopped;
modifier stoppable {
require(!stopped);
_;
}
function stop() public payable auth note {
stopped = true; //inject NONPUBLIC VAR ACCESSD BY PUBLIC FUNC
}
function start() public payable auth note {
stopped = false; //inject NONPUBLIC VAR ACCESSD BY PUBLIC FUNC
}
}
contract PHC is PHCTokenBase, PHCStop {
mapping (address => mapping (address => bool)) _trusted;
bytes32 public symbol;
uint256 public decimals = 18; // standard token precision. override to customize
constructor(bytes32 symbol_) public {
symbol = symbol_;
}
event Trust(address indexed src, address indexed guy, bool wat);
function trusted(address src, address guy) public view returns (bool) {
return _trusted[src][guy]; //inject NONPUBLIC VAR ACCESSD BY PUBLIC FUNC
}
function trust(address guy, bool wat) public stoppable {
_trusted[msg.sender][guy] = wat; //inject NONPUBLIC VAR ACCESSD BY PUBLIC FUNC
emit Trust(msg.sender, guy, wat);
}
function approve(address guy, uint256 wad) public stoppable returns (bool) {
return super.approve(guy, wad);
}
function transferFrom(address src, address dst, uint256 wad)
public
stoppable
returns (bool)
{
if (src != msg.sender && !_trusted[src][msg.sender]) { //inject NONPUBLIC VAR ACCESSD BY PUBLIC FUNC
_approvals[src][msg.sender] = sub(_approvals[src][msg.sender], wad); //inject NONPUBLIC VAR ACCESSD BY PUBLIC FUNC
}
_balances[src] = sub(_balances[src], wad); //inject NONPUBLIC VAR ACCESSD BY PUBLIC FUNC
_balances[dst] = add(_balances[dst], wad); //inject NONPUBLIC VAR ACCESSD BY PUBLIC FUNC
emit Transfer(src, dst, wad);
return true;
}
function push(address dst, uint256 wad) public {
transferFrom(msg.sender, dst, wad);
}
function pull(address src, uint256 wad) public {
transferFrom(src, msg.sender, wad);
}
function move(address src, address dst, uint256 wad) public {
transferFrom(src, dst, wad);
}
// Optional token name
bytes32 internal name = "";
function setName(bytes32 name_) public auth {
name = name_; //inject NONPUBLIC VAR ACCESSD BY PUBLIC FUNC
}
} | inject NONPUBLIC VAR ACCESSD BY PUBLIC FUNC
| stopped = false; | 12,789,990 | [
1,
22170,
18708,
14939,
8350,
13255,
40,
6953,
17187,
478,
21163,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
3639,
9627,
273,
629,
31,
202,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
] |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.