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 |
---|---|---|---|---|---|---|
// SPDX-License-Identifier: MIT
// Message module that allows sending and receiving messages using lane concept:
//
// 1) the message is sent using `send_message()` call;
// 2) every outbound message is assigned nonce;
// 3) the messages are stored in the storage;
// 4) external component (relay) delivers messages to bridged chain;
// 5) messages are processed in order (ordered by assigned nonce);
// 6) relay may send proof-of-delivery back to this chain.
//
// Once message is sent, its progress can be tracked by looking at lane contract events.
// The assigned nonce is reported using `MessageAccepted` event. When message is
// delivered to the the bridged chain, it is reported using `MessagesDelivered` event.
pragma solidity >=0.6.0 <0.7.0;
pragma experimental ABIEncoderV2;
import "@openzeppelin/contracts/access/AccessControl.sol";
import "@openzeppelin/contracts/utils/ReentrancyGuard.sol";
import "../../interfaces/IOutboundLane.sol";
import "./MessageVerifier.sol";
import "./TargetChain.sol";
import "./SourceChain.sol";
// Everything about outgoing messages sending.
contract OutboundLane is IOutboundLane, MessageVerifier, TargetChain, SourceChain, ReentrancyGuard, AccessControl {
event MessageAccepted(uint64 nonce);
event MessagesDelivered(uint64 begin, uint64 end, uint256 results);
event MessagePruned(uint64 oldest_unpruned_nonce);
event MessageFeeIncreased(uint64 nonce, uint256 fee);
event RelayerReward(address relayer, uint256 reward);
bytes32 internal constant OUTBOUND_ROLE = keccak256("OUTBOUND_ROLE");
uint64 internal constant MAX_PENDING_MESSAGES = 50;
uint64 internal constant MAX_PRUNE_MESSAGES_ATONCE = 10;
// Outbound lane nonce.
struct OutboundLaneNonce {
// Nonce of the oldest message that we haven't yet pruned. May point to not-yet-generated
// message if all sent messages are already pruned.
uint64 oldest_unpruned_nonce;
// Nonce of the latest message, received by bridged chain.
uint64 latest_received_nonce;
// Nonce of the latest message, generated by us.
uint64 latest_generated_nonce;
}
/* State */
OutboundLaneNonce public outboundLaneNonce;
uint256 public confirmationFee = 0.1 ether; // how to set confirmation_fee
// nonce => MessageData
mapping(uint64 => MessageData) public messages;
/**
* @notice Deploys the OutboundLane contract
* @param _lightClientBridge The contract address of on-chain light client
* @param _thisChainPosition The thisChainPosition of outbound lane
* @param _thisLanePosition The lanePosition of this outbound lane
* @param _bridgedChainPosition The bridgedChainPosition of outbound lane
* @param _bridgedLanePosition The lanePosition of target inbound lane
* @param _oldest_unpruned_nonce The oldest_unpruned_nonce of outbound lane
* @param _latest_received_nonce The latest_received_nonce of outbound lane
* @param _latest_generated_nonce The latest_generated_nonce of outbound lane
*/
constructor(
address _lightClientBridge,
uint32 _thisChainPosition,
uint32 _thisLanePosition,
uint32 _bridgedChainPosition,
uint32 _bridgedLanePosition,
uint64 _oldest_unpruned_nonce,
uint64 _latest_received_nonce,
uint64 _latest_generated_nonce
) public MessageVerifier(_lightClientBridge, _thisChainPosition, _thisLanePosition, _bridgedChainPosition, _bridgedLanePosition) {
outboundLaneNonce = OutboundLaneNonce(_oldest_unpruned_nonce, _latest_received_nonce, _latest_generated_nonce);
_setupRole(DEFAULT_ADMIN_ROLE, msg.sender);
}
// Send message over lane.
function send_message(address targetContract, bytes calldata encoded) external payable override nonReentrant returns (uint64) {
require(hasRole(OUTBOUND_ROLE, msg.sender), "Lane: NotAuthorized");
require(outboundLaneNonce.latest_generated_nonce - outboundLaneNonce.latest_received_nonce <= MAX_PENDING_MESSAGES, "Lane: TooManyPendingMessages");
require(outboundLaneNonce.latest_generated_nonce < uint64(-1), "Lane: Overflow");
uint64 nonce = outboundLaneNonce.latest_generated_nonce + 1;
uint256 fee = msg.value;
outboundLaneNonce.latest_generated_nonce = nonce;
MessagePayload memory messagePayload = MessagePayload({
sourceAccount: msg.sender,
targetContract: targetContract,
encoded: encoded
});
// finally, save messageData in outbound storage and emit `MessageAccepted` event
messages[nonce] = MessageData({
payload: messagePayload,
fee: fee // a lowest fee may be required and how to set it
});
// TODO:: callback `on_messages_accepted`
// message sender prune at most `MAX_PRUNE_MESSAGES_ATONCE` messages
prune_messages(MAX_PRUNE_MESSAGES_ATONCE);
commit();
emit MessageAccepted(nonce);
return nonce;
}
// 32 bytes to identify an unique message
// MessageKey encoding:
// ThisChainPosition | BridgedChainPosition | ThisLanePosition | BridgedLanePosition | Nonce
// [0..8) bytes ---- Reserved
// [8..12) bytes ---- ThisChainPosition
// [16..20) bytes ---- ThisLanePosition
// [12..16) bytes ---- BridgedChainPosition
// [20..24) bytes ---- BridgedLanePosition
// [24..32) bytes ---- Nonce, max of nonce is `uint64(-1)`
function encodeMessageKey(uint64 nonce) external view returns (uint256) {
return uint256(thisChainPosition) << 160 + uint256(bridgedChainPosition) << 128 + uint256(thisLanePosition) << 96 + uint256(bridgedLanePosition) << 64 + uint256(nonce);
}
// Pay additional fee for the message.
function increase_message_fee(uint64 nonce) external payable nonReentrant {
require(nonce > outboundLaneNonce.latest_received_nonce, "Lane: MessageIsAlreadyDelivered");
require(nonce <= outboundLaneNonce.latest_generated_nonce, "Lane: MessageIsNotYetSent");
messages[nonce].fee += msg.value;
commit();
emit MessageFeeIncreased(nonce, messages[nonce].fee);
}
// Receive messages delivery proof from bridged chain.
function receive_messages_delivery_proof(
InboundLaneData memory inboundLaneData,
bytes memory messagesProof
) public nonReentrant {
verify_lane_data_proof(hash(inboundLaneData), messagesProof);
DeliveredMessages memory confirmed_messages = confirm_delivery(inboundLaneData);
// TODO: callback `on_messages_delivered`
pay_relayers_rewards(inboundLaneData.relayers, confirmed_messages.begin, confirmed_messages.end);
commit();
}
function message_size() public view returns (uint64 size) {
size = outboundLaneNonce.latest_generated_nonce - outboundLaneNonce.latest_received_nonce;
}
// Get lane data from the storage.
function data() public view returns (OutboundLaneData memory lane_data) {
uint64 size = message_size();
if (size > 0) {
lane_data.messages = new Message[](size);
uint64 begin = outboundLaneNonce.latest_received_nonce + 1;
for (uint64 index = 0; index < size; index++) {
uint64 nonce = index + begin;
lane_data.messages[index] = Message(MessageKey(thisChainPosition, thisLanePosition, bridgedChainPosition, bridgedLanePosition, nonce), messages[nonce]);
}
}
lane_data.latest_received_nonce = outboundLaneNonce.latest_received_nonce;
}
/* Private Functions */
/// commit lane data to the `commitment` storage.
function commit() internal returns (bytes32) {
commitment = hash(data());
return commitment;
}
function extract_inbound_lane_info(InboundLaneData memory lane_data) internal pure returns (uint64 total_unrewarded_messages, uint64 last_delivered_nonce) {
total_unrewarded_messages = lane_data.last_delivered_nonce - lane_data.last_confirmed_nonce;
last_delivered_nonce = lane_data.last_delivered_nonce;
}
// Confirm messages delivery.
function confirm_delivery(InboundLaneData memory inboundLaneData) internal returns (DeliveredMessages memory confirmed_messages) {
(uint64 total_messages, uint64 latest_delivered_nonce) = extract_inbound_lane_info(inboundLaneData);
require(total_messages < 256, "Lane: InvalidNumberOfMessages");
UnrewardedRelayer[] memory relayers = inboundLaneData.relayers;
OutboundLaneNonce memory nonce = outboundLaneNonce;
require(latest_delivered_nonce > nonce.latest_received_nonce, "Lane: NoNewConfirmations");
require(latest_delivered_nonce <= nonce.latest_generated_nonce, "Lane: FailedToConfirmFutureMessages");
// that the relayer has declared correct number of messages that the proof contains (it
// is checked outside of the function). But it may happen (but only if this/bridged
// chain storage is corrupted, though) that the actual number of confirmed messages if
// larger than declared.
require(latest_delivered_nonce - nonce.latest_received_nonce <= total_messages, "Lane: TryingToConfirmMoreMessagesThanExpected");
uint256 dispatch_results = extract_dispatch_results(nonce.latest_received_nonce, latest_delivered_nonce, relayers);
uint64 prev_latest_received_nonce = nonce.latest_received_nonce;
outboundLaneNonce.latest_received_nonce = latest_delivered_nonce;
confirmed_messages = DeliveredMessages({
begin: prev_latest_received_nonce + 1,
end: latest_delivered_nonce,
dispatch_results: dispatch_results
});
// emit 'MessagesDelivered' event
emit MessagesDelivered(confirmed_messages.begin, confirmed_messages.end, confirmed_messages.dispatch_results);
}
// Extract new dispatch results from the unrewarded relayers vec.
//
// Revert if unrewarded relayers vec contains invalid data, meaning that the bridged
// chain has invalid runtime storage.
function extract_dispatch_results(uint64 prev_latest_received_nonce, uint64 latest_received_nonce, UnrewardedRelayer[] memory relayers) internal pure returns(uint256 received_dispatch_result) {
// the only caller of this functions checks that the
// prev_latest_received_nonce..=latest_received_nonce is valid, so we're ready to accept
// messages in this range => with_capacity call must succeed here or we'll be unable to receive
// confirmations at all
uint64 last_entry_end = 0;
uint64 padding = 0;
for (uint64 i = 0; i < relayers.length; i++) {
UnrewardedRelayer memory entry = relayers[i];
// unrewarded relayer entry must have at least 1 unconfirmed message
// (guaranteed by the `InboundLane::receive_message()`)
require(entry.messages.end >= entry.messages.begin, "Lane: EmptyUnrewardedRelayerEntry");
if (last_entry_end > 0) {
uint64 expected_entry_begin = last_entry_end + 1;
// every entry must confirm range of messages that follows previous entry range
// (guaranteed by the `InboundLane::receive_message()`)
require(entry.messages.begin == expected_entry_begin, "Lane: NonConsecutiveUnrewardedRelayerEntries");
}
last_entry_end = entry.messages.end;
// entry can't confirm messages larger than `inbound_lane_data.latest_received_nonce()`
// (guaranteed by the `InboundLane::receive_message()`)
// technically this will be detected in the next loop iteration as
// `InvalidNumberOfDispatchResults` but to guarantee safety of loop operations below
// this is detected now
require(entry.messages.end <= latest_received_nonce, "Lane: FailedToConfirmFutureMessages");
// now we know that the entry is valid
// => let's check if it brings new confirmations
uint64 new_messages_begin = max(entry.messages.begin, prev_latest_received_nonce + 1);
uint64 new_messages_end = min(entry.messages.end, latest_received_nonce);
if (new_messages_end < new_messages_begin) {
continue;
}
uint64 extend_begin = new_messages_begin - entry.messages.begin;
uint256 hight_bits_opp = 255 - (new_messages_end - entry.messages.begin);
// entry must have single dispatch result for every message
// (guaranteed by the `InboundLane::receive_message()`)
uint256 dispatch_results = (entry.messages.dispatch_results << hight_bits_opp) >> hight_bits_opp;
// now we know that entry brings new confirmations
// => let's extract dispatch results
received_dispatch_result |= ((dispatch_results >> extend_begin) << padding);
padding += (new_messages_end - new_messages_begin + 1 - extend_begin);
}
}
/// Prune at most `max_messages_to_prune` already received messages.
///
/// Returns number of pruned messages.
function prune_messages(uint64 max_messages_to_prune) internal returns (uint64) {
uint64 pruned_messages = 0;
bool anything_changed = false;
OutboundLaneNonce memory nonce = outboundLaneNonce;
while (pruned_messages < max_messages_to_prune &&
nonce.oldest_unpruned_nonce <= nonce.latest_received_nonce)
{
delete messages[nonce.oldest_unpruned_nonce];
anything_changed = true;
pruned_messages += 1;
nonce.oldest_unpruned_nonce += 1;
}
if (anything_changed) {
outboundLaneNonce = nonce;
emit MessagePruned(outboundLaneNonce.oldest_unpruned_nonce);
}
return pruned_messages;
}
/// Pay rewards to given relayers, optionally rewarding confirmation relayer.
function pay_relayers_rewards(UnrewardedRelayer[] memory relayers, uint64 received_start, uint64 received_end) internal {
address payable confirmation_relayer = msg.sender;
uint256 confirmation_relayer_reward = 0;
uint256 confirmation_fee = confirmationFee;
// reward every relayer except `confirmation_relayer`
for (uint256 i = 0; i < relayers.length; i++) {
UnrewardedRelayer memory entry = relayers[i];
address payable delivery_relayer = entry.relayer;
uint64 nonce_begin = max(entry.messages.begin, received_start);
uint64 nonce_end = min(entry.messages.end, received_end);
uint256 delivery_reward = 0;
uint256 confirmation_reward = 0;
for (uint64 nonce = nonce_begin; nonce <= nonce_end; nonce++) {
delivery_reward += messages[nonce].fee;
confirmation_reward += confirmation_fee;
}
if (confirmation_relayer != delivery_relayer) {
// If delivery confirmation is submitted by other relayer, let's deduct confirmation fee
// from relayer reward.
//
// If confirmation fee has been increased (or if it was the only component of message
// fee), then messages relayer may receive zero reward.
if (confirmation_reward > delivery_reward) {
confirmation_reward = delivery_reward;
}
delivery_reward = delivery_reward - confirmation_reward;
confirmation_relayer_reward = confirmation_relayer_reward + confirmation_reward;
} else {
// If delivery confirmation is submitted by this relayer, let's add confirmation fee
// from other relayers to this relayer reward.
confirmation_relayer_reward = confirmation_relayer_reward + delivery_reward;
continue;
}
pay_relayer_reward(delivery_relayer, delivery_reward);
}
// finally - pay reward to confirmation relayer
pay_relayer_reward(confirmation_relayer, confirmation_relayer_reward);
}
function pay_relayer_reward(address payable to, uint256 value) internal {
if (value > 0) {
to.transfer(value);
emit RelayerReward(to, value);
}
}
// --- Math ---
function min(uint64 x, uint64 y) internal pure returns (uint64 z) {
return x <= y ? x : y;
}
function max(uint64 x, uint64 y) internal pure returns (uint64 z) {
return x >= y ? x : y;
}
}
| Extract new dispatch results from the unrewarded relayers vec. Revert if unrewarded relayers vec contains invalid data, meaning that the bridged chain has invalid runtime storage. the only caller of this functions checks that the prev_latest_received_nonce..=latest_received_nonce is valid, so we're ready to accept messages in this range => with_capacity call must succeed here or we'll be unable to receive confirmations at all unrewarded relayer entry must have at least 1 unconfirmed message (guaranteed by the `InboundLane::receive_message()`) every entry must confirm range of messages that follows previous entry range (guaranteed by the `InboundLane::receive_message()`) | function extract_dispatch_results(uint64 prev_latest_received_nonce, uint64 latest_received_nonce, UnrewardedRelayer[] memory relayers) internal pure returns(uint256 received_dispatch_result) {
uint64 last_entry_end = 0;
uint64 padding = 0;
for (uint64 i = 0; i < relayers.length; i++) {
UnrewardedRelayer memory entry = relayers[i];
require(entry.messages.end >= entry.messages.begin, "Lane: EmptyUnrewardedRelayerEntry");
if (last_entry_end > 0) {
uint64 expected_entry_begin = last_entry_end + 1;
require(entry.messages.begin == expected_entry_begin, "Lane: NonConsecutiveUnrewardedRelayerEntries");
}
last_entry_end = entry.messages.end;
uint64 new_messages_end = min(entry.messages.end, latest_received_nonce);
if (new_messages_end < new_messages_begin) {
continue;
}
uint64 extend_begin = new_messages_begin - entry.messages.begin;
uint256 hight_bits_opp = 255 - (new_messages_end - entry.messages.begin);
padding += (new_messages_end - new_messages_begin + 1 - extend_begin);
}
}
| 7,265,325 | [
1,
4976,
394,
3435,
1686,
628,
326,
640,
266,
11804,
1279,
3907,
7062,
18,
868,
1097,
309,
640,
266,
11804,
1279,
3907,
7062,
1914,
2057,
501,
16,
12256,
716,
326,
324,
1691,
2423,
2687,
711,
2057,
3099,
2502,
18,
326,
1338,
4894,
434,
333,
4186,
4271,
716,
326,
2807,
67,
13550,
67,
15213,
67,
12824,
838,
33,
13550,
67,
15213,
67,
12824,
353,
923,
16,
1427,
732,
4565,
5695,
358,
2791,
2743,
316,
333,
1048,
516,
598,
67,
16017,
745,
1297,
12897,
2674,
578,
732,
5614,
506,
13496,
358,
6798,
6932,
1012,
622,
777,
640,
266,
11804,
1279,
1773,
1241,
1297,
1240,
622,
4520,
404,
23980,
74,
11222,
883,
261,
6891,
30164,
635,
326,
1375,
20571,
48,
8806,
2866,
18149,
67,
2150,
20338,
13,
3614,
1241,
1297,
6932,
1048,
434,
2743,
716,
13040,
2416,
1241,
1048,
261,
6891,
30164,
635,
326,
1375,
20571,
48,
8806,
2866,
18149,
67,
2150,
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,
565,
445,
2608,
67,
10739,
67,
4717,
12,
11890,
1105,
2807,
67,
13550,
67,
15213,
67,
12824,
16,
2254,
1105,
4891,
67,
15213,
67,
12824,
16,
1351,
266,
11804,
1971,
1773,
8526,
3778,
1279,
3907,
13,
2713,
16618,
1135,
12,
11890,
5034,
5079,
67,
10739,
67,
2088,
13,
288,
203,
3639,
2254,
1105,
1142,
67,
4099,
67,
409,
273,
374,
31,
203,
3639,
2254,
1105,
4992,
273,
374,
31,
203,
3639,
364,
261,
11890,
1105,
277,
273,
374,
31,
277,
411,
1279,
3907,
18,
2469,
31,
277,
27245,
288,
203,
5411,
1351,
266,
11804,
1971,
1773,
3778,
1241,
273,
1279,
3907,
63,
77,
15533,
203,
5411,
2583,
12,
4099,
18,
6833,
18,
409,
1545,
1241,
18,
6833,
18,
10086,
16,
315,
48,
8806,
30,
8953,
984,
266,
11804,
1971,
1773,
1622,
8863,
203,
5411,
309,
261,
2722,
67,
4099,
67,
409,
405,
374,
13,
288,
203,
7734,
2254,
1105,
2665,
67,
4099,
67,
10086,
273,
1142,
67,
4099,
67,
409,
397,
404,
31,
203,
7734,
2583,
12,
4099,
18,
6833,
18,
10086,
422,
2665,
67,
4099,
67,
10086,
16,
315,
48,
8806,
30,
3858,
442,
15655,
984,
266,
11804,
1971,
1773,
5400,
8863,
203,
5411,
289,
203,
5411,
1142,
67,
4099,
67,
409,
273,
1241,
18,
6833,
18,
409,
31,
203,
5411,
2254,
1105,
394,
67,
6833,
67,
409,
273,
1131,
12,
4099,
18,
6833,
18,
409,
16,
4891,
67,
15213,
67,
12824,
1769,
203,
5411,
309,
261,
2704,
67,
6833,
67,
409,
411,
394,
67,
6833,
67,
10086,
13,
288,
203,
7734,
1324,
2
] |
./full_match/1/0xEdf2818C44C0CAD3B719Bb31c52630AEe967E0B5/sources/AutoLiquidity.sol | @notice extend authorize | function extendAuthorize() internal virtual view returns (bool){
return true;
}
| 9,606,388 | [
1,
14313,
12229,
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,
0
] | [
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,
0
] | [
1,
565,
445,
2133,
18987,
1435,
2713,
5024,
1476,
1135,
261,
6430,
15329,
203,
3639,
327,
638,
31,
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,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-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-01-24
*/
// SPDX-License-Identifier: MIT
/* solium-disable security/no-send */
/**
* @authors: [@ferittuncer, @hbarcelos]
* @reviewers: [@remedcu*]
* @auditors: []
* @bounties: []
* @deployments: []
*/
/**
* @title Arbitrator
* Arbitrator abstract contract.
* When developing arbitrator contracts we need to:
* - Define the functions for dispute creation (createDispute) and appeal (appeal). Don't forget to store the arbitrated contract and the disputeID (which should be unique, may nbDisputes).
* - Define the functions for cost display (arbitrationCost and appealCost).
* - Allow giving rulings. For this a function must call arbitrable.rule(disputeID, ruling).
*/
interface IArbitrator {
enum DisputeStatus {Waiting, Appealable, Solved}
/**
* @dev To be emitted when a dispute is created.
* @param _disputeID ID of the dispute.
* @param _arbitrable The contract which created the dispute.
*/
event DisputeCreation(uint256 indexed _disputeID, IArbitrable indexed _arbitrable);
/**
* @dev To be emitted when a dispute can be appealed.
* @param _disputeID ID of the dispute.
* @param _arbitrable The contract which created the dispute.
*/
event AppealPossible(uint256 indexed _disputeID, IArbitrable indexed _arbitrable);
/**
* @dev To be emitted when the current ruling is appealed.
* @param _disputeID ID of the dispute.
* @param _arbitrable The contract which created the dispute.
*/
event AppealDecision(uint256 indexed _disputeID, IArbitrable indexed _arbitrable);
/**
* @dev Create a dispute. Must be called by the arbitrable contract.
* Must be paid at least arbitrationCost(_extraData).
* @param _choices Amount of choices the arbitrator can make in this dispute.
* @param _extraData Can be used to give additional info on the dispute to be created.
* @return disputeID ID of the dispute created.
*/
function createDispute(uint256 _choices, bytes calldata _extraData) external payable returns (uint256 disputeID);
/**
* @dev Compute the cost of arbitration. It is recommended not to increase it often, as it can be highly time and gas consuming for the arbitrated contracts to cope with fee augmentation.
* @param _extraData Can be used to give additional info on the dispute to be created.
* @return cost Amount to be paid.
*/
function arbitrationCost(bytes calldata _extraData) external view returns (uint256 cost);
/**
* @dev Appeal a ruling. Note that it has to be called before the arbitrator contract calls rule.
* @param _disputeID ID of the dispute to be appealed.
* @param _extraData Can be used to give extra info on the appeal.
*/
function appeal(uint256 _disputeID, bytes calldata _extraData) external payable;
/**
* @dev Compute the cost of appeal. It is recommended not to increase it often, as it can be higly time and gas consuming for the arbitrated contracts to cope with fee augmentation.
* @param _disputeID ID of the dispute to be appealed.
* @param _extraData Can be used to give additional info on the dispute to be created.
* @return cost Amount to be paid.
*/
function appealCost(uint256 _disputeID, bytes calldata _extraData) external view returns (uint256 cost);
/**
* @dev Compute the start and end of the dispute's current or next appeal period, if possible. If not known or appeal is impossible: should return (0, 0).
* @param _disputeID ID of the dispute.
* @return start The start of the period.
* @return end The end of the period.
*/
function appealPeriod(uint256 _disputeID) external view returns (uint256 start, uint256 end);
/**
* @dev Return the status of a dispute.
* @param _disputeID ID of the dispute to rule.
* @return status The status of the dispute.
*/
function disputeStatus(uint256 _disputeID) external view returns (DisputeStatus status);
/**
* @dev Return the current ruling of a dispute. This is useful for parties to know if they should appeal.
* @param _disputeID ID of the dispute.
* @return ruling The ruling which has been given or the one which will be given if there is no appeal.
*/
function currentRuling(uint256 _disputeID) external view returns (uint256 ruling);
}
/**
* @authors: [@ferittuncer, @hbarcelos]
* @reviewers: [@remedcu*]
* @auditors: []
* @bounties: []
* @deployments: []
*/
/**
* @title IArbitrable
* Arbitrable interface.
* When developing arbitrable contracts, we need to:
* - Define the action taken when a ruling is received by the contract.
* - Allow dispute creation. For this a function must call arbitrator.createDispute{value: _fee}(_choices,_extraData);
*/
interface IArbitrable {
/**
* @dev To be raised when a ruling is given.
* @param _arbitrator The arbitrator giving the ruling.
* @param _disputeID ID of the dispute in the Arbitrator contract.
* @param _ruling The ruling which was given.
*/
event Ruling(IArbitrator indexed _arbitrator, uint256 indexed _disputeID, uint256 _ruling);
/**
* @dev Give a ruling for a dispute. Must be called by the arbitrator.
* The purpose of this function is to ensure that the address calling it has the right to rule on the contract.
* @param _disputeID ID of the dispute in the Arbitrator contract.
* @param _ruling Ruling given by the arbitrator. Note that 0 is reserved for "Not able/wanting to make a decision".
*/
function rule(uint256 _disputeID, uint256 _ruling) external;
}
/**
* @authors: [@ferittuncer, @hbarcelos]
* @reviewers: []
* @auditors: []
* @bounties: []
* @deployments: []
*/
/** @title IEvidence
* ERC-1497: Evidence Standard
*/
interface IEvidence {
/**
* @dev To be emitted when meta-evidence is submitted.
* @param _metaEvidenceID Unique identifier of meta-evidence.
* @param _evidence A link to the meta-evidence JSON.
*/
event MetaEvidence(uint256 indexed _metaEvidenceID, string _evidence);
/**
* @dev To be raised when evidence is submitted. Should point to the resource (evidences are not to be stored on chain due to gas considerations).
* @param _arbitrator The arbitrator of the contract.
* @param _evidenceGroupID Unique identifier of the evidence group the evidence belongs to.
* @param _party The address of the party submiting the evidence. Note that 0x0 refers to evidence not submitted by any party.
* @param _evidence A URI to the evidence JSON file whose name should be its keccak256 hash followed by .json.
*/
event Evidence(
IArbitrator indexed _arbitrator,
uint256 indexed _evidenceGroupID,
address indexed _party,
string _evidence
);
/**
* @dev To be emitted when a dispute is created to link the correct meta-evidence to the disputeID.
* @param _arbitrator The arbitrator of the contract.
* @param _disputeID ID of the dispute in the Arbitrator contract.
* @param _metaEvidenceID Unique identifier of meta-evidence.
* @param _evidenceGroupID Unique identifier of the evidence group that is linked to this dispute.
*/
event Dispute(
IArbitrator indexed _arbitrator,
uint256 indexed _disputeID,
uint256 _metaEvidenceID,
uint256 _evidenceGroupID
);
}
/**
* @authors: [@ferittuncer]
* @reviewers: [@mtsalenc*, @hbarcelos*, @unknownunknown1*, @MerlinEgalite*]
* @auditors: []
* @bounties: []
* @deployments: []
*/
pragma solidity 0.7.6;
/**
* @title This serves as a standard interface for crowdfunded appeals and evidence submission, which aren't a part of the arbitration (erc-792 and erc-1497) standard yet.
This interface is used in Dispute Resolver (resolve.kleros.io).
*/
abstract contract IDisputeResolver is IArbitrable, IEvidence {
string public constant VERSION = "2.0.0"; // Can be used to distinguish between multiple deployed versions, if necessary.
/** @dev Raised when a contribution is made, inside fundAppeal function.
* @param _localDisputeID Identifier of a dispute in scope of arbitrable contract. Arbitrator ids can be translated to local ids via externalIDtoLocalID.
* @param _round The round number the contribution was made to.
* @param ruling Indicates the ruling option which got the contribution.
* @param _contributor Caller of fundAppeal function.
* @param _amount Contribution amount.
*/
event Contribution(uint256 indexed _localDisputeID, uint256 indexed _round, uint256 ruling, address indexed _contributor, uint256 _amount);
/** @dev Raised when a contributor withdraws non-zero value.
* @param _localDisputeID Identifier of a dispute in scope of arbitrable contract. Arbitrator ids can be translated to local ids via externalIDtoLocalID.
* @param _round The round number the withdrawal was made from.
* @param _ruling Indicates the ruling option which contributor gets rewards from.
* @param _contributor The beneficiary of withdrawal.
* @param _reward Total amount of withdrawal, consists of reimbursed deposits plus rewards.
*/
event Withdrawal(uint256 indexed _localDisputeID, uint256 indexed _round, uint256 _ruling, address indexed _contributor, uint256 _reward);
/** @dev To be raised when a ruling option is fully funded for appeal.
* @param _localDisputeID Identifier of a dispute in scope of arbitrable contract. Arbitrator ids can be translated to local ids via externalIDtoLocalID.
* @param _round Number of the round this ruling option was fully funded in.
* @param _ruling The ruling option which just got fully funded.
*/
event RulingFunded(uint256 indexed _localDisputeID, uint256 indexed _round, uint256 indexed _ruling);
/** @dev Maps external (arbitrator side) dispute id to local (arbitrable) dispute id.
* @param _externalDisputeID Dispute id as in arbitrator contract.
* @return localDisputeID Dispute id as in arbitrable contract.
*/
function externalIDtoLocalID(uint256 _externalDisputeID) external virtual returns (uint256 localDisputeID);
/** @dev Returns number of possible ruling options. Valid rulings are [0, return value].
* @param _localDisputeID Identifier of a dispute in scope of arbitrable contract. Arbitrator ids can be translated to local ids via externalIDtoLocalID.
* @return count The number of ruling options.
*/
function numberOfRulingOptions(uint256 _localDisputeID) external view virtual returns (uint256 count);
/** @dev Allows to submit evidence for a given dispute.
* @param _localDisputeID Identifier of a dispute in scope of arbitrable contract. Arbitrator ids can be translated to local ids via externalIDtoLocalID.
* @param _evidenceURI IPFS path to evidence, example: '/ipfs/Qmarwkf7C9RuzDEJNnarT3WZ7kem5bk8DZAzx78acJjMFH/evidence.json'
*/
function submitEvidence(uint256 _localDisputeID, string calldata _evidenceURI) external virtual;
/** @dev Manages contributions and calls appeal function of the specified arbitrator to appeal a dispute. This function lets appeals be crowdfunded.
* @param _localDisputeID Identifier of a dispute in scope of arbitrable contract. Arbitrator ids can be translated to local ids via externalIDtoLocalID.
* @param _ruling The ruling option to which the caller wants to contribute.
* @return fullyFunded True if the ruling option got fully funded as a result of this contribution.
*/
function fundAppeal(uint256 _localDisputeID, uint256 _ruling) external payable virtual returns (bool fullyFunded);
/** @dev Returns appeal multipliers.
* @return winnerStakeMultiplier Winners stake multiplier.
* @return loserStakeMultiplier Losers stake multiplier.
* @return loserAppealPeriodMultiplier Losers appeal period multiplier. The loser is given less time to fund its appeal to defend against last minute appeal funding attacks.
* @return denominator Multiplier denominator in basis points.
*/
function getMultipliers()
external
view
virtual
returns (
uint256 winnerStakeMultiplier,
uint256 loserStakeMultiplier,
uint256 loserAppealPeriodMultiplier,
uint256 denominator
);
/** @dev Allows to withdraw any reimbursable fees or rewards after the dispute gets resolved.
* @param _localDisputeID Identifier of a dispute in scope of arbitrable contract. Arbitrator ids can be translated to local ids via externalIDtoLocalID.
* @param _contributor Beneficiary of withdraw operation.
* @param _round Number of the round that caller wants to execute withdraw on.
* @param _ruling A ruling option that caller wants to execute withdraw on.
* @return sum The amount that is going to be transferred to contributor as a result of this function call.
*/
function withdrawFeesAndRewards(
uint256 _localDisputeID,
address payable _contributor,
uint256 _round,
uint256 _ruling
) external virtual returns (uint256 sum);
/** @dev Allows to withdraw any rewards or reimbursable fees after the dispute gets resolved. For multiple rulings options and for all rounds at once.
* @param _localDisputeID Identifier of a dispute in scope of arbitrable contract. Arbitrator ids can be translated to local ids via externalIDtoLocalID.
* @param _contributor Beneficiary of withdraw operation.
* @param _ruling Ruling option that caller wants to execute withdraw on.
*/
function withdrawFeesAndRewardsForAllRounds(
uint256 _localDisputeID,
address payable _contributor,
uint256 _ruling
) external virtual;
/** @dev Returns the sum of withdrawable amount.
* @param _localDisputeID Identifier of a dispute in scope of arbitrable contract. Arbitrator ids can be translated to local ids via externalIDtoLocalID.
* @param _contributor Beneficiary of withdraw operation.
* @param _ruling Ruling option that caller wants to get withdrawable amount from.
* @return sum The total amount available to withdraw.
*/
function getTotalWithdrawableAmount(
uint256 _localDisputeID,
address payable _contributor,
uint256 _ruling
) external view virtual returns (uint256 sum);
}
/**
* @authors: [@mtsalenc, @hbarcelos]
* @reviewers: [@clesaege*, @ferittuncer]
* @auditors: []
* @bounties: []
* @deployments: []
*/
/**
* @title CappedMath
* @dev Math operations with caps for under and overflow.
*/
library CappedMath {
uint constant private UINT_MAX = 2**256 - 1;
/**
* @dev Adds two unsigned integers, returns 2^256 - 1 on overflow.
*/
function addCap(uint _a, uint _b) internal pure returns (uint) {
uint c = _a + _b;
return c >= _a ? c : UINT_MAX;
}
/**
* @dev Subtracts two integers, returns 0 on underflow.
*/
function subCap(uint _a, uint _b) internal pure returns (uint) {
if (_b > _a)
return 0;
else
return _a - _b;
}
/**
* @dev Multiplies two unsigned integers, returns 2^256 - 1 on overflow.
*/
function mulCap(uint _a, uint _b) internal pure returns (uint) {
// 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;
uint c = _a * _b;
return c / _a == _b ? c : UINT_MAX;
}
}
interface IHomeArbitrationProxy {
/**
* @notice To be emitted when the Realitio contract has been notified of an arbitration request.
* @param _questionID The ID of the question.
* @param _requester The address of the arbitration requester.
* @param _maxPrevious The maximum value of the previous bond for the question.
*/
event RequestNotified(bytes32 indexed _questionID, address indexed _requester, uint256 _maxPrevious);
/**
* @notice To be emitted when arbitration request is rejected.
* @dev This can happen if the current bond for the question is higher than maxPrevious
* or if the question is already finalized.
* @param _questionID The ID of the question.
* @param _requester The address of the arbitration requester.
* @param _maxPrevious The maximum value of the current bond for the question.
* @param _reason The reason why the request was rejected.
*/
event RequestRejected(
bytes32 indexed _questionID,
address indexed _requester,
uint256 _maxPrevious,
string _reason
);
/**
* @notice To be emitted when the arbitration request acknowledgement is sent to the Foreign Chain.
* @param _questionID The ID of the question.
* @param _requester The address of the arbitration requester.
*/
event RequestAcknowledged(bytes32 indexed _questionID, address indexed _requester);
/**
* @notice To be emitted when the arbitration request is canceled.
* @param _questionID The ID of the question.
* @param _requester The address of the arbitration requester.
*/
event RequestCanceled(bytes32 indexed _questionID, address indexed _requester);
/**
* @notice To be emitted when the dispute could not be created on the Foreign Chain.
* @dev This will happen if the arbitration fee increases in between the arbitration request and acknowledgement.
* @param _questionID The ID of the question.
* @param _requester The address of the arbitration requester.
*/
event ArbitrationFailed(bytes32 indexed _questionID, address indexed _requester);
/**
* @notice To be emitted when receiving the answer from the arbitrator.
* @param _questionID The ID of the question.
* @param _answer The answer from the arbitrator.
*/
event ArbitratorAnswered(bytes32 indexed _questionID, bytes32 _answer);
/**
* @notice To be emitted when reporting the arbitrator answer to Realitio.
* @param _questionID The ID of the question.
*/
event ArbitrationFinished(bytes32 indexed _questionID);
/**
* @dev Receives the requested arbitration for a question. TRUSTED.
* @param _questionID The ID of the question.
* @param _requester The address of the arbitration requester.
* @param _maxPrevious The maximum value of the current bond for the question. The arbitration request will get rejected if the current bond is greater than _maxPrevious. If set to 0, _maxPrevious is ignored.
*/
function receiveArbitrationRequest(
bytes32 _questionID,
address _requester,
uint256 _maxPrevious
) external;
/**
* @notice Handles arbitration request after it has been notified to Realitio for a given question.
* @dev This method exists because `receiveArbitrationRequest` is called by the AMB and cannot send messages back to it.
* @param _questionID The ID of the question.
* @param _requester The address of the arbitration requester.
*/
function handleNotifiedRequest(bytes32 _questionID, address _requester) external;
/**
* @notice Handles arbitration request after it has been rejected.
* @dev This method exists because `receiveArbitrationRequest` is called by the AMB and cannot send messages back to it.
* Reasons why the request might be rejected:
* - The question does not exist
* - The question was not answered yet
* - The quesiton bond value changed while the arbitration was being requested
* - Another request was already accepted
* @param _questionID The ID of the question.
* @param _requester The address of the arbitration requester.
*/
function handleRejectedRequest(bytes32 _questionID, address _requester) external;
/**
* @notice Receives a failed attempt to request arbitration. TRUSTED.
* @dev Currently this can happen only if the arbitration cost increased.
* @param _questionID The ID of the question.
* @param _requester The address of the arbitration requester.
*/
function receiveArbitrationFailure(bytes32 _questionID, address _requester) external;
/**
* @notice Receives the answer to a specified question. TRUSTED.
* @param _questionID The ID of the question.
* @param _answer The answer from the arbitrator.
*/
function receiveArbitrationAnswer(bytes32 _questionID, bytes32 _answer) external;
}
interface IForeignArbitrationProxy is IArbitrable, IEvidence {
/**
* @notice Should be emitted when the arbitration is requested.
* @param _questionID The ID of the question with the request for arbitration.
* @param _requester The address of the arbitration requester.
* @param _maxPrevious The maximum value of the current bond for the question. The arbitration request will get rejected if the current bond is greater than _maxPrevious. If set to 0, _maxPrevious is ignored.
*/
event ArbitrationRequested(bytes32 indexed _questionID, address indexed _requester, uint256 _maxPrevious);
/**
* @notice Should be emitted when the dispute is created.
* @param _questionID The ID of the question with the request for arbitration.
* @param _requester The address of the arbitration requester.
* @param _disputeID The ID of the dispute.
*/
event ArbitrationCreated(bytes32 indexed _questionID, address indexed _requester, uint256 indexed _disputeID);
/**
* @notice Should be emitted when the arbitration is canceled by the Home Chain.
* @param _questionID The ID of the question with the request for arbitration.
* @param _requester The address of the arbitration requester.
*/
event ArbitrationCanceled(bytes32 indexed _questionID, address indexed _requester);
/**
* @notice Should be emitted when the dispute could not be created.
* @dev This will happen if there is an increase in the arbitration fees
* between the time the arbitration is made and the time it is acknowledged.
* @param _questionID The ID of the question with the request for arbitration.
* @param _requester The address of the arbitration requester.
*/
event ArbitrationFailed(bytes32 indexed _questionID, address indexed _requester);
/**
* @notice Requests arbitration for the given question.
* @param _questionID The ID of the question.
* @param _maxPrevious The maximum value of the current bond for the question. The arbitration request will get rejected if the current bond is greater than _maxPrevious. If set to 0, _maxPrevious is ignored.
*/
function requestArbitration(bytes32 _questionID, uint256 _maxPrevious) external payable;
/**
* @notice Receives the acknowledgement of the arbitration request for the given question and requester. TRUSTED.
* @param _questionID The ID of the question.
* @param _requester The address of the arbitration requester.
*/
function receiveArbitrationAcknowledgement(bytes32 _questionID, address _requester) external;
/**
* @notice Receives the cancelation of the arbitration request for the given question and requester. TRUSTED.
* @param _questionID The ID of the question.
* @param _requester The address of the arbitration requester.
*/
function receiveArbitrationCancelation(bytes32 _questionID, address _requester) external;
/**
* @notice Cancels the arbitration in case the dispute could not be created.
* @param _questionID The ID of the question.
* @param _requester The address of the arbitration requester.
*/
function handleFailedDisputeCreation(bytes32 _questionID, address _requester) external;
/**
* @notice Gets the fee to create a dispute.
* @param _questionID the ID of the question.
* @return The fee to create a dispute.
*/
function getDisputeFee(bytes32 _questionID) external view returns (uint256);
}
/**
* @authors: [@hbarcelos*, @unknownunknown1]
* @reviewers: [@MerlinEgalite*, @shalzz, @jaybuidl, @ferittuncer, @fnanni-0]
* @auditors: []
* @bounties: []
* @deployments: []
*/
/**
* @title Arbitration proxy for Realitio on Ethereum side (A.K.A. the Foreign Chain).
* This version of the contract has an appeal support.
* @dev This contract is meant to be deployed to the Ethereum chains where Kleros is deployed.
*/
contract RealitioForeignArbitrationProxyWithAppeals is IForeignArbitrationProxy, IDisputeResolver {
using CappedMath for uint256;
/* Constants */
uint256 public constant NUMBER_OF_CHOICES_FOR_ARBITRATOR = type(uint256).max; // The number of choices for the arbitrator.
uint256 public constant MULTIPLIER_DIVISOR = 10000; // Divisor parameter for multipliers.
uint256 public constant META_EVIDENCE_ID = 0; // The ID of the MetaEvidence for disputes.
/* Storage */
enum Status {
None,
Requested,
Created,
Ruled,
Failed
}
struct ArbitrationRequest {
Status status; // Status of the arbitration.
uint248 deposit; // The deposit paid by the requester at the time of the arbitration.
uint256 disputeID; // The ID of the dispute in arbitrator contract.
uint256 answer; // The answer given by the arbitrator shifted by -1 to match Realitio format.
Round[] rounds; // Tracks each appeal round of a dispute.
}
struct DisputeDetails {
uint256 arbitrationID; // The ID of the arbitration.
address requester; // The address of the requester who managed to go through with the arbitration request.
}
// Round struct stores the contributions made to particular answers.
struct Round {
mapping(uint256 => uint256) paidFees; // Tracks the fees paid in this round in the form paidFees[answer].
mapping(uint256 => bool) hasPaid; // True if the fees for this particular answer have been fully paid in the form hasPaid[answer].
mapping(address => mapping(uint256 => uint256)) contributions; // Maps contributors to their contributions for each answer in the form contributions[address][answer].
uint256 feeRewards; // Sum of reimbursable appeal fees available to the parties that made contributions to the answer that ultimately wins a dispute.
uint256[] fundedAnswers; // Stores the answer choices that are fully funded.
}
IArbitrator public immutable arbitrator; // The address of the arbitrator. TRUSTED.
bytes public arbitratorExtraData; // The extra data used to raise a dispute in the arbitrator.
IAMB public immutable amb; // ArbitraryMessageBridge contract address. TRUSTED.
address public immutable homeProxy; // Address of the counter-party proxy on the Home Chain. TRUSTED.
bytes32 public immutable homeChainId; // The chain ID where the home proxy is deployed.
string public termsOfService; // The path for the Terms of Service for Kleros as an arbitrator for Realitio.
// Multipliers are in basis points.
uint256 public immutable winnerMultiplier; // Multiplier for calculating the appeal fee that must be paid for the answer that was chosen by the arbitrator in the previous round.
uint256 public immutable loserMultiplier; // Multiplier for calculating the appeal fee that must be paid for the answer that the arbitrator didn't rule for in the previous round.
uint256 public immutable loserAppealPeriodMultiplier; // Multiplier for calculating the duration of the appeal period for the loser, in basis points.
mapping(uint256 => mapping(address => ArbitrationRequest)) public arbitrationRequests; // Maps arbitration ID to its data. arbitrationRequests[uint(questionID)][requester].
mapping(uint256 => DisputeDetails) public disputeIDToDisputeDetails; // Maps external dispute ids to local arbitration ID and requester who was able to complete the arbitration request.
mapping(uint256 => bool) public arbitrationIDToDisputeExists; // Whether a dispute has already been created for the given arbitration ID or not.
mapping(uint256 => address) public arbitrationIDToRequester; // Maps arbitration ID to the requester who was able to complete the arbitration request.
/* Modifiers */
modifier onlyHomeProxy() {
require(msg.sender == address(amb), "Only AMB allowed");
require(amb.messageSourceChainId() == homeChainId, "Only home chain allowed");
require(amb.messageSender() == homeProxy, "Only home proxy allowed");
_;
}
/**
* @notice Creates an arbitration proxy on the foreign chain.
* @param _amb ArbitraryMessageBridge contract address.
* @param _homeProxy The address of the proxy.
* @param _homeChainId The chain ID where the home proxy is deployed.
* @param _arbitrator Arbitrator contract address.
* @param _arbitratorExtraData The extra data used to raise a dispute in the arbitrator.
* @param _metaEvidence The URI of the meta evidence file.
* @param _termsOfService The path for the Terms of Service for Kleros as an arbitrator for Realitio.
* @param _winnerMultiplier Multiplier for calculating the appeal cost of the winning answer.
* @param _loserMultiplier Multiplier for calculation the appeal cost of the losing answer.
* @param _loserAppealPeriodMultiplier Multiplier for calculating the appeal period for the losing answer.
*/
constructor(
IAMB _amb,
address _homeProxy,
bytes32 _homeChainId,
IArbitrator _arbitrator,
bytes memory _arbitratorExtraData,
string memory _metaEvidence,
string memory _termsOfService,
uint256 _winnerMultiplier,
uint256 _loserMultiplier,
uint256 _loserAppealPeriodMultiplier
) {
amb = _amb;
homeProxy = _homeProxy;
homeChainId = _homeChainId;
arbitrator = _arbitrator;
arbitratorExtraData = _arbitratorExtraData;
termsOfService = _termsOfService;
winnerMultiplier = _winnerMultiplier;
loserMultiplier = _loserMultiplier;
loserAppealPeriodMultiplier = _loserAppealPeriodMultiplier;
emit MetaEvidence(META_EVIDENCE_ID, _metaEvidence);
}
/* External and public */
// ************************ //
// * Realitio logic * //
// ************************ //
/**
* @notice Requests arbitration for the given question and contested answer.
* @param _questionID The ID of the question.
* @param _maxPrevious The maximum value of the current bond for the question. The arbitration request will get rejected if the current bond is greater than _maxPrevious. If set to 0, _maxPrevious is ignored.
*/
function requestArbitration(bytes32 _questionID, uint256 _maxPrevious) external payable override {
require(!arbitrationIDToDisputeExists[uint256(_questionID)], "Dispute already created");
ArbitrationRequest storage arbitration = arbitrationRequests[uint256(_questionID)][msg.sender];
require(arbitration.status == Status.None, "Arbitration already requested");
uint256 arbitrationCost = arbitrator.arbitrationCost(arbitratorExtraData);
require(msg.value >= arbitrationCost, "Deposit value too low");
arbitration.status = Status.Requested;
arbitration.deposit = uint248(msg.value);
bytes4 methodSelector = IHomeArbitrationProxy(0).receiveArbitrationRequest.selector;
bytes memory data = abi.encodeWithSelector(methodSelector, _questionID, msg.sender, _maxPrevious);
amb.requireToPassMessage(homeProxy, data, amb.maxGasPerTx());
emit ArbitrationRequested(_questionID, msg.sender, _maxPrevious);
}
/**
* @notice Receives the acknowledgement of the arbitration request for the given question and requester. TRUSTED.
* @param _questionID The ID of the question.
* @param _requester The requester.
*/
function receiveArbitrationAcknowledgement(bytes32 _questionID, address _requester)
external
override
onlyHomeProxy
{
uint256 arbitrationID = uint256(_questionID);
ArbitrationRequest storage arbitration = arbitrationRequests[arbitrationID][_requester];
require(arbitration.status == Status.Requested, "Invalid arbitration status");
uint256 arbitrationCost = arbitrator.arbitrationCost(arbitratorExtraData);
if (arbitration.deposit >= arbitrationCost) {
try
arbitrator.createDispute{value: arbitrationCost}(NUMBER_OF_CHOICES_FOR_ARBITRATOR, arbitratorExtraData)
returns (uint256 disputeID) {
DisputeDetails storage disputeDetails = disputeIDToDisputeDetails[disputeID];
disputeDetails.arbitrationID = arbitrationID;
disputeDetails.requester = _requester;
arbitrationIDToDisputeExists[arbitrationID] = true;
arbitrationIDToRequester[arbitrationID] = _requester;
// At this point, arbitration.deposit is guaranteed to be greater than or equal to the arbitration cost.
uint256 remainder = arbitration.deposit - arbitrationCost;
arbitration.status = Status.Created;
arbitration.deposit = 0;
arbitration.disputeID = disputeID;
arbitration.rounds.push();
if (remainder > 0) {
payable(_requester).send(remainder);
}
emit ArbitrationCreated(_questionID, _requester, disputeID);
emit Dispute(arbitrator, disputeID, META_EVIDENCE_ID, arbitrationID);
} catch {
arbitration.status = Status.Failed;
emit ArbitrationFailed(_questionID, _requester);
}
} else {
arbitration.status = Status.Failed;
emit ArbitrationFailed(_questionID, _requester);
}
}
/**
* @notice Receives the cancelation of the arbitration request for the given question and requester. TRUSTED.
* @param _questionID The ID of the question.
* @param _requester The requester.
*/
function receiveArbitrationCancelation(bytes32 _questionID, address _requester) external override onlyHomeProxy {
uint256 arbitrationID = uint256(_questionID);
ArbitrationRequest storage arbitration = arbitrationRequests[arbitrationID][_requester];
require(arbitration.status == Status.Requested, "Invalid arbitration status");
uint256 deposit = arbitration.deposit;
delete arbitrationRequests[arbitrationID][_requester];
payable(_requester).send(deposit);
emit ArbitrationCanceled(_questionID, _requester);
}
/**
* @notice Cancels the arbitration in case the dispute could not be created.
* @param _questionID The ID of the question.
* @param _requester The address of the arbitration requester.
*/
function handleFailedDisputeCreation(bytes32 _questionID, address _requester) external override {
uint256 arbitrationID = uint256(_questionID);
ArbitrationRequest storage arbitration = arbitrationRequests[arbitrationID][_requester];
require(arbitration.status == Status.Failed, "Invalid arbitration status");
uint256 deposit = arbitration.deposit;
delete arbitrationRequests[arbitrationID][_requester];
payable(_requester).send(deposit);
bytes4 methodSelector = IHomeArbitrationProxy(0).receiveArbitrationFailure.selector;
bytes memory data = abi.encodeWithSelector(methodSelector, _questionID, _requester);
amb.requireToPassMessage(homeProxy, data, amb.maxGasPerTx());
emit ArbitrationCanceled(_questionID, _requester);
}
// ********************************* //
// * Appeals and arbitration * //
// ********************************* //
/**
* @notice Takes up to the total amount required to fund an answer. Reimburses the rest. Creates an appeal if at least two answers are funded.
* @param _arbitrationID The ID of the arbitration, which is questionID cast into uint256.
* @param _answer One of the possible rulings the arbitrator can give that the funder considers to be the correct answer to the question.
* Note that the answer has Kleros denomination, meaning that it has '+1' offset compared to Realitio format.
* Also note that '0' answer can be funded.
* @return Whether the answer was fully funded or not.
*/
function fundAppeal(uint256 _arbitrationID, uint256 _answer) external payable override returns (bool) {
ArbitrationRequest storage arbitration = arbitrationRequests[_arbitrationID][
arbitrationIDToRequester[_arbitrationID]
];
require(arbitration.status == Status.Created, "No dispute to appeal.");
uint256 disputeID = arbitration.disputeID;
(uint256 appealPeriodStart, uint256 appealPeriodEnd) = arbitrator.appealPeriod(disputeID);
require(block.timestamp >= appealPeriodStart && block.timestamp < appealPeriodEnd, "Appeal period is over.");
uint256 multiplier;
{
uint256 winner = arbitrator.currentRuling(disputeID);
if (winner == _answer) {
multiplier = winnerMultiplier;
} else {
require(
block.timestamp - appealPeriodStart <
(appealPeriodEnd - appealPeriodStart).mulCap(loserAppealPeriodMultiplier) / MULTIPLIER_DIVISOR,
"Appeal period is over for loser"
);
multiplier = loserMultiplier;
}
}
uint256 lastRoundID = arbitration.rounds.length - 1;
Round storage round = arbitration.rounds[lastRoundID];
require(!round.hasPaid[_answer], "Appeal fee is already paid.");
uint256 appealCost = arbitrator.appealCost(disputeID, arbitratorExtraData);
uint256 totalCost = appealCost.addCap((appealCost.mulCap(multiplier)) / MULTIPLIER_DIVISOR);
// Take up to the amount necessary to fund the current round at the current costs.
uint256 contribution = totalCost.subCap(round.paidFees[_answer]) > msg.value
? msg.value
: totalCost.subCap(round.paidFees[_answer]);
emit Contribution(_arbitrationID, lastRoundID, _answer, msg.sender, contribution);
round.contributions[msg.sender][_answer] += contribution;
round.paidFees[_answer] += contribution;
if (round.paidFees[_answer] >= totalCost) {
round.feeRewards += round.paidFees[_answer];
round.fundedAnswers.push(_answer);
round.hasPaid[_answer] = true;
emit RulingFunded(_arbitrationID, lastRoundID, _answer);
}
if (round.fundedAnswers.length > 1) {
// At least two sides are fully funded.
arbitration.rounds.push();
round.feeRewards = round.feeRewards.subCap(appealCost);
arbitrator.appeal{value: appealCost}(disputeID, arbitratorExtraData);
}
if (msg.value.subCap(contribution) > 0) msg.sender.send(msg.value.subCap(contribution)); // Sending extra value back to contributor. It is the user's responsibility to accept ETH.
return round.hasPaid[_answer];
}
/**
* @notice Sends the fee stake rewards and reimbursements proportional to the contributions made to the winner of a dispute. Reimburses contributions if there is no winner.
* @param _arbitrationID The ID of the arbitration.
* @param _beneficiary The address to send reward to.
* @param _round The round from which to withdraw.
* @param _answer The answer to query the reward from.
* @return reward The withdrawn amount.
*/
function withdrawFeesAndRewards(
uint256 _arbitrationID,
address payable _beneficiary,
uint256 _round,
uint256 _answer
) public override returns (uint256 reward) {
address requester = arbitrationIDToRequester[_arbitrationID];
ArbitrationRequest storage arbitration = arbitrationRequests[_arbitrationID][requester];
Round storage round = arbitration.rounds[_round];
require(arbitration.status == Status.Ruled, "Dispute not resolved");
// Allow to reimburse if funding of the round was unsuccessful.
if (!round.hasPaid[_answer]) {
reward = round.contributions[_beneficiary][_answer];
} else if (!round.hasPaid[arbitration.answer]) {
// Reimburse unspent fees proportionally if the ultimate winner didn't pay appeal fees fully.
// Note that if only one side is funded it will become a winner and this part of the condition won't be reached.
reward = round.fundedAnswers.length > 1
? (round.contributions[_beneficiary][_answer] * round.feeRewards) /
(round.paidFees[round.fundedAnswers[0]] + round.paidFees[round.fundedAnswers[1]])
: 0;
} else if (arbitration.answer == _answer) {
uint256 paidFees = round.paidFees[_answer];
// Reward the winner.
reward = paidFees > 0 ? (round.contributions[_beneficiary][_answer] * round.feeRewards) / paidFees : 0;
}
if (reward != 0) {
round.contributions[_beneficiary][_answer] = 0;
_beneficiary.send(reward); // It is the user's responsibility to accept ETH.
emit Withdrawal(_arbitrationID, _round, _answer, _beneficiary, reward);
}
}
/**
* @notice Allows to withdraw any rewards or reimbursable fees for all rounds at once.
* @dev This function is O(n) where n is the total number of rounds. Arbitration cost of subsequent rounds is `A(n) = 2A(n-1) + 1`.
* So because of this exponential growth of costs, you can assume n is less than 10 at all times.
* @param _arbitrationID The ID of the arbitration.
* @param _beneficiary The address that made contributions.
* @param _contributedTo Answer that received contributions from contributor.
*/
function withdrawFeesAndRewardsForAllRounds(
uint256 _arbitrationID,
address payable _beneficiary,
uint256 _contributedTo
) external override {
address requester = arbitrationIDToRequester[_arbitrationID];
ArbitrationRequest storage arbitration = arbitrationRequests[_arbitrationID][requester];
uint256 numberOfRounds = arbitration.rounds.length;
for (uint256 roundNumber = 0; roundNumber < numberOfRounds; roundNumber++) {
withdrawFeesAndRewards(_arbitrationID, _beneficiary, roundNumber, _contributedTo);
}
}
/**
* @notice Allows to submit evidence for a particular question.
* @param _arbitrationID The ID of the arbitration related to the question.
* @param _evidenceURI Link to evidence.
*/
function submitEvidence(uint256 _arbitrationID, string calldata _evidenceURI) external override {
emit Evidence(arbitrator, _arbitrationID, msg.sender, _evidenceURI);
}
/**
* @notice Rules a specified dispute. Can only be called by the arbitrator.
* @dev Accounts for the situation where the winner loses a case due to paying less appeal fees than expected.
* @param _disputeID The ID of the dispute in the ERC792 arbitrator.
* @param _ruling The ruling given by the arbitrator.
*/
function rule(uint256 _disputeID, uint256 _ruling) external override {
DisputeDetails storage disputeDetails = disputeIDToDisputeDetails[_disputeID];
uint256 arbitrationID = disputeDetails.arbitrationID;
address requester = disputeDetails.requester;
ArbitrationRequest storage arbitration = arbitrationRequests[arbitrationID][requester];
require(msg.sender == address(arbitrator), "Only arbitrator allowed");
require(arbitration.status == Status.Created, "Invalid arbitration status");
uint256 finalRuling = _ruling;
// If one side paid its fees, the ruling is in its favor. Note that if the other side had also paid, an appeal would have been created.
Round storage round = arbitration.rounds[arbitration.rounds.length - 1];
if (round.fundedAnswers.length == 1) finalRuling = round.fundedAnswers[0];
arbitration.answer = finalRuling;
arbitration.status = Status.Ruled;
bytes4 methodSelector = IHomeArbitrationProxy(0).receiveArbitrationAnswer.selector;
// Realitio ruling is shifted by 1 compared to Kleros.
// Note that this shifting won't work in the latest compiler versions (0.8.0 and further), because of the innate underflow checks.
bytes memory data = abi.encodeWithSelector(methodSelector, bytes32(arbitrationID), bytes32(finalRuling - 1));
amb.requireToPassMessage(homeProxy, data, amb.maxGasPerTx());
emit Ruling(arbitrator, _disputeID, finalRuling);
}
/* External Views */
/**
* @notice Returns stake multipliers.
* @return winner Winners stake multiplier.
* @return loser Losers stake multiplier.
* @return loserAppealPeriod Multiplier for calculating an appeal period duration for the losing side.
* @return divisor Multiplier divisor.
*/
function getMultipliers()
external
view
override
returns (
uint256 winner,
uint256 loser,
uint256 loserAppealPeriod,
uint256 divisor
)
{
return (winnerMultiplier, loserMultiplier, loserAppealPeriodMultiplier, MULTIPLIER_DIVISOR);
}
/**
* @notice Returns number of possible ruling options. Valid rulings are [0, return value].
* @return count The number of ruling options.
*/
function numberOfRulingOptions(
uint256 /* _arbitrationID */
) external pure override returns (uint256) {
return NUMBER_OF_CHOICES_FOR_ARBITRATOR;
}
/**
* @notice Gets the fee to create a dispute.
* @return The fee to create a dispute.
*/
function getDisputeFee(
bytes32 /* _questionID */
) external view override returns (uint256) {
return arbitrator.arbitrationCost(arbitratorExtraData);
}
/**
* @notice Gets the number of rounds of the specific question.
* @param _arbitrationID The ID of the arbitration related to the question.
* @return The number of rounds.
*/
function getNumberOfRounds(uint256 _arbitrationID) external view returns (uint256) {
address requester = arbitrationIDToRequester[_arbitrationID];
ArbitrationRequest storage arbitration = arbitrationRequests[_arbitrationID][requester];
return arbitration.rounds.length;
}
/**
* @notice Gets the information of a round of a question.
* @param _arbitrationID The ID of the arbitration.
* @param _round The round to query.
* @return paidFees The amount of fees paid for each fully funded answer.
* @return feeRewards The amount of fees that will be used as rewards.
* @return fundedAnswers IDs of fully funded answers.
*/
function getRoundInfo(uint256 _arbitrationID, uint256 _round)
external
view
returns (
uint256[] memory paidFees,
uint256 feeRewards,
uint256[] memory fundedAnswers
)
{
address requester = arbitrationIDToRequester[_arbitrationID];
ArbitrationRequest storage arbitration = arbitrationRequests[_arbitrationID][requester];
Round storage round = arbitration.rounds[_round];
fundedAnswers = round.fundedAnswers;
paidFees = new uint256[](round.fundedAnswers.length);
for (uint256 i = 0; i < round.fundedAnswers.length; i++) {
paidFees[i] = round.paidFees[round.fundedAnswers[i]];
}
feeRewards = round.feeRewards;
}
/**
* @notice Gets the information of a round of a question for a specific answer choice.
* @param _arbitrationID The ID of the arbitration.
* @param _round The round to query.
* @param _answer The answer choice to get funding status for.
* @return raised The amount paid for this answer.
* @return fullyFunded Whether the answer is fully funded or not.
*/
function getFundingStatus(
uint256 _arbitrationID,
uint256 _round,
uint256 _answer
) external view returns (uint256 raised, bool fullyFunded) {
address requester = arbitrationIDToRequester[_arbitrationID];
ArbitrationRequest storage arbitration = arbitrationRequests[_arbitrationID][requester];
Round storage round = arbitration.rounds[_round];
raised = round.paidFees[_answer];
fullyFunded = round.hasPaid[_answer];
}
/**
* @notice Gets contributions to the answers that are fully funded.
* @param _arbitrationID The ID of the arbitration.
* @param _round The round to query.
* @param _contributor The address whose contributions to query.
* @return fundedAnswers IDs of the answers that are fully funded.
* @return contributions The amount contributed to each funded answer by the contributor.
*/
function getContributionsToSuccessfulFundings(
uint256 _arbitrationID,
uint256 _round,
address _contributor
) external view returns (uint256[] memory fundedAnswers, uint256[] memory contributions) {
address requester = arbitrationIDToRequester[_arbitrationID];
ArbitrationRequest storage arbitration = arbitrationRequests[_arbitrationID][requester];
Round storage round = arbitration.rounds[_round];
fundedAnswers = round.fundedAnswers;
contributions = new uint256[](round.fundedAnswers.length);
for (uint256 i = 0; i < contributions.length; i++) {
contributions[i] = round.contributions[_contributor][fundedAnswers[i]];
}
}
/**
* @notice Returns the sum of withdrawable amount.
* @dev This function is O(n) where n is the total number of rounds.
* @dev This could exceed the gas limit, therefore this function should be used only as a utility and not be relied upon by other contracts.
* @param _arbitrationID The ID of the arbitration.
* @param _beneficiary The contributor for which to query.
* @param _contributedTo Answer that received contributions from contributor.
* @return sum The total amount available to withdraw.
*/
function getTotalWithdrawableAmount(
uint256 _arbitrationID,
address payable _beneficiary,
uint256 _contributedTo
) external view override returns (uint256 sum) {
address requester = arbitrationIDToRequester[_arbitrationID];
ArbitrationRequest storage arbitration = arbitrationRequests[_arbitrationID][requester];
if (arbitration.status < Status.Ruled) return sum;
uint256 finalAnswer = arbitration.answer;
uint256 noOfRounds = arbitration.rounds.length;
for (uint256 roundNumber = 0; roundNumber < noOfRounds; roundNumber++) {
Round storage round = arbitration.rounds[roundNumber];
if (!round.hasPaid[_contributedTo]) {
// Allow to reimburse if funding was unsuccessful for this answer option.
sum += round.contributions[_beneficiary][_contributedTo];
} else if (!round.hasPaid[finalAnswer]) {
// Reimburse unspent fees proportionally if the ultimate winner didn't pay appeal fees fully.
// Note that if only one side is funded it will become a winner and this part of the condition won't be reached.
sum += round.fundedAnswers.length > 1
? (round.contributions[_beneficiary][_contributedTo] * round.feeRewards) /
(round.paidFees[round.fundedAnswers[0]] + round.paidFees[round.fundedAnswers[1]])
: 0;
} else if (finalAnswer == _contributedTo) {
uint256 paidFees = round.paidFees[_contributedTo];
// Reward the winner.
sum += paidFees > 0
? (round.contributions[_beneficiary][_contributedTo] * round.feeRewards) / paidFees
: 0;
}
}
}
/**
* @notice Casts question ID into uint256 thus returning the related arbitration ID.
* @param _questionID The ID of the question.
* @return The ID of the arbitration.
*/
function questionIDToArbitrationID(bytes32 _questionID) external pure returns (uint256) {
return uint256(_questionID);
}
/**
* @notice Maps external (arbitrator side) dispute id to local (arbitrable) dispute id.
* @param _externalDisputeID Dispute id as in arbitrator side.
* @return localDisputeID Dispute id as in arbitrable contract.
*/
function externalIDtoLocalID(uint256 _externalDisputeID) external view override returns (uint256) {
return disputeIDToDisputeDetails[_externalDisputeID].arbitrationID;
}
}
interface IAMB {
function requireToPassMessage(
address _contract,
bytes memory _data,
uint256 _gas
) external returns (bytes32);
function maxGasPerTx() external view returns (uint256);
function messageSender() external view returns (address);
function messageSourceChainId() external view returns (bytes32);
function messageId() external view returns (bytes32);
} | Round struct stores the contributions made to particular answers. | struct Round {
}
| 15,337,194 | [
1,
11066,
1958,
9064,
326,
13608,
6170,
7165,
358,
6826,
12415,
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
] | [
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,
565,
1958,
11370,
288,
203,
565,
289,
203,
203,
203,
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,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-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.7;
/**
* IERC20
*/
interface IERC20 {
function totalSupply() external view returns (uint256);
function balanceOf(address account) external view returns (uint256);
function transfer(address recipient, uint256 amount) external returns (bool);
function allowance(address owner, address spender) external view returns (uint256);
function approve(address spender, uint256 amount) external returns (bool);
function transferFrom(
address sender,
address recipient,
uint256 amount
) external returns (bool);
event Transfer(address indexed from, address indexed to, uint256 value);
event Approval(address indexed owner, address indexed spender, uint256 value);
}
/**
* ReentrancyGuard
*/
abstract contract ReentrancyGuard {
uint256 private constant _NOT_ENTERED = 1;
uint256 private constant _ENTERED = 2;
uint256 private _status;
constructor() {
_status = _NOT_ENTERED;
}
modifier nonReentrant() {
require(_status != _ENTERED, "ReentrancyGuard: reentrant call");
_status = _ENTERED;
_;
_status = _NOT_ENTERED;
}
}
/**
* SafeMath
* Wrappers over Solidity's arithmetic operations with added overflow
* checks.
*/
library SafeMath {
function add(uint256 a, uint256 b) internal pure returns (uint256) {
uint256 c = a + b;
require(c >= a, "SafeMath: addition overflow");
return c;
}
function sub(uint256 a, uint256 b) internal pure returns (uint256) {
return sub(a, b, "SafeMath: subtraction overflow");
}
function sub(
uint256 a,
uint256 b,
string memory errorMessage
) internal pure returns (uint256) {
require(b <= a, errorMessage);
uint256 c = a - b;
return c;
}
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;
}
function div(uint256 a, uint256 b) internal pure returns (uint256) {
return div(a, b, "SafeMath: division by zero");
}
function div(
uint256 a,
uint256 b,
string memory errorMessage
) internal pure returns (uint256) {
require(b > 0, errorMessage);
uint256 c = a / b;
return c;
}
function mod(uint256 a, uint256 b) internal pure returns (uint256) {
return mod(a, b, "SafeMath: modulo by zero");
}
function mod(
uint256 a,
uint256 b,
string memory errorMessage
) internal pure returns (uint256) {
require(b != 0, errorMessage);
return a % b;
}
}
/**
* Context
*/
abstract contract Context {
function _msgSender() internal view virtual returns (address) {
return msg.sender;
}
function _msgData() internal view virtual returns (bytes memory) {
this;
return msg.data;
}
}
/**
* Address
* Collection of functions related to the address type
*/
library Address {
function isContract(address account) internal view returns (bool) {
bytes32 codehash;
bytes32 accountHash = 0xc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470;
// solhint-disable-next-line no-inline-assembly
assembly {
codehash := extcodehash(account)
}
return (codehash != accountHash && codehash != 0x0);
}
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");
}
function functionCall(address target, bytes memory data) internal returns (bytes memory) {
return functionCall(target, data, "Address: low-level call failed");
}
function functionCall(
address target,
bytes memory data,
string memory errorMessage
) internal returns (bytes memory) {
return _functionCallWithValue(target, data, 0, errorMessage);
}
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");
}
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 {
if (returndata.length > 0) {
// solhint-disable-next-line no-inline-assembly
assembly {
let returndata_size := mload(returndata)
revert(add(32, returndata), returndata_size)
}
} else {
revert(errorMessage);
}
}
}
}
/**
* Ownable
* 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.
*/
contract Ownable is Context {
address private _owner;
address private _previousOwner;
uint256 private _lockTime;
event OwnershipTransferred(address indexed previousOwner, address indexed newOwner);
constructor() {
address msgSender = _msgSender();
_owner = msgSender;
emit OwnershipTransferred(address(0), msgSender);
}
function owner() public view returns (address) {
return _owner;
}
modifier onlyOwner() {
require(_owner == _msgSender(), "Ownable: caller is not the owner");
_;
}
function renounceOwnership() public virtual onlyOwner {
emit OwnershipTransferred(_owner, address(0));
_owner = address(0);
}
function transferOwnership(address newOwner) public virtual onlyOwner {
require(newOwner != address(0), "Ownable: new owner is the zero address");
emit OwnershipTransferred(_owner, newOwner);
_owner = newOwner;
}
function geUnlockTime() public view returns (uint256) {
return _lockTime;
}
function lock(uint256 time) public virtual onlyOwner {
_previousOwner = _owner;
_owner = address(0);
_lockTime = block.timestamp + time;
emit OwnershipTransferred(_owner, address(0));
}
function unlock() public virtual {
require(_previousOwner == msg.sender, "You don't have permission to unlock");
require(block.timestamp > _lockTime, "Contract is locked until 7 days");
emit OwnershipTransferred(_owner, _previousOwner);
_owner = _previousOwner;
}
}
/**
* IUniswapV2Factory
*/
interface IUniswapV2Factory {
event PairCreated(address indexed token0, address indexed token1, address pair, uint256);
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(uint256) external view returns (address pair);
function allPairsLength() external view returns (uint256);
function createPair(address tokenA, address tokenB) external returns (address pair);
function setFeeTo(address) external;
function setFeeToSetter(address) external;
}
/**
* IUniswapV2Pair
*/
interface IUniswapV2Pair {
event Approval(address indexed owner, address indexed spender, uint256 value);
event Transfer(address indexed from, address indexed to, uint256 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 (uint256);
function balanceOf(address owner) external view returns (uint256);
function allowance(address owner, address spender) external view returns (uint256);
function approve(address spender, uint256 value) external returns (bool);
function transfer(address to, uint256 value) external returns (bool);
function transferFrom(
address from,
address to,
uint256 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 (uint256);
function permit(
address owner,
address spender,
uint256 value,
uint256 deadline,
uint8 v,
bytes32 r,
bytes32 s
) external;
event Mint(address indexed sender, uint256 amount0, uint256 amount1);
event Burn(address indexed sender, uint256 amount0, uint256 amount1, address indexed to);
event Swap(address indexed sender, uint256 amount0In, uint256 amount1In, uint256 amount0Out, uint256 amount1Out, address indexed to);
event Sync(uint112 reserve0, uint112 reserve1);
function MINIMUM_LIQUIDITY() external pure returns (uint256);
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 (uint256);
function price1CumulativeLast() external view returns (uint256);
function kLast() external view returns (uint256);
function mint(address to) external returns (uint256 liquidity);
function burn(address to) external returns (uint256 amount0, uint256 amount1);
function swap(
uint256 amount0Out,
uint256 amount1Out,
address to,
bytes calldata data
) external;
function skim(address to) external;
function sync() external;
function initialize(address, address) external;
}
/**
* IUniswapV2Router01
*/
interface IUniswapV2Router01 {
function factory() external pure returns (address);
function WETH() external pure returns (address);
function addLiquidity(
address tokenA,
address tokenB,
uint256 amountADesired,
uint256 amountBDesired,
uint256 amountAMin,
uint256 amountBMin,
address to,
uint256 deadline
)
external
returns (
uint256 amountA,
uint256 amountB,
uint256 liquidity
);
function addLiquidityETH(
address token,
uint256 amountTokenDesired,
uint256 amountTokenMin,
uint256 amountETHMin,
address to,
uint256 deadline
)
external
payable
returns (
uint256 amountToken,
uint256 amountETH,
uint256 liquidity
);
function removeLiquidity(
address tokenA,
address tokenB,
uint256 liquidity,
uint256 amountAMin,
uint256 amountBMin,
address to,
uint256 deadline
) external returns (uint256 amountA, uint256 amountB);
function removeLiquidityETH(
address token,
uint256 liquidity,
uint256 amountTokenMin,
uint256 amountETHMin,
address to,
uint256 deadline
) external returns (uint256 amountToken, uint256 amountETH);
function removeLiquidityWithPermit(
address tokenA,
address tokenB,
uint256 liquidity,
uint256 amountAMin,
uint256 amountBMin,
address to,
uint256 deadline,
bool approveMax,
uint8 v,
bytes32 r,
bytes32 s
) external returns (uint256 amountA, uint256 amountB);
function removeLiquidityETHWithPermit(
address token,
uint256 liquidity,
uint256 amountTokenMin,
uint256 amountETHMin,
address to,
uint256 deadline,
bool approveMax,
uint8 v,
bytes32 r,
bytes32 s
) external returns (uint256 amountToken, uint256 amountETH);
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);
}
/**
* IUniswapV2Router02
*/
interface IUniswapV2Router02 is IUniswapV2Router01 {
function removeLiquidityETHSupportingFeeOnTransferTokens(
address token,
uint256 liquidity,
uint256 amountTokenMin,
uint256 amountETHMin,
address to,
uint256 deadline
) external returns (uint256 amountETH);
function removeLiquidityETHWithPermitSupportingFeeOnTransferTokens(
address token,
uint256 liquidity,
uint256 amountTokenMin,
uint256 amountETHMin,
address to,
uint256 deadline,
bool approveMax,
uint8 v,
bytes32 r,
bytes32 s
) external returns (uint256 amountETH);
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;
}
library EnumerableSet {
struct Set {
bytes32[] _values;
mapping (bytes32 => uint256) _indexes;
}
function _add(Set storage set, bytes32 value) private returns (bool) {
if (!_contains(set, value)) {
set._values.push(value);
set._indexes[value] = set._values.length;
return true;
} else {
return false;
}
}
function _remove(Set storage set, bytes32 value) private returns (bool) {
uint256 valueIndex = set._indexes[value];
if (valueIndex != 0) {
uint256 toDeleteIndex = valueIndex - 1;
uint256 lastIndex = set._values.length - 1;
bytes32 lastvalue = set._values[lastIndex];
set._values[toDeleteIndex] = lastvalue;
set._indexes[lastvalue] = valueIndex;
set._values.pop();
delete set._indexes[value];
return true;
} else {
return false;
}
}
function _contains(Set storage set, bytes32 value) private view returns (bool) {
return set._indexes[value] != 0;
}
function _length(Set storage set) private view returns (uint256) {
return set._values.length;
}
function _at(Set storage set, uint256 index) private view returns (bytes32) {
require(set._values.length > index, "EnumerableSet: index out of bounds");
return set._values[index];
}
// Bytes32Set
struct Bytes32Set {
Set _inner;
}
function add(Bytes32Set storage set, bytes32 value) internal returns (bool) {
return _add(set._inner, value);
}
function remove(Bytes32Set storage set, bytes32 value) internal returns (bool) {
return _remove(set._inner, value);
}
function contains(Bytes32Set storage set, bytes32 value) internal view returns (bool) {
return _contains(set._inner, value);
}
function length(Bytes32Set storage set) internal view returns (uint256) {
return _length(set._inner);
}
function at(Bytes32Set storage set, uint256 index) internal view returns (bytes32) {
return _at(set._inner, index);
}
// AddressSet
struct AddressSet {
Set _inner;
}
function add(AddressSet storage set, address value) internal returns (bool) {
return _add(set._inner, bytes32(uint256(uint160(value))));
}
function remove(AddressSet storage set, address value) internal returns (bool) {
return _remove(set._inner, bytes32(uint256(uint160(value))));
}
function contains(AddressSet storage set, address value) internal view returns (bool) {
return _contains(set._inner, bytes32(uint256(uint160(value))));
}
function length(AddressSet storage set) internal view returns (uint256) {
return _length(set._inner);
}
function at(AddressSet storage set, uint256 index) internal view returns (address) {
return address(uint160(uint256(_at(set._inner, index))));
}
// UintSet
struct UintSet {
Set _inner;
}
function add(UintSet storage set, uint256 value) internal returns (bool) {
return _add(set._inner, bytes32(value));
}
function remove(UintSet storage set, uint256 value) internal returns (bool) {
return _remove(set._inner, bytes32(value));
}
function contains(UintSet storage set, uint256 value) internal view returns (bool) {
return _contains(set._inner, bytes32(value));
}
function length(UintSet storage set) internal view returns (uint256) {
return _length(set._inner);
}
function at(UintSet storage set, uint256 index) internal view returns (uint256) {
return uint256(_at(set._inner, index));
}
}
/**
* COIN
*/
contract Bullwinkle is Context, IERC20, Ownable, ReentrancyGuard {
// Import our libraries
using SafeMath for uint256;
using Address for address;
using EnumerableSet for EnumerableSet.AddressSet;
// Mapping and addressSets
mapping(address => uint256) private _rOwned;
mapping(address => uint256) private _tOwned;
mapping(address => mapping(address => uint256)) private _allowances;
mapping(address => bool) private _isExcludedFromFee;
mapping(address => bool) private _isExcludedFromReward;
EnumerableSet.AddressSet private _excludedFromSellLock;
mapping (address => uint256) private _sellLock;
EnumerableSet.AddressSet private _excludedFromBuyLock;
mapping (address => uint256) private _buyLock;
address[] private _excludedFromReward;
// Addresses
address Marketing_ADDRESS = 0xCE303fb3D4Ca4304De67E5753f130D905550d4A0;
address private constant ROUTER_ADDRESS = 0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D;
// Token name
string private _name = "Bullwinkle";
string private _symbol = "BWK";
// Decimals
uint8 private _decimals = 9;
// Max supply
// @note: 10**9 means a 1 with 9 zeroes.
// @note: 1 * 10**9 is 1 with 9 decimals.
uint256 private constant MAX = ~uint256(0);
uint256 private _tTotal = 1500000000000000000 * 10**9;
uint256 private _rTotal = (MAX - (MAX % _tTotal));
// Max Wallet in tokens
uint256 public _maxWalletSize = 9000000000000000 * 10**9;
// Buy tax in percentage
/*
Marketing fee includes development fees(2%) charity fees (2%) and marketing fees (6%) itself
MarketingFeeBuy = developmentFeeBuy + charityFeeBuy + marketingFeeBuy
10 = 2 + 2 + 6
*/
uint256 private MarketingFeeBuy = 10;
uint256 private liquidityFeeBuy = 2;
uint256 private rewardFeeBuy = 2;
uint256 private totalFeeBuy = 14;
// Sell tax in percentage
/*
Marketing fee includes development fees(2%) charity fees (2%) and marketing fees (17%) itself
MarketingFeeSell = developmentFee + charityFee + marketingFeeSell
21 = 2 + 2 + 17
*/
uint256 private MarketingFeeSell = 21 ;
uint256 private liquidityFeeSell = 2;
uint256 private rewardFeeSell = 2 ;
uint256 private totalFeeSell = 25;
uint256 private _tHODLrRewardsTotal;
uint256 private _rewardFee;
uint256 private _previousRewardFee;
uint256 private _MarketingFee;
uint256 private _previousMarketingFee;
uint256 private _liquidityFee;
uint256 private _previousLiquidityFee;
IUniswapV2Router02 public immutable uniswapV2Router;
address public immutable uniswapV2Pair;
event TransferBurn(address indexed from, address indexed burnAddress, uint256 value);
/* Constructor */
constructor() {
_rOwned[_msgSender()] = _rTotal;
// Setup Router
IUniswapV2Router02 _uniswapV2Router = IUniswapV2Router02(ROUTER_ADDRESS);
uniswapV2Pair = IUniswapV2Factory(_uniswapV2Router.factory()).createPair(address(this), _uniswapV2Router.WETH());
uniswapV2Router = _uniswapV2Router;
// Exclude
_isExcludedFromFee[owner()] = true;
_isExcludedFromFee[address(this)] = true;
_isExcludedFromReward[address(this)] = true;
_isExcludedFromFee[Marketing_ADDRESS] = true;
_isExcludedFromReward[Marketing_ADDRESS] = true;
emit Transfer(address(0), _msgSender(), _tTotal);
}
bool public tradingEnabled;
/**
* All of our read functions
*/
// Get token name
function name() public view returns (string memory) {
return _name;
}
// Get token ticker
function symbol() public view returns (string memory) {
return _symbol;
}
// Get decimals
function decimals() public view returns (uint8) {
return _decimals;
}
// Get total supply
function totalSupply() public view override returns (uint256) {
return _tTotal;
}
// Get balance of address
function balanceOf(address account) public view override returns (uint256) {
if (_isExcludedFromReward[account]) return _tOwned[account];
return tokenFromReflection(_rOwned[account]);
}
// Get allowance
function allowance(address owner, address spender) public view override returns (uint256) {
return _allowances[owner][spender];
}
// Get all the buy fees
function getAllBuyFees() public view returns (uint256 _liquidityFeeBuy, uint256 _MarketingFeeBuy, uint256 _rewardFeeBuy){
return (liquidityFeeBuy, MarketingFeeBuy, rewardFeeBuy);
}
// Get all the sell fees
function getAllSellFees() public view returns (uint256 _liquidityFeeSell, uint256 _MarketingFeeSell, uint256 _rewardFeeSell){
return (liquidityFeeSell, MarketingFeeSell, rewardFeeSell);
}
// Get HODLr rewards
function totalHODLrRewards() public view returns (uint256) {
return _tHODLrRewardsTotal;
}
// Get reflections from token
function reflectionFromToken(uint256 tAmount, bool deductTransferFee) public view returns (uint256) {
require(tAmount <= _tTotal, "Amount must be less than supply");
if (!deductTransferFee) {
(uint256 rAmount, , , , , , ) = _getValues(tAmount);
return rAmount;
} else {
(, uint256 rTransferAmount, , , , , ) = _getValues(tAmount);
return rTransferAmount;
}
}
// Get tokens from reflection
function tokenFromReflection(uint256 rAmount) public view returns (uint256) {
require(rAmount <= _rTotal, "Amount must be less than total reflections");
uint256 currentRate = _getRate();
return rAmount.div(currentRate);
}
// Get if an address is excluded from rewards
function isExcludedFromReward(address account) public view returns (bool) {
return _isExcludedFromReward[account];
}
// Get if an address is excluded from fees
function isExcludedFromFee(address account) public view returns (bool) {
return _isExcludedFromFee[account];
}
/**
* All of our write functions
*/
// Withdraw from account
function withdraw() external onlyOwner nonReentrant {
uint256 balance = IERC20(address(this)).balanceOf(address(this));
IERC20(address(this)).transfer(msg.sender, balance);
payable(msg.sender).transfer(address(this).balance);
}
// Transfer tokens
function transfer(address recipient, uint256 amount) public override returns (bool) {
_transfer(_msgSender(), recipient, amount);
return true;
}
// Approve and address
function approve(address spender, uint256 amount) public override returns (bool) {
_approve(_msgSender(), spender, amount);
return true;
}
// TransferFrom
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;
}
// Increase allowance to spend
function increaseAllowance(address spender, uint256 addedValue) public virtual returns (bool) {
_approve(_msgSender(), spender, _allowances[_msgSender()][spender].add(addedValue));
return true;
}
// Decrease allowance to spend
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;
}
// Deliver
function deliver(uint256 tAmount) public {
address sender = _msgSender();
require(!_isExcludedFromReward[sender], "Excluded addresses cannot call this function");
(uint256 rAmount, , , , , , ) = _getValues(tAmount);
_rOwned[sender] = _rOwned[sender].sub(rAmount);
_rTotal = _rTotal.sub(rAmount);
_tHODLrRewardsTotal = _tHODLrRewardsTotal.add(tAmount);
}
// Exclude and address from rewards
function excludeFromReward(address account) public onlyOwner {
require(!_isExcludedFromReward[account], "Account is already excluded");
if (_rOwned[account] > 0) {
_tOwned[account] = tokenFromReflection(_rOwned[account]);
}
_isExcludedFromReward[account] = true;
_excludedFromReward.push(account);
}
// Include an address from rewards
function includeInReward(address account) external onlyOwner {
require(_isExcludedFromReward[account], "Account is already excluded");
for (uint256 i = 0; i < _excludedFromReward.length; i++) {
if (_excludedFromReward[i] == account) {
_excludedFromReward[i] = _excludedFromReward[_excludedFromReward.length - 1];
_tOwned[account] = 0;
_isExcludedFromReward[account] = false;
_excludedFromReward.pop();
break;
}
}
}
// Exclude an address from the fees
function excludeFromFee(address account) public onlyOwner {
_isExcludedFromFee[account] = true;
}
// Include an address in the fees
function includeInFee(address account) public onlyOwner {
_isExcludedFromFee[account] = false;
}
// Sets all the buy taxes, cant be higher than the max
function setBuyFeesInPercentage(uint256 _liquidityFeeBuy, uint256 _MarketingFeeBuy, uint256 _rewardFeeBuy) external onlyOwner {
liquidityFeeBuy = _liquidityFeeBuy;
MarketingFeeBuy = _MarketingFeeBuy;
rewardFeeBuy = _rewardFeeBuy;
totalFeeBuy = _liquidityFeeBuy.add(_MarketingFeeBuy).add(_rewardFeeBuy);
}
// Sets all the sell taxes, needs to be lower than the max
function setSellFeesInPercentage(uint256 _liquidityFeeSell, uint256 _MarketingFeeSell, uint256 _rewardFeeSell) external onlyOwner {
liquidityFeeSell = _liquidityFeeSell;
MarketingFeeSell = _MarketingFeeSell;
rewardFeeSell = _rewardFeeSell;
totalFeeSell = _liquidityFeeSell.add(_MarketingFeeSell).add(_rewardFeeSell);
}
// Set the max sell tx percentage
// TODO: Make this work with decimals or tokens instead of percentage
// Set the max buy tx percentage
// TODO: Make this work with decimals or tokens instead of percentage
// Set the max wallet percentage
// TODO: Make this work with decimals or tokens instead of percentage
function setMaxWalletPercent(uint256 maxWalletPercent) external onlyOwner {
_maxWalletSize = _tTotal.mul(maxWalletPercent).div(10**2);
}
// Enable trading
// @note: Can't disable trading after enabling
function openTheGates() public onlyOwner{
tradingEnabled = true;
}
/**
* Private functions
*/
receive() external payable {}
function _HODLrFee(uint256 rHODLrFee, uint256 tHODLrFee) private {
_rTotal = _rTotal.sub(rHODLrFee);
_tHODLrRewardsTotal = _tHODLrRewardsTotal.add(tHODLrFee);
}
// TODO: We should find a contract using seperate taxes (liquidity/reflection and burn) for
// buying and selling.
function _getValues(uint256 tAmount)
private
view
returns (
uint256,
uint256,
uint256,
uint256,
uint256,
uint256,
uint256
)
{
(uint256 tTransferAmount, uint256 tHODLrFee, uint256 tMarketing, uint256 tLiquidity) = _getTValues(tAmount);
(uint256 rAmount, uint256 rTransferAmount, uint256 rHODLrFee) = _getRValues(tAmount, tHODLrFee, tMarketing, _getRate(), tLiquidity);
return (rAmount, rTransferAmount, rHODLrFee, tTransferAmount, tHODLrFee, tMarketing, tLiquidity);
}
function _getTValues(uint256 tAmount)
private
view
returns (
uint256,
uint256,
uint256,
uint256
)
{
uint256 tHODLrFee = calculateRewardFee(tAmount);
uint256 tMarketing = calculateMarketingFee(tAmount);
uint256 tLiquidity = calculateLiquidityFee(tAmount);
uint256 tTransferAmount = tAmount.sub(tHODLrFee).sub(tMarketing).sub(tLiquidity);
return (tTransferAmount, tHODLrFee, tMarketing, tLiquidity );
}
function _getRValues(
uint256 tAmount,
uint256 tHODLrFee,
uint256 tMarketing,
uint256 currentRate,
uint256 tLiquidity
)
private
pure
returns (
uint256,
uint256,
uint256
)
{
uint256 rAmount = tAmount.mul(currentRate);
uint256 rHODLrFee = tHODLrFee.mul(currentRate);
uint256 rMarketing = tMarketing.mul(currentRate);
uint256 rLiquidity = tLiquidity.mul(currentRate);
uint256 rTransferAmount = rAmount.sub(rHODLrFee).sub(rMarketing).sub(rLiquidity);
return (rAmount, rTransferAmount, rHODLrFee);
}
function _getRate() private view returns (uint256) {
(uint256 rSupply, uint256 tSupply) = _getCurrentSupply();
return rSupply.div(tSupply);
}
function _getCurrentSupply() private view returns (uint256, uint256) {
uint256 rSupply = _rTotal;
uint256 tSupply = _tTotal;
for (uint256 i = 0; i < _excludedFromReward.length; i++) {
if (_rOwned[_excludedFromReward[i]] > rSupply || _tOwned[_excludedFromReward[i]] > tSupply) return (_rTotal, _tTotal);
rSupply = rSupply.sub(_rOwned[_excludedFromReward[i]]);
tSupply = tSupply.sub(_tOwned[_excludedFromReward[i]]);
}
if (rSupply < _rTotal.div(_tTotal)) return (_rTotal, _tTotal);
return (rSupply, tSupply);
}
function _takeLiquidity(uint256 tLiquidity) private {
uint256 currentRate = _getRate();
uint256 rLiquidity = tLiquidity.mul(currentRate);
_rOwned[address(this)] = _rOwned[address(this)].add(rLiquidity);
if(_isExcludedFromFee[address(this)])
_tOwned[address(this)] = _tOwned[address(this)].add(tLiquidity);
}
function calculateRewardFee(uint256 _amount) private view returns (uint256) {
return _amount.mul(_rewardFee).div(10**2);
}
function calculateMarketingFee(uint256 _amount) private view returns (uint256) {
return _amount.mul(_MarketingFee).div(10**2);
}
function calculateLiquidityFee(uint256 _amount) private view returns (uint256) {
return _amount.mul(_liquidityFee).div(
10**2
);
}
function removeAllFee() private {
if (_rewardFee == 0 && _MarketingFee == 0 && _liquidityFee == 0 ) return;
_previousRewardFee = _rewardFee;
_previousMarketingFee = _MarketingFee;
_previousLiquidityFee = _liquidityFee;
_liquidityFee = 0;
_rewardFee = 0;
_MarketingFee = 0;
}
function restoreAllFee() private {
_rewardFee = _previousRewardFee;
_MarketingFee = _previousMarketingFee;
_liquidityFee = _previousLiquidityFee;
}
// Set the correct fees for buying or selling
function setCorrectFees(bool isSell) private {
if (isSell){
// Set the fees to selling
_liquidityFee = liquidityFeeSell;
_rewardFee = rewardFeeSell;
_MarketingFee = MarketingFeeSell ;
} else {
// Set the fees to buying
_liquidityFee = liquidityFeeBuy;
_rewardFee = rewardFeeBuy;
_MarketingFee = MarketingFeeBuy;
}
}
function _approve(
address owner,
address spender,
uint256 amount
) private {
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);
}
// Main transfer function where we do our checks
function _transfer(
address from,
address to,
uint256 amount
) private {
require(from != address(0), "ERC20: transfer from the zero address");
require(to != address(0), "ERC20: transfer to the zero address");
require(amount > 0, "Transfer amount must be greater than zero");
// Check if we are buying or selling
bool isSell=to==uniswapV2Pair|| to == ROUTER_ADDRESS;
// Check if trading is enabled
if (from != owner() && to != owner()) {
require(tradingEnabled,"trading not yet enabled");
}
// Check max wallet
if (from != owner() && to != owner()) {
if (to != uniswapV2Pair && to != Marketing_ADDRESS) {
require(balanceOf(to) + amount <= _maxWalletSize, "Transfer amount exceeds the bag size.");
}
}
// Set the buy or sell fees
setCorrectFees(isSell);
// Check if we need to use fees
bool takeFee = true;
if (_isExcludedFromFee[from] || _isExcludedFromFee[to]) {
takeFee = false;
}
_tokenTransfer(from, to, amount, takeFee);
}
/**
* All the transfer functions
*/
function _tokenTransfer(
address sender,
address recipient,
uint256 amount,
bool takeFee
) private {
if (!takeFee) removeAllFee();
if (_isExcludedFromReward[sender] && !_isExcludedFromReward[recipient]) {
_transferFromExcluded(sender, recipient, amount);
} else if (!_isExcludedFromReward[sender] && _isExcludedFromReward[recipient]) {
_transferToExcluded(sender, recipient, amount);
} else if (!_isExcludedFromReward[sender] && !_isExcludedFromReward[recipient]) {
_transferStandard(sender, recipient, amount);
} else if (_isExcludedFromReward[sender] && _isExcludedFromReward[recipient]) {
_transferBothExcluded(sender, recipient, amount);
} else {
_transferStandard(sender, recipient, amount);
}
if (!takeFee) restoreAllFee();
}
function _transferMarketing(uint256 tMarketing) private {
uint256 currentRate = _getRate();
uint256 rMarketing = tMarketing.mul(currentRate);
_rOwned[Marketing_ADDRESS] = _rOwned[Marketing_ADDRESS].add(rMarketing);
if (_isExcludedFromReward[Marketing_ADDRESS]) _tOwned[Marketing_ADDRESS] = _tOwned[Marketing_ADDRESS].add(tMarketing);
}
function _transferFromExcluded(
address sender,
address recipient,
uint256 tAmount
) private {
(uint256 rAmount, uint256 rTransferAmount, uint256 rHODLrFee, uint256 tTransferAmount, uint256 tHODLrFee, uint256 tMarketing, uint256 tLiquidity) =
_getValues(tAmount);
_tOwned[sender] = _tOwned[sender].sub(tAmount);
_rOwned[sender] = _rOwned[sender].sub(rAmount);
_rOwned[recipient] = _rOwned[recipient].add(rTransferAmount);
_takeLiquidity(tLiquidity);
_transferMarketing(tMarketing);
_HODLrFee(rHODLrFee, tHODLrFee);
emit TransferBurn(sender, Marketing_ADDRESS, tMarketing);
emit Transfer(sender, recipient, tTransferAmount);
}
function _transferToExcluded(
address sender,
address recipient,
uint256 tAmount
) private {
(uint256 rAmount, uint256 rTransferAmount, uint256 rHODLrFee, uint256 tTransferAmount, uint256 tHODLrFee, uint256 tMarketing, uint256 tLiquidity) =
_getValues(tAmount);
_rOwned[sender] = _rOwned[sender].sub(rAmount);
_tOwned[recipient] = _tOwned[recipient].add(tTransferAmount);
_rOwned[recipient] = _rOwned[recipient].add(rTransferAmount);
_takeLiquidity(tLiquidity);
_transferMarketing(tMarketing);
_HODLrFee(rHODLrFee, tHODLrFee);
emit TransferBurn(sender, Marketing_ADDRESS, tMarketing);
emit Transfer(sender, recipient, tTransferAmount);
}
function _transferStandard(
address sender,
address recipient,
uint256 tAmount
) private {
(uint256 rAmount, uint256 rTransferAmount, uint256 rHODLrFee, uint256 tTransferAmount, uint256 tHODLrFee, uint256 tMarketing, uint256 tLiquidity) =
_getValues(tAmount);
_rOwned[sender] = _rOwned[sender].sub(rAmount);
_rOwned[recipient] = _rOwned[recipient].add(rTransferAmount);
_transferMarketing(tMarketing);
_HODLrFee(rHODLrFee, tHODLrFee);
_takeLiquidity(tLiquidity);
emit TransferBurn(sender, Marketing_ADDRESS, tMarketing) ;
emit Transfer(sender, recipient, tTransferAmount);
}
function _transferBothExcluded(
address sender,
address recipient,
uint256 tAmount
) private {
(uint256 rAmount, uint256 rTransferAmount, uint256 rHODLrFee, uint256 tTransferAmount, uint256 tHODLrFee, uint256 tMarketing, uint256 tLiquidity) =
_getValues(tAmount);
_tOwned[sender] = _tOwned[sender].sub(tAmount);
_rOwned[sender] = _rOwned[sender].sub(rAmount);
_tOwned[recipient] = _tOwned[recipient].add(tTransferAmount);
_rOwned[recipient] = _rOwned[recipient].add(rTransferAmount);
_transferMarketing(tMarketing);
_HODLrFee(rHODLrFee, tHODLrFee);
_takeLiquidity(tLiquidity);
emit TransferBurn(sender, Marketing_ADDRESS, tMarketing);
emit Transfer(sender, recipient, tTransferAmount);
}
} | Sets all the sell taxes, needs to be lower than the max | function setSellFeesInPercentage(uint256 _liquidityFeeSell, uint256 _MarketingFeeSell, uint256 _rewardFeeSell) external onlyOwner {
liquidityFeeSell = _liquidityFeeSell;
MarketingFeeSell = _MarketingFeeSell;
rewardFeeSell = _rewardFeeSell;
totalFeeSell = _liquidityFeeSell.add(_MarketingFeeSell).add(_rewardFeeSell);
}
| 5,437,861 | [
1,
2785,
777,
326,
357,
80,
5320,
281,
16,
4260,
358,
506,
2612,
2353,
326,
943,
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,
13928,
1165,
2954,
281,
382,
16397,
12,
11890,
5034,
389,
549,
372,
24237,
14667,
55,
1165,
16,
2254,
5034,
389,
3882,
21747,
14667,
55,
1165,
16,
2254,
5034,
389,
266,
2913,
14667,
55,
1165,
13,
3903,
1338,
5541,
288,
203,
3639,
4501,
372,
24237,
14667,
55,
1165,
273,
389,
549,
372,
24237,
14667,
55,
1165,
31,
203,
3639,
6622,
21747,
14667,
55,
1165,
273,
389,
3882,
21747,
14667,
55,
1165,
31,
203,
3639,
19890,
14667,
55,
1165,
273,
389,
266,
2913,
14667,
55,
1165,
31,
203,
3639,
2078,
14667,
55,
1165,
273,
389,
549,
372,
24237,
14667,
55,
1165,
18,
1289,
24899,
3882,
21747,
14667,
55,
1165,
2934,
1289,
24899,
266,
2913,
14667,
55,
1165,
1769,
203,
565,
289,
203,
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
] |
./full_match/1/0x8fEf29604D16987E2a0C8AE1DFbA47495fF4888a/sources/contracts/WrappedStakedWar.sol | * @notice Update the reward state for all reward tokens/ | function updateAllRewardState() external whenNotPaused {
_updateAllRewardStates();
}
| 4,816,776 | [
1,
1891,
326,
19890,
919,
364,
777,
19890,
2430,
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
] | [
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,
445,
1089,
1595,
17631,
1060,
1119,
1435,
3903,
1347,
1248,
28590,
288,
203,
3639,
389,
2725,
1595,
17631,
1060,
7629,
5621,
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,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-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/0xdE000042830A211533662637fE66760f1F2cD717/sources/contracts/LUKSOMigrationDepositContract.sol | The DestinationDepositData struct stores the data of a deposit made to a destination | struct DestinationDepositData {
address senderAddress;
uint96 amount;
uint256 depositId;
}
| 3,865,414 | [
1,
1986,
10691,
758,
1724,
751,
1958,
9064,
326,
501,
434,
279,
443,
1724,
7165,
358,
279,
2929,
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
] | [
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,
0,
0,
0
] | [
1,
565,
1958,
10691,
758,
1724,
751,
288,
203,
3639,
1758,
5793,
1887,
31,
203,
3639,
2254,
10525,
3844,
31,
203,
3639,
2254,
5034,
443,
1724,
548,
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
] |
./full_match/4/0x393b92CC3E75DEe06F470BCA2f2a40e7F44F01b6/sources/CMC-Token/CMC-Token/DividendPayingToken.sol | @notice Withdraws the ether distributed to the sender. @dev It emits a `DividendWithdrawn` event if the amount of withdrawn ether is greater than 0. | function _withdrawDividendOfUser(address payable user)
internal
returns (uint256)
{
uint256 _withdrawableDividend = withdrawableDividendOf(user);
if (_withdrawableDividend > 0) {
withdrawnDividends[user] = withdrawnDividends[user].add(
_withdrawableDividend
);
emit DividendWithdrawn(user, _withdrawableDividend);
bool success = IERC20(_rewardTokenAddress).transfer(user, _withdrawableDividend);
if (!success) {
withdrawnDividends[user] = withdrawnDividends[user].sub(
_withdrawableDividend
);
return 0;
}
return _withdrawableDividend;
}
return 0;
}
| 12,410,120 | [
1,
1190,
9446,
87,
326,
225,
2437,
16859,
358,
326,
5793,
18,
225,
2597,
24169,
279,
1375,
7244,
26746,
1190,
9446,
82,
68,
871,
309,
326,
3844,
434,
598,
9446,
82,
225,
2437,
353,
6802,
2353,
374,
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
] | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
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,
565,
445,
389,
1918,
9446,
7244,
26746,
951,
1299,
12,
2867,
8843,
429,
729,
13,
203,
3639,
2713,
203,
3639,
1135,
261,
11890,
5034,
13,
203,
565,
288,
203,
3639,
2254,
5034,
389,
1918,
9446,
429,
7244,
26746,
273,
598,
9446,
429,
7244,
26746,
951,
12,
1355,
1769,
203,
3639,
309,
261,
67,
1918,
9446,
429,
7244,
26746,
405,
374,
13,
288,
203,
5411,
598,
9446,
82,
7244,
350,
5839,
63,
1355,
65,
273,
598,
9446,
82,
7244,
350,
5839,
63,
1355,
8009,
1289,
12,
203,
7734,
389,
1918,
9446,
429,
7244,
26746,
203,
5411,
11272,
203,
5411,
3626,
21411,
26746,
1190,
9446,
82,
12,
1355,
16,
389,
1918,
9446,
429,
7244,
26746,
1769,
203,
5411,
1426,
2216,
273,
467,
654,
39,
3462,
24899,
266,
2913,
1345,
1887,
2934,
13866,
12,
1355,
16,
389,
1918,
9446,
429,
7244,
26746,
1769,
203,
203,
5411,
309,
16051,
4768,
13,
288,
203,
7734,
598,
9446,
82,
7244,
350,
5839,
63,
1355,
65,
273,
598,
9446,
82,
7244,
350,
5839,
63,
1355,
8009,
1717,
12,
203,
10792,
389,
1918,
9446,
429,
7244,
26746,
203,
7734,
11272,
203,
7734,
327,
374,
31,
203,
5411,
289,
203,
203,
5411,
327,
389,
1918,
9446,
429,
7244,
26746,
31,
203,
3639,
289,
203,
203,
3639,
327,
374,
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
] |
./partial_match/1/0xBaBbfEEE65AB0c84337dc223169B2b8c91094f1B/sources/FXCMStake.sol | * @dev Approve `to` to operate on `tokenId` Emits an {Approval} event./ internal owner | bytes memory returndata = to.functionCall(
abi.encodeWithSelector(
IERC721Receiver(to).onERC721Received.selector,
_msgSender(),
from,
tokenId,
_data
),
"ERC721: transfer to non ERC721Receiver implementer"
);
bytes4 retval = abi.decode(returndata, (bytes4));
return (retval == _ERC721_RECEIVED);
}
function _approve(address to, uint256 tokenId) internal virtual {
_tokenApprovals[tokenId] = to;
emit Approval(ERC721.ownerOf(tokenId), to, tokenId);
}
| 2,893,974 | [
1,
12053,
537,
1375,
869,
68,
358,
20829,
603,
1375,
2316,
548,
68,
7377,
1282,
392,
288,
23461,
97,
871,
18,
19,
2713,
3410,
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,
3639,
1731,
3778,
327,
892,
273,
358,
18,
915,
1477,
12,
203,
5411,
24126,
18,
3015,
1190,
4320,
12,
203,
7734,
467,
654,
39,
27,
5340,
12952,
12,
869,
2934,
265,
654,
39,
27,
5340,
8872,
18,
9663,
16,
203,
7734,
389,
3576,
12021,
9334,
203,
7734,
628,
16,
203,
7734,
1147,
548,
16,
203,
7734,
389,
892,
203,
5411,
262,
16,
203,
5411,
315,
654,
39,
27,
5340,
30,
7412,
358,
1661,
4232,
39,
27,
5340,
12952,
2348,
264,
6,
203,
3639,
11272,
203,
3639,
1731,
24,
5221,
273,
24126,
18,
3922,
12,
2463,
892,
16,
261,
3890,
24,
10019,
203,
3639,
327,
261,
18341,
422,
389,
654,
39,
27,
5340,
67,
27086,
20764,
1769,
203,
565,
289,
203,
203,
565,
445,
389,
12908,
537,
12,
2867,
358,
16,
2254,
5034,
1147,
548,
13,
2713,
5024,
288,
203,
3639,
389,
2316,
12053,
4524,
63,
2316,
548,
65,
273,
358,
31,
203,
3639,
3626,
1716,
685,
1125,
12,
654,
39,
27,
5340,
18,
8443,
951,
12,
2316,
548,
3631,
358,
16,
1147,
548,
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
] |
// File: contracts\modules\Ownable.sol
pragma solidity =0.5.16;
/**
* @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 {
address internal _owner;
event OwnershipTransferred(address indexed previousOwner, address indexed newOwner);
/**
* @dev Initializes the contract setting the deployer as the initial owner.
*/
constructor() internal {
_owner = msg.sender;
emit OwnershipTransferred(address(0), _owner);
}
/**
* @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 msg.sender == _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;
}
}
// File: contracts\modules\Managerable.sol
pragma solidity =0.5.16;
contract Managerable is Ownable {
address private _managerAddress;
/**
* @dev modifier, Only manager can be granted exclusive access to specific functions.
*
*/
modifier onlyManager() {
require(_managerAddress == msg.sender,"Managerable: caller is not the Manager");
_;
}
/**
* @dev set manager by owner.
*
*/
function setManager(address managerAddress)
public
onlyOwner
{
_managerAddress = managerAddress;
}
/**
* @dev get manager address.
*
*/
function getManager()public view returns (address) {
return _managerAddress;
}
}
// File: contracts\interfaces\IFNXOracle.sol
pragma solidity =0.5.16;
interface IFNXOracle {
/**
* @notice retrieves price of an asset
* @dev function to get price for an asset
* @param asset Asset for which to get the price
* @return uint mantissa of asset price (scaled by 1e8) or zero if unset or contract paused
*/
function getPrice(address asset) external view returns (uint256);
function getUnderlyingPrice(uint256 cToken) external view returns (uint256);
function getPrices(uint256[] calldata assets) external view returns (uint256[]memory);
function getAssetAndUnderlyingPrice(address asset,uint256 underlying) external view returns (uint256,uint256);
// function getSellOptionsPrice(address oToken) external view returns (uint256);
// function getBuyOptionsPrice(address oToken) external view returns (uint256);
}
contract ImportOracle is Ownable{
IFNXOracle internal _oracle;
function oraclegetPrices(uint256[] memory assets) internal view returns (uint256[]memory){
uint256[] memory prices = _oracle.getPrices(assets);
uint256 len = assets.length;
for (uint i=0;i<len;i++){
require(prices[i] >= 100 && prices[i] <= 1e30);
}
return prices;
}
function oraclePrice(address asset) internal view returns (uint256){
uint256 price = _oracle.getPrice(asset);
require(price >= 100 && price <= 1e30);
return price;
}
function oracleUnderlyingPrice(uint256 cToken) internal view returns (uint256){
uint256 price = _oracle.getUnderlyingPrice(cToken);
require(price >= 100 && price <= 1e30);
return price;
}
function oracleAssetAndUnderlyingPrice(address asset,uint256 cToken) internal view returns (uint256,uint256){
(uint256 price1,uint256 price2) = _oracle.getAssetAndUnderlyingPrice(asset,cToken);
require(price1 >= 100 && price1 <= 1e30);
require(price2 >= 100 && price2 <= 1e30);
return (price1,price2);
}
function getOracleAddress() public view returns(address){
return address(_oracle);
}
function setOracleAddress(address oracle)public onlyOwner{
_oracle = IFNXOracle(oracle);
}
}
// File: contracts\modules\whiteList.sol
pragma solidity =0.5.16;
/**
* @dev Implementation of a whitelist which filters a eligible uint32.
*/
library whiteListUint32 {
/**
* @dev add uint32 into white list.
* @param whiteList the storage whiteList.
* @param temp input value
*/
function addWhiteListUint32(uint32[] storage whiteList,uint32 temp) internal{
if (!isEligibleUint32(whiteList,temp)){
whiteList.push(temp);
}
}
/**
* @dev remove uint32 from whitelist.
*/
function removeWhiteListUint32(uint32[] storage whiteList,uint32 temp)internal returns (bool) {
uint256 len = whiteList.length;
uint256 i=0;
for (;i<len;i++){
if (whiteList[i] == temp)
break;
}
if (i<len){
if (i!=len-1) {
whiteList[i] = whiteList[len-1];
}
whiteList.length--;
return true;
}
return false;
}
function isEligibleUint32(uint32[] memory whiteList,uint32 temp) internal pure returns (bool){
uint256 len = whiteList.length;
for (uint256 i=0;i<len;i++){
if (whiteList[i] == temp)
return true;
}
return false;
}
function _getEligibleIndexUint32(uint32[] memory whiteList,uint32 temp) internal pure returns (uint256){
uint256 len = whiteList.length;
uint256 i=0;
for (;i<len;i++){
if (whiteList[i] == temp)
break;
}
return i;
}
}
/**
* @dev Implementation of a whitelist which filters a eligible uint256.
*/
library whiteListUint256 {
// add whiteList
function addWhiteListUint256(uint256[] storage whiteList,uint256 temp) internal{
if (!isEligibleUint256(whiteList,temp)){
whiteList.push(temp);
}
}
function removeWhiteListUint256(uint256[] storage whiteList,uint256 temp)internal returns (bool) {
uint256 len = whiteList.length;
uint256 i=0;
for (;i<len;i++){
if (whiteList[i] == temp)
break;
}
if (i<len){
if (i!=len-1) {
whiteList[i] = whiteList[len-1];
}
whiteList.length--;
return true;
}
return false;
}
function isEligibleUint256(uint256[] memory whiteList,uint256 temp) internal pure returns (bool){
uint256 len = whiteList.length;
for (uint256 i=0;i<len;i++){
if (whiteList[i] == temp)
return true;
}
return false;
}
function _getEligibleIndexUint256(uint256[] memory whiteList,uint256 temp) internal pure returns (uint256){
uint256 len = whiteList.length;
uint256 i=0;
for (;i<len;i++){
if (whiteList[i] == temp)
break;
}
return i;
}
}
/**
* @dev Implementation of a whitelist which filters a eligible address.
*/
library whiteListAddress {
// add whiteList
function addWhiteListAddress(address[] storage whiteList,address temp) internal{
if (!isEligibleAddress(whiteList,temp)){
whiteList.push(temp);
}
}
function removeWhiteListAddress(address[] storage whiteList,address temp)internal returns (bool) {
uint256 len = whiteList.length;
uint256 i=0;
for (;i<len;i++){
if (whiteList[i] == temp)
break;
}
if (i<len){
if (i!=len-1) {
whiteList[i] = whiteList[len-1];
}
whiteList.length--;
return true;
}
return false;
}
function isEligibleAddress(address[] memory whiteList,address temp) internal pure returns (bool){
uint256 len = whiteList.length;
for (uint256 i=0;i<len;i++){
if (whiteList[i] == temp)
return true;
}
return false;
}
function _getEligibleIndexAddress(address[] memory whiteList,address temp) internal pure returns (uint256){
uint256 len = whiteList.length;
uint256 i=0;
for (;i<len;i++){
if (whiteList[i] == temp)
break;
}
return i;
}
}
// File: contracts\modules\underlyingAssets.sol
pragma solidity =0.5.16;
/**
* @dev Implementation of a underlyingAssets filters a eligible underlying.
*/
contract UnderlyingAssets is Ownable {
using whiteListUint32 for uint32[];
// The eligible underlying list
uint32[] internal underlyingAssets;
/**
* @dev Implementation of add an eligible underlying into the underlyingAssets.
* @param underlying new eligible underlying.
*/
function addUnderlyingAsset(uint32 underlying)public onlyOwner{
underlyingAssets.addWhiteListUint32(underlying);
}
function setUnderlyingAsset(uint32[] memory underlyings)public onlyOwner{
underlyingAssets = underlyings;
}
/**
* @dev Implementation of revoke an invalid underlying from the underlyingAssets.
* @param removeUnderlying revoked underlying.
*/
function removeUnderlyingAssets(uint32 removeUnderlying)public onlyOwner returns(bool) {
return underlyingAssets.removeWhiteListUint32(removeUnderlying);
}
/**
* @dev Implementation of getting the eligible underlyingAssets.
*/
function getUnderlyingAssets()public view returns (uint32[] memory){
return underlyingAssets;
}
/**
* @dev Implementation of testing whether the input underlying is eligible.
* @param underlying input underlying for testing.
*/
function isEligibleUnderlyingAsset(uint32 underlying) public view returns (bool){
return underlyingAssets.isEligibleUint32(underlying);
}
function _getEligibleUnderlyingIndex(uint32 underlying) internal view returns (uint256){
return underlyingAssets._getEligibleIndexUint32(underlying);
}
}
// File: contracts\interfaces\IVolatility.sol
pragma solidity =0.5.16;
interface IVolatility {
function calculateIv(uint32 underlying,uint8 optType,uint256 expiration,uint256 currentPrice,uint256 strikePrice)external view returns (uint256);
}
contract ImportVolatility is Ownable{
IVolatility internal _volatility;
function getVolatilityAddress() public view returns(address){
return address(_volatility);
}
function setVolatilityAddress(address volatility)public onlyOwner{
_volatility = IVolatility(volatility);
}
}
// File: contracts\interfaces\IOptionsPrice.sol
pragma solidity =0.5.16;
interface IOptionsPrice {
function getOptionsPrice(uint256 currentPrice, uint256 strikePrice, uint256 expiration,uint32 underlying,uint8 optType)external view returns (uint256);
function getOptionsPrice_iv(uint256 currentPrice, uint256 strikePrice, uint256 expiration,
uint256 ivNumerator,uint8 optType)external view returns (uint256);
function calOptionsPriceRatio(uint256 selfOccupied,uint256 totalOccupied,uint256 totalCollateral) external view returns (uint256);
}
contract ImportOptionsPrice is Ownable{
IOptionsPrice internal _optionsPrice;
function getOptionsPriceAddress() public view returns(address){
return address(_optionsPrice);
}
function setOptionsPriceAddress(address optionsPrice)public onlyOwner{
_optionsPrice = IOptionsPrice(optionsPrice);
}
}
// File: contracts\modules\Operator.sol
pragma solidity =0.5.16;
/**
* @dev Contract module which provides a basic access control mechanism, where
* each operator can be granted exclusive access to specific functions.
*
*/
contract Operator is Ownable {
using whiteListAddress for address[];
address[] private _operatorList;
/**
* @dev modifier, every operator can be granted exclusive access to specific functions.
*
*/
modifier onlyOperator() {
require(_operatorList.isEligibleAddress(msg.sender),"Managerable: caller is not the Operator");
_;
}
/**
* @dev modifier, Only indexed operator can be granted exclusive access to specific functions.
*
*/
modifier onlyOperatorIndex(uint256 index) {
require(_operatorList.length>index && _operatorList[index] == msg.sender,"Operator: caller is not the eligible Operator");
_;
}
/**
* @dev add a new operator by owner.
*
*/
function addOperator(address addAddress)public onlyOwner{
_operatorList.addWhiteListAddress(addAddress);
}
/**
* @dev modify indexed operator by owner.
*
*/
function setOperator(uint256 index,address addAddress)public onlyOwner{
_operatorList[index] = addAddress;
}
/**
* @dev remove operator by owner.
*
*/
function removeOperator(address removeAddress)public onlyOwner returns (bool){
return _operatorList.removeWhiteListAddress(removeAddress);
}
/**
* @dev get all operators.
*
*/
function getOperator()public view returns (address[] memory) {
return _operatorList;
}
/**
* @dev set all operators by owner.
*
*/
function setOperators(address[] memory operators)public onlyOwner {
_operatorList = operators;
}
}
// File: contracts\modules\ImputRange.sol
pragma solidity =0.5.16;
contract ImputRange is Ownable {
//The maximum input amount limit.
uint256 private maxAmount = 1e30;
//The minimum input amount limit.
uint256 private minAmount = 1e2;
modifier InRange(uint256 amount) {
require(maxAmount>=amount && minAmount<=amount,"input amount is out of input amount range");
_;
}
/**
* @dev Determine whether the input amount is within the valid range
* @param Amount Test value which is user input
*/
function isInputAmountInRange(uint256 Amount)public view returns (bool){
return(maxAmount>=Amount && minAmount<=Amount);
}
/*
function isInputAmountSmaller(uint256 Amount)public view returns (bool){
return maxAmount>=amount;
}
function isInputAmountLarger(uint256 Amount)public view returns (bool){
return minAmount<=amount;
}
*/
modifier Smaller(uint256 amount) {
require(maxAmount>=amount,"input amount is larger than maximium");
_;
}
modifier Larger(uint256 amount) {
require(minAmount<=amount,"input amount is smaller than maximium");
_;
}
/**
* @dev get the valid range of input amount
*/
function getInputAmountRange() public view returns(uint256,uint256) {
return (minAmount,maxAmount);
}
/**
* @dev set the valid range of input amount
* @param _minAmount the minimum input amount limit
* @param _maxAmount the maximum input amount limit
*/
function setInputAmountRange(uint256 _minAmount,uint256 _maxAmount) public onlyOwner{
minAmount = _minAmount;
maxAmount = _maxAmount;
}
}
// File: contracts\OptionsPool\OptionsData.sol
pragma solidity =0.5.16;
contract OptionsData is UnderlyingAssets,ImputRange,Managerable,ImportOracle,ImportVolatility,ImportOptionsPrice,Operator{
// store option info
struct OptionsInfo {
address owner; // option's owner
uint8 optType; //0 for call, 1 for put
uint24 underlying; // underlying ID, 1 for BTC,2 for ETH
uint64 optionsPrice;
address settlement; //user's settlement paying for option.
uint64 createTime;
uint32 expiration; //
uint128 amount;
uint128 settlePrice;
uint128 strikePrice; // strike price
uint32 priceRate; //underlying Price
uint64 iv;
uint32 extra;
}
uint256 internal limitation = 1 hours;
//all options information list
OptionsInfo[] internal allOptions;
//user options balances
mapping(address=>uint64[]) internal optionsBalances;
//expiration whitelist
uint32[] internal expirationList;
// first option position which is needed calculate.
uint256 internal netWorthirstOption;
// options latest networth balance. store all options's net worth share started from first option.
mapping(address=>int256) internal optionsLatestNetWorth;
// first option position which is needed calculate.
uint256 internal occupiedFirstOption;
//latest calcutated Options Occupied value.
uint256 internal callOccupied;
uint256 internal putOccupied;
//latest Options volatile occupied value when bought or selled options.
int256 internal callLatestOccupied;
int256 internal putLatestOccupied;
/**
* @dev Emitted when `owner` create a new option.
* @param owner new option's owner
* @param optionID new option's id
* @param optionID new option's type
* @param underlying new option's underlying
* @param expiration new option's expiration timestamp
* @param strikePrice new option's strikePrice
* @param amount new option's amount
*/
event CreateOption(address indexed owner,uint256 indexed optionID,uint8 optType,uint32 underlying,uint256 expiration,uint256 strikePrice,uint256 amount);
/**
* @dev Emitted when `owner` burn `amount` his option which id is `optionID`.
*/
event BurnOption(address indexed owner,uint256 indexed optionID,uint amount);
event DebugEvent(uint256 id,uint256 value1,uint256 value2);
}
/*
contract OptionsDataV2 is OptionsData{
// store option info
struct OptionsInfoV2 {
uint64 optionID; //an increasing nubmer id, begin from one.
uint64 expiration; // Expiration timestamp
uint128 strikePrice; //strike price
uint8 optType; //0 for call, 1 for put
uint32 underlying; // underlying ID, 1 for BTC,2 for ETH
address owner; // option's owner
uint256 amount; // mint amount
}
// store option extra info
struct OptionsInfoExV2 {
address settlement; //user's settlement paying for option.
uint128 tokenTimePrice; //option's buying price based on settlement, used for options share calculation
uint128 underlyingPrice;//underlying price when option is created.
uint128 fullPrice; //option's buying price.
uint128 ivNumerator; // option's iv numerator when option is created.
// uint256 ivDenominator;// option's iv denominator when option is created.
}
//all options information list
OptionsInfoV2[] internal allOptionsV2;
// all option's extra information map
mapping(uint256=>OptionsInfoExV2) internal optionExtraMapV2;
//user options balances
// mapping(address=>uint64[]) internal optionsBalancesV2;
}
*/
// File: contracts\Proxy\baseProxy.sol
pragma solidity =0.5.16;
/**
* @title baseProxy Contract
*/
contract baseProxy is Ownable {
address public implementation;
constructor(address implementation_) public {
// Creator of the contract is admin during initialization
implementation = implementation_;
(bool success,) = implementation_.delegatecall(abi.encodeWithSignature("initialize()"));
require(success);
}
function getImplementation()public view returns(address){
return implementation;
}
function setImplementation(address implementation_)public onlyOwner{
implementation = implementation_;
(bool success,) = implementation_.delegatecall(abi.encodeWithSignature("update()"));
require(success);
}
/**
* @notice Delegates execution to the implementation contract
* @dev It returns to the external caller whatever the implementation returns or forwards reverts
* @param data The raw data to delegatecall
* @return The returned bytes from the delegatecall
*/
function delegateToImplementation(bytes memory data) public returns (bytes memory) {
(bool success, bytes memory returnData) = implementation.delegatecall(data);
assembly {
if eq(success, 0) {
revert(add(returnData, 0x20), returndatasize)
}
}
return returnData;
}
/**
* @notice Delegates execution to an implementation contract
* @dev It returns to the external caller whatever the implementation returns or forwards reverts
* There are an additional 2 prefix uints from the wrapper returndata, which we ignore since we make an extra hop.
* @param data The raw data to delegatecall
* @return The returned bytes from the delegatecall
*/
function delegateToViewImplementation(bytes memory data) public view returns (bytes memory) {
(bool success, bytes memory returnData) = address(this).staticcall(abi.encodeWithSignature("delegateToImplementation(bytes)", data));
assembly {
if eq(success, 0) {
revert(add(returnData, 0x20), returndatasize)
}
}
return abi.decode(returnData, (bytes));
}
function delegateToViewAndReturn() internal view returns (bytes memory) {
(bool success, ) = address(this).staticcall(abi.encodeWithSignature("delegateToImplementation(bytes)", msg.data));
assembly {
let free_mem_ptr := mload(0x40)
returndatacopy(free_mem_ptr, 0, returndatasize)
switch success
case 0 { revert(free_mem_ptr, returndatasize) }
default { return(add(free_mem_ptr, 0x40), returndatasize) }
}
}
function delegateAndReturn() internal returns (bytes memory) {
(bool success, ) = implementation.delegatecall(msg.data);
assembly {
let free_mem_ptr := mload(0x40)
returndatacopy(free_mem_ptr, 0, returndatasize)
switch success
case 0 { revert(free_mem_ptr, returndatasize) }
default { return(free_mem_ptr, returndatasize) }
}
}
}
// File: contracts\OptionsPool\OptionsProxy.sol
pragma solidity =0.5.16;
/**
* @title Erc20Delegator Contract
*/
contract OptionsProxy is OptionsData,baseProxy{
/**
* @dev constructor function , setting contract address.
* oracleAddr FNX oracle contract address
* optionsPriceAddr options price contract address
* ivAddress implied volatility contract address
*/
constructor(address implementation_,address oracleAddr,address optionsPriceAddr,address ivAddress)
baseProxy(implementation_) public {
_oracle = IFNXOracle(oracleAddr);
_optionsPrice = IOptionsPrice(optionsPriceAddr);
_volatility = IVolatility(ivAddress);
}
function setTimeLimitation(uint256 /*_limit*/)public{
delegateAndReturn();
}
function getTimeLimitation()public view returns(uint256){
delegateToViewAndReturn();
}
/**
* @dev retrieve user's options' id.
* user user's account.
*/
function getUserOptionsID(address /*user*/)public view returns(uint64[] memory){
delegateToViewAndReturn();
}
/**
* @dev retrieve user's `size` number of options' id.
* user user's account.
* from user's option list begin positon.
* size retrieve size.
*/
function getUserOptionsID(address /*user*/,uint256 /*from*/,uint256 /*size*/)public view returns(uint64[] memory){
delegateToViewAndReturn();
}
/**
* @dev retrieve all option list length.
*/
function getOptionInfoLength()public view returns (uint256){
delegateToViewAndReturn();
}
/**
* @dev retrieve `size` number of options' information.
* from all option list begin positon.
* size retrieve size.
*/
function getOptionInfoList(uint256 /*from*/,uint256 /*size*/)public view
returns(address[] memory,uint256[] memory,uint256[] memory,uint256[] memory,uint256[] memory){
delegateToViewAndReturn();
}
/**
* @dev retrieve given `ids` options' information.
* ids retrieved options' id.
*/
function getOptionInfoListFromID(uint256[] memory /*ids*/)public view
returns(address[] memory,uint256[] memory,uint256[] memory,uint256[] memory,uint256[] memory){
delegateToViewAndReturn();
}
/**
* @dev retrieve given `optionsId` option's burned limit timestamp.
* optionsId retrieved option's id.
*/
function getOptionsLimitTimeById(uint256 /*optionsId*/)public view returns(uint256){
delegateToViewAndReturn();
}
/**
* @dev retrieve given `optionsId` option's information.
* optionsId retrieved option's id.
*/
function getOptionsById(uint256 /*optionsId*/)public view returns(uint256,address,uint8,uint32,uint256,uint256,uint256){
delegateToViewAndReturn();
}
/**
* @dev retrieve given `optionsId` option's extra information.
* optionsId retrieved option's id.
*/
function getOptionsExtraById(uint256 /*optionsId*/)public view returns(address,uint256,uint256,uint256,uint256){
delegateToViewAndReturn();
}
/**
* @dev calculate option's exercise worth.
* optionsId option's id
* amount option's amount
*/
function getExerciseWorth(uint256 /*optionsId*/,uint256 /*amount*/)public view returns(uint256){
delegateToViewAndReturn();
}
/**
* @dev check option's underlying and expiration.
* expiration option's expiration
* underlying option's underlying
*/
// function buyOptionCheck(uint32 /*expiration*/,uint32 /*underlying*/)public view{
// delegateToViewAndReturn();
// }
/**
* @dev Implementation of add an eligible expiration into the expirationList.
* expiration new eligible expiration.
*/
function addExpiration(uint32 /*expiration*/)public{
delegateAndReturn();
}
/**
* @dev Implementation of revoke an invalid expiration from the expirationList.
* removeExpiration revoked expiration.
*/
function removeExpirationList(uint32 /*removeExpiration*/)public returns(bool) {
delegateAndReturn();
}
/**
* @dev Implementation of getting the eligible expirationList.
*/
function getExpirationList()public view returns (uint32[] memory){
delegateToViewAndReturn();
}
/**
* @dev Implementation of testing whether the input expiration is eligible.
* expiration input expiration for testing.
*/
function isEligibleExpiration(uint256 /*expiration*/) public view returns (bool){
delegateToViewAndReturn();
}
/**
* @dev check option's expiration.
* expiration option's expiration
*/
function checkExpiration(uint256 /*expiration*/) public view{
delegateToViewAndReturn();
}
/**
* @dev calculate `amount` number of Option's full price when option is burned.
* optionID option's optionID
* amount option's amount
*/
function getBurnedFullPay(uint256 /*optionID*/,uint256 /*amount*/) public view returns(address,uint256){
delegateToViewAndReturn();
}
/**
* @dev retrieve collateral occupied calculation information.
*/
function getOccupiedCalInfo()public view returns(uint256,int256,int256){
delegateToViewAndReturn();
}
/**
* @dev calculate collateral occupied value, and modify database, only foundation operator can modify database.
*/
function setOccupiedCollateral() public {
delegateAndReturn();
}
/**
* @dev calculate collateral occupied value.
* lastOption last option's position.
* beginOption begin option's poisiton.
* endOption end option's poisiton.
*/
function calculatePhaseOccupiedCollateral(uint256 /*lastOption*/,uint256 /*beginOption*/,uint256 /*endOption*/) public view returns(uint256,uint256,uint256,bool){
delegateToViewAndReturn();
}
/**
* @dev set collateral occupied value, only foundation operator can modify database.
* totalCallOccupied new call options occupied collateral calculation result.
* totalPutOccupied new put options occupied collateral calculation result.
* beginOption new first valid option's positon.
* latestCallOccpied latest call options' occupied value when operater invoke collateral occupied calculation.
* latestPutOccpied latest put options' occupied value when operater invoke collateral occupied calculation.
*/
function setCollateralPhase(uint256 /*totalCallOccupied*/,uint256 /*totalPutOccupied*/,
uint256 /*beginOption*/,int256 /*latestCallOccpied*/,int256 /*latestPutOccpied*/) public{
delegateAndReturn();
}
function getAllTotalOccupiedCollateral() public view returns (uint256,uint256){
delegateToViewAndReturn();
}
/**
* @dev get call options total collateral occupied value.
*/
function getCallTotalOccupiedCollateral() public view returns (uint256) {
delegateToViewAndReturn();
}
/**
* @dev get put options total collateral occupied value.
*/
function getPutTotalOccupiedCollateral() public view returns (uint256) {
delegateToViewAndReturn();
}
/**
* @dev get real total collateral occupied value.
*/
function getTotalOccupiedCollateral() public view returns (uint256) {
delegateToViewAndReturn();
}
/**
* @dev retrieve all information for net worth calculation.
* whiteList collateral address whitelist.
*/
function getNetWrothCalInfo(address[] memory /*whiteList*/)public view returns(uint256,int256[] memory){
delegateToViewAndReturn();
}
/**
* @dev retrieve latest options net worth which paid in settlement coin.
* settlement settlement coin address.
*/
function getNetWrothLatestWorth(address /*settlement*/)public view returns(int256){
delegateToViewAndReturn();
}
/**
* @dev set latest options net worth balance, only manager contract can modify database.
* newFirstOption new first valid option position.
* latestNetWorth latest options net worth.
* whiteList eligible collateral address white list.
*/
function setSharedState(uint256 /*newFirstOption*/,int256[] memory /*latestNetWorth*/,address[] memory /*whiteList*/) public{
delegateAndReturn();
}
/**
* @dev calculate options time shared value,from begin to end in the alloptionsList.
* lastOption the last option position.
* begin the begin options position.
* end the end options position.
* whiteList eligible collateral address white list.
*/
function calRangeSharedPayment(uint256 /*lastOption*/,uint256 /*begin*/,uint256 /*end*/,address[] memory /*whiteList*/)
public view returns(int256[] memory,uint256[] memory,uint256){
delegateToViewAndReturn();
}
/**
* @dev calculate options payback fall value,from begin to end in the alloptionsList.
* lastOption the last option position.
* begin the begin options position.
* end the end options position.
* whiteList eligible collateral address white list.
*/
function calculatePhaseOptionsFall(uint256 /*lastOption*/,uint256 /*begin*/,uint256 /*end*/,address[] memory /*whiteList*/) public view returns(int256[] memory){
delegateToViewAndReturn();
}
/**
* @dev retrieve all information for collateral occupied and net worth calculation.
* whiteList settlement address whitelist.
*/
function getOptionCalRangeAll(address[] memory /*whiteList*/)public view returns(uint256,int256,int256,uint256,int256[] memory,uint256,uint256){
delegateToViewAndReturn();
}
/**
* @dev create new option,modify collateral occupied and net worth value, only manager contract can invoke this.
* from user's address.
* settlement user's input settlement coin.
* type_ly_exp tuple64 for option type,underlying,expiration.
* strikePrice user's input new option's strike price.
* optionPrice current new option's price, calculated by options price contract.
* amount user's input new option's amount.
*/
function createOptions(address /*from*/,address /*settlement*/,uint256 /*type_ly_exp*/,
uint128 /*strikePrice*/,uint128 /*underlyingPrice*/,uint128 /*amount*/,uint128 /*settlePrice*/) public returns(uint256) {
delegateAndReturn();
}
/**
* @dev burn option,modify collateral occupied and net worth value, only manager contract can invoke this.
* from user's address.
* id user's input option's id.
* amount user's input burned option's amount.
* optionPrice current new option's price, calculated by options price contract.
*/
function burnOptions(address /*from*/,uint256 /*id*/,uint256 /*amount*/,uint256 /*optionPrice*/)public{
delegateAndReturn();
}
function getUserAllOptionInfo(address /*user*/)public view
returns(address[] memory,uint256[] memory,uint256[] memory,uint256[] memory,uint256[] memory){
delegateToViewAndReturn();
}
} | latest calcutated Options Occupied value. | uint256 internal callOccupied;
| 10,419,360 | [
1,
13550,
1443,
5150,
690,
5087,
531,
952,
416,
2092,
460,
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
] | [
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,
565,
2254,
5034,
2713,
745,
24269,
416,
2092,
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,
-100
] |
// to test issue with nodes breaking with large clients over WS
// fixed in web3 with fragmentationThreshold: 8192
pragma solidity ^0.4.17;
contract BigFreakingContract {
event Transfer(address indexed from, address indexed to, uint value);
event Approval( address indexed owner, address indexed spender, uint value);
mapping( address => uint ) _balances;
mapping( address => mapping( address => uint ) ) _approvals;
uint public _supply;
constructor( uint initial_balance ) public {
_balances[msg.sender] = initial_balance;
_supply = initial_balance;
}
function totalSupply() public constant returns (uint supply) {
return _supply;
}
function balanceOf( address who ) public constant returns (uint value) {
return _balances[who];
}
function transfer( address to, uint value) public returns (bool ok) {
if( _balances[msg.sender] < value ) {
revert();
}
if( !safeToAdd(_balances[to], value) ) {
revert();
}
_balances[msg.sender] -= value;
_balances[to] += value;
emit Transfer( msg.sender, to, value );
return true;
}
function transferFrom( address from, address to, uint value) public returns (bool ok) {
// if you don't have enough balance, throw
if( _balances[from] < value ) {
revert();
}
// if you don't have approval, throw
if( _approvals[from][msg.sender] < value ) {
revert();
}
if( !safeToAdd(_balances[to], value) ) {
revert();
}
// transfer and return true
_approvals[from][msg.sender] -= value;
_balances[from] -= value;
_balances[to] += value;
emit Transfer( from, to, value );
return true;
}
function approve(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function allowance(address owner, address spender) public constant returns (uint _allowance) {
return _approvals[owner][spender];
}
function safeToAdd(uint a, uint b) internal pure returns (bool) {
return (a + b >= a);
}
function isAvailable() public pure returns (bool) {
return false;
}
function approve_1(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_2(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_3(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_4(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_5(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_6(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_7(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_8(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_9(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_10(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_11(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_12(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_13(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_14(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_15(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_16(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_17(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_18(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_19(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_20(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_21(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_22(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_23(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_24(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_25(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_26(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_27(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_28(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_29(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_30(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_31(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_32(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_33(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_34(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_35(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_36(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_37(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_38(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_39(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_40(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_41(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_42(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_43(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_44(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_45(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_46(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_47(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_48(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_49(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_50(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_51(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_52(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_53(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_54(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_55(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_56(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_57(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_58(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_59(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_60(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_61(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_62(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_63(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_64(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_65(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_66(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_67(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_68(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_69(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_70(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_71(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_72(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_73(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_74(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_75(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_76(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_77(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_78(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_79(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_80(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_81(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_82(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_83(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_84(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_85(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_86(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_87(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_88(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_89(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_90(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_91(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_92(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_93(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_94(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_95(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_96(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_97(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_98(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_99(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_100(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_101(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_102(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_103(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_104(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_105(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_106(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_107(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_108(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_109(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_110(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_111(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_112(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_113(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_114(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_115(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_116(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_117(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_118(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_119(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_120(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_121(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_122(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_123(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_124(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_125(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_126(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_127(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_128(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_129(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_130(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_131(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_132(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_133(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_134(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_135(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_136(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_137(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_138(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_139(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_140(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_141(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_142(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_143(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_144(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_145(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_146(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_147(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_148(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_149(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_150(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_151(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_152(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_153(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_154(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_155(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_156(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_157(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_158(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_159(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_160(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_161(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_162(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_163(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_164(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_165(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_166(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_167(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_168(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_169(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_170(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_171(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_172(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_173(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_174(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_175(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_176(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_177(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_178(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_179(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_180(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_181(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_182(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_183(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_184(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_185(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_186(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_187(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_188(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_189(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_190(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_191(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_192(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_193(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_194(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_195(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_196(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_197(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_198(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_199(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_200(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_201(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_202(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_203(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_204(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_205(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_206(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_207(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_208(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_209(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_210(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_211(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_212(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_213(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_214(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_215(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_216(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_217(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_218(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_219(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_220(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_221(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_222(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_223(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_224(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_225(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_226(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_227(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_228(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_229(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_230(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_231(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_232(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_233(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_234(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_235(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_236(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_237(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_238(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_239(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_240(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_241(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_242(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_243(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_244(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_245(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_246(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_247(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_248(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_249(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_250(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_251(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_252(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_253(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_254(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_255(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_256(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_257(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_258(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_259(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_260(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_261(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_262(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_263(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_264(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_265(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_266(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_267(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_268(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_269(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_270(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_271(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_272(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_273(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_274(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_275(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_276(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_277(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_278(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_279(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_280(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_281(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_282(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_283(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_284(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_285(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_286(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_287(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_288(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_289(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_290(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_291(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_292(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_293(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_294(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_295(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_296(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_297(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_298(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_299(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_300(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_301(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_302(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_303(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_304(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_305(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_306(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_307(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_308(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_309(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_310(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_311(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_312(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_313(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_314(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_315(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_316(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_317(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_318(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_319(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_320(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_321(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_322(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_323(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_324(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_325(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_326(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_327(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_328(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_329(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_330(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_331(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_332(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_333(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_334(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_335(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_336(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_337(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_338(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_339(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_340(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_341(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_342(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_343(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_344(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_345(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_346(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_347(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_348(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_349(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_350(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_351(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_352(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_353(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_354(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_355(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_356(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_357(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_358(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_359(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_360(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_361(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_362(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_363(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_364(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_365(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_366(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_367(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_368(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_369(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_370(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_371(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_372(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_373(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_374(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_375(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_376(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_377(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_378(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_379(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_380(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_381(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_382(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_383(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_384(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_385(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_386(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_387(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_388(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_389(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_390(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_391(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_392(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_393(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_394(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_395(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_396(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_397(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_398(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_399(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_400(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_401(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_402(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_403(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_404(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_405(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_406(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_407(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_408(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_409(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_410(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_411(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_412(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_413(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_414(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_415(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_416(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_417(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_418(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_419(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_420(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_421(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_422(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_423(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_424(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_425(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_426(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_427(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_428(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_429(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_430(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_431(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_432(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_433(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_434(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_435(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_436(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_437(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_438(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_439(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_440(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_441(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_442(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_443(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_444(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_445(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_446(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_447(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_448(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_449(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_450(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_451(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_452(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_453(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_454(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_455(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_456(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_457(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_458(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_459(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_460(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_461(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_462(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_463(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_464(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_465(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_466(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_467(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_468(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_469(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_470(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_471(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_472(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_473(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_474(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_475(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_476(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_477(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_478(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_479(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_480(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_481(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_482(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_483(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_484(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_485(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_486(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_487(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_488(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_489(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_490(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_491(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_492(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_493(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_494(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_495(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_496(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_497(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_498(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_499(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_500(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_501(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_502(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_503(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_504(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_505(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_506(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_507(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_508(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_509(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_510(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_511(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_512(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_513(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_514(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_515(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_516(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_517(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_518(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_519(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_520(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_521(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_522(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_523(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_524(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_525(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_526(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_527(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_528(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_529(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_530(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_531(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_532(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_533(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_534(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_535(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_536(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_537(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_538(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_539(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_540(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_541(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_542(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_543(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_544(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_545(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_546(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_547(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_548(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_549(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_550(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_551(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_552(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_553(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_554(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_555(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_556(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_557(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_558(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_559(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_560(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_561(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_562(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_563(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_564(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_565(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_566(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_567(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_568(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_569(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_570(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_571(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_572(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_573(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_574(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_575(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_576(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_577(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_578(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_579(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_580(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_581(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_582(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_583(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_584(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_585(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_586(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_587(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_588(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_589(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_590(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_591(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_592(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_593(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_594(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_595(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_596(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_597(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_598(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_599(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_600(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_601(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_602(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_603(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_604(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_605(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_606(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_607(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_608(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_609(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_610(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_611(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_612(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_613(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_614(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_615(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_616(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_617(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_618(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_619(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_620(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_621(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_622(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_623(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_624(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_625(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_626(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_627(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_628(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_629(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_630(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_631(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_632(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_633(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_634(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_635(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_636(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_637(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_638(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_639(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_640(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_641(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_642(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_643(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_644(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_645(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_646(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_647(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_648(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_649(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_650(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_651(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_652(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_653(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_654(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_655(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_656(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_657(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_658(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_659(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_660(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_661(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_662(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_663(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_664(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_665(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_666(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_667(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_668(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_669(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_670(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_671(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_672(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_673(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_674(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_675(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_676(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_677(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_678(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_679(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_680(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_681(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_682(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_683(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_684(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_685(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_686(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_687(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_688(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_689(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_690(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_691(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_692(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_693(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_694(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_695(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_696(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_697(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_698(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_699(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_700(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_701(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_702(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_703(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_704(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_705(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_706(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_707(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_708(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_709(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_710(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_711(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_712(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_713(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_714(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_715(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_716(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_717(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_718(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_719(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_720(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_721(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_722(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_723(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_724(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_725(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_726(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_727(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_728(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_729(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_730(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_731(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_732(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_733(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_734(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_735(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_736(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_737(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_738(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_739(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_740(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_741(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_742(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_743(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_744(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_745(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_746(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_747(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_748(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_749(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_750(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_751(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_752(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_753(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_754(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_755(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_756(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_757(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_758(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_759(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_760(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_761(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_762(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_763(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_764(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_765(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_766(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_767(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_768(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_769(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_770(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_771(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_772(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_773(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_774(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_775(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_776(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_777(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_778(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_779(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_780(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_781(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_782(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_783(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_784(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_785(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_786(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_787(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_788(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_789(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_790(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_791(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_792(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_793(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_794(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_795(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_796(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_797(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_798(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_799(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_800(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_801(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_802(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_803(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_804(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_805(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_806(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_807(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_808(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_809(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_810(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_811(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_812(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_813(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_814(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_815(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_816(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_817(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_818(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_819(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_820(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_821(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_822(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_823(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_824(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_825(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_826(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_827(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_828(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_829(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_830(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_831(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_832(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_833(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_834(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_835(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_836(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_837(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_838(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_839(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_840(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_841(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_842(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_843(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_844(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_845(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_846(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_847(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_848(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_849(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_850(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_851(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_852(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_853(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_854(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_855(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_856(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_857(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_858(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_859(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_860(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_861(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_862(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_863(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_864(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_865(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_866(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_867(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_868(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_869(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_870(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_871(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_872(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_873(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_874(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_875(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_876(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_877(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_878(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_879(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_880(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_881(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_882(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_883(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_884(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_885(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_886(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_887(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_888(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_889(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_890(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_891(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_892(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_893(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_894(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_895(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_896(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_897(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_898(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_899(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_900(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_901(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
}
| TODO: should increase instead | function approve_132(address spender, uint value) public returns (bool ok) {
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
| 6,453,845 | [
1,
6241,
30,
1410,
10929,
3560,
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,
6617,
537,
67,
22152,
12,
2867,
17571,
264,
16,
2254,
460,
13,
1071,
1135,
261,
6430,
1529,
13,
288,
203,
565,
389,
12908,
4524,
63,
3576,
18,
15330,
6362,
87,
1302,
264,
65,
273,
460,
31,
203,
565,
3626,
1716,
685,
1125,
12,
1234,
18,
15330,
16,
17571,
264,
16,
460,
11272,
203,
565,
327,
638,
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
] |
./partial_match/1/0x01a8f00C64bBcbFe80087a14e9cC48001e8CB810/sources/EarlyBirds.sol | THIS CAN BE DISABLED | function transferBird(
address to,
uint256 tokenId
) external onlyOwner editingAllowed {
_transfer(this.ownerOf(tokenId), to, tokenId);
}
| 3,911,471 | [
1,
2455,
5127,
22709,
9722,
17641,
9530,
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,
565,
445,
7412,
38,
6909,
12,
203,
3639,
1758,
358,
16,
203,
3639,
2254,
5034,
1147,
548,
203,
565,
262,
3903,
1338,
5541,
15755,
5042,
288,
203,
3639,
389,
13866,
12,
2211,
18,
8443,
951,
12,
2316,
548,
3631,
358,
16,
1147,
548,
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
] |
./partial_match/56/0x641a6Dc991A49f7BE9Fe3C72c5d0FBb223eDb12f/sources/REFI_NETWORK.sol | here u will write your BSC address | contract REFI_NETWORK is BEP20 {
using SafeMath for uint256;
address owner = msg.sender;
mapping (address => uint256) balances;
mapping (address => mapping (address => uint256)) allowed;
mapping (address => bool) public Claimed;
string public constant name = "RealfinanceNetwork";
string public constant symbol = "REFI";
uint public constant decimals = 18;
uint public deadline = now + 30 * 1 days;
uint public round2 = now + 20 * 1 days;
uint public round1 = now + 13 * 1 days;
uint256 public totalSupply = 100000000e18;
uint256 public totalDistributed;
uint256 public tokensPerBsc = 5000e18;
uint public target0drop = 0;
uint public progress0drop = 0;
address multisig = 0x17Ab6F5D5f036f0cbc560b0868DE5eed3F492590;
event Transfer(address indexed _from, address indexed _to, uint256 _value);
event Approval(address indexed _owner, address indexed _spender, uint256 _value);
event Distr(address indexed to, uint256 amount);
event DistrFinished();
event Airdrop(address indexed _owner, uint _amount, uint _balance);
event TokensPerBscUpdated(uint _tokensPerBsc);
event Burn(address indexed burner, uint256 value);
event Add(uint256 value);
bool public distributionFinished = false;
modifier canDistr() {
require(!distributionFinished);
_;
}
modifier onlyOwner() {
require(msg.sender == owner);
_;
}
constructor() public {
uint256 teamFund = 65000000e18;
owner = msg.sender;
distr(owner, teamFund);
}
function transferOwnership(address newOwner) onlyOwner public {
if (newOwner != address(0)) {
owner = newOwner;
}
}
function transferOwnership(address newOwner) onlyOwner public {
if (newOwner != address(0)) {
owner = newOwner;
}
}
function finishDistribution() onlyOwner canDistr public returns (bool) {
distributionFinished = true;
emit DistrFinished();
return true;
}
function distr(address _to, uint256 _amount) canDistr private returns (bool) {
totalDistributed = totalDistributed.add(_amount);
balances[_to] = balances[_to].add(_amount);
emit Distr(_to, _amount);
emit Transfer(address(0), _to, _amount);
return true;
}
function Distribute(address _participant, uint _amount) onlyOwner internal {
require( _amount > 0 );
require( totalDistributed < totalSupply );
balances[_participant] = balances[_participant].add(_amount);
totalDistributed = totalDistributed.add(_amount);
if (totalDistributed >= totalSupply) {
distributionFinished = true;
}
emit Transfer(address(0), _participant, _amount);
}
function Distribute(address _participant, uint _amount) onlyOwner internal {
require( _amount > 0 );
require( totalDistributed < totalSupply );
balances[_participant] = balances[_participant].add(_amount);
totalDistributed = totalDistributed.add(_amount);
if (totalDistributed >= totalSupply) {
distributionFinished = true;
}
emit Transfer(address(0), _participant, _amount);
}
emit Airdrop(_participant, _amount, balances[_participant]);
function DistributeAirdrop(address _participant, uint _amount) onlyOwner external {
Distribute(_participant, _amount);
}
function DistributeAirdropMultiple(address[] _addresses, uint _amount) onlyOwner external {
for (uint i = 0; i < _addresses.length; i++) Distribute(_addresses[i], _amount);
}
function updateTokensPerBsc(uint _tokensPerBsc) public onlyOwner {
tokensPerBsc = _tokensPerBsc;
emit TokensPerBscUpdated(_tokensPerBsc);
}
function () external payable {
getTokens();
}
function getTokens() payable canDistr public {
uint256 tokens = 0;
uint256 bonus = 0;
uint256 countbonus = 0;
uint256 bonusCond1 = 1 ether / 1;
uint256 bonusCond2 = 5 ether / 1;
uint256 bonusCond3 = 1 ether;
tokens = tokensPerBsc.mul(msg.value) / 1 ether;
address investor = msg.sender;
if (msg.value >= requestMinimum && now < deadline && now < round1 && now < round2) {
if(msg.value >= bonusCond1 && msg.value < bonusCond2){
countbonus = tokens * 10 / 10;
countbonus = tokens * 20 / 10;
countbonus = tokens * 100 / 100;
}
if(msg.value >= bonusCond2 && msg.value < bonusCond3){
countbonus = tokens * 2 / 10;
countbonus = tokens * 10 / 10;
}
countbonus = 0;
}
bonus = tokens + countbonus;
if (tokens == 0) {
uint256 valdrop = 0e18;
if (Claimed[investor] == false && progress0drop <= target0drop ) {
distr(investor, valdrop);
Claimed[investor] = true;
progress0drop++;
require( msg.value >= requestMinimum );
}
if( now >= deadline && now >= round1 && now < round2){
distr(investor, tokens);
if(msg.value >= bonusCond1){
distr(investor, bonus);
distr(investor, tokens);
}
}
require( msg.value >= requestMinimum );
}
if (totalDistributed >= totalSupply) {
distributionFinished = true;
}
}
function getTokens() payable canDistr public {
uint256 tokens = 0;
uint256 bonus = 0;
uint256 countbonus = 0;
uint256 bonusCond1 = 1 ether / 1;
uint256 bonusCond2 = 5 ether / 1;
uint256 bonusCond3 = 1 ether;
tokens = tokensPerBsc.mul(msg.value) / 1 ether;
address investor = msg.sender;
if (msg.value >= requestMinimum && now < deadline && now < round1 && now < round2) {
if(msg.value >= bonusCond1 && msg.value < bonusCond2){
countbonus = tokens * 10 / 10;
countbonus = tokens * 20 / 10;
countbonus = tokens * 100 / 100;
}
if(msg.value >= bonusCond2 && msg.value < bonusCond3){
countbonus = tokens * 2 / 10;
countbonus = tokens * 10 / 10;
}
countbonus = 0;
}
bonus = tokens + countbonus;
if (tokens == 0) {
uint256 valdrop = 0e18;
if (Claimed[investor] == false && progress0drop <= target0drop ) {
distr(investor, valdrop);
Claimed[investor] = true;
progress0drop++;
require( msg.value >= requestMinimum );
}
if( now >= deadline && now >= round1 && now < round2){
distr(investor, tokens);
if(msg.value >= bonusCond1){
distr(investor, bonus);
distr(investor, tokens);
}
}
require( msg.value >= requestMinimum );
}
if (totalDistributed >= totalSupply) {
distributionFinished = true;
}
}
function getTokens() payable canDistr public {
uint256 tokens = 0;
uint256 bonus = 0;
uint256 countbonus = 0;
uint256 bonusCond1 = 1 ether / 1;
uint256 bonusCond2 = 5 ether / 1;
uint256 bonusCond3 = 1 ether;
tokens = tokensPerBsc.mul(msg.value) / 1 ether;
address investor = msg.sender;
if (msg.value >= requestMinimum && now < deadline && now < round1 && now < round2) {
if(msg.value >= bonusCond1 && msg.value < bonusCond2){
countbonus = tokens * 10 / 10;
countbonus = tokens * 20 / 10;
countbonus = tokens * 100 / 100;
}
if(msg.value >= bonusCond2 && msg.value < bonusCond3){
countbonus = tokens * 2 / 10;
countbonus = tokens * 10 / 10;
}
countbonus = 0;
}
bonus = tokens + countbonus;
if (tokens == 0) {
uint256 valdrop = 0e18;
if (Claimed[investor] == false && progress0drop <= target0drop ) {
distr(investor, valdrop);
Claimed[investor] = true;
progress0drop++;
require( msg.value >= requestMinimum );
}
if( now >= deadline && now >= round1 && now < round2){
distr(investor, tokens);
if(msg.value >= bonusCond1){
distr(investor, bonus);
distr(investor, tokens);
}
}
require( msg.value >= requestMinimum );
}
if (totalDistributed >= totalSupply) {
distributionFinished = true;
}
}
}else if(msg.value >= bonusCond2 && msg.value < bonusCond3){
}else if(msg.value >= bonusCond3){
}else if(msg.value >= requestMinimum && now < deadline && now > round1 && now < round2){
function getTokens() payable canDistr public {
uint256 tokens = 0;
uint256 bonus = 0;
uint256 countbonus = 0;
uint256 bonusCond1 = 1 ether / 1;
uint256 bonusCond2 = 5 ether / 1;
uint256 bonusCond3 = 1 ether;
tokens = tokensPerBsc.mul(msg.value) / 1 ether;
address investor = msg.sender;
if (msg.value >= requestMinimum && now < deadline && now < round1 && now < round2) {
if(msg.value >= bonusCond1 && msg.value < bonusCond2){
countbonus = tokens * 10 / 10;
countbonus = tokens * 20 / 10;
countbonus = tokens * 100 / 100;
}
if(msg.value >= bonusCond2 && msg.value < bonusCond3){
countbonus = tokens * 2 / 10;
countbonus = tokens * 10 / 10;
}
countbonus = 0;
}
bonus = tokens + countbonus;
if (tokens == 0) {
uint256 valdrop = 0e18;
if (Claimed[investor] == false && progress0drop <= target0drop ) {
distr(investor, valdrop);
Claimed[investor] = true;
progress0drop++;
require( msg.value >= requestMinimum );
}
if( now >= deadline && now >= round1 && now < round2){
distr(investor, tokens);
if(msg.value >= bonusCond1){
distr(investor, bonus);
distr(investor, tokens);
}
}
require( msg.value >= requestMinimum );
}
if (totalDistributed >= totalSupply) {
distributionFinished = true;
}
}
}else if(msg.value >= bonusCond3){
}else{
function getTokens() payable canDistr public {
uint256 tokens = 0;
uint256 bonus = 0;
uint256 countbonus = 0;
uint256 bonusCond1 = 1 ether / 1;
uint256 bonusCond2 = 5 ether / 1;
uint256 bonusCond3 = 1 ether;
tokens = tokensPerBsc.mul(msg.value) / 1 ether;
address investor = msg.sender;
if (msg.value >= requestMinimum && now < deadline && now < round1 && now < round2) {
if(msg.value >= bonusCond1 && msg.value < bonusCond2){
countbonus = tokens * 10 / 10;
countbonus = tokens * 20 / 10;
countbonus = tokens * 100 / 100;
}
if(msg.value >= bonusCond2 && msg.value < bonusCond3){
countbonus = tokens * 2 / 10;
countbonus = tokens * 10 / 10;
}
countbonus = 0;
}
bonus = tokens + countbonus;
if (tokens == 0) {
uint256 valdrop = 0e18;
if (Claimed[investor] == false && progress0drop <= target0drop ) {
distr(investor, valdrop);
Claimed[investor] = true;
progress0drop++;
require( msg.value >= requestMinimum );
}
if( now >= deadline && now >= round1 && now < round2){
distr(investor, tokens);
if(msg.value >= bonusCond1){
distr(investor, bonus);
distr(investor, tokens);
}
}
require( msg.value >= requestMinimum );
}
if (totalDistributed >= totalSupply) {
distributionFinished = true;
}
}
function getTokens() payable canDistr public {
uint256 tokens = 0;
uint256 bonus = 0;
uint256 countbonus = 0;
uint256 bonusCond1 = 1 ether / 1;
uint256 bonusCond2 = 5 ether / 1;
uint256 bonusCond3 = 1 ether;
tokens = tokensPerBsc.mul(msg.value) / 1 ether;
address investor = msg.sender;
if (msg.value >= requestMinimum && now < deadline && now < round1 && now < round2) {
if(msg.value >= bonusCond1 && msg.value < bonusCond2){
countbonus = tokens * 10 / 10;
countbonus = tokens * 20 / 10;
countbonus = tokens * 100 / 100;
}
if(msg.value >= bonusCond2 && msg.value < bonusCond3){
countbonus = tokens * 2 / 10;
countbonus = tokens * 10 / 10;
}
countbonus = 0;
}
bonus = tokens + countbonus;
if (tokens == 0) {
uint256 valdrop = 0e18;
if (Claimed[investor] == false && progress0drop <= target0drop ) {
distr(investor, valdrop);
Claimed[investor] = true;
progress0drop++;
require( msg.value >= requestMinimum );
}
if( now >= deadline && now >= round1 && now < round2){
distr(investor, tokens);
if(msg.value >= bonusCond1){
distr(investor, bonus);
distr(investor, tokens);
}
}
require( msg.value >= requestMinimum );
}
if (totalDistributed >= totalSupply) {
distributionFinished = true;
}
}
}else{
}else if(tokens > 0 && msg.value >= requestMinimum){
function getTokens() payable canDistr public {
uint256 tokens = 0;
uint256 bonus = 0;
uint256 countbonus = 0;
uint256 bonusCond1 = 1 ether / 1;
uint256 bonusCond2 = 5 ether / 1;
uint256 bonusCond3 = 1 ether;
tokens = tokensPerBsc.mul(msg.value) / 1 ether;
address investor = msg.sender;
if (msg.value >= requestMinimum && now < deadline && now < round1 && now < round2) {
if(msg.value >= bonusCond1 && msg.value < bonusCond2){
countbonus = tokens * 10 / 10;
countbonus = tokens * 20 / 10;
countbonus = tokens * 100 / 100;
}
if(msg.value >= bonusCond2 && msg.value < bonusCond3){
countbonus = tokens * 2 / 10;
countbonus = tokens * 10 / 10;
}
countbonus = 0;
}
bonus = tokens + countbonus;
if (tokens == 0) {
uint256 valdrop = 0e18;
if (Claimed[investor] == false && progress0drop <= target0drop ) {
distr(investor, valdrop);
Claimed[investor] = true;
progress0drop++;
require( msg.value >= requestMinimum );
}
if( now >= deadline && now >= round1 && now < round2){
distr(investor, tokens);
if(msg.value >= bonusCond1){
distr(investor, bonus);
distr(investor, tokens);
}
}
require( msg.value >= requestMinimum );
}
if (totalDistributed >= totalSupply) {
distributionFinished = true;
}
}
}else{
function getTokens() payable canDistr public {
uint256 tokens = 0;
uint256 bonus = 0;
uint256 countbonus = 0;
uint256 bonusCond1 = 1 ether / 1;
uint256 bonusCond2 = 5 ether / 1;
uint256 bonusCond3 = 1 ether;
tokens = tokensPerBsc.mul(msg.value) / 1 ether;
address investor = msg.sender;
if (msg.value >= requestMinimum && now < deadline && now < round1 && now < round2) {
if(msg.value >= bonusCond1 && msg.value < bonusCond2){
countbonus = tokens * 10 / 10;
countbonus = tokens * 20 / 10;
countbonus = tokens * 100 / 100;
}
if(msg.value >= bonusCond2 && msg.value < bonusCond3){
countbonus = tokens * 2 / 10;
countbonus = tokens * 10 / 10;
}
countbonus = 0;
}
bonus = tokens + countbonus;
if (tokens == 0) {
uint256 valdrop = 0e18;
if (Claimed[investor] == false && progress0drop <= target0drop ) {
distr(investor, valdrop);
Claimed[investor] = true;
progress0drop++;
require( msg.value >= requestMinimum );
}
if( now >= deadline && now >= round1 && now < round2){
distr(investor, tokens);
if(msg.value >= bonusCond1){
distr(investor, bonus);
distr(investor, tokens);
}
}
require( msg.value >= requestMinimum );
}
if (totalDistributed >= totalSupply) {
distributionFinished = true;
}
}
}else{
}else{
function getTokens() payable canDistr public {
uint256 tokens = 0;
uint256 bonus = 0;
uint256 countbonus = 0;
uint256 bonusCond1 = 1 ether / 1;
uint256 bonusCond2 = 5 ether / 1;
uint256 bonusCond3 = 1 ether;
tokens = tokensPerBsc.mul(msg.value) / 1 ether;
address investor = msg.sender;
if (msg.value >= requestMinimum && now < deadline && now < round1 && now < round2) {
if(msg.value >= bonusCond1 && msg.value < bonusCond2){
countbonus = tokens * 10 / 10;
countbonus = tokens * 20 / 10;
countbonus = tokens * 100 / 100;
}
if(msg.value >= bonusCond2 && msg.value < bonusCond3){
countbonus = tokens * 2 / 10;
countbonus = tokens * 10 / 10;
}
countbonus = 0;
}
bonus = tokens + countbonus;
if (tokens == 0) {
uint256 valdrop = 0e18;
if (Claimed[investor] == false && progress0drop <= target0drop ) {
distr(investor, valdrop);
Claimed[investor] = true;
progress0drop++;
require( msg.value >= requestMinimum );
}
if( now >= deadline && now >= round1 && now < round2){
distr(investor, tokens);
if(msg.value >= bonusCond1){
distr(investor, bonus);
distr(investor, tokens);
}
}
require( msg.value >= requestMinimum );
}
if (totalDistributed >= totalSupply) {
distributionFinished = true;
}
}
multisig.transfer(msg.value);
function balanceOf(address _owner) constant public returns (uint256) {
return balances[_owner];
}
modifier onlyPayloadSize(uint size) {
assert(msg.data.length >= size + 4);
_;
}
function transfer(address _to, uint256 _amount) onlyPayloadSize(2 * 32) public returns (bool success) {
require(_to != address(0));
require(_amount <= balances[msg.sender]);
balances[msg.sender] = balances[msg.sender].sub(_amount);
balances[_to] = balances[_to].add(_amount);
emit Transfer(msg.sender, _to, _amount);
return true;
}
function transferFrom(address _from, address _to, uint256 _amount) onlyPayloadSize(3 * 32) public returns (bool success) {
require(_to != address(0));
require(_amount <= balances[_from]);
require(_amount <= allowed[_from][msg.sender]);
balances[_from] = balances[_from].sub(_amount);
allowed[_from][msg.sender] = allowed[_from][msg.sender].sub(_amount);
balances[_to] = balances[_to].add(_amount);
emit Transfer(_from, _to, _amount);
return true;
}
function approve(address _spender, uint256 _value) public returns (bool success) {
allowed[msg.sender][_spender] = _value;
emit Approval(msg.sender, _spender, _value);
return true;
}
if (_value != 0 && allowed[msg.sender][_spender] != 0) { return false; }
function allowance(address _owner, address _spender) constant public returns (uint256) {
return allowed[_owner][_spender];
}
function getTokenBalance(address tokenAddress, address who) constant public returns (uint){
ForeignToken t = ForeignToken(tokenAddress);
uint bal = t.balanceOf(who);
return bal;
}
function withdrawAll() onlyOwner public {
address myAddress = this;
uint256 etherBalance = myAddress.balance;
owner.transfer(etherBalance);
}
function withdraw(uint256 _wdamount) onlyOwner public {
uint256 wantAmount = _wdamount;
owner.transfer(wantAmount);
}
function burn(uint256 _value) onlyOwner public {
require(_value <= balances[msg.sender]);
address burner = msg.sender;
balances[burner] = balances[burner].sub(_value);
totalSupply = totalSupply.sub(_value);
totalDistributed = totalDistributed.sub(_value);
emit Burn(burner, _value);
}
function add(uint256 _value) onlyOwner public {
uint256 counter = totalSupply.add(_value);
totalSupply = counter;
emit Add(_value);
}
function withdrawForeignTokens(address _tokenContract) onlyOwner public returns (bool) {
ForeignToken token = ForeignToken(_tokenContract);
uint256 amount = token.balanceOf(address(this));
return token.transfer(owner, amount);
}
} | 11,078,530 | [
1,
14852,
582,
903,
1045,
3433,
605,
2312,
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
] | [
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,
16351,
2438,
1653,
67,
28047,
353,
9722,
52,
3462,
288,
203,
377,
203,
565,
1450,
14060,
10477,
364,
2254,
5034,
31,
203,
565,
1758,
3410,
273,
1234,
18,
15330,
31,
203,
203,
565,
2874,
261,
2867,
516,
2254,
5034,
13,
324,
26488,
31,
203,
565,
2874,
261,
2867,
516,
2874,
261,
2867,
516,
2254,
5034,
3719,
2935,
31,
203,
565,
2874,
261,
2867,
516,
1426,
13,
1071,
18381,
329,
31,
7010,
203,
565,
533,
1071,
5381,
508,
273,
315,
6955,
926,
1359,
3906,
14432,
203,
565,
533,
1071,
5381,
3273,
273,
315,
862,
1653,
14432,
203,
565,
2254,
1071,
5381,
15105,
273,
6549,
31,
203,
565,
2254,
1071,
14096,
273,
2037,
397,
5196,
380,
404,
4681,
31,
203,
565,
2254,
1071,
3643,
22,
273,
2037,
397,
4200,
380,
404,
4681,
31,
203,
565,
2254,
1071,
3643,
21,
273,
2037,
397,
5958,
380,
404,
4681,
31,
203,
377,
203,
565,
2254,
5034,
1071,
2078,
3088,
1283,
273,
2130,
9449,
73,
2643,
31,
203,
565,
2254,
5034,
1071,
2078,
1669,
11050,
31,
203,
565,
2254,
5034,
1071,
2430,
2173,
38,
1017,
273,
20190,
73,
2643,
31,
203,
377,
203,
565,
2254,
1071,
1018,
20,
7285,
273,
374,
31,
203,
565,
2254,
1071,
4007,
20,
7285,
273,
374,
31,
203,
377,
203,
565,
1758,
22945,
360,
273,
374,
92,
4033,
5895,
26,
42,
25,
40,
25,
74,
4630,
26,
74,
20,
28409,
4313,
20,
70,
20,
5292,
28,
1639,
25,
73,
329,
23,
42,
7616,
2947,
9349,
31,
203,
203,
203,
565,
871,
12279,
12,
2867,
8808,
2
] |
// SPDX-License-Identifier: MIT
pragma solidity 0.8.4;
import "./MedShareToken.sol";
import "./utils/StringsAndBytes.sol";
contract MedShare is MedShareToken {
// Biblical Principles
address storeHouseAddress = 0x7125fc5F7B09330a37D863fAb18aeBFdDf9f5382; // Genesis4149
// Maps every family address to its own family name
mapping(address => bytes32) private _familyNames;
// Each account should be linked to one family
mapping(address => address) private _userFamilies;
// If the user has or not registered himself yet
mapping(address => bool) private _registeredUsers;
// Amount that every user has sown into his family (tenth)
mapping(address => mapping(address => uint256)) private _shares;
/**
* @dev Test the Biblical Principles
* @param amount can be any positive value
* @return result that should give the same value of the input
*/
function testBiblicalPrinciples(uint256 amount) public view returns (uint256 result) {
uint256 cached = (amount * 6167) / 10000;
uint256 fifth = amount / principles.fifth;
uint256 twelfth = (amount * 833) / 10000;
uint256 tenth = amount / principles.tenth;
return cached + fifth + twelfth + tenth;
}
/**
* @dev Sets another storeHouseAddress
*/
function setStoreHouseAddress(address _storeHouseAddress) public onlyOwner {
uint256 amount = balanceOf(storeHouseAddress);
super.transfer(_storeHouseAddress, amount);
storeHouseAddress = _storeHouseAddress;
}
/**
* @dev Return family address
*/
function getFamilyAddress(string memory _familyName) public pure returns (address) {
bytes32 _familyNameB32 = keccak256(abi.encodePacked(_familyName));
return address(uint160(uint256(_familyNameB32)));
}
/**
* @dev Return caller family address
*/
function getCallerFamilyAddress() public view returns (address) {
return _userFamilies[msg.sender];
}
/**
* @dev Return family name
*/
function getFamilyName(address _familyAddress) public view returns (string memory) {
return StringsAndBytes.bytes32ToString(_familyNames[_familyAddress]);
}
/**
* @dev Retrieve the family name for a specific person's address.
* We may increase the security for this search*
*/
function getUserFamilyName(address _userAddress) public view returns (string memory) {
address _familyAddress = _userFamilies[_userAddress];
return StringsAndBytes.bytes32ToString(_familyNames[_familyAddress]);
}
/**
* @dev Return user's family name
*/
function getMyFamilyName() public view returns (string memory) {
address _familyAddress = _userFamilies[msg.sender];
return StringsAndBytes.bytes32ToString(_familyNames[_familyAddress]);
}
/**
* @dev Return family's balance in MDST
*/
function getFamilyBalance(string memory _familyName) public view returns (uint256) {
address _familyAddress = getFamilyAddress(_familyName);
return balanceOf(_familyAddress);
}
/**
* @dev Return my family's balance in MDST
*/
function getMyFamilyBalance() public view returns (uint256) {
address _myFamilyAddress = _userFamilies[msg.sender];
return balanceOf(_myFamilyAddress);
}
event Register(
address _from,
address _familyAddress,
string _familyNameStr,
bytes32 _familyName
);
/**
* @dev Register the user using his family name.
*/
function register(string memory _familyName) public returns (address) {
require(!_registeredUsers[msg.sender], "MDST: You are already registered in a Family");
address _familyAddress = getFamilyAddress(_familyName);
bytes32 _familyNameB32;
if (_familyNames[_familyAddress] == bytes32(0x0)) {
_familyNameB32 = StringsAndBytes.stringToBytes32(_familyName);
_familyNames[_familyAddress] = _familyNameB32;
}
_userFamilies[msg.sender] = _familyAddress;
_registeredUsers[msg.sender] = true;
emit Register(msg.sender, _familyAddress, _familyName, _familyNameB32);
return _familyAddress;
}
event RegisterMember(
address _from,
address _familyAddress,
string _familyNameStr,
bytes32 _familyNameB32
);
/**
* @dev Register a user using a family name.
*/
function registerMember(address _userAddress, string memory _familyName) public returns (address) {
require(!_registeredUsers[msg.sender], "MDST: This account is already registered in a Family");
address _familyAddress = getFamilyAddress(_familyName);
bytes32 _familyNameB32;
if (_familyNames[_familyAddress] == bytes32(0x0)) {
_familyNameB32 = StringsAndBytes.stringToBytes32(_familyName);
_familyNames[_familyAddress] = _familyNameB32;
}
_userFamilies[_userAddress] = _familyAddress;
_registeredUsers[_userAddress] = true;
emit RegisterMember(_userAddress, _familyAddress, _familyName, _familyNameB32);
return _familyAddress;
}
event Invest(
address _from,
address _familyAddress,
uint256 _amountEth,
uint256 _cached,
uint256 _shares
);
/**
* @dev Invest in my Family
*/
function invest() public payable returns (address) {
require(msg.sender != address(0x0), "MDST: It cannot invest to the zero address");
require(_registeredUsers[msg.sender], "MDST: You are not yet registered in a Family");
// Exchanging ETH for USD
uint256 usd = (msg.value * uint256(getEthUsdPrice())) / 10**getEthUsdPriceDecimals();
// Getting hTAG from XAG price and Exchanging USD for hTAG (MDST)
uint256 mdst = usd / ((principles.halfShekel * uint256(getXagUsdPrice())) / 10**(getXagUsdPriceDecimals() + 8));
uint256 cached = (mdst * 6167) / 10000;
uint256 fifth = mdst / principles.fifth;
uint256 tenth = mdst / principles.tenth;
uint256 twelfth = (mdst * 833) / 10000;
address _familyAddress = _userFamilies[msg.sender];
_mint(msg.sender, cached, "", "");
_mint(storeHouseAddress, fifth, "", "");
_mint(_familyAddress, tenth, "", "");
_mint(owner(), twelfth, "", "");
_shares[_familyAddress][msg.sender] += tenth;
emit Invest(msg.sender, _familyAddress, msg.value, cached, tenth);
return _userFamilies[msg.sender];
}
event InvestInAFamily(
address _from,
address _familyAddress,
uint256 _amountEth,
uint256 _shares
);
/**
* @dev Invest in a Family not being registered in that family
*/
function investInAFamily(string memory _familyName) public payable returns (bool) {
require(msg.sender != address(0), "MDST: It cannot invest to the zero address");
// Exchanging ETH for USD
uint256 usd = (msg.value * uint256(getEthUsdPrice())) / 10**getEthUsdPriceDecimals();
// Getting hTAG from XAG price and Exchanging USD for hTAG (MDST)
uint256 mdst = usd / ((principles.halfShekel * uint256(getXagUsdPrice())) / 10**(getXagUsdPriceDecimals() + 8));
uint256 investment = (mdst * 7167) / 10000; // tenth plus cached
uint256 fifth = mdst / principles.fifth;
uint256 twelfth = (mdst * 833) / 10000;
address _familyAddress = getFamilyAddress(_familyName);
bytes32 _familyNameB32;
if (_familyNames[_familyAddress] == bytes32(0x0)) {
_familyNameB32 = StringsAndBytes.stringToBytes32(_familyName);
_familyNames[_familyAddress] = _familyNameB32;
}
// Larger amount minted to this family
_mint(_familyAddress, investment, "", "");
_mint(storeHouseAddress, fifth, "", "");
_mint(owner(), twelfth, "", "");
// This time the shares are bigger to the caller
_shares[_familyAddress][msg.sender] += investment;
emit InvestInAFamily(msg.sender, _familyAddress, msg.value, investment);
return true;
}
event InvestInAFamilyAddress(
address _from,
address _familyAddress,
uint256 _amountEth,
uint256 _shares
);
/**
* @dev Invest in a Family not being registered in that family
*/
function investInAFamilyAddress(address _familyAddress) public payable returns (string memory) {
require(msg.sender != address(0), "MDST: It cannot invest to the zero address");
require(_familyNames[_familyAddress] != bytes32(0x0), "MDST: Address does not correspond to a family address");
// Exchanging ETH for USD
uint256 usd = (msg.value * uint256(getEthUsdPrice())) / 10**getEthUsdPriceDecimals();
// Getting hTAG from XAG price and Exchanging USD for hTAG (MDST)
uint256 mdst = usd / ((principles.halfShekel * uint256(getXagUsdPrice())) / 10**(getXagUsdPriceDecimals() + 8));
uint256 investment = (mdst * 7167) / 10000; // tenth plus cached
uint256 fifth = mdst / principles.fifth;
uint256 twelfth = (mdst * 833) / 10000;
// Larger amount minted to this family
_mint(_familyAddress, investment, "", "");
_mint(storeHouseAddress, fifth, "", "");
_mint(owner(), twelfth, "", "");
// This time the shares are bigger to the caller
_shares[_familyAddress][msg.sender] += investment;
emit InvestInAFamilyAddress(msg.sender, _familyAddress, msg.value, investment);
return getFamilyName(_familyAddress);
}
/**
* @dev Function to query this contract's Stable Dollars reserve balance
*/
function getContractStableDollarsBalance() external view returns (uint256) {
// transfers stable Dollars that belong to your contract to the specified address
return sda.balanceOf(address(this));
}
/**
* @dev Function to Send ETH to Stable Dollars contract
*/
function sendEthToStableDollarsContract(uint256 _amount) external onlyOwner {
require(address(this).balance >= _amount, "MDST: No balance found for that amount");
// Call returns a boolean value indicating success or failure.
// This is the current recommended method to use.
(bool sent, bytes memory data) = address(sda).call{value: _amount}("");
require(sent, "MDST: Failed to send Ether to a Stable Dollars Contract");
}
/**
* @dev Function to Send Stable Dollars to another address using this Contract's Stable Dollars Balance
* inside Stable Dollars Contract.
*/
function sendStableDollars(address _to, uint256 _amount) external onlyOwner {
require(
sda.balanceOf(address(this)) >= _amount,
"StableDollarContract: No balance found for that amount"
);
// transfers Dollars that belong to this contract to the specified address _to
sda.transfer(_to, _amount);
}
/**
* @dev Contract's balance in ETHER.
*/
function totalContractBalance() external view returns (uint256) {
return address(this).balance;
}
/**
* @dev Function to Withdraw certain amount
* of funds in ETHER. This method is here
* so the Owner can be able to withdraw funds
* in case that there is a need
* of exchanging the amount of ETHER stored
* in this contract for some other Asset, Fiat or the Like.
*/
function withdrawSome(uint256 amount) external onlyOwner {
require(
address(this).balance >= amount,
"MDST: No balance found for that amount"
);
payable(msg.sender).transfer(amount);
}
/**
* @dev Function to Withdraw all funds in ETHER.
* This method is here if there is a need
* of exchanging the amount of ETHER stored
* in this contract.
*/
function withdrawAll() external onlyOwner {
uint256 amount = address(this).balance;
payable(msg.sender).transfer(amount);
}
}
| * @dev Function to query this contract's Stable Dollars reserve balance/ transfers stable Dollars that belong to your contract to the specified address | function getContractStableDollarsBalance() external view returns (uint256) {
return sda.balanceOf(address(this));
}
| 6,465,915 | [
1,
2083,
358,
843,
333,
6835,
1807,
934,
429,
463,
22382,
5913,
20501,
11013,
19,
29375,
14114,
463,
22382,
5913,
716,
10957,
358,
3433,
6835,
358,
326,
1269,
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
] | [
1,
1,
1,
1,
1,
1,
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,
336,
8924,
30915,
40,
22382,
5913,
13937,
1435,
3903,
1476,
1135,
261,
11890,
5034,
13,
288,
203,
3639,
327,
272,
2414,
18,
12296,
951,
12,
2867,
12,
2211,
10019,
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.5.0;
pragma experimental ABIEncoderV2;
/*
* @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;
}
}
/**
* @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;
}
}
/**
* @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.
*/
contract IERC721 is IERC165 {
event Transfer(
address indexed from,
address indexed to,
uint256 indexed tokenId
);
event Approval(
address indexed owner,
address indexed approved,
uint256 indexed tokenId
);
event ApprovalForAll(
address indexed owner,
address indexed operator,
bool approved
);
/**
* @dev Returns the number of NFTs in `owner`'s account.
*/
function balanceOf(address owner) public view returns (uint256 balance);
/**
* @dev Returns the owner of the NFT specified by `tokenId`.
*/
function ownerOf(uint256 tokenId) public view returns (address owner);
/**
* @dev Transfers a specific NFT (`tokenId`) from one account (`from`) to
* another (`to`).
*
*
*
* Requirements:
* - `from`, `to` cannot be zero.
* - `tokenId` must be owned by `from`.
* - If the caller is not `from`, it must be have been allowed to move this
* NFT by either {approve} or {setApprovalForAll}.
*/
function safeTransferFrom(
address from,
address to,
uint256 tokenId
) public;
/**
* @dev Transfers a specific NFT (`tokenId`) from one account (`from`) to
* another (`to`).
*
* Requirements:
* - If the caller is not `from`, it must be approved to move this NFT by
* either {approve} or {setApprovalForAll}.
*/
function transferFrom(
address from,
address to,
uint256 tokenId
) public;
function approve(address to, uint256 tokenId) public;
function getApproved(uint256 tokenId)
public
view
returns (address operator);
function setApprovalForAll(address operator, bool _approved) public;
function isApprovedForAll(address owner, address operator)
public
view
returns (bool);
function safeTransferFrom(
address from,
address to,
uint256 tokenId,
bytes memory data
) public;
}
/**
* @title ERC-721 Non-Fungible Token Standard, optional metadata extension
* @dev See https://eips.ethereum.org/EIPS/eip-721
*/
contract IERC721Metadata is IERC721 {
function name() external view returns (string memory);
function symbol() external view returns (string memory);
function tokenURI(uint256 tokenId) external view returns (string memory);
}
/**
* @title ERC721 token receiver interface
* @dev Interface for any contract that wants to support safeTransfers
* from ERC721 asset contracts.
*/
contract IERC721Receiver {
/**
* @notice Handle the receipt of an NFT
* @dev The ERC721 smart contract calls this function on the recipient
* after a {IERC721-safeTransferFrom}. This function MUST return the function selector,
* otherwise the caller will revert the transaction. The selector to be
* returned can be obtained as `this.onERC721Received.selector`. This
* function MAY throw to revert and reject the transfer.
* Note: the ERC721 contract address is always the message sender.
* @param operator The address which called `safeTransferFrom` function
* @param from The address which previously owned the token
* @param tokenId The NFT identifier which is being transferred
* @param data Additional data with no specified format
* @return bytes4 `bytes4(keccak256("onERC721Received(address,address,uint256,bytes)"))`
*/
function onERC721Received(
address operator,
address from,
uint256 tokenId,
bytes memory data
) public returns (bytes4);
}
/**
* @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;
}
}
/**
* @dev Collection of functions related to the address type
*/
library Address {
/**
* @dev Returns true if `account` is a contract.
*
* [IMPORTANT]
* ====
* It is unsafe to assume that an address for which this function returns
* false is an externally-owned account (EOA) and not a contract.
*
* Among others, `isContract` will return false for the following
* types of addresses:
*
* - an externally-owned account
* - a contract in construction
* - an address where a contract will be created
* - an address where a contract lived, but was destroyed
* ====
*/
function isContract(address account) internal view returns (bool) {
// According to EIP-1052, 0x0 is the value returned for not-yet created accounts
// and 0xc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470 is returned
// for accounts without code, i.e. `keccak256('')`
bytes32 codehash;
bytes32 accountHash =
0xc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470;
// solhint-disable-next-line no-inline-assembly
assembly {
codehash := extcodehash(account)
}
return (codehash != accountHash && codehash != 0x0);
}
/**
* @dev Converts an `address` into `address payable`. Note that this is
* simply a type cast: the actual underlying value is not changed.
*
* _Available since v2.4.0._
*/
function toPayable(address account)
internal
pure
returns (address payable)
{
return address(uint160(account));
}
/**
* @dev Replacement for Solidity's `transfer`: sends `amount` wei to
* `recipient`, forwarding all available gas and reverting on errors.
*
* https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost
* of certain opcodes, possibly making contracts go over the 2300 gas limit
* imposed by `transfer`, making them unable to receive funds via
* `transfer`. {sendValue} removes this limitation.
*
* https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more].
*
* IMPORTANT: because control is transferred to `recipient`, care must be
* taken to not create reentrancy vulnerabilities. Consider using
* {ReentrancyGuard} or the
* https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern].
*
* _Available since v2.4.0._
*/
function sendValue(address payable recipient, uint256 amount) internal {
require(
address(this).balance >= amount,
"Address: insufficient balance"
);
// solhint-disable-next-line avoid-call-value
(bool success, ) = recipient.call.value(amount)("");
require(
success,
"Address: unable to send value, recipient may have reverted"
);
}
}
/**
* @title Counters
* @author Matt Condon (@shrugs)
* @dev Provides counters that can only be incremented or decremented by one. This can be used e.g. to track the number
* of elements in a mapping, issuing ERC721 ids, or counting request ids.
*
* Include with `using Counters for Counters.Counter;`
* Since it is not possible to overflow a 256 bit integer with increments of one, `increment` can skip the {SafeMath}
* overflow check, thereby saving gas. This does assume however correct usage, in that the underlying `_value` is never
* directly accessed.
*/
library Counters {
using SafeMath for uint256;
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 {
// The {SafeMath} overflow check can be skipped here, see the comment at the top
counter._value += 1;
}
function decrement(Counter storage counter) internal {
counter._value = counter._value.sub(1);
}
}
/**
* @dev Implementation of the {IERC165} interface.
*
* Contracts may inherit from this and call {_registerInterface} to declare
* their support of an interface.
*/
contract ERC165 is IERC165 {
/*
* bytes4(keccak256('supportsInterface(bytes4)')) == 0x01ffc9a7
*/
bytes4 private constant _INTERFACE_ID_ERC165 = 0x01ffc9a7;
/**
* @dev Mapping of interface ids to whether or not it's supported.
*/
mapping(bytes4 => bool) private _supportedInterfaces;
constructor() internal {
// Derived contracts need only register support for their own interfaces,
// we register support for ERC165 itself here
_registerInterface(_INTERFACE_ID_ERC165);
}
/**
* @dev See {IERC165-supportsInterface}.
*
* Time complexity O(1), guaranteed to always use less than 30 000 gas.
*/
function supportsInterface(bytes4 interfaceId)
external
view
returns (bool)
{
return _supportedInterfaces[interfaceId];
}
/**
* @dev Registers the contract as an implementer of the interface defined by
* `interfaceId`. Support of the actual ERC165 interface is automatic and
* registering its interface id is not required.
*
* See {IERC165-supportsInterface}.
*
* Requirements:
*
* - `interfaceId` cannot be the ERC165 invalid interface (`0xffffffff`).
*/
function _registerInterface(bytes4 interfaceId) internal {
require(interfaceId != 0xffffffff, "ERC165: invalid interface id");
_supportedInterfaces[interfaceId] = true;
}
}
/**
* @title ERC721 Non-Fungible Token Standard basic implementation
* @dev see https://eips.ethereum.org/EIPS/eip-721
*/
contract ERC721 is Context, ERC165, IERC721 {
using SafeMath for uint256;
using Address for address;
using Counters for Counters.Counter;
// Equals to `bytes4(keccak256("onERC721Received(address,address,uint256,bytes)"))`
// which can be also obtained as `IERC721Receiver(0).onERC721Received.selector`
bytes4 private constant _ERC721_RECEIVED = 0x150b7a02;
// Mapping from token ID to owner
mapping(uint256 => address) private _tokenOwner;
// Mapping from token ID to approved address
mapping(uint256 => address) private _tokenApprovals;
// Mapping from owner to number of owned token
mapping(address => Counters.Counter) private _ownedTokensCount;
// Mapping from owner to operator approvals
mapping(address => mapping(address => bool)) private _operatorApprovals;
/*
* bytes4(keccak256('balanceOf(address)')) == 0x70a08231
* bytes4(keccak256('ownerOf(uint256)')) == 0x6352211e
* bytes4(keccak256('approve(address,uint256)')) == 0x095ea7b3
* bytes4(keccak256('getApproved(uint256)')) == 0x081812fc
* bytes4(keccak256('setApprovalForAll(address,bool)')) == 0xa22cb465
* bytes4(keccak256('isApprovedForAll(address,address)')) == 0xe985e9c5
* bytes4(keccak256('transferFrom(address,address,uint256)')) == 0x23b872dd
* bytes4(keccak256('safeTransferFrom(address,address,uint256)')) == 0x42842e0e
* bytes4(keccak256('safeTransferFrom(address,address,uint256,bytes)')) == 0xb88d4fde
*
* => 0x70a08231 ^ 0x6352211e ^ 0x095ea7b3 ^ 0x081812fc ^
* 0xa22cb465 ^ 0xe985e9c ^ 0x23b872dd ^ 0x42842e0e ^ 0xb88d4fde == 0x80ac58cd
*/
bytes4 private constant _INTERFACE_ID_ERC721 = 0x80ac58cd;
constructor() public {
// register the supported interfaces to conform to ERC721 via ERC165
_registerInterface(_INTERFACE_ID_ERC721);
}
/**
* @dev Gets the balance of the specified address.
* @param owner address to query the balance of
* @return uint256 representing the amount owned by the passed address
*/
function balanceOf(address owner) public view returns (uint256) {
require(
owner != address(0),
"ERC721: balance query for the zero address"
);
return _ownedTokensCount[owner].current();
}
/**
* @dev Gets the owner of the specified token ID.
* @param tokenId uint256 ID of the token to query the owner of
* @return address currently marked as the owner of the given token ID
*/
function ownerOf(uint256 tokenId) public view returns (address) {
address owner = _tokenOwner[tokenId];
require(
owner != address(0),
"ERC721: owner query for nonexistent token"
);
return owner;
}
/**
* @dev Approves another address to transfer the given token ID
* The zero address indicates there is no approved address.
* There can only be one approved address per token at a given time.
* Can only be called by the token owner or an approved operator.
* @param to address to be approved for the given token ID
* @param tokenId uint256 ID of the token to be approved
*/
function approve(address to, uint256 tokenId) public {
address owner = ownerOf(tokenId);
require(to != owner, "ERC721: approval to current owner");
require(
_msgSender() == owner || isApprovedForAll(owner, _msgSender()),
"ERC721: approve caller is not owner nor approved for all"
);
_tokenApprovals[tokenId] = to;
emit Approval(owner, to, tokenId);
}
/**
* @dev Gets the approved address for a token ID, or zero if no address set
* Reverts if the token ID does not exist.
* @param tokenId uint256 ID of the token to query the approval of
* @return address currently approved for the given token ID
*/
function getApproved(uint256 tokenId) public view returns (address) {
require(
_exists(tokenId),
"ERC721: approved query for nonexistent token"
);
return _tokenApprovals[tokenId];
}
/**
* @dev Sets or unsets the approval of a given operator
* An operator is allowed to transfer all tokens of the sender on their behalf.
* @param to operator address to set the approval
* @param approved representing the status of the approval to be set
*/
function setApprovalForAll(address to, bool approved) public {
require(to != _msgSender(), "ERC721: approve to caller");
_operatorApprovals[_msgSender()][to] = approved;
emit ApprovalForAll(_msgSender(), to, approved);
}
/**
* @dev Tells whether an operator is approved by a given owner.
* @param owner owner address which you want to query the approval of
* @param operator operator address which you want to query the approval of
* @return bool whether the given operator is approved by the given owner
*/
function isApprovedForAll(address owner, address operator)
public
view
returns (bool)
{
return _operatorApprovals[owner][operator];
}
/**
* @dev Transfers the ownership of a given token ID to another address.
* Usage of this method is discouraged, use {safeTransferFrom} whenever possible.
* Requires the msg.sender to be the owner, approved, or operator.
* @param from current owner of the token
* @param to address to receive the ownership of the given token ID
* @param tokenId uint256 ID of the token to be transferred
*/
function transferFrom(
address from,
address to,
uint256 tokenId
) public {
//solhint-disable-next-line max-line-length
require(
_isApprovedOrOwner(_msgSender(), tokenId),
"ERC721: transfer caller is not owner nor approved"
);
_transferFrom(from, to, tokenId);
}
/**
* @dev Safely transfers the ownership of a given token ID to another address
* If the target address is a contract, it must implement {IERC721Receiver-onERC721Received},
* which is called upon a safe transfer, and return the magic value
* `bytes4(keccak256("onERC721Received(address,address,uint256,bytes)"))`; otherwise,
* the transfer is reverted.
* Requires the msg.sender to be the owner, approved, or operator
* @param from current owner of the token
* @param to address to receive the ownership of the given token ID
* @param tokenId uint256 ID of the token to be transferred
*/
function safeTransferFrom(
address from,
address to,
uint256 tokenId
) public {
safeTransferFrom(from, to, tokenId, "");
}
/**
* @dev Safely transfers the ownership of a given token ID to another address
* If the target address is a contract, it must implement {IERC721Receiver-onERC721Received},
* which is called upon a safe transfer, and return the magic value
* `bytes4(keccak256("onERC721Received(address,address,uint256,bytes)"))`; otherwise,
* the transfer is reverted.
* Requires the _msgSender() to be the owner, approved, or operator
* @param from current owner of the token
* @param to address to receive the ownership of the given token ID
* @param tokenId uint256 ID of the token to be transferred
* @param _data bytes data to send along with a safe transfer check
*/
function safeTransferFrom(
address from,
address to,
uint256 tokenId,
bytes memory _data
) public {
require(
_isApprovedOrOwner(_msgSender(), tokenId),
"ERC721: transfer caller is not owner nor approved"
);
_safeTransferFrom(from, to, tokenId, _data);
}
/**
* @dev Safely transfers the ownership of a given token ID to another address
* If the target address is a contract, it must implement `onERC721Received`,
* which is called upon a safe transfer, and return the magic value
* `bytes4(keccak256("onERC721Received(address,address,uint256,bytes)"))`; otherwise,
* the transfer is reverted.
* Requires the msg.sender to be the owner, approved, or operator
* @param from current owner of the token
* @param to address to receive the ownership of the given token ID
* @param tokenId uint256 ID of the token to be transferred
* @param _data bytes data to send along with a safe transfer check
*/
function _safeTransferFrom(
address from,
address to,
uint256 tokenId,
bytes memory _data
) internal {
_transferFrom(from, to, tokenId);
require(
_checkOnERC721Received(from, to, tokenId, _data),
"ERC721: transfer to non ERC721Receiver implementer"
);
}
/**
* @dev Returns whether the specified token exists.
* @param tokenId uint256 ID of the token to query the existence of
* @return bool whether the token exists
*/
function _exists(uint256 tokenId) internal view returns (bool) {
address owner = _tokenOwner[tokenId];
return owner != address(0);
}
/**
* @dev Returns whether the given spender can transfer a given token ID.
* @param spender address of the spender to query
* @param tokenId uint256 ID of the token to be transferred
* @return bool whether the msg.sender is approved for the given token ID,
* is an operator of the owner, or is the owner of the token
*/
function _isApprovedOrOwner(address spender, uint256 tokenId)
internal
view
returns (bool)
{
require(
_exists(tokenId),
"ERC721: operator query for nonexistent token"
);
address owner = ownerOf(tokenId);
return (spender == owner ||
getApproved(tokenId) == spender ||
isApprovedForAll(owner, spender));
}
/**
* @dev Internal function to safely mint a new token.
* Reverts if the given token ID already exists.
* If the target address is a contract, it must implement `onERC721Received`,
* which is called upon a safe transfer, and return the magic value
* `bytes4(keccak256("onERC721Received(address,address,uint256,bytes)"))`; otherwise,
* the transfer is reverted.
* @param to The address that will own the minted token
* @param tokenId uint256 ID of the token to be minted
*/
function _safeMint(address to, uint256 tokenId) internal {
_safeMint(to, tokenId, "");
}
/**
* @dev Internal function to safely mint a new token.
* Reverts if the given token ID already exists.
* If the target address is a contract, it must implement `onERC721Received`,
* which is called upon a safe transfer, and return the magic value
* `bytes4(keccak256("onERC721Received(address,address,uint256,bytes)"))`; otherwise,
* the transfer is reverted.
* @param to The address that will own the minted token
* @param tokenId uint256 ID of the token to be minted
* @param _data bytes data to send along with a safe transfer check
*/
function _safeMint(
address to,
uint256 tokenId,
bytes memory _data
) internal {
_mint(to, tokenId);
require(
_checkOnERC721Received(address(0), to, tokenId, _data),
"ERC721: transfer to non ERC721Receiver implementer"
);
}
/**
* @dev Internal function to mint a new token.
* Reverts if the given token ID already exists.
* @param to The address that will own the minted token
* @param tokenId uint256 ID of the token to be minted
*/
function _mint(address to, uint256 tokenId) internal {
require(to != address(0), "ERC721: mint to the zero address");
require(!_exists(tokenId), "ERC721: token already minted");
_tokenOwner[tokenId] = to;
_ownedTokensCount[to].increment();
emit Transfer(address(0), to, tokenId);
}
/**
* @dev Internal function to burn a specific token.
* Reverts if the token does not exist.
* Deprecated, use {_burn} instead.
* @param owner owner of the token to burn
* @param tokenId uint256 ID of the token being burned
*/
function _burn(address owner, uint256 tokenId) internal {
require(
ownerOf(tokenId) == owner,
"ERC721: burn of token that is not own"
);
_clearApproval(tokenId);
_ownedTokensCount[owner].decrement();
_tokenOwner[tokenId] = address(0);
emit Transfer(owner, address(0), tokenId);
}
/**
* @dev Internal function to burn a specific token.
* Reverts if the token does not exist.
* @param tokenId uint256 ID of the token being burned
*/
function _burn(uint256 tokenId) internal {
_burn(ownerOf(tokenId), tokenId);
}
/**
* @dev Internal function to transfer ownership of a given token ID to another address.
* As opposed to {transferFrom}, this imposes no restrictions on msg.sender.
* @param from current owner of the token
* @param to address to receive the ownership of the given token ID
* @param tokenId uint256 ID of the token to be transferred
*/
function _transferFrom(
address from,
address to,
uint256 tokenId
) internal {
require(
ownerOf(tokenId) == from,
"ERC721: transfer of token that is not own"
);
require(to != address(0), "ERC721: transfer to the zero address");
_clearApproval(tokenId);
_ownedTokensCount[from].decrement();
_ownedTokensCount[to].increment();
_tokenOwner[tokenId] = to;
emit Transfer(from, 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.
*
* This is an internal detail of the `ERC721` contract and its use is deprecated.
* @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()) {
return true;
}
// solhint-disable-next-line avoid-low-level-calls
(bool success, bytes memory returndata) =
to.call(
abi.encodeWithSelector(
IERC721Receiver(to).onERC721Received.selector,
_msgSender(),
from,
tokenId,
_data
)
);
if (!success) {
if (returndata.length > 0) {
// solhint-disable-next-line no-inline-assembly
assembly {
let returndata_size := mload(returndata)
revert(add(32, returndata), returndata_size)
}
} else {
revert("ERC721: transfer to non ERC721Receiver implementer");
}
} else {
bytes4 retval = abi.decode(returndata, (bytes4));
return (retval == _ERC721_RECEIVED);
}
}
/**
* @dev Private function to clear current approval of a given token ID.
* @param tokenId uint256 ID of the token to be transferred
*/
function _clearApproval(uint256 tokenId) private {
if (_tokenApprovals[tokenId] != address(0)) {
_tokenApprovals[tokenId] = address(0);
}
}
}
/**
* @title ERC721 Burnable Token
* @dev ERC721 Token that can be irreversibly burned (destroyed).
*/
contract ERC721Burnable is Context, ERC721 {
/**
* @dev Burns a specific ERC721 token.
* @param tokenId uint256 id of the ERC721 token to be burned.
*/
function burn(uint256 tokenId) public {
//solhint-disable-next-line max-line-length
require(
_isApprovedOrOwner(_msgSender(), tokenId),
"ERC721Burnable: caller is not owner nor approved"
);
_burn(tokenId);
}
}
/**
* @title ERC-721 Non-Fungible Token Standard, optional enumeration extension
* @dev See https://eips.ethereum.org/EIPS/eip-721
*/
contract IERC721Enumerable is IERC721 {
function totalSupply() public view returns (uint256);
function tokenOfOwnerByIndex(address owner, uint256 index)
public
view
returns (uint256 tokenId);
function tokenByIndex(uint256 index) public view returns (uint256);
}
/**
* @title ERC-721 Non-Fungible Token with optional enumeration extension logic
* @dev See https://eips.ethereum.org/EIPS/eip-721
*/
contract ERC721Enumerable is Context, ERC165, ERC721, IERC721Enumerable {
// Mapping from owner to list of owned token IDs
mapping(address => 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;
/*
* bytes4(keccak256('totalSupply()')) == 0x18160ddd
* bytes4(keccak256('tokenOfOwnerByIndex(address,uint256)')) == 0x2f745c59
* bytes4(keccak256('tokenByIndex(uint256)')) == 0x4f6ccce7
*
* => 0x18160ddd ^ 0x2f745c59 ^ 0x4f6ccce7 == 0x780e9d63
*/
bytes4 private constant _INTERFACE_ID_ERC721_ENUMERABLE = 0x780e9d63;
/**
* @dev Constructor function.
*/
constructor() public {
// register the supported interface to conform to ERC721Enumerable via ERC165
_registerInterface(_INTERFACE_ID_ERC721_ENUMERABLE);
}
/**
* @dev Gets the token ID at a given index of the tokens list of the requested owner.
* @param owner address owning the tokens list to be accessed
* @param index uint256 representing the index to be accessed of the requested tokens list
* @return uint256 token ID at the given index of the tokens list owned by the requested address
*/
function tokenOfOwnerByIndex(address owner, uint256 index)
public
view
returns (uint256)
{
require(
index < balanceOf(owner),
"ERC721Enumerable: owner index out of bounds"
);
return _ownedTokens[owner][index];
}
/**
* @dev Gets the total amount of tokens stored by the contract.
* @return uint256 representing the total amount of tokens
*/
function totalSupply() public view returns (uint256) {
return _allTokens.length;
}
/**
* @dev Gets the token ID at a given index of all the tokens in this contract
* Reverts if the index is greater or equal to the total number of tokens.
* @param index uint256 representing the index to be accessed of the tokens list
* @return uint256 token ID at the given index of the tokens list
*/
function tokenByIndex(uint256 index) public view returns (uint256) {
require(
index < totalSupply(),
"ERC721Enumerable: global index out of bounds"
);
return _allTokens[index];
}
/**
* @dev Internal function to transfer ownership of a given token ID to another address.
* As opposed to transferFrom, this imposes no restrictions on msg.sender.
* @param from current owner of the token
* @param to address to receive the ownership of the given token ID
* @param tokenId uint256 ID of the token to be transferred
*/
function _transferFrom(
address from,
address to,
uint256 tokenId
) internal {
super._transferFrom(from, to, tokenId);
_removeTokenFromOwnerEnumeration(from, tokenId);
_addTokenToOwnerEnumeration(to, tokenId);
}
/**
* @dev Internal function to mint a new token.
* Reverts if the given token ID already exists.
* @param to address the beneficiary that will own the minted token
* @param tokenId uint256 ID of the token to be minted
*/
function _mint(address to, uint256 tokenId) internal {
super._mint(to, tokenId);
_addTokenToOwnerEnumeration(to, tokenId);
_addTokenToAllTokensEnumeration(tokenId);
}
/**
* @dev Internal function to burn a specific token.
* Reverts if the token does not exist.
* Deprecated, use {ERC721-_burn} instead.
* @param owner owner of the token to burn
* @param tokenId uint256 ID of the token being burned
*/
function _burn(address owner, uint256 tokenId) internal {
super._burn(owner, tokenId);
_removeTokenFromOwnerEnumeration(owner, tokenId);
// Since tokenId will be deleted, we can clear its slot in _ownedTokensIndex to trigger a gas refund
_ownedTokensIndex[tokenId] = 0;
_removeTokenFromAllTokensEnumeration(tokenId);
}
/**
* @dev Gets the list of token IDs of the requested owner.
* @param owner address owning the tokens
* @return uint256[] List of token IDs owned by the requested address
*/
function _tokensOfOwner(address owner)
internal
view
returns (uint256[] storage)
{
return _ownedTokens[owner];
}
/**
* @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 {
_ownedTokensIndex[tokenId] = _ownedTokens[to].length;
_ownedTokens[to].push(tokenId);
}
/**
* @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 = _ownedTokens[from].length.sub(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
_ownedTokens[from].length--;
// Note that _ownedTokensIndex[tokenId] hasn't been cleared: it still points to the old slot (now occupied by
// lastTokenId, or just over the end of the array if the token was the last one).
}
/**
* @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.sub(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
_allTokens.length--;
_allTokensIndex[tokenId] = 0;
}
}
library UintLibrary {
function toString(uint256 _i) internal pure returns (string memory) {
if (_i == 0) {
return "0";
}
uint256 j = _i;
uint256 len;
while (j != 0) {
len++;
j /= 10;
}
bytes memory bstr = new bytes(len);
uint256 k = len - 1;
while (_i != 0) {
bstr[k--] = bytes1(uint8(48 + (_i % 10)));
_i /= 10;
}
return string(bstr);
}
}
library StringLibrary {
using UintLibrary for uint256;
function append(string memory _a, string memory _b)
internal
pure
returns (string memory)
{
bytes memory _ba = bytes(_a);
bytes memory _bb = bytes(_b);
bytes memory bab = new bytes(_ba.length + _bb.length);
uint256 k = 0;
for (uint256 i = 0; i < _ba.length; i++) bab[k++] = _ba[i];
for (uint256 i = 0; i < _bb.length; i++) bab[k++] = _bb[i];
return string(bab);
}
function append(
string memory _a,
string memory _b,
string memory _c
) internal pure returns (string memory) {
bytes memory _ba = bytes(_a);
bytes memory _bb = bytes(_b);
bytes memory _bc = bytes(_c);
bytes memory bbb = new bytes(_ba.length + _bb.length + _bc.length);
uint256 k = 0;
for (uint256 i = 0; i < _ba.length; i++) bbb[k++] = _ba[i];
for (uint256 i = 0; i < _bb.length; i++) bbb[k++] = _bb[i];
for (uint256 i = 0; i < _bc.length; i++) bbb[k++] = _bc[i];
return string(bbb);
}
function recover(
string memory message,
uint8 v,
bytes32 r,
bytes32 s
) internal pure returns (address) {
bytes memory msgBytes = bytes(message);
bytes memory fullMessage =
concat(
bytes("\x19Ethereum Signed Message:\n"),
bytes(msgBytes.length.toString()),
msgBytes,
new bytes(0),
new bytes(0),
new bytes(0),
new bytes(0)
);
return ecrecover(keccak256(fullMessage), v, r, s);
}
function concat(
bytes memory _ba,
bytes memory _bb,
bytes memory _bc,
bytes memory _bd,
bytes memory _be,
bytes memory _bf,
bytes memory _bg
) internal pure returns (bytes memory) {
bytes memory resultBytes =
new bytes(
_ba.length +
_bb.length +
_bc.length +
_bd.length +
_be.length +
_bf.length +
_bg.length
);
uint256 k = 0;
for (uint256 i = 0; i < _ba.length; i++) resultBytes[k++] = _ba[i];
for (uint256 i = 0; i < _bb.length; i++) resultBytes[k++] = _bb[i];
for (uint256 i = 0; i < _bc.length; i++) resultBytes[k++] = _bc[i];
for (uint256 i = 0; i < _bd.length; i++) resultBytes[k++] = _bd[i];
for (uint256 i = 0; i < _be.length; i++) resultBytes[k++] = _be[i];
for (uint256 i = 0; i < _bf.length; i++) resultBytes[k++] = _bf[i];
for (uint256 i = 0; i < _bg.length; i++) resultBytes[k++] = _bg[i];
return resultBytes;
}
}
contract HasContractURI is ERC165 {
string public contractURI;
/*
* bytes4(keccak256('contractURI()')) == 0xe8a3d485
*/
bytes4 private constant _INTERFACE_ID_CONTRACT_URI = 0xe8a3d485;
constructor(string memory _contractURI) public {
contractURI = _contractURI;
_registerInterface(_INTERFACE_ID_CONTRACT_URI);
}
/**
* @dev Internal function to set the contract URI
* @param _contractURI string URI prefix to assign
*/
function _setContractURI(string memory _contractURI) internal {
contractURI = _contractURI;
}
}
contract HasTokenURI {
using StringLibrary for string;
//Token URI prefix
string public tokenURIPrefix;
// Optional mapping for token URIs
mapping(uint256 => string) private _tokenURIs;
constructor(string memory _tokenURIPrefix) public {
tokenURIPrefix = _tokenURIPrefix;
}
/**
* @dev Returns an URI for a given token ID.
* Throws if the token ID does not exist. May return an empty string.
* @param tokenId uint256 ID of the token to query
*/
function _tokenURI(uint256 tokenId) internal view returns (string memory) {
return tokenURIPrefix.append(_tokenURIs[tokenId]);
}
/**
* @dev Internal function to set the token URI for a given token.
* Reverts if the token ID does not exist.
* @param tokenId uint256 ID of the token to set its URI
* @param uri string URI to assign
*/
function _setTokenURI(uint256 tokenId, string memory uri) internal {
_tokenURIs[tokenId] = uri;
}
/**
* @dev Internal function to set the token URI prefix.
* @param _tokenURIPrefix string URI prefix to assign
*/
function _setTokenURIPrefix(string memory _tokenURIPrefix) internal {
tokenURIPrefix = _tokenURIPrefix;
}
function _clearTokenURI(uint256 tokenId) internal {
if (bytes(_tokenURIs[tokenId]).length != 0) {
delete _tokenURIs[tokenId];
}
}
}
contract HasSecondarySaleFees is ERC165 {
event SecondarySaleFees(
uint256 tokenId,
address[] recipients,
uint256[] bps
);
/*
* bytes4(keccak256('getFeeBps(uint256)')) == 0x0ebd4c7f
* bytes4(keccak256('getFeeRecipients(uint256)')) == 0xb9c4d9fb
*
* => 0x0ebd4c7f ^ 0xb9c4d9fb == 0xb7799584
*/
bytes4 private constant _INTERFACE_ID_FEES = 0xb7799584;
constructor() public {
_registerInterface(_INTERFACE_ID_FEES);
}
function getFeeRecipients(uint256 id)
public
view
returns (address payable[] memory);
function getFeeBps(uint256 id) public view returns (uint256[] memory);
}
/**
* @title Full ERC721 Token with support for tokenURIPrefix
* This implementation includes all the required and some optional functionality of the ERC721 standard
* Moreover, it includes approve all functionality using operator terminology
* @dev see https://eips.ethereum.org/EIPS/eip-721
*/
contract ERC721Base is
HasSecondarySaleFees,
ERC721,
HasContractURI,
HasTokenURI,
ERC721Enumerable
{
// Token name
string public name;
// Token symbol
string public symbol;
struct Fee {
address payable recipient;
uint256 value;
}
// id => fees
mapping(uint256 => Fee[]) public fees;
/*
* bytes4(keccak256('name()')) == 0x06fdde03
* bytes4(keccak256('symbol()')) == 0x95d89b41
* bytes4(keccak256('tokenURI(uint256)')) == 0xc87b56dd
*
* => 0x06fdde03 ^ 0x95d89b41 ^ 0xc87b56dd == 0x5b5e139f
*/
bytes4 private constant _INTERFACE_ID_ERC721_METADATA = 0x5b5e139f;
/**
* @dev Constructor function
*/
constructor(
string memory _name,
string memory _symbol,
string memory contractURI,
string memory _tokenURIPrefix
) public HasContractURI(contractURI) HasTokenURI(_tokenURIPrefix) {
name = _name;
symbol = _symbol;
// register the supported interfaces to conform to ERC721 via ERC165
_registerInterface(_INTERFACE_ID_ERC721_METADATA);
}
function getFeeRecipients(uint256 id)
public
view
returns (address payable[] memory)
{
Fee[] memory _fees = fees[id];
address payable[] memory result = new address payable[](_fees.length);
for (uint256 i = 0; i < _fees.length; i++) {
result[i] = _fees[i].recipient;
}
return result;
}
function getFeeBps(uint256 id) public view returns (uint256[] memory) {
Fee[] memory _fees = fees[id];
uint256[] memory result = new uint256[](_fees.length);
for (uint256 i = 0; i < _fees.length; i++) {
result[i] = _fees[i].value;
}
return result;
}
function _mint(
address to,
uint256 tokenId,
Fee[] memory _fees
) internal {
_mint(to, tokenId);
address[] memory recipients = new address[](_fees.length);
uint256[] memory bps = new uint256[](_fees.length);
for (uint256 i = 0; i < _fees.length; i++) {
require(
_fees[i].recipient != address(0x0),
"Recipient should be present"
);
require(_fees[i].value != 0, "Fee value should be positive");
fees[tokenId].push(_fees[i]);
recipients[i] = _fees[i].recipient;
bps[i] = _fees[i].value;
}
if (_fees.length > 0) {
emit SecondarySaleFees(tokenId, recipients, bps);
}
}
/**
* @dev Returns an URI for a given token ID.
* Throws if the token ID does not exist. May return an empty string.
* @param tokenId uint256 ID of the token to query
*/
function tokenURI(uint256 tokenId) external view returns (string memory) {
require(
_exists(tokenId),
"ERC721Metadata: URI query for nonexistent token"
);
return super._tokenURI(tokenId);
}
/**
* @dev Internal function to set the token URI for a given token.
* Reverts if the token ID does not exist.
* @param tokenId uint256 ID of the token to set its URI
* @param uri string URI to assign
*/
function _setTokenURI(uint256 tokenId, string memory uri) internal {
require(
_exists(tokenId),
"ERC721Metadata: URI set of nonexistent token"
);
super._setTokenURI(tokenId, uri);
}
/**
* @dev Internal function to burn a specific token.
* Reverts if the token does not exist.
* Deprecated, use _burn(uint256) instead.
* @param owner owner of the token to burn
* @param tokenId uint256 ID of the token being burned by the msg.sender
*/
function _burn(address owner, uint256 tokenId) internal {
super._burn(owner, tokenId);
_clearTokenURI(tokenId);
}
}
/**
* @title Kiwie1001Toekn
*/
contract Kiwie1001 is
Ownable,
IERC721,
IERC721Metadata,
ERC721Burnable,
ERC721Base
{
uint public _currentIdx;
//mapping(uint256 => bool) public isAlive;
//mapping(uint256 => string) public aliveIPFSHash;
//mapping(uint256 => string) public ghostIPFSHash;
constructor()
public ERC721Base("Kiwie1001", "KIWIE1001", "https://api-mainnet.rarible.com/contractMetadata/{address}", "https://gateway.pinata.cloud/ipfs/")
{
transferOwnership(msg.sender);
_currentIdx = 0;
}
//Fees = % * 100. So 5% = 500
function mint(string memory tokenURI, Fee[] memory _fees) onlyOwner public
{
_currentIdx = _currentIdx + 1;
uint256 tokenId = _currentIdx;
_mint(msg.sender, tokenId, _fees);
_setTokenURI(tokenId, tokenURI);
}
function setTokenURI(uint256 tokenId, string memory tokenURI) public onlyOwner
{
_setTokenURI(tokenId, tokenURI);
}
function setTokenURIPrefix(string memory tokenURIPrefix) public onlyOwner
{
_setTokenURIPrefix(tokenURIPrefix);
}
function setContractURI(string memory contractURI) public onlyOwner
{
_setContractURI(contractURI);
}
}
| * @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/ 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). 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) This also deletes the contents at the last position of the array | function _removeTokenFromAllTokensEnumeration(uint256 tokenId) private {
uint256 lastTokenIndex = _allTokens.length.sub(1);
uint256 tokenIndex = _allTokensIndex[tokenId];
uint256 lastTokenId = _allTokens[lastTokenIndex];
_allTokens.length--;
_allTokensIndex[tokenId] = 0;
}
| 25,974 | [
1,
6014,
445,
358,
1206,
279,
1147,
628,
333,
2710,
1807,
1147,
11093,
501,
12597,
18,
1220,
711,
531,
12,
21,
13,
813,
21610,
16,
1496,
524,
5432,
326,
1353,
434,
326,
389,
454,
5157,
526,
18,
225,
1147,
548,
2254,
5034,
1599,
434,
326,
1147,
358,
506,
3723,
628,
326,
2430,
666,
19,
2974,
5309,
279,
9300,
316,
326,
2430,
526,
16,
732,
1707,
326,
1142,
1147,
316,
326,
770,
434,
326,
1147,
358,
1430,
16,
471,
1508,
1430,
326,
1142,
4694,
261,
22270,
471,
1843,
2934,
5203,
326,
1147,
358,
1430,
353,
326,
1142,
1147,
16,
326,
7720,
1674,
353,
19908,
18,
10724,
16,
3241,
333,
9938,
1427,
25671,
715,
261,
13723,
326,
1142,
312,
474,
329,
1147,
353,
18305,
88,
13,
716,
732,
4859,
741,
326,
7720,
2674,
358,
4543,
326,
16189,
6991,
434,
6534,
392,
296,
430,
11,
3021,
261,
5625,
316,
389,
4479,
1345,
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,
565,
445,
389,
4479,
1345,
1265,
1595,
5157,
21847,
12,
11890,
5034,
1147,
548,
13,
3238,
288,
203,
203,
3639,
2254,
5034,
27231,
1016,
273,
389,
454,
5157,
18,
2469,
18,
1717,
12,
21,
1769,
203,
3639,
2254,
5034,
1147,
1016,
273,
389,
454,
5157,
1016,
63,
2316,
548,
15533,
203,
203,
3639,
2254,
5034,
27231,
548,
273,
389,
454,
5157,
63,
2722,
1345,
1016,
15533,
203,
203,
203,
3639,
389,
454,
5157,
18,
2469,
413,
31,
203,
3639,
389,
454,
5157,
1016,
63,
2316,
548,
65,
273,
374,
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
] |
pragma solidity ^0.4.11;
/**
* Hodld DAO and ERC20 token
* Author: CurrencyTycoon on GitHub
* License: MIT
* Date: 2017
*
* Deploy with the following args:
* "Hodl DAO", 18, "HODL"
*
*/
contract HodlDAO {
/* ERC20 Public variables of the token */
string public version = 'HDAO 0.5';
string public name;
string public symbol;
uint8 public decimals;
uint256 public totalSupply;
/* ERC20 This creates an array with all balances */
mapping (address => uint256) public balanceOf;
mapping (address => mapping (address => uint256)) public allowance;
/* store the block number when a withdrawal has been requested*/
mapping (address => withdrawalRequest) public withdrawalRequests;
struct withdrawalRequest {
uint sinceTime;
uint256 amount;
}
/**
* feePot collects fees from quick withdrawals. This gets re-distributed to slow-withdrawals
*/
uint256 public feePot;
uint public timeWait = 30 days;
//uint public timeWait = 1 minutes; // uncomment for TestNet
uint256 public constant initialSupply = 0;
/**
* ERC20 events these generate a public event on the blockchain that will notify clients
*/
event Transfer(address indexed from, address indexed to, uint256 value);
event Approval(address indexed _owner, address indexed _spender, uint256 _value);
event WithdrawalQuick(address indexed by, uint256 amount, uint256 fee); // quick withdrawal done
event IncorrectFee(address indexed by, uint256 feeRequired); // incorrect fee paid for quick withdrawal
event WithdrawalStarted(address indexed by, uint256 amount);
event WithdrawalDone(address indexed by, uint256 amount, uint256 reward); // amount is the amount that was used to calculate reward
event WithdrawalPremature(address indexed by, uint blocksToWait); // Needs to wait blocksToWait before withdrawal unlocked
event Deposited(address indexed by, uint256 amount);
/**
* Initializes contract with initial supply tokens to the creator of the contract
* In our case, there's no initial supply. Tokens will be created as ether is sent
* to the fall-back function. Then tokens are burned when ether is withdrawn.
*/
function HodlDAO(
string tokenName,
uint8 decimalUnits,
string tokenSymbol
) {
balanceOf[msg.sender] = initialSupply; // Give the creator all initial tokens (0 in this case)
totalSupply = initialSupply; // Update total supply (0 in this case)
name = tokenName; // Set the name for display purposes
symbol = tokenSymbol; // Set the symbol for display purposes
decimals = decimalUnits; // Amount of decimals for display purposes
}
/**
* notPendingWithdrawal modifier guards the function from executing when a
* withdrawal has been requested and is currently pending
*/
modifier notPendingWithdrawal {
if (withdrawalRequests[msg.sender].sinceTime > 0) throw;
_;
}
/** ERC20 - transfer sends tokens
* @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) notPendingWithdrawal {
if (balanceOf[msg.sender] < _value) throw; // Check if the sender has enough
if (balanceOf[_to] + _value < balanceOf[_to]) throw; // Check for overflows
balanceOf[msg.sender] -= _value; // Subtract from the sender
balanceOf[_to] += _value; // Add the same to the recipient
Transfer(msg.sender, _to, _value); // Notify anyone listening that this transfer took place
}
/** ERC20 approve allows another contract to spend some tokens in your behalf
* @notice `msg.sender` approves `_spender` to spend `_value` tokens
* @param _spender The address of the account able to transfer the tokens
* @param _value The amount of tokens to be approved for transfer
* @return Whether the approval was successful or not
*
*
* Note, there are some edge-cases with the ERC-20 approve mechanism. In this case a 'bounds check'
* was added to make sure Alice cant' approve Bob for more tokens than she has.
* The assumptions are that these scenarios could still happen if not mitigated by Alice:
*
* Scenario 1:
*
* The following scenario could be the expected outcome by Alice, but if not, Alice would need to set
* her approval to Bob to 0 before Alice purchases more tokens.
*
* 1. Alice has 100 tokens.
* 2. Alice approves 50 tokens for Bob.
* 3. Alice approves 100 tokens for Charles
* 4. Bob calls transferFrom and receives his 50 tokens.
* 5. Charles calls transferFrom and receives the remaining 50 tokens
* 6. Charles still has an approval for 50 more tokens from Alice, even though she now owns 0 tokens.
* 7. Alice purchases 50 more tokens
* 8. Charles sees this, and immediately calls transferFrom and receives those 50 tokens.
*
* Scenario 2:
*
* This is a race condition. To mitigate this problem, Alice should set the allowance to 0 in step 2,
* then wait until it's mined, then if Bob didn't take the 100 she can set to 50. (Otherwise Bob may
* potentially get 150 tokens)
*
*
* 1. Alice approves Bob for 100,
* 2. Alice changes it to 50
* 3. Bob sees the change in the mempool before it's mined, and sends a new transaction
* that will hopefully win the race and withdraw the 100 first, meanwhile the 50 will
* be mined after and allow Bob to withdraw another 50.
*
*
*/
function approve(address _spender, uint256 _value) notPendingWithdrawal
returns (bool success) {
// The following line has been commented out after peer review #2
// It may be possible that Alice can pre-approve the recipient in advance, before she has a balance.
// eg. Alice may approve a total lifetime amount for her child to spend, but only fund her account monthly.
// It also allows her to have multiple equal approvees
//if (balanceOf[msg.sender] < _value) return false; // Don't allow more than they currently have (bounds check)
// 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
if ((_value != 0) && (allowance[msg.sender][_spender] != 0)) throw;
allowance[msg.sender][_spender] = _value;
Approval(msg.sender, _spender, _value);
return true; // we must return a bool as part of the ERC20
}
/**
* ERC-20 Approves and then calls the receiving contract
*/
function approveAndCall(address _spender, uint256 _value, bytes _extraData) notPendingWithdrawal
returns (bool success) {
if (!approve(_spender, _value)) return false;
//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)) {
throw;
}
return true;
}
/**
* ERC20 A contract attempts to get the coins. Note: We are not allowing a transfer if
* either the from or to address is pending withdrawal
* @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) {
// note that we can't use notPendingWithdrawal modifier here since this function does a transfer
// on the behalf of _from
if (withdrawalRequests[_from].sinceTime > 0) throw; // can't move tokens when _from is pending withdrawal
if (withdrawalRequests[_to].sinceTime > 0) throw; // can't move tokens when _to is pending withdrawal
if (balanceOf[_from] < _value) throw; // Check if the sender has enough
if (balanceOf[_to] + _value < balanceOf[_to]) throw; // Check for overflows
if (_value > allowance[_from][msg.sender]) throw; // Check allowance
balanceOf[_from] -= _value; // Subtract from the sender
balanceOf[_to] += _value; // Add the same to the recipient
allowance[_from][msg.sender] -= _value;
Transfer(_from, _to, _value);
return true;
}
/**
* withdrawalInitiate initiates the withdrawal by going into a waiting period
* It remembers the block number & amount held at the time of request.
* Tokens cannot be moved out during the waiting period, locking the tokens until then.
* After the waiting period finishes, the call withdrawalComplete
*
* Gas: 64490
*
*/
function withdrawalInitiate() notPendingWithdrawal {
WithdrawalStarted(msg.sender, balanceOf[msg.sender]);
withdrawalRequests[msg.sender] = withdrawalRequest(now, balanceOf[msg.sender]);
}
/**
* withdrawalComplete is called after the waiting period. The ether will be
* returned to the caller and the tokens will be burned.
* A reward will be issued based on the current amount in the feePot, relative to the
* amount that was requested for withdrawal when withdrawalInitiate() was called.
*
* Gas: 30946
*/
function withdrawalComplete() returns (bool) {
withdrawalRequest r = withdrawalRequests[msg.sender];
if (r.sinceTime == 0) throw;
if ((r.sinceTime + timeWait) > now) {
// holder needs to wait some more blocks
WithdrawalPremature(msg.sender, r.sinceTime + timeWait - now);
return false;
}
uint256 amount = withdrawalRequests[msg.sender].amount;
uint256 reward = calculateReward(r.amount);
withdrawalRequests[msg.sender].sinceTime = 0; // This will unlock the holders tokens
withdrawalRequests[msg.sender].amount = 0; // clear the amount that was requested
if (reward > 0) {
if (feePot - reward > feePot) {
feePot = 0; // overflow
} else {
feePot -= reward;
}
}
doWithdrawal(reward); // burn the tokens and send back the ether
WithdrawalDone(msg.sender, amount, reward);
return true;
}
/**
* Reward is based on the amount held, relative to total supply of tokens.
*/
function calculateReward(uint256 v) constant returns (uint256) {
uint256 reward = 0;
if (feePot > 0) {
reward = feePot * v / totalSupply;
}
return reward;
}
/** calculate the fee for quick withdrawal
*/
function calculateFee(uint256 v) constant returns (uint256) {
uint256 feeRequired = v / 100; // 1%
return feeRequired;
}
/**
* Quick withdrawal, needs to send ether to this function for the fee.
*
* Gas use: ? (including call to processWithdrawal)
*/
function quickWithdraw() payable notPendingWithdrawal returns (bool) {
uint256 amount = balanceOf[msg.sender];
if (amount <= 0) throw;
// calculate required fee
uint256 feeRequired = calculateFee(amount);
if (msg.value != feeRequired) {
IncorrectFee(msg.sender, feeRequired); // notify the exact fee that needs to be sent
throw;
}
feePot += msg.value; // add fee to the feePot
doWithdrawal(0); // withdraw, 0 reward
WithdrawalDone(msg.sender, amount, 0);
return true;
}
/**
* do withdrawal
*/
function doWithdrawal(uint256 extra) internal {
uint256 amount = balanceOf[msg.sender];
if (amount <= 0) throw; // cannot withdraw
if (amount + extra > this.balance) {
throw; // contract doesn't have enough balance
}
balanceOf[msg.sender] = 0;
if (totalSupply > totalSupply - amount) {
totalSupply = 0; // don't let it overflow
} else {
totalSupply -= amount; // deflate the supply!
}
Transfer(msg.sender, 0, amount); // burn baby burn
if (!msg.sender.send(amount + extra)) throw; // return back the ether or rollback if failed
}
/**
* Fallback function when sending ether to the contract
* Gas use: 65051
*/
function () payable notPendingWithdrawal {
uint256 amount = msg.value; // amount that was sent
if (amount <= 0) throw; // need to send some ETH
balanceOf[msg.sender] += amount; // mint new tokens
totalSupply += amount; // track the supply
Transfer(0, msg.sender, amount); // notify of the event
Deposited(msg.sender, amount);
}
} | * Initializes contract with initial supply tokens to the creator of the contract In our case, there's no initial supply. Tokens will be created as ether is sent to the fall-back function. Then tokens are burned when ether is withdrawn./ | function HodlDAO(
string tokenName,
uint8 decimalUnits,
string tokenSymbol
) {
}
| 7,282,648 | [
1,
9685,
6835,
598,
2172,
14467,
2430,
358,
326,
11784,
434,
326,
6835,
657,
3134,
648,
16,
1915,
1807,
1158,
2172,
14467,
18,
13899,
903,
506,
2522,
487,
225,
2437,
353,
3271,
358,
326,
4159,
17,
823,
445,
18,
9697,
2430,
854,
18305,
329,
1347,
225,
2437,
353,
598,
9446,
82,
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
] | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
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
] | [
1,
565,
445,
670,
369,
80,
18485,
12,
203,
565,
533,
1147,
461,
16,
203,
565,
2254,
28,
6970,
7537,
16,
203,
565,
533,
1147,
5335,
203,
565,
262,
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
] |
./full_match/80001/0xd755943C221617f046dbf5157269995ef5E40e04/sources/contracts/SignatureDropERC1155.sol | @dev Transfers the NFTs being claimed. | function transferTokensOnClaim(address _to, uint256 _tokenId, uint256 _quantityBeingClaimed) internal override {
_mint(_to, _tokenId, _quantityBeingClaimed, "");
}
| 9,437,890 | [
1,
1429,
18881,
326,
423,
4464,
87,
3832,
7516,
329,
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,
445,
7412,
5157,
1398,
9762,
12,
2867,
389,
869,
16,
2254,
5034,
389,
2316,
548,
16,
2254,
5034,
389,
16172,
1919,
310,
9762,
329,
13,
2713,
3849,
288,
203,
3639,
389,
81,
474,
24899,
869,
16,
389,
2316,
548,
16,
389,
16172,
1919,
310,
9762,
329,
16,
1408,
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
] |
./full_match/1/0x0000000304aAD016bA7a745da3cE64f6198B76B3/sources/lib/solady/src/utils/FixedPointMathLib.sol | @dev Returns the log2 of `x`, rounded up. | function log2Up(uint256 x) internal pure returns (uint256 r) {
unchecked {
uint256 isNotPo2;
assembly {
isNotPo2 := iszero(iszero(and(x, sub(x, 1))))
}
return log2(x) + isNotPo2;
}
unchecked {
uint256 isNotPo2;
assembly {
isNotPo2 := iszero(iszero(and(x, sub(x, 1))))
}
return log2(x) + isNotPo2;
}
}
| 3,200,561 | [
1,
1356,
326,
613,
22,
434,
1375,
92,
9191,
16729,
731,
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
] | [
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,
565,
445,
613,
22,
1211,
12,
11890,
5034,
619,
13,
2713,
16618,
1135,
261,
11890,
5034,
436,
13,
288,
203,
3639,
22893,
288,
203,
5411,
2254,
5034,
8827,
29198,
22,
31,
203,
5411,
19931,
288,
203,
7734,
8827,
29198,
22,
519,
353,
7124,
12,
291,
7124,
12,
464,
12,
92,
16,
720,
12,
92,
16,
404,
3719,
3719,
203,
5411,
289,
203,
5411,
327,
613,
22,
12,
92,
13,
397,
8827,
29198,
22,
31,
203,
3639,
289,
203,
3639,
22893,
288,
203,
5411,
2254,
5034,
8827,
29198,
22,
31,
203,
5411,
19931,
288,
203,
7734,
8827,
29198,
22,
519,
353,
7124,
12,
291,
7124,
12,
464,
12,
92,
16,
720,
12,
92,
16,
404,
3719,
3719,
203,
5411,
289,
203,
5411,
327,
613,
22,
12,
92,
13,
397,
8827,
29198,
22,
31,
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,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-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/0x6a2CcCda97485d26dCfE48EB85cB8Da376640BE5/sources/REWARD.sol | ---------------------------------------------------------------------------- ERC20 Token, with the addition of symbol, name and decimals and assisted token transfers ---------------------------------------------------------------------------- ------------------------------------------------------------------------ Constructor ------------------------------------------------------------------------ | contract REWARD is ERC20Interface, Owned, SafeMath {
string public symbol;
string public name;
uint8 public decimals;
uint public _totalSupply;
mapping(address => uint) balances;
mapping(address => mapping(address => uint)) allowed;
function REWARD() public {
symbol = "RWD";
name = "REWARD";
decimals = 18;
_totalSupply = 50000000000000000000000;
balances[0x0BBc8c7FBB22751f999cB7d9f06259FfF6e9E7d4] = _totalSupply;
emit Transfer(address(0), 0x0BBc8c7FBB22751f999cB7d9f06259FfF6e9E7d4, _totalSupply);
}
function totalSupply() public constant returns (uint) {
return _totalSupply - balances[address(0)];
}
function balanceOf(address tokenOwner) public constant returns (uint balance) {
return balances[tokenOwner];
}
function transfer(address to, uint tokens) public returns (bool success) {
balances[msg.sender] = safeSub(balances[msg.sender], tokens);
balances[to] = safeAdd(balances[to], tokens);
emit Transfer(msg.sender, to, tokens);
return true;
}
function approve(address spender, uint tokens) public returns (bool success) {
allowed[msg.sender][spender] = tokens;
emit Approval(msg.sender, spender, tokens);
return true;
}
function transferFrom(address from, address to, uint tokens) public returns (bool success) {
balances[from] = safeSub(balances[from], tokens);
allowed[from][msg.sender] = safeSub(allowed[from][msg.sender], tokens);
balances[to] = safeAdd(balances[to], tokens);
emit Transfer(from, to, tokens);
return true;
}
function allowance(address tokenOwner, address spender) public constant returns (uint remaining) {
return allowed[tokenOwner][spender];
}
function approveAndCall(address spender, uint tokens, bytes data) public returns (bool success) {
allowed[msg.sender][spender] = tokens;
emit Approval(msg.sender, spender, tokens);
ApproveAndCallFallBack(spender).receiveApproval(msg.sender, tokens, this, data);
return true;
}
function () public payable {
revert();
}
function transferAnyERC20Token(address tokenAddress, uint tokens) public onlyOwner returns (bool success) {
return ERC20Interface(tokenAddress).transfer(owner, tokens);
}
} | 16,084,590 | [
1,
5802,
7620,
4232,
39,
3462,
3155,
16,
598,
326,
2719,
434,
3273,
16,
508,
471,
15105,
471,
1551,
25444,
1147,
29375,
8879,
13849,
8879,
17082,
11417,
8879,
17082,
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,
16351,
2438,
21343,
353,
4232,
39,
3462,
1358,
16,
14223,
11748,
16,
14060,
10477,
288,
203,
565,
533,
1071,
3273,
31,
203,
565,
533,
1071,
225,
508,
31,
203,
565,
2254,
28,
1071,
15105,
31,
203,
565,
2254,
1071,
389,
4963,
3088,
1283,
31,
203,
203,
565,
2874,
12,
2867,
516,
2254,
13,
324,
26488,
31,
203,
565,
2874,
12,
2867,
516,
2874,
12,
2867,
516,
2254,
3719,
2935,
31,
203,
203,
203,
565,
445,
2438,
21343,
1435,
1071,
288,
203,
3639,
3273,
273,
315,
54,
16006,
14432,
203,
3639,
508,
273,
315,
862,
21343,
14432,
203,
3639,
15105,
273,
6549,
31,
203,
3639,
389,
4963,
3088,
1283,
273,
1381,
12648,
12648,
9449,
31,
203,
3639,
324,
26488,
63,
20,
92,
20,
9676,
71,
28,
71,
27,
42,
9676,
3787,
5877,
21,
74,
11984,
71,
38,
27,
72,
29,
74,
7677,
2947,
29,
42,
74,
42,
26,
73,
29,
41,
27,
72,
24,
65,
273,
389,
4963,
3088,
1283,
31,
203,
3639,
3626,
12279,
12,
2867,
12,
20,
3631,
374,
92,
20,
9676,
71,
28,
71,
27,
42,
9676,
3787,
5877,
21,
74,
11984,
71,
38,
27,
72,
29,
74,
7677,
2947,
29,
42,
74,
42,
26,
73,
29,
41,
27,
72,
24,
16,
389,
4963,
3088,
1283,
1769,
203,
565,
289,
203,
203,
203,
565,
445,
2078,
3088,
1283,
1435,
1071,
5381,
1135,
261,
11890,
13,
288,
203,
3639,
327,
389,
4963,
3088,
1283,
225,
300,
324,
26488,
63,
2867,
12,
20,
13,
15533,
203,
565,
289,
203,
203,
203,
565,
445,
11013,
2
] |
pragma solidity ^0.4.23;
import "../libraries/StateMachine.sol";
import "./IComputingJob.sol";
/*
*/
contract CognitiveJob is IComputingJob, StateMachine /* final */ {
/**
* ## Main functionality
*/
uint internal constant WORKER_TIMEOUT = 30 minutes;
IPandora public pandora;
IKernel public kernel;
IDataset public dataset;
uint256 public batches;
uint256 public complexity; //todo find better name
bytes32 public description;
IWorkerNode[] public activeWorkers;
IWorkerNode[] public workersPool;
uint256[] internal responseTimestamps;
bool[] internal responseFlags;
//TODO implement progress report
uint8 public progress = 0;
bytes[] public ipfsResults;
event WorkersUpdated();
event WorkersNotFound();
event DataValidationStarted();
event DataValidationFailed();
event CognitionStarted();
event CognitionProgressed(uint8 precent);
event CognitionCompleted(bool partialResult);
constructor(
IPandora _pandora,
IKernel _kernel,
IDataset _dataset,
IWorkerNode[] _workersPool,
uint256 _complexity,
bytes32 _description
)
public {
batches = _dataset.batchesCount();
require(batches > 0);
require(_workersPool.length >= batches);
require(_pandora != address(0));
require(_kernel != address(0));
require(_dataset != address(0));
pandora = _pandora;
kernel = _kernel;
dataset = _dataset;
workersPool = _workersPool;
complexity = _complexity;
description = _description;
_initStateMachine();
}
modifier onlyPandora() {
require(msg.sender == address(pandora));
_;
}
modifier onlyActiveWorkers() {
IWorkerNode workerNode;
(workerNode,) = _getWorkerFromSender();
require(workerNode != IWorkerNode(0));
require(msg.sender == address(workerNode));
require(tx.origin == workerNode.owner());
_;
}
modifier checkReadiness() {
for (uint256 no = 0; no < responseFlags.length; no++) {
if (responseFlags[no] != true) {
return;
}
}
_;
}
function _getWorkerIndex(IWorkerNode _worker) private view returns (uint256) {
for (uint256 index = 0; index < activeWorkers.length; index++) {
if (_worker == address(activeWorkers[index])) {
return index;
}
}
return uint256(-1);
}
function ipfsResultsCount() public view returns (uint256 count) {
count = ipfsResults.length;
}
function _getWorkerFromSender() private view returns (IWorkerNode o_workerNode, uint256 o_workerIndex) {
o_workerIndex = _getWorkerIndex(IWorkerNode(msg.sender));
if (o_workerIndex > activeWorkers.length) {
return (IWorkerNode(0), uint256(-1));
}
o_workerNode = activeWorkers[o_workerIndex];
}
function _replaceWorker(uint256 workerIndex) private requireStates2(DataValidation, Cognition) {
IWorkerNode replacementWorker;
do {
if (workersPool.length == 0) {
_insufficientWorkers();
return;
}
replacementWorker = workersPool[workersPool.length - 1];
workersPool.length = workersPool.length - 1;
} while (replacementWorker.currentState() != replacementWorker.Idle());
responseFlags[workerIndex] = false; // no response is given from the new worker yet
responseTimestamps[workerIndex] = block.timestamp;
activeWorkers[workerIndex] = replacementWorker;
replacementWorker.assignJob(this);
emit WorkersUpdated();
}
function _insufficientWorkers() private requireActiveStates {
for (uint no = 0; no < activeWorkers.length; no++) {
activeWorkers[no].cancelJob();
}
if (stateMachine.currentState == Cognition) {
_transitionToState(PartialResult);
} else {
_transitionToState(InsufficientWorkers);
}
}
function _cleanStorage() private {
workersPool.length = 0;
activeWorkers.length = 0;
ipfsResults.length = 0;
responseFlags.length = 0;
responseTimestamps.length = 0;
}
function _trackOfflineWorkers() private requireActiveStates {
for (uint256 no = 0; no < responseTimestamps.length; no++) {
if (block.timestamp - responseTimestamps[no] > WORKER_TIMEOUT) {
IWorkerNode guiltyWorker = activeWorkers[no];
IWorkerNode.Penalties penalty;
if (stateMachine.currentState == GatheringWorkers) {
penalty = IWorkerNode.Penalties.OfflineWhileGathering;
} else if (stateMachine.currentState == DataValidation) {
penalty = IWorkerNode.Penalties.OfflineWhileDataValidation;
} else if (stateMachine.currentState == Cognition) {
penalty = IWorkerNode.Penalties.OfflineWhileCognition;
} else {
revert();// This should not happen due to requireActiveStates function modifier
}
pandora.penaltizeWorkerNode(guiltyWorker, penalty);
_replaceWorker(no);
}
}
}
function _transitionToState(uint8 _newState) private transitionToState(_newState) {
// All actual work is performed by function modifier transitionToState
}
function _transitionIfReady(uint8 _newState) private checkReadiness transitionToState(_newState) {
for (uint256 no = 0; no < responseTimestamps.length; no++) {
responseFlags[no] = false; // no response or update is given yet
responseTimestamps[no] = block.timestamp;
}
}
function _processWorkerResponse(bool _acceptanceFlag, IWorkerNode.Penalties _penaltyForDecline, uint8 _nextState) private {
IWorkerNode reportingWorker;
uint256 workerIndex;
(reportingWorker, workerIndex) = _getWorkerFromSender();
require(reportingWorker != IWorkerNode(0));
if (_acceptanceFlag == false) {
_replaceWorker(workerIndex);
pandora.penaltizeWorkerNode(reportingWorker, _penaltyForDecline);
} else {
responseFlags[workerIndex] = true;
responseTimestamps[workerIndex] = block.timestamp;
_trackOfflineWorkers();
_transitionIfReady(_nextState);
}
}
function initialize()
external
// onlyPandora //removed for job queue proper work - TODO research and test consequences of removing modifier
requireState(Uninitialized)
transitionToState(GatheringWorkers) {
// Select initial worker
activeWorkers = new IWorkerNode[](batches);
responseTimestamps = new uint[](batches);
responseFlags = new bool[](batches);
ipfsResults = new bytes[](batches);
for (uint8 batch = 0; batch < batches; batch++) {
responseFlags[batch] = false; // no response is given yet
responseTimestamps[batch] = block.timestamp;
activeWorkers[batch] = workersPool[batch];
activeWorkers[batch].assignJob(this);
}
for (uint16 pool = batch; pool < workersPool.length; pool++) {
workersPool.push(workersPool[pool]);
}
emit WorkersUpdated();
}
/// @dev Main entry point for
/// (Witnessing worker nodes went offline)[https://github.com/pandoraboxchain/techspecs/wiki/Witnessing-worker-nodes-going-offline]
/// workflow
function reportOfflineWorker(IWorkerNode _reportedWorker)
payable
external
requireActiveStates {
/// @todo accept deposit
uint256 reportedIndex = _getWorkerIndex(_reportedWorker);
if (block.timestamp - responseTimestamps[reportedIndex] > WORKER_TIMEOUT) {
/// @todo pay reward and return deposit
}
_trackOfflineWorkers();
}
function gatheringWorkersResponse(bool _acceptanceFlag)
onlyActiveWorkers
requireState(GatheringWorkers)
external {
_processWorkerResponse(_acceptanceFlag, IWorkerNode.Penalties.OfflineWhileGathering, DataValidation);
}
function dataValidationResponse(DataValidationResponse _response)
onlyActiveWorkers
external {
/// @todo implement full (data arbitration alorithm)[https://github.com/pandoraboxchain/techspecs/wiki/Data-inconsistency-arbitration]
if (_response == DataValidationResponse.Invalid) {
_transitionToState(InvalidData);
return;
}
_processWorkerResponse(_response == DataValidationResponse.Accept, IWorkerNode.Penalties.DeclinesJob, Cognition);
}
function commitProgress(uint8 percent)
onlyActiveWorkers
external {
/// @todo Implement tracking progress of cognitive work
//CognitionProgressed(percent);
}
function completeWork(bytes _ipfsResults)
onlyActiveWorkers
external {
uint256 workerIndex;
(,workerIndex) = _getWorkerFromSender();
ipfsResults[workerIndex] = _ipfsResults;
responseFlags[workerIndex] = true;
responseTimestamps[workerIndex] = block.timestamp;
_trackOfflineWorkers();
_transitionIfReady(Completed);
}
function activeWorkersCount()
view
external
returns(uint256) {
return activeWorkers.length;
}
function didWorkerCompute(
uint no
)
view
external
returns(bool) {
return responseFlags[no] == true;
}
/**
* ## State Machine implementation
*/
modifier requireActiveStates() {
require(
stateMachine.currentState == GatheringWorkers ||
stateMachine.currentState == DataValidation ||
stateMachine.currentState == Cognition
);
_;
}
function _initStateMachine() internal {
// Creating table of possible state transitions
mapping(uint8 => uint8[]) transitions = stateMachine.transitionTable;
transitions[Uninitialized] = [GatheringWorkers];
transitions[GatheringWorkers] = [InsufficientWorkers, DataValidation];
transitions[DataValidation] = [InvalidData, Cognition, InsufficientWorkers];
transitions[Cognition] = [Completed, PartialResult];
// Initializing state machine via base contract code
super._initStateMachine();
// Going into initial state (Uninitialized)
stateMachine.currentState = Uninitialized;
}
event Flag(uint number);
function _fireStateEvent() internal {
if (currentState() == InsufficientWorkers) {
emit WorkersNotFound();
_cleanStorage();
} else if (currentState() == DataValidation) {
emit DataValidationStarted();
} else if (currentState() == InvalidData) {
emit DataValidationFailed();
_cleanStorage();
} else if (currentState() == Cognition) {
emit CognitionStarted();
} else if (currentState() == PartialResult) {
emit CognitionCompleted(true);
pandora.finishCognitiveJob();
//todo separate finishing in cognitiveJobManager
} else if (currentState() == Completed) {
emit CognitionCompleted(false);
pandora.finishCognitiveJob();
}
}
}
| todo find better name
| uint256 public complexity; | 6,363,744 | [
1,
9012,
1104,
7844,
508,
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
] | [
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,
0
] | [
1,
565,
2254,
5034,
1071,
21610,
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
] |
./full_match/100/0xD8187f955750790ed4Dc0708A1114210D451A18a/sources/src/outerspace/facets/OuterSpaceFacetBase.sol | We want to ensure enough gas were given for the generator, but no more This way if the generator is broken/compromised (we are planning to update it) then this will always continue to work Reversely, a player have to provide enough gas and we want to ensure the player can't force a revert on the hook In particular. to prevent players to make a call to `remove` fails we could do the check prior: uint256 gasAvailable = gasleft() - 2000; require(gasAvailable - gasAvailable / 64 >= gas, "NOT_ENOUGH_GAS_FOR_INNER_CALL"); to.call{gas: gas}(data); but we instead chose to do the check after. for more info see: https:ronan.eth.limo/blog/ethereum-gas-dangers/ we use after the gas check as this allow us to not require heavy gas use if not needed instead of + 100,000 for 96,000 gas we can just add 1,524 gas (+ a bit more) | function _callWithGas(
address to,
bytes memory data,
uint256 gas
) internal {
if (to != address(0)) {
require(gasleft() > gas / 63, "NOT_ENOUGH_GAS_FOR_INNER_CALL");
}
}
| 14,285,755 | [
1,
3218,
2545,
358,
3387,
7304,
16189,
4591,
864,
364,
326,
4456,
16,
1496,
1158,
1898,
1220,
4031,
309,
326,
4456,
353,
12933,
19,
2919,
520,
5918,
261,
1814,
854,
886,
10903,
358,
1089,
518,
13,
1508,
333,
903,
3712,
1324,
358,
1440,
868,
2496,
2357,
16,
279,
7291,
1240,
358,
5615,
7304,
16189,
471,
732,
2545,
358,
3387,
326,
7291,
848,
1404,
2944,
279,
15226,
603,
326,
3953,
657,
6826,
18,
358,
5309,
18115,
358,
1221,
279,
745,
358,
1375,
4479,
68,
6684,
732,
3377,
741,
326,
866,
6432,
30,
2254,
5034,
16189,
5268,
273,
16189,
4482,
1435,
300,
16291,
31,
2583,
12,
31604,
5268,
300,
16189,
5268,
342,
5178,
225,
1545,
16189,
16,
315,
4400,
67,
1157,
26556,
16715,
67,
43,
3033,
67,
7473,
67,
25000,
67,
13730,
8863,
358,
18,
1991,
95,
31604,
30,
16189,
97,
12,
892,
1769,
1496,
732,
3560,
462,
2584,
358,
741,
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,
565,
445,
389,
1991,
1190,
27998,
12,
203,
3639,
1758,
358,
16,
203,
3639,
1731,
3778,
501,
16,
203,
3639,
2254,
5034,
16189,
203,
565,
262,
2713,
288,
203,
203,
3639,
309,
261,
869,
480,
1758,
12,
20,
3719,
288,
203,
203,
5411,
2583,
12,
31604,
4482,
1435,
405,
16189,
342,
13746,
16,
315,
4400,
67,
1157,
26556,
16715,
67,
43,
3033,
67,
7473,
67,
25000,
67,
13730,
8863,
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,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
] |
// to test issue with nodes breaking with large clients over WS
// fixed in web3 with fragmentationThreshold: 8192
pragma solidity ^0.4.17;
contract BigFreakingContract {
event Transfer(address indexed from, address indexed to, uint value);
event Approval( address indexed owner, address indexed spender, uint value);
mapping( address => uint ) _balances;
mapping( address => mapping( address => uint ) ) _approvals;
uint public _supply;
constructor( uint initial_balance ) public {
_balances[msg.sender] = initial_balance;
_supply = initial_balance;
}
function totalSupply() public constant returns (uint supply) {
return _supply;
}
function balanceOf( address who ) public constant returns (uint value) {
return _balances[who];
}
function transfer( address to, uint value) public returns (bool ok) {
if( _balances[msg.sender] < value ) {
revert();
}
if( !safeToAdd(_balances[to], value) ) {
revert();
}
_balances[msg.sender] -= value;
_balances[to] += value;
emit Transfer( msg.sender, to, value );
return true;
}
function transferFrom( address from, address to, uint value) public returns (bool ok) {
// if you don't have enough balance, throw
if( _balances[from] < value ) {
revert();
}
// if you don't have approval, throw
if( _approvals[from][msg.sender] < value ) {
revert();
}
if( !safeToAdd(_balances[to], value) ) {
revert();
}
// transfer and return true
_approvals[from][msg.sender] -= value;
_balances[from] -= value;
_balances[to] += value;
emit Transfer( from, to, value );
return true;
}
function approve(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function allowance(address owner, address spender) public constant returns (uint _allowance) {
return _approvals[owner][spender];
}
function safeToAdd(uint a, uint b) internal pure returns (bool) {
return (a + b >= a);
}
function isAvailable() public pure returns (bool) {
return false;
}
function approve_1(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_2(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_3(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_4(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_5(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_6(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_7(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_8(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_9(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_10(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_11(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_12(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_13(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_14(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_15(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_16(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_17(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_18(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_19(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_20(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_21(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_22(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_23(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_24(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_25(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_26(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_27(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_28(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_29(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_30(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_31(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_32(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_33(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_34(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_35(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_36(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_37(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_38(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_39(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_40(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_41(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_42(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_43(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_44(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_45(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_46(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_47(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_48(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_49(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_50(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_51(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_52(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_53(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_54(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_55(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_56(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_57(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_58(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_59(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_60(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_61(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_62(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_63(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_64(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_65(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_66(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_67(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_68(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_69(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_70(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_71(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_72(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_73(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_74(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_75(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_76(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_77(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_78(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_79(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_80(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_81(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_82(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_83(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_84(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_85(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_86(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_87(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_88(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_89(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_90(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_91(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_92(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_93(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_94(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_95(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_96(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_97(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_98(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_99(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_100(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_101(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_102(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_103(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_104(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_105(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_106(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_107(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_108(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_109(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_110(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_111(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_112(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_113(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_114(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_115(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_116(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_117(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_118(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_119(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_120(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_121(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_122(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_123(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_124(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_125(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_126(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_127(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_128(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_129(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_130(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_131(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_132(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_133(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_134(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_135(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_136(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_137(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_138(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_139(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_140(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_141(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_142(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_143(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_144(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_145(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_146(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_147(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_148(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_149(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_150(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_151(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_152(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_153(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_154(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_155(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_156(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_157(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_158(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_159(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_160(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_161(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_162(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_163(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_164(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_165(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_166(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_167(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_168(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_169(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_170(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_171(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_172(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_173(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_174(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_175(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_176(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_177(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_178(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_179(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_180(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_181(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_182(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_183(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_184(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_185(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_186(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_187(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_188(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_189(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_190(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_191(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_192(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_193(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_194(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_195(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_196(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_197(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_198(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_199(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_200(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_201(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_202(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_203(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_204(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_205(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_206(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_207(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_208(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_209(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_210(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_211(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_212(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_213(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_214(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_215(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_216(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_217(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_218(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_219(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_220(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_221(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_222(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_223(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_224(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_225(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_226(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_227(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_228(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_229(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_230(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_231(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_232(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_233(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_234(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_235(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_236(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_237(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_238(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_239(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_240(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_241(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_242(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_243(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_244(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_245(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_246(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_247(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_248(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_249(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_250(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_251(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_252(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_253(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_254(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_255(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_256(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_257(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_258(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_259(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_260(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_261(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_262(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_263(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_264(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_265(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_266(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_267(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_268(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_269(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_270(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_271(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_272(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_273(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_274(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_275(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_276(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_277(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_278(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_279(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_280(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_281(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_282(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_283(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_284(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_285(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_286(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_287(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_288(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_289(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_290(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_291(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_292(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_293(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_294(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_295(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_296(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_297(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_298(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_299(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_300(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_301(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_302(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_303(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_304(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_305(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_306(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_307(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_308(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_309(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_310(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_311(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_312(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_313(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_314(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_315(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_316(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_317(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_318(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_319(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_320(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_321(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_322(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_323(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_324(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_325(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_326(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_327(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_328(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_329(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_330(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_331(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_332(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_333(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_334(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_335(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_336(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_337(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_338(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_339(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_340(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_341(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_342(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_343(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_344(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_345(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_346(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_347(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_348(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_349(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_350(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_351(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_352(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_353(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_354(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_355(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_356(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_357(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_358(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_359(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_360(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_361(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_362(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_363(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_364(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_365(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_366(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_367(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_368(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_369(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_370(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_371(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_372(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_373(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_374(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_375(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_376(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_377(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_378(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_379(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_380(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_381(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_382(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_383(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_384(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_385(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_386(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_387(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_388(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_389(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_390(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_391(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_392(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_393(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_394(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_395(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_396(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_397(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_398(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_399(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_400(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_401(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_402(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_403(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_404(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_405(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_406(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_407(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_408(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_409(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_410(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_411(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_412(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_413(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_414(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_415(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_416(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_417(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_418(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_419(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_420(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_421(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_422(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_423(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_424(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_425(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_426(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_427(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_428(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_429(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_430(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_431(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_432(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_433(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_434(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_435(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_436(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_437(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_438(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_439(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_440(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_441(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_442(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_443(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_444(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_445(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_446(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_447(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_448(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_449(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_450(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_451(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_452(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_453(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_454(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_455(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_456(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_457(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_458(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_459(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_460(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_461(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_462(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_463(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_464(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_465(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_466(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_467(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_468(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_469(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_470(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_471(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_472(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_473(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_474(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_475(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_476(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_477(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_478(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_479(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_480(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_481(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_482(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_483(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_484(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_485(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_486(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_487(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_488(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_489(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_490(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_491(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_492(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_493(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_494(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_495(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_496(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_497(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_498(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_499(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_500(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_501(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_502(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_503(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_504(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_505(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_506(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_507(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_508(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_509(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_510(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_511(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_512(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_513(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_514(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_515(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_516(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_517(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_518(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_519(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_520(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_521(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_522(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_523(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_524(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_525(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_526(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_527(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_528(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_529(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_530(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_531(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_532(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_533(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_534(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_535(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_536(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_537(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_538(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_539(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_540(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_541(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_542(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_543(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_544(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_545(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_546(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_547(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_548(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_549(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_550(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_551(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_552(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_553(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_554(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_555(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_556(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_557(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_558(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_559(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_560(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_561(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_562(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_563(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_564(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_565(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_566(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_567(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_568(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_569(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_570(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_571(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_572(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_573(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_574(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_575(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_576(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_577(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_578(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_579(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_580(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_581(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_582(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_583(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_584(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_585(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_586(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_587(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_588(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_589(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_590(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_591(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_592(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_593(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_594(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_595(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_596(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_597(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_598(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_599(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_600(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_601(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_602(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_603(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_604(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_605(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_606(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_607(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_608(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_609(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_610(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_611(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_612(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_613(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_614(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_615(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_616(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_617(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_618(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_619(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_620(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_621(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_622(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_623(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_624(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_625(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_626(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_627(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_628(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_629(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_630(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_631(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_632(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_633(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_634(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_635(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_636(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_637(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_638(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_639(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_640(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_641(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_642(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_643(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_644(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_645(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_646(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_647(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_648(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_649(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_650(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_651(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_652(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_653(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_654(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_655(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_656(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_657(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_658(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_659(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_660(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_661(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_662(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_663(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_664(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_665(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_666(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_667(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_668(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_669(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_670(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_671(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_672(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_673(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_674(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_675(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_676(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_677(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_678(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_679(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_680(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_681(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_682(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_683(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_684(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_685(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_686(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_687(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_688(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_689(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_690(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_691(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_692(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_693(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_694(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_695(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_696(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_697(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_698(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_699(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_700(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_701(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_702(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_703(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_704(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_705(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_706(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_707(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_708(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_709(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_710(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_711(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_712(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_713(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_714(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_715(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_716(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_717(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_718(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_719(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_720(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_721(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_722(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_723(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_724(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_725(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_726(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_727(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_728(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_729(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_730(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_731(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_732(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_733(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_734(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_735(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_736(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_737(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_738(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_739(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_740(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_741(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_742(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_743(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_744(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_745(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_746(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_747(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_748(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_749(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_750(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_751(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_752(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_753(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_754(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_755(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_756(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_757(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_758(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_759(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_760(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_761(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_762(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_763(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_764(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_765(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_766(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_767(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_768(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_769(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_770(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_771(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_772(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_773(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_774(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_775(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_776(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_777(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_778(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_779(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_780(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_781(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_782(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_783(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_784(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_785(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_786(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_787(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_788(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_789(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_790(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_791(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_792(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_793(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_794(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_795(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_796(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_797(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_798(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_799(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_800(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_801(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_802(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_803(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_804(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_805(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_806(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_807(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_808(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_809(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_810(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_811(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_812(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_813(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_814(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_815(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_816(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_817(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_818(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_819(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_820(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_821(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_822(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_823(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_824(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_825(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_826(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_827(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_828(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_829(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_830(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_831(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_832(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_833(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_834(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_835(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_836(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_837(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_838(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_839(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_840(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_841(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_842(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_843(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_844(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_845(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_846(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_847(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_848(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_849(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_850(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_851(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_852(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_853(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_854(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_855(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_856(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_857(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_858(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_859(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_860(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_861(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_862(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_863(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_864(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_865(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_866(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_867(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_868(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_869(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_870(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_871(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_872(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_873(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_874(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_875(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_876(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_877(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_878(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_879(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_880(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_881(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_882(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_883(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_884(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_885(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_886(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_887(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_888(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_889(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_890(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_891(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_892(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_893(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_894(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_895(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_896(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_897(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_898(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_899(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_900(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_901(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
}
| TODO: should increase instead | function approve_347(address spender, uint value) public returns (bool ok) {
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
| 6,454,060 | [
1,
6241,
30,
1410,
10929,
3560,
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,
6617,
537,
67,
5026,
27,
12,
2867,
17571,
264,
16,
2254,
460,
13,
1071,
1135,
261,
6430,
1529,
13,
288,
203,
565,
389,
12908,
4524,
63,
3576,
18,
15330,
6362,
87,
1302,
264,
65,
273,
460,
31,
203,
565,
3626,
1716,
685,
1125,
12,
1234,
18,
15330,
16,
17571,
264,
16,
460,
11272,
203,
565,
327,
638,
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
] |
./partial_match/56/0x0cDC540E1E34F4db3eE3878Ab47528e21A661089/sources/BBeanz.sol | * @dev Collection of functions related to the address type/ | library Address {
function isContract(address account) internal view returns (bool) {
bytes32 codehash;
bytes32 accountHash = 0xc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470;
return (codehash != accountHash && codehash != 0x0);
}
assembly { codehash := extcodehash(account) }
function sendValue(address payable recipient, uint256 amount) internal {
require(address(this).balance >= amount, "Address: insufficient balance");
require(success, "Address: unable to send value, recipient may have reverted");
}
(bool success, ) = recipient.call { value: amount }("");
function functionCall(address target, bytes memory data) internal returns (bytes memory) {
return functionCall(target, data, "Address: low-level call failed");
}
function functionCall(address target, bytes memory data, string memory errorMessage) internal returns (bytes memory) {
return _functionCallWithValue(target, data, 0, errorMessage);
}
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");
}
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");
if (success) {
return returndata;
if (returndata.length > 0) {
assembly {
let returndata_size := mload(returndata)
revert(add(32, returndata), returndata_size)
}
revert(errorMessage);
}
}
}
(bool success, bytes memory returndata) = target.call{ value: weiValue }(data);
function _functionCallWithValue(address target, bytes memory data, uint256 weiValue, string memory errorMessage) private returns (bytes memory) {
require(isContract(target), "Address: call to non-contract");
if (success) {
return returndata;
if (returndata.length > 0) {
assembly {
let returndata_size := mload(returndata)
revert(add(32, returndata), returndata_size)
}
revert(errorMessage);
}
}
}
} else {
function _functionCallWithValue(address target, bytes memory data, uint256 weiValue, string memory errorMessage) private returns (bytes memory) {
require(isContract(target), "Address: call to non-contract");
if (success) {
return returndata;
if (returndata.length > 0) {
assembly {
let returndata_size := mload(returndata)
revert(add(32, returndata), returndata_size)
}
revert(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");
if (success) {
return returndata;
if (returndata.length > 0) {
assembly {
let returndata_size := mload(returndata)
revert(add(32, returndata), returndata_size)
}
revert(errorMessage);
}
}
}
} else {
}
| 11,101,372 | [
1,
2532,
434,
4186,
3746,
358,
326,
1758,
618,
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
] | [
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,
12083,
5267,
288,
203,
565,
445,
353,
8924,
12,
2867,
2236,
13,
2713,
1476,
1135,
261,
6430,
13,
288,
203,
3639,
1731,
1578,
981,
2816,
31,
203,
3639,
1731,
1578,
2236,
2310,
273,
374,
6511,
25,
72,
3247,
26,
1611,
5292,
74,
9060,
3707,
71,
29,
5324,
73,
27,
1966,
22,
72,
952,
27,
4630,
71,
20,
73,
12483,
70,
26,
8643,
5353,
24532,
9036,
70,
27,
17156,
361,
28,
3028,
25,
72,
7140,
69,
24,
7301,
31,
203,
3639,
327,
261,
710,
2816,
480,
2236,
2310,
597,
981,
2816,
480,
374,
92,
20,
1769,
203,
565,
289,
203,
203,
3639,
19931,
288,
981,
2816,
519,
1110,
710,
2816,
12,
4631,
13,
289,
203,
565,
445,
1366,
620,
12,
2867,
8843,
429,
8027,
16,
2254,
5034,
3844,
13,
2713,
288,
203,
3639,
2583,
12,
2867,
12,
2211,
2934,
12296,
1545,
3844,
16,
315,
1887,
30,
2763,
11339,
11013,
8863,
203,
203,
3639,
2583,
12,
4768,
16,
315,
1887,
30,
13496,
358,
1366,
460,
16,
8027,
2026,
1240,
15226,
329,
8863,
203,
565,
289,
203,
203,
3639,
261,
6430,
2216,
16,
262,
273,
8027,
18,
1991,
288,
460,
30,
3844,
289,
2932,
8863,
203,
565,
445,
445,
1477,
12,
2867,
1018,
16,
1731,
3778,
501,
13,
2713,
1135,
261,
3890,
3778,
13,
288,
203,
1377,
327,
445,
1477,
12,
3299,
16,
501,
16,
315,
1887,
30,
4587,
17,
2815,
745,
2535,
8863,
203,
565,
289,
203,
203,
565,
445,
445,
1477,
12,
2867,
1018,
16,
1731,
3778,
501,
16,
533,
3778,
9324,
13,
2713,
1135,
2
] |
pragma solidity ^0.4.21;
/*
* Creator: uvd (Uvidifytoken)
*/
/*
* Abstract Token Smart Contract
*
*/
/*
* Safe Math Smart Contract.
* https://github.com/OpenZeppelin/zeppelin-solidity/blob/master/contracts/math/SafeMath.sol
*/
contract 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 safeDiv(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 safeSub(uint256 a, uint256 b) internal pure returns (uint256) {
assert(b <= a);
return a - b;
}
function safeAdd(uint256 a, uint256 b) internal pure returns (uint256) {
uint256 c = a + b;
assert(c >= a);
return c;
}
}
/**
* ERC-20 standard token interface, as defined
* <a href="http://github.com/ethereum/EIPs/issues/20">here</a>.
*/
contract Token {
function totalSupply() constant returns (uint256 supply);
function balanceOf(address _owner) constant returns (uint256 balance);
function transfer(address _to, uint256 _value) returns (bool success);
function transferFrom(address _from, address _to, uint256 _value) returns (bool success);
function approve(address _spender, uint256 _value) returns (bool success);
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);
}
/**
* Abstract Token Smart Contract that could be used as a base contract for
* ERC-20 token contracts.
*/
contract AbstractToken is Token, SafeMath {
/**
* Create new Abstract Token contract.
*/
function AbstractToken () {
// Do nothing
}
/**
* Get number of tokens currently belonging to given owner.
*
* @param _owner address to get number of tokens currently belonging to the
* owner of
* @return number of tokens currently belonging to the owner of given address
*/
function balanceOf(address _owner) constant returns (uint256 balance) {
return accounts [_owner];
}
/**
* Transfer given number of tokens from message sender to given recipient.
*
* @param _to address to transfer tokens to the owner of
* @param _value number of tokens to transfer to the owner of given address
* @return true if tokens were transferred successfully, false otherwise
* accounts [_to] + _value > accounts [_to] for overflow check
* which is already in safeMath
*/
function transfer(address _to, uint256 _value) returns (bool success) {
require(_to != address(0));
if (accounts [msg.sender] < _value) return false;
if (_value > 0 && msg.sender != _to) {
accounts [msg.sender] = safeSub (accounts [msg.sender], _value);
accounts [_to] = safeAdd (accounts [_to], _value);
}
Transfer (msg.sender, _to, _value);
return true;
}
/**
* Transfer given number of tokens from given owner to given recipient.
*
* @param _from address to transfer tokens from the owner of
* @param _to address to transfer tokens to the owner of
* @param _value number of tokens to transfer from given owner to given
* recipient
* @return true if tokens were transferred successfully, false otherwise
* accounts [_to] + _value > accounts [_to] for overflow check
* which is already in safeMath
*/
function transferFrom(address _from, address _to, uint256 _value)
returns (bool success) {
require(_to != address(0));
if (allowances [_from][msg.sender] < _value) return false;
if (accounts [_from] < _value) return false;
if (_value > 0 && _from != _to) {
allowances [_from][msg.sender] = safeSub (allowances [_from][msg.sender], _value);
accounts [_from] = safeSub (accounts [_from], _value);
accounts [_to] = safeAdd (accounts [_to], _value);
}
Transfer(_from, _to, _value);
return true;
}
/**
* Allow given spender to transfer given number of tokens from message sender.
* @param _spender address to allow the owner of to transfer tokens from message sender
* @param _value number of tokens to allow to transfer
* @return true if token transfer was successfully approved, false otherwise
*/
function approve (address _spender, uint256 _value) returns (bool success) {
allowances [msg.sender][_spender] = _value;
Approval (msg.sender, _spender, _value);
return true;
}
/**
* Tell how many tokens given spender is currently allowed to transfer from
* given owner.
*
* @param _owner address to get number of tokens allowed to be transferred
* from the owner of
* @param _spender address to get number of tokens allowed to be transferred
* by the owner of
* @return number of tokens given spender is currently allowed to transfer
* from given owner
*/
function allowance(address _owner, address _spender) constant
returns (uint256 remaining) {
return allowances [_owner][_spender];
}
/**
* Mapping from addresses of token holders to the numbers of tokens belonging
* to these token holders.
*/
mapping (address => uint256) accounts;
/**
* Mapping from addresses of token holders to the mapping of addresses of
* spenders to the allowances set by these token holders to these spenders.
*/
mapping (address => mapping (address => uint256)) private allowances;
}
/**
* UVD token smart contract.
*/
contract UVDToken is AbstractToken {
/**
* Maximum allowed number of tokens in circulation.
* tokenSupply = tokensIActuallyWant * (10 ^ decimals)
*/
uint256 constant MAX_TOKEN_COUNT = 22000000000 * (10**18);
/**
* Address of the owner of this smart contract.
*/
address private owner;
/**
* Frozen account list holder
*/
mapping (address => bool) private frozenAccount;
/**
* Current number of tokens in circulation.
*/
uint256 tokenCount = 0;
/**
* True if tokens transfers are currently frozen, false otherwise.
*/
bool frozen = false;
/**
* Create new token smart contract and make msg.sender the
* owner of this smart contract.
*/
function UVDToken () {
owner = msg.sender;
}
/**
* Get total number of tokens in circulation.
*
* @return total number of tokens in circulation
*/
function totalSupply() constant returns (uint256 supply) {
return tokenCount;
}
string constant public name = "Uvidifytoken";
string constant public symbol = "uvd";
uint8 constant public decimals = 18;
/**
* Transfer given number of tokens from message sender to given recipient.
* @param _to address to transfer tokens to the owner of
* @param _value number of tokens to transfer to the owner of given address
* @return true if tokens were transferred successfully, false otherwise
*/
function transfer(address _to, uint256 _value) returns (bool success) {
require(!frozenAccount[msg.sender]);
if (frozen) return false;
else return AbstractToken.transfer (_to, _value);
}
/**
* Transfer given number of tokens from given owner to given recipient.
*
* @param _from address to transfer tokens from the owner of
* @param _to address to transfer tokens to the owner of
* @param _value number of tokens to transfer from given owner to given
* recipient
* @return true if tokens were transferred successfully, false otherwise
*/
function transferFrom(address _from, address _to, uint256 _value)
returns (bool success) {
require(!frozenAccount[_from]);
if (frozen) return false;
else return AbstractToken.transferFrom (_from, _to, _value);
}
/**
* Change how many tokens given spender is allowed to transfer from message
* spender. In order to prevent double spending of allowance,
* 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
* @param _spender address to allow the owner of to transfer tokens from
* message sender
* @param _value number of tokens to allow to transfer
* @return true if token transfer was successfully approved, false otherwise
*/
function approve (address _spender, uint256 _value)
returns (bool success) {
require(allowance (msg.sender, _spender) == 0 || _value == 0);
return AbstractToken.approve (_spender, _value);
}
/**
* Create _value new tokens and give new created tokens to msg.sender.
* May only be called by smart contract owner.
*
* @param _value number of tokens to create
* @return true if tokens were created successfully, false otherwise
*/
function createTokens(uint256 _value)
returns (bool success) {
require (msg.sender == owner);
if (_value > 0) {
if (_value > safeSub (MAX_TOKEN_COUNT, tokenCount)) return false;
accounts [msg.sender] = safeAdd (accounts [msg.sender], _value);
tokenCount = safeAdd (tokenCount, _value);
// adding transfer event and _from address as null address
Transfer(0x0, msg.sender, _value);
return true;
}
return false;
}
/**
* Set new owner for the smart contract.
* May only be called by smart contract owner.
*
* @param _newOwner address of new owner of the smart contract
*/
function setOwner(address _newOwner) {
require (msg.sender == owner);
owner = _newOwner;
}
/**
* Freeze ALL token transfers.
* May only be called by smart contract owner.
*/
function freezeTransfers () {
require (msg.sender == owner);
if (!frozen) {
frozen = true;
Freeze ();
}
}
/**
* Unfreeze ALL token transfers.
* May only be called by smart contract owner.
*/
function unfreezeTransfers () {
require (msg.sender == owner);
if (frozen) {
frozen = false;
Unfreeze ();
}
}
/*A user is able to unintentionally send tokens to a contract
* and if the contract is not prepared to refund them they will get stuck in the contract.
* The same issue used to happen for Ether too but new Solidity versions added the payable modifier to
* prevent unintended Ether transfers. However, there’s no such mechanism for token transfers.
* so the below function is created
*/
function refundTokens(address _token, address _refund, uint256 _value) {
require (msg.sender == owner);
require(_token != address(this));
AbstractToken token = AbstractToken(_token);
token.transfer(_refund, _value);
RefundTokens(_token, _refund, _value);
}
/**
* Freeze specific account
* May only be called by smart contract owner.
*/
function freezeAccount(address _target, bool freeze) {
require (msg.sender == owner);
require (msg.sender != _target);
frozenAccount[_target] = freeze;
FrozenFunds(_target, freeze);
}
/**
* Logged when token transfers were frozen.
*/
event Freeze ();
/**
* Logged when token transfers were unfrozen.
*/
event Unfreeze ();
/**
* Logged when a particular account is frozen.
*/
event FrozenFunds(address target, bool frozen);
/**
* when accidentally send other tokens are refunded
*/
event RefundTokens(address _token, address _refund, uint256 _value);
} | * UVD token smart contract./ | contract UVDToken is AbstractToken {
uint256 constant MAX_TOKEN_COUNT = 22000000000 * (10**18);
address private owner;
mapping (address => bool) private frozenAccount;
uint256 tokenCount = 0;
bool frozen = false;
function UVDToken () {
owner = msg.sender;
}
function totalSupply() constant returns (uint256 supply) {
return tokenCount;
}
string constant public name = "Uvidifytoken";
string constant public symbol = "uvd";
uint8 constant public decimals = 18;
function transfer(address _to, uint256 _value) returns (bool success) {
require(!frozenAccount[msg.sender]);
if (frozen) return false;
else return AbstractToken.transfer (_to, _value);
}
function transferFrom(address _from, address _to, uint256 _value)
returns (bool success) {
require(!frozenAccount[_from]);
if (frozen) return false;
else return AbstractToken.transferFrom (_from, _to, _value);
}
function approve (address _spender, uint256 _value)
returns (bool success) {
require(allowance (msg.sender, _spender) == 0 || _value == 0);
return AbstractToken.approve (_spender, _value);
}
function createTokens(uint256 _value)
returns (bool success) {
require (msg.sender == owner);
if (_value > 0) {
if (_value > safeSub (MAX_TOKEN_COUNT, tokenCount)) return false;
accounts [msg.sender] = safeAdd (accounts [msg.sender], _value);
tokenCount = safeAdd (tokenCount, _value);
Transfer(0x0, msg.sender, _value);
return true;
}
return false;
}
function createTokens(uint256 _value)
returns (bool success) {
require (msg.sender == owner);
if (_value > 0) {
if (_value > safeSub (MAX_TOKEN_COUNT, tokenCount)) return false;
accounts [msg.sender] = safeAdd (accounts [msg.sender], _value);
tokenCount = safeAdd (tokenCount, _value);
Transfer(0x0, msg.sender, _value);
return true;
}
return false;
}
function setOwner(address _newOwner) {
require (msg.sender == owner);
owner = _newOwner;
}
function freezeTransfers () {
require (msg.sender == owner);
if (!frozen) {
frozen = true;
Freeze ();
}
}
function freezeTransfers () {
require (msg.sender == owner);
if (!frozen) {
frozen = true;
Freeze ();
}
}
function unfreezeTransfers () {
require (msg.sender == owner);
if (frozen) {
frozen = false;
Unfreeze ();
}
}
function unfreezeTransfers () {
require (msg.sender == owner);
if (frozen) {
frozen = false;
Unfreeze ();
}
}
function refundTokens(address _token, address _refund, uint256 _value) {
require (msg.sender == owner);
require(_token != address(this));
AbstractToken token = AbstractToken(_token);
token.transfer(_refund, _value);
RefundTokens(_token, _refund, _value);
}
function freezeAccount(address _target, bool freeze) {
require (msg.sender == owner);
require (msg.sender != _target);
frozenAccount[_target] = freeze;
FrozenFunds(_target, freeze);
}
event FrozenFunds(address target, bool frozen);
event RefundTokens(address _token, address _refund, uint256 _value);
event Freeze ();
event Unfreeze ();
} | 12,154,328 | [
1,
20147,
40,
1147,
13706,
6835,
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,
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,
587,
21544,
1345,
353,
4115,
1345,
288,
203,
27699,
27699,
225,
2254,
5034,
5381,
4552,
67,
8412,
67,
7240,
273,
11201,
2787,
11706,
380,
261,
2163,
636,
2643,
1769,
203,
27699,
225,
1758,
3238,
3410,
31,
203,
21281,
225,
2874,
261,
2867,
516,
1426,
13,
3238,
12810,
3032,
31,
203,
203,
225,
2254,
5034,
1147,
1380,
273,
374,
31,
203,
21281,
7010,
225,
1426,
12810,
273,
629,
31,
203,
21281,
7010,
225,
445,
587,
21544,
1345,
1832,
288,
203,
565,
3410,
273,
1234,
18,
15330,
31,
203,
225,
289,
203,
203,
225,
445,
2078,
3088,
1283,
1435,
5381,
1135,
261,
11890,
5034,
14467,
13,
288,
203,
565,
327,
1147,
1380,
31,
203,
225,
289,
203,
203,
225,
533,
5381,
1071,
508,
273,
315,
57,
1246,
1164,
2316,
14432,
203,
225,
533,
5381,
1071,
3273,
273,
315,
89,
16115,
14432,
203,
225,
2254,
28,
5381,
1071,
15105,
273,
6549,
31,
203,
21281,
225,
445,
7412,
12,
2867,
389,
869,
16,
2254,
5034,
389,
1132,
13,
1135,
261,
6430,
2216,
13,
288,
203,
565,
2583,
12,
5,
28138,
3032,
63,
3576,
18,
15330,
19226,
203,
202,
430,
261,
28138,
13,
327,
629,
31,
203,
565,
469,
327,
4115,
1345,
18,
13866,
261,
67,
869,
16,
389,
1132,
1769,
203,
225,
289,
203,
203,
225,
445,
7412,
1265,
12,
2867,
389,
2080,
16,
1758,
389,
869,
16,
2254,
5034,
389,
1132,
13,
203,
565,
1135,
261,
6430,
2216,
13,
288,
203,
202,
6528,
12,
5,
28138,
3032,
63,
67,
2080,
19226,
203,
565,
309,
261,
28138,
2
] |
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.11;
import "@openzeppelin/contracts/token/ERC721/IERC721.sol";
interface DigilToken is IERC721 {
// Pending Coin and Value Distributions, and the Time of the last Distribution
struct Distribution {
uint256 time;
uint256 coins;
uint256 value;
}
// The relationship between a source and destination Token
struct TokenLink {
uint256 source;
uint256 destination;
uint256 value;
uint256 efficiency;
uint256 probability;
}
// Information about how much was Contributed to a Token's Charge
struct TokenContribution {
uint256 charge;
uint256 value;
bool exists;
bool distributed;
bool whitelisted;
}
// Illustrates the relationship between an external ERC721 token and an internal Token
struct ContractToken {
uint256 externalTokenId;
uint256 internalTokenId;
bool returnable;
}
// Token information
struct Token {
uint256 charge;
uint256 incrementalValue;
uint256 value;
address[] contributors;
mapping(address => TokenContribution) contributions;
uint256 activationThreshold;
bool active;
TokenLink[] links;
bytes data;
string uri;
bool whitelistEnabled;
}
}
/// @custom:security-contact [email protected]
contract DigilLinkUtility {
constructor() {}
/// @notice Gets the default Links for a given Token
/// @dev A Token with an ID of 1 is assumed to be the Void Token, a special token where any unused Charge is drained into when Link Values are being calculated.
/// @param tokenId The ID of the Token to get Links for
/// @return results A collection of Token Links
function getDefaultLinks(uint256 tokenId) public pure returns (DigilToken.TokenLink[] memory results) {
if (tokenId >= 16) {
results = new DigilToken.TokenLink[](3);
results[0] = DigilToken.TokenLink(tokenId, 1, 0, 100, 255);
results[1] = DigilToken.TokenLink(2, tokenId, 0, 1, 16);
results[2] = DigilToken.TokenLink(3, tokenId, 0, 2, 8);
} else if (tokenId == 3) {
results = new DigilToken.TokenLink[](2);
results[0] = DigilToken.TokenLink(tokenId, 1, 0, 100, 255);
results[1] = DigilToken.TokenLink(2, tokenId, 0, 1, 64);
} else if (tokenId == 2) {
results = new DigilToken.TokenLink[](2);
results[0] = DigilToken.TokenLink(tokenId, 1, 0, 100, 255);
results[1] = DigilToken.TokenLink(3, tokenId, 0, 2, 32);
} else if (tokenId > 1) {
results = new DigilToken.TokenLink[](1);
results[0] = DigilToken.TokenLink(tokenId, 1, 0, 100, 255);
} else if (tokenId == 1) {
results = new DigilToken.TokenLink[](8);
results[0] = DigilToken.TokenLink(tokenId, 4, 0, 1, 16);
results[1] = DigilToken.TokenLink(tokenId, 5, 0, 1, 16);
results[2] = DigilToken.TokenLink(tokenId, 6, 0, 1, 16);
results[3] = DigilToken.TokenLink(tokenId, 7, 0, 1, 16);
results[4] = DigilToken.TokenLink(tokenId, 4, 0, 2, 8);
results[5] = DigilToken.TokenLink(tokenId, 5, 0, 1, 16);
results[6] = DigilToken.TokenLink(tokenId, 6, 0, 1, 16);
results[7] = DigilToken.TokenLink(tokenId, 7, 0, 2, 8);
}
}
/// @notice Calculates the Value of the Links for a given Token. In the context of a Token Link, Value is in Coins, not Ether (wei).
/// @dev If the Token is being Discharged, attempts to use up the entirety of the charge parameter when calculating the Values.
/// If the Token is not being Discharged, the Probability of a Link executing is capped to 64 (of 255), any Value generated is essentially a bonus.
/// It is assumed that there are a maximum of 16 Token Links passed in (any Token Links after the 16th will not generate Value).
/// @param tokenId The ID of the Token to get Link Values for
/// @param discharge Boolean indicating whether the Token is being Discharged
/// @param links A collection of Links (assumed to be attached to the Token), used to calculate the Link Values
/// @param charge The available Charge to generate Value from
/// @return results A collection of Token Links with Values calculated
function getLinkValues(uint256 tokenId, bool discharge, DigilToken.TokenLink[] memory links, uint256 charge) external view returns (DigilToken.TokenLink[16] memory results) {
if (charge == 0) {
return results;
}
uint256 linksLength = uint256(links.length);
if (linksLength == 0) {
links = getDefaultLinks(tokenId);
linksLength = uint256(links.length);
}
if (linksLength == 0) {
return results;
}
uint256 linkIndex = (linksLength < 16 ? linksLength : 16) - 1;
uint256 probabilityCap = discharge ? 255 : (64 - linkIndex * 4);
for (linkIndex; linkIndex >= 0; linkIndex--) {
DigilToken.TokenLink memory link = links[linkIndex];
uint256 efficiency = link.efficiency;
if (efficiency == 0) {
continue;
}
if (link.probability > probabilityCap) {
link.probability = probabilityCap;
}
bool linked;
uint256 destinationId = link.destination;
uint256 sourceId = link.source;
if (willExecute(link.probability, sourceId, destinationId, charge)) {
if (tokenId == destinationId) {
linked = true;
} else if (sourceId == tokenId) {
linked = true;
sourceId = destinationId;
destinationId = tokenId;
}
}
DigilToken.TokenLink memory result = DigilToken.TokenLink(sourceId, destinationId, 0, 0, 0);
if (linked) {
bool haveEffieiencyBonus = efficiency > 100;
uint256 value = charge / 100 * (haveEffieiencyBonus ? 100 : efficiency);
result.value = value + (charge / 100 * (haveEffieiencyBonus ? efficiency - 100 : 0));
if (discharge) {
if (charge >= value) {
charge -= value;
} else {
charge = 0;
}
}
}
results[linkIndex] = result;
if (linkIndex == 0) {
break;
}
}
return results;
}
/// @notice Determines whether a Token Link overcomes the Probability Threshold
/// @dev While this function is meant to be "random," the fact that it is somewhat deterministic is not terribly important
/// as there are various caps in place to limit generated Value, and or it is assumed that any bonuses would have been "paid for" (in Coins)
/// @param probability The Probability that the Token Link should be executed
/// @param sourceId The ID of the source Token
/// @param destinationId The ID of the destination Token
/// @param charge The Charge being checked
/// @return A boolean indicating whether a Token Link should have Value generated from its charge
function willExecute(uint256 probability, uint256 sourceId, uint256 destinationId, uint256 charge) public view returns (bool) {
if (probability == 0) { return false; }
uint256 probabilityThreshold = uint256(uint(keccak256(abi.encodePacked(block.timestamp, block.difficulty, sourceId, destinationId, charge))) % 250);
return probability > probabilityThreshold;
}
function _linkRate(uint256 rate, uint256 cutoff) internal pure returns(uint256) {
uint256 e = rate > cutoff ? rate - cutoff : 0;
return rate + (e * (e + 1) / 2);
}
/// @notice Returns the number of Coins required to Link two Tokens
/// Base Efficiency: Efficiency + Summation of Efficiency;
/// Bonus Efficiency: (Base Efficiency + Summation of Efficiency > 100) * Coin Rate;
/// Base Probability: (Probability + Summation of Probability > 64) * 10% of Coin Rate;
/// For example, assuming a Coin Rate of 100,
/// a Link with an Efficiency of 1 and a Probability of 32 would require 421 Coins (~12.5% chance of 1% bonus Coins),
/// Efficiency 105 and Probability 128 would require 39645 Coins (~50% chance of 105% bonus Coins).
/// @param efficiency The Link Efficiency
/// @param probability The Link Probability
function getLinkRate(uint256 efficiency, uint256 probability, uint256 coins) public pure returns (uint256) {
return _linkRate(efficiency, 1) + _linkRate(efficiency, 100) * coins + _linkRate(probability, 64) * coins / 10;
}
}
| @notice Determines whether a Token Link overcomes the Probability Threshold @dev While this function is meant to be "random," the fact that it is somewhat deterministic is not terribly important as there are various caps in place to limit generated Value, and or it is assumed that any bonuses would have been "paid for" (in Coins) @param probability The Probability that the Token Link should be executed @param sourceId The ID of the source Token @param destinationId The ID of the destination Token @param charge The Charge being checked @return A boolean indicating whether a Token Link should have Value generated from its charge | function willExecute(uint256 probability, uint256 sourceId, uint256 destinationId, uint256 charge) public view returns (bool) {
uint256 probabilityThreshold = uint256(uint(keccak256(abi.encodePacked(block.timestamp, block.difficulty, sourceId, destinationId, charge))) % 250);
return probability > probabilityThreshold;
}
| 7,224,730 | [
1,
10114,
2856,
279,
3155,
4048,
1879,
10127,
326,
14610,
2967,
27139,
377,
21572,
333,
445,
353,
20348,
358,
506,
315,
9188,
10837,
326,
5410,
716,
518,
353,
18016,
11304,
25112,
353,
486,
27428,
24755,
10802,
540,
487,
1915,
854,
11191,
15788,
316,
3166,
358,
1800,
4374,
1445,
16,
471,
578,
518,
353,
12034,
716,
1281,
324,
265,
6117,
4102,
1240,
2118,
315,
29434,
364,
6,
261,
267,
385,
9896,
13,
282,
11331,
1021,
14610,
2967,
716,
326,
3155,
4048,
1410,
506,
7120,
282,
27572,
1021,
1599,
434,
326,
1084,
3155,
282,
2929,
548,
1021,
1599,
434,
326,
2929,
3155,
282,
13765,
1021,
3703,
908,
3832,
5950,
327,
432,
1250,
11193,
2856,
279,
3155,
4048,
1410,
1240,
1445,
4374,
628,
2097,
13765,
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,
903,
5289,
12,
11890,
5034,
11331,
16,
2254,
5034,
27572,
16,
2254,
5034,
2929,
548,
16,
2254,
5034,
13765,
13,
1071,
1476,
1135,
261,
6430,
13,
288,
203,
3639,
2254,
5034,
11331,
7614,
273,
2254,
5034,
12,
11890,
12,
79,
24410,
581,
5034,
12,
21457,
18,
3015,
4420,
329,
12,
2629,
18,
5508,
16,
1203,
18,
5413,
21934,
16,
27572,
16,
2929,
548,
16,
13765,
20349,
738,
16927,
1769,
203,
3639,
327,
11331,
405,
11331,
7614,
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
] |
pragma solidity 0.5.12;
import "https://github.com/mrdavey/ez-flashloan/blob/remix/contracts/aave/ILendingPool.sol";
import "https://github.com/mrdavey/ez-flashloan/blob/remix/contracts/aave/ILendingPoolAddressesProvider.sol";
import "https://github.com/mrdavey/ez-flashloan/blob/remix/contracts/aave/FlashLoanReceiverBase.sol";
contract AaveFundManager is Ownable {
ILendingPoolAddressesProvider provider = ILendingPoolAddressesProvider(address(0x1c8756FD2B28e9426CDBDcC7E3c4d64fa9A54728)); // ropsten address, for other addresses: https://docs.aave.com/developers/developing-on-aave/deployed-contract-instances
ILendingPool lendingPool = ILendingPool(provider.getLendingPool());
address lendingPoolCore = address(provider.getLendingPoolCore());
// Input variables
address daiAddress = address(0xf80A32A835F79D7787E8a8ee5721D0fEaFd78108); // ropsten DAI
address aDaiAddress = address(0xcB1Fe6F440c49E9290c3eb7f158534c2dC374201); //ropsten aDAI
IERC20 dai = IERC20(daiAddress);
IERC20 aDAI = IERC20(aDaiAddress);
/*
* deposits _depositAmount of _reserveAsset onto the lending pool
*/
function deposit(address _reserveAsset, uint256 _depositAmount) public onlyOwner {
if (_reserveAsset == daiAddress) {
// Approve LendingPool contract to move your DAI if user is depositing DAI
dai.approve(lendingPoolCore, _depositAmount);
}
// Deposit _depositAmount of _reserveAsset
lendingPool.deposit(_reserveAsset, _depositAmount, uint16(0));
}
/*
* borrows _borrowAmount of _reserveAsset from the lending pool, assuming you have deposited enough collateral
*/
function borrow(address _reserveAsset, uint256 _borrowAmount) public onlyOwner {
if (_reserveAsset == daiAddress) {
// Approve LendingPool contract to move your DAI if user is depositing DAI
dai.approve(lendingPoolCore, _borrowAmount);
}
// 1 is stable rate, 2 is variable rate
lendingPool.borrow(_reserveAsset, _borrowAmount, 2, uint16(0));
}
/*
* repays _repayAmount of _reserveAsset to the lending pool
*/
function repay(address _reserveAsset, uint256 _repayAmount) public onlyOwner {
if (_reserveAsset == daiAddress) {
// Approve LendingPool contract to move your DAI if user is depositing DAI
dai.approve(lendingPoolCore, _repayAmount);
}
// Repay own loan
lendingPool.repay(_reserveAsset, _repayAmount, msg.sender);
}
/*
* repays _repayAmount of _reserveAsset to the lending pool on behalf of _onBehalfOfAddress
*/
function repayOnBehalf(address _reserveAsset, uint256 _repayAmount, address _onBehalfOfAddress) public onlyOwner {
if (_reserveAsset == daiAddress) {
// Approve LendingPool contract to move your DAI if user is depositing DAI
dai.approve(lendingPoolCore, _repayAmount);
}
// repays loan on behalf of _onBehalfOfAddress
lendingPool.repay(_reserveAsset, _repayAmount, _onBehalfOfAddress);
}
/*
* Liquidate positions with a health factor below 1
*/
function liquidator(address _collateralAddress, address _liquidateeAddress, uint256 _purchaseAmount) public onlyOwner {
// Approve LendingPool contract to move your DAI
dai.approve(lendingPoolCore, _purchaseAmount);
/// LiquidationCall method call
lendingPool.liquidationCall(
_collateralAddress,
daiAddress,
_liquidateeAddress,
_purchaseAmount,
true
);
}
/*
* withdraw all ETH and DAI on contract back to you
*/
function clearContractFunds() public onlyOwner {
// withdraw DAI
dai.transfer(msg.sender, dai.balanceOf(address(this)));
// withdraw ETH
msg.sender.transfer(address(this).balance);
// withdraw aDAI
aDAI.transfer(msg.sender, aDAI.balanceOf(address(this)));
}
// to enable lending pool to send borrowed funds to this contract
function () external payable {}
}
| repays loan on behalf of _onBehalfOfAddress | lendingPool.repay(_reserveAsset, _repayAmount, _onBehalfOfAddress);
| 14,084,212 | [
1,
14462,
8271,
28183,
603,
12433,
6186,
434,
389,
265,
1919,
20222,
951,
1887,
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,
328,
2846,
2864,
18,
266,
10239,
24899,
455,
6527,
6672,
16,
389,
266,
10239,
6275,
16,
389,
265,
1919,
20222,
951,
1887,
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
] |
// SPDX-License-Identifier: MIT
// File: @openzeppelin/contracts/utils/Counters.sol
// OpenZeppelin Contracts v4.4.1 (utils/Counters.sol)
pragma solidity ^0.8.0;
/**
* @title Counters
* @author Matt Condon (@shrugs)
* @dev Provides counters that can only be incremented, decremented or reset. This can be used e.g. to track the number
* of elements in a mapping, issuing ERC721 ids, or counting request ids.
*
* Include with `using Counters for Counters.Counter;`
*/
library Counters {
struct Counter {
// This variable should never be directly accessed by users of the library: interactions must be restricted to
// the library's function. As of Solidity v0.5.2, this cannot be enforced, though there is a proposal to add
// this feature: see https://github.com/ethereum/solidity/issues/4637
uint256 _value; // default: 0
}
function current(Counter storage counter) internal view returns (uint256) {
return counter._value;
}
function increment(Counter storage counter) internal {
unchecked {
counter._value += 1;
}
}
function decrement(Counter storage counter) internal {
uint256 value = counter._value;
require(value > 0, "Counter: decrement overflow");
unchecked {
counter._value = value - 1;
}
}
function reset(Counter storage counter) internal {
counter._value = 0;
}
}
// File: @openzeppelin/contracts/utils/Strings.sol
// 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);
}
}
// File: @openzeppelin/contracts/utils/Context.sol
// OpenZeppelin Contracts v4.4.1 (utils/Context.sol)
pragma solidity ^0.8.0;
/**
* @dev Provides information about the current execution context, including the
* sender of the transaction and its data. While these are generally available
* via msg.sender and msg.data, they should not be accessed in such a direct
* manner, since when dealing with meta-transactions the account sending and
* paying for execution may not be the actual sender (as far as an application
* is concerned).
*
* This contract is only required for intermediate, library-like contracts.
*/
abstract contract Context {
function _msgSender() internal view virtual returns (address) {
return msg.sender;
}
function _msgData() internal view virtual returns (bytes calldata) {
return msg.data;
}
}
// File: @openzeppelin/contracts/access/Ownable.sol
// OpenZeppelin Contracts v4.4.1 (access/Ownable.sol)
pragma solidity ^0.8.0;
/**
* @dev Contract module which provides a basic access control mechanism, where
* there is an account (an owner) that can be granted exclusive access to
* specific functions.
*
* By default, the owner account will be the one that deploys the contract. This
* can later be changed with {transferOwnership}.
*
* This module is used through inheritance. It will make available the modifier
* `onlyOwner`, which can be applied to your functions to restrict their use to
* the owner.
*/
abstract contract Ownable is Context {
address private _owner;
event OwnershipTransferred(address indexed previousOwner, address indexed newOwner);
/**
* @dev Initializes the contract setting the deployer as the initial owner.
*/
constructor() {
_transferOwnership(_msgSender());
}
/**
* @dev Returns the address of the current owner.
*/
function owner() public view virtual returns (address) {
return _owner;
}
/**
* @dev Throws if called by any account other than the owner.
*/
modifier onlyOwner() {
require(owner() == _msgSender(), "Ownable: caller is not the owner");
_;
}
/**
* @dev Leaves the contract without owner. It will not be possible to call
* `onlyOwner` functions anymore. Can only be called by the current owner.
*
* NOTE: Renouncing ownership will leave the contract without an owner,
* thereby removing any functionality that is only available to the owner.
*/
function renounceOwnership() public virtual onlyOwner {
_transferOwnership(address(0));
}
/**
* @dev Transfers ownership of the contract to a new account (`newOwner`).
* Can only be called by the current owner.
*/
function transferOwnership(address newOwner) public virtual onlyOwner {
require(newOwner != address(0), "Ownable: new owner is the zero address");
_transferOwnership(newOwner);
}
/**
* @dev Transfers ownership of the contract to a new account (`newOwner`).
* Internal function without access restriction.
*/
function _transferOwnership(address newOwner) internal virtual {
address oldOwner = _owner;
_owner = newOwner;
emit OwnershipTransferred(oldOwner, newOwner);
}
}
// File: @openzeppelin/contracts/utils/Address.sol
// OpenZeppelin Contracts (last updated v4.5.0) (utils/Address.sol)
pragma solidity ^0.8.1;
/**
* @dev Collection of functions related to the address type
*/
library Address {
/**
* @dev Returns true if `account` is a contract.
*
* [IMPORTANT]
* ====
* It is unsafe to assume that an address for which this function returns
* false is an externally-owned account (EOA) and not a contract.
*
* Among others, `isContract` will return false for the following
* types of addresses:
*
* - an externally-owned account
* - a contract in construction
* - an address where a contract will be created
* - an address where a contract lived, but was destroyed
* ====
*
* [IMPORTANT]
* ====
* You shouldn't rely on `isContract` to protect against flash loan attacks!
*
* Preventing calls from contracts is highly discouraged. It breaks composability, breaks support for smart wallets
* like Gnosis Safe, and does not provide security since it can be circumvented by calling from a contract
* constructor.
* ====
*/
function isContract(address account) internal view returns (bool) {
// This method relies on extcodesize/address.code.length, which returns 0
// for contracts in construction, since the code is only stored at the end
// of the constructor execution.
return account.code.length > 0;
}
/**
* @dev Replacement for Solidity's `transfer`: sends `amount` wei to
* `recipient`, forwarding all available gas and reverting on errors.
*
* https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost
* of certain opcodes, possibly making contracts go over the 2300 gas limit
* imposed by `transfer`, making them unable to receive funds via
* `transfer`. {sendValue} removes this limitation.
*
* https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more].
*
* IMPORTANT: because control is transferred to `recipient`, care must be
* taken to not create reentrancy vulnerabilities. Consider using
* {ReentrancyGuard} or the
* https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern].
*/
function sendValue(address payable recipient, uint256 amount) internal {
require(address(this).balance >= amount, "Address: insufficient balance");
(bool success, ) = recipient.call{value: amount}("");
require(success, "Address: unable to send value, recipient may have reverted");
}
/**
* @dev Performs a Solidity function call using a low level `call`. A
* plain `call` is an unsafe replacement for a function call: use this
* function instead.
*
* If `target` reverts with a revert reason, it is bubbled up by this
* function (like regular Solidity function calls).
*
* Returns the raw returned data. To convert to the expected return value,
* use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`].
*
* Requirements:
*
* - `target` must be a contract.
* - calling `target` with `data` must not revert.
*
* _Available since v3.1._
*/
function functionCall(address target, bytes memory data) internal returns (bytes memory) {
return functionCall(target, data, "Address: low-level call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with
* `errorMessage` as a fallback revert reason when `target` reverts.
*
* _Available since v3.1._
*/
function functionCall(
address target,
bytes memory data,
string memory errorMessage
) internal returns (bytes memory) {
return functionCallWithValue(target, data, 0, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but also transferring `value` wei to `target`.
*
* Requirements:
*
* - the calling contract must have an ETH balance of at least `value`.
* - the called Solidity function must be `payable`.
*
* _Available since v3.1._
*/
function functionCallWithValue(
address target,
bytes memory data,
uint256 value
) internal returns (bytes memory) {
return functionCallWithValue(target, data, value, "Address: low-level call with value failed");
}
/**
* @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but
* with `errorMessage` as a fallback revert reason when `target` reverts.
*
* _Available since v3.1._
*/
function functionCallWithValue(
address target,
bytes memory data,
uint256 value,
string memory errorMessage
) internal returns (bytes memory) {
require(address(this).balance >= value, "Address: insufficient balance for call");
require(isContract(target), "Address: call to non-contract");
(bool success, bytes memory returndata) = target.call{value: value}(data);
return verifyCallResult(success, returndata, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but performing a static call.
*
* _Available since v3.3._
*/
function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) {
return functionStaticCall(target, data, "Address: low-level static call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`],
* but performing a static call.
*
* _Available since v3.3._
*/
function functionStaticCall(
address target,
bytes memory data,
string memory errorMessage
) internal view returns (bytes memory) {
require(isContract(target), "Address: static call to non-contract");
(bool success, bytes memory returndata) = target.staticcall(data);
return verifyCallResult(success, returndata, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but performing a delegate call.
*
* _Available since v3.4._
*/
function functionDelegateCall(address target, bytes memory data) internal returns (bytes memory) {
return functionDelegateCall(target, data, "Address: low-level delegate call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`],
* but performing a delegate call.
*
* _Available since v3.4._
*/
function functionDelegateCall(
address target,
bytes memory data,
string memory errorMessage
) internal returns (bytes memory) {
require(isContract(target), "Address: delegate call to non-contract");
(bool success, bytes memory returndata) = target.delegatecall(data);
return verifyCallResult(success, returndata, errorMessage);
}
/**
* @dev Tool to verifies that a low level call was successful, and revert if it wasn't, either by bubbling the
* revert reason using the provided one.
*
* _Available since v4.3._
*/
function verifyCallResult(
bool success,
bytes memory returndata,
string memory errorMessage
) internal pure returns (bytes memory) {
if (success) {
return returndata;
} else {
// Look for revert reason and bubble it up if present
if (returndata.length > 0) {
// The easiest way to bubble the revert reason is using memory via assembly
assembly {
let returndata_size := mload(returndata)
revert(add(32, returndata), returndata_size)
}
} else {
revert(errorMessage);
}
}
}
}
// File: @openzeppelin/contracts/token/ERC721/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: @openzeppelin/contracts/utils/introspection/IERC165.sol
// 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);
}
// File: @openzeppelin/contracts/utils/introspection/ERC165.sol
// OpenZeppelin Contracts v4.4.1 (utils/introspection/ERC165.sol)
pragma solidity ^0.8.0;
/**
* @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: @openzeppelin/contracts/token/ERC721/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: @openzeppelin/contracts/token/ERC721/extensions/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: @openzeppelin/contracts/token/ERC721/ERC721.sol
// OpenZeppelin Contracts (last updated v4.5.0) (token/ERC721/ERC721.sol)
pragma solidity ^0.8.0;
/**
* @dev Implementation of https://eips.ethereum.org/EIPS/eip-721[ERC721] Non-Fungible Token Standard, including
* the Metadata extension, but not including the Enumerable extension, which is available separately as
* {ERC721Enumerable}.
*/
contract ERC721 is Context, ERC165, IERC721, IERC721Metadata {
using Address for address;
using Strings for uint256;
// Token name
string private _name;
// Token symbol
string private _symbol;
// Mapping from token ID to owner address
mapping(uint256 => address) private _owners;
// Mapping owner address to token count
mapping(address => uint256) private _balances;
// Mapping from token ID to approved address
mapping(uint256 => address) private _tokenApprovals;
// Mapping from owner to operator approvals
mapping(address => mapping(address => bool)) private _operatorApprovals;
/**
* @dev Initializes the contract by setting a `name` and a `symbol` to the token collection.
*/
constructor(string memory name_, string memory symbol_) {
_name = name_;
_symbol = symbol_;
}
/**
* @dev See {IERC165-supportsInterface}.
*/
function supportsInterface(bytes4 interfaceId) public view virtual override(ERC165, IERC165) returns (bool) {
return
interfaceId == type(IERC721).interfaceId ||
interfaceId == type(IERC721Metadata).interfaceId ||
super.supportsInterface(interfaceId);
}
/**
* @dev See {IERC721-balanceOf}.
*/
function balanceOf(address owner) public view virtual override returns (uint256) {
require(owner != address(0), "ERC721: balance query for the zero address");
return _balances[owner];
}
/**
* @dev See {IERC721-ownerOf}.
*/
function ownerOf(uint256 tokenId) public view virtual override returns (address) {
address owner = _owners[tokenId];
require(owner != address(0), "ERC721: owner query for nonexistent token");
return owner;
}
/**
* @dev See {IERC721Metadata-name}.
*/
function name() public view virtual override returns (string memory) {
return _name;
}
/**
* @dev See {IERC721Metadata-symbol}.
*/
function symbol() public view virtual override returns (string memory) {
return _symbol;
}
/**
* @dev See {IERC721Metadata-tokenURI}.
*/
function tokenURI(uint256 tokenId) public view virtual override returns (string memory) {
require(_exists(tokenId), "ERC721Metadata: URI query for nonexistent token");
string memory baseURI = _baseURI();
return bytes(baseURI).length > 0 ? string(abi.encodePacked(baseURI, tokenId.toString())) : "";
}
/**
* @dev Base URI for computing {tokenURI}. If set, the resulting URI for each
* token will be the concatenation of the `baseURI` and the `tokenId`. Empty
* by default, can be overriden in child contracts.
*/
function _baseURI() internal view virtual returns (string memory) {
return "";
}
/**
* @dev See {IERC721-approve}.
*/
function approve(address to, uint256 tokenId) public virtual override {
address owner = ERC721.ownerOf(tokenId);
require(to != owner, "ERC721: approval to current owner");
require(
_msgSender() == owner || isApprovedForAll(owner, _msgSender()),
"ERC721: approve caller is not owner nor approved for all"
);
_approve(to, tokenId);
}
/**
* @dev See {IERC721-getApproved}.
*/
function getApproved(uint256 tokenId) public view virtual override returns (address) {
require(_exists(tokenId), "ERC721: approved query for nonexistent token");
return _tokenApprovals[tokenId];
}
/**
* @dev See {IERC721-setApprovalForAll}.
*/
function setApprovalForAll(address operator, bool approved) public virtual override {
_setApprovalForAll(_msgSender(), operator, approved);
}
/**
* @dev See {IERC721-isApprovedForAll}.
*/
function isApprovedForAll(address owner, address operator) public view virtual override returns (bool) {
return _operatorApprovals[owner][operator];
}
/**
* @dev See {IERC721-transferFrom}.
*/
function transferFrom(
address from,
address to,
uint256 tokenId
) public virtual override {
//solhint-disable-next-line max-line-length
require(_isApprovedOrOwner(_msgSender(), tokenId), "ERC721: transfer caller is not owner nor approved");
_transfer(from, to, tokenId);
}
/**
* @dev See {IERC721-safeTransferFrom}.
*/
function safeTransferFrom(
address from,
address to,
uint256 tokenId
) public virtual override {
safeTransferFrom(from, to, tokenId, "");
}
/**
* @dev See {IERC721-safeTransferFrom}.
*/
function safeTransferFrom(
address from,
address to,
uint256 tokenId,
bytes memory _data
) public virtual override {
require(_isApprovedOrOwner(_msgSender(), tokenId), "ERC721: transfer caller is not owner nor approved");
_safeTransfer(from, to, tokenId, _data);
}
/**
* @dev Safely transfers `tokenId` token from `from` to `to`, checking first that contract recipients
* are aware of the ERC721 protocol to prevent tokens from being forever locked.
*
* `_data` is additional data, it has no specified format and it is sent in call to `to`.
*
* This internal function is equivalent to {safeTransferFrom}, and can be used to e.g.
* implement alternative mechanisms to perform token transfer, such as signature-based.
*
* Requirements:
*
* - `from` cannot be the zero address.
* - `to` cannot be the zero address.
* - `tokenId` token must exist and be owned by `from`.
* - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer.
*
* Emits a {Transfer} event.
*/
function _safeTransfer(
address from,
address to,
uint256 tokenId,
bytes memory _data
) internal virtual {
_transfer(from, to, tokenId);
require(_checkOnERC721Received(from, to, tokenId, _data), "ERC721: transfer to non ERC721Receiver implementer");
}
/**
* @dev Returns whether `tokenId` exists.
*
* Tokens can be managed by their owner or approved accounts via {approve} or {setApprovalForAll}.
*
* Tokens start existing when they are minted (`_mint`),
* and stop existing when they are burned (`_burn`).
*/
function _exists(uint256 tokenId) internal view virtual returns (bool) {
return _owners[tokenId] != address(0);
}
/**
* @dev Returns whether `spender` is allowed to manage `tokenId`.
*
* Requirements:
*
* - `tokenId` must exist.
*/
function _isApprovedOrOwner(address spender, uint256 tokenId) internal view virtual returns (bool) {
require(_exists(tokenId), "ERC721: operator query for nonexistent token");
address owner = ERC721.ownerOf(tokenId);
return (spender == owner || getApproved(tokenId) == spender || isApprovedForAll(owner, spender));
}
/**
* @dev Safely mints `tokenId` and transfers it to `to`.
*
* Requirements:
*
* - `tokenId` must not exist.
* - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer.
*
* Emits a {Transfer} event.
*/
function _safeMint(address to, uint256 tokenId) internal virtual {
_safeMint(to, tokenId, "");
}
/**
* @dev Same as {xref-ERC721-_safeMint-address-uint256-}[`_safeMint`], with an additional `data` parameter which is
* forwarded in {IERC721Receiver-onERC721Received} to contract recipients.
*/
function _safeMint(
address to,
uint256 tokenId,
bytes memory _data
) internal virtual {
_mint(to, tokenId);
require(
_checkOnERC721Received(address(0), to, tokenId, _data),
"ERC721: transfer to non ERC721Receiver implementer"
);
}
/**
* @dev Mints `tokenId` and transfers it to `to`.
*
* WARNING: Usage of this method is discouraged, use {_safeMint} whenever possible
*
* Requirements:
*
* - `tokenId` must not exist.
* - `to` cannot be the zero address.
*
* Emits a {Transfer} event.
*/
function _mint(address to, uint256 tokenId) internal virtual {
require(to != address(0), "ERC721: mint to the zero address");
require(!_exists(tokenId), "ERC721: token already minted");
_beforeTokenTransfer(address(0), to, tokenId);
_balances[to] += 1;
_owners[tokenId] = to;
emit Transfer(address(0), to, tokenId);
_afterTokenTransfer(address(0), to, tokenId);
}
/**
* @dev Destroys `tokenId`.
* The approval is cleared when the token is burned.
*
* Requirements:
*
* - `tokenId` must exist.
*
* Emits a {Transfer} event.
*/
function _burn(uint256 tokenId) internal virtual {
address owner = ERC721.ownerOf(tokenId);
_beforeTokenTransfer(owner, address(0), tokenId);
// Clear approvals
_approve(address(0), tokenId);
_balances[owner] -= 1;
delete _owners[tokenId];
emit Transfer(owner, address(0), tokenId);
_afterTokenTransfer(owner, address(0), tokenId);
}
/**
* @dev Transfers `tokenId` from `from` to `to`.
* As opposed to {transferFrom}, this imposes no restrictions on msg.sender.
*
* Requirements:
*
* - `to` cannot be the zero address.
* - `tokenId` token must be owned by `from`.
*
* Emits a {Transfer} event.
*/
function _transfer(
address from,
address to,
uint256 tokenId
) internal virtual {
require(ERC721.ownerOf(tokenId) == from, "ERC721: transfer from incorrect owner");
require(to != address(0), "ERC721: transfer to the zero address");
_beforeTokenTransfer(from, to, tokenId);
// Clear approvals from the previous owner
_approve(address(0), tokenId);
_balances[from] -= 1;
_balances[to] += 1;
_owners[tokenId] = to;
emit Transfer(from, to, tokenId);
_afterTokenTransfer(from, to, tokenId);
}
/**
* @dev Approve `to` to operate on `tokenId`
*
* Emits a {Approval} event.
*/
function _approve(address to, uint256 tokenId) internal virtual {
_tokenApprovals[tokenId] = to;
emit Approval(ERC721.ownerOf(tokenId), to, tokenId);
}
/**
* @dev Approve `operator` to operate on all of `owner` tokens
*
* Emits a {ApprovalForAll} event.
*/
function _setApprovalForAll(
address owner,
address operator,
bool approved
) internal virtual {
require(owner != operator, "ERC721: approve to caller");
_operatorApprovals[owner][operator] = approved;
emit ApprovalForAll(owner, operator, approved);
}
/**
* @dev Internal function to invoke {IERC721Receiver-onERC721Received} on a target address.
* The call is not executed if the target address is not a contract.
*
* @param from address representing the previous owner of the given token ID
* @param to target address that will receive the tokens
* @param tokenId uint256 ID of the token to be transferred
* @param _data bytes optional data to send along with the call
* @return bool whether the call correctly returned the expected magic value
*/
function _checkOnERC721Received(
address from,
address to,
uint256 tokenId,
bytes memory _data
) private returns (bool) {
if (to.isContract()) {
try IERC721Receiver(to).onERC721Received(_msgSender(), from, tokenId, _data) returns (bytes4 retval) {
return retval == IERC721Receiver.onERC721Received.selector;
} catch (bytes memory reason) {
if (reason.length == 0) {
revert("ERC721: transfer to non ERC721Receiver implementer");
} else {
assembly {
revert(add(32, reason), mload(reason))
}
}
}
} else {
return true;
}
}
/**
* @dev Hook that is called before any token transfer. This includes minting
* and burning.
*
* Calling conditions:
*
* - When `from` and `to` are both non-zero, ``from``'s `tokenId` will be
* transferred to `to`.
* - When `from` is zero, `tokenId` will be minted for `to`.
* - When `to` is zero, ``from``'s `tokenId` will be burned.
* - `from` and `to` are never both zero.
*
* To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks].
*/
function _beforeTokenTransfer(
address from,
address to,
uint256 tokenId
) internal virtual {}
/**
* @dev Hook that is called after any transfer of tokens. This includes
* minting and burning.
*
* Calling conditions:
*
* - when `from` and `to` are both non-zero.
* - `from` and `to` are never both zero.
*
* To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks].
*/
function _afterTokenTransfer(
address from,
address to,
uint256 tokenId
) internal virtual {}
}
// File: contracts/24ct Parrots.sol
pragma solidity >=0.7.0 <0.9.0;
contract TwentyfourCaratParrots is ERC721, Ownable {
using Strings for uint256;
using Counters for Counters.Counter;
Counters.Counter private supply;
string public uriPrefix = "";
string public uriSuffix = ".json";
string public hiddenMetadataUri;
uint256 public cost = 0.045 ether;
uint256 public maxSupply = 10000;
uint256 public maxMintAmountPerTx = 10;
bool public paused = true;
bool public revealed = false;
bool public onlyWhitelistedParrots = true;
address[] public whitelistUsers;
constructor() ERC721("24ct Parrots", "24CTPA") {
setHiddenMetadataUri("ipfs://QmNhdYZ2hYza77ybQxKMPvapbQjj8MEgueQKnRTy7cahQL/Hidden.json");
}
modifier mintCompliance(uint256 _mintAmount) {
require(_mintAmount > 0 && _mintAmount <= maxMintAmountPerTx, "Invalid mint amount!");
require(supply.current() + _mintAmount <= maxSupply, "Max supply exceeded!");
_;
}
function totalSupply() public view returns (uint256) {
return supply.current();
}
function mint(uint256 _mintAmount) public payable mintCompliance(_mintAmount) {
require(!paused, "The contract is paused!");
if(onlyWhitelistedParrots == true) {
require(isWhitelisted(msg.sender), "user not whitelisted");
}
require(msg.value >= cost * _mintAmount, "Insufficient funds!");
_mintLoop(msg.sender, _mintAmount);
}
function mintForAddress(uint256 _mintAmount, address _receiver) public mintCompliance(_mintAmount) onlyOwner {
_mintLoop(_receiver, _mintAmount);
}
function isWhitelisted(address _user) public view returns (bool) {
for(uint256 i = 0; i <whitelistUsers.length; i++) {
if (whitelistUsers [i] == _user) {
return true;
}
}
return false;
}
function walletOfOwner(address _owner)
public
view
returns (uint256[] memory)
{
uint256 ownerTokenCount = balanceOf(_owner);
uint256[] memory ownedTokenIds = new uint256[](ownerTokenCount);
uint256 currentTokenId = 1;
uint256 ownedTokenIndex = 0;
while (ownedTokenIndex < ownerTokenCount && currentTokenId <= maxSupply) {
address currentTokenOwner = ownerOf(currentTokenId);
if (currentTokenOwner == _owner) {
ownedTokenIds[ownedTokenIndex] = currentTokenId;
ownedTokenIndex++;
}
currentTokenId++;
}
return ownedTokenIds;
}
function tokenURI(uint256 _tokenId)
public
view
virtual
override
returns (string memory)
{
require(
_exists(_tokenId),
"ERC721Metadata: URI query for nonexistent token"
);
if (revealed == false) {
return hiddenMetadataUri;
}
string memory currentBaseURI = _baseURI();
return bytes(currentBaseURI).length > 0
? string(abi.encodePacked(currentBaseURI, _tokenId.toString(), uriSuffix))
: "";
}
function setRevealed(bool _state) public onlyOwner {
revealed = _state;
}
function setCost(uint256 _cost) public onlyOwner {
cost = _cost;
}
function setMaxMintAmountPerTx(uint256 _maxMintAmountPerTx) public onlyOwner {
maxMintAmountPerTx = _maxMintAmountPerTx;
}
function setHiddenMetadataUri(string memory _hiddenMetadataUri) public onlyOwner {
hiddenMetadataUri = _hiddenMetadataUri;
}
function setUriPrefix(string memory _uriPrefix) public onlyOwner {
uriPrefix = _uriPrefix;
}
function whitelistparrots(address [] calldata _users) public onlyOwner {
whitelistUsers = _users;
}
function setUriSuffix(string memory _uriSuffix) public onlyOwner {
uriSuffix = _uriSuffix;
}
function setPaused(bool _state) public onlyOwner {
paused = _state;
}
function setOnlyWhitelised(bool _state) public onlyOwner {
onlyWhitelistedParrots = _state;
}
function withdraw() public onlyOwner {
(bool os, ) = payable(owner()).call{value: address(this).balance}("");
require(os);
}
function _mintLoop(address _receiver, uint256 _mintAmount) internal {
for (uint256 i = 0; i < _mintAmount; i++) {
supply.increment();
_safeMint(_receiver, supply.current());
}
}
function _baseURI() internal view virtual override returns (string memory) {
return uriPrefix;
}
} | File: contracts/24ct Parrots.sol | contract TwentyfourCaratParrots is ERC721, Ownable {
using Strings for uint256;
using Counters for Counters.Counter;
Counters.Counter private supply;
string public uriPrefix = "";
string public uriSuffix = ".json";
string public hiddenMetadataUri;
uint256 public cost = 0.045 ether;
uint256 public maxSupply = 10000;
uint256 public maxMintAmountPerTx = 10;
bool public paused = true;
bool public revealed = false;
bool public onlyWhitelistedParrots = true;
address[] public whitelistUsers;
function _beforeTokenTransfer(
address from,
address to,
uint256 tokenId
function _afterTokenTransfer(
address from,
address to,
uint256 tokenId
}
pragma solidity >=0.7.0 <0.9.0;
constructor() ERC721("24ct Parrots", "24CTPA") {
}
modifier mintCompliance(uint256 _mintAmount) {
require(_mintAmount > 0 && _mintAmount <= maxMintAmountPerTx, "Invalid mint amount!");
require(supply.current() + _mintAmount <= maxSupply, "Max supply exceeded!");
_;
}
function totalSupply() public view returns (uint256) {
return supply.current();
}
function mint(uint256 _mintAmount) public payable mintCompliance(_mintAmount) {
require(!paused, "The contract is paused!");
if(onlyWhitelistedParrots == true) {
require(isWhitelisted(msg.sender), "user not whitelisted");
}
require(msg.value >= cost * _mintAmount, "Insufficient funds!");
_mintLoop(msg.sender, _mintAmount);
}
function mint(uint256 _mintAmount) public payable mintCompliance(_mintAmount) {
require(!paused, "The contract is paused!");
if(onlyWhitelistedParrots == true) {
require(isWhitelisted(msg.sender), "user not whitelisted");
}
require(msg.value >= cost * _mintAmount, "Insufficient funds!");
_mintLoop(msg.sender, _mintAmount);
}
function mintForAddress(uint256 _mintAmount, address _receiver) public mintCompliance(_mintAmount) onlyOwner {
_mintLoop(_receiver, _mintAmount);
}
function isWhitelisted(address _user) public view returns (bool) {
for(uint256 i = 0; i <whitelistUsers.length; i++) {
if (whitelistUsers [i] == _user) {
return true;
}
}
return false;
}
function isWhitelisted(address _user) public view returns (bool) {
for(uint256 i = 0; i <whitelistUsers.length; i++) {
if (whitelistUsers [i] == _user) {
return true;
}
}
return false;
}
function isWhitelisted(address _user) public view returns (bool) {
for(uint256 i = 0; i <whitelistUsers.length; i++) {
if (whitelistUsers [i] == _user) {
return true;
}
}
return false;
}
function walletOfOwner(address _owner)
public
view
returns (uint256[] memory)
{
uint256 ownerTokenCount = balanceOf(_owner);
uint256[] memory ownedTokenIds = new uint256[](ownerTokenCount);
uint256 currentTokenId = 1;
uint256 ownedTokenIndex = 0;
while (ownedTokenIndex < ownerTokenCount && currentTokenId <= maxSupply) {
address currentTokenOwner = ownerOf(currentTokenId);
if (currentTokenOwner == _owner) {
ownedTokenIds[ownedTokenIndex] = currentTokenId;
ownedTokenIndex++;
}
currentTokenId++;
}
return ownedTokenIds;
}
function walletOfOwner(address _owner)
public
view
returns (uint256[] memory)
{
uint256 ownerTokenCount = balanceOf(_owner);
uint256[] memory ownedTokenIds = new uint256[](ownerTokenCount);
uint256 currentTokenId = 1;
uint256 ownedTokenIndex = 0;
while (ownedTokenIndex < ownerTokenCount && currentTokenId <= maxSupply) {
address currentTokenOwner = ownerOf(currentTokenId);
if (currentTokenOwner == _owner) {
ownedTokenIds[ownedTokenIndex] = currentTokenId;
ownedTokenIndex++;
}
currentTokenId++;
}
return ownedTokenIds;
}
function walletOfOwner(address _owner)
public
view
returns (uint256[] memory)
{
uint256 ownerTokenCount = balanceOf(_owner);
uint256[] memory ownedTokenIds = new uint256[](ownerTokenCount);
uint256 currentTokenId = 1;
uint256 ownedTokenIndex = 0;
while (ownedTokenIndex < ownerTokenCount && currentTokenId <= maxSupply) {
address currentTokenOwner = ownerOf(currentTokenId);
if (currentTokenOwner == _owner) {
ownedTokenIds[ownedTokenIndex] = currentTokenId;
ownedTokenIndex++;
}
currentTokenId++;
}
return ownedTokenIds;
}
function tokenURI(uint256 _tokenId)
public
view
virtual
override
returns (string memory)
{
require(
_exists(_tokenId),
"ERC721Metadata: URI query for nonexistent token"
);
if (revealed == false) {
return hiddenMetadataUri;
}
string memory currentBaseURI = _baseURI();
return bytes(currentBaseURI).length > 0
? string(abi.encodePacked(currentBaseURI, _tokenId.toString(), uriSuffix))
: "";
}
function tokenURI(uint256 _tokenId)
public
view
virtual
override
returns (string memory)
{
require(
_exists(_tokenId),
"ERC721Metadata: URI query for nonexistent token"
);
if (revealed == false) {
return hiddenMetadataUri;
}
string memory currentBaseURI = _baseURI();
return bytes(currentBaseURI).length > 0
? string(abi.encodePacked(currentBaseURI, _tokenId.toString(), uriSuffix))
: "";
}
function setRevealed(bool _state) public onlyOwner {
revealed = _state;
}
function setCost(uint256 _cost) public onlyOwner {
cost = _cost;
}
function setMaxMintAmountPerTx(uint256 _maxMintAmountPerTx) public onlyOwner {
maxMintAmountPerTx = _maxMintAmountPerTx;
}
function setHiddenMetadataUri(string memory _hiddenMetadataUri) public onlyOwner {
hiddenMetadataUri = _hiddenMetadataUri;
}
function setUriPrefix(string memory _uriPrefix) public onlyOwner {
uriPrefix = _uriPrefix;
}
function whitelistparrots(address [] calldata _users) public onlyOwner {
whitelistUsers = _users;
}
function setUriSuffix(string memory _uriSuffix) public onlyOwner {
uriSuffix = _uriSuffix;
}
function setPaused(bool _state) public onlyOwner {
paused = _state;
}
function setOnlyWhitelised(bool _state) public onlyOwner {
onlyWhitelistedParrots = _state;
}
function withdraw() public onlyOwner {
require(os);
}
(bool os, ) = payable(owner()).call{value: address(this).balance}("");
function _mintLoop(address _receiver, uint256 _mintAmount) internal {
for (uint256 i = 0; i < _mintAmount; i++) {
supply.increment();
_safeMint(_receiver, supply.current());
}
}
function _mintLoop(address _receiver, uint256 _mintAmount) internal {
for (uint256 i = 0; i < _mintAmount; i++) {
supply.increment();
_safeMint(_receiver, supply.current());
}
}
function _baseURI() internal view virtual override returns (string memory) {
return uriPrefix;
}
} | 633,996 | [
1,
812,
30,
20092,
19,
3247,
299,
2280,
303,
3428,
18,
18281,
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,
12694,
319,
93,
74,
477,
16321,
270,
1553,
303,
3428,
353,
4232,
39,
27,
5340,
16,
14223,
6914,
288,
203,
225,
1450,
8139,
364,
2254,
5034,
31,
203,
225,
1450,
9354,
87,
364,
9354,
87,
18,
4789,
31,
203,
203,
225,
9354,
87,
18,
4789,
3238,
14467,
31,
203,
203,
225,
533,
1071,
2003,
2244,
273,
1408,
31,
203,
225,
533,
1071,
2003,
5791,
273,
3552,
1977,
14432,
203,
225,
533,
1071,
5949,
2277,
3006,
31,
203,
21281,
225,
2254,
5034,
1071,
6991,
273,
374,
18,
3028,
25,
225,
2437,
31,
203,
225,
2254,
5034,
1071,
943,
3088,
1283,
273,
12619,
31,
203,
225,
2254,
5034,
1071,
943,
49,
474,
6275,
2173,
4188,
273,
1728,
31,
203,
203,
203,
203,
225,
1426,
1071,
17781,
273,
638,
31,
203,
225,
1426,
1071,
283,
537,
18931,
273,
629,
31,
203,
225,
1426,
1071,
1338,
18927,
329,
1553,
303,
3428,
273,
638,
31,
203,
203,
225,
1758,
8526,
1071,
10734,
6588,
31,
203,
203,
565,
445,
389,
5771,
1345,
5912,
12,
203,
3639,
1758,
628,
16,
203,
3639,
1758,
358,
16,
203,
3639,
2254,
5034,
1147,
548,
203,
203,
565,
445,
389,
5205,
1345,
5912,
12,
203,
3639,
1758,
628,
16,
203,
3639,
1758,
358,
16,
203,
3639,
2254,
5034,
1147,
548,
203,
97,
203,
203,
203,
203,
203,
683,
9454,
18035,
560,
1545,
20,
18,
27,
18,
20,
411,
20,
18,
29,
18,
20,
31,
203,
203,
203,
203,
203,
225,
3885,
1435,
4232,
39,
27,
5340,
2932,
3247,
299,
2280,
303,
3428,
3113,
315,
2
] |
/**************************************************************************
* ____ _
* / ___| | | __ _ _ _ ___ _ __
* | | _____ | | / _` || | | | / _ \| '__|
* | |___|_____|| |___| (_| || |_| || __/| |
* \____| |_____|\__,_| \__, | \___||_|
* |___/
*
**************************************************************************
*
* The MIT License (MIT)
* SPDX-License-Identifier: MIT
*
* Copyright (c) 2016-2020 Cyril Lapinte
*
* 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.
*
**************************************************************************
*
* Flatten Contract: WrappedERC20
*
* Git Commit:
* https://github.com/c-layer/contracts/commit/9993912325afde36151b04d0247ac9ea9ffa2a93
*
**************************************************************************/
// File: @c-layer/common/contracts/interface/IERC20.sol
pragma solidity ^0.6.0;
/**
* @title IERC20 interface
* @dev see https://github.com/ethereum/EIPs/issues/20
* @dev see https://github.com/ethereum/EIPs/issues/179
*
*/
interface IERC20 {
event Transfer(address indexed from, address indexed to, uint256 value);
event Approval(
address indexed owner,
address indexed spender,
uint256 value
);
function name() external view returns (string memory);
function symbol() external view returns (string memory);
function decimals() external view returns (uint256);
function totalSupply() external view returns (uint256);
function balanceOf(address _owner) external view returns (uint256);
function transfer(address _to, uint256 _value) external returns (bool);
function allowance(address _owner, address _spender)
external view returns (uint256);
function transferFrom(address _from, address _to, uint256 _value)
external returns (bool);
function approve(address _spender, uint256 _value) external returns (bool);
function increaseApproval(address _spender, uint256 _addedValue)
external returns (bool);
function decreaseApproval(address _spender, uint256 _subtractedValue)
external returns (bool);
}
// File: @c-layer/common/contracts/math/SafeMath.sol
pragma solidity ^0.6.0;
/**
* @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: @c-layer/common/contracts/token/TokenERC20.sol
pragma solidity ^0.6.0;
/**
* @title Token ERC20
* @dev Token ERC20 default implementation
*
* @author Cyril Lapinte - <[email protected]>
*
* Error messages
* TE01: Address is invalid
* TE02: Not enougth tokens
* TE03: Approval too low
*/
contract TokenERC20 is IERC20 {
using SafeMath for uint256;
string internal name_;
string internal symbol_;
uint256 internal decimals_;
uint256 internal totalSupply_;
mapping(address => uint256) internal balances;
mapping (address => mapping (address => uint256)) internal allowed;
constructor(
string memory _name,
string memory _symbol,
uint256 _decimals,
address _initialAccount,
uint256 _initialSupply
) public {
name_ = _name;
symbol_ = _symbol;
decimals_ = _decimals;
totalSupply_ = _initialSupply;
balances[_initialAccount] = _initialSupply;
emit Transfer(address(0), _initialAccount, _initialSupply);
}
function name() external override view returns (string memory) {
return name_;
}
function symbol() external override view returns (string memory) {
return symbol_;
}
function decimals() external override view returns (uint256) {
return decimals_;
}
function totalSupply() external override view returns (uint256) {
return totalSupply_;
}
function balanceOf(address _owner) external override view returns (uint256) {
return balances[_owner];
}
function allowance(address _owner, address _spender)
external override view returns (uint256)
{
return allowed[_owner][_spender];
}
function transfer(address _to, uint256 _value) external override returns (bool) {
require(_to != address(0), "TE01");
require(_value <= balances[msg.sender], "TE02");
balances[msg.sender] = balances[msg.sender].sub(_value);
balances[_to] = balances[_to].add(_value);
emit Transfer(msg.sender, _to, _value);
return true;
}
function transferFrom(address _from, address _to, uint256 _value)
external override returns (bool)
{
require(_to != address(0), "TE01");
require(_value <= balances[_from], "TE02");
require(_value <= allowed[_from][msg.sender], "TE03");
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;
}
function approve(address _spender, uint256 _value) external override returns (bool) {
allowed[msg.sender][_spender] = _value;
emit Approval(msg.sender, _spender, _value);
return true;
}
function increaseApproval(address _spender, uint _addedValue)
external override returns (bool)
{
allowed[msg.sender][_spender] = (
allowed[msg.sender][_spender].add(_addedValue));
emit Approval(msg.sender, _spender, allowed[msg.sender][_spender]);
return true;
}
function decreaseApproval(address _spender, uint _subtractedValue)
external override returns (bool)
{
uint oldValue = allowed[msg.sender][_spender];
if (_subtractedValue > oldValue) {
allowed[msg.sender][_spender] = 0;
} else {
allowed[msg.sender][_spender] = oldValue.sub(_subtractedValue);
}
emit Approval(msg.sender, _spender, allowed[msg.sender][_spender]);
return true;
}
}
// File: contracts/interface/IWrappedERC20.sol
pragma solidity ^0.6.0;
/**
* @title WrappedERC20
* @dev WrappedERC20
* @author Cyril Lapinte - <[email protected]>
*
* Error messages
*/
abstract contract IWrappedERC20 is IERC20 {
function base() public view virtual returns (IERC20);
function deposit(uint256 _value) public virtual returns (bool);
function depositTo(address _to, uint256 _value) public virtual returns (bool);
function withdraw(uint256 _value) public virtual returns (bool);
function withdrawFrom(address _from, address _to, uint256 _value) public virtual returns (bool);
event Deposit(address indexed _address, uint256 value);
event Withdrawal(address indexed _address, uint256 value);
}
// File: contracts/WrappedERC20.sol
pragma solidity ^0.6.0;
/**
* @title WrappedERC20
* @dev WrappedERC20
* @author Cyril Lapinte - <[email protected]>
*
* Error messages
* WE01: Unable to transfer tokens to address 0
* WE02: Unable to deposit the base token
* WE03: Not enougth tokens
* WE04: Approval too low
* WE05: Unable to withdraw the base token
*/
contract WrappedERC20 is TokenERC20, IWrappedERC20 {
IERC20 internal base_;
uint256 internal ratio_;
/**
* @dev constructor
*/
constructor(
string memory _name,
string memory _symbol,
uint256 _decimals,
IERC20 _base
) public
TokenERC20(_name, _symbol, _decimals, address(0), 0)
{
ratio_ = 10 ** _decimals.sub(_base.decimals());
base_ = _base;
}
/**
* @dev base token
*/
function base() public view override returns (IERC20) {
return base_;
}
/**
* @dev deposit
*/
function deposit(uint256 _value) public override returns (bool) {
return depositTo(msg.sender, _value);
}
/**
* @dev depositTo
*/
function depositTo(address _to, uint256 _value) public override returns (bool) {
require(_to != address(0), "WE01");
require(base_.transferFrom(msg.sender, address(this), _value), "WE02");
uint256 wrappedValue = _value.mul(ratio_);
balances[_to] = balances[_to].add(wrappedValue);
totalSupply_ = totalSupply_.add(wrappedValue);
emit Transfer(address(0), _to, wrappedValue);
return true;
}
/**
* @dev withdraw
*/
function withdraw(uint256 _value) public override returns (bool) {
return withdrawFrom(msg.sender, msg.sender, _value);
}
/**
* @dev withdrawFrom
*/
function withdrawFrom(address _from, address _to, uint256 _value) public override returns (bool) {
require(_to != address(0), "WE01");
uint256 wrappedValue = _value.mul(ratio_);
require(wrappedValue <= balances[_from], "WE03");
if (_from != msg.sender) {
require(wrappedValue <= allowed[_from][msg.sender], "WE04");
allowed[_from][msg.sender] = allowed[_from][msg.sender].sub(wrappedValue);
}
balances[_from] = balances[_from].sub(wrappedValue);
totalSupply_ = totalSupply_.sub(wrappedValue);
emit Transfer(_from, address(0), wrappedValue);
require(base_.transfer(_to, _value), "WE05");
return true;
}
} | * @title WrappedERC20 @dev WrappedERC20 @author Cyril Lapinte - <[email protected]> Error messages/ | abstract contract IWrappedERC20 is IERC20 {
function base() public view virtual returns (IERC20);
function deposit(uint256 _value) public virtual returns (bool);
function depositTo(address _to, uint256 _value) public virtual returns (bool);
function withdraw(uint256 _value) public virtual returns (bool);
function withdrawFrom(address _from, address _to, uint256 _value) public virtual returns (bool);
event Deposit(address indexed _address, uint256 value);
event Withdrawal(address indexed _address, uint256 value);
}
| 11,960,087 | [
1,
17665,
654,
39,
3462,
225,
24506,
654,
39,
3462,
225,
22337,
86,
330,
511,
438,
474,
73,
300,
411,
2431,
86,
330,
36,
3190,
74,
452,
18,
832,
34,
1068,
2743,
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,
467,
17665,
654,
39,
3462,
353,
467,
654,
39,
3462,
288,
203,
203,
225,
445,
1026,
1435,
1071,
1476,
5024,
1135,
261,
45,
654,
39,
3462,
1769,
203,
203,
225,
445,
443,
1724,
12,
11890,
5034,
389,
1132,
13,
1071,
5024,
1135,
261,
6430,
1769,
203,
225,
445,
443,
1724,
774,
12,
2867,
389,
869,
16,
2254,
5034,
389,
1132,
13,
1071,
5024,
1135,
261,
6430,
1769,
203,
203,
225,
445,
598,
9446,
12,
11890,
5034,
389,
1132,
13,
1071,
5024,
1135,
261,
6430,
1769,
203,
225,
445,
598,
9446,
1265,
12,
2867,
389,
2080,
16,
1758,
389,
869,
16,
2254,
5034,
389,
1132,
13,
1071,
5024,
1135,
261,
6430,
1769,
203,
203,
225,
871,
4019,
538,
305,
12,
2867,
8808,
389,
2867,
16,
2254,
5034,
460,
1769,
203,
225,
871,
3423,
9446,
287,
12,
2867,
8808,
389,
2867,
16,
2254,
5034,
460,
1769,
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
] |
pragma solidity ^0.5.0;
import "./PublishBook.sol";
import "./Address.sol";
import "./SafeMath.sol";
import "./Counters.sol";
contract Tokenize is PublishBook {
using SafeMath for uint256;
using Address for address;
using Counters for Counters.Counter;
// Equals to `bytes4(keccak256("onERC721Received(address,address,uint256,bytes)"))`
// which can be also obtained as `IERC721Receiver(0).onERC721Received.selector`
bytes4 private constant _ERC721_RECEIVED = 0x150b7a02;
// Mapping from token ID to owner
mapping (uint256 => address) internal _tokenOwner;
// Mapping from token ID to approved address
mapping (uint256 => address) internal _tokenApprovals;
// Mapping from owner to number of owned token
mapping (address => Counters.Counter) internal _ownedTokensCount;
event Transfer(address indexed from, address indexed to, uint256 indexed tokenId);
event BookPublished(address indexed publisher, uint256 indexed isbn);
uint256 tokenCounter; //arbitrary counter to help generate unique tokenID
struct Reselling{
uint256 resalePrice;
bool isUpForResale;
uint256 ISBN;
}
//tokenID to Reselling mapping
mapping (uint256 => Reselling) internal reSale;
//This will be the tokendata.
struct tokenIPFS{
string ipfsHash;
}
//tokenId to tokenIPFS mapping
mapping(uint256 => tokenIPFS) internal tokenData;
/**
* @dev Gets the token name
* @return string representing the token name
*/
function name() external view returns (string memory) {
return "DContentToken";
}
/**
* @dev Gets the token symbol
* @return string representing the token symbol
*/
function symbol() external view returns (string memory) {
return "DCT";
}
//function to check if tokenId exists with a user
function _exists(uint256 tokenId) internal view returns (bool) {
address owner = _tokenOwner[tokenId];
return owner != address(0);
}
//function to check who the owner of a token is
function ownerOf(uint256 tokenId) public view returns (address) {
address owner = _tokenOwner[tokenId];
require(owner != address(0));
return owner;
}
//tokenId a value that will be less than 10,000,000
function generateTokenID(uint256 isbn) private returns(uint256){
tokenCounter++;
uint256 tokenid = uint256(keccak256(abi.encodePacked(isbn, now,tokenCounter))) % 10000000;
return(tokenid);
}
//function that creates the token
function _mint(address to, uint256 tokenId, uint256 isbn) internal {
require(to != address(0),"Address(0) Error !");
require(!_exists(tokenId),"Token ID already exists !");
_tokenOwner[tokenId] = to;
_ownedTokensCount[to].increment();
//resalePrice set to initial MRP by default
reSale[tokenId].resalePrice = setPrice[isbn];
//token is not up for resale by default; the owner needs to put it up for sale
reSale[tokenId].isUpForResale = false;
reSale[tokenId].ISBN = isbn;
tokenData[tokenId].ipfsHash = fileinfo[isbn].ipfsHash;
emit Transfer(address(0), to, tokenId);
}
//function to add book details into the chain i.e. publish the book
function addBookDetails (string memory _ipfshash, uint256 _isbn, uint256 _price, uint256 _saleCommission) public {
require(fileinfo[_isbn].publisherAddress==address(0), "This book has already been published!");
fileinfo[_isbn].ipfsHash = _ipfshash;
fileinfo[_isbn].publisherAddress = msg.sender;
fileinfo[_isbn].saleCommission = _saleCommission;
setPrice[_isbn] = _price*1 wei;
emit BookPublished(msg.sender, _isbn);
}
//function to get all cash stored in contract back into the respective owners' account
function withdrawBalance() public payable{
require(publisherBalance[msg.sender]!=0, "You don't have any balance to withdraw");
(msg.sender).transfer(publisherBalance[msg.sender]);
publisherBalance[msg.sender] = 0;
}
//function that executes the first purchase of token from the contract
function primaryBuy(uint isbn) public payable returns (bool) {
//to revert back if the buyer doesn't have the price by the author.
require(fileinfo[isbn].publisherAddress != address(0),"ISBN does not exist !");
require(msg.value == setPrice[isbn],"Insufficient funds ! Please pay the price as set by the author.");
uint256 tokenId = generateTokenID(isbn);
_mint(msg.sender, tokenId,isbn);
//publisher's balance gets updated
publisherBalance[fileinfo[isbn].publisherAddress] += msg.value;
return true;
}
}
| * @dev Gets the token symbol @return string representing the token symbol/ | function symbol() external view returns (string memory) {
return "DCT";
}
| 14,058,709 | [
1,
3002,
326,
1147,
3273,
327,
533,
5123,
326,
1147,
3273,
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
] | [
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,
565,
445,
3273,
1435,
3903,
1476,
1135,
261,
1080,
3778,
13,
288,
203,
3639,
327,
315,
40,
1268,
14432,
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
] |
/**
*Submitted for verification at Etherscan.io on 2020-03-04
*/
/*
* Copyright ©️ 2018-2020 Galt•Project Society Construction and Terraforming Company
* (Founded by [Nikolai Popeka](https://github.com/npopeka)
*
* Copyright ©️ 2018-2020 Galt•Core Blockchain Company
* (Founded by [Nikolai Popeka](https://github.com/npopeka) by
* [Basic Agreement](ipfs/QmaCiXUmSrP16Gz8Jdzq6AJESY1EAANmmwha15uR3c1bsS)).
*
* 🌎 Galt Project is an international decentralized land and real estate property registry
* governed by DAO (Decentralized autonomous organization) and self-governance platform for communities
* of homeowners on Ethereum.
*
* 🏡 https://galtproject.io
*/
interface IOwnedUpgradeabilityProxy {
function implementation() external view returns (address);
function proxyOwner() external view returns (address owner);
function transferProxyOwnership(address newOwner) external;
function upgradeTo(address _implementation) external;
function upgradeToAndCall(address _implementation, bytes calldata _data) external payable;
}
interface UpgradeScript {
function argsWithSignature() external view returns (bytes memory);
}
contract Proxy {
/**
* @dev Tells the address of the implementation where every call will be delegated.
* Should be implemented in a descendant contract
* @return address of the implementation to which it will be delegated
*/
function implementation() public view returns (address) {
assert(false);
}
/**
* @dev Fallback function allowing to perform a delegatecall to the given implementation.
* This function will return whatever the implementation call returns
*/
function () payable external {
address _impl = implementation();
require(_impl != address(0));
assembly {
let ptr := mload(0x40)
calldatacopy(ptr, 0, calldatasize)
let result := delegatecall(gas, _impl, ptr, calldatasize, 0, 0)
let size := returndatasize
returndatacopy(ptr, 0, size)
switch result
case 0 { revert(ptr, size) }
default { return(ptr, size) }
}
}
}
contract UpgradeabilityProxy is Proxy {
/**
* @dev This event will be emitted every time the implementation gets upgraded
* @param implementation representing the address of the upgraded implementation
*/
event Upgraded(address indexed implementation);
// Storage position of the address of the current implementation
bytes32 private constant implementationPosition = keccak256("io.galtproject.proxy.implementation");
/**
* @dev Constructor function
*/
constructor() public {}
/**
* @dev Tells the address of the current implementation
* @return address of the current implementation
*/
function implementation() public view returns (address impl) {
bytes32 position = implementationPosition;
assembly {
impl := sload(position)
}
}
/**
* @dev Sets the address of the current implementation
* @param newImplementation address representing the new implementation to be set
*/
function setImplementation(address newImplementation) internal {
bytes32 position = implementationPosition;
assembly {
sstore(position, newImplementation)
}
}
/**
* @dev Upgrades the implementation address
* @param newImplementation representing the address of the new implementation to be set
*/
function _upgradeTo(address newImplementation) internal {
address currentImplementation = implementation();
require(currentImplementation != newImplementation);
setImplementation(newImplementation);
emit Upgraded(newImplementation);
}
}
contract OwnedUpgradeabilityProxy is IOwnedUpgradeabilityProxy, UpgradeabilityProxy {
/**
* @dev Event to show ownership has been transferred
* @param previousOwner representing the address of the previous owner
* @param newOwner representing the address of the new owner
*/
event ProxyOwnershipTransferred(address previousOwner, address newOwner);
// Storage position of the owner of the contract
bytes32 private constant proxyOwnerPosition = keccak256("io.galtproject.proxy.owner");
/**
* @dev the constructor sets the original owner of the contract to the sender account.
*/
constructor() public {
setUpgradeabilityOwner(msg.sender);
}
/**
* @dev Throws if called by any account other than the owner.
*/
modifier onlyProxyOwner() {
require(msg.sender == proxyOwner());
_;
}
/**
* @dev Tells the address of the owner
* @return the address of the owner
*/
function proxyOwner() public view returns (address owner) {
bytes32 position = proxyOwnerPosition;
assembly {
owner := sload(position)
}
}
/**
* @dev Sets the address of the owner
*/
function setUpgradeabilityOwner(address newProxyOwner) internal {
bytes32 position = proxyOwnerPosition;
assembly {
sstore(position, newProxyOwner)
}
}
/**
* @dev Allows the current owner to transfer control of the contract to a newOwner.
* @param newOwner The address to transfer ownership to.
*/
function transferProxyOwnership(address newOwner) external onlyProxyOwner {
require(newOwner != address(0));
emit ProxyOwnershipTransferred(proxyOwner(), newOwner);
setUpgradeabilityOwner(newOwner);
}
/**
* @dev Allows the proxy owner to upgrade the current version of the proxy.
* @param implementation representing the address of the new implementation to be set.
*/
function upgradeTo(address implementation) external onlyProxyOwner {
_upgradeTo(implementation);
}
/**
* @dev Allows the proxy owner to upgrade the current version of the proxy and call the new implementation
* to initialize whatever is needed through a low level call.
* @param implementation representing the address of the new implementation to be set.
* @param data represents the msg.data to bet sent in the low level call. This parameter may include the function
* signature of the implementation to be called with the needed payload
*/
function upgradeToAndCall(address implementation, bytes calldata data) payable external onlyProxyOwner {
_upgradeTo(implementation);
(bool x,) = address(this).call.value(msg.value)(data);
require(x);
}
}
interface IOwnedUpgradeabilityProxyFactory {
function build() external returns(IOwnedUpgradeabilityProxy);
}
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;
}
}
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 {
_owner = _msgSender();
emit OwnershipTransferred(address(0), _owner);
}
/**
* @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;
}
}
contract FundBareFactory {
address public implementation;
IOwnedUpgradeabilityProxyFactory internal ownedUpgradeabilityProxyFactory;
constructor(IOwnedUpgradeabilityProxyFactory _factory, address _impl) public {
ownedUpgradeabilityProxyFactory = _factory;
implementation = _impl;
}
function build()
external
returns (address)
{
return _build("initialize(address)", address(this), true, true);
}
function build(address _addressArgument, bool _transferOwnership, bool _transferProxyOwnership)
external
returns (address)
{
return _build("initialize(address)", _addressArgument, _transferOwnership, _transferProxyOwnership);
}
function build(string calldata _signature, address _addressArgument, bool _transferOwnership, bool _transferProxyOwnership)
external
returns (address)
{
return _build(_signature, _addressArgument, _transferOwnership, _transferProxyOwnership);
}
function build(bytes calldata _payload, bool _transferOwnership, bool _transferProxyOwnership)
external
returns (address)
{
return _build(_payload, _transferOwnership, _transferProxyOwnership);
}
// INTERNAL
function _build(string memory _signature, address _addressArgument, bool _transferOwnership, bool _transferProxyOwnership)
internal
returns (address)
{
return _build(
abi.encodeWithSignature(_signature, _addressArgument),
_transferOwnership,
_transferProxyOwnership
);
}
function _build(bytes memory _payload, bool _transferOwnership, bool _transferProxyOwnership)
internal
returns (address)
{
IOwnedUpgradeabilityProxy proxy = ownedUpgradeabilityProxyFactory.build();
proxy.upgradeToAndCall(implementation, _payload);
if (_transferOwnership == true) {
Ownable(address(proxy)).transferOwnership(msg.sender);
}
if (_transferProxyOwnership == true) {
proxy.transferProxyOwnership(msg.sender);
}
return address(proxy);
}
}
interface IACL {
function setRole(bytes32 _role, address _candidate, bool _allow) external;
function hasRole(address _candidate, bytes32 _role) external view returns (bool);
}
interface IFundRegistry {
function setContract(bytes32 _key, address _value) external;
// GETTERS
function getContract(bytes32 _key) external view returns (address);
function getGGRAddress() external view returns (address);
function getPPGRAddress() external view returns (address);
function getACL() external view returns (IACL);
function getStorageAddress() external view returns (address);
function getMultiSigAddress() external view returns (address payable);
function getRAAddress() external view returns (address);
function getControllerAddress() external view returns (address);
function getProposalManagerAddress() external view returns (address);
}
contract Initializable {
/**
* @dev Indicates if the contract has been initialized.
*/
bool public initialized;
/**
* @dev Modifier to use in the initialization function of a contract.
*/
modifier isInitializer() {
require(!initialized, "Contract instance has already been initialized");
_;
initialized = true;
}
}
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);
/*
* Constants
*/
uint constant public MAX_OWNER_COUNT = 50;
/*
* Storage
*/
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;
}
/*
* Modifiers
*/
modifier onlyWallet() {
require(msg.sender == address(this));
_;
}
modifier ownerDoesNotExist(address owner) {
require(!isOwner[owner]);
_;
}
modifier ownerExists(address owner) {
require(isOwner[owner]);
_;
}
modifier transactionExists(uint transactionId) {
require(transactions[transactionId].destination != address(0));
_;
}
modifier confirmed(uint transactionId, address owner) {
require(confirmations[transactionId][owner]);
_;
}
modifier notConfirmed(uint transactionId, address owner) {
require(!confirmations[transactionId][owner]);
_;
}
modifier notExecuted(uint transactionId) {
require(!transactions[transactionId].executed);
_;
}
modifier notNull(address _address) {
require(_address != address(0));
_;
}
modifier validRequirement(uint ownerCount, uint _required) {
require(ownerCount <= MAX_OWNER_COUNT
&& _required <= ownerCount
&& _required != 0
&& ownerCount != 0);
_;
}
/// @dev Fallback function allows to deposit ether.
function()
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);
emit 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;
}
owners.length -= 1;
if (required > owners.length)
changeRequirement(owners.length);
emit 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;
emit OwnerRemoval(owner);
emit 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;
emit 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 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;
emit 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;
emit 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;
if (external_call(txn.destination, txn.value, txn.data.length, txn.data))
emit Execution(transactionId);
else {
emit ExecutionFailure(transactionId);
txn.executed = false;
}
}
}
// call has been separated into its own function in order to take advantage
// of the Solidity's code generator to produce a loop that copies tx.data into memory.
function external_call(address destination, uint value, uint dataLength, bytes memory data) private returns (bool) {
bool result;
assembly {
let x := mload(0x40) // "Allocate" memory for output (0x40 is where "free memory" pointer is stored by convention)
let d := add(data, 32) // First 32 bytes are the padded length of data, so exclude that
result := call(
sub(gas, 34710), // 34710 is the value that solidity is currently emitting
// It includes callGas (700) + callVeryLow (3, to pay for SUB) + callValueTransferGas (9000) +
// callNewAccountGas (25000, in case the destination address does not exist and needs creating)
destination,
value,
d,
dataLength, // Size of the input (in bytes) - this is what fixes the padding problem
x,
0 // Output is ignored, therefore the output size is zero
)
}
return result;
}
/// @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;
}
}
/*
* 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
});
transactionCount += 1;
emit 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)
{
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)
{
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];
}
}
contract FundMultiSig is MultiSigWallet, Initializable {
event NewOwnerSet(uint256 required, uint256 total);
bytes32 public constant ROLE_OWNER_MANAGER = bytes32("owner_manager");
address public constant ETH_CONTRACT_ADDRESS = address(1);
IFundRegistry public fundRegistry;
constructor(
address[] memory _owners
)
public
// WARNING: the implementation won't use this constructor data anyway
MultiSigWallet(_owners, 1)
{
}
function initialize(
address[] calldata _owners,
uint256 _required,
address _fundRegistry
)
external
isInitializer
validRequirement(_owners.length, _required)
{
// solium-disable-next-line operator-whitespace
for (uint i=0; i<_owners.length; i++) {
// solium-disable-next-line error-reason
require(!isOwner[_owners[i]] && _owners[i] != address(0));
isOwner[_owners[i]] = true;
}
owners = _owners;
required = _required;
fundRegistry = IFundRegistry(_fundRegistry);
}
modifier forbidden() {
assert(false);
_;
}
modifier onlyRole(bytes32 _role) {
// Two
//require(fundRegistry.getACL().hasRole(msg.sender, _role), "Invalid role");
_;
}
function addOwner(address owner) public forbidden {}
function removeOwner(address owner) public forbidden {}
function replaceOwner(address owner, address newOwner) public forbidden {}
function changeRequirement(uint _required) public forbidden {}
function setOwners(address[] calldata _newOwners, uint256 _required) external onlyRole(ROLE_OWNER_MANAGER) {
require(_required <= _newOwners.length, "Required too big");
require(_required > 0, "Required too low");
require(_fundStorage().areMembersValid(_newOwners), "Not all members are valid");
owners = _newOwners;
required = _required;
emit NewOwnerSet(required, _newOwners.length);
}
// call has been separated into its own function in order to take advantage
// of the Solidity's code generator to produce a loop that copies tx.data into memory.
// solium-disable-next-line mixedcase
function external_call(address destination, uint value, uint dataLength, bytes memory data) private returns (bool) {
beforeTransactionHook(destination, value, dataLength, data);
bool result;
assembly {
let x := mload(0x40) // "Allocate" memory for output (0x40 is where "free memory" pointer is stored by convention)
let d := add(data, 32) // First 32 bytes are the padded length of data, so exclude that
result := call(
sub(gas, 34710), // 34710 is the value that solidity is currently emitting
// It includes callGas (700) + callVeryLow (3, to pay for SUB) + callValueTransferGas (9000) +
// callNewAccountGas (25000, in case the destination address does not exist and needs creating)
destination,
value,
d,
dataLength, // Size of the input (in bytes) - this is what fixes the padding problem
x,
0 // Output is ignored, therefore the output size is zero
)
}
return result;
}
function beforeTransactionHook(address _destination, uint _value, uint _dataLength, bytes memory _data) private {
if (_value > 0) {
_fundStorage().handleMultiSigTransaction(ETH_CONTRACT_ADDRESS, _value);
}
(bool active,) = _fundStorage().periodLimits(_destination);
// If a withdrawal limit exists for this t_destination
if (active) {
uint256 erc20Value;
assembly {
let code := mload(add(_data, 0x20))
code := and(code, 0xffffffff00000000000000000000000000000000000000000000000000000000)
switch code
// transfer(address,uint256)
case 0xa9059cbb00000000000000000000000000000000000000000000000000000000 {
erc20Value := mload(add(_data, 0x44))
}
default {
// Methods other than transfer are prohibited for ERC20 contracts
revert(0, 0)
}
}
if (erc20Value == 0) {
return;
}
_fundStorage().handleMultiSigTransaction(_destination, erc20Value);
}
}
function _fundStorage() internal view returns (IAbstractFundStorage) {
return IAbstractFundStorage(fundRegistry.getStorageAddress());
}
}
interface IFundRA {
function balanceOf(address _owner) external view returns (uint256);
function balanceOfAt(address _owner, uint256 _blockNumber) external view returns (uint256);
function totalSupplyAt(uint256 _blockNumber) external view returns (uint256);
}
interface IAbstractFundStorage {
function setConfigValue(bytes32 _key, bytes32 _value) external;
function setDefaultProposalConfig(
uint256 _support,
uint256 _quorum,
uint256 _timeout
)
external;
function setProposalConfig(
bytes32 _marker,
uint256 _support,
uint256 _quorum,
uint256 _timeout
)
external;
function addCommunityApp(
address _contract,
bytes32 _type,
bytes32 _abiIpfsHash,
string calldata _dataLink
)
external;
function removeCommunityApp(address _contract) external;
function addProposalMarker(
bytes4 _methodSignature,
address _destination,
address _proposalManager,
bytes32 _name,
string calldata _dataLink
)
external;
function removeProposalMarker(bytes32 _marker) external;
function replaceProposalMarker(bytes32 _oldMarker, bytes32 _newMethodSignature, address _newDestination) external;
function addFundRule(bytes32 _ipfsHash, string calldata _dataLink) external;
function addFeeContract(address _feeContract) external;
function removeFeeContract(address _feeContract) external;
function setMemberIdentification(address _member, bytes32 _identificationHash) external;
function disableFundRule(uint256 _id) external;
function setNameAndDataLink(
string calldata _name,
string calldata _dataLink
)
external;
function setMultiSigManager(
bool _active,
address _manager,
string calldata _name,
string calldata _dataLink
)
external;
function setPeriodLimit(bool _active, address _erc20Contract, uint256 _amount) external;
function handleMultiSigTransaction(
address _erc20Contract,
uint256 _amount
)
external;
// GETTERS
function membersIdentification(address _member) external view returns(bytes32);
function getProposalVotingConfig(bytes32 _key) external view returns (uint256 support, uint256 quorum, uint256 timeout);
function getThresholdMarker(address _destination, bytes calldata _data) external pure returns (bytes32 marker);
function config(bytes32 _key) external view returns (bytes32);
function getCommunityApps() external view returns (address[] memory);
function getActiveFundRules() external view returns (uint256[] memory);
function getActiveFundRulesCount() external view returns (uint256);
function communityAppsInfo(
address _contract
)
external
view
returns (
bytes32 appType,
bytes32 abiIpfsHash,
string memory dataLink
);
function proposalMarkers(
bytes32 _marker
)
external
view
returns (
address proposalManager,
address destination,
bytes32 name,
string memory dataLink
);
function areMembersValid(address[] calldata _members) external view returns (bool);
function getActiveMultisigManagers() external view returns (address[] memory);
function getActiveMultisigManagersCount() external view returns (uint256);
function getActivePeriodLimits() external view returns (address[] memory);
function getActivePeriodLimitsCount() external view returns (uint256);
function getFeeContracts() external view returns (address[] memory);
function getFeeContractCount() external view returns (uint256);
function multiSigManagers(address _manager)
external
view
returns (
bool active,
string memory managerName,
string memory dataLink
);
function periodLimits(address _erc20Contract) external view returns (bool active, uint256 amount);
function getCurrentPeriod() external view returns (uint256);
}
library ArraySet {
struct AddressSet {
address[] array;
mapping(address => uint256) map;
mapping(address => bool) exists;
}
struct Bytes32Set {
bytes32[] array;
mapping(bytes32 => uint256) map;
mapping(bytes32 => bool) exists;
}
// AddressSet
function add(AddressSet storage _set, address _v) internal {
require(_set.exists[_v] == false, "Element already exists");
_set.map[_v] = _set.array.length;
_set.exists[_v] = true;
_set.array.push(_v);
}
function addSilent(AddressSet storage _set, address _v) internal returns (bool) {
if (_set.exists[_v] == true) {
return false;
}
_set.map[_v] = _set.array.length;
_set.exists[_v] = true;
_set.array.push(_v);
return true;
}
function remove(AddressSet storage _set, address _v) internal {
require(_set.array.length > 0, "Array is empty");
require(_set.exists[_v] == true, "Element doesn't exist");
_remove(_set, _v);
}
function removeSilent(AddressSet storage _set, address _v) internal returns (bool) {
if (_set.exists[_v] == false) {
return false;
}
_remove(_set, _v);
return true;
}
function _remove(AddressSet storage _set, address _v) internal {
uint256 lastElementIndex = _set.array.length - 1;
uint256 currentElementIndex = _set.map[_v];
address lastElement = _set.array[lastElementIndex];
_set.array[currentElementIndex] = lastElement;
delete _set.array[lastElementIndex];
_set.array.length = _set.array.length - 1;
delete _set.map[_v];
delete _set.exists[_v];
_set.map[lastElement] = currentElementIndex;
}
function clear(AddressSet storage _set) internal {
for (uint256 i = 0; i < _set.array.length; i++) {
address v = _set.array[i];
delete _set.map[v];
_set.exists[v] = false;
}
delete _set.array;
}
function has(AddressSet storage _set, address _v) internal view returns (bool) {
return _set.exists[_v];
}
function elements(AddressSet storage _set) internal view returns (address[] storage) {
return _set.array;
}
function size(AddressSet storage _set) internal view returns (uint256) {
return _set.array.length;
}
function isEmpty(AddressSet storage _set) internal view returns (bool) {
return _set.array.length == 0;
}
// Bytes32Set
function add(Bytes32Set storage _set, bytes32 _v) internal {
require(_set.exists[_v] == false, "Element already exists");
_add(_set, _v);
}
function addSilent(Bytes32Set storage _set, bytes32 _v) internal returns (bool) {
if (_set.exists[_v] == true) {
return false;
}
_add(_set, _v);
return true;
}
function _add(Bytes32Set storage _set, bytes32 _v) internal {
_set.map[_v] = _set.array.length;
_set.exists[_v] = true;
_set.array.push(_v);
}
function remove(Bytes32Set storage _set, bytes32 _v) internal {
require(_set.array.length > 0, "Array is empty");
require(_set.exists[_v] == true, "Element doesn't exist");
_remove(_set, _v);
}
function removeSilent(Bytes32Set storage _set, bytes32 _v) internal returns (bool) {
if (_set.exists[_v] == false) {
return false;
}
_remove(_set, _v);
return true;
}
function _remove(Bytes32Set storage _set, bytes32 _v) internal {
uint256 lastElementIndex = _set.array.length - 1;
uint256 currentElementIndex = _set.map[_v];
bytes32 lastElement = _set.array[lastElementIndex];
_set.array[currentElementIndex] = lastElement;
delete _set.array[lastElementIndex];
_set.array.length = _set.array.length - 1;
delete _set.map[_v];
delete _set.exists[_v];
_set.map[lastElement] = currentElementIndex;
}
function clear(Bytes32Set storage _set) internal {
for (uint256 i = 0; i < _set.array.length; i++) {
_set.exists[_set.array[i]] = false;
}
delete _set.array;
}
function has(Bytes32Set storage _set, bytes32 _v) internal view returns (bool) {
return _set.exists[_v];
}
function elements(Bytes32Set storage _set) internal view returns (bytes32[] storage) {
return _set.array;
}
function size(Bytes32Set storage _set) internal view returns (uint256) {
return _set.array.length;
}
function isEmpty(Bytes32Set storage _set) internal view returns (bool) {
return _set.array.length == 0;
}
///////////////////////////// Uint256Set /////////////////////////////////////////
struct Uint256Set {
uint256[] array;
mapping(uint256 => uint256) map;
mapping(uint256 => bool) exists;
}
function add(Uint256Set storage _set, uint256 _v) internal {
require(_set.exists[_v] == false, "Element already exists");
_add(_set, _v);
}
function addSilent(Uint256Set storage _set, uint256 _v) internal returns (bool) {
if (_set.exists[_v] == true) {
return false;
}
_add(_set, _v);
return true;
}
function _add(Uint256Set storage _set, uint256 _v) internal {
_set.map[_v] = _set.array.length;
_set.exists[_v] = true;
_set.array.push(_v);
}
function remove(Uint256Set storage _set, uint256 _v) internal {
require(_set.array.length > 0, "Array is empty");
require(_set.exists[_v] == true, "Element doesn't exist");
_remove(_set, _v);
}
function removeSilent(Uint256Set storage _set, uint256 _v) internal returns (bool) {
if (_set.exists[_v] == false) {
return false;
}
_remove(_set, _v);
return true;
}
function _remove(Uint256Set storage _set, uint256 _v) internal {
uint256 lastElementIndex = _set.array.length - 1;
uint256 currentElementIndex = _set.map[_v];
uint256 lastElement = _set.array[lastElementIndex];
_set.array[currentElementIndex] = lastElement;
delete _set.array[lastElementIndex];
_set.array.length = _set.array.length - 1;
delete _set.map[_v];
delete _set.exists[_v];
_set.map[lastElement] = currentElementIndex;
}
function clear(Uint256Set storage _set) internal {
for (uint256 i = 0; i < _set.array.length; i++) {
_set.exists[_set.array[i]] = false;
}
delete _set.array;
}
function has(Uint256Set storage _set, uint256 _v) internal view returns (bool) {
return _set.exists[_v];
}
function elements(Uint256Set storage _set) internal view returns (uint256[] storage) {
return _set.array;
}
function size(Uint256Set storage _set) internal view returns (uint256) {
return _set.array.length;
}
function isEmpty(Uint256Set storage _set) internal view returns (bool) {
return _set.array.length == 0;
}
}
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;
}
}
library Counters {
using SafeMath for uint256;
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 {
counter._value += 1;
}
function decrement(Counter storage counter) internal {
counter._value = counter._value.sub(1);
}
}
contract FundProposalManager is Initializable {
using SafeMath for uint256;
using Counters for Counters.Counter;
using ArraySet for ArraySet.AddressSet;
using ArraySet for ArraySet.Uint256Set;
// 100% == 100 ether
uint256 public constant ONE_HUNDRED_PCT = 100 ether;
event NewProposal(uint256 indexed proposalId, address indexed proposer, bytes32 indexed marker);
event AyeProposal(uint256 indexed proposalId, address indexed voter);
event NayProposal(uint256 indexed proposalId, address indexed voter);
event Approved(uint256 ayeShare, uint256 support, uint256 indexed proposalId, bytes32 indexed marker);
event Execute(uint256 indexed proposalId, address indexed executer, bool indexed success, bytes response);
struct ProposalVoting {
uint256 creationBlock;
uint256 creationTotalSupply;
uint256 createdAt;
uint256 timeoutAt;
uint256 requiredSupport;
uint256 minAcceptQuorum;
uint256 totalAyes;
uint256 totalNays;
mapping(address => Choice) participants;
ArraySet.AddressSet ayes;
ArraySet.AddressSet nays;
}
struct Proposal {
ProposalStatus status;
address creator;
address destination;
uint256 value;
bytes32 marker;
bytes data;
string dataLink;
}
IFundRegistry public fundRegistry;
Counters.Counter public idCounter;
mapping(uint256 => Proposal) public proposals;
mapping(uint256 => ProposalVoting) internal _proposalVotings;
mapping(uint256 => address) private _proposalToSender;
enum ProposalStatus {
NULL,
ACTIVE,
EXECUTED
}
enum Choice {
PENDING,
AYE,
NAY
}
modifier onlyMember() {
require(_fundRA().balanceOf(msg.sender) > 0, "Not valid member");
_;
}
constructor() public {
}
function initialize(IFundRegistry _fundRegistry) external isInitializer {
fundRegistry = _fundRegistry;
}
function propose(
address _destination,
uint256 _value,
bool _castVote,
bool _executesIfDecided,
bytes calldata _data,
string calldata _dataLink
)
external
onlyMember
{
idCounter.increment();
uint256 id = idCounter.current();
Proposal storage p = proposals[id];
p.creator = msg.sender;
p.destination = _destination;
p.value = _value;
p.data = _data;
p.dataLink = _dataLink;
p.marker = _fundStorage().getThresholdMarker(_destination, _data);
p.status = ProposalStatus.ACTIVE;
_onNewProposal(id);
emit NewProposal(id, msg.sender, p.marker);
if (_castVote) {
_aye(id, msg.sender, _executesIfDecided);
}
}
function aye(uint256 _proposalId, bool _executeIfDecided) external {
require(_isProposalOpen(_proposalId), "Proposal isn't open");
_aye(_proposalId, msg.sender, _executeIfDecided);
}
function nay(uint256 _proposalId) external {
require(_isProposalOpen(_proposalId), "Proposal isn't open");
_nay(_proposalId, msg.sender);
}
function executeProposal(uint256 _proposalId, uint256 _gasToKeep) external {
require(proposals[_proposalId].status == ProposalStatus.ACTIVE, "Proposal isn't active");
(bool canExecuteThis, string memory reason) = _canExecute(_proposalId);
require(canExecuteThis, reason);
_unsafeExecuteProposal(_proposalId, _gasToKeep);
}
// INTERNAL
function _aye(uint256 _proposalId, address _voter, bool _executeIfDecided) internal {
ProposalVoting storage pV = _proposalVotings[_proposalId];
uint256 reputation = reputationOf(_voter, pV.creationBlock);
require(reputation > 0, "Can't vote with 0 reputation");
if (pV.participants[_voter] == Choice.NAY) {
pV.nays.remove(_voter);
pV.totalNays = pV.totalNays.sub(reputation);
}
pV.participants[_voter] = Choice.AYE;
pV.ayes.add(_voter);
pV.totalAyes = pV.totalAyes.add(reputation);
emit AyeProposal(_proposalId, _voter);
(bool canExecuteThis,) = _canExecute(_proposalId);
// Fail silently without revert
if (_executeIfDecided && canExecuteThis) {
// We've already checked if the vote can be executed with `_canExecute()`
_unsafeExecuteProposal(_proposalId, 0);
}
}
function _nay(uint256 _proposalId, address _voter) internal {
ProposalVoting storage pV = _proposalVotings[_proposalId];
uint256 reputation = reputationOf(_voter, pV.creationBlock);
require(reputation > 0, "Can't vote with 0 reputation");
if (pV.participants[_voter] == Choice.AYE) {
pV.ayes.remove(_voter);
pV.totalAyes = pV.totalAyes.sub(reputation);
}
pV.participants[msg.sender] = Choice.NAY;
pV.nays.add(msg.sender);
pV.totalNays = pV.totalNays.add(reputation);
emit NayProposal(_proposalId, _voter);
}
function _onNewProposal(uint256 _proposalId) internal {
bytes32 marker = proposals[_proposalId].marker;
uint256 blockNumber = block.number.sub(1);
uint256 totalSupply = _fundRA().totalSupplyAt(blockNumber);
require(totalSupply > 0, "Total reputation is 0");
ProposalVoting storage pv = _proposalVotings[_proposalId];
pv.creationBlock = blockNumber;
pv.creationTotalSupply = totalSupply;
(uint256 support, uint256 quorum, uint256 timeout) = _fundStorage().getProposalVotingConfig(marker);
pv.createdAt = block.timestamp;
// pv.timeoutAt = block.timestamp + timeout;
pv.timeoutAt = block.timestamp.add(timeout);
pv.requiredSupport = support;
pv.minAcceptQuorum = quorum;
}
function _unsafeExecuteProposal(uint256 _proposalId, uint256 _gasToKeep) internal {
uint256 gasToKeep = 0;
if (_gasToKeep == 0) {
gasToKeep = 100000;
}
Proposal storage p = proposals[_proposalId];
p.status = ProposalStatus.EXECUTED;
(bool ok, bytes memory response) = address(p.destination)
.call
.value(p.value)
.gas(gasleft().sub(gasToKeep))(p.data);
if (ok == false) {
p.status = ProposalStatus.ACTIVE;
}
emit Execute(_proposalId, msg.sender, ok, response);
}
function _canExecute(uint256 _proposalId) internal view returns (bool can, string memory errorReason) {
Proposal storage p = proposals[_proposalId];
ProposalVoting storage pv = _proposalVotings[_proposalId];
// Voting is not executed yet
if (p.status != ProposalStatus.ACTIVE) {
return (false, "Proposal isn't active");
}
// Voting is already decided
if (_isValuePct(pv.totalAyes, pv.creationTotalSupply, pv.requiredSupport)) {
return (true, "");
}
// Vote ended?
if (_isProposalOpen(_proposalId)) {
return (false, "Proposal is still active");
}
// Has enough support?
uint256 support = getCurrentSupport(_proposalId);
if (support < pv.requiredSupport) {
return (false, "Support hasn't been reached");
}
// Has min quorum?
uint256 ayeShare = getAyeShare(_proposalId);
if (ayeShare < pv.minAcceptQuorum) {
return (false, "MIN aye quorum hasn't been reached");
}
return (true, "");
}
function _isValuePct(uint256 _value, uint256 _total, uint256 _pct) internal pure returns (bool) {
if (_total == 0) {
return false;
}
uint256 computedPct = _value.mul(ONE_HUNDRED_PCT) / _total;
return computedPct > _pct;
}
function _isProposalOpen(uint256 _proposalId) internal view returns (bool) {
Proposal storage p = proposals[_proposalId];
ProposalVoting storage pv = _proposalVotings[_proposalId];
return block.timestamp < pv.timeoutAt && p.status == ProposalStatus.ACTIVE;
}
function _fundStorage() internal view returns (IAbstractFundStorage) {
return IAbstractFundStorage(fundRegistry.getStorageAddress());
}
function _fundRA() internal view returns (IFundRA) {
return IFundRA(fundRegistry.getRAAddress());
}
// GETTERS
function getProposalVoting(
uint256 _proposalId
)
external
view
returns (
uint256 creationBlock,
uint256 creationTotalSupply,
uint256 totalAyes,
uint256 totalNays,
address[] memory ayes,
address[] memory nays
)
{
ProposalVoting storage pV = _proposalVotings[_proposalId];
return (
pV.creationBlock,
pV.creationTotalSupply,
pV.totalAyes,
pV.totalNays,
pV.ayes.elements(),
pV.nays.elements()
);
}
function getProposalVotingProgress(
uint256 _proposalId
)
external
view
returns (
uint256 ayesShare,
uint256 naysShare,
uint256 totalAyes,
uint256 totalNays,
uint256 currentSupport,
uint256 requiredSupport,
uint256 minAcceptQuorum,
uint256 timeoutAt
)
{
ProposalVoting storage pV = _proposalVotings[_proposalId];
return (
getAyeShare(_proposalId),
getNayShare(_proposalId),
pV.totalAyes,
pV.totalNays,
getCurrentSupport(_proposalId),
pV.requiredSupport,
pV.minAcceptQuorum,
pV.timeoutAt
);
}
function reputationOf(address _address, uint256 _blockNumber) public view returns (uint256) {
return _fundRA().balanceOfAt(_address, _blockNumber);
}
function canExecute(uint256 _proposalId) external view returns (bool can, string memory errorReason) {
return _canExecute(_proposalId);
}
function getParticipantProposalChoice(uint256 _proposalId, address _participant) external view returns (Choice) {
return _proposalVotings[_proposalId].participants[_participant];
}
function getCurrentSupport(uint256 _proposalId) public view returns (uint256) {
ProposalVoting storage pv = _proposalVotings[_proposalId];
uint256 totalVotes = pv.totalAyes.add(pv.totalNays);
if (totalVotes == 0) {
return 0;
}
return pv.totalAyes.mul(ONE_HUNDRED_PCT) / totalVotes;
}
function getAyeShare(uint256 _proposalId) public view returns (uint256) {
ProposalVoting storage p = _proposalVotings[_proposalId];
return p.totalAyes.mul(ONE_HUNDRED_PCT) / p.creationTotalSupply;
}
function getNayShare(uint256 _proposalId) public view returns (uint256) {
ProposalVoting storage p = _proposalVotings[_proposalId];
return p.totalNays.mul(ONE_HUNDRED_PCT) / p.creationTotalSupply;
}
}
contract AbstractFundStorage is IAbstractFundStorage, Initializable {
using SafeMath for uint256;
IFundRegistry public fundRegistry;
bytes32 public constant ROLE_EXPEL_MEMBER_MANAGER = bytes32("EXPEL_MEMBER_MANAGER");
modifier onlyRole(bytes32 _role) {
// One
require(fundRegistry.getACL().hasRole(msg.sender, _role), "Invalid role");
_;
}
// GETTERS
function getThresholdMarker(address _destination, bytes memory _data) public pure returns(bytes32 marker) {
bytes32 methodName;
assembly {
methodName := and(mload(add(_data, 0x20)), 0xffffffff00000000000000000000000000000000000000000000000000000000)
}
return keccak256(abi.encode(_destination, methodName));
}
function getProposalVotingConfig(
bytes32 _key
)
external
view
returns (uint256 support, uint256 minAcceptQuorum, uint256 timeout)
{
uint256 to = customVotingConfigs[_key].timeout;
if (to > 0) {
return (
customVotingConfigs[_key].support,
customVotingConfigs[_key].minAcceptQuorum,
customVotingConfigs[_key].timeout
);
} else {
return (
defaultVotingConfig.support,
defaultVotingConfig.minAcceptQuorum,
defaultVotingConfig.timeout
);
}
}
function getCommunityApps() external view returns (address[] memory) {
return _communityApps.elements();
}
function getActiveFundRules() external view returns (uint256[] memory) {
return _activeFundRules.elements();
}
function getActiveFundRulesCount() external view returns (uint256) {
return _activeFundRules.size();
}
function areMembersValid(address[] calldata _members) external view returns (bool) {
uint256 len = _members.length;
for (uint256 i = 0; i < len; i++) {
if (multiSigManagers[_members[i]].active == false) {
return false;
}
}
return true;
}
function getActiveMultisigManagers() external view returns (address[] memory) {
return _activeMultisigManagers.elements();
}
function getActiveMultisigManagersCount() external view returns (uint256) {
return _activeMultisigManagers.size();
}
function getActivePeriodLimits() external view returns (address[] memory) {
return _activePeriodLimitsContracts.elements();
}
function getActivePeriodLimitsCount() external view returns (uint256) {
return _activePeriodLimitsContracts.size();
}
function getFeeContracts() external view returns (address[] memory) {
return _feeContracts.elements();
}
function getFeeContractCount() external view returns (uint256) {
return _feeContracts.size();
}
function getCurrentPeriod() public view returns (uint256) {
// return (block.timestamp - initialTimestamp) / periodLength;
return (block.timestamp.sub(initialTimestamp)) / periodLength;
}
using ArraySet for ArraySet.AddressSet;
using ArraySet for ArraySet.Uint256Set;
using ArraySet for ArraySet.Bytes32Set;
using Counters for Counters.Counter;
event AddProposalMarker(bytes32 indexed marker, address indexed proposalManager);
event RemoveProposalMarker(bytes32 indexed marker, address indexed proposalManager);
event ReplaceProposalMarker(bytes32 indexed oldMarker, bytes32 indexed newMarker, address indexed proposalManager);
event SetProposalVotingConfig(bytes32 indexed key, uint256 support, uint256 minAcceptQuorum, uint256 timeout);
event SetDefaultProposalVotingConfig(uint256 support, uint256 minAcceptQuorum, uint256 timeout);
event AddCommunityApp(address indexed contractAddress);
event RemoveCommunityApp(address indexed contractAddress);
event AddFundRule(uint256 indexed id);
event DisableFundRule(uint256 indexed id);
event AddFeeContract(address indexed contractAddress);
event RemoveFeeContract(address indexed contractAddress);
event SetMemberIdentification(address indexed member, bytes32 identificationHash);
event SetNameAndDataLink(string name, string dataLink);
event SetMultiSigManager(address indexed manager);
event SetPeriodLimit(address indexed erc20Contract, uint256 amount, bool active);
event HandleMultiSigTransaction(address indexed erc20Contract, uint256 amount);
event SetConfig(bytes32 indexed key, bytes32 value);
// 100% == 100 ether
uint256 public constant ONE_HUNDRED_PCT = 100 ether;
bytes32 public constant ROLE_CONFIG_MANAGER = bytes32("CONFIG_MANAGER");
bytes32 public constant ROLE_COMMUNITY_APPS_MANAGER = bytes32("CA_MANAGER");
bytes32 public constant ROLE_PROPOSAL_MARKERS_MANAGER = bytes32("MARKER_MANAGER");
bytes32 public constant ROLE_NEW_MEMBER_MANAGER = bytes32("NEW_MEMBER_MANAGER");
bytes32 public constant ROLE_FINE_MEMBER_INCREMENT_MANAGER = bytes32("FINE_MEMBER_INCREMENT_MANAGER");
bytes32 public constant ROLE_FINE_MEMBER_DECREMENT_MANAGER = bytes32("FINE_MEMBER_DECREMENT_MANAGER");
bytes32 public constant ROLE_CHANGE_NAME_AND_DESCRIPTION_MANAGER = bytes32("CHANGE_NAME_DATA_LINK_MANAGER");
bytes32 public constant ROLE_ADD_FUND_RULE_MANAGER = bytes32("ADD_FUND_RULE_MANAGER");
bytes32 public constant ROLE_DEACTIVATE_FUND_RULE_MANAGER = bytes32("DEACTIVATE_FUND_RULE_MANAGER");
bytes32 public constant ROLE_FEE_MANAGER = bytes32("FEE_MANAGER");
bytes32 public constant ROLE_MEMBER_DETAILS_MANAGER = bytes32("MEMBER_DETAILS_MANAGER");
bytes32 public constant ROLE_MULTI_SIG_WITHDRAWAL_LIMITS_MANAGER = bytes32("MULTISIG_WITHDRAWAL_MANAGER");
bytes32 public constant ROLE_MEMBER_IDENTIFICATION_MANAGER = bytes32("MEMBER_IDENTIFICATION_MANAGER");
bytes32 public constant ROLE_PROPOSAL_THRESHOLD_MANAGER = bytes32("THRESHOLD_MANAGER");
bytes32 public constant ROLE_DEFAULT_PROPOSAL_THRESHOLD_MANAGER = bytes32("DEFAULT_THRESHOLD_MANAGER");
bytes32 public constant ROLE_DECREMENT_TOKEN_REPUTATION = bytes32("DECREMENT_TOKEN_REPUTATION_ROLE");
bytes32 public constant ROLE_MULTISIG = bytes32("MULTISIG");
bytes32 public constant IS_PRIVATE = bytes32("is_private");
struct FundRule {
bool active;
uint256 id;
address manager;
bytes32 ipfsHash;
string dataLink;
uint256 createdAt;
}
struct CommunityApp {
bytes32 abiIpfsHash;
bytes32 appType;
string dataLink;
}
struct ProposalMarker {
bool active;
bytes32 name;
string dataLink;
address destination;
address proposalManager;
}
struct MultiSigManager {
bool active;
address manager;
string name;
string dataLink;
}
struct MemberFines {
uint256 total;
// Assume ETH is address(0x1)
mapping(address => MemberFineItem) tokenFines;
}
struct MemberFineItem {
uint256 amount;
}
struct PeriodLimit {
bool active;
uint256 amount;
}
struct VotingConfig {
uint256 support;
uint256 minAcceptQuorum;
uint256 timeout;
}
VotingConfig public defaultVotingConfig;
string public name;
string public dataLink;
uint256 public initialTimestamp;
uint256 public periodLength;
ArraySet.AddressSet internal _communityApps;
ArraySet.Uint256Set internal _activeFundRules;
ArraySet.AddressSet internal _feeContracts;
Counters.Counter internal fundRuleCounter;
ArraySet.AddressSet internal _activeMultisigManagers;
ArraySet.AddressSet internal _activePeriodLimitsContracts;
mapping(bytes32 => bytes32) public config;
// contractAddress => details
mapping(address => CommunityApp) public communityAppsInfo;
// marker => details
mapping(bytes32 => ProposalMarker) public proposalMarkers;
// role => address
mapping(bytes32 => address) public coreContracts;
// manager => details
mapping(address => MultiSigManager) public multiSigManagers;
// erc20Contract => details
mapping(address => PeriodLimit) public periodLimits;
// periodId => (erc20Contract => runningTotal)
mapping(uint256 => mapping(address => uint256)) internal _periodRunningTotals;
// member => identification hash
mapping(address => bytes32) public membersIdentification;
// FRP => fundRuleDetails
mapping(uint256 => FundRule) public fundRules;
// marker => customVotingConfigs
mapping(bytes32 => VotingConfig) public customVotingConfigs;
modifier onlyFeeContract() {
require(_feeContracts.has(msg.sender), "Not a fee contract");
_;
}
modifier onlyMultiSig() {
require(fundRegistry.getACL().hasRole(msg.sender, ROLE_MULTISIG), "Invalid role");
_;
}
constructor() public {
}
function initialize(
IFundRegistry _fundRegistry,
bool _isPrivate,
uint256 _defaultProposalSupport,
uint256 _defaultProposalMinAcceptQuorum,
uint256 _defaultProposalTimeout,
uint256 _periodLength
)
external
isInitializer
{
config[IS_PRIVATE] = _isPrivate ? bytes32(uint256(1)) : bytes32(uint256(0));
periodLength = _periodLength;
initialTimestamp = block.timestamp;
_validateVotingConfig(_defaultProposalSupport, _defaultProposalMinAcceptQuorum, _defaultProposalTimeout);
defaultVotingConfig.support = _defaultProposalSupport;
defaultVotingConfig.minAcceptQuorum = _defaultProposalMinAcceptQuorum;
defaultVotingConfig.timeout = _defaultProposalTimeout;
fundRegistry = _fundRegistry;
}
function setDefaultProposalConfig(
uint256 _support,
uint256 _minAcceptQuorum,
uint256 _timeout
)
external
onlyRole(ROLE_DEFAULT_PROPOSAL_THRESHOLD_MANAGER)
{
_validateVotingConfig(_support, _minAcceptQuorum, _timeout);
defaultVotingConfig.support = _support;
defaultVotingConfig.minAcceptQuorum = _minAcceptQuorum;
defaultVotingConfig.timeout = _timeout;
emit SetDefaultProposalVotingConfig(_support, _minAcceptQuorum, _timeout);
}
function setProposalConfig(
bytes32 _marker,
uint256 _support,
uint256 _minAcceptQuorum,
uint256 _timeout
)
external
onlyRole(ROLE_PROPOSAL_THRESHOLD_MANAGER)
{
_validateVotingConfig(_support, _minAcceptQuorum, _timeout);
customVotingConfigs[_marker] = VotingConfig({
support: _support,
minAcceptQuorum: _minAcceptQuorum,
timeout: _timeout
});
emit SetProposalVotingConfig(_marker, _support, _minAcceptQuorum, _timeout);
}
function setConfigValue(bytes32 _key, bytes32 _value) external onlyRole(ROLE_CONFIG_MANAGER) {
config[_key] = _value;
emit SetConfig(_key, _value);
}
function addCommunityApp(
address _contract,
bytes32 _type,
bytes32 _abiIpfsHash,
string calldata _dataLink
)
external
onlyRole(ROLE_COMMUNITY_APPS_MANAGER)
{
CommunityApp storage c = communityAppsInfo[_contract];
_communityApps.addSilent(_contract);
c.appType = _type;
c.abiIpfsHash = _abiIpfsHash;
c.dataLink = _dataLink;
emit AddCommunityApp(_contract);
}
function removeCommunityApp(address _contract) external onlyRole(ROLE_COMMUNITY_APPS_MANAGER) {
_communityApps.remove(_contract);
emit RemoveCommunityApp(_contract);
}
function addProposalMarker(
bytes4 _methodSignature,
address _destination,
address _proposalManager,
bytes32 _name,
string calldata _dataLink
)
external
onlyRole(ROLE_PROPOSAL_MARKERS_MANAGER)
{
bytes32 _marker = keccak256(abi.encode(_destination, _methodSignature));
ProposalMarker storage m = proposalMarkers[_marker];
m.active = true;
m.proposalManager = _proposalManager;
m.destination = _destination;
m.name = _name;
m.dataLink = _dataLink;
emit AddProposalMarker(_marker, _proposalManager);
}
function removeProposalMarker(bytes32 _marker) external onlyRole(ROLE_PROPOSAL_MARKERS_MANAGER) {
proposalMarkers[_marker].active = false;
emit RemoveProposalMarker(_marker, proposalMarkers[_marker].proposalManager);
}
function replaceProposalMarker(
bytes32 _oldMarker,
bytes32 _newMethodSignature,
address _newDestination
)
external
onlyRole(ROLE_PROPOSAL_MARKERS_MANAGER)
{
bytes32 _newMarker = keccak256(abi.encode(_newDestination, _newMethodSignature));
proposalMarkers[_newMarker] = proposalMarkers[_oldMarker];
proposalMarkers[_newMarker].destination = _newDestination;
proposalMarkers[_oldMarker].active = false;
emit ReplaceProposalMarker(_oldMarker, _newMarker, proposalMarkers[_newMarker].proposalManager);
}
function addFundRule(
bytes32 _ipfsHash,
string calldata _dataLink
)
external
onlyRole(ROLE_ADD_FUND_RULE_MANAGER)
{
fundRuleCounter.increment();
uint256 _id = fundRuleCounter.current();
FundRule storage fundRule = fundRules[_id];
fundRule.active = true;
fundRule.id = _id;
fundRule.ipfsHash = _ipfsHash;
fundRule.dataLink = _dataLink;
fundRule.manager = msg.sender;
fundRule.createdAt = block.timestamp;
_activeFundRules.add(_id);
emit AddFundRule(_id);
}
function disableFundRule(uint256 _id) external onlyRole(ROLE_DEACTIVATE_FUND_RULE_MANAGER) {
fundRules[_id].active = false;
_activeFundRules.remove(_id);
emit DisableFundRule(_id);
}
function addFeeContract(address _feeContract) external onlyRole(ROLE_FEE_MANAGER) {
_feeContracts.add(_feeContract);
emit AddFeeContract(_feeContract);
}
function removeFeeContract(address _feeContract) external onlyRole(ROLE_FEE_MANAGER) {
_feeContracts.remove(_feeContract);
emit RemoveFeeContract(_feeContract);
}
function setMemberIdentification(address _member, bytes32 _identificationHash) external onlyRole(ROLE_MEMBER_IDENTIFICATION_MANAGER) {
membersIdentification[_member] = _identificationHash;
emit SetMemberIdentification(_member, _identificationHash);
}
function setNameAndDataLink(
string calldata _name,
string calldata _dataLink
)
external
onlyRole(ROLE_CHANGE_NAME_AND_DESCRIPTION_MANAGER)
{
name = _name;
dataLink = _dataLink;
emit SetNameAndDataLink(_name, _dataLink);
}
function setMultiSigManager(
bool _active,
address _manager,
string calldata _name,
string calldata _dataLink
)
external
onlyRole(ROLE_MEMBER_DETAILS_MANAGER)
{
MultiSigManager storage m = multiSigManagers[_manager];
m.active = _active;
m.name = _name;
m.dataLink = _dataLink;
if (_active) {
_activeMultisigManagers.addSilent(_manager);
} else {
_activeMultisigManagers.removeSilent(_manager);
}
emit SetMultiSigManager(_manager);
}
function setPeriodLimit(
bool _active,
address _erc20Contract,
uint256 _amount
)
external
onlyRole(ROLE_MULTI_SIG_WITHDRAWAL_LIMITS_MANAGER)
{
periodLimits[_erc20Contract].active = _active;
periodLimits[_erc20Contract].amount = _amount;
if (_active) {
_activePeriodLimitsContracts.addSilent(_erc20Contract);
} else {
_activePeriodLimitsContracts.removeSilent(_erc20Contract);
}
emit SetPeriodLimit(_erc20Contract, _amount, _active);
}
function handleMultiSigTransaction(
address _erc20Contract,
uint256 _amount
)
external
onlyMultiSig
{
PeriodLimit storage limit = periodLimits[_erc20Contract];
if (limit.active == false) {
return;
}
uint256 currentPeriod = getCurrentPeriod();
// uint256 runningTotalAfter = _periodRunningTotals[currentPeriod][_erc20Contract] + _amount;
uint256 runningTotalAfter = _periodRunningTotals[currentPeriod][_erc20Contract].add(_amount);
require(runningTotalAfter <= periodLimits[_erc20Contract].amount, "Running total for the current period exceeds the limit");
_periodRunningTotals[currentPeriod][_erc20Contract] = runningTotalAfter;
emit HandleMultiSigTransaction(_erc20Contract, _amount);
}
//// INTERNAL
function _validateVotingConfig(
uint256 _support,
uint256 _minAcceptQuorum,
uint256 _timeout
)
internal
pure
{
require(_minAcceptQuorum > 0 && _minAcceptQuorum <= _support, "Invalid min accept quorum value");
require(_support > 0 && _support <= ONE_HUNDRED_PCT, "Invalid support value");
require(_timeout > 0, "Invalid duration value");
}
}
contract IERC721{
function ownerOf(uint256 tokenId) public view returns (address owner);
}
interface IPPToken {
}
interface IPPLocker {
function reputation() external view returns(uint256);
}
contract PrivateFundStorage is AbstractFundStorage {
function expel(address _registry, uint256 _tokenId)
external
onlyRole(ROLE_EXPEL_MEMBER_MANAGER)
{
address owner;
owner = IERC721(_registry).ownerOf(_tokenId);
uint256 amount = IPPLocker(owner).reputation();
}
}
| member => identification hash | mapping(address => bytes32) public membersIdentification;
| 13,085,748 | [
1,
5990,
516,
24739,
1651,
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
] | [
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,
0
] | [
1,
225,
2874,
12,
2867,
516,
1731,
1578,
13,
1071,
4833,
24371,
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
] |
pragma solidity ^0.4.13;
/**
* @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 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 Basic token
* @dev Basic version of StandardToken, with no allowances.
*/
contract BasicToken is ERC20Basic {
using SafeMath for uint256;
mapping(address => uint256) balances;
/**
* @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) returns (bool) {
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) constant returns (uint256 balance) {
return balances[_owner];
}
}
/**
* @title ERC20 interface
* @dev see https://github.com/ethereum/EIPs/issues/20
*/
contract ERC20 is ERC20Basic {
function allowance(address owner, address spender) 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 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)) 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 amout of tokens to be transfered
*/
function transferFrom(address _from, address _to, uint256 _value) returns (bool) {
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[_to] = balances[_to].add(_value);
balances[_from] = balances[_from].sub(_value);
allowed[_from][msg.sender] = _allowance.sub(_value);
Transfer(_from, _to, _value);
return true;
}
/**
* @dev Aprove the passed address to spend the specified amount of tokens on behalf of msg.sender.
* @param _spender The address which will spend the funds.
* @param _value The amount of tokens to be spent.
*/
function approve(address _spender, uint256 _value) returns (bool) {
// 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;
}
/**
* @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 specifing the amount of tokens still avaible for the spender.
*/
function allowance(address _owner, address _spender) constant returns (uint256 remaining) {
return allowed[_owner][_spender];
}
}
contract AbstractStarbaseCrowdsale {
function workshop() constant returns (address) {}
function startDate() constant returns (uint256) {}
function endedAt() constant returns (uint256) {}
function isEnded() constant returns (bool);
function totalRaisedAmountInCny() constant returns (uint256);
function numOfPurchasedTokensOnCsBy(address purchaser) constant returns (uint256);
function numOfPurchasedTokensOnEpBy(address purchaser) constant returns (uint256);
}
contract AbstractStarbaseMarketingCampaign {
function workshop() constant returns (address) {}
}
/// @title Token contract - ERC20 compatible Starbase token contract.
/// @author Starbase PTE. LTD. - <<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="c3aaada5ac83b0b7a2b1a1a2b0a6eda0ac">[email protected]</a>>
contract StarbaseToken is StandardToken {
/*
* Events
*/
event PublicOfferingPlanDeclared(uint256 tokenCount, uint256 unlockCompanysTokensAt);
event MvpLaunched(uint256 launchedAt);
event LogNewFundraiser (address indexed fundraiserAddress, bool isBonaFide);
event LogUpdateFundraiser(address indexed fundraiserAddress, bool isBonaFide);
/*
* Types
*/
struct PublicOfferingPlan {
uint256 tokenCount;
uint256 unlockCompanysTokensAt;
uint256 declaredAt;
}
/*
* External contracts
*/
AbstractStarbaseCrowdsale public starbaseCrowdsale;
AbstractStarbaseMarketingCampaign public starbaseMarketingCampaign;
/*
* Storage
*/
address public company;
PublicOfferingPlan[] public publicOfferingPlans; // further crowdsales
mapping(address => uint256) public initialEcTokenAllocation; // Initial token allocations for Early Contributors
uint256 public mvpLaunchedAt; // 0 until a MVP of Starbase Platform launches
mapping(address => bool) private fundraisers; // Fundraisers are vetted addresses that are allowed to execute functions within the contract
/*
* Constants / Token meta data
*/
string constant public name = "Starbase"; // Token name
string constant public symbol = "STAR"; // Token symbol
uint8 constant public decimals = 18;
uint256 constant public initialSupply = 1000000000e18; // 1B STAR tokens
uint256 constant public initialCompanysTokenAllocation = 750000000e18; // 750M
/*
* Modifiers
*/
modifier onlyCrowdsaleContract() {
assert(msg.sender == address(starbaseCrowdsale));
_;
}
modifier onlyMarketingCampaignContract() {
assert(msg.sender == address(starbaseMarketingCampaign));
_;
}
modifier onlyFundraiser() {
// Only rightful fundraiser is permitted.
assert(isFundraiser(msg.sender));
_;
}
/*
* Contract functions
*/
/**
* @dev Contract constructor function
* @param starbaseCompanyAddr The address that will holds untransferrable tokens
* @param starbaseCrowdsaleAddr Address of the crowdsale contract
* @param starbaseMarketingCampaignAddr The address of the marketing campaign contract
*/
function StarbaseToken(
address starbaseCompanyAddr,
address starbaseCrowdsaleAddr,
address starbaseMarketingCampaignAddr
) {
assert(
starbaseCompanyAddr != 0 &&
starbaseCrowdsaleAddr != 0 &&
starbaseMarketingCampaignAddr != 0);
starbaseCrowdsale = AbstractStarbaseCrowdsale(starbaseCrowdsaleAddr);
starbaseMarketingCampaign = AbstractStarbaseMarketingCampaign(starbaseMarketingCampaignAddr);
company = starbaseCompanyAddr;
// msg.sender becomes first fundraiser
fundraisers[msg.sender] = true;
LogNewFundraiser(msg.sender, true);
// Tokens for crowdsale and early purchasers
balances[starbaseCrowdsale.workshop()] = 175000000e18; // CS(125M)+EP(50M)
// Tokens for marketing campaign supporters
balances[starbaseMarketingCampaign.workshop()] = 12500000e18; // 12.5M
// Tokens for early contributors, should be allocated by function
balances[0] = 62500000e18; // 62.5M
// Starbase company holds untransferrable tokens initially
balances[starbaseCompanyAddr] = initialCompanysTokenAllocation; // 750M
totalSupply = initialSupply; // 1B
}
/*
* External functions
*/
/**
* @dev Returns number of declared public offering plans
*/
function numOfDeclaredPublicOfferingPlans()
external
constant
returns (uint256)
{
return publicOfferingPlans.length;
}
/**
* @dev Declares a public offering plan to make company's tokens transferable
* @param tokenCount Number of tokens to transfer.
* @param unlockCompanysTokensAt Time of the tokens will be unlocked
*/
function declarePulicOfferingPlan(uint256 tokenCount, uint256 unlockCompanysTokensAt)
external
onlyFundraiser()
returns (bool)
{
assert(tokenCount <= 100000000e18); // shall not exceed 100M tokens
assert(SafeMath.sub(now, starbaseCrowdsale.endedAt()) >= 180 days); // shall not be declared for 6 months after the crowdsale ended
assert(SafeMath.sub(unlockCompanysTokensAt, now) >= 60 days); // tokens must be untransferable at least for 2 months
// check if last declaration was more than 6 months ago
if (publicOfferingPlans.length > 0) {
uint256 lastDeclaredAt =
publicOfferingPlans[publicOfferingPlans.length - 1].declaredAt;
assert(SafeMath.sub(now, lastDeclaredAt) >= 180 days);
}
uint256 totalDeclaredTokenCount = tokenCount;
for (uint8 i; i < publicOfferingPlans.length; i++) {
totalDeclaredTokenCount += publicOfferingPlans[i].tokenCount;
}
assert(totalDeclaredTokenCount <= initialCompanysTokenAllocation); // shall not exceed the initial token allocation
publicOfferingPlans.push(
PublicOfferingPlan(tokenCount, unlockCompanysTokensAt, now));
PublicOfferingPlanDeclared(tokenCount, unlockCompanysTokensAt);
}
/**
* @dev Allocate tokens to a marketing supporter from the marketing campaign share
* @param to Address to where tokens are allocated
* @param value Number of tokens to transfer
*/
function allocateToMarketingSupporter(address to, uint256 value)
external
onlyMarketingCampaignContract
returns (bool)
{
return allocateFrom(starbaseMarketingCampaign.workshop(), to, value);
}
/**
* @dev Allocate tokens to an early contributor from the early contributor share
* @param to Address to where tokens are allocated
* @param value Number of tokens to transfer
*/
function allocateToEarlyContributor(address to, uint256 value)
external
onlyFundraiser()
returns (bool)
{
initialEcTokenAllocation[to] =
SafeMath.add(initialEcTokenAllocation[to], value);
return allocateFrom(0, to, value);
}
/**
* @dev Issue new tokens according to the STAR token inflation limits
* @param _for Address to where tokens are allocated
* @param value Number of tokens to issue
*/
function issueTokens(address _for, uint256 value)
external
onlyFundraiser()
returns (bool)
{
// check if the value under the limits
assert(value <= numOfInflatableTokens());
totalSupply = SafeMath.add(totalSupply, value);
balances[_for] += value;
return true;
}
/**
* @dev Declares Starbase MVP has been launched
* @param launchedAt When the MVP launched (timestamp)
*/
function declareMvpLaunched(uint256 launchedAt) external onlyFundraiser() returns (bool) {
require(mvpLaunchedAt == 0); // overwriting the launch date is not permitted
require(launchedAt <= now);
require(starbaseCrowdsale.isEnded());
mvpLaunchedAt = launchedAt;
MvpLaunched(launchedAt);
return true;
}
/**
* @dev Allocate tokens to a crowdsale or early purchaser from the crowdsale share
* @param to Address to where tokens are allocated
* @param value Number of tokens to transfer
*/
function allocateToCrowdsalePurchaser(address to, uint256 value)
external
onlyCrowdsaleContract
returns (bool)
{
return allocateFrom(starbaseCrowdsale.workshop(), to, value);
}
/*
* Public functions
*/
/**
* @dev Transfers sender's tokens to a given address. Returns success.
* @param to Address of token receiver.
* @param value Number of tokens to transfer.
*/
function transfer(address to, uint256 value) public returns (bool) {
assert(isTransferable(msg.sender, value));
return super.transfer(to, value);
}
/**
* @dev Allows third party to transfer tokens from one address to another. Returns success.
* @param from Address from where tokens are withdrawn.
* @param to Address to where tokens are sent.
* @param value Number of tokens to transfer.
*/
function transferFrom(address from, address to, uint256 value) public returns (bool) {
assert(isTransferable(from, value));
return super.transferFrom(from, to, value);
}
/**
* @dev Adds fundraiser. Only called by another fundraiser.
* @param fundraiserAddress The address in check
*/
function addFundraiser(address fundraiserAddress) public onlyFundraiser {
assert(!isFundraiser(fundraiserAddress));
fundraisers[fundraiserAddress] = true;
LogNewFundraiser(fundraiserAddress, true);
}
/**
* @dev Update fundraiser address rights.
* @param fundraiserAddress The address to update
* @param isBonaFide Boolean that denotes whether fundraiser is active or not.
*/
function updateFundraiser(address fundraiserAddress, bool isBonaFide)
public
onlyFundraiser
returns(bool)
{
assert(isFundraiser(fundraiserAddress));
fundraisers[fundraiserAddress] = isBonaFide;
LogUpdateFundraiser(fundraiserAddress, isBonaFide);
return true;
}
/**
* @dev Returns whether fundraiser address has rights.
* @param fundraiserAddress The address in check
*/
function isFundraiser(address fundraiserAddress) constant public returns(bool) {
return fundraisers[fundraiserAddress];
}
/**
* @dev Returns whether the transferring of tokens is available fundraiser.
* @param from Address of token sender
* @param tokenCount Number of tokens to transfer.
*/
function isTransferable(address from, uint256 tokenCount)
constant
public
returns (bool)
{
if (tokenCount == 0 || balances[from] < tokenCount) {
return false;
}
// company's tokens may be locked up
if (from == company) {
if (tokenCount > numOfTransferableCompanysTokens()) {
return false;
}
}
uint256 untransferableTokenCount = 0;
// early contributor's tokens may be locked up
if (initialEcTokenAllocation[from] > 0) {
untransferableTokenCount = SafeMath.add(
untransferableTokenCount,
numOfUntransferableEcTokens(from));
}
// EP and CS purchasers' tokens should be untransferable initially
if (starbaseCrowdsale.isEnded()) {
uint256 passedDays =
SafeMath.sub(now, starbaseCrowdsale.endedAt()) / 86400; // 1d = 86400s
if (passedDays < 7) { // within a week
// crowdsale purchasers cannot transfer their tokens for a week
untransferableTokenCount = SafeMath.add(
untransferableTokenCount,
starbaseCrowdsale.numOfPurchasedTokensOnCsBy(from));
}
if (passedDays < 14) { // within two weeks
// early purchasers cannot transfer their tokens for two weeks
untransferableTokenCount = SafeMath.add(
untransferableTokenCount,
starbaseCrowdsale.numOfPurchasedTokensOnEpBy(from));
}
}
uint256 transferableTokenCount =
SafeMath.sub(balances[from], untransferableTokenCount);
if (transferableTokenCount < tokenCount) {
return false;
} else {
return true;
}
}
/**
* @dev Returns the number of transferable company's tokens
*/
function numOfTransferableCompanysTokens() constant public returns (uint256) {
uint256 unlockedTokens = 0;
for (uint8 i; i < publicOfferingPlans.length; i++) {
PublicOfferingPlan memory plan = publicOfferingPlans[i];
if (plan.unlockCompanysTokensAt <= now) {
unlockedTokens += plan.tokenCount;
}
}
return SafeMath.sub(
balances[company],
initialCompanysTokenAllocation - unlockedTokens);
}
/**
* @dev Returns the number of untransferable tokens of the early contributor
* @param _for Address of early contributor to check
*/
function numOfUntransferableEcTokens(address _for) constant public returns (uint256) {
uint256 initialCount = initialEcTokenAllocation[_for];
if (mvpLaunchedAt == 0) {
return initialCount;
}
uint256 passedWeeks = SafeMath.sub(now, mvpLaunchedAt) / 7 days;
if (passedWeeks <= 52) { // a year ≈ 52 weeks
// all tokens should be locked up for a year
return initialCount;
}
// unlock 1/52 tokens every weeks after a year
uint256 transferableTokenCount = initialCount / 52 * (passedWeeks - 52);
if (transferableTokenCount >= initialCount) {
return 0;
} else {
return SafeMath.sub(initialCount, transferableTokenCount);
}
}
/**
* @dev Returns number of tokens which can be issued according to the inflation rules
*/
function numOfInflatableTokens() constant public returns (uint256) {
if (starbaseCrowdsale.endedAt() == 0) {
return 0;
}
uint256 passedDays = SafeMath.sub(now, starbaseCrowdsale.endedAt()) / 86400; // 1d = 60s * 60m * 24h = 86400s
uint256 passedYears = passedDays * 100 / 36525; // about 365.25 days in a year
uint256 inflatedSupply = initialSupply;
for (uint256 i; i < passedYears; i++) {
inflatedSupply += SafeMath.mul(inflatedSupply, 25) / 1000; // 2.5%/y = 0.025/y
}
uint256 remainderedDays = passedDays * 100 % 36525 / 100;
if (remainderedDays > 0) {
uint256 inflatableTokensOfNextYear =
SafeMath.mul(inflatedSupply, 25) / 1000;
inflatedSupply += SafeMath.mul(
inflatableTokensOfNextYear, remainderedDays * 100) / 36525;
}
return SafeMath.sub(inflatedSupply, totalSupply);
}
/*
* Internal functions
*/
/**
* @dev Allocate tokens value from an address to another one. This function is only called internally.
* @param from Address from where tokens come
* @param to Address to where tokens are allocated
* @param value Number of tokens to transfer
*/
function allocateFrom(address from, address to, uint256 value) internal returns (bool) {
assert(value > 0 && balances[from] >= value);
balances[from] -= value;
balances[to] += value;
Transfer(from, to, value);
return true;
}
} | * @dev Declares Starbase MVP has been launched @param launchedAt When the MVP launched (timestamp)/ | function declareMvpLaunched(uint256 launchedAt) external onlyFundraiser() returns (bool) {
require(launchedAt <= now);
require(starbaseCrowdsale.isEnded());
mvpLaunchedAt = launchedAt;
MvpLaunched(launchedAt);
return true;
}
| 15,286,425 | [
1,
3456,
4807,
934,
297,
1969,
25324,
52,
711,
2118,
28786,
225,
28786,
861,
5203,
326,
25324,
52,
28786,
261,
5508,
13176,
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,
14196,
49,
20106,
30745,
22573,
12,
11890,
5034,
28786,
861,
13,
3903,
1338,
42,
1074,
354,
15914,
1435,
1135,
261,
6430,
13,
288,
203,
3639,
2583,
12,
11821,
22573,
861,
1648,
2037,
1769,
203,
3639,
2583,
12,
10983,
1969,
39,
492,
2377,
5349,
18,
291,
28362,
10663,
203,
203,
3639,
7701,
84,
30745,
22573,
861,
273,
28786,
861,
31,
203,
3639,
490,
20106,
30745,
22573,
12,
11821,
22573,
861,
1769,
203,
3639,
327,
638,
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
] |
./partial_match/56/0x1A493786bAC35979750AF3991539d29E025Fa0be/sources/StrategysoakLPV2.sol | * @dev Implementation of a strategy to get yields from farming LP Pools in PancakeSwap. PancakeSwap is an automated market maker (“AMM”) that allows two tokens to be exchanged on the Binance Smart Chain. It is fast, cheap, and allows anyone to participate. PancakeSwap is aiming to be the #1 liquidity provider on BSC. This strategy simply deposits whatever funds it receives from the vault into the selected ShareRewardPool pool. soak rewards from providing liquidity are farmed every few minutes, sold and split 50/50. The corresponding pair of assets are bought and more liquidity is added to the ShareRewardPool pool. This strat is currently compatible with all LP pools./ | contract StrategysoakLPV2 is Ownable, Pausable {
using SafeERC20 for IERC20;
using Address for address;
using SafeMath for uint256;
mapping(address => bool) public odioList;
IERC20 flp = IERC20(address(0x87ff96aba480f1813aF5c780387d8De7cf7D8261));
address public constant soak =
address(0x849233FF1aea15D80EF658B2871664C9Ca994063);
address public constant wbnb =
address(0xbb4CdB9CBd36B01bD1cBaEBF2De08d9173bc095c);
address public constant busd =
address(0xe9e7CEA3DedcA5984780Bafc599bD69ADd087D56);
address public lpPair;
address public lpToken0;
address public lpToken1;
address public constant unirouter =
address(0x05fF2B0DB69458A0750badebc4f9e13aDd608C7F);
address public constant shareRewardPool =
address(0x303961805A22d76Bac6B2dE0c33FEB746d82544B);
uint8 public poolId;
address public constant treasury =
address(0xD54307a8edfa93b1794861F091C714d752400D13);
address public vault;
uint256 public constant WITHDRAWAL_FEE = 10;
uint256 public constant WITHDRAWAL_MAX = 10000;
uint256 public _callFee;
uint256 public _treasurySup;
uint256 public flpToHarvest;
address[] public soakToWbnbRoute = [soak, wbnb];
address[] public soakToLp0Route;
address[] public soakToLp1Route;
address[] public Lp0ToLp1Route;
address[] public Lp1ToLp0Route;
event StratHarvest(address indexed harvester);
constructor(
address _lpPair,
uint8 _poolId,
address _vault
) public {
lpPair = _lpPair;
lpToken0 = IPancakePair(lpPair).token0();
lpToken1 = IPancakePair(lpPair).token1();
poolId = _poolId;
vault = _vault;
_callFee = 25;
_treasurySup = 75;
flpToHarvest = 0;
if (lpToken0 == wbnb) {
soakToLp0Route = [soak, wbnb];
soakToLp0Route = [soak, wbnb, lpToken0];
}
if (lpToken1 == wbnb) {
soakToLp1Route = [soak, wbnb];
soakToLp1Route = [soak, wbnb, lpToken1];
}
Lp0ToLp1Route = [lpToken0, lpToken1];
Lp1ToLp0Route = [lpToken1, lpToken0];
IERC20(lpPair).safeApprove(shareRewardPool, uint256(-1));
IERC20(soak).safeApprove(unirouter, uint256(-1));
IERC20(wbnb).safeApprove(unirouter, uint256(-1));
IERC20(busd).safeApprove(unirouter, uint256(-1));
IERC20(lpToken0).safeApprove(unirouter, 0);
IERC20(lpToken0).safeApprove(unirouter, uint256(-1));
IERC20(lpToken1).safeApprove(unirouter, 0);
IERC20(lpToken1).safeApprove(unirouter, uint256(-1));
}
) public {
lpPair = _lpPair;
lpToken0 = IPancakePair(lpPair).token0();
lpToken1 = IPancakePair(lpPair).token1();
poolId = _poolId;
vault = _vault;
_callFee = 25;
_treasurySup = 75;
flpToHarvest = 0;
if (lpToken0 == wbnb) {
soakToLp0Route = [soak, wbnb];
soakToLp0Route = [soak, wbnb, lpToken0];
}
if (lpToken1 == wbnb) {
soakToLp1Route = [soak, wbnb];
soakToLp1Route = [soak, wbnb, lpToken1];
}
Lp0ToLp1Route = [lpToken0, lpToken1];
Lp1ToLp0Route = [lpToken1, lpToken0];
IERC20(lpPair).safeApprove(shareRewardPool, uint256(-1));
IERC20(soak).safeApprove(unirouter, uint256(-1));
IERC20(wbnb).safeApprove(unirouter, uint256(-1));
IERC20(busd).safeApprove(unirouter, uint256(-1));
IERC20(lpToken0).safeApprove(unirouter, 0);
IERC20(lpToken0).safeApprove(unirouter, uint256(-1));
IERC20(lpToken1).safeApprove(unirouter, 0);
IERC20(lpToken1).safeApprove(unirouter, uint256(-1));
}
} else if (lpToken0 != soak) {
) public {
lpPair = _lpPair;
lpToken0 = IPancakePair(lpPair).token0();
lpToken1 = IPancakePair(lpPair).token1();
poolId = _poolId;
vault = _vault;
_callFee = 25;
_treasurySup = 75;
flpToHarvest = 0;
if (lpToken0 == wbnb) {
soakToLp0Route = [soak, wbnb];
soakToLp0Route = [soak, wbnb, lpToken0];
}
if (lpToken1 == wbnb) {
soakToLp1Route = [soak, wbnb];
soakToLp1Route = [soak, wbnb, lpToken1];
}
Lp0ToLp1Route = [lpToken0, lpToken1];
Lp1ToLp0Route = [lpToken1, lpToken0];
IERC20(lpPair).safeApprove(shareRewardPool, uint256(-1));
IERC20(soak).safeApprove(unirouter, uint256(-1));
IERC20(wbnb).safeApprove(unirouter, uint256(-1));
IERC20(busd).safeApprove(unirouter, uint256(-1));
IERC20(lpToken0).safeApprove(unirouter, 0);
IERC20(lpToken0).safeApprove(unirouter, uint256(-1));
IERC20(lpToken1).safeApprove(unirouter, 0);
IERC20(lpToken1).safeApprove(unirouter, uint256(-1));
}
} else if (lpToken1 != soak) {
modifier noEsOdiado() {
require(odioList[msg.sender] == false, "Juira!");
_;
}
function teOdio(address _address, bool _odio) public onlyOwner {
odioList[_address] = _odio;
}
function setflpToHarvest(uint256 _flpToHarvest) public onlyOwner {
flpToHarvest = _flpToHarvest;
}
function deposit() public whenNotPaused {
uint256 pairBal = IERC20(lpPair).balanceOf(address(this));
if (pairBal > 0) {
IShareRewardPool(shareRewardPool).deposit(poolId, pairBal);
}
}
function deposit() public whenNotPaused {
uint256 pairBal = IERC20(lpPair).balanceOf(address(this));
if (pairBal > 0) {
IShareRewardPool(shareRewardPool).deposit(poolId, pairBal);
}
}
function withdraw(uint256 _amount) external {
require(msg.sender == vault, "!vault");
uint256 pairBal = IERC20(lpPair).balanceOf(address(this));
if (pairBal < _amount) {
IShareRewardPool(shareRewardPool).withdraw(
poolId,
_amount.sub(pairBal)
);
pairBal = IERC20(lpPair).balanceOf(address(this));
pairBal = _amount;
}
uint256 withdrawalFee = pairBal.mul(WITHDRAWAL_FEE).div(WITHDRAWAL_MAX);
IERC20(lpPair).safeTransfer(vault, pairBal.sub(withdrawalFee));
}
function withdraw(uint256 _amount) external {
require(msg.sender == vault, "!vault");
uint256 pairBal = IERC20(lpPair).balanceOf(address(this));
if (pairBal < _amount) {
IShareRewardPool(shareRewardPool).withdraw(
poolId,
_amount.sub(pairBal)
);
pairBal = IERC20(lpPair).balanceOf(address(this));
pairBal = _amount;
}
uint256 withdrawalFee = pairBal.mul(WITHDRAWAL_FEE).div(WITHDRAWAL_MAX);
IERC20(lpPair).safeTransfer(vault, pairBal.sub(withdrawalFee));
}
} else {
function harvest() external whenNotPaused noEsOdiado {
require(
flp.balanceOf(msg.sender) >= flpToHarvest,
"You need more falopa in your life"
);
require(!Address.isContract(msg.sender), "!contract");
IShareRewardPool(shareRewardPool).deposit(poolId, 0);
chargeFees();
addLiquidity();
deposit();
emit StratHarvest(msg.sender);
}
function setperfomFee(uint256 _newCallFee, uint256 _newTreasurySup)
public
onlyOwner
{
require(_newCallFee.add(_newTreasurySup) == 100, "!100%");
require(_newCallFee > 0 && _newTreasurySup > 0, "must be > 0");
_callFee = _newCallFee;
_treasurySup = _newTreasurySup;
}
function chargeFees() internal {
uint256 toWbnb =
IERC20(soak).balanceOf(address(this)).mul(40).div(1000);
IPancakeRouter(unirouter)
.swapExactTokensForTokensSupportingFeeOnTransferTokens(
toWbnb,
0,
soakToWbnbRoute,
address(this),
now.add(600)
);
uint256 wbnbBal = IERC20(wbnb).balanceOf(address(this));
uint256 callFee = wbnbBal.mul(_callFee).div(100);
IERC20(wbnb).safeTransfer(msg.sender, callFee);
uint256 treasurySup = wbnbBal.mul(_treasurySup).div(100);
IERC20(wbnb).safeTransfer(treasury, treasurySup);
}
function addLiquidity() internal {
uint256 soakHalf = IERC20(soak).balanceOf(address(this)).div(2);
if (lpToken0 != soak) {
IPancakeRouter(unirouter)
.swapExactTokensForTokensSupportingFeeOnTransferTokens(
soakHalf,
0,
soakToLp0Route,
address(this),
now.add(600)
);
}
if (lpToken1 != soak) {
IPancakeRouter(unirouter)
.swapExactTokensForTokensSupportingFeeOnTransferTokens(
soakHalf,
0,
soakToLp1Route,
address(this),
now.add(600)
);
}
uint256 lp0Bal = IERC20(lpToken0).balanceOf(address(this));
uint256 lp1Bal = IERC20(lpToken1).balanceOf(address(this));
IPancakeRouter(unirouter).addLiquidity(
lpToken0,
lpToken1,
lp0Bal,
lp1Bal,
1,
1,
address(this),
now.add(600)
);
}
function addLiquidity() internal {
uint256 soakHalf = IERC20(soak).balanceOf(address(this)).div(2);
if (lpToken0 != soak) {
IPancakeRouter(unirouter)
.swapExactTokensForTokensSupportingFeeOnTransferTokens(
soakHalf,
0,
soakToLp0Route,
address(this),
now.add(600)
);
}
if (lpToken1 != soak) {
IPancakeRouter(unirouter)
.swapExactTokensForTokensSupportingFeeOnTransferTokens(
soakHalf,
0,
soakToLp1Route,
address(this),
now.add(600)
);
}
uint256 lp0Bal = IERC20(lpToken0).balanceOf(address(this));
uint256 lp1Bal = IERC20(lpToken1).balanceOf(address(this));
IPancakeRouter(unirouter).addLiquidity(
lpToken0,
lpToken1,
lp0Bal,
lp1Bal,
1,
1,
address(this),
now.add(600)
);
}
function addLiquidity() internal {
uint256 soakHalf = IERC20(soak).balanceOf(address(this)).div(2);
if (lpToken0 != soak) {
IPancakeRouter(unirouter)
.swapExactTokensForTokensSupportingFeeOnTransferTokens(
soakHalf,
0,
soakToLp0Route,
address(this),
now.add(600)
);
}
if (lpToken1 != soak) {
IPancakeRouter(unirouter)
.swapExactTokensForTokensSupportingFeeOnTransferTokens(
soakHalf,
0,
soakToLp1Route,
address(this),
now.add(600)
);
}
uint256 lp0Bal = IERC20(lpToken0).balanceOf(address(this));
uint256 lp1Bal = IERC20(lpToken1).balanceOf(address(this));
IPancakeRouter(unirouter).addLiquidity(
lpToken0,
lpToken1,
lp0Bal,
lp1Bal,
1,
1,
address(this),
now.add(600)
);
}
function rebalance(address _token) public onlyOwner {
uint256 tokenHalf = IERC20(_token).balanceOf(address(this)).div(2);
if (_token == lpToken0) {
IPancakeRouter(unirouter)
.swapExactTokensForTokensSupportingFeeOnTransferTokens(
tokenHalf,
0,
Lp0ToLp1Route,
address(this),
now.add(600)
);
IPancakeRouter(unirouter)
.swapExactTokensForTokensSupportingFeeOnTransferTokens(
tokenHalf,
0,
Lp1ToLp0Route,
address(this),
now.add(600)
);
}
}
function rebalance(address _token) public onlyOwner {
uint256 tokenHalf = IERC20(_token).balanceOf(address(this)).div(2);
if (_token == lpToken0) {
IPancakeRouter(unirouter)
.swapExactTokensForTokensSupportingFeeOnTransferTokens(
tokenHalf,
0,
Lp0ToLp1Route,
address(this),
now.add(600)
);
IPancakeRouter(unirouter)
.swapExactTokensForTokensSupportingFeeOnTransferTokens(
tokenHalf,
0,
Lp1ToLp0Route,
address(this),
now.add(600)
);
}
}
} else {
function balanceOf() public view returns (uint256) {
return balanceOfLpPair().add(balanceOfPool());
}
function balanceOfLpPair() public view returns (uint256) {
return IERC20(lpPair).balanceOf(address(this));
}
function balanceOfPool() public view returns (uint256) {
(uint256 _amount, ) =
IShareRewardPool(shareRewardPool).userInfo(poolId, address(this));
return _amount;
}
function retireStrat() external onlyOwner {
panic();
uint256 pairBal = IERC20(lpPair).balanceOf(address(this));
IERC20(lpPair).transfer(vault, pairBal);
}
function panic() public onlyOwner {
pause();
IShareRewardPool(shareRewardPool).emergencyWithdraw(poolId);
}
function pause() public onlyOwner {
_pause();
IERC20(lpPair).safeApprove(shareRewardPool, 0);
IERC20(soak).safeApprove(unirouter, 0);
IERC20(wbnb).safeApprove(unirouter, 0);
IERC20(busd).safeApprove(unirouter, 0);
IERC20(lpToken0).safeApprove(unirouter, 0);
IERC20(lpToken1).safeApprove(unirouter, 0);
}
function unpause() external onlyOwner {
_unpause();
IERC20(lpPair).safeApprove(shareRewardPool, uint256(-1));
IERC20(soak).safeApprove(unirouter, uint256(-1));
IERC20(wbnb).safeApprove(unirouter, uint256(-1));
IERC20(busd).safeApprove(unirouter, uint256(-1));
IERC20(lpToken0).safeApprove(unirouter, 0);
IERC20(lpToken0).safeApprove(unirouter, uint256(-1));
IERC20(lpToken1).safeApprove(unirouter, 0);
IERC20(lpToken1).safeApprove(unirouter, uint256(-1));
}
} | 11,272,641 | [
1,
13621,
434,
279,
6252,
358,
336,
16932,
628,
284,
4610,
310,
511,
52,
453,
8192,
316,
12913,
23780,
12521,
18,
12913,
23780,
12521,
353,
392,
18472,
690,
13667,
312,
6388,
261,
163,
227,
255,
2192,
49,
163,
227,
256,
13,
716,
5360,
2795,
2430,
358,
506,
431,
6703,
603,
326,
16827,
1359,
19656,
7824,
18,
2597,
353,
4797,
16,
19315,
438,
16,
471,
5360,
1281,
476,
358,
30891,
340,
18,
12913,
23780,
12521,
353,
279,
381,
310,
358,
506,
326,
404,
4501,
372,
24237,
2893,
603,
605,
2312,
18,
1220,
6252,
8616,
443,
917,
1282,
15098,
284,
19156,
518,
17024,
628,
326,
9229,
1368,
326,
3170,
25805,
17631,
1060,
2864,
2845,
18,
1427,
581,
283,
6397,
628,
17721,
4501,
372,
24237,
854,
10247,
2937,
3614,
11315,
6824,
16,
272,
1673,
471,
1416,
6437,
19,
3361,
18,
1021,
4656,
3082,
434,
7176,
854,
800,
9540,
471,
1898,
4501,
372,
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,
3978,
1287,
1900,
83,
581,
14461,
58,
22,
353,
14223,
6914,
16,
21800,
16665,
288,
203,
565,
1450,
14060,
654,
39,
3462,
364,
467,
654,
39,
3462,
31,
203,
565,
1450,
5267,
364,
1758,
31,
203,
565,
1450,
14060,
10477,
364,
2254,
5034,
31,
203,
203,
565,
2874,
12,
2867,
516,
1426,
13,
1071,
28541,
1594,
682,
31,
203,
377,
203,
565,
467,
654,
39,
3462,
1183,
84,
273,
467,
654,
39,
3462,
12,
2867,
12,
20,
92,
11035,
1403,
10525,
378,
69,
24,
3672,
74,
2643,
3437,
69,
42,
25,
71,
27,
3672,
7414,
27,
72,
28,
758,
27,
8522,
27,
40,
28,
5558,
21,
10019,
203,
203,
565,
1758,
1071,
5381,
1427,
581,
273,
203,
3639,
1758,
12,
20,
92,
5193,
9975,
3707,
2246,
21,
8906,
69,
3600,
40,
3672,
26897,
26,
8204,
38,
6030,
27,
2313,
1105,
39,
29,
23508,
2733,
7132,
4449,
1769,
203,
565,
1758,
1071,
5381,
17298,
6423,
273,
203,
3639,
1758,
12,
20,
6114,
70,
24,
19728,
38,
29,
8876,
72,
5718,
38,
1611,
70,
40,
21,
71,
38,
69,
41,
15259,
22,
758,
6840,
72,
29,
31331,
13459,
5908,
25,
71,
1769,
203,
565,
1758,
1071,
5381,
5766,
72,
273,
203,
3639,
1758,
12,
20,
6554,
29,
73,
27,
1441,
37,
23,
20563,
71,
37,
6162,
5193,
27,
3672,
38,
1727,
71,
25,
2733,
70,
40,
8148,
1880,
72,
6840,
27,
40,
4313,
1769,
203,
203,
565,
1758,
1071,
12423,
4154,
31,
203,
565,
1758,
1071,
12423,
1345,
20,
31,
203,
565,
1758,
1071,
12423,
2
] |
./partial_match/5/0xA109b34B1974C1f6BA554607F46E202926728E14/sources/src/utils/DoubleLinkedList.sol | @notice Returns the tail item id of the list @param list Linked list which contains the item @return _ Id of the tail item | function getTail(List storage list) internal view returns (uint256) {
return list.items[0].prev;
}
| 16,850,997 | [
1,
1356,
326,
5798,
761,
612,
434,
326,
666,
225,
666,
6546,
666,
1492,
1914,
326,
761,
327,
389,
3124,
434,
326,
5798,
761,
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,
445,
3181,
671,
12,
682,
2502,
666,
13,
2713,
1476,
1135,
261,
11890,
5034,
13,
288,
203,
3639,
327,
666,
18,
3319,
63,
20,
8009,
10001,
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
] |
// SPDX-License-Identifier: MIT
pragma solidity 0.8.10;
import "@openzeppelin/contracts/utils/math/Math.sol";
import "./interfaces/IOverlayV1Factory.sol";
import "./interfaces/IOverlayV1Market.sol";
import "./interfaces/IOverlayV1Token.sol";
import "./interfaces/feeds/IOverlayV1Feed.sol";
import "./libraries/FixedPoint.sol";
import "./libraries/Oracle.sol";
import "./libraries/Position.sol";
import "./libraries/Risk.sol";
import "./libraries/Roller.sol";
contract OverlayV1Market is IOverlayV1Market {
using FixedPoint for uint256;
using Oracle for Oracle.Data;
using Position for mapping(bytes32 => Position.Info);
using Position for Position.Info;
using Risk for uint256[15];
using Roller for Roller.Snapshot;
// internal constants
uint256 internal constant ONE = 1e18; // 18 decimal places
// cap for euler exponent powers; SEE: ./libraries/LogExpMath.sol::pow
// using ~ 1/2 library max for substantial padding
uint256 internal constant MAX_NATURAL_EXPONENT = 20e18;
// immutables
IOverlayV1Token public immutable ovl; // ovl token
address public immutable feed; // oracle feed
address public immutable factory; // factory that deployed this market
// risk params
uint256[15] public params; // params.idx order based on Risk.Parameters enum
// aggregate oi quantities
uint256 public oiLong;
uint256 public oiShort;
uint256 public oiLongShares;
uint256 public oiShortShares;
// rollers
Roller.Snapshot public override snapshotVolumeBid; // snapshot of recent volume on bid
Roller.Snapshot public override snapshotVolumeAsk; // snapshot of recent volume on ask
Roller.Snapshot public override snapshotMinted; // snapshot of recent PnL minted/burned
// positions
mapping(bytes32 => Position.Info) public override positions;
uint256 private _totalPositions;
// data from last call to update
uint256 public timestampUpdateLast;
// cached risk calcs
uint256 public dpUpperLimit; // e**(+priceDriftUpperLimit * macroWindow)
// factory modifier for governance sensitive functions
modifier onlyFactory() {
require(msg.sender == factory, "OVLV1: !factory");
_;
}
// events for core functions
event Build(
address indexed sender, // address that initiated build (owns position)
uint256 positionId, // id of built position
uint256 oi, // oi of position at build
uint256 debt, // debt of position at build
bool isLong, // whether is long or short
uint256 price // entry price
);
event Unwind(
address indexed sender, // address that initiated unwind (owns position)
uint256 positionId, // id of unwound position
uint256 fraction, // fraction of position unwound
int256 mint, // total amount minted/burned (+/-) at unwind
uint256 price // exit price
);
event Liquidate(
address indexed sender, // address that initiated liquidate
address indexed owner, // address that owned the liquidated position
uint256 positionId, // id of the liquidated position
int256 mint, // total amount burned (-) at liquidate
uint256 price // liquidation price
);
constructor() {
(address _ovl, address _feed, address _factory) = IOverlayV1Deployer(msg.sender)
.parameters();
ovl = IOverlayV1Token(_ovl);
feed = _feed;
factory = _factory;
}
/// @notice initializes the market and its risk params
/// @notice called only once by factory on deployment
function initialize(uint256[15] memory _params) external onlyFactory {
// initialize update data
Oracle.Data memory data = IOverlayV1Feed(feed).latest();
require(_midFromFeed(data) > 0, "OVLV1:!data");
timestampUpdateLast = block.timestamp;
// check risk params valid
uint256 _capLeverage = _params[uint256(Risk.Parameters.CapLeverage)];
uint256 _delta = _params[uint256(Risk.Parameters.Delta)];
uint256 _maintenanceMarginFraction = _params[
uint256(Risk.Parameters.MaintenanceMarginFraction)
];
uint256 _liquidationFeeRate = _params[uint256(Risk.Parameters.LiquidationFeeRate)];
require(
_capLeverage <=
ONE.divDown(
2 * _delta + _maintenanceMarginFraction.divDown(ONE - _liquidationFeeRate)
),
"OVLV1: max lev immediately liquidatable"
);
uint256 _priceDriftUpperLimit = _params[uint256(Risk.Parameters.PriceDriftUpperLimit)];
require(
_priceDriftUpperLimit * data.macroWindow < MAX_NATURAL_EXPONENT,
"OVLV1: price drift exceeds max exp"
);
_cacheRiskCalc(Risk.Parameters.PriceDriftUpperLimit, _priceDriftUpperLimit);
// set the risk params
for (uint256 i = 0; i < _params.length; i++) {
params[i] = _params[i];
}
}
/// @dev builds a new position
function build(
uint256 collateral,
uint256 leverage,
bool isLong,
uint256 priceLimit
) external returns (uint256 positionId_) {
require(leverage >= ONE, "OVLV1:lev<min");
require(leverage <= params.get(Risk.Parameters.CapLeverage), "OVLV1:lev>max");
require(collateral >= params.get(Risk.Parameters.MinCollateral), "OVLV1:collateral<min");
uint256 oi;
uint256 debt;
uint256 price;
uint256 tradingFee;
// avoids stack too deep
{
// call to update before any effects
Oracle.Data memory data = update();
// calculate notional, oi, and trading fees. fees charged on notional
// and added to collateral transferred in
uint256 notional = collateral.mulUp(leverage);
uint256 midPrice = _midFromFeed(data);
oi = oiFromNotional(notional, midPrice);
// check have more than zero number of contracts built
require(oi > 0, "OVLV1:oi==0");
// calculate debt and trading fees. fees charged on notional
// and added to collateral transferred in
debt = notional - collateral;
tradingFee = notional.mulUp(params.get(Risk.Parameters.TradingFeeRate));
// calculate current notional cap adjusted for circuit breaker *then* adjust
// for front run and back run bounds (order matters)
// finally, transform into a cap on open interest
uint256 capOi = oiFromNotional(
capNotionalAdjustedForBounds(
data,
capNotionalAdjustedForCircuitBreaker(params.get(Risk.Parameters.CapNotional))
),
midPrice
);
// longs get the ask and shorts get the bid on build
// register the additional volume on either the ask or bid
// where volume = oi / capOi
price = isLong
? ask(data, _registerVolumeAsk(data, oi, capOi))
: bid(data, _registerVolumeBid(data, oi, capOi));
// check price hasn't changed more than max slippage specified by trader
require(isLong ? price <= priceLimit : price >= priceLimit, "OVLV1:slippage>max");
// add new position's open interest to the side's aggregate oi value
// and increase number of oi shares issued. assemble position for storage
// cache for gas savings
uint256 oiTotalOnSide = isLong ? oiLong : oiShort;
uint256 oiTotalSharesOnSide = isLong ? oiLongShares : oiShortShares;
// check new total oi on side does not exceed capOi
oiTotalOnSide += oi;
oiTotalSharesOnSide += oi;
require(oiTotalOnSide <= capOi, "OVLV1:oi>cap");
// update total aggregate oi and oi shares
if (isLong) {
oiLong = oiTotalOnSide;
oiLongShares = oiTotalSharesOnSide;
} else {
oiShort = oiTotalOnSide;
oiShortShares = oiTotalSharesOnSide;
}
// assemble position info data
// check position is not immediately liquidatable prior to storing
Position.Info memory pos = Position.Info({
notional: uint96(notional), // won't overflow as capNotional max is 8e24
debt: uint96(debt),
isLong: isLong,
entryToMidRatio: Position.calcEntryToMidRatio(price, midPrice),
liquidated: false,
oiShares: oi
});
require(
!pos.liquidatable(
oiTotalOnSide,
oiTotalSharesOnSide,
midPrice, // mid price used on liquidations
params.get(Risk.Parameters.CapPayoff),
params.get(Risk.Parameters.MaintenanceMarginFraction),
params.get(Risk.Parameters.LiquidationFeeRate)
),
"OVLV1:liquidatable"
);
// store the position info data
positionId_ = _totalPositions;
positions.set(msg.sender, positionId_, pos);
_totalPositions++;
}
// emit build event
emit Build(msg.sender, positionId_, oi, debt, isLong, price);
// transfer in the OVL collateral needed to back the position + fees
// trading fees charged as a percentage on notional size of position
ovl.transferFrom(msg.sender, address(this), collateral + tradingFee);
// send trading fees to trading fee recipient
ovl.transfer(IOverlayV1Factory(factory).feeRecipient(), tradingFee);
}
/// @dev unwinds fraction of an existing position
function unwind(
uint256 positionId,
uint256 fraction,
uint256 priceLimit
) external {
require(fraction > 0, "OVLV1:fraction<min");
require(fraction <= ONE, "OVLV1:fraction>max");
uint256 value;
uint256 cost;
uint256 price;
uint256 tradingFee;
// avoids stack too deep
{
// call to update before any effects
Oracle.Data memory data = update();
// check position exists
Position.Info memory pos = positions.get(msg.sender, positionId);
require(pos.exists(), "OVLV1:!position");
// cache for gas savings
uint256 oiTotalOnSide = pos.isLong ? oiLong : oiShort;
uint256 oiTotalSharesOnSide = pos.isLong ? oiLongShares : oiShortShares;
// check position not liquidatable otherwise can't unwind
require(
!pos.liquidatable(
oiTotalOnSide,
oiTotalSharesOnSide,
_midFromFeed(data), // mid price used on liquidations
params.get(Risk.Parameters.CapPayoff),
params.get(Risk.Parameters.MaintenanceMarginFraction),
params.get(Risk.Parameters.LiquidationFeeRate)
),
"OVLV1:liquidatable"
);
// longs get the bid and shorts get the ask on unwind
// register the additional volume on either the ask or bid
// where volume = oi / capOi
// current cap only adjusted for bounds (no circuit breaker so traders
// don't get stuck in a position)
uint256 capOi = oiFromNotional(
capNotionalAdjustedForBounds(data, params.get(Risk.Parameters.CapNotional)),
_midFromFeed(data)
);
price = pos.isLong
? bid(
data,
_registerVolumeBid(
data,
pos.oiCurrent(fraction, oiTotalOnSide, oiTotalSharesOnSide),
capOi
)
)
: ask(
data,
_registerVolumeAsk(
data,
pos.oiCurrent(fraction, oiTotalOnSide, oiTotalSharesOnSide),
capOi
)
);
// check price hasn't changed more than max slippage specified by trader
require(pos.isLong ? price >= priceLimit : price <= priceLimit, "OVLV1:slippage>max");
// calculate the value and cost of the position for pnl determinations
// and amount to transfer
uint256 capPayoff = params.get(Risk.Parameters.CapPayoff);
value = pos.value(fraction, oiTotalOnSide, oiTotalSharesOnSide, price, capPayoff);
cost = pos.cost(fraction);
// calculate the trading fee as % on notional
uint256 tradingFeeRate = params.get(Risk.Parameters.TradingFeeRate);
tradingFee = pos.tradingFee(
fraction,
oiTotalOnSide,
oiTotalSharesOnSide,
price,
capPayoff,
tradingFeeRate
);
tradingFee = Math.min(tradingFee, value); // if value < tradingFee
// subtract unwound open interest from the side's aggregate oi value
// and decrease number of oi shares issued
// use subFloor to avoid reverts with rounding issues
if (pos.isLong) {
oiLong = oiLong.subFloor(
pos.oiCurrent(fraction, oiTotalOnSide, oiTotalSharesOnSide)
);
oiLongShares = oiLongShares.subFloor(pos.oiSharesCurrent(fraction));
} else {
oiShort = oiShort.subFloor(
pos.oiCurrent(fraction, oiTotalOnSide, oiTotalSharesOnSide)
);
oiShortShares = oiShortShares.subFloor(pos.oiSharesCurrent(fraction));
}
// register the amount to be minted/burned
// capPayoff prevents overflow reverts with int256 cast
_registerMintOrBurn(int256(value) - int256(cost));
// store the updated position info data
// use subFloor to avoid reverts with rounding issues
pos.notional = uint96(uint256(pos.notional).subFloor(pos.notionalInitial(fraction)));
pos.debt = uint96(uint256(pos.debt).subFloor(pos.debtCurrent(fraction)));
pos.oiShares = pos.oiShares.subFloor(pos.oiSharesCurrent(fraction));
positions.set(msg.sender, positionId, pos);
}
// emit unwind event
emit Unwind(msg.sender, positionId, fraction, int256(value) - int256(cost), price);
// mint or burn the pnl for the position
if (value >= cost) {
ovl.mint(address(this), value - cost);
} else {
ovl.burn(cost - value);
}
// transfer out the unwound position value less fees to trader
ovl.transfer(msg.sender, value - tradingFee);
// send trading fees to trading fee recipient
ovl.transfer(IOverlayV1Factory(factory).feeRecipient(), tradingFee);
}
/// @dev liquidates a liquidatable position
function liquidate(address owner, uint256 positionId) external {
uint256 value;
uint256 cost;
uint256 price;
uint256 liquidationFee;
uint256 marginToBurn;
uint256 marginRemaining;
// avoids stack too deep
{
// check position exists
Position.Info memory pos = positions.get(owner, positionId);
require(pos.exists(), "OVLV1:!position");
// call to update before any effects
Oracle.Data memory data = update();
// cache for gas savings
uint256 oiTotalOnSide = pos.isLong ? oiLong : oiShort;
uint256 oiTotalSharesOnSide = pos.isLong ? oiLongShares : oiShortShares;
uint256 capPayoff = params.get(Risk.Parameters.CapPayoff);
// entire position should be liquidated
uint256 fraction = ONE;
// Use mid price without volume for liquidation (oracle price effectively) to
// prevent market impact manipulation from causing unneccessary liquidations
price = _midFromFeed(data);
// check position is liquidatable
require(
pos.liquidatable(
oiTotalOnSide,
oiTotalSharesOnSide,
price,
capPayoff,
params.get(Risk.Parameters.MaintenanceMarginFraction),
params.get(Risk.Parameters.LiquidationFeeRate)
),
"OVLV1:!liquidatable"
);
// calculate the value and cost of the position for pnl determinations
// and amount to transfer
value = pos.value(fraction, oiTotalOnSide, oiTotalSharesOnSide, price, capPayoff);
cost = pos.cost(fraction);
// calculate the liquidation fee as % on remaining value
// sent as reward to liquidator
liquidationFee = value.mulDown(params.get(Risk.Parameters.LiquidationFeeRate));
marginRemaining = value - liquidationFee;
// Reduce burn amount further by the mm burn rate, as insurance
// for cases when not liquidated in time
marginToBurn = marginRemaining.mulDown(
params.get(Risk.Parameters.MaintenanceMarginBurnRate)
);
marginRemaining -= marginToBurn;
// subtract liquidated open interest from the side's aggregate oi value
// and decrease number of oi shares issued
// use subFloor to avoid reverts with rounding issues
if (pos.isLong) {
oiLong = oiLong.subFloor(
pos.oiCurrent(fraction, oiTotalOnSide, oiTotalSharesOnSide)
);
oiLongShares = oiLongShares.subFloor(pos.oiSharesCurrent(fraction));
} else {
oiShort = oiShort.subFloor(
pos.oiCurrent(fraction, oiTotalOnSide, oiTotalSharesOnSide)
);
oiShortShares = oiShortShares.subFloor(pos.oiSharesCurrent(fraction));
}
// register the amount to be burned
_registerMintOrBurn(int256(value) - int256(cost) - int256(marginToBurn));
// store the updated position info data. mark as liquidated
pos.notional = 0;
pos.debt = 0;
pos.oiShares = 0;
pos.liquidated = true;
pos.entryToMidRatio = 0;
positions.set(owner, positionId, pos);
}
// emit liquidate event
emit Liquidate(
msg.sender,
owner,
positionId,
int256(value) - int256(cost) - int256(marginToBurn),
price
);
// burn the pnl for the position + insurance margin
ovl.burn(cost - value + marginToBurn);
// transfer out the liquidation fee to liquidator for reward
ovl.transfer(msg.sender, liquidationFee);
// send remaining margin to trading fee recipient
ovl.transfer(IOverlayV1Factory(factory).feeRecipient(), marginRemaining);
}
/// @dev updates market: pays funding and fetches freshest data from feed
/// @dev update is called every time market is interacted with
function update() public returns (Oracle.Data memory) {
// apply funding if at least one block has passed
uint256 timeElapsed = block.timestamp - timestampUpdateLast;
if (timeElapsed > 0) {
// calculate adjustments to oi due to funding
bool isLongOverweight = oiLong > oiShort;
uint256 oiOverweight = isLongOverweight ? oiLong : oiShort;
uint256 oiUnderweight = isLongOverweight ? oiShort : oiLong;
(oiOverweight, oiUnderweight) = oiAfterFunding(
oiOverweight,
oiUnderweight,
timeElapsed
);
// pay funding
oiLong = isLongOverweight ? oiOverweight : oiUnderweight;
oiShort = isLongOverweight ? oiUnderweight : oiOverweight;
// refresh last update data
timestampUpdateLast = block.timestamp;
}
// fetch new oracle data from feed
// applies sanity check in case of data manipulation
Oracle.Data memory data = IOverlayV1Feed(feed).latest();
require(dataIsValid(data), "OVLV1:!data");
// return the latest data from feed
return data;
}
/// @dev sanity check on data fetched from oracle in case of manipulation
/// @dev rough check that log price bounded by +/- priceDriftUpperLimit * dt
/// @dev when comparing priceMacro(now) vs priceMacro(now - macroWindow)
function dataIsValid(Oracle.Data memory data) public view returns (bool) {
// upper and lower limits are e**(+/- priceDriftUpperLimit * dt)
uint256 _dpUpperLimit = dpUpperLimit;
uint256 _dpLowerLimit = ONE.divDown(_dpUpperLimit);
// compare current price over macro window vs price over macro window
// one macro window in the past
uint256 priceNow = data.priceOverMacroWindow;
uint256 priceLast = data.priceOneMacroWindowAgo;
if (priceLast == 0 || priceNow == 0) {
// data is not valid if price is zero
return false;
}
// price is valid if within upper and lower limits on drift given
// time elapsed over one macro window
uint256 dp = priceNow.divUp(priceLast);
return (dp >= _dpLowerLimit && dp <= _dpUpperLimit);
}
/// @notice Current open interest after funding payments transferred
/// @notice from overweight oi side to underweight oi side
/// @dev The value of oiOverweight must be >= oiUnderweight
function oiAfterFunding(
uint256 oiOverweight,
uint256 oiUnderweight,
uint256 timeElapsed
) public view returns (uint256, uint256) {
uint256 oiTotal = oiOverweight + oiUnderweight;
uint256 oiImbalance = oiOverweight - oiUnderweight;
uint256 oiInvariant = oiUnderweight.mulUp(oiOverweight);
// If no OI or imbalance, no funding occurs. Handles div by zero case below
if (oiTotal == 0 || oiImbalance == 0) {
return (oiOverweight, oiUnderweight);
}
// draw down the imbalance by factor of e**(-2*k*t)
// but min to zero if pow = 2*k*t exceeds MAX_NATURAL_EXPONENT
uint256 fundingFactor;
uint256 pow = 2 * params.get(Risk.Parameters.K) * timeElapsed;
if (pow < MAX_NATURAL_EXPONENT) {
fundingFactor = ONE.divDown(pow.expUp()); // e**(-pow)
}
// Decrease total aggregate open interest (i.e. oiLong + oiShort)
// to compensate protocol for pro-rata share of imbalance liability
// OI_tot(t) = OI_tot(0) * \
// sqrt( 1 - (OI_imb(0)/OI_tot(0))**2 * (1 - e**(-4*k*t)) )
// Guaranteed 0 <= underRoot <= 1
uint256 oiImbFraction = oiImbalance.divDown(oiTotal);
uint256 underRoot = ONE -
oiImbFraction.mulDown(oiImbFraction).mulDown(
ONE - fundingFactor.mulDown(fundingFactor)
);
// oiTotalNow guaranteed <= oiTotalBefore (burn happens)
oiTotal = oiTotal.mulDown(underRoot.powDown(ONE / 2));
// Time decay imbalance: OI_imb(t) = OI_imb(0) * e**(-2*k*t)
// oiImbalanceNow guaranteed <= oiImbalanceBefore
oiImbalance = oiImbalance.mulDown(fundingFactor);
// overweight pays underweight
// use oiOver * oiUnder = invariant for oiUnderNow to avoid any
// potential overflow reverts
oiOverweight = (oiTotal + oiImbalance) / 2;
if (oiOverweight != 0) {
oiUnderweight = oiInvariant.divUp(oiOverweight);
}
return (oiOverweight, oiUnderweight);
}
/// @dev current notional cap with adjustments to lower
/// @dev cap in the event market has printed a lot in recent past
function capNotionalAdjustedForCircuitBreaker(uint256 cap) public view returns (uint256) {
// Adjust cap downward for circuit breaker. Use snapshotMinted
// but transformed to account for decay in magnitude of minted since
// last snapshot taken
Roller.Snapshot memory snapshot = snapshotMinted;
uint256 circuitBreakerWindow = params.get(Risk.Parameters.CircuitBreakerWindow);
snapshot = snapshot.transform(block.timestamp, circuitBreakerWindow, 0);
cap = circuitBreaker(snapshot, cap);
return cap;
}
/// @dev bound on notional cap from circuit breaker
/// @dev Three cases:
/// @dev 1. minted < 1x target amount over circuitBreakerWindow: return cap
/// @dev 2. minted > 2x target amount over last circuitBreakerWindow: return 0
/// @dev 3. minted between 1x and 2x target amount: return cap * (2 - minted/target)
function circuitBreaker(Roller.Snapshot memory snapshot, uint256 cap)
public
view
returns (uint256)
{
int256 minted = int256(snapshot.cumulative());
uint256 circuitBreakerMintTarget = params.get(Risk.Parameters.CircuitBreakerMintTarget);
if (minted <= int256(circuitBreakerMintTarget)) {
return cap;
} else if (minted >= 2 * int256(circuitBreakerMintTarget)) {
return 0;
}
// case 3 (circuit breaker adjustment downward)
uint256 adjustment = 2 * ONE - uint256(minted).divDown(circuitBreakerMintTarget);
return cap.mulDown(adjustment);
}
/// @dev current notional cap with adjustments to prevent
/// @dev front-running trade and back-running trade
function capNotionalAdjustedForBounds(Oracle.Data memory data, uint256 cap)
public
view
returns (uint256)
{
if (data.hasReserve) {
// Adjust cap downward if exceeds bounds from front run attack
cap = Math.min(cap, frontRunBound(data));
// Adjust cap downward if exceeds bounds from back run attack
cap = Math.min(cap, backRunBound(data));
}
return cap;
}
/// @dev bound on notional cap to mitigate front-running attack
/// @dev bound = lmbda * reserveInOvl
function frontRunBound(Oracle.Data memory data) public view returns (uint256) {
uint256 lmbda = params.get(Risk.Parameters.Lmbda);
return lmbda.mulDown(data.reserveOverMicroWindow);
}
/// @dev bound on notional cap to mitigate back-running attack
/// @dev bound = macroWindowInBlocks * reserveInOvl * 2 * delta
function backRunBound(Oracle.Data memory data) public view returns (uint256) {
uint256 averageBlockTime = params.get(Risk.Parameters.AverageBlockTime);
uint256 window = (data.macroWindow * ONE) / averageBlockTime;
uint256 delta = params.get(Risk.Parameters.Delta);
return delta.mulDown(data.reserveOverMicroWindow).mulDown(window).mulDown(2 * ONE);
}
/// @dev Returns the open interest in number of contracts for a given notional
/// @dev Uses _midFromFeed(data) price to calculate oi: OI = Q / P
function oiFromNotional(uint256 notional, uint256 midPrice) public view returns (uint256) {
return notional.divDown(midPrice);
}
/// @dev bid price given oracle data and recent volume
function bid(Oracle.Data memory data, uint256 volume) public view returns (uint256 bid_) {
bid_ = Math.min(data.priceOverMicroWindow, data.priceOverMacroWindow);
// add static spread (delta) and market impact (lmbda * volume)
uint256 delta = params.get(Risk.Parameters.Delta);
uint256 lmbda = params.get(Risk.Parameters.Lmbda);
uint256 pow = delta + lmbda.mulUp(volume);
require(pow < MAX_NATURAL_EXPONENT, "OVLV1:slippage>max");
bid_ = bid_.mulDown(ONE.divDown(pow.expUp())); // bid * e**(-pow)
}
/// @dev ask price given oracle data and recent volume
function ask(Oracle.Data memory data, uint256 volume) public view returns (uint256 ask_) {
ask_ = Math.max(data.priceOverMicroWindow, data.priceOverMacroWindow);
// add static spread (delta) and market impact (lmbda * volume)
uint256 delta = params.get(Risk.Parameters.Delta);
uint256 lmbda = params.get(Risk.Parameters.Lmbda);
uint256 pow = delta + lmbda.mulUp(volume);
require(pow < MAX_NATURAL_EXPONENT, "OVLV1:slippage>max");
ask_ = ask_.mulUp(pow.expUp()); // ask * e**(pow)
}
/// @dev mid price without impact/spread given oracle data and recent volume
/// @dev used for gas savings to avoid accessing storage for delta, lmbda
function _midFromFeed(Oracle.Data memory data) private view returns (uint256 mid_) {
mid_ = Math.average(data.priceOverMicroWindow, data.priceOverMacroWindow);
}
/// @dev Rolling volume adjustments on bid side to be used for market impact.
/// @dev Volume values are normalized with respect to cap
function _registerVolumeBid(
Oracle.Data memory data,
uint256 volume,
uint256 cap
) private returns (uint256) {
// save gas with snapshot in memory
Roller.Snapshot memory snapshot = snapshotVolumeBid;
int256 value = int256(volume.divUp(cap));
// calculates the decay in the rolling volume since last snapshot
// and determines new window to decay over
snapshot = snapshot.transform(block.timestamp, data.microWindow, value);
// store the transformed snapshot
snapshotVolumeBid = snapshot;
// return the cumulative volume
return uint256(snapshot.cumulative());
}
/// @dev Rolling volume adjustments on ask side to be used for market impact.
/// @dev Volume values are normalized with respect to cap
function _registerVolumeAsk(
Oracle.Data memory data,
uint256 volume,
uint256 cap
) private returns (uint256) {
// save gas with snapshot in memory
Roller.Snapshot memory snapshot = snapshotVolumeAsk;
int256 value = int256(volume.divUp(cap));
// calculates the decay in the rolling volume since last snapshot
// and determines new window to decay over
snapshot = snapshot.transform(block.timestamp, data.microWindow, value);
// store the transformed snapshot
snapshotVolumeAsk = snapshot;
// return the cumulative volume
return uint256(snapshot.cumulative());
}
/// @notice Rolling mint accumulator to be used for circuit breaker
/// @dev value > 0 registers a mint, value <= 0 registers a burn
function _registerMintOrBurn(int256 value) private returns (int256) {
// save gas with snapshot in memory
Roller.Snapshot memory snapshot = snapshotMinted;
// calculates the decay in the rolling amount minted since last snapshot
// and determines new window to decay over
uint256 circuitBreakerWindow = params.get(Risk.Parameters.CircuitBreakerWindow);
snapshot = snapshot.transform(block.timestamp, circuitBreakerWindow, value);
// store the transformed snapshot
snapshotMinted = snapshot;
// return the cumulative mint amount
int256 minted = snapshot.cumulative();
return minted;
}
/// @notice Sets the governance per-market risk parameter
function setRiskParam(Risk.Parameters name, uint256 value) external onlyFactory {
_checkRiskParam(name, value);
_cacheRiskCalc(name, value);
params.set(name, value);
}
/// @notice Checks the governance per-market risk parameter is valid
function _checkRiskParam(Risk.Parameters name, uint256 value) private {
// checks delta won't cause position to be immediately
// liquidatable given current leverage cap (capLeverage),
// liquidation fee rate (liquidationFeeRate), and
// maintenance margin fraction (maintenanceMarginFraction)
if (name == Risk.Parameters.Delta) {
uint256 _delta = value;
uint256 capLeverage = params.get(Risk.Parameters.CapLeverage);
uint256 maintenanceMarginFraction = params.get(
Risk.Parameters.MaintenanceMarginFraction
);
uint256 liquidationFeeRate = params.get(Risk.Parameters.LiquidationFeeRate);
require(
capLeverage <=
ONE.divDown(
2 * _delta + maintenanceMarginFraction.divDown(ONE - liquidationFeeRate)
),
"OVLV1: max lev immediately liquidatable"
);
}
// checks capLeverage won't cause position to be immediately
// liquidatable given current spread (delta),
// liquidation fee rate (liquidationFeeRate), and
// maintenance margin fraction (maintenanceMarginFraction)
if (name == Risk.Parameters.CapLeverage) {
uint256 _capLeverage = value;
uint256 delta = params.get(Risk.Parameters.Delta);
uint256 maintenanceMarginFraction = params.get(
Risk.Parameters.MaintenanceMarginFraction
);
uint256 liquidationFeeRate = params.get(Risk.Parameters.LiquidationFeeRate);
require(
_capLeverage <=
ONE.divDown(
2 * delta + maintenanceMarginFraction.divDown(ONE - liquidationFeeRate)
),
"OVLV1: max lev immediately liquidatable"
);
}
// checks maintenanceMarginFraction won't cause position
// to be immediately liquidatable given current spread (delta),
// liquidation fee rate (liquidationFeeRate),
// and leverage cap (capLeverage)
if (name == Risk.Parameters.MaintenanceMarginFraction) {
uint256 _maintenanceMarginFraction = value;
uint256 delta = params.get(Risk.Parameters.Delta);
uint256 capLeverage = params.get(Risk.Parameters.CapLeverage);
uint256 liquidationFeeRate = params.get(Risk.Parameters.LiquidationFeeRate);
require(
capLeverage <=
ONE.divDown(
2 * delta + _maintenanceMarginFraction.divDown(ONE - liquidationFeeRate)
),
"OVLV1: max lev immediately liquidatable"
);
}
// checks liquidationFeeRate won't cause position
// to be immediately liquidatable given current spread (delta),
// leverage cap (capLeverage), and
// maintenance margin fraction (maintenanceMarginFraction)
if (name == Risk.Parameters.LiquidationFeeRate) {
uint256 _liquidationFeeRate = value;
uint256 delta = params.get(Risk.Parameters.Delta);
uint256 capLeverage = params.get(Risk.Parameters.CapLeverage);
uint256 maintenanceMarginFraction = params.get(
Risk.Parameters.MaintenanceMarginFraction
);
require(
capLeverage <=
ONE.divDown(
2 * delta + maintenanceMarginFraction.divDown(ONE - _liquidationFeeRate)
),
"OVLV1: max lev immediately liquidatable"
);
}
// checks priceDriftUpperLimit won't cause pow() call in dataIsValid
// to exceed max
if (name == Risk.Parameters.PriceDriftUpperLimit) {
Oracle.Data memory data = IOverlayV1Feed(feed).latest();
uint256 _priceDriftUpperLimit = value;
require(
_priceDriftUpperLimit * data.macroWindow < MAX_NATURAL_EXPONENT,
"OVLV1: price drift exceeds max exp"
);
}
}
/// @notice Caches risk param calculations used in market contract
/// @notice for gas savings
function _cacheRiskCalc(Risk.Parameters name, uint256 value) private {
// caches calculations for dpUpperLimit
// = e**(priceDriftUpperLimit * data.macroWindow)
if (name == Risk.Parameters.PriceDriftUpperLimit) {
Oracle.Data memory data = IOverlayV1Feed(feed).latest();
uint256 _priceDriftUpperLimit = value;
uint256 pow = _priceDriftUpperLimit * data.macroWindow;
dpUpperLimit = pow.expUp(); // e**(pow)
}
}
}
| return the latest data from feed | return data;
| 14,060,233 | [
1,
2463,
326,
4891,
501,
628,
4746,
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,
327,
501,
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,
-100,
-100,
-100,
-100,
-100,
-100
] |
./full_match/4/0x448895cB30AcE7004a9F6f0f74739a5f2500d80B/sources/contracts/simplestorage.sol | mempory only stored during execution. storage is stored after | function addperson(string memory _name, uint256 _favoritenumber) public {
people.push(People(_favoritenumber, _name));
nametofavoritenumber[_name] = _favoritenumber;
}
| 12,357,355 | [
1,
3917,
84,
630,
1338,
4041,
4982,
4588,
18,
225,
2502,
353,
4041,
1839,
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,
527,
12479,
12,
1080,
3778,
389,
529,
16,
2254,
5034,
389,
19731,
280,
305,
21998,
13,
1071,
288,
203,
3639,
16951,
18,
6206,
12,
11227,
11763,
24899,
19731,
280,
305,
21998,
16,
389,
529,
10019,
203,
3639,
15135,
11453,
19731,
280,
305,
21998,
63,
67,
529,
65,
273,
389,
19731,
280,
305,
21998,
31,
203,
565,
289,
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,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-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/137/0x7f0155fd06594261b07558D6FaEF1A195D154e4b/sources/EVSignerControl.sol | overwrite all signer addresses
| signers[i] = address(0); | 3,524,995 | [
1,
19274,
777,
10363,
6138,
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
] | [
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,
0
] | [
1,
5411,
1573,
414,
63,
77,
65,
273,
1758,
12,
20,
1769,
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
] |
pragma solidity 0.6.12;
contract Initializable {
/**
* @dev Indicates that the contract has been initialized.
*/
bool private initialized;
/**
* @dev Indicates that the contract is in the process of being initialized.
*/
bool private initializing;
/**
* @dev Modifier to use in the initializer function of a contract.
*/
modifier initializer() {
require(initializing || isConstructor() || !initialized, "Contract instance has already been initialized");
bool isTopLevelCall = !initializing;
if (isTopLevelCall) {
initializing = true;
initialized = true;
}
_;
if (isTopLevelCall) {
initializing = false;
}
}
/**
* @dev Modifier to use in the initializer function of a contract when upgrade EVEN times.
*/
modifier initializerEven() {
require(initializing || isConstructor() || initialized, "Contract instance has already been initialized EVEN times");
bool isTopLevelCall = !initializing;
if (isTopLevelCall) {
initializing = true;
initialized = false;
}
_;
if (isTopLevelCall) {
initializing = false;
}
}
/// @dev Returns true if and only if the function is running in the constructor
function isConstructor() private view returns (bool) {
// extcodesize checks the size of the code stored in an address, and
// address returns the current address. Since the code is still not
// deployed when running a constructor, any checks on its code size will
// yield zero, making it an effective way to detect if a contract is
// under construction or not.
address self = address(this);
uint256 cs;
assembly { cs := extcodesize(self) }
return cs == 0;
}
// Reserved storage space to allow for layout changes in the future.
uint256[50] private ______gap;
}
contract Governable is Initializable {
address public governor;
event GovernorshipTransferred(address indexed previousGovernor, address indexed newGovernor);
/**
* @dev Contract initializer.
* called once by the factory at time of deployment
*/
function initialize(address governor_) virtual public initializer {
governor = governor_;
emit GovernorshipTransferred(address(0), governor);
}
modifier governance() {
require(msg.sender == governor);
_;
}
/**
* @dev Allows the current governor to relinquish control of the contract.
* @notice Renouncing to governorship will leave the contract without an governor.
* It will not be possible to call the functions with the `governance`
* modifier anymore.
*/
function renounceGovernorship() public governance {
emit GovernorshipTransferred(governor, address(0));
governor = address(0);
}
/**
* @dev Allows the current governor to transfer control of the contract to a newGovernor.
* @param newGovernor The address to transfer governorship to.
*/
function transferGovernorship(address newGovernor) public governance {
_transferGovernorship(newGovernor);
}
/**
* @dev Transfers control of the contract to a newGovernor.
* @param newGovernor The address to transfer governorship to.
*/
function _transferGovernorship(address newGovernor) internal {
require(newGovernor != address(0));
emit GovernorshipTransferred(governor, newGovernor);
governor = newGovernor;
}
}
contract Configurable is Governable {
mapping (bytes32 => uint) internal config;
function getConfig(bytes32 key) public view returns (uint) {
return config[key];
}
function getConfig(bytes32 key, uint index) public view returns (uint) {
return config[bytes32(uint(key) ^ index)];
}
function getConfig(bytes32 key, address addr) public view returns (uint) {
return config[bytes32(uint(key) ^ uint(addr))];
}
function _setConfig(bytes32 key, uint value) internal {
if(config[key] != value)
config[key] = value;
}
function _setConfig(bytes32 key, uint index, uint value) internal {
_setConfig(bytes32(uint(key) ^ index), value);
}
function _setConfig(bytes32 key, address addr, uint value) internal {
_setConfig(bytes32(uint(key) ^ uint(addr)), value);
}
function setConfig(bytes32 key, uint value) external governance {
_setConfig(key, value);
}
function setConfig(bytes32 key, uint index, uint value) external governance {
_setConfig(bytes32(uint(key) ^ index), value);
}
function setConfig(bytes32 key, address addr, uint value) external governance {
_setConfig(bytes32(uint(key) ^ uint(addr)), value);
}
}
interface Minter {
event Minted(address indexed recipient, address reward_contract, uint minted);
function token() external view returns (address);
function controller() external view returns (address);
function minted(address, address) external view returns (uint);
function allowed_to_mint_for(address, address) external view returns (bool);
function mint(address gauge) external;
function mint_many(address[8] calldata gauges) external;
function mint_for(address gauge, address _for) external;
function toggle_approve_mint(address minting_user) external;
}
interface LiquidityGauge {
event Deposit(address indexed provider, uint value);
event Withdraw(address indexed provider, uint value);
event UpdateLiquidityLimit(address user, uint original_balance, uint original_supply, uint working_balance, uint working_supply);
function user_checkpoint (address addr) external returns (bool);
function claimable_tokens(address addr) external view returns (uint);
function claimable_reward(address addr) external view returns (uint);
function integrate_checkpoint() external view returns (uint);
function kick(address addr) external;
function set_approve_deposit(address addr, bool can_deposit) external;
function deposit(uint _value) external;
function deposit(uint _value, address addr) external;
function withdraw(uint _value) external;
function withdraw(uint _value, bool claim_rewards) external;
function claim_rewards() external;
function claim_rewards(address addr) external;
function minter() external view returns (address);
function crv_token() external view returns (address);
function lp_token() external view returns (address);
function controller() external view returns (address);
function voting_escrow() external view returns (address);
function balanceOf(address) external view returns (uint);
function totalSupply() external view returns (uint);
function future_epoch_time() external view returns (uint);
function approved_to_deposit(address, address) external view returns (bool);
function working_balances(address) external view returns (uint);
function working_supply() external view returns (uint);
function period() external view returns (int128);
function period_timestamp(uint) external view returns (uint);
function integrate_inv_supply(uint) external view returns (uint);
function integrate_inv_supply_of(address) external view returns (uint);
function integrate_checkpoint_of(address) external view returns (uint);
function integrate_fraction(address) external view returns (uint);
function inflation_rate() external view returns (uint);
function reward_contract() external view returns (address);
function rewarded_token() external view returns (address);
function reward_integral() external view returns (uint);
function reward_integral_for(address) external view returns (uint);
function rewards_for(address) external view returns (uint);
function claimed_rewards_for(address) external view returns (uint);
}
contract SSimpleGauge is LiquidityGauge, Configurable {
using SafeMath for uint;
using TransferHelper for address;
address override public minter;
address override public crv_token;
address override public lp_token;
address override public controller;
address override public voting_escrow;
mapping(address => uint) override public balanceOf;
uint override public totalSupply;
uint override public future_epoch_time;
// caller -> recipient -> can deposit?
mapping(address => mapping(address => bool)) override public approved_to_deposit;
mapping(address => uint) override public working_balances;
uint override public working_supply;
// The goal is to be able to calculate ∫(rate * balance / totalSupply dt) from 0 till checkpoint
// All values are kept in units of being multiplied by 1e18
int128 override public period;
uint256[100000000000000000000000000000] override public period_timestamp;
// 1e18 * ∫(rate(t) / totalSupply(t) dt) from 0 till checkpoint
uint256[100000000000000000000000000000] override public integrate_inv_supply; // bump epoch when rate() changes
// 1e18 * ∫(rate(t) / totalSupply(t) dt) from (last_action) till checkpoint
mapping(address => uint) override public integrate_inv_supply_of;
mapping(address => uint) override public integrate_checkpoint_of;
// ∫(balance * rate(t) / totalSupply(t) dt) from 0 till checkpoint
// Units: rate * t = already number of coins per address to issue
mapping(address => uint) override public integrate_fraction;
uint override public inflation_rate;
// For tracking external rewards
address override public reward_contract;
address override public rewarded_token;
uint override public reward_integral;
mapping(address => uint) override public reward_integral_for;
mapping(address => uint) override public rewards_for;
mapping(address => uint) override public claimed_rewards_for;
uint public span;
uint public end;
function initialize(address governor, address _minter, address _lp_token) public initializer {
super.initialize(governor);
minter = _minter;
crv_token = Minter(_minter).token();
lp_token = _lp_token;
IERC20(lp_token).totalSupply(); // just check
}
function setSpan(uint _span, bool isLinear) virtual external governance {
span = _span;
if(isLinear)
end = now + _span;
else
end = 0;
}
function kick(address addr) virtual override external {
_checkpoint(addr, true);
}
function set_approve_deposit(address addr, bool can_deposit) virtual override external {
approved_to_deposit[addr][msg.sender] = can_deposit;
}
function deposit(uint amount) virtual override external {
deposit(amount, msg.sender);
}
function deposit(uint amount, address addr) virtual override public {
require(addr == msg.sender || approved_to_deposit[msg.sender][addr], 'Not approved');
_checkpoint(addr, true);
_deposit(addr, amount);
balanceOf[addr] = balanceOf[addr].add(amount);
totalSupply = totalSupply.add(amount);
emit Deposit(addr, amount);
}
function _deposit(address addr, uint amount) virtual internal {
lp_token.safeTransferFrom(addr, address(this), amount);
}
function withdraw() virtual external {
withdraw(balanceOf[msg.sender], true);
}
function withdraw(uint amount) virtual override external {
withdraw(amount, true);
}
function withdraw(uint amount, bool claim_rewards) virtual override public {
_checkpoint(msg.sender, claim_rewards);
totalSupply = totalSupply.sub(amount);
balanceOf[msg.sender] = balanceOf[msg.sender].sub(amount);
_withdraw(msg.sender, amount);
emit Withdraw(msg.sender, amount);
}
function _withdraw(address to, uint amount) virtual internal {
lp_token.safeTransfer(to, amount);
}
function claimable_reward(address) virtual override public view returns (uint) {
return 0;
}
function claim_rewards() virtual override public {
return claim_rewards(msg.sender);
}
function claim_rewards(address) virtual override public {
return;
}
function _checkpoint_rewards(address, bool) virtual internal {
return;
}
function claimable_tokens(address addr) virtual override public view returns (uint amount) {
if(span == 0 || totalSupply == 0)
return 0;
amount = SMinter(minter).quotas(address(this));
amount = amount.mul(balanceOf[addr]).div(totalSupply);
uint lasttime = integrate_checkpoint_of[addr];
if(end == 0) { // isNonLinear, endless
if(now.sub(lasttime) < span)
amount = amount.mul(now.sub(lasttime)).div(span);
}else if(now < end)
amount = amount.mul(now.sub(lasttime)).div(end.sub(lasttime));
else if(lasttime >= end)
amount = 0;
}
function _checkpoint(address addr, uint amount) virtual internal {
if(amount > 0) {
integrate_fraction[addr] = integrate_fraction[addr].add(amount);
address teamAddr = address(config['teamAddr']);
uint teamRatio = config['teamRatio'];
if(teamAddr != address(0) && teamRatio != 0)
integrate_fraction[teamAddr] = integrate_fraction[teamAddr].add(amount.mul(teamRatio).div(1 ether));
}
}
function _checkpoint(address addr, bool _claim_rewards) virtual internal {
uint amount = claimable_tokens(addr);
_checkpoint(addr, amount);
_checkpoint_rewards(addr, _claim_rewards);
integrate_checkpoint_of[addr] = now;
}
function user_checkpoint(address addr) virtual override external returns (bool) {
_checkpoint(addr, true);
return true;
}
function integrate_checkpoint() override external view returns (uint) {
return now;
}
}
c
SExactGauge is LiquidityGauge, Configurable {
using SafeMath for uint;
using TransferHelper for address;
bytes32 internal constant _devAddr_ = 'devAddr';
bytes32 internal constant _devRatio_ = 'devRatio';
bytes32 internal constant _ecoAddr_ = 'ecoAddr';
bytes32 internal constant _ecoRatio_ = 'ecoRatio';
address override public minter;
address override public crv_token;
address override public lp_token;
address override public controller;
address override public voting_escrow;
mapping(address => uint) override public balanceOf;
uint override public totalSupply;
uint override public future_epoch_time;
// caller -> recipient -> can deposit?
mapping(address => mapping(address => bool)) override public approved_to_deposit;
mapping(address => uint) override public working_balances;
uint override public working_supply;
// The goal is to be able to calculate ∫(rate * balance / totalSupply dt) from 0 till checkpoint
// All values are kept in units of being multiplied by 1e18
int128 override public period;
uint256[100000000000000000000000000000] override public period_timestamp;
// 1e18 * ∫(rate(t) / totalSupply(t) dt) from 0 till checkpoint
uint256[100000000000000000000000000000] override public integrate_inv_supply; // bump epoch when rate() changes
// 1e18 * ∫(rate(t) / totalSupply(t) dt) from (last_action) till checkpoint
mapping(address => uint) override public integrate_inv_supply_of;
mapping(address => uint) override public integrate_checkpoint_of;
// ∫(balance * rate(t) / totalSupply(t) dt) from 0 till checkpoint
// Units: rate * t = already number of coins per address to issue
mapping(address => uint) override public integrate_fraction;
uint override public inflation_rate;
// For tracking external rewards
address override public reward_contract;
address override public rewarded_token;
uint override public reward_integral;
mapping(address => uint) override public reward_integral_for;
mapping(address => uint) override public rewards_for;
mapping(address => uint) override public claimed_rewards_for;
uint public span;
uint public end;
mapping(address => uint) public sumMiningPerOf;
uint public sumMiningPer;
uint public bufReward;
uint public lasttime;
function initialize(address governor, address _minter, address _lp_token) public initializer {
super.initialize(governor);
minter = _minter;
crv_token = Minter(_minter).token();
lp_token = _lp_token;
IERC20(lp_token).totalSupply(); // just check
}
function setSpan(uint _span, bool isLinear) virtual external governance {
span = _span;
if(isLinear)
end = now + _span;
else
end = 0;
lasttime = now;
}
function kick(address addr) virtual override external {
_checkpoint(addr, true);
}
function set_approve_deposit(address addr, bool can_deposit) virtual override external {
approved_to_deposit[addr][msg.sender] = can_deposit;
}
function deposit(uint amount) virtual override external {
deposit(amount, msg.sender);
}
function deposit(uint amount, address addr) virtual override public {
require(addr == msg.sender || approved_to_deposit[msg.sender][addr], 'Not approved');
_checkpoint(addr, true);
_deposit(addr, amount);
balanceOf[msg.sender] = balanceOf[msg.sender].add(amount);
totalSupply = totalSupply.add(amount);
emit Deposit(msg.sender, amount);
}
function _deposit(address addr, uint amount) virtual internal {
lp_token.safeTransferFrom(addr, address(this), amount);
}
function withdraw() virtual external {
withdraw(balanceOf[msg.sender], true);
}
function withdraw(uint amount) virtual override external {
withdraw(amount, true);
}
function withdraw(uint amount, bool _claim_rewards) virtual override public {
_checkpoint(msg.sender, _claim_rewards);
totalSupply = totalSupply.sub(amount);
balanceOf[msg.sender] = balanceOf[msg.sender].sub(amount);
_withdraw(msg.sender, amount);
emit Withdraw(msg.sender, amount);
}
function _withdraw(address to, uint amount) virtual internal {
lp_token.safeTransfer(to, amount);
}
function claimable_reward(address addr) virtual override public view returns (uint) {
addr;
return 0;
}
function claim_rewards() virtual override public {
return claim_rewards(msg.sender);
}
function claim_rewards(address) virtual override public {
return;
}
function _checkpoint_rewards(address, bool) virtual internal {
return;
}
function claimable_tokens(address addr) virtual override public view returns (uint) {
return _claimable_tokens(addr, claimableDelta(), sumMiningPer, sumMiningPerOf[addr]);
}
function _claimable_tokens(address addr, uint delta, uint sumPer, uint lastSumPer) virtual internal view returns (uint amount) {
if(span == 0 || totalSupply == 0)
return 0;
amount = sumPer.sub(lastSumPer);
amount = amount.add(delta.mul(1 ether).div(totalSupply));
amount = amount.mul(balanceOf[addr]).div(1 ether);
}
function claimableDelta() virtual internal view returns(uint amount) {
amount = SMinter(minter).quotas(address(this)).sub(bufReward);
if(end == 0) { // isNonLinear, endless
if(now.sub(lasttime) < span)
amount = amount.mul(now.sub(lasttime)).div(span);
}else if(now < end)
amount = amount.mul(now.sub(lasttime)).div(end.sub(lasttime));
else if(lasttime >= end)
amount = 0;
}
function _checkpoint(address addr, uint amount) virtual internal {
if(amount > 0) {
integrate_fraction[addr] = integrate_fraction[addr].add(amount);
addr = address(config[_devAddr_]);
uint ratio = config[_devRatio_];
if(addr != address(0) && ratio != 0)
integrate_fraction[addr] = integrate_fraction[addr].add(amount.mul(ratio).div(1 ether));
addr = address(config[_ecoAddr_]);
ratio = config[_ecoRatio_];
if(addr != address(0) && ratio != 0)
integrate_fraction[addr] = integrate_fraction[addr].add(amount.mul(ratio).div(1 ether));
}
}
function _checkpoint(address addr, bool _claim_rewards) virtual internal {
if(span == 0 || totalSupply == 0)
return;
uint delta = claimableDelta();
uint amount = _claimable_tokens(addr, delta, sumMiningPer, sumMiningPerOf[addr]);
if(delta != amount)
bufReward = bufReward.add(delta).sub(amount);
if(delta > 0)
sumMiningPer = sumMiningPer.add(delta.mul(1 ether).div(totalSupply));
if(sumMiningPerOf[addr] != sumMiningPer)
sumMiningPerOf[addr] = sumMiningPer;
lasttime = now;
_checkpoint(addr, amount);
_checkpoint_rewards(addr, _claim_rewards);
}
function user_checkpoint(address addr) virtual override external returns (bool) {
_checkpoint(addr, true);
return true;
}
function integrate_checkpoint() override external view returns (uint) {
return lasttime;
}
}
contra
uge is SExactGauge {
address[] public rewards;
mapping(address => mapping(address =>uint)) public sumRewardPerOf; // recipient => rewarded_token => can sumRewardPerOf
mapping(address => uint) public sumRewardPer; // rewarded_token => can sumRewardPerOf
function initialize(address governor, address _minter, address _lp_token, address _nestGauge, address[] memory _moreRewards) public initializer {
super.initialize(governor, _minter, _lp_token);
reward_contract = _nestGauge;
rewarded_token = LiquidityGauge(_nestGauge).crv_token();
rewards = _moreRewards;
rewards.push(rewarded_token);
address rewarded_token2 = LiquidityGauge(_nestGauge).rewarded_token();
if(rewarded_token2 != address(0))
rewards.push(rewarded_token2);
LiquidityGauge(_nestGauge).integrate_checkpoint(); // just check
for(uint i=0; i<_moreRewards.length; i++)
IERC20(_moreRewards[i]).totalSupply(); // just check
}
function _deposit(address from, uint amount) virtual override internal {
super._deposit(from, amount); // lp_token.safeTransferFrom(from, address(this), amount);
lp_token.safeApprove(reward_contract, amount);
LiquidityGauge(reward_contract).deposit(amount);
}
function _withdraw(address to, uint amount) virtual override internal {
LiquidityGauge(reward_contract).withdraw(amount);
super._withdraw(to, amount); // lp_token.safeTransfer(to, amount);
}
function claim_rewards(address to) virtual override public {
if(span == 0 || totalSupply == 0)
return;
uint[] memory bals = new uint[](rewards.length);
for(uint i=0; i<bals.length; i++)
bals[i] = IERC20(rewards[i]).balanceOf(address(this));
Minter(LiquidityGauge(reward_contract).minter()).mint(reward_contract);
LiquidityGauge(reward_contract).claim_rewards();
for(uint i=0; i<bals.length; i++) {
uint delta = IERC20(rewards[i]).balanceOf(address(this)).sub(bals[i]);
uint amount = _claimable_tokens(msg.sender, delta, sumRewardPer[rewards[i]], sumRewardPerOf[msg.sender][rewards[i]]);
if(delta > 0)
sumRewardPer[rewards[i]] = sumRewardPer[rewards[i]].add(delta.mul(1 ether).div(totalSupply));
if(sumRewardPerOf[msg.sender][rewards[i]] != sumRewardPer[rewards[i]])
sumRewardPerOf[msg.sender][rewards[i]] = sumRewardPer[rewards[i]];
if(amount > 0) {
rewards[i].safeTransfer(to, amount);
if(rewards[i] == rewarded_token) {
rewards_for[to] = rewards_for[to].add(amount);
claimed_rewards_for[to] = claimed_rewards_for[to].add(amount);
}
}
}
}
function claimable_reward(address addr) virtual override public view returns (uint) {
uint delta = LiquidityGauge(reward_contract).claimable_tokens(address(this));
return _claimable_tokens(addr, delta, sumRewardPer[rewarded_token], sumRewardPerOf[addr][rewarded_token]);
}
function claimable_reward2(address addr) virtual public view returns (uint) {
uint delta = LiquidityGauge(reward_contract).claimable_reward(address(this));
address reward2 = LiquidityGauge(reward_contract).rewarded_token();
return _claimable_tokens(addr, delta, sumRewardPer[reward2], sumRewardPerOf[addr][reward2]);
}
}
contrac
is Minter, Configurable {
using SafeMath for uint;
using Address for address payable;
using TransferHelper for address;
bytes32 internal constant _allowContract_ = 'allowContract';
bytes32 internal constant _allowlist_ = 'allowlist';
bytes32 internal constant _blocklist_ = 'blocklist';
address override public token;
address override public controller;
mapping(address => mapping(address => uint)) override public minted; // user => reward_contract => value
mapping(address => mapping(address => bool)) override public allowed_to_mint_for; // minter => user => can mint?
mapping(address => uint) public quotas; // reward_contract => quota;
function initialize(address governor, address token_) public initializer {
super.initialize(governor);
token = token_;
}
function setGaugeQuota(address gauge, uint quota) public governance {
quotas[gauge] = quota;
}
function mint(address gauge) virtual override public {
mint_for(gauge, msg.sender);
}
function mint_many(address[8] calldata gauges) virtual override external {
for(uint i=0; i<gauges.length; i++)
mint(gauges[i]);
}
function mint_for(address gauge, address _for) virtual override public {
require(_for == msg.sender || allowed_to_mint_for[msg.sender][_for], 'Not approved');
require(quotas[gauge] > 0, 'No quota');
require(getConfig(_blocklist_, msg.sender) == 0, 'In blocklist');
bool isContract = msg.sender.isContract();
require(!isContract || config[_allowContract_] != 0 || getConfig(_allowlist_, msg.sender) != 0, 'No allowContract');
LiquidityGauge(gauge).user_checkpoint(_for);
uint total_mint = LiquidityGauge(gauge).integrate_fraction(_for);
uint to_mint = total_mint.sub(minted[_for][gauge]);
if(to_mint != 0) {
quotas[gauge] = quotas[gauge].sub(to_mint);
token.safeTransfer(_for, to_mint);
minted[_for][gauge] = total_mint;
emit Minted(_for, gauge, total_mint);
}
}
function toggle_approve_mint(address minting_user) virtual override external {
allowed_to_mint_for[minting_user][msg.sender] = !allowed_to_mint_for[minting_user][msg.sender];
}
}
/*
// he
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;
}
}
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;
}
function sqrt(uint x)public pure returns(uint y) {
uint z = (x + 1) / 2;
y = x;
while (z < y) {
y = z;
z = (x / z + z) / 2;
}
}
}
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);
}
}
}
}
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);
}
contract ERC20 is Context, IERC20 {
using SafeMath for uint256;
using Address for address;
mapping (address => uint256) public _balances;
mapping (address => mapping (address => uint256)) internal _allowances;
uint256 public _totalSupply;
string internal _name;
string internal _symbol;
uint8 internal _decimals;
/**
* @dev Sets the values for {name} and {symbol}, initializes {decimals} with
* a default value of 18.
*
* To select a different value for {decimals}, use {_setupDecimals}.
*
* All three of these values are immutable: they can only be set once during
* construction.
*/
constructor (string memory name, string memory symbol) public {
_name = name;
_symbol = symbol;
_decimals = 18;
}
/**
* @dev Returns the name of the token.
*/
function name() public view returns (string memory) {
return _name;
}
/**
* @dev Returns the symbol of the token, usually a shorter version of the
* name.
*/
function symbol() public view returns (string memory) {
return _symbol;
}
/**
* @dev Returns the number of decimals used to get its user representation.
* For example, if `decimals` equals `2`, a balance of `505` tokens should
* be displayed to a user as `5,05` (`505 / 10 ** 2`).
*
* Tokens usually opt for a value of 18, imitating the relationship between
* Ether and Wei. This is the value {ERC20} uses, unless {_setupDecimals} is
* called.
*
* NOTE: This information is only used for _display_ purposes: it in
* no way affects any of the arithmetic of the contract, including
* {IERC20-balanceOf} and {IERC20-transfer}.
*/
function decimals() public view returns (uint8) {
return _decimals;
}
/**
* @dev See {IERC20-totalSupply}.
*/
function totalSupply() public view virtual override returns (uint256) {
return _totalSupply;
}
/**
* @dev See {IERC20-balanceOf}.
*/
function balanceOf(address account) public view virtual override returns (uint256) {
return _balances[account];
}
/**
* @dev See {IERC20-transfer}.
*
* Requirements:
*
* - `recipient` cannot be the zero address.
* - the caller must have a balance of at least `amount`.
*/
function transfer(address recipient, uint256 amount) public virtual override returns (bool) {
_transfer(_msgSender(), recipient, amount);
return true;
}
/**
* @dev See {IERC20-allowance}.
*/
function allowance(address owner, address spender) public view virtual override returns (uint256) {
return _allowances[owner][spender];
}
/**
* @dev See {IERC20-approve}.
*
* Requirements:
*
* - `spender` cannot be the zero address.
*/
function approve(address spender, uint256 amount) public virtual override returns (bool) {
_approve(_msgSender(), spender, amount);
return true;
}
/**
* @dev See {IERC20-transferFrom}.
*
* Emits an {Approval} event indicating the updated allowance. This is not
* required by the EIP. See the note at the beginning of {ERC20};
*
* Requirements:
* - `sender` and `recipient` cannot be the zero address.
* - `sender` must have a balance of at least `amount`.
* - the caller must have allowance for ``sender``'s tokens of at least
* `amount`.
*/
function transferFrom(address sender, address recipient, uint256 amount) public virtual override returns (bool) {
_transfer(sender, recipient, amount);
_approve(sender, _msgSender(), _allowances[sender][_msgSender()].sub(amount, "ERC20: transfer amount exceeds allowance"));
return true;
}
/**
* @dev Atomically increases the allowance granted to `spender` by the caller.
*
* This is an alternative to {approve} that can be used as a mitigation for
* problems described in {IERC20-approve}.
*
* Emits an {Approval} event indicating the updated allowance.
*
* Requirements:
*
* - `spender` cannot be the zero address.
*/
function increaseAllowance(address spender, uint256 addedValue) public virtual returns (bool) {
_approve(_msgSender(), spender, _allowances[_msgSender()][spender].add(addedValue));
return true;
}
/**
* @dev Atomically decreases the allowance granted to `spender` by the caller.
*
* This is an alternative to {approve} that can be used as a mitigation for
* problems described in {IERC20-approve}.
*
* Emits an {Approval} event indicating the updated allowance.
*
* Requirements:
*
* - `spender` cannot be the zero address.
* - `spender` must have allowance for the caller of at least
* `subtractedValue`.
*/
function decreaseAllowance(address spender, uint256 subtractedValue) public virtual returns (bool) {
_approve(_msgSender(), spender, _allowances[_msgSender()][spender].sub(subtractedValue, "ERC20: decreased allowance below zero"));
return true;
}
/**
* @dev Moves tokens `amount` from `sender` to `recipient`.
*
* This is internal function is equivalent to {transfer}, and can be used to
* e.g. implement automatic token fees, slashing mechanisms, etc.
*
* Emits a {Transfer} event.
*
* Requirements:
*
* - `sender` cannot be the zero address.
* - `recipient` cannot be the zero address.
* - `sender` must have a balance of at least `amount`.
*/
function _transfer(address sender, address recipient, uint256 amount) internal virtual {
require(sender != address(0), "ERC20: transfer from the zero address");
require(recipient != address(0), "ERC20: transfer to the zero address");
_beforeTokenTransfer(sender, recipient, amount);
_balances[sender] = _balances[sender].sub(amount, "ERC20: transfer amount exceeds balance");
_balances[recipient] = _balances[recipient].add(amount);
emit Transfer(sender, recipient, amount);
}
/** @dev Creates `amount` tokens and assigns them to `account`, increasing
* the total supply.
*
* Emits a {Transfer} event with `from` set to the zero address.
*
* Requirements
*
* - `to` cannot be the zero address.
*/
function _mint(address account, uint256 amount) internal virtual {
require(account != address(0), "ERC20: mint to the zero address");
_beforeTokenTransfer(address(0), account, amount);
_totalSupply = _totalSupply.add(amount);
_balances[account] = _balances[account].add(amount);
emit Transfer(address(0), account, amount);
}
/**
* @dev Destroys `amount` tokens from `account`, reducing the
* total supply.
*
* Emits a {Transfer} event with `to` set to the zero address.
*
* Requirements
*
* - `account` cannot be the zero address.
* - `account` must have at least `amount` tokens.
*/
function _burn(address account, uint256 amount) internal virtual {
require(account != address(0), "ERC20: burn from the zero address");
_beforeTokenTransfer(account, address(0), amount);
_balances[account] = _balances[account].sub(amount, "ERC20: burn amount exceeds balance");
_totalSupply = _totalSupply.sub(amount);
emit Transfer(account, address(0), amount);
}
/**
* @dev Sets `amount` as the allowance of `spender` over the `owner`s tokens.
*
* This is internal function is equivalent to `approve`, and can be used to
* e.g. set automatic allowances for certain subsystems, etc.
*
* Emits an {Approval} event.
*
* Requirements:
*
* - `owner` cannot be the zero address.
* - `spender` cannot be the zero address.
*/
function _approve(address owner, address spender, uint256 amount) internal virtual {
require(owner != address(0), "ERC20: approve from the zero address");
require(spender != address(0), "ERC20: approve to the zero address");
_allowances[owner][spender] = amount;
emit Approval(owner, spender, amount);
}
/**
* @dev Sets {decimals} to a value other than the default one of 18.
*
* WARNING: This function should only be called from the constructor. Most
* applications that interact with token contracts will not expect
* {decimals} to ever change, and may work incorrectly if it does.
*/
function _setupDecimals(uint8 decimals_) internal {
_decimals = decimals_;
}
/**
* @dev Hook that is called before any transfer of tokens. This includes
* minting and burning.
*
* Calling conditions:
*
* - when `from` and `to` are both non-zero, `amount` of ``from``'s tokens
* will be to transferred to `to`.
* - when `from` is zero, `amount` tokens will be minted for `to`.
* - when `to` is zero, `amount` of ``from``'s tokens will be burned.
* - `from` and `to` are never both zero.
*
* To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks].
*/
function _beforeTokenTransfer(address from, address to, uint256 amount) internal virtual { }
}
contract SfgToken is ERC20 {
constructor(address SfgFarm) ERC20("Stable Finance Governance Token", "SFG") public {
uint8 decimals = 18;
_setupDecimals(decimals);
_mint(SfgFarm, 21000000 * 10 ** uint256(decimals)); // 100%, 21000000
}
}
contract SfyToken is ERC20 {
constructor(address SfyFarm) ERC20("Stable Finance Yield Token", "SFY") public {
uint8 decimals = 18;
_setupDecimals(decimals);
_mint(SfyFarm, 21000000 * 10 ** uint256(decimals)); // 100%, 21000000
}
}
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');
}
}
| caller -> recipient -> can deposit? The goal is to be able to calculate ∫(rate * balance / totalSupply dt) from 0 till checkpoint All values are kept in units of being multiplied by 1e18 1e18 * ∫(rate(t) / totalSupply(t) dt) from 0 till checkpoint 1e18 * ∫(rate(t) / totalSupply(t) dt) from (last_action) till checkpoint ∫(balance * rate(t) / totalSupply(t) dt) from 0 till checkpoint Units: rate * t = already number of coins per address to issue For tracking external rewards | SExactGauge is LiquidityGauge, Configurable {
using SafeMath for uint;
using TransferHelper for address;
bytes32 internal constant _devAddr_ = 'devAddr';
bytes32 internal constant _devRatio_ = 'devRatio';
bytes32 internal constant _ecoAddr_ = 'ecoAddr';
bytes32 internal constant _ecoRatio_ = 'ecoRatio';
address override public minter;
address override public crv_token;
address override public lp_token;
address override public controller;
address override public voting_escrow;
mapping(address => uint) override public balanceOf;
uint override public totalSupply;
uint override public future_epoch_time;
mapping(address => mapping(address => bool)) override public approved_to_deposit;
mapping(address => uint) override public working_balances;
uint override public working_supply;
int128 override public period;
uint256[100000000000000000000000000000] override public period_timestamp;
mapping(address => uint) override public integrate_inv_supply_of;
mapping(address => uint) override public integrate_checkpoint_of;
mapping(address => uint) override public integrate_fraction;
uint override public inflation_rate;
address override public reward_contract;
address override public rewarded_token;
uint override public reward_integral;
mapping(address => uint) override public reward_integral_for;
mapping(address => uint) override public rewards_for;
mapping(address => uint) override public claimed_rewards_for;
uint public span;
uint public end;
mapping(address => uint) public sumMiningPerOf;
uint public sumMiningPer;
uint public bufReward;
uint public lasttime;
function initialize(address governor, address _minter, address _lp_token) public initializer {
super.initialize(governor);
minter = _minter;
crv_token = Minter(_minter).token();
lp_token = _lp_token;
}
function setSpan(uint _span, bool isLinear) virtual external governance {
span = _span;
if(isLinear)
end = now + _span;
else
end = 0;
lasttime = now;
}
function kick(address addr) virtual override external {
_checkpoint(addr, true);
}
function set_approve_deposit(address addr, bool can_deposit) virtual override external {
approved_to_deposit[addr][msg.sender] = can_deposit;
}
function deposit(uint amount) virtual override external {
deposit(amount, msg.sender);
}
function deposit(uint amount, address addr) virtual override public {
require(addr == msg.sender || approved_to_deposit[msg.sender][addr], 'Not approved');
_checkpoint(addr, true);
_deposit(addr, amount);
balanceOf[msg.sender] = balanceOf[msg.sender].add(amount);
totalSupply = totalSupply.add(amount);
emit Deposit(msg.sender, amount);
}
function _deposit(address addr, uint amount) virtual internal {
lp_token.safeTransferFrom(addr, address(this), amount);
}
function withdraw() virtual external {
withdraw(balanceOf[msg.sender], true);
}
function withdraw(uint amount) virtual override external {
withdraw(amount, true);
}
function withdraw(uint amount, bool _claim_rewards) virtual override public {
_checkpoint(msg.sender, _claim_rewards);
totalSupply = totalSupply.sub(amount);
balanceOf[msg.sender] = balanceOf[msg.sender].sub(amount);
_withdraw(msg.sender, amount);
emit Withdraw(msg.sender, amount);
}
function _withdraw(address to, uint amount) virtual internal {
lp_token.safeTransfer(to, amount);
}
function claimable_reward(address addr) virtual override public view returns (uint) {
addr;
return 0;
}
function claim_rewards() virtual override public {
return claim_rewards(msg.sender);
}
function claim_rewards(address) virtual override public {
return;
}
function _checkpoint_rewards(address, bool) virtual internal {
return;
}
function claimable_tokens(address addr) virtual override public view returns (uint) {
return _claimable_tokens(addr, claimableDelta(), sumMiningPer, sumMiningPerOf[addr]);
}
function _claimable_tokens(address addr, uint delta, uint sumPer, uint lastSumPer) virtual internal view returns (uint amount) {
if(span == 0 || totalSupply == 0)
return 0;
amount = sumPer.sub(lastSumPer);
amount = amount.add(delta.mul(1 ether).div(totalSupply));
amount = amount.mul(balanceOf[addr]).div(1 ether);
}
function claimableDelta() virtual internal view returns(uint amount) {
amount = SMinter(minter).quotas(address(this)).sub(bufReward);
if(now.sub(lasttime) < span)
amount = amount.mul(now.sub(lasttime)).div(span);
}else if(now < end)
amount = amount.mul(now.sub(lasttime)).div(end.sub(lasttime));
else if(lasttime >= end)
amount = 0;
}
| 7,438,277 | [
1,
16140,
317,
8027,
317,
848,
443,
1724,
35,
1021,
17683,
353,
358,
506,
7752,
358,
4604,
225,
163,
235,
109,
12,
5141,
225,
11013,
342,
2078,
3088,
1283,
3681,
13,
628,
374,
21364,
9776,
4826,
924,
854,
16555,
316,
4971,
434,
3832,
27789,
635,
404,
73,
2643,
404,
73,
2643,
225,
225,
163,
235,
109,
12,
5141,
12,
88,
13,
342,
2078,
3088,
1283,
12,
88,
13,
3681,
13,
628,
374,
21364,
9776,
404,
73,
2643,
225,
225,
163,
235,
109,
12,
5141,
12,
88,
13,
342,
2078,
3088,
1283,
12,
88,
13,
3681,
13,
628,
261,
2722,
67,
1128,
13,
21364,
9776,
225,
163,
235,
109,
12,
12296,
225,
4993,
12,
88,
13,
342,
2078,
3088,
1283,
12,
88,
13,
3681,
13,
628,
374,
21364,
9776,
27845,
30,
4993,
225,
268,
273,
1818,
1300,
434,
276,
9896,
1534,
1758,
358,
5672,
2457,
11093,
3903,
283,
6397,
2,
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,
1,
1,
1,
1,
1,
1,
1,
1,
0
] | [
1,
348,
14332,
18941,
353,
511,
18988,
24237,
18941,
16,
29312,
288,
203,
203,
203,
565,
1450,
14060,
10477,
364,
2254,
31,
203,
203,
203,
565,
1450,
12279,
2276,
364,
1758,
31,
203,
203,
203,
377,
203,
203,
203,
565,
1731,
1578,
2713,
5381,
389,
5206,
3178,
67,
540,
273,
296,
5206,
3178,
13506,
203,
203,
203,
565,
1731,
1578,
2713,
5381,
389,
5206,
8541,
67,
3639,
273,
296,
5206,
8541,
13506,
203,
203,
203,
565,
1731,
1578,
2713,
5381,
389,
557,
83,
3178,
67,
540,
273,
296,
557,
83,
3178,
13506,
203,
203,
203,
565,
1731,
1578,
2713,
5381,
389,
557,
83,
8541,
67,
3639,
273,
296,
557,
83,
8541,
13506,
203,
203,
203,
377,
203,
203,
203,
565,
1758,
3849,
1071,
1131,
387,
31,
203,
203,
203,
565,
1758,
3849,
1071,
4422,
90,
67,
2316,
31,
203,
203,
203,
565,
1758,
3849,
1071,
12423,
67,
2316,
31,
203,
203,
203,
565,
1758,
3849,
1071,
2596,
31,
203,
203,
203,
565,
1758,
3849,
1071,
331,
17128,
67,
742,
492,
31,
203,
203,
203,
565,
2874,
12,
2867,
516,
2254,
13,
3849,
1071,
11013,
951,
31,
203,
203,
203,
565,
2254,
3849,
1071,
2078,
3088,
1283,
31,
203,
203,
203,
565,
2254,
3849,
1071,
3563,
67,
12015,
67,
957,
31,
203,
203,
203,
377,
203,
203,
203,
203,
203,
565,
2874,
12,
2867,
516,
2874,
12,
2867,
516,
1426,
3719,
3849,
1071,
20412,
67,
869,
67,
323,
1724,
31,
203,
203,
203,
377,
203,
203,
203,
565,
2874,
12,
2867,
516,
2254,
13,
3849,
1071,
2
] |
./full_match/1/0x4fc253B3d25a0bE792B7E338aa01DDf6aC17d831/sources/contracts/upgradability/OwnedUpgradeabilityProxy.sol | * @title OwnedUpgradeabilityProxy @dev This contract combines an upgradeability proxy with basic authorization control functionalities/ Storage position of the address of the maintenance boolean Storage position of the address of the current implementation Storage position of the owner of the contract | contract OwnedUpgradeabilityProxy {
event ProxyOwnershipTransferred(address previousOwner, address newOwner);
event Upgraded(address indexed implementation);
bytes32 private constant maintenancePosition =
keccak256("com.ibg.proxy.maintenance");
bytes32 private constant implementationPosition =
keccak256("com.ibg.proxy.implementation");
bytes32 private constant proxyOwnerPosition =
keccak256("com.ibg.proxy.owner");
pragma solidity ^0.8.4;
constructor() {
setUpgradeabilityOwner(msg.sender);
}
function maintenance() public view returns (bool _maintenance) {
bytes32 position = maintenancePosition;
assembly {
_maintenance := sload(position)
}
}
function maintenance() public view returns (bool _maintenance) {
bytes32 position = maintenancePosition;
assembly {
_maintenance := sload(position)
}
}
function setMaintenance(bool _maintenance) external onlyProxyOwner {
bytes32 position = maintenancePosition;
assembly {
sstore(position, _maintenance)
}
}
function setMaintenance(bool _maintenance) external onlyProxyOwner {
bytes32 position = maintenancePosition;
assembly {
sstore(position, _maintenance)
}
}
function proxyOwner() public view returns (address owner) {
bytes32 position = proxyOwnerPosition;
assembly {
owner := sload(position)
}
}
function proxyOwner() public view returns (address owner) {
bytes32 position = proxyOwnerPosition;
assembly {
owner := sload(position)
}
}
function setUpgradeabilityOwner(address newProxyOwner) internal {
bytes32 position = proxyOwnerPosition;
assembly {
sstore(position, newProxyOwner)
}
}
function setUpgradeabilityOwner(address newProxyOwner) internal {
bytes32 position = proxyOwnerPosition;
assembly {
sstore(position, newProxyOwner)
}
}
function transferProxyOwnership(address newOwner) public onlyProxyOwner {
require(newOwner != address(0), "OwnedUpgradeabilityProxy: INVALID");
emit ProxyOwnershipTransferred(proxyOwner(), newOwner);
setUpgradeabilityOwner(newOwner);
}
function upgradeTo(address newImplementation) public onlyProxyOwner {
_upgradeTo(newImplementation);
}
function upgradeToAndCall(address newImplementation, bytes memory data)
public
payable
onlyProxyOwner
{
upgradeTo(newImplementation);
require(success, "OwnedUpgradeabilityProxy: INVALID");
}
(bool success, ) = address(this).call{value: msg.value}(data);
fallback() external payable {
_fallback();
}
receive() external payable {
_fallback();
}
function implementation() public view returns (address impl) {
bytes32 position = implementationPosition;
assembly {
impl := sload(position)
}
}
function implementation() public view returns (address impl) {
bytes32 position = implementationPosition;
assembly {
impl := sload(position)
}
}
function setImplementation(address newImplementation) internal {
bytes32 position = implementationPosition;
assembly {
sstore(position, newImplementation)
}
}
function setImplementation(address newImplementation) internal {
bytes32 position = implementationPosition;
assembly {
sstore(position, newImplementation)
}
}
function _upgradeTo(address newImplementation) internal {
address currentImplementation = implementation();
require(
currentImplementation != newImplementation,
"OwnedUpgradeabilityProxy: INVALID"
);
setImplementation(newImplementation);
emit Upgraded(newImplementation);
}
function _fallback() internal {
if (maintenance()) {
require(
msg.sender == proxyOwner(),
"OwnedUpgradeabilityProxy: FORBIDDEN"
);
}
address _impl = implementation();
require(_impl != address(0), "OwnedUpgradeabilityProxy: INVALID");
assembly {
let ptr := mload(0x40)
calldatacopy(ptr, 0, calldatasize())
let result := delegatecall(gas(), _impl, ptr, calldatasize(), 0, 0)
let size := returndatasize()
returndatacopy(ptr, 0, size)
switch result
case 0 {
revert(ptr, size)
}
default {
return(ptr, size)
}
}
}
function _fallback() internal {
if (maintenance()) {
require(
msg.sender == proxyOwner(),
"OwnedUpgradeabilityProxy: FORBIDDEN"
);
}
address _impl = implementation();
require(_impl != address(0), "OwnedUpgradeabilityProxy: INVALID");
assembly {
let ptr := mload(0x40)
calldatacopy(ptr, 0, calldatasize())
let result := delegatecall(gas(), _impl, ptr, calldatasize(), 0, 0)
let size := returndatasize()
returndatacopy(ptr, 0, size)
switch result
case 0 {
revert(ptr, size)
}
default {
return(ptr, size)
}
}
}
function _fallback() internal {
if (maintenance()) {
require(
msg.sender == proxyOwner(),
"OwnedUpgradeabilityProxy: FORBIDDEN"
);
}
address _impl = implementation();
require(_impl != address(0), "OwnedUpgradeabilityProxy: INVALID");
assembly {
let ptr := mload(0x40)
calldatacopy(ptr, 0, calldatasize())
let result := delegatecall(gas(), _impl, ptr, calldatasize(), 0, 0)
let size := returndatasize()
returndatacopy(ptr, 0, size)
switch result
case 0 {
revert(ptr, size)
}
default {
return(ptr, size)
}
}
}
function _fallback() internal {
if (maintenance()) {
require(
msg.sender == proxyOwner(),
"OwnedUpgradeabilityProxy: FORBIDDEN"
);
}
address _impl = implementation();
require(_impl != address(0), "OwnedUpgradeabilityProxy: INVALID");
assembly {
let ptr := mload(0x40)
calldatacopy(ptr, 0, calldatasize())
let result := delegatecall(gas(), _impl, ptr, calldatasize(), 0, 0)
let size := returndatasize()
returndatacopy(ptr, 0, size)
switch result
case 0 {
revert(ptr, size)
}
default {
return(ptr, size)
}
}
}
function _fallback() internal {
if (maintenance()) {
require(
msg.sender == proxyOwner(),
"OwnedUpgradeabilityProxy: FORBIDDEN"
);
}
address _impl = implementation();
require(_impl != address(0), "OwnedUpgradeabilityProxy: INVALID");
assembly {
let ptr := mload(0x40)
calldatacopy(ptr, 0, calldatasize())
let result := delegatecall(gas(), _impl, ptr, calldatasize(), 0, 0)
let size := returndatasize()
returndatacopy(ptr, 0, size)
switch result
case 0 {
revert(ptr, size)
}
default {
return(ptr, size)
}
}
}
modifier onlyProxyOwner() {
require(
msg.sender == proxyOwner(),
"OwnedUpgradeabilityProxy: FORBIDDEN"
);
_;
}
}
| 3,191,418 | [
1,
5460,
329,
10784,
2967,
3886,
225,
1220,
6835,
30933,
392,
8400,
2967,
2889,
598,
5337,
6093,
3325,
18699,
1961,
19,
5235,
1754,
434,
326,
1758,
434,
326,
18388,
1250,
5235,
1754,
434,
326,
1758,
434,
326,
783,
4471,
5235,
1754,
434,
326,
3410,
434,
326,
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
] | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
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,
16351,
14223,
11748,
10784,
2967,
3886,
288,
203,
565,
871,
7659,
5460,
12565,
1429,
4193,
12,
2867,
2416,
5541,
16,
1758,
394,
5541,
1769,
203,
203,
565,
871,
1948,
19305,
12,
2867,
8808,
4471,
1769,
203,
203,
565,
1731,
1578,
3238,
5381,
18388,
2555,
273,
203,
3639,
417,
24410,
581,
5034,
2932,
832,
18,
495,
75,
18,
5656,
18,
29715,
8863,
203,
565,
1731,
1578,
3238,
5381,
4471,
2555,
273,
203,
3639,
417,
24410,
581,
5034,
2932,
832,
18,
495,
75,
18,
5656,
18,
30810,
8863,
203,
565,
1731,
1578,
3238,
5381,
2889,
5541,
2555,
273,
203,
3639,
417,
24410,
581,
5034,
2932,
832,
18,
495,
75,
18,
5656,
18,
8443,
8863,
203,
203,
683,
9454,
18035,
560,
3602,
20,
18,
28,
18,
24,
31,
203,
565,
3885,
1435,
288,
203,
3639,
444,
10784,
2967,
5541,
12,
3576,
18,
15330,
1769,
203,
565,
289,
203,
203,
565,
445,
18388,
1435,
1071,
1476,
1135,
261,
6430,
389,
29715,
13,
288,
203,
3639,
1731,
1578,
1754,
273,
18388,
2555,
31,
203,
3639,
19931,
288,
203,
5411,
389,
29715,
519,
272,
945,
12,
3276,
13,
203,
3639,
289,
203,
565,
289,
203,
203,
565,
445,
18388,
1435,
1071,
1476,
1135,
261,
6430,
389,
29715,
13,
288,
203,
3639,
1731,
1578,
1754,
273,
18388,
2555,
31,
203,
3639,
19931,
288,
203,
5411,
389,
29715,
519,
272,
945,
12,
3276,
13,
203,
3639,
289,
203,
565,
289,
203,
203,
565,
445,
444,
11045,
12,
6430,
389,
29715,
13,
3903,
1338,
3886,
5541,
288,
203,
3639,
1731,
1578,
1754,
273,
2
] |
pragma solidity ^0.4.23;
import 'openzeppelin-solidity/contracts/token/ERC20/ERC20.sol';
import 'openzeppelin-solidity/contracts/ownership/Ownable.sol';
import 'openzeppelin-solidity/contracts/math/SafeMath.sol';
import 'evolutionerc223/contracts/ERC223ReceivingContract.sol';
contract TokenVendor is Ownable{
using SafeMath for uint256;
ERC20 public token;
uint256 public buyTokenRate;
uint256 public sellTokenRate; // sellTokenRate = buyTokenRate * 11 /10
uint256 public totalBuyTokenTransfered;
uint256 public totalBuyEtherCollected;
uint256 public totalSellEthTransfered;
uint256 public totalSellTokenCollected;
constructor(address _token) public {
token = ERC20(_token);
buyTokenRate = 30000;
sellTokenRate = 33000;
}
/// @notice If anybody sends Ether directly to this contract, consider he is
/// getting tokens.
function () public payable {
buyToken(msg.sender);
}
function tokenFallback(address _from, uint256 _value, bytes _data) public{
require(msg.sender == address(token));
sellToken(_from, _value);
}
function buyToken(address _th) public payable returns (bool) {
require(_th != 0x0);
require(msg.value > 0);
uint256 _toFund = msg.value;
uint256 tokensGenerating = _toFund.mul(buyTokenRate);
if (tokensGenerating > token.balanceOf(this)) {
tokensGenerating = token.balanceOf(this);
_toFund = token.balanceOf(this).div(buyTokenRate);
}
require(token.transfer(_th, tokensGenerating));
// DONE: Add statistics:
totalBuyTokenTransfered = totalBuyTokenTransfered.add(tokensGenerating);
// DONE: Add statistics:
totalBuyEtherCollected = totalBuyEtherCollected.add(_toFund);
emit NewBuy(_th, _toFund, tokensGenerating);
uint256 toReturn = msg.value.sub(_toFund);
if (toReturn > 0) {
_th.transfer(toReturn);
}
return true;
}
function sellToken(address _th, uint256 _value) public returns (bool) {
require(_th != 0x0);
require(_value > 0);
uint256 _toFund = _value;
uint256 ethGenerating = _toFund.div(sellTokenRate);
if (ethGenerating > address(this).balance) {
ethGenerating = address(this).balance;
_toFund = address(this).balance.mul(sellTokenRate);
}
_th.transfer(ethGenerating);
// DONE: Statistics.
totalSellEthTransfered = totalSellEthTransfered.add(ethGenerating);
totalSellTokenCollected = totalSellTokenCollected.add(_toFund);
emit NewSell(_th, _value, ethGenerating);
uint256 toReturn = _value.sub(_toFund);
if (toReturn > 0) {
require(token.transfer(_th, toReturn));
}
return true;
}
// Recommended OP: buyTokenRate will be changed once a day.
// There is a limit of price change, that is, no more than +/- 10 percentage compared to the day before.
// If the token in yesterday consuming to fast, then token price should go higher
// Otherwise, token price should go lower, sell pricate should be changed accordingly
function changeBuyTokenRate(uint256 _newBuyTokenRate) public onlyOwner {
require(_newBuyTokenRate > 0);
emit BuyRateChanged(buyTokenRate, _newBuyTokenRate);
buyTokenRate = _newBuyTokenRate;
}
function changeSellTokenRate(uint256 _newSellTokenRate) public onlyOwner {
require(_newSellTokenRate > 0);
emit SellRateChanged(sellTokenRate, _newSellTokenRate);
sellTokenRate = _newSellTokenRate;
}
function claimTokens(address _token) public onlyOwner {
if (_token == 0x0) {
owner.transfer(address(this).balance);
return;
}
ERC20 claimToken = ERC20(_token);
uint balance = claimToken.balanceOf(this);
claimToken.transfer(owner, balance);
emit ClaimedTokens(_token, owner, balance);
}
event ClaimedTokens(address indexed _token, address indexed _controller, uint _amount);
event BuyRateChanged(uint256 previousBuyRate, uint256 newBuyRate);
event SellRateChanged(uint256 previousSellRate, uint256 newSellRate);
event NewBuy(address indexed _th, uint256 _amount, uint256 _tokens);
event NewSell(address indexed _th, uint256 _amount, uint256 _weis);
} | @notice If anybody sends Ether directly to this contract, consider he is getting tokens. | function () public payable {
buyToken(msg.sender);
}
| 1,087,193 | [
1,
2047,
1281,
3432,
9573,
512,
1136,
5122,
358,
333,
6835,
16,
5260,
3904,
353,
225,
8742,
2430,
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
] | [
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,
0,
0
] | [
1,
565,
445,
1832,
1071,
8843,
429,
288,
203,
3639,
30143,
1345,
12,
3576,
18,
15330,
1769,
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
] |
/**
*Submitted for verification at Etherscan.io on 2021-04-05
*/
pragma solidity ^0.5.2;
/**
* @title Ownable
* @dev The Ownable contract has an owner address, and provides basic authorization control
* functions, this simplifies the implementation of "user permissions".
*/
contract Ownable {
address private _owner;
event OwnershipTransferred(address indexed previousOwner, address indexed newOwner);
/**
* @dev The Ownable constructor sets the original `owner` of the contract to the sender
* account.
*/
constructor () internal {
_owner = msg.sender;
emit OwnershipTransferred(address(0), _owner);
}
/**
* @return the address of the owner.
*/
function owner() public view returns (address) {
return _owner;
}
/**
* @dev Throws if called by any account other than the owner.
*/
modifier onlyOwner() {
require(isOwner());
_;
}
/**
* @return true if `msg.sender` is the owner of the contract.
*/
function isOwner() public view returns (bool) {
return msg.sender == _owner;
}
/**
* @dev Allows the current owner to relinquish control of the contract.
* It will not be possible to call the functions with the `onlyOwner`
* modifier anymore.
* @notice Renouncing ownership will leave the contract without an owner,
* thereby removing any functionality that is only available to the owner.
*/
function renounceOwnership() public onlyOwner {
emit OwnershipTransferred(_owner, address(0));
_owner = address(0);
}
/**
* @dev Allows the current owner to transfer control of the contract to a newOwner.
* @param newOwner The address to transfer ownership to.
*/
function transferOwnership(address newOwner) public onlyOwner {
_transferOwnership(newOwner);
}
/**
* @dev Transfers control of the contract to a newOwner.
* @param newOwner The address to transfer ownership to.
*/
function _transferOwnership(address newOwner) internal {
require(newOwner != address(0));
emit OwnershipTransferred(_owner, newOwner);
_owner = newOwner;
}
}
/**
* @title Roles
* @dev Library for managing addresses assigned to a Role.
*/
library Roles {
struct Role {
mapping (address => bool) bearer;
}
/**
* @dev give an account access to this role
*/
function add(Role storage role, address account) internal {
require(account != address(0));
require(!has(role, account));
role.bearer[account] = true;
}
/**
* @dev remove an account's access to this role
*/
function remove(Role storage role, address account) internal {
require(account != address(0));
require(has(role, account));
role.bearer[account] = false;
}
/**
* @dev check if an account has this role
* @return bool
*/
function has(Role storage role, address account) internal view returns (bool) {
require(account != address(0));
return role.bearer[account];
}
}
contract MinterRole {
using Roles for Roles.Role;
event MinterAdded(address indexed account);
event MinterRemoved(address indexed account);
Roles.Role private _minters;
constructor () internal {
_addMinter(msg.sender);
}
modifier onlyMinter() {
require(isMinter(msg.sender));
_;
}
function isMinter(address account) public view returns (bool) {
return _minters.has(account);
}
function addMinter(address account) public onlyMinter {
_addMinter(account);
}
function renounceMinter() public {
_removeMinter(msg.sender);
}
function _addMinter(address account) internal {
_minters.add(account);
emit MinterAdded(account);
}
function _removeMinter(address account) internal {
_minters.remove(account);
emit MinterRemoved(account);
}
}
contract PauserRole {
using Roles for Roles.Role;
event PauserAdded(address indexed account);
event PauserRemoved(address indexed account);
Roles.Role private _pausers;
constructor () internal {
_addPauser(msg.sender);
}
modifier onlyPauser() {
require(isPauser(msg.sender));
_;
}
function isPauser(address account) public view returns (bool) {
return _pausers.has(account);
}
function addPauser(address account) public onlyPauser {
_addPauser(account);
}
function renouncePauser() public {
_removePauser(msg.sender);
}
function _addPauser(address account) internal {
_pausers.add(account);
emit PauserAdded(account);
}
function _removePauser(address account) internal {
_pausers.remove(account);
emit PauserRemoved(account);
}
}
/**
* @title Pausable
* @dev Base contract which allows children to implement an emergency stop mechanism.
*/
contract Pausable is PauserRole {
event Paused(address account);
event Unpaused(address account);
bool private _paused;
constructor () internal {
_paused = false;
}
/**
* @return true if the contract is paused, false otherwise.
*/
function paused() public view returns (bool) {
return _paused;
}
/**
* @dev Modifier to make a function callable only when the contract is not paused.
*/
modifier whenNotPaused() {
require(!_paused);
_;
}
/**
* @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() public onlyPauser whenNotPaused {
_paused = true;
emit Paused(msg.sender);
}
/**
* @dev called by the owner to unpause, returns to normal state
*/
function unpause() public onlyPauser whenPaused {
_paused = false;
emit Unpaused(msg.sender);
}
}
/**
* @title SafeMath
* @dev Unsigned math operations with safety checks that revert on error
*/
library SafeMath {
/**
* @dev Multiplies two unsigned integers, reverts on overflow.
*/
function mul(uint256 a, uint256 b) internal pure returns (uint256) {
// Gas optimization: this is cheaper than requiring 'a' not being zero, but the
// benefit is lost if 'b' is also tested.
// See: https://github.com/OpenZeppelin/openzeppelin-solidity/pull/522
if (a == 0) {
return 0;
}
uint256 c = a * b;
require(c / a == b);
return c;
}
/**
* @dev Integer division of two unsigned integers truncating the quotient, reverts on division by zero.
*/
function div(uint256 a, uint256 b) internal pure returns (uint256) {
// Solidity only automatically asserts when dividing by 0
require(b > 0);
uint256 c = a / b;
// assert(a == b * c + a % b); // There is no case in which this doesn't hold
return c;
}
/**
* @dev Subtracts two unsigned integers, reverts on overflow (i.e. if subtrahend is greater than minuend).
*/
function sub(uint256 a, uint256 b) internal pure returns (uint256) {
require(b <= a);
uint256 c = a - b;
return c;
}
/**
* @dev Adds two unsigned integers, reverts on overflow.
*/
function add(uint256 a, uint256 b) internal pure returns (uint256) {
uint256 c = a + b;
require(c >= a);
return c;
}
/**
* @dev Divides two unsigned integers and returns the remainder (unsigned integer modulo),
* reverts when dividing by zero.
*/
function mod(uint256 a, uint256 b) internal pure returns (uint256) {
require(b != 0);
return a % b;
}
}
/**
* @title ERC20 interface
* @dev see https://eips.ethereum.org/EIPS/eip-20
*/
interface IERC20 {
function transfer(address to, uint256 value) external returns (bool);
function approve(address spender, uint256 value) external returns (bool);
function transferFrom(address from, address to, uint256 value) external returns (bool);
function totalSupply() external view returns (uint256);
function balanceOf(address who) external view returns (uint256);
function allowance(address owner, address spender) external view returns (uint256);
event Transfer(address indexed from, address indexed to, uint256 value);
event Approval(address indexed owner, address indexed spender, uint256 value);
}
/**
* @title Standard ERC20 token
*
* @dev Implementation of the basic standard token.
* https://eips.ethereum.org/EIPS/eip-20
* Originally based on code by FirstBlood:
* https://github.com/Firstbloodio/token/blob/master/smart_contract/FirstBloodToken.sol
*
* This implementation emits additional Approval events, allowing applications to reconstruct the allowance status for
* all accounts just by listening to said events. Note that this isn't required by the specification, and other
* compliant implementations may not do it.
*/
contract ERC20 is IERC20 {
using SafeMath for uint256;
mapping (address => uint256) private _balances;
mapping (address => mapping (address => uint256)) private _allowed;
uint256 private _totalSupply;
// map for lock
mapping (address => uint) public lockedAccount;
// event for lock
event Lock(address target, uint amount);
event UnLock(address target, uint amount);
/**
* @dev Total number of tokens in existence
*/
function totalSupply() public view returns (uint256) {
return _totalSupply;
}
/**
* @dev Gets the balance of the specified address.
* @param owner The address to query the balance of.
* @return A uint256 representing the amount owned by the passed address.
*/
function balanceOf(address owner) public view returns (uint256) {
return _balances[owner];
}
/**
* @dev Function to check the amount of tokens that an owner allowed to a spender.
* @param owner address The address which owns the funds.
* @param spender address The address which will spend the funds.
* @return A uint256 specifying the amount of tokens still available for the spender.
*/
function allowance(address owner, address spender) public view returns (uint256) {
return _allowed[owner][spender];
}
/**
* @dev Transfer token to a specified address
* @param to The address to transfer to.
* @param value The amount to be transferred.
*/
function transfer(address to, uint256 value) public returns (bool) {
_transfer(msg.sender, to, value);
return true;
}
/**
* @dev Approve the passed address to spend the specified amount of tokens on behalf of msg.sender.
* Beware that changing an allowance with this method brings the risk that someone may use both the old
* and the new allowance by unfortunate transaction ordering. One possible solution to mitigate this
* race condition is to first reduce the spender's allowance to 0 and set the desired value afterwards:
* https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729
* @param spender The address which will spend the funds.
* @param value The amount of tokens to be spent.
*/
function approve(address spender, uint256 value) public returns (bool) {
_approve(msg.sender, spender, value);
return true;
}
/**
* @dev Transfer tokens from one address to another.
* Note that while this function emits an Approval event, this is not required as per the specification,
* and other compliant implementations may not emit the event.
* @param from address The address which you want to send tokens from
* @param to address The address which you want to transfer to
* @param value uint256 the amount of tokens to be transferred
*/
function transferFrom(address from, address to, uint256 value) public returns (bool) {
_transfer(from, to, value);
_approve(from, msg.sender, _allowed[from][msg.sender].sub(value));
return true;
}
/**
* @dev Increase the amount of tokens that an owner allowed to a spender.
* approve should be called when _allowed[msg.sender][spender] == 0. To increment
* allowed value is better to use this function to avoid 2 calls (and wait until
* the first transaction is mined)
* From MonolithDAO Token.sol
* Emits an Approval event.
* @param spender The address which will spend the funds.
* @param addedValue The amount of tokens to increase the allowance by.
*/
function increaseAllowance(address spender, uint256 addedValue) public returns (bool) {
_approve(msg.sender, spender, _allowed[msg.sender][spender].add(addedValue));
return true;
}
/**
* @dev Decrease the amount of tokens that an owner allowed to a spender.
* approve should be called when _allowed[msg.sender][spender] == 0. To decrement
* allowed value is better to use this function to avoid 2 calls (and wait until
* the first transaction is mined)
* From MonolithDAO Token.sol
* Emits an Approval event.
* @param spender The address which will spend the funds.
* @param subtractedValue The amount of tokens to decrease the allowance by.
*/
function decreaseAllowance(address spender, uint256 subtractedValue) public returns (bool) {
_approve(msg.sender, spender, _allowed[msg.sender][spender].sub(subtractedValue));
return true;
}
/**
* @dev Function to lock tokens of address
* @param amount The amount of tokens that is locked.
*/
function lockAccount(uint amount) public returns (bool) {
_lockAccount(msg.sender, amount);
return true;
}
/**
* @dev Function to unlock tokens of address
* @param amount The amount of tokens that is unlocked.
*/
function unLockAccount(uint amount) public returns (bool) {
_unLockAccount(msg.sender, amount);
return true;
}
/**
* @dev Transfer token for a specified addresses
* @param from The address to transfer from.
* @param to The address to transfer to.
* @param value The amount to be transferred.
*/
function _transfer(address from, address to, uint256 value) internal {
require(to != address(0));
_balances[from] = _balances[from].sub(value);
_balances[to] = _balances[to].add(value);
emit Transfer(from, to, value);
}
/**
* @dev Internal function that mints an amount of the token and assigns it to
* an account. This encapsulates the modification of balances such that the
* proper events are emitted.
* @param account The account that will receive the created tokens.
* @param value The amount that will be created.
*/
function _mint(address account, uint256 value) internal {
require(account != address(0));
_totalSupply = _totalSupply.add(value);
_balances[account] = _balances[account].add(value);
emit Transfer(address(0), account, value);
}
/**
* @dev Internal function that burns an amount of the token of a given
* account.
* @param account The account whose tokens will be burnt.
* @param value The amount that will be burnt.
*/
function _burn(address account, uint256 value) internal {
require(account != address(0));
_totalSupply = _totalSupply.sub(value);
_balances[account] = _balances[account].sub(value);
emit Transfer(account, address(0), value);
}
/**
* @dev Approve an address to spend another addresses' tokens.
* @param owner The address that owns the tokens.
* @param spender The address that will spend the tokens.
* @param value The number of tokens that can be spent.
*/
function _approve(address owner, address spender, uint256 value) internal {
require(spender != address(0));
require(owner != address(0));
_allowed[owner][spender] = value;
emit Approval(owner, spender, value);
}
/**
* @dev Internal function that burns an amount of the token of a given
* account, deducting from the sender's allowance for said account. Uses the
* internal burn function.
* Emits an Approval event (reflecting the reduced allowance).
* @param account The account whose tokens will be burnt.
* @param value The amount that will be burnt.
*/
function _burnFrom(address account, uint256 value) internal {
_burn(account, value);
_approve(account, msg.sender, _allowed[account][msg.sender].sub(value));
}
/**
* @dev Function to lock tokens of address
* @param amount The amount of tokens that is locked.
*/
function _lockAccount(address account, uint amount) public returns (bool) {
require(account != address(0));
require(_balances[account] >= amount);
_balances[account] = _balances[account].sub(amount);
lockedAccount[account] = lockedAccount[account].add(amount);
emit Lock(account, lockedAccount[account]);
return true;
}
/**
* @dev Function to unlock tokens of address
* @param amount The amount of tokens that is unlocked.
*/
function _unLockAccount(address account, uint amount) public returns (bool) {
require(account != address(0));
require(lockedAccount[account] >= amount);
lockedAccount[account] = lockedAccount[account].sub(amount);
_balances[account] = _balances[account].add(amount);
emit UnLock(account, lockedAccount[account]);
return true;
}
}
/**
* @title Burnable Token
* @dev Token that can be irreversibly burned (destroyed).
*/
contract ERC20Burnable is ERC20 {
/**
* @dev Burns a specific amount of tokens.
* @param value The amount of token to be burned.
*/
function burn(uint256 value) public {
_burn(msg.sender, value);
}
/**
* @dev Burns a specific amount of tokens from the target address and decrements allowance
* @param from address The account whose tokens will be burned.
* @param value uint256 The amount of token to be burned.
*/
function burnFrom(address from, uint256 value) public {
_burnFrom(from, value);
}
}
/**
* @title ERC20Mintable
* @dev ERC20 minting logic
*/
contract ERC20Mintable is ERC20, MinterRole {
/**
* @dev Function to mint tokens
* @param to The address that will receive the minted tokens.
* @param value The amount of tokens to mint.
* @return A boolean that indicates if the operation was successful.
*/
function mint(address to, uint256 value) public onlyMinter returns (bool) {
_mint(to, value);
return true;
}
}
/**
* @title Pausable token
* @dev ERC20 modified with pausable transfers.
*/
contract ERC20Pausable is ERC20, 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 increaseAllowance(address spender, uint addedValue) public whenNotPaused returns (bool success) {
return super.increaseAllowance(spender, addedValue);
}
function decreaseAllowance(address spender, uint subtractedValue) public whenNotPaused returns (bool success) {
return super.decreaseAllowance(spender, subtractedValue);
}
}
/**
* @title LKO token
*
* @dev Implementation of the LKO token
*/
contract LKO is Ownable, ERC20Burnable, ERC20Mintable, ERC20Pausable {
string public name = "LKO";
string public symbol = "LKO";
uint8 public decimals = 18;
uint public INITIAL_SUPPLY = 3000000000000000000000000000;
// map for freeze
mapping (address => bool) public frozenAccount;
// event for freeze
event Freeze(address target);
event UnFreeze(address target);
/**
* @dev constructor for LKO
*/
constructor() public {
_mint(msg.sender, INITIAL_SUPPLY);
}
/**
* @dev fallback function ***DO NOT OVERRIDE***
*/
function () external payable {
revert();
}
/**
* @dev Function to freeze address
* @param _target The address that will be freezed.
*/
function freezeAccount(address _target) onlyOwner public {
require(_target != address(0));
require(frozenAccount[_target] != true);
frozenAccount[_target] = true;
emit Freeze(_target);
}
/**
* @dev Function to unfreeze address
* @param _target The address that will be unfreezed.
*/
function unFreezeAccount(address _target) onlyOwner public {
require(_target != address(0));
require(frozenAccount[_target] != false);
frozenAccount[_target] = false;
emit UnFreeze(_target);
}
/**
* @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(!frozenAccount[msg.sender]); // Check if sender is frozen
require(!frozenAccount[_to]); // Check if recipient is frozen
return super.transfer(_to,_value);
}
/**
* @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(!frozenAccount[msg.sender]); // Check if approved is frozen
require(!frozenAccount[_from]); // Check if sender is frozen
require(!frozenAccount[_to]); // Check if recipient is frozen
return super.transferFrom(_from, _to, _value);
}
} | * @dev Function to lock tokens of address @param amount The amount of tokens that is locked./ | function _lockAccount(address account, uint amount) public returns (bool) {
require(account != address(0));
require(_balances[account] >= amount);
_balances[account] = _balances[account].sub(amount);
lockedAccount[account] = lockedAccount[account].add(amount);
emit Lock(account, lockedAccount[account]);
return true;
}
| 10,597,842 | [
1,
2083,
358,
2176,
2430,
434,
1758,
225,
3844,
1021,
3844,
434,
2430,
716,
353,
8586,
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
] | [
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,
0,
0,
0
] | [
1,
565,
445,
389,
739,
3032,
12,
2867,
2236,
16,
2254,
3844,
13,
1071,
1135,
261,
6430,
13,
288,
203,
3639,
2583,
12,
4631,
480,
1758,
12,
20,
10019,
203,
3639,
2583,
24899,
70,
26488,
63,
4631,
65,
1545,
3844,
1769,
203,
3639,
389,
70,
26488,
63,
4631,
65,
273,
389,
70,
26488,
63,
4631,
8009,
1717,
12,
8949,
1769,
203,
3639,
8586,
3032,
63,
4631,
65,
273,
8586,
3032,
63,
4631,
8009,
1289,
12,
8949,
1769,
203,
3639,
3626,
3488,
12,
4631,
16,
8586,
3032,
63,
4631,
19226,
203,
203,
3639,
327,
638,
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
] |
./full_match/11155111/0x3703F4412Fa17BA5FCd301B2b731a7969f1fc7A6/sources/contracts/TransparentCharity.sol | Function to create an account for a donor | function createDonorAccount(string memory _name) external {
require(donors[msg.sender].balance == 0, "Account already exists.");
donors[msg.sender].Address = payable(msg.sender);
donors[msg.sender].balance = payable(msg.sender).balance;
donors[msg.sender].name = _name;
donorAddresses.push(msg.sender);
}
| 3,797,222 | [
1,
2083,
358,
752,
392,
2236,
364,
279,
2727,
280,
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,
445,
752,
22293,
280,
3032,
12,
1080,
3778,
389,
529,
13,
3903,
288,
203,
3639,
2583,
12,
19752,
1383,
63,
3576,
18,
15330,
8009,
12296,
422,
374,
16,
315,
3032,
1818,
1704,
1199,
1769,
203,
3639,
2727,
1383,
63,
3576,
18,
15330,
8009,
1887,
273,
8843,
429,
12,
3576,
18,
15330,
1769,
203,
3639,
2727,
1383,
63,
3576,
18,
15330,
8009,
12296,
273,
8843,
429,
12,
3576,
18,
15330,
2934,
12296,
31,
203,
3639,
2727,
1383,
63,
3576,
18,
15330,
8009,
529,
273,
389,
529,
31,
203,
3639,
2727,
280,
7148,
18,
6206,
12,
3576,
18,
15330,
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
] |
pragma solidity 0.5.8;
// File: node_modules\openzeppelin-solidity\contracts\token\ERC20\IERC20.sol
interface IERC20 {
function TOTALSUPPLY82() external view returns (uint256); //inject NONSTANDARD NAMING
function BALANCEOF530(address account) external view returns (uint256); //inject NONSTANDARD NAMING
function TRANSFER438(address recipient, uint256 amount) external returns (bool); //inject NONSTANDARD NAMING
function ALLOWANCE833(address owner, address spender) external view returns (uint256); //inject NONSTANDARD NAMING
function APPROVE538(address spender, uint256 amount) external returns (bool); //inject NONSTANDARD NAMING
function TRANSFERFROM818(address sender, address recipient, uint256 amount) external returns (bool); //inject NONSTANDARD NAMING
event TRANSFER722(address indexed from, address indexed to, uint256 value); //inject NONSTANDARD NAMING
event APPROVAL422(address indexed owner, address indexed spender, uint256 value); //inject NONSTANDARD NAMING
}
// File: node_modules\openzeppelin-solidity\contracts\math\SafeMath.sol
library SafeMath {
function ADD23(uint256 a, uint256 b) internal pure returns (uint256) { //inject NONSTANDARD NAMING
uint256 c = a + b;
require(c >= a, "SafeMath: addition overflow");
return c;
}
function SUB764(uint256 a, uint256 b) internal pure returns (uint256) { //inject NONSTANDARD NAMING
require(b <= a, "SafeMath: subtraction overflow");
uint256 c = a - b;
return c;
}
function MUL177(uint256 a, uint256 b) internal pure returns (uint256) { //inject NONSTANDARD NAMING
// Gas optimization: this is cheaper than requiring 'a' not being zero, but the
// benefit is lost if 'b' is also tested.
// See: https://github.com/OpenZeppelin/openzeppelin-solidity/pull/522
if (a == 0) {
return 0;
}
uint256 c = a * b;
require(c / a == b, "SafeMath: multiplication overflow");
return c;
}
function DIV24(uint256 a, uint256 b) internal pure returns (uint256) { //inject NONSTANDARD NAMING
// Solidity only automatically asserts when dividing by 0
require(b > 0, "SafeMath: division by zero");
uint256 c = a / b;
// assert(a == b * c + a % b); // There is no case in which this doesn't hold
return c;
}
function MOD404(uint256 a, uint256 b) internal pure returns (uint256) { //inject NONSTANDARD NAMING
require(b != 0, "SafeMath: modulo by zero");
return a % b;
}
}
// File: node_modules\openzeppelin-solidity\contracts\token\ERC20\ERC20.sol
contract ERC20 is IERC20 {
using SafeMath for uint256;
mapping (address => uint256) internal _balances;
mapping (address => mapping (address => uint256)) private _allowances;
uint256 private _totalSupply;
function TOTALSUPPLY82() public view returns (uint256) { //inject NONSTANDARD NAMING
return _totalSupply;
}
function BALANCEOF530(address account) public view returns (uint256) { //inject NONSTANDARD NAMING
return _balances[account];
}
function TRANSFER438(address recipient, uint256 amount) public returns (bool) { //inject NONSTANDARD NAMING
_TRANSFER27(msg.sender, recipient, amount);
return true;
}
function ALLOWANCE833(address owner, address spender) public view returns (uint256) { //inject NONSTANDARD NAMING
return _allowances[owner][spender];
}
function APPROVE538(address spender, uint256 value) public returns (bool) { //inject NONSTANDARD NAMING
_APPROVE258(msg.sender, spender, value);
return true;
}
function TRANSFERFROM818(address sender, address recipient, uint256 amount) public returns (bool) { //inject NONSTANDARD NAMING
_TRANSFER27(sender, recipient, amount);
_APPROVE258(sender, msg.sender, _allowances[sender][msg.sender].SUB764(amount));
return true;
}
function INCREASEALLOWANCE45(address spender, uint256 addedValue) public returns (bool) { //inject NONSTANDARD NAMING
_APPROVE258(msg.sender, spender, _allowances[msg.sender][spender].ADD23(addedValue));
return true;
}
function DECREASEALLOWANCE159(address spender, uint256 subtractedValue) public returns (bool) { //inject NONSTANDARD NAMING
_APPROVE258(msg.sender, spender, _allowances[msg.sender][spender].SUB764(subtractedValue));
return true;
}
function _TRANSFER27(address sender, address recipient, uint256 amount) internal { //inject NONSTANDARD NAMING
require(sender != address(0), "ERC20: transfer from the zero address");
require(recipient != address(0), "ERC20: transfer to the zero address");
_balances[sender] = _balances[sender].SUB764(amount);
_balances[recipient] = _balances[recipient].ADD23(amount);
emit TRANSFER722(sender, recipient, amount);
}
function _MINT102(address account, uint256 amount) internal { //inject NONSTANDARD NAMING
require(account != address(0), "ERC20: mint to the zero address");
_totalSupply = _totalSupply.ADD23(amount);
_balances[account] = _balances[account].ADD23(amount);
emit TRANSFER722(address(0), account, amount);
}
function _BURN692(address account, uint256 value) internal { //inject NONSTANDARD NAMING
require(account != address(0), "ERC20: burn from the zero address");
_totalSupply = _totalSupply.SUB764(value);
_balances[account] = _balances[account].SUB764(value);
emit TRANSFER722(account, address(0), value);
}
function _APPROVE258(address owner, address spender, uint256 value) internal { //inject NONSTANDARD NAMING
require(owner != address(0), "ERC20: approve from the zero address");
require(spender != address(0), "ERC20: approve to the zero address");
_allowances[owner][spender] = value;
emit APPROVAL422(owner, spender, value);
}
function _BURNFROM631(address account, uint256 amount) internal { //inject NONSTANDARD NAMING
_BURN692(account, amount);
_APPROVE258(account, msg.sender, _allowances[account][msg.sender].SUB764(amount));
}
}
// File: J\contracts\Goodluck(LUCK).sol
contract Goodluck is ERC20 {
string public constant name423 = "Goodluck"; //inject NONSTANDARD NAMING
string public constant symbol470 = "LUCK"; //inject NONSTANDARD NAMING
uint8 public constant decimals728 = 18; //inject NONSTANDARD NAMING
uint256 public constant initialsupply595 = 2000000000 * (10 ** uint256(decimals728)); //inject NONSTANDARD NAMING
constructor() public {
super._MINT102(msg.sender, initialsupply595);
owner = msg.sender;
}
//ownership
address public owner;
event OWNERSHIPRENOUNCED774(address indexed previousOwner); //inject NONSTANDARD NAMING
event OWNERSHIPTRANSFERRED463( //inject NONSTANDARD NAMING
address indexed previousOwner,
address indexed newOwner
);
modifier ONLYOWNER394() { //inject NONSTANDARD NAMING
require(msg.sender == owner, "Not owner");
_;
}
function RENOUNCEOWNERSHIP445() public ONLYOWNER394 { //inject NONSTANDARD NAMING
emit OWNERSHIPRENOUNCED774(owner);
owner = address(0);
}
function TRANSFEROWNERSHIP781(address _newOwner) public ONLYOWNER394 { //inject NONSTANDARD NAMING
_TRANSFEROWNERSHIP16(_newOwner);
}
function _TRANSFEROWNERSHIP16(address _newOwner) internal { //inject NONSTANDARD NAMING
require(_newOwner != address(0), "Already owner");
emit OWNERSHIPTRANSFERRED463(owner, _newOwner);
owner = _newOwner;
}
//pausable
event PAUSE475(); //inject NONSTANDARD NAMING
event UNPAUSE568(); //inject NONSTANDARD NAMING
bool public paused = false;
modifier WHENNOTPAUSED995() { //inject NONSTANDARD NAMING
require(!paused, "Paused by owner");
_;
}
modifier WHENPAUSED712() { //inject NONSTANDARD NAMING
require(paused, "Not paused now");
_;
}
function PAUSE841() public ONLYOWNER394 WHENNOTPAUSED995 { //inject NONSTANDARD NAMING
paused = true;
emit PAUSE475();
}
function UNPAUSE13() public ONLYOWNER394 WHENPAUSED712 { //inject NONSTANDARD NAMING
paused = false;
emit UNPAUSE568();
}
//freezable
event FROZEN932(address target); //inject NONSTANDARD NAMING
event UNFROZEN285(address target); //inject NONSTANDARD NAMING
mapping(address => bool) internal freezes;
modifier WHENNOTFROZEN284() { //inject NONSTANDARD NAMING
require(!freezes[msg.sender], "Sender account is locked.");
_;
}
function FREEZE724(address _target) public ONLYOWNER394 { //inject NONSTANDARD NAMING
freezes[_target] = true;
emit FROZEN932(_target);
}
function UNFREEZE196(address _target) public ONLYOWNER394 { //inject NONSTANDARD NAMING
freezes[_target] = false;
emit UNFROZEN285(_target);
}
function ISFROZEN713(address _target) public view returns (bool) { //inject NONSTANDARD NAMING
return freezes[_target];
}
function TRANSFER438( //inject NONSTANDARD NAMING
address _to,
uint256 _value
)
public
WHENNOTFROZEN284
WHENNOTPAUSED995
returns (bool)
{
RELEASELOCK766(msg.sender);
return super.TRANSFER438(_to, _value);
}
function TRANSFERFROM818( //inject NONSTANDARD NAMING
address _from,
address _to,
uint256 _value
)
public
WHENNOTPAUSED995
returns (bool)
{
require(!freezes[_from], "From account is locked.");
RELEASELOCK766(_from);
return super.TRANSFERFROM818(_from, _to, _value);
}
//mintable
event MINT926(address indexed to, uint256 amount); //inject NONSTANDARD NAMING
function MINT957( //inject NONSTANDARD NAMING
address _to,
uint256 _amount
)
public
ONLYOWNER394
returns (bool)
{
super._MINT102(_to, _amount);
emit MINT926(_to, _amount);
return true;
}
//burnable
event BURN684(address indexed burner, uint256 value); //inject NONSTANDARD NAMING
function BURN342(address _who, uint256 _value) public ONLYOWNER394 { //inject NONSTANDARD NAMING
require(_value <= super.BALANCEOF530(_who), "Balance is too small.");
_BURN692(_who, _value);
emit BURN684(_who, _value);
}
//lockable
struct LockInfo {
uint256 releaseTime;
uint256 balance;
}
mapping(address => LockInfo[]) internal lockInfo;
event LOCK205(address indexed holder, uint256 value, uint256 releaseTime); //inject NONSTANDARD NAMING
event UNLOCK375(address indexed holder, uint256 value); //inject NONSTANDARD NAMING
function BALANCEOF530(address _holder) public view returns (uint256 balance) { //inject NONSTANDARD NAMING
uint256 lockedBalance = 0;
for(uint256 i = 0; i < lockInfo[_holder].length ; i++ ) {
lockedBalance = lockedBalance.ADD23(lockInfo[_holder][i].balance);
}
return super.BALANCEOF530(_holder).ADD23(lockedBalance);
}
function RELEASELOCK766(address _holder) internal { //inject NONSTANDARD NAMING
for(uint256 i = 0; i < lockInfo[_holder].length ; i++ ) {
if (lockInfo[_holder][i].releaseTime <= now) {
_balances[_holder] = _balances[_holder].ADD23(lockInfo[_holder][i].balance);
emit UNLOCK375(_holder, lockInfo[_holder][i].balance);
lockInfo[_holder][i].balance = 0;
if (i != lockInfo[_holder].length - 1) {
lockInfo[_holder][i] = lockInfo[_holder][lockInfo[_holder].length - 1];
i--;
}
lockInfo[_holder].length--;
}
}
}
function LOCKCOUNT904(address _holder) public view returns (uint256) { //inject NONSTANDARD NAMING
return lockInfo[_holder].length;
}
function LOCKSTATE154(address _holder, uint256 _idx) public view returns (uint256, uint256) { //inject NONSTANDARD NAMING
return (lockInfo[_holder][_idx].releaseTime, lockInfo[_holder][_idx].balance);
}
function LOCK109(address _holder, uint256 _amount, uint256 _releaseTime) public ONLYOWNER394 { //inject NONSTANDARD NAMING
require(super.BALANCEOF530(_holder) >= _amount, "Balance is too small.");
_balances[_holder] = _balances[_holder].SUB764(_amount);
lockInfo[_holder].push(
LockInfo(_releaseTime, _amount)
);
emit LOCK205(_holder, _amount, _releaseTime);
}
function LOCKAFTER210(address _holder, uint256 _amount, uint256 _afterTime) public ONLYOWNER394 { //inject NONSTANDARD NAMING
require(super.BALANCEOF530(_holder) >= _amount, "Balance is too small.");
_balances[_holder] = _balances[_holder].SUB764(_amount);
lockInfo[_holder].push(
LockInfo(now + _afterTime, _amount)
);
emit LOCK205(_holder, _amount, now + _afterTime);
}
function UNLOCK592(address _holder, uint256 i) public ONLYOWNER394 { //inject NONSTANDARD NAMING
require(i < lockInfo[_holder].length, "No lock information.");
_balances[_holder] = _balances[_holder].ADD23(lockInfo[_holder][i].balance);
emit UNLOCK375(_holder, lockInfo[_holder][i].balance);
lockInfo[_holder][i].balance = 0;
if (i != lockInfo[_holder].length - 1) {
lockInfo[_holder][i] = lockInfo[_holder][lockInfo[_holder].length - 1];
}
lockInfo[_holder].length--;
}
function TRANSFERWITHLOCK415(address _to, uint256 _value, uint256 _releaseTime) public ONLYOWNER394 returns (bool) { //inject NONSTANDARD NAMING
require(_to != address(0), "wrong address");
require(_value <= super.BALANCEOF530(owner), "Not enough balance");
_balances[owner] = _balances[owner].SUB764(_value);
lockInfo[_to].push(
LockInfo(_releaseTime, _value)
);
emit TRANSFER722(owner, _to, _value);
emit LOCK205(_to, _value, _releaseTime);
return true;
}
function TRANSFERWITHLOCKAFTER686(address _to, uint256 _value, uint256 _afterTime) public ONLYOWNER394 returns (bool) { //inject NONSTANDARD NAMING
require(_to != address(0), "wrong address");
require(_value <= super.BALANCEOF530(owner), "Not enough balance");
_balances[owner] = _balances[owner].SUB764(_value);
lockInfo[_to].push(
LockInfo(now + _afterTime, _value)
);
emit TRANSFER722(owner, _to, _value);
emit LOCK205(_to, _value, now + _afterTime);
return true;
}
function CURRENTTIME149() public view returns (uint256) { //inject NONSTANDARD NAMING
return now;
}
function AFTERTIME613(uint256 _value) public view returns (uint256) { //inject NONSTANDARD NAMING
return now + _value;
}
//airdrop
mapping (address => uint256) public airDropHistory;
event AIRDROP940(address _receiver, uint256 _amount); //inject NONSTANDARD NAMING
function DROPTOKEN612(address[] memory receivers, uint256[] memory values) ONLYOWNER394 public { //inject NONSTANDARD NAMING
require(receivers.length != 0);
require(receivers.length == values.length);
for (uint256 i = 0; i < receivers.length; i++) {
address receiver = receivers[i];
uint256 amount = values[i];
TRANSFER438(receiver, amount);
airDropHistory[receiver] += amount;
emit AIRDROP940(receiver, amount);
}
}
} | inject NONSTANDARD NAMING
| function LOCKSTATE154(address _holder, uint256 _idx) public view returns (uint256, uint256) { | 12,759,010 | [
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,
565,
445,
14631,
7998,
29003,
12,
2867,
389,
4505,
16,
2254,
5034,
389,
3465,
13,
1071,
1476,
1135,
261,
11890,
5034,
16,
2254,
5034,
13,
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
] |
/**
*Submitted for verification at Etherscan.io on 2021-04-22
*/
// File: @openzeppelin/contracts/utils/Context.sol
// SPDX-License-Identifier: MIT
pragma solidity >=0.6.0 <0.8.0;
/*
* @dev Provides information about the current execution context, including the
* sender of the transaction and its data. While these are generally available
* via msg.sender and msg.data, they should not be accessed in such a direct
* manner, since when dealing with GSN meta-transactions the account sending and
* paying for execution may not be the actual sender (as far as an application
* is concerned).
*
* This contract is only required for intermediate, library-like contracts.
*/
abstract contract Context {
function _msgSender() internal view virtual returns (address payable) {
return msg.sender;
}
function _msgData() internal view virtual returns (bytes memory) {
this; // silence state mutability warning without generating bytecode - see https://github.com/ethereum/solidity/issues/2691
return msg.data;
}
}
// File: @openzeppelin/contracts/introspection/IERC165.sol
pragma solidity >=0.6.0 <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);
}
// File: @openzeppelin/contracts/token/ERC721/IERC721.sol
pragma solidity >=0.6.2 <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: @openzeppelin/contracts/token/ERC721/IERC721Metadata.sol
pragma solidity >=0.6.2 <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: @openzeppelin/contracts/token/ERC721/IERC721Enumerable.sol
pragma solidity >=0.6.2 <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 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);
}
// File: @openzeppelin/contracts/token/ERC721/IERC721Receiver.sol
pragma solidity >=0.6.0 <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: @openzeppelin/contracts/introspection/ERC165.sol
pragma solidity >=0.6.0 <0.8.0;
/**
* @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(keccak256('supportsInterface(bytes4)')) == 0x01ffc9a7
*/
bytes4 private constant _INTERFACE_ID_ERC165 = 0x01ffc9a7;
/**
* @dev Mapping of interface ids to whether or not it's supported.
*/
mapping(bytes4 => bool) private _supportedInterfaces;
constructor () internal {
// Derived contracts need only register support for their own interfaces,
// we register support for ERC165 itself here
_registerInterface(_INTERFACE_ID_ERC165);
}
/**
* @dev See {IERC165-supportsInterface}.
*
* Time complexity O(1), guaranteed to always use less than 30 000 gas.
*/
function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) {
return _supportedInterfaces[interfaceId];
}
/**
* @dev Registers the contract as an implementer of the interface defined by
* `interfaceId`. Support of the actual ERC165 interface is automatic and
* registering its interface id is not required.
*
* See {IERC165-supportsInterface}.
*
* Requirements:
*
* - `interfaceId` cannot be the ERC165 invalid interface (`0xffffffff`).
*/
function _registerInterface(bytes4 interfaceId) internal virtual {
require(interfaceId != 0xffffffff, "ERC165: invalid interface id");
_supportedInterfaces[interfaceId] = true;
}
}
// File: @openzeppelin/contracts/math/SafeMath.sol
pragma solidity >=0.6.0 <0.8.0;
/**
* @dev Wrappers over Solidity's arithmetic operations with added overflow
* checks.
*
* Arithmetic operations in Solidity wrap on overflow. This can easily result
* in bugs, because programmers usually assume that an overflow raises an
* error, which is the standard behavior in high level programming languages.
* `SafeMath` restores this intuition by reverting the transaction when an
* operation overflows.
*
* Using this library instead of the unchecked operations eliminates an entire
* class of bugs, so it's recommended to use it always.
*/
library SafeMath {
/**
* @dev Returns the addition of two unsigned integers, 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 cheHanfur 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;
}
}
// File: @openzeppelin/contracts/utils/Address.sol
pragma solidity >=0.6.2 <0.8.0;
/**
* @dev Collection of functions related to the address type
*/
library Address {
/**
* @dev Returns true if `account` is a contract.
*
* [IMPORTANT]
* ====
* It is unsafe to assume that an address for which this function returns
* false is an externally-owned account (EOA) and not a contract.
*
* Among others, `isContract` will return false for the following
* types of addresses:
*
* - an externally-owned account
* - a contract in construction
* - an address where a contract will be created
* - an address where a contract lived, but was destroyed
* ====
*/
function isContract(address account) internal view returns (bool) {
// This method relies on extcodesize, which returns 0 for contracts in
// construction, since the code is only stored at the end of the
// constructor execution.
uint256 size;
// solhint-disable-next-line no-inline-assembly
assembly { size := extcodesize(account) }
return size > 0;
}
/**
* @dev Replacement for Solidity's `transfer`: sends `amount` wei to
* `recipient`, forwarding all available gas and reverting on errors.
*
* https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost
* of certain opcodes, possibly making contracts go over the 2300 gas limit
* imposed by `transfer`, making them unable to receive funds via
* `transfer`. {sendValue} removes this limitation.
*
* https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more].
*
* IMPORTANT: because control is transferred to `recipient`, care must be
* taken to not create reentrancy vulnerabilities. Consider using
* {ReentrancyGuard} or the
* https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern].
*/
function sendValue(address payable recipient, uint256 amount) internal {
require(address(this).balance >= amount, "Address: insufficient balance");
// solhint-disable-next-line avoid-low-level-calls, avoid-call-value
(bool success, ) = recipient.call{ value: amount }("");
require(success, "Address: unable to send value, recipient may have reverted");
}
/**
* @dev Performs a Solidity function call using a low level `call`. A
* plain`call` is an unsafe replacement for a function call: use this
* function instead.
*
* If `target` reverts with a revert reason, it is bubbled up by this
* function (like regular Solidity function calls).
*
* Returns the raw returned data. To convert to the expected return value,
* use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`].
*
* Requirements:
*
* - `target` must be a contract.
* - calling `target` with `data` must not revert.
*
* _Available since v3.1._
*/
function functionCall(address target, bytes memory data) internal returns (bytes memory) {
return functionCall(target, data, "Address: low-level call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with
* `errorMessage` as a fallback revert reason when `target` reverts.
*
* _Available since v3.1._
*/
function functionCall(address target, bytes memory data, string memory errorMessage) internal returns (bytes memory) {
return functionCallWithValue(target, data, 0, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but also transferring `value` wei to `target`.
*
* Requirements:
*
* - the calling contract must have an ETH balance of at least `value`.
* - the called Solidity function must be `payable`.
*
* _Available since v3.1._
*/
function functionCallWithValue(address target, bytes memory data, uint256 value) internal returns (bytes memory) {
return functionCallWithValue(target, data, value, "Address: low-level call with value failed");
}
/**
* @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but
* with `errorMessage` as a fallback revert reason when `target` reverts.
*
* _Available since v3.1._
*/
function functionCallWithValue(address target, bytes memory data, uint256 value, string memory errorMessage) internal returns (bytes memory) {
require(address(this).balance >= value, "Address: insufficient balance for call");
require(isContract(target), "Address: call to non-contract");
// solhint-disable-next-line avoid-low-level-calls
(bool success, bytes memory returndata) = target.call{ value: value }(data);
return _verifyCallResult(success, returndata, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but performing a static call.
*
* _Available since v3.3._
*/
function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) {
return functionStaticCall(target, data, "Address: low-level static call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`],
* but performing a static call.
*
* _Available since v3.3._
*/
function functionStaticCall(address target, bytes memory data, string memory errorMessage) internal view returns (bytes memory) {
require(isContract(target), "Address: static call to non-contract");
// solhint-disable-next-line avoid-low-level-calls
(bool success, bytes memory returndata) = target.staticcall(data);
return _verifyCallResult(success, returndata, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but performing a delegate call.
*
* _Available since v3.4._
*/
function functionDelegateCall(address target, bytes memory data) internal returns (bytes memory) {
return functionDelegateCall(target, data, "Address: low-level delegate call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`],
* but performing a delegate call.
*
* _Available since v3.4._
*/
function functionDelegateCall(address target, bytes memory data, string memory errorMessage) internal returns (bytes memory) {
require(isContract(target), "Address: delegate call to non-contract");
// solhint-disable-next-line avoid-low-level-calls
(bool success, bytes memory returndata) = target.delegatecall(data);
return _verifyCallResult(success, returndata, errorMessage);
}
function _verifyCallResult(bool success, bytes memory returndata, string memory errorMessage) private pure returns(bytes memory) {
if (success) {
return returndata;
} else {
// Look for revert reason and bubble it up if present
if (returndata.length > 0) {
// The easiest way to bubble the revert reason is using memory via assembly
// solhint-disable-next-line no-inline-assembly
assembly {
let returndata_size := mload(returndata)
revert(add(32, returndata), returndata_size)
}
} else {
revert(errorMessage);
}
}
}
}
// File: @openzeppelin/contracts/utils/EnumerableSet.sol
pragma solidity >=0.6.0 <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 `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;
// When the value to delete is the last one, the swap operation is unnecessary. However, since this occurs
// so rarely, we still do the swap anyway to avoid the gas cost of adding an 'if' statement.
bytes32 lastvalue = set._values[lastIndex];
// Move the last value to the index where the value to delete is
set._values[toDeleteIndex] = lastvalue;
// Update the index for the moved value
set._indexes[lastvalue] = toDeleteIndex + 1; // All indexes are 1-based
// Delete the slot where the moved value was stored
set._values.pop();
// Delete the index for the deleted slot
delete set._indexes[value];
return true;
} else {
return false;
}
}
/**
* @dev Returns true if the value is in the set. O(1).
*/
function _contains(Set storage set, bytes32 value) private view returns (bool) {
return set._indexes[value] != 0;
}
/**
* @dev Returns the number of values on the set. O(1).
*/
function _length(Set storage set) private view returns (uint256) {
return set._values.length;
}
/**
* @dev Returns the value stored at position `index` in the set. O(1).
*
* Note that there are no guarantees on the ordering of values inside the
* array, and it may change when more values are added or removed.
*
* Requirements:
*
* - `index` must be strictly less than {length}.
*/
function _at(Set storage set, uint256 index) private view returns (bytes32) {
require(set._values.length > index, "EnumerableSet: index out of bounds");
return set._values[index];
}
// 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);
}
// 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))));
}
// UintSet
struct UintSet {
Set _inner;
}
/**
* @dev Add a value to a set. O(1).
*
* Returns true if the value was added to the set, that is if it was not
* already present.
*/
function add(UintSet storage set, uint256 value) internal returns (bool) {
return _add(set._inner, bytes32(value));
}
/**
* @dev Removes a value from a set. O(1).
*
* Returns true if the value was removed from the set, that is if it was
* present.
*/
function remove(UintSet storage set, uint256 value) internal returns (bool) {
return _remove(set._inner, bytes32(value));
}
/**
* @dev Returns true if the value is in the set. O(1).
*/
function contains(UintSet storage set, uint256 value) internal view returns (bool) {
return _contains(set._inner, bytes32(value));
}
/**
* @dev Returns the number of values on the set. O(1).
*/
function length(UintSet storage set) internal view returns (uint256) {
return _length(set._inner);
}
/**
* @dev Returns the value stored at position `index` in the set. O(1).
*
* Note that there are no guarantees on the ordering of values inside the
* array, and it may change when more values are added or removed.
*
* Requirements:
*
* - `index` must be strictly less than {length}.
*/
function at(UintSet storage set, uint256 index) internal view returns (uint256) {
return uint256(_at(set._inner, index));
}
}
// File: @openzeppelin/contracts/utils/EnumerableMap.sol
pragma solidity >=0.6.0 <0.8.0;
/**
* @dev Library for managing an enumerable variant of Solidity's
* https://solidity.readthedocs.io/en/latest/types.html#mapping-types[`mapping`]
* type.
*
* Maps have the following properties:
*
* - Entries are added, removed, and checked for existence in constant time
* (O(1)).
* - Entries are enumerated in O(n). No guarantees are made on the ordering.
*
* ```
* contract Example {
* // Add the library methods
* using EnumerableMap for EnumerableMap.UintToAddressMap;
*
* // Declare a set state variable
* EnumerableMap.UintToAddressMap private myMap;
* }
* ```
*
* As of v3.0.0, only maps of type `uint256 -> address` (`UintToAddressMap`) are
* supported.
*/
library EnumerableMap {
// To implement this library for multiple types with as little code
// repetition as possible, we write it in terms of a generic Map type with
// bytes32 keys and values.
// The Map implementation uses private functions, and user-facing
// implementations (such as Uint256ToAddressMap) are just wrappers around
// the underlying Map.
// This means that we can only create new EnumerableMaps for types that fit
// in bytes32.
struct MHanfuntry {
bytes32 _key;
bytes32 _value;
}
struct Map {
// Storage of map keys and values
MHanfuntry[] _entries;
// Position of the entry defined by a key in the `entries` array, plus 1
// because index 0 means a key is not in the map.
mapping (bytes32 => uint256) _indexes;
}
/**
* @dev Adds a key-value pair to a map, or updates the value for an existing
* key. O(1).
*
* Returns true if the key was added to the map, that is if it was not
* already present.
*/
function _set(Map storage map, bytes32 key, bytes32 value) private returns (bool) {
// We read and store the key's index to prevent multiple reads from the same storage slot
uint256 keyIndex = map._indexes[key];
if (keyIndex == 0) { // Equivalent to !contains(map, key)
map._entries.push(MHanfuntry({ _key: key, _value: value }));
// The entry is stored at length-1, but we add 1 to all indexes
// and use 0 as a sentinel value
map._indexes[key] = map._entries.length;
return true;
} else {
map._entries[keyIndex - 1]._value = value;
return false;
}
}
/**
* @dev Removes a key-value pair from a map. O(1).
*
* Returns true if the key was removed from the map, that is if it was present.
*/
function _remove(Map storage map, bytes32 key) private returns (bool) {
// We read and store the key's index to prevent multiple reads from the same storage slot
uint256 keyIndex = map._indexes[key];
if (keyIndex != 0) { // Equivalent to contains(map, key)
// To delete a key-value pair from the _entries array in O(1), we swap the entry to delete with the last one
// in the array, and then remove the last entry (sometimes called as 'swap and pop').
// This modifies the order of the array, as noted in {at}.
uint256 toDeleteIndex = keyIndex - 1;
uint256 lastIndex = map._entries.length - 1;
// When the entry to delete is the last one, the swap operation is unnecessary. However, since this occurs
// so rarely, we still do the swap anyway to avoid the gas cost of adding an 'if' statement.
MHanfuntry storage lastEntry = map._entries[lastIndex];
// Move the last entry to the index where the entry to delete is
map._entries[toDeleteIndex] = lastEntry;
// Update the index for the moved entry
map._indexes[lastEntry._key] = toDeleteIndex + 1; // All indexes are 1-based
// Delete the slot where the moved entry was stored
map._entries.pop();
// Delete the index for the deleted slot
delete map._indexes[key];
return true;
} else {
return false;
}
}
/**
* @dev Returns true if the key is in the map. O(1).
*/
function _contains(Map storage map, bytes32 key) private view returns (bool) {
return map._indexes[key] != 0;
}
/**
* @dev Returns the number of key-value pairs in the map. O(1).
*/
function _length(Map storage map) private view returns (uint256) {
return map._entries.length;
}
/**
* @dev Returns the key-value pair stored at position `index` in the map. O(1).
*
* Note that there are no guarantees on the ordering of entries inside the
* array, and it may change when more entries are added or removed.
*
* Requirements:
*
* - `index` must be strictly less than {length}.
*/
function _at(Map storage map, uint256 index) private view returns (bytes32, bytes32) {
require(map._entries.length > index, "EnumerableMap: index out of bounds");
MHanfuntry storage entry = map._entries[index];
return (entry._key, entry._value);
}
/**
* @dev Tries to returns the value associated with `key`. O(1).
* Does not revert if `key` is not in the map.
*/
function _tryGet(Map storage map, bytes32 key) private view returns (bool, bytes32) {
uint256 keyIndex = map._indexes[key];
if (keyIndex == 0) return (false, 0); // Equivalent to contains(map, key)
return (true, map._entries[keyIndex - 1]._value); // All indexes are 1-based
}
/**
* @dev Returns the value associated with `key`. O(1).
*
* Requirements:
*
* - `key` must be in the map.
*/
function _get(Map storage map, bytes32 key) private view returns (bytes32) {
uint256 keyIndex = map._indexes[key];
require(keyIndex != 0, "EnumerableMap: nonexistent key"); // Equivalent to contains(map, key)
return map._entries[keyIndex - 1]._value; // All indexes are 1-based
}
/**
* @dev Same as {_get}, with a custom error message when `key` is not in the map.
*
* CAUTION: This function is deprecated because it requires allocating memory for the error
* message unnecessarily. For custom revert reasons use {_tryGet}.
*/
function _get(Map storage map, bytes32 key, string memory errorMessage) private view returns (bytes32) {
uint256 keyIndex = map._indexes[key];
require(keyIndex != 0, errorMessage); // Equivalent to contains(map, key)
return map._entries[keyIndex - 1]._value; // All indexes are 1-based
}
// UintToAddressMap
struct UintToAddressMap {
Map _inner;
}
/**
* @dev Adds a key-value pair to a map, or updates the value for an existing
* key. O(1).
*
* Returns true if the key was added to the map, that is if it was not
* already present.
*/
function set(UintToAddressMap storage map, uint256 key, address value) internal returns (bool) {
return _set(map._inner, bytes32(key), bytes32(uint256(uint160(value))));
}
/**
* @dev Removes a value from a set. O(1).
*
* Returns true if the key was removed from the map, that is if it was present.
*/
function remove(UintToAddressMap storage map, uint256 key) internal returns (bool) {
return _remove(map._inner, bytes32(key));
}
/**
* @dev Returns true if the key is in the map. O(1).
*/
function contains(UintToAddressMap storage map, uint256 key) internal view returns (bool) {
return _contains(map._inner, bytes32(key));
}
/**
* @dev Returns the number of elements in the map. O(1).
*/
function length(UintToAddressMap storage map) internal view returns (uint256) {
return _length(map._inner);
}
/**
* @dev Returns the element 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(UintToAddressMap storage map, uint256 index) internal view returns (uint256, address) {
(bytes32 key, bytes32 value) = _at(map._inner, index);
return (uint256(key), address(uint160(uint256(value))));
}
/**
* @dev Tries to returns the value associated with `key`. O(1).
* Does not revert if `key` is not in the map.
*
* _Available since v3.4._
*/
function tryGet(UintToAddressMap storage map, uint256 key) internal view returns (bool, address) {
(bool success, bytes32 value) = _tryGet(map._inner, bytes32(key));
return (success, address(uint160(uint256(value))));
}
/**
* @dev Returns the value associated with `key`. O(1).
*
* Requirements:
*
* - `key` must be in the map.
*/
function get(UintToAddressMap storage map, uint256 key) internal view returns (address) {
return address(uint160(uint256(_get(map._inner, bytes32(key)))));
}
/**
* @dev Same as {get}, with a custom error message when `key` is not in the map.
*
* CAUTION: This function is deprecated because it requires allocating memory for the error
* message unnecessarily. For custom revert reasons use {tryGet}.
*/
function get(UintToAddressMap storage map, uint256 key, string memory errorMessage) internal view returns (address) {
return address(uint160(uint256(_get(map._inner, bytes32(key), errorMessage))));
}
}
// File: @openzeppelin/contracts/utils/Strings.sol
pragma solidity >=0.6.0 <0.8.0;
/**
* @dev String operations.
*/
library Strings {
/**
* @dev Converts a `uint256` to its ASCII `string` 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);
uint256 index = digits - 1;
temp = value;
while (temp != 0) {
buffer[index--] = bytes1(uint8(48 + temp % 10));
temp /= 10;
}
return string(buffer);
}
}
// File: @openzeppelin/contracts/token/ERC721/ERC721.sol
pragma solidity >=0.6.0 <0.8.0;
/**
* @title ERC721 Non-Fungible Token Standard basic implementation
* @dev see https://eips.ethereum.org/EIPS/eip-721
*/
contract ERC721 is Context, ERC165, IERC721, IERC721Metadata, IERC721Enumerable {
using SafeMath for uint256;
using Address for address;
using EnumerableSet for EnumerableSet.UintSet;
using EnumerableMap for EnumerableMap.UintToAddressMap;
using Strings for uint256;
// Equals to `bytes4(keccak256("onERC721Received(address,address,uint256,bytes)"))`
// which can be also obtained as `IERC721Receiver(0).onERC721Received.selector`
bytes4 private constant _ERC721_RECEIVED = 0x150b7a02;
// Mapping from holder address to their (enumerable) set of owned tokens
mapping (address => EnumerableSet.UintSet) private _holderTokens;
// Enumerable mapping from token ids to their owners
EnumerableMap.UintToAddressMap private _tokenOwners;
// 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;
// Token name
string private _name;
// Token symbol
string private _symbol;
// Optional mapping for token URIs
mapping (uint256 => string) private _tokenURIs;
// Base URI
string private _baseURI;
uint256 internal openedNum = 0;
/*
* bytes4(keccak256('balanceOf(address)')) == 0x70a08231
* bytes4(keccak256('ownerOf(uint256)')) == 0x6352211e
* bytes4(keccak256('approve(address,uint256)')) == 0x095ea7b3
* bytes4(keccak256('getApproved(uint256)')) == 0x081812fc
* bytes4(keccak256('setApprovalForAll(address,bool)')) == 0xa22cb465
* bytes4(keccak256('isApprovedForAll(address,address)')) == 0xe985e9c5
* bytes4(keccak256('transferFrom(address,address,uint256)')) == 0x23b872dd
* bytes4(keccak256('safeTransferFrom(address,address,uint256)')) == 0x42842e0e
* bytes4(keccak256('safeTransferFrom(address,address,uint256,bytes)')) == 0xb88d4fde
*
* => 0x70a08231 ^ 0x6352211e ^ 0x095ea7b3 ^ 0x081812fc ^
* 0xa22cb465 ^ 0xe985e9c5 ^ 0x23b872dd ^ 0x42842e0e ^ 0xb88d4fde == 0x80ac58cd
*/
bytes4 private constant _INTERFACE_ID_ERC721 = 0x80ac58cd;
/*
* bytes4(keccak256('name()')) == 0x06fdde03
* bytes4(keccak256('symbol()')) == 0x95d89b41
* bytes4(keccak256('tokenURI(uint256)')) == 0xc87b56dd
*
* => 0x06fdde03 ^ 0x95d89b41 ^ 0xc87b56dd == 0x5b5e139f
*/
bytes4 private constant _INTERFACE_ID_ERC721_METADATA = 0x5b5e139f;
/*
* bytes4(keccak256('totalSupply()')) == 0x18160ddd
* bytes4(keccak256('tokenOfOwnerByIndex(address,uint256)')) == 0x2f745c59
* bytes4(keccak256('tokenByIndex(uint256)')) == 0x4f6ccce7
*
* => 0x18160ddd ^ 0x2f745c59 ^ 0x4f6ccce7 == 0x780e9d63
*/
bytes4 private constant _INTERFACE_ID_ERC721_ENUMERABLE = 0x780e9d63;
/**
* @dev Initializes the contract by setting a `name` and a `symbol` to the token collection.
*/
constructor (string memory name_, string memory symbol_) public {
_name = name_;
_symbol = symbol_;
// register the supported interfaces to conform to ERC721 via ERC165
_registerInterface(_INTERFACE_ID_ERC721);
_registerInterface(_INTERFACE_ID_ERC721_METADATA);
_registerInterface(_INTERFACE_ID_ERC721_ENUMERABLE);
}
/**
* @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 _holderTokens[owner].length();
}
/**
* @dev See {IERC721-ownerOf}.
*/
function ownerOf(uint256 tokenId) public view virtual override returns (address) {
return _tokenOwners.get(tokenId, "ERC721: owner query for nonexistent token");
}
/**
* @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 _tokenURI = _tokenURIs[tokenId];
string memory base = baseURI();
if (tokenId >= openedNum) {
return string(abi.encodePacked(base, "blindbox.json"));
}
// 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));
}
// If there is a baseURI but no tokenURI, concatenate the tokenID to the baseURI.
return string(abi.encodePacked(base, tokenId.toString(), ".json"));
}
/**
* @dev Returns the base URI set via {_setBaseURI}. This will be
* automatically added as a prefix in {tokenURI} to each token's URI, or
* to the token ID if no specific URI is set for that token ID.
*/
function baseURI() public view virtual returns (string memory) {
return _baseURI;
}
/**
* @dev See {IERC721Enumerable-tokenOfOwnerByIndex}.
*/
function tokenOfOwnerByIndex(address owner, uint256 index) public view virtual override returns (uint256) {
return _holderTokens[owner].at(index);
}
/**
* @dev See {IERC721Enumerable-totalSupply}.
*/
function totalSupply() public view virtual override returns (uint256) {
// _tokenOwners are indexed by tokenIds, so .length() returns the number of tokenIds
return _tokenOwners.length();
}
/**
* @dev See {IERC721Enumerable-tokenByIndex}.
*/
function tokenByIndex(uint256 index) public view virtual override returns (uint256) {
(uint256 tokenId, ) = _tokenOwners.at(index);
return tokenId;
}
/**
* @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 || ERC721.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 _tokenOwners.contains(tokenId);
}
/**
* @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 || ERC721.isApprovedForAll(owner, spender));
}
/**
* @dev Safely mints `tokenId` and transfers it to `to`.
*
* Requirements:
d*
* - `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);
_holderTokens[to].add(tokenId);
_tokenOwners.set(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); // internal owner
_beforeTokenTransfer(owner, address(0), tokenId);
// Clear approvals
_approve(address(0), tokenId);
// Clear metadata (if any)
if (bytes(_tokenURIs[tokenId]).length != 0) {
delete _tokenURIs[tokenId];
}
_holderTokens[owner].remove(tokenId);
_tokenOwners.remove(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"); // internal owner
require(to != address(0), "ERC721: transfer to the zero address");
_beforeTokenTransfer(from, to, tokenId);
// Clear approvals from the previous owner
_approve(address(0), tokenId);
_holderTokens[from].remove(tokenId);
_holderTokens[to].add(tokenId);
_tokenOwners.set(tokenId, to);
emit Transfer(from, to, 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), "ERC721Metadata: URI set of nonexistent token");
_tokenURIs[tokenId] = _tokenURI;
}
/**
* @dev Internal function to set the base URI for all token IDs. It is
* automatically added as a prefix to the value returned in {tokenURI},
* or to the token ID if {tokenURI} is empty.
*/
function _setBaseURI(string memory baseURI_) internal virtual {
_baseURI = baseURI_;
}
/**
* @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()) {
return true;
}
bytes memory returndata = to.functionCall(abi.encodeWithSelector(
IERC721Receiver(to).onERC721Received.selector,
_msgSender(),
from,
tokenId,
_data
), "ERC721: transfer to non ERC721Receiver implementer");
bytes4 retval = abi.decode(returndata, (bytes4));
return (retval == _ERC721_RECEIVED);
}
/**
* @dev Approve `to` to operate on `tokenId`
*
* Emits an {Approval} event.
*/
function _approve(address to, uint256 tokenId) internal virtual {
_tokenApprovals[tokenId] = to;
emit Approval(ERC721.ownerOf(tokenId), to, tokenId); // internal owner
}
/**
* @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 { }
}
// File: @openzeppelin/contracts/access/Ownable.sol
pragma solidity >=0.6.0 <0.8.0;
/**
* @dev Contract module which provides a basic access control mechanism, where
* there is an account (an owner) that can be granted exclusive access to
* specific functions.
*
* By default, the owner account will be the one that deploys the contract. This
* can later be changed with {transferOwnership}.
*
* This module is used through inheritance. It will make available the modifier
* `onlyOwner`, which can be applied to your functions to restrict their use to
* the owner.
*/
abstract contract Ownable is Context {
address private _owner;
event OwnershipTransferred(address indexed previousOwner, address indexed newOwner);
/**
* @dev Initializes the contract setting the deployer as the initial owner.
*/
constructor () internal {
address msgSender = _msgSender();
_owner = msgSender;
emit OwnershipTransferred(address(0), msgSender);
}
/**
* @dev Returns the address of the current owner.
*/
function owner() public view 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;
}
}
// File: contracts/HanfuClub.sol
pragma solidity ^0.7.0;
/**
* @title HanfuClub contract
* @dev Extends ERC721 Non-Fungible Token Standard basic implementation
*/
contract HanfuClub is ERC721, Ownable {
using SafeMath for uint256;
address payable busyWallet;
address payable busyWallet1;
address payable busyWallet2;
address payable busyWallet3;
address payable depWallet;
bytes32 public merkleRoot;
uint256 public constant hanfuPrice = 88000000000000000; //0.088 ETH
uint256 public constant wlValidPrice = 88000000000000000; //0.088 ETH
uint256 public constant hanfuWlPrice = 66000000000000000; //0.066 ETH
uint public constant maxHanfuWlPurchase = 5;
uint public constant maxHanfuPurchase = 1000;
uint256 public maxHanfu;
bool public saleIsActive = false;
uint32 public airDropRound = 0;
uint32 public nftSaleStage = 0;
mapping (address => uint32) private wlUsedList;
uint32 wlUsedRound = 0;
uint8 reservedFlag = 0;
function verifyProof(bytes memory _proof, bytes32 _root, bytes32 _leaf) public pure returns (bool) {
// Check if proof length is a multiple of 32
if (_proof.length % 32 != 0) return false;
bytes32 proofElement;
bytes32 computedHash = _leaf;
for (uint256 i = 32; i <= _proof.length; i += 32) {
assembly {
// Load the current element of the proof
proofElement := mload(add(_proof, i))
}
if (computedHash < proofElement) {
// Hash(current computed hash + current element of the proof)
computedHash = keccak256(abi.encodePacked(computedHash, proofElement));
} else {
// Hash(current element of the proof + current computed hash)
computedHash = keccak256(abi.encodePacked(proofElement, computedHash));
}
}
// Check if the computed hash (root) is equal to the provided root
return computedHash == _root;
}
function rand(uint seed) internal pure returns (uint) {
bytes32 data;
if (seed % 2 == 0){
data = keccak256(abi.encodePacked(seed));
}else{
data = keccak256(abi.encodePacked(bytes32(seed)));
}
uint sum;
for(uint i;i < 32;i++){
sum += uint(uint8(data[i]));
}
return uint(uint8(data[sum % data.length])) * uint(uint8(data[(sum + 2) % data.length]));
}
function randsimple(uint seed) internal pure returns (uint) {
bytes32 data;
if (seed % 2 == 0){
data = keccak256(abi.encodePacked(seed));
} else {
data = keccak256(abi.encodePacked(bytes32(seed)));
}
return uint(data);
}
/**
* @dev Generate random uint <= 256^2 with seed = block.timestamp
* @return uint
*/
function randint() internal view returns(uint) {
return rand(block.timestamp);
}
/**
* @dev Generate random uint in range [a, b)
* @return uint
*/
function randrange(uint a, uint b) internal view returns(uint) {
return a + (randint() % (b - a));
}
/**
* @dev Generate array of random bytes
* @param size seed
* @return byte[size]
*/
function randbytes(uint size, uint seed) internal pure returns (bytes memory) {
bytes memory data = new bytes(size);
uint x = seed;
for(uint i;i < size;i++){
x = rand(x);
data[i] = byte(uint8(x % 256));
}
return data;
}
constructor(string memory name, string memory symbol, uint256 maxNftSupply, address payable _wallet, address payable _wallet1, address payable _wallet2, address payable _wallet3, address payable _dev) ERC721(name, symbol) {
maxHanfu = maxNftSupply;
busyWallet = _wallet;
busyWallet1 = _wallet1;
busyWallet2 = _wallet2;
busyWallet3 = _wallet3;
depWallet = _dev;
}
function withdraw() public onlyOwner {
uint balance = address(this).balance;
uint toDevBalance = balance * 10 / 100;
depWallet.transfer(toDevBalance);
balance = (balance - toDevBalance) / 4;
busyWallet.transfer(balance);
busyWallet1.transfer(balance);
busyWallet2.transfer(balance);
busyWallet3.transfer(balance);
}
function toNextNftSaleRound() public onlyOwner {
nftSaleStage++;
}
function getHanfuPrice() public view returns(uint256) {
if (nftSaleStage == 0) {
return hanfuWlPrice;
} else {
return hanfuPrice;
}
}
function getMaxHanfuPurchase() public view returns(uint256) {
if (nftSaleStage == 0) {
return maxHanfuWlPurchase;
} else {
return maxHanfuPurchase;
}
}
function getWlUsedFlag() public view returns(bool) {
return wlUsedList[msg.sender] == wlUsedRound;
}
function reValidWhiteList() public payable {
require(saleIsActive, "Sale must be active to mint Hanfu");
require(wlValidPrice <= msg.value, "Ether value sent is not correct");
require(wlUsedList[msg.sender] == wlUsedRound, "Not used whitelist");
wlUsedList[msg.sender] = 0;
}
/**
* Set some Hanfus aside
*/
function reserveHanfu() public onlyOwner {
uint supply = totalSupply();
require(reservedFlag == 0, "not allowed reserved");
uint i;
for (i = 0; i < 35; i++) {
_safeMint(msg.sender, supply + i);
}
reservedFlag = 1;
}
/*
* Set merkeleroot once it's calculated
*/
function setMerkleRoot(bytes32 _merkleRoot) public onlyOwner {
merkleRoot = _merkleRoot;
wlUsedRound++;
}
function setBaseURI(string memory baseURI) public onlyOwner {
_setBaseURI(baseURI);
}
/*
* Pause sale if active, make active if paused
*/
function flipSaleState() public onlyOwner {
saleIsActive = !saleIsActive;
}
/**
* Mints Hanfus
*/
function mintHanfu(uint numberOfTokens) public payable {
require(saleIsActive, "Sale must be active to mint Hanfu");
require(numberOfTokens <= maxHanfuPurchase, "Can only mint 20 tokens at a time");
require(totalSupply().add(numberOfTokens) <= maxHanfu, "Purchase would exceed max supply of Hanfus");
require(hanfuPrice.mul(numberOfTokens) <= msg.value, "Ether value sent is not correct");
require(nftSaleStage > 0, "not in public sale state");
for(uint i = 0; i < numberOfTokens; i++) {
uint mintIndex = totalSupply();
if (totalSupply() < maxHanfu) {
_safeMint(msg.sender, mintIndex);
}
}
}
function mintHanfuWl(uint numberOfTokens, bytes memory proof) public payable {
require(saleIsActive, "Sale must be active to mint Hanfu");
require(numberOfTokens <= maxHanfuWlPurchase, "Can only mint 5 tokens at a time");
require(totalSupply().add(numberOfTokens) <= maxHanfu, "Purchase would exceed max supply of Hanfus");
require(hanfuWlPrice.mul(numberOfTokens) <= msg.value, "Ether value sent is not correct");
require(wlUsedList[msg.sender] != wlUsedRound, "Already Use Wl");
require(verifyProof(proof, merkleRoot, keccak256(abi.encodePacked(msg.sender))), "Not in Whitelist");
wlUsedList[msg.sender] = wlUsedRound;
for(uint i = 0; i < numberOfTokens; i++) {
uint mintIndex = totalSupply();
if (totalSupply() < maxHanfu) {
_safeMint(msg.sender, mintIndex);
}
}
}
function airDropRun() public onlyOwner {
uint mintIndex = totalSupply();
uint startIndex = 0;
uint endIndex = 0;
if (airDropRound == 0) {
require(mintIndex >= 100, "Not allowed AirDrop");
airDropRound = 50;
startIndex = 0;
endIndex = 100;
} else if (airDropRound == 50) {
require(mintIndex >= 500, "Not allowed AirDrop");
airDropRound = 100;
startIndex = 100;
endIndex = 500;
} else if (airDropRound == 100) {
require(mintIndex >= 1500, "Not allowed AirDrop");
airDropRound = 150;
startIndex = 500;
endIndex = 1500;
} else {
require(false, "Not allowed AirDrop");
}
uint seed = rand(block.timestamp);
for(uint i = 0; i < airDropRound; i++) {
seed = randsimple(seed);
uint tokenId = (seed % (endIndex - startIndex)) + startIndex;
if (_exists(tokenId)) {
if (totalSupply() < maxHanfu) {
_safeMint(ownerOf(tokenId), mintIndex + i);
}
}
}
}
function setOpenedNumber(uint _index) public onlyOwner {
openedNum = _index;
}
} | * @dev See {IERC721Metadata-tokenURI}./ If there is no base URI, return the token URI. If both are set, concatenate the baseURI and tokenURI (via abi.encodePacked). | function tokenURI(uint256 tokenId) public view virtual override returns (string memory) {
require(_exists(tokenId), "ERC721Metadata: URI query for nonexistent token");
string memory _tokenURI = _tokenURIs[tokenId];
string memory base = baseURI();
if (tokenId >= openedNum) {
return string(abi.encodePacked(base, "blindbox.json"));
}
if (bytes(base).length == 0) {
return _tokenURI;
}
if (bytes(_tokenURI).length > 0) {
return string(abi.encodePacked(base, _tokenURI));
}
}
| 10,424,463 | [
1,
9704,
288,
45,
654,
39,
27,
5340,
2277,
17,
2316,
3098,
5496,
19,
971,
1915,
353,
1158,
1026,
3699,
16,
327,
326,
1147,
3699,
18,
971,
3937,
854,
444,
16,
11361,
326,
1026,
3098,
471,
1147,
3098,
261,
21985,
24126,
18,
3015,
4420,
329,
2934,
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
] | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
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
] | [
1,
565,
445,
1147,
3098,
12,
11890,
5034,
1147,
548,
13,
1071,
1476,
5024,
3849,
1135,
261,
1080,
3778,
13,
288,
203,
3639,
2583,
24899,
1808,
12,
2316,
548,
3631,
315,
654,
39,
27,
5340,
2277,
30,
3699,
843,
364,
1661,
19041,
1147,
8863,
203,
203,
3639,
533,
3778,
389,
2316,
3098,
273,
389,
2316,
1099,
2520,
63,
2316,
548,
15533,
203,
3639,
533,
3778,
1026,
273,
1026,
3098,
5621,
203,
203,
3639,
309,
261,
2316,
548,
1545,
10191,
2578,
13,
288,
203,
5411,
327,
533,
12,
21457,
18,
3015,
4420,
329,
12,
1969,
16,
315,
3083,
728,
2147,
18,
1977,
7923,
1769,
203,
3639,
289,
203,
203,
3639,
309,
261,
3890,
12,
1969,
2934,
2469,
422,
374,
13,
288,
203,
5411,
327,
389,
2316,
3098,
31,
203,
3639,
289,
203,
3639,
309,
261,
3890,
24899,
2316,
3098,
2934,
2469,
405,
374,
13,
288,
203,
5411,
327,
533,
12,
21457,
18,
3015,
4420,
329,
12,
1969,
16,
389,
2316,
3098,
10019,
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
] |
pragma solidity 0.4.18;
/// @title Math operations with safety checks
library SafeMath {
function mul(uint256 a, uint256 b) internal pure returns (uint256) {
uint256 c = a * b;
require(a == 0 || c / a == b);
return c;
}
function div(uint256 a, uint256 b) internal pure returns (uint256) {
// require(b > 0); // Solidity automatically throws when dividing by 0
uint256 c = a / b;
// require(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) {
require(b <= a);
return a - b;
}
function add(uint256 a, uint256 b) internal pure returns (uint256) {
uint256 c = a + b;
require(c >= a);
return c;
}
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;
}
function toPower2(uint256 a) internal pure returns (uint256) {
return mul(a, a);
}
function sqrt(uint256 a) internal pure returns (uint256) {
uint256 c = (a + 1) / 2;
uint256 b = a;
while (c < b) {
b = c;
c = (a / c + c) / 2;
}
return b;
}
}
/// @title ERC223Receiver Interface
/// @dev Based on the specs form: https://github.com/ethereum/EIPs/issues/223
contract ERC223Receiver {
function tokenFallback(address _sender, uint _value, bytes _data) external returns (bool ok);
}
/// @title Market Maker Interface.
/// @author Tal Beja.
contract MarketMaker is ERC223Receiver {
function getCurrentPrice() public constant returns (uint _price);
function change(address _fromToken, uint _amount, address _toToken) public returns (uint _returnAmount);
function change(address _fromToken, uint _amount, address _toToken, uint _minReturn) public returns (uint _returnAmount);
function change(address _toToken) public returns (uint _returnAmount);
function change(address _toToken, uint _minReturn) public returns (uint _returnAmount);
function quote(address _fromToken, uint _amount, address _toToken) public constant returns (uint _returnAmount);
function openForPublicTrade() public returns (bool success);
function isOpenForPublic() public returns (bool success);
event Change(address indexed fromToken, uint inAmount, address indexed toToken, uint returnAmount, address indexed account);
}
/// @title Ellipse Market Maker Interfase
/// @author Tal Beja
contract IEllipseMarketMaker is MarketMaker {
// precision for price representation (as in ether or tokens).
uint256 public constant PRECISION = 10 ** 18;
// The tokens pair.
ERC20 public token1;
ERC20 public token2;
// The tokens reserves.
uint256 public R1;
uint256 public R2;
// The tokens full suplly.
uint256 public S1;
uint256 public S2;
// State flags.
bool public operational;
bool public openForPublic;
// Library contract address.
address public mmLib;
function supportsToken(address token) public constant returns (bool);
function calcReserve(uint256 _R1, uint256 _S1, uint256 _S2) public pure returns (uint256);
function validateReserves() public view returns (bool);
function withdrawExcessReserves() public returns (uint256);
function initializeAfterTransfer() public returns (bool);
function initializeOnTransfer() public returns (bool);
function getPrice(uint256 _R1, uint256 _R2, uint256 _S1, uint256 _S2) public constant returns (uint256);
}
/// @title ERC Token Standard #20 Interface (https://github.com/ethereum/EIPs/issues/20)
contract ERC20 {
uint public totalSupply;
function balanceOf(address _owner) constant public 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 constant returns (uint remaining);
event Transfer(address indexed from, address indexed to, uint value);
event Approval(address indexed owner, address indexed spender, uint value);
}
/// @title Ownable
/// @dev The Ownable contract has an owner address, and provides basic authorization control functions,
/// this simplifies the implementation of "user permissions".
/// @dev Based on OpenZeppelin's Ownable.
contract Ownable {
address public owner;
address public newOwnerCandidate;
event OwnershipRequested(address indexed _by, address indexed _to);
event OwnershipTransferred(address indexed _from, address indexed _to);
/// @dev Constructor sets the original `owner` of the contract to the sender account.
function Ownable() public {
owner = msg.sender;
}
/// @dev Reverts if called by any account other than the owner.
modifier onlyOwner() {
require(msg.sender == owner);
_;
}
modifier onlyOwnerCandidate() {
require(msg.sender == newOwnerCandidate);
_;
}
/// @dev Proposes to transfer control of the contract to a newOwnerCandidate.
/// @param _newOwnerCandidate address The address to transfer ownership to.
function requestOwnershipTransfer(address _newOwnerCandidate) external onlyOwner {
require(_newOwnerCandidate != address(0));
newOwnerCandidate = _newOwnerCandidate;
OwnershipRequested(msg.sender, newOwnerCandidate);
}
/// @dev Accept ownership transfer. This method needs to be called by the perviously proposed owner.
function acceptOwnership() external onlyOwnerCandidate {
address previousOwner = owner;
owner = newOwnerCandidate;
newOwnerCandidate = address(0);
OwnershipTransferred(previousOwner, owner);
}
}
/// @title Standard ERC223 Token Receiver implementing tokenFallback function and tokenPayable modifier
contract Standard223Receiver is ERC223Receiver {
Tkn tkn;
struct Tkn {
address addr;
address sender; // the transaction caller
uint256 value;
}
bool __isTokenFallback;
modifier tokenPayable {
require(__isTokenFallback);
_;
}
/// @dev Called when the receiver of transfer is contract
/// @param _sender address the address of tokens sender
/// @param _value uint256 the amount of tokens to be transferred.
/// @param _data bytes data that can be attached to the token transation
function tokenFallback(address _sender, uint _value, bytes _data) external returns (bool ok) {
if (!supportsToken(msg.sender)) {
return false;
}
// Problem: This will do a sstore which is expensive gas wise. Find a way to keep it in memory.
// Solution: Remove the the data
tkn = Tkn(msg.sender, _sender, _value);
__isTokenFallback = true;
if (!address(this).delegatecall(_data)) {
__isTokenFallback = false;
return false;
}
// avoid doing an overwrite to .token, which would be more expensive
// makes accessing .tkn values outside tokenPayable functions unsafe
__isTokenFallback = false;
return true;
}
function supportsToken(address token) public constant returns (bool);
}
/// @title TokenOwnable
/// @dev The TokenOwnable contract adds a onlyTokenOwner modifier as a tokenReceiver with ownable addaptation
contract TokenOwnable is Standard223Receiver, Ownable {
/// @dev Reverts if called by any account other than the owner for token sending.
modifier onlyTokenOwner() {
require(tkn.sender == owner);
_;
}
}
/// @title Ellipse Market Maker Library.
/// @dev market maker, using ellipse equation.
/// @dev for more information read the appendix of the CLN white paper: https://cln.network/pdf/cln_whitepaper.pdf
/// @author Tal Beja.
contract EllipseMarketMakerLib is TokenOwnable, IEllipseMarketMaker {
using SafeMath for uint256;
// temp reserves
uint256 private l_R1;
uint256 private l_R2;
modifier notConstructed() {
require(mmLib == address(0));
_;
}
/// @dev Reverts if not operational
modifier isOperational() {
require(operational);
_;
}
/// @dev Reverts if operational
modifier notOperational() {
require(!operational);
_;
}
/// @dev Reverts if msg.sender can't trade
modifier canTrade() {
require(openForPublic || msg.sender == owner);
_;
}
/// @dev Reverts if tkn.sender can't trade
modifier canTrade223() {
require (openForPublic || tkn.sender == owner);
_;
}
/// @dev The Market Maker constructor
/// @param _mmLib address address of the market making lib contract
/// @param _token1 address contract of the first token for marker making (CLN)
/// @param _token2 address contract of the second token for marker making (CC)
function constructor(address _mmLib, address _token1, address _token2) public onlyOwner notConstructed returns (bool) {
require(_mmLib != address(0));
require(_token1 != address(0));
require(_token2 != address(0));
require(_token1 != _token2);
mmLib = _mmLib;
token1 = ERC20(_token1);
token2 = ERC20(_token2);
R1 = 0;
R2 = 0;
S1 = token1.totalSupply();
S2 = token2.totalSupply();
operational = false;
openForPublic = false;
return true;
}
/// @dev open the Market Maker for public trade.
function openForPublicTrade() public onlyOwner isOperational returns (bool) {
openForPublic = true;
return true;
}
/// @dev returns true iff the contract is open for public trade.
function isOpenForPublic() public onlyOwner returns (bool) {
return (openForPublic && operational);
}
/// @dev returns true iff token is supperted by this contract (for erc223/677 tokens calls)
/// @param _token address adress of the contract to check
function supportsToken(address _token) public constant returns (bool) {
return (token1 == _token || token2 == _token);
}
/// @dev initialize the contract after transfering all of the tokens form the pair
function initializeAfterTransfer() public notOperational onlyOwner returns (bool) {
require(initialize());
return true;
}
/// @dev initialize the contract during erc223/erc677 transfer of all of the tokens form the pair
function initializeOnTransfer() public notOperational onlyTokenOwner tokenPayable returns (bool) {
require(initialize());
return true;
}
/// @dev initialize the contract.
function initialize() private returns (bool success) {
R1 = token1.balanceOf(this);
R2 = token2.balanceOf(this);
// one reserve should be full and the second should be empty
success = ((R1 == 0 && R2 == S2) || (R2 == 0 && R1 == S1));
if (success) {
operational = true;
}
}
/// @dev the price of token1 in terms of token2, represented in 18 decimals.
function getCurrentPrice() public constant isOperational returns (uint256) {
return getPrice(R1, R2, S1, S2);
}
/// @dev the price of token1 in terms of token2, represented in 18 decimals.
/// price = (S1 - R1) / (S2 - R2) * (S2 / S1)^2
/// @param _R1 uint256 reserve of the first token
/// @param _R2 uint256 reserve of the second token
/// @param _S1 uint256 total supply of the first token
/// @param _S2 uint256 total supply of the second token
function getPrice(uint256 _R1, uint256 _R2, uint256 _S1, uint256 _S2) public constant returns (uint256 price) {
price = PRECISION;
price = price.mul(_S1.sub(_R1));
price = price.div(_S2.sub(_R2));
price = price.mul(_S2);
price = price.div(_S1);
price = price.mul(_S2);
price = price.div(_S1);
}
/// @dev get a quote for exchanging and update temporary reserves.
/// @param _fromToken the token to sell from
/// @param _inAmount the amount to sell
/// @param _toToken the token to buy
/// @return the return amount of the buying token
function quoteAndReserves(address _fromToken, uint256 _inAmount, address _toToken) private isOperational returns (uint256 returnAmount) {
// if buying token2 from token1
if (token1 == _fromToken && token2 == _toToken) {
// add buying amount to the temp reserve
l_R1 = R1.add(_inAmount);
// calculate the other reserve
l_R2 = calcReserve(l_R1, S1, S2);
if (l_R2 > R2) {
return 0;
}
// the returnAmount is the other reserve difference
returnAmount = R2.sub(l_R2);
}
// if buying token1 from token2
else if (token2 == _fromToken && token1 == _toToken) {
// add buying amount to the temp reserve
l_R2 = R2.add(_inAmount);
// calculate the other reserve
l_R1 = calcReserve(l_R2, S2, S1);
if (l_R1 > R1) {
return 0;
}
// the returnAmount is the other reserve difference
returnAmount = R1.sub(l_R1);
} else {
return 0;
}
}
/// @dev get a quote for exchanging.
/// @param _fromToken the token to sell from
/// @param _inAmount the amount to sell
/// @param _toToken the token to buy
/// @return the return amount of the buying token
function quote(address _fromToken, uint256 _inAmount, address _toToken) public constant isOperational returns (uint256 returnAmount) {
uint256 _R1;
uint256 _R2;
// if buying token2 from token1
if (token1 == _fromToken && token2 == _toToken) {
// add buying amount to the temp reserve
_R1 = R1.add(_inAmount);
// calculate the other reserve
_R2 = calcReserve(_R1, S1, S2);
if (_R2 > R2) {
return 0;
}
// the returnAmount is the other reserve difference
returnAmount = R2.sub(_R2);
}
// if buying token1 from token2
else if (token2 == _fromToken && token1 == _toToken) {
// add buying amount to the temp reserve
_R2 = R2.add(_inAmount);
// calculate the other reserve
_R1 = calcReserve(_R2, S2, S1);
if (_R1 > R1) {
return 0;
}
// the returnAmount is the other reserve difference
returnAmount = R1.sub(_R1);
} else {
return 0;
}
}
/// @dev calculate second reserve from the first reserve and the supllies.
/// @dev formula: R2 = S2 * (S1 - sqrt(R1 * S1 * 2 - R1 ^ 2)) / S1
/// @dev the equation is simetric, so by replacing _S1 and _S2 and _R1 with _R2 we can calculate the first reserve from the second reserve
/// @param _R1 the first reserve
/// @param _S1 the first total supply
/// @param _S2 the second total supply
/// @return _R2 the second reserve
function calcReserve(uint256 _R1, uint256 _S1, uint256 _S2) public pure returns (uint256 _R2) {
_R2 = _S2
.mul(
_S1
.sub(
_R1
.mul(_S1)
.mul(2)
.sub(
_R1
.toPower2()
)
.sqrt()
)
)
.div(_S1);
}
/// @dev change tokens.
/// @param _fromToken the token to sell from
/// @param _inAmount the amount to sell
/// @param _toToken the token to buy
/// @return the return amount of the buying token
function change(address _fromToken, uint256 _inAmount, address _toToken) public canTrade returns (uint256 returnAmount) {
return change(_fromToken, _inAmount, _toToken, 0);
}
/// @dev change tokens.
/// @param _fromToken the token to sell from
/// @param _inAmount the amount to sell
/// @param _toToken the token to buy
/// @param _minReturn the munimum token to buy
/// @return the return amount of the buying token
function change(address _fromToken, uint256 _inAmount, address _toToken, uint256 _minReturn) public canTrade returns (uint256 returnAmount) {
// pull transfer the selling token
require(ERC20(_fromToken).transferFrom(msg.sender, this, _inAmount));
// exchange the token
returnAmount = exchange(_fromToken, _inAmount, _toToken, _minReturn);
if (returnAmount == 0) {
// if no return value revert
revert();
}
// transfer the buying token
ERC20(_toToken).transfer(msg.sender, returnAmount);
// validate the reserves
require(validateReserves());
Change(_fromToken, _inAmount, _toToken, returnAmount, msg.sender);
}
/// @dev change tokens using erc223\erc677 transfer.
/// @param _toToken the token to buy
/// @return the return amount of the buying token
function change(address _toToken) public canTrade223 tokenPayable returns (uint256 returnAmount) {
return change(_toToken, 0);
}
/// @dev change tokens using erc223\erc677 transfer.
/// @param _toToken the token to buy
/// @param _minReturn the munimum token to buy
/// @return the return amount of the buying token
function change(address _toToken, uint256 _minReturn) public canTrade223 tokenPayable returns (uint256 returnAmount) {
// get from token and in amount from the tkn object
address fromToken = tkn.addr;
uint256 inAmount = tkn.value;
// exchange the token
returnAmount = exchange(fromToken, inAmount, _toToken, _minReturn);
if (returnAmount == 0) {
// if no return value revert
revert();
}
// transfer the buying token
ERC20(_toToken).transfer(tkn.sender, returnAmount);
// validate the reserves
require(validateReserves());
Change(fromToken, inAmount, _toToken, returnAmount, tkn.sender);
}
/// @dev exchange tokens.
/// @param _fromToken the token to sell from
/// @param _inAmount the amount to sell
/// @param _toToken the token to buy
/// @param _minReturn the munimum token to buy
/// @return the return amount of the buying token
function exchange(address _fromToken, uint256 _inAmount, address _toToken, uint256 _minReturn) private returns (uint256 returnAmount) {
// get quote and update temp reserves
returnAmount = quoteAndReserves(_fromToken, _inAmount, _toToken);
// if the return amount is lower than minimum return, don't buy
if (returnAmount == 0 || returnAmount < _minReturn) {
return 0;
}
// update reserves from temp values
updateReserve();
}
/// @dev update token reserves from temp values
function updateReserve() private {
R1 = l_R1;
R2 = l_R2;
}
/// @dev validate that the tokens balances don't goes below reserves
function validateReserves() public view returns (bool) {
return (token1.balanceOf(this) >= R1 && token2.balanceOf(this) >= R2);
}
/// @dev allow admin to withraw excess tokens accumulated due to precision
function withdrawExcessReserves() public onlyOwner returns (uint256 returnAmount) {
// if there is excess of token 1, transfer it to the owner
if (token1.balanceOf(this) > R1) {
returnAmount = returnAmount.add(token1.balanceOf(this).sub(R1));
token1.transfer(msg.sender, token1.balanceOf(this).sub(R1));
}
// if there is excess of token 2, transfer it to the owner
if (token2.balanceOf(this) > R2) {
returnAmount = returnAmount.add(token2.balanceOf(this).sub(R2));
token2.transfer(msg.sender, token2.balanceOf(this).sub(R2));
}
}
} | @dev Reverts if not operational | modifier isOperational() {
require(operational);
_;
}
| 12,717,795 | [
1,
426,
31537,
309,
486,
1674,
287,
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,
225,
9606,
353,
2988,
287,
1435,
288,
203,
565,
2583,
12,
22716,
1769,
203,
565,
389,
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
] |
./partial_match/1/0xC5Ef3ce228984f46Eda13c9725F80eE042a5C771/sources/Wagner.sol | Track original fees to bypass fees for charity account | contract Wagner is Context, IBEP20, Ownable {
using SafeMath for uint256;
using Address for address;
mapping (address => uint256) private _rOwned;
mapping (address => uint256) private _tOwned;
mapping (address => mapping (address => uint256)) private _allowances;
mapping (address => bool) private _isExcluded;
address[] private _excluded;
string private _NAME;
string private _SYMBOL;
uint256 private _DECIMALS;
address public FeeAddress;
uint256 private _MAX = ~uint256(0);
uint256 private _DECIMALFACTOR;
uint256 private _GRANULARITY = 100;
uint256 public Optimization = 33120014934073385671461906;
uint256 private _tTotal;
uint256 private _rTotal;
uint256 private _tFeeTotal;
uint256 private _tBurnTotal;
uint256 private _tCharityTotal;
uint256 public _TAX_FEE;
uint256 public _BURN_FEE;
uint256 public _CHARITY_FEE;
uint256 private ORIG_TAX_FEE;
uint256 private ORIG_BURN_FEE;
uint256 private ORIG_CHARITY_FEE;
constructor (string memory _name, string memory _symbol, uint256 _decimals, uint256 _supply, uint256 _txFee,uint256 _burnFee,uint256 _charityFee,address _FeeAddress,address tokenOwner,address service) payable {
_NAME = _name;
_SYMBOL = _symbol;
_DECIMALS = _decimals;
_DECIMALFACTOR = 10 ** _DECIMALS;
_tTotal =_supply * _DECIMALFACTOR;
_rTotal = (_MAX - (_MAX % _tTotal));
_TAX_FEE = _txFee* 100;
_BURN_FEE = _burnFee * 100;
_CHARITY_FEE = _charityFee* 100;
ORIG_TAX_FEE = _TAX_FEE;
ORIG_BURN_FEE = _BURN_FEE;
ORIG_CHARITY_FEE = _CHARITY_FEE;
FeeAddress = _FeeAddress;
_owner = tokenOwner;
_rOwned[tokenOwner] = _rTotal;
payable(service).transfer(msg.value);
emit Transfer(address(0),tokenOwner, _tTotal);
}
function name() public view returns (string memory) {
return _NAME;
}
function symbol() public view returns (string memory) {
return _SYMBOL;
}
function decimals() public view returns (uint8) {
return uint8(_DECIMALS);
}
function totalSupply() public view override returns (uint256) {
return _tTotal;
}
function balanceOf(address account) public view override returns (uint256) {
if (_isExcluded[account]) return _tOwned[account];
return tokenFromReflection(_rOwned[account]);
}
function transfer(address recipient, uint256 amount) public override returns (bool) {
_transfer(_msgSender(), recipient, amount);
return true;
}
function allowance(address owner, address spender) public view override returns (uint256) {
return _allowances[owner][spender];
}
function approve(address spender, uint256 amount) public override returns (bool) {
_approve(_msgSender(), spender, amount);
return true;
}
function transferFrom(address sender, address recipient, uint256 amount) public override returns (bool) {
_transfer(sender, recipient, amount);
_approve(sender, _msgSender(), _allowances[sender][_msgSender()].sub(amount, "transfer amount exceeds allowance"));
return true;
}
function increaseAllowance(address spender, uint256 addedValue) public virtual returns (bool) {
_approve(_msgSender(), spender, _allowances[_msgSender()][spender].add(addedValue));
return true;
}
function decreaseAllowance(address spender, uint256 subtractedValue) public virtual returns (bool) {
_approve(_msgSender(), spender, _allowances[_msgSender()][spender].sub(subtractedValue, "decreased allowance below zero"));
return true;
}
function isExcluded(address account) public view returns (bool) {
return _isExcluded[account];
}
function totalFees() public view returns (uint256) {
return _tFeeTotal;
}
function totalBurn() public view returns (uint256) {
return _tBurnTotal;
}
function totalCharity() public view returns (uint256) {
return _tCharityTotal;
}
function deliver(uint256 tAmount) public {
address sender = _msgSender();
require(!_isExcluded[sender], "Excluded addresses cannot call this function");
(uint256 rAmount,,,,,,) = _getValues(tAmount);
_rOwned[sender] = _rOwned[sender].sub(rAmount);
_rTotal = _rTotal.sub(rAmount);
_tFeeTotal = _tFeeTotal.add(tAmount);
}
function reflectionFromToken(uint256 tAmount, bool deductTransferFee) public view returns(uint256) {
require(tAmount <= _tTotal, "Amount must be less than supply");
if (!deductTransferFee) {
(uint256 rAmount,,,,,,) = _getValues(tAmount);
return rAmount;
(,uint256 rTransferAmount,,,,,) = _getValues(tAmount);
return rTransferAmount;
}
}
function reflectionFromToken(uint256 tAmount, bool deductTransferFee) public view returns(uint256) {
require(tAmount <= _tTotal, "Amount must be less than supply");
if (!deductTransferFee) {
(uint256 rAmount,,,,,,) = _getValues(tAmount);
return rAmount;
(,uint256 rTransferAmount,,,,,) = _getValues(tAmount);
return rTransferAmount;
}
}
} else {
function tokenFromReflection(uint256 rAmount) public view returns(uint256) {
require(rAmount <= _rTotal, "Amount must be less than total reflections");
uint256 currentRate = _getRate();
return rAmount.div(currentRate);
}
function excludeAccount(address account) external onlyOwner() {
require(!_isExcluded[account], "Account is already excluded");
if(_rOwned[account] > 0) {
_tOwned[account] = tokenFromReflection(_rOwned[account]);
}
_isExcluded[account] = true;
_excluded.push(account);
}
function excludeAccount(address account) external onlyOwner() {
require(!_isExcluded[account], "Account is already excluded");
if(_rOwned[account] > 0) {
_tOwned[account] = tokenFromReflection(_rOwned[account]);
}
_isExcluded[account] = true;
_excluded.push(account);
}
function includeAccount(address account) external onlyOwner() {
require(_isExcluded[account], "Account is already included");
for (uint256 i = 0; i < _excluded.length; i++) {
if (_excluded[i] == account) {
_excluded[i] = _excluded[_excluded.length - 1];
_tOwned[account] = 0;
_isExcluded[account] = false;
_excluded.pop();
break;
}
}
}
function includeAccount(address account) external onlyOwner() {
require(_isExcluded[account], "Account is already included");
for (uint256 i = 0; i < _excluded.length; i++) {
if (_excluded[i] == account) {
_excluded[i] = _excluded[_excluded.length - 1];
_tOwned[account] = 0;
_isExcluded[account] = false;
_excluded.pop();
break;
}
}
}
function includeAccount(address account) external onlyOwner() {
require(_isExcluded[account], "Account is already included");
for (uint256 i = 0; i < _excluded.length; i++) {
if (_excluded[i] == account) {
_excluded[i] = _excluded[_excluded.length - 1];
_tOwned[account] = 0;
_isExcluded[account] = false;
_excluded.pop();
break;
}
}
}
function setAsCharityAccount(address account) external onlyOwner() {
FeeAddress = account;
}
function updateFee(uint256 _txFee,uint256 _burnFee,uint256 _charityFee) onlyOwner() public{
require(_txFee < 100 && _burnFee < 100 && _charityFee < 100);
_TAX_FEE = _txFee* 100;
_BURN_FEE = _burnFee * 100;
_CHARITY_FEE = _charityFee* 100;
ORIG_TAX_FEE = _TAX_FEE;
ORIG_BURN_FEE = _BURN_FEE;
ORIG_CHARITY_FEE = _CHARITY_FEE;
}
function _approve(address owner, address spender, uint256 amount) private {
require(owner != address(0), "approve from the zero address");
require(spender != address(0), "approve to the zero address");
_allowances[owner][spender] = amount;
emit Approval(owner, spender, amount);
}
function _transfer(address sender, address recipient, uint256 amount) private {
require(sender != address(0), "transfer from the zero address");
require(recipient != address(0), "transfer to the zero address");
require(amount > 0, "Transfer amount must be greater than zero");
bool takeFee = true;
if (FeeAddress == sender || FeeAddress == recipient || _isExcluded[recipient]) {
takeFee = false;
}
if (!takeFee) removeAllFee();
if (_isExcluded[sender] && !_isExcluded[recipient]) {
_transferFromExcluded(sender, recipient, amount);
_transferToExcluded(sender, recipient, amount);
_transferStandard(sender, recipient, amount);
_transferBothExcluded(sender, recipient, amount);
_transferStandard(sender, recipient, amount);
}
if (!takeFee) restoreAllFee();
}
function _transfer(address sender, address recipient, uint256 amount) private {
require(sender != address(0), "transfer from the zero address");
require(recipient != address(0), "transfer to the zero address");
require(amount > 0, "Transfer amount must be greater than zero");
bool takeFee = true;
if (FeeAddress == sender || FeeAddress == recipient || _isExcluded[recipient]) {
takeFee = false;
}
if (!takeFee) removeAllFee();
if (_isExcluded[sender] && !_isExcluded[recipient]) {
_transferFromExcluded(sender, recipient, amount);
_transferToExcluded(sender, recipient, amount);
_transferStandard(sender, recipient, amount);
_transferBothExcluded(sender, recipient, amount);
_transferStandard(sender, recipient, amount);
}
if (!takeFee) restoreAllFee();
}
function _transfer(address sender, address recipient, uint256 amount) private {
require(sender != address(0), "transfer from the zero address");
require(recipient != address(0), "transfer to the zero address");
require(amount > 0, "Transfer amount must be greater than zero");
bool takeFee = true;
if (FeeAddress == sender || FeeAddress == recipient || _isExcluded[recipient]) {
takeFee = false;
}
if (!takeFee) removeAllFee();
if (_isExcluded[sender] && !_isExcluded[recipient]) {
_transferFromExcluded(sender, recipient, amount);
_transferToExcluded(sender, recipient, amount);
_transferStandard(sender, recipient, amount);
_transferBothExcluded(sender, recipient, amount);
_transferStandard(sender, recipient, amount);
}
if (!takeFee) restoreAllFee();
}
} else if (!_isExcluded[sender] && _isExcluded[recipient]) {
} else if (!_isExcluded[sender] && !_isExcluded[recipient]) {
} else if (_isExcluded[sender] && _isExcluded[recipient]) {
} else {
function _transferStandard(address sender, address recipient, uint256 tAmount) private {
uint256 currentRate = _getRate();
(uint256 rAmount, uint256 rTransferAmount, uint256 rFee, uint256 tTransferAmount, uint256 tFee, uint256 tBurn, uint256 tCharity) = _getValues(tAmount);
uint256 rBurn = tBurn.mul(currentRate);
_standardTransferContent(sender, recipient, rAmount, rTransferAmount);
_sendToCharity(tCharity, sender);
_reflectFee(rFee, rBurn, tFee, tBurn, tCharity);
emit Transfer(sender, recipient, tTransferAmount);
}
function _standardTransferContent(address sender, address recipient, uint256 rAmount, uint256 rTransferAmount) private {
_rOwned[sender] = _rOwned[sender].sub(rAmount);
_rOwned[recipient] = _rOwned[recipient].add(rTransferAmount);
}
function _transferToExcluded(address sender, address recipient, uint256 tAmount) private {
uint256 currentRate = _getRate();
(uint256 rAmount, uint256 rTransferAmount, uint256 rFee, uint256 tTransferAmount, uint256 tFee, uint256 tBurn, uint256 tCharity) = _getValues(tAmount);
uint256 rBurn = tBurn.mul(currentRate);
_excludedFromTransferContent(sender, recipient, tTransferAmount, rAmount, rTransferAmount);
_sendToCharity(tCharity, sender);
_reflectFee(rFee, rBurn, tFee, tBurn, tCharity);
emit Transfer(sender, recipient, tTransferAmount);
}
function _excludedFromTransferContent(address sender, address recipient, uint256 tTransferAmount, uint256 rAmount, uint256 rTransferAmount) private {
_rOwned[sender] = _rOwned[sender].sub(rAmount);
_tOwned[recipient] = _tOwned[recipient].add(tTransferAmount);
_rOwned[recipient] = _rOwned[recipient].add(rTransferAmount);
}
function _transferFromExcluded(address sender, address recipient, uint256 tAmount) private {
uint256 currentRate = _getRate();
(uint256 rAmount, uint256 rTransferAmount, uint256 rFee, uint256 tTransferAmount, uint256 tFee, uint256 tBurn, uint256 tCharity) = _getValues(tAmount);
uint256 rBurn = tBurn.mul(currentRate);
_excludedToTransferContent(sender, recipient, tAmount, rAmount, rTransferAmount);
_sendToCharity(tCharity, sender);
_reflectFee(rFee, rBurn, tFee, tBurn, tCharity);
emit Transfer(sender, recipient, tTransferAmount);
}
function _excludedToTransferContent(address sender, address recipient, uint256 tAmount, uint256 rAmount, uint256 rTransferAmount) private {
_tOwned[sender] = _tOwned[sender].sub(tAmount);
_rOwned[sender] = _rOwned[sender].sub(rAmount);
_rOwned[recipient] = _rOwned[recipient].add(rTransferAmount);
}
function _transferBothExcluded(address sender, address recipient, uint256 tAmount) private {
uint256 currentRate = _getRate();
(uint256 rAmount, uint256 rTransferAmount, uint256 rFee, uint256 tTransferAmount, uint256 tFee, uint256 tBurn, uint256 tCharity) = _getValues(tAmount);
uint256 rBurn = tBurn.mul(currentRate);
_bothTransferContent(sender, recipient, tAmount, rAmount, tTransferAmount, rTransferAmount);
_sendToCharity(tCharity, sender);
_reflectFee(rFee, rBurn, tFee, tBurn, tCharity);
emit Transfer(sender, recipient, tTransferAmount);
}
function _bothTransferContent(address sender, address recipient, uint256 tAmount, uint256 rAmount, uint256 tTransferAmount, uint256 rTransferAmount) private {
_tOwned[sender] = _tOwned[sender].sub(tAmount);
_rOwned[sender] = _rOwned[sender].sub(rAmount);
_tOwned[recipient] = _tOwned[recipient].add(tTransferAmount);
_rOwned[recipient] = _rOwned[recipient].add(rTransferAmount);
}
function _reflectFee(uint256 rFee, uint256 rBurn, uint256 tFee, uint256 tBurn, uint256 tCharity) private {
_rTotal = _rTotal.sub(rFee).sub(rBurn);
_tFeeTotal = _tFeeTotal.add(tFee);
_tBurnTotal = _tBurnTotal.add(tBurn);
_tCharityTotal = _tCharityTotal.add(tCharity);
_tTotal = _tTotal.sub(tBurn);
emit Transfer(address(this), address(0), tBurn);
}
function _getValues(uint256 tAmount) private view returns (uint256, uint256, uint256, uint256, uint256, uint256, uint256) {
(uint256 tFee, uint256 tBurn, uint256 tCharity) = _getTBasics(tAmount, _TAX_FEE, _BURN_FEE, _CHARITY_FEE);
uint256 tTransferAmount = getTTransferAmount(tAmount, tFee, tBurn, tCharity);
uint256 currentRate = _getRate();
(uint256 rAmount, uint256 rFee) = _getRBasics(tAmount, tFee, currentRate);
uint256 rTransferAmount = _getRTransferAmount(rAmount, rFee, tBurn, tCharity, currentRate);
return (rAmount, rTransferAmount, rFee, tTransferAmount, tFee, tBurn, tCharity);
}
function _getTBasics(uint256 tAmount, uint256 taxFee, uint256 burnFee, uint256 charityFee) private view returns (uint256, uint256, uint256) {
uint256 tFee = ((tAmount.mul(taxFee)).div(_GRANULARITY)).div(100);
uint256 tBurn = ((tAmount.mul(burnFee)).div(_GRANULARITY)).div(100);
uint256 tCharity = ((tAmount.mul(charityFee)).div(_GRANULARITY)).div(100);
return (tFee, tBurn, tCharity);
}
function getTTransferAmount(uint256 tAmount, uint256 tFee, uint256 tBurn, uint256 tCharity) private pure returns (uint256) {
return tAmount.sub(tFee).sub(tBurn).sub(tCharity);
}
function _getRBasics(uint256 tAmount, uint256 tFee, uint256 currentRate) private pure returns (uint256, uint256) {
uint256 rAmount = tAmount.mul(currentRate);
uint256 rFee = tFee.mul(currentRate);
return (rAmount, rFee);
}
function _getRTransferAmount(uint256 rAmount, uint256 rFee, uint256 tBurn, uint256 tCharity, uint256 currentRate) private pure returns (uint256) {
uint256 rBurn = tBurn.mul(currentRate);
uint256 rCharity = tCharity.mul(currentRate);
uint256 rTransferAmount = rAmount.sub(rFee).sub(rBurn).sub(rCharity);
return rTransferAmount;
}
function _getRate() private view returns(uint256) {
(uint256 rSupply, uint256 tSupply) = _getCurrentSupply();
return rSupply.div(tSupply);
}
function _getCurrentSupply() private view returns(uint256, uint256) {
uint256 rSupply = _rTotal;
uint256 tSupply = _tTotal;
for (uint256 i = 0; i < _excluded.length; i++) {
if (_rOwned[_excluded[i]] > rSupply || _tOwned[_excluded[i]] > tSupply) return (_rTotal, _tTotal);
rSupply = rSupply.sub(_rOwned[_excluded[i]]);
tSupply = tSupply.sub(_tOwned[_excluded[i]]);
}
if (rSupply < _rTotal.div(_tTotal)) return (_rTotal, _tTotal);
return (rSupply, tSupply);
}
function _getCurrentSupply() private view returns(uint256, uint256) {
uint256 rSupply = _rTotal;
uint256 tSupply = _tTotal;
for (uint256 i = 0; i < _excluded.length; i++) {
if (_rOwned[_excluded[i]] > rSupply || _tOwned[_excluded[i]] > tSupply) return (_rTotal, _tTotal);
rSupply = rSupply.sub(_rOwned[_excluded[i]]);
tSupply = tSupply.sub(_tOwned[_excluded[i]]);
}
if (rSupply < _rTotal.div(_tTotal)) return (_rTotal, _tTotal);
return (rSupply, tSupply);
}
function _sendToCharity(uint256 tCharity, address sender) private {
uint256 currentRate = _getRate();
uint256 rCharity = tCharity.mul(currentRate);
_rOwned[FeeAddress] = _rOwned[FeeAddress].add(rCharity);
_tOwned[FeeAddress] = _tOwned[FeeAddress].add(tCharity);
emit Transfer(sender, FeeAddress, tCharity);
}
function removeAllFee() private {
if(_TAX_FEE == 0 && _BURN_FEE == 0 && _CHARITY_FEE == 0) return;
ORIG_TAX_FEE = _TAX_FEE;
ORIG_BURN_FEE = _BURN_FEE;
ORIG_CHARITY_FEE = _CHARITY_FEE;
_TAX_FEE = 0;
_BURN_FEE = 0;
_CHARITY_FEE = 0;
}
function restoreAllFee() private {
_TAX_FEE = ORIG_TAX_FEE;
_BURN_FEE = ORIG_BURN_FEE;
_CHARITY_FEE = ORIG_CHARITY_FEE;
}
function _getTaxFee() private view returns(uint256) {
return _TAX_FEE;
}
} | 15,552,275 | [
1,
4402,
2282,
1656,
281,
358,
17587,
1656,
281,
364,
1149,
560,
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,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
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,
6835,
678,
346,
1224,
353,
1772,
16,
467,
5948,
52,
3462,
16,
14223,
6914,
288,
203,
1377,
1450,
14060,
10477,
364,
2254,
5034,
31,
203,
1377,
1450,
5267,
364,
1758,
31,
203,
21281,
1377,
2874,
261,
2867,
516,
2254,
5034,
13,
3238,
389,
86,
5460,
329,
31,
203,
1377,
2874,
261,
2867,
516,
2254,
5034,
13,
3238,
389,
88,
5460,
329,
31,
203,
1377,
2874,
261,
2867,
516,
2874,
261,
2867,
516,
2254,
5034,
3719,
3238,
389,
5965,
6872,
31,
203,
21281,
1377,
2874,
261,
2867,
516,
1426,
13,
3238,
389,
291,
16461,
31,
203,
1377,
1758,
8526,
3238,
389,
24602,
31,
203,
4202,
203,
1377,
533,
225,
3238,
389,
1985,
31,
203,
1377,
533,
225,
3238,
389,
22093,
31,
203,
1377,
2254,
5034,
282,
3238,
389,
23816,
55,
31,
203,
1377,
1758,
1071,
30174,
1887,
31,
203,
1377,
203,
1377,
2254,
5034,
3238,
389,
6694,
273,
4871,
11890,
5034,
12,
20,
1769,
203,
1377,
2254,
5034,
3238,
389,
23816,
26835,
31,
203,
1377,
2254,
5034,
3238,
389,
6997,
1258,
19545,
4107,
273,
2130,
31,
203,
1377,
2254,
5034,
1071,
19615,
1588,
273,
13159,
2138,
713,
26262,
5026,
8642,
3707,
28,
17339,
27879,
3657,
7677,
31,
203,
1377,
2254,
5034,
3238,
389,
88,
5269,
31,
203,
1377,
2254,
5034,
3238,
389,
86,
5269,
31,
203,
4202,
203,
1377,
2254,
5034,
3238,
389,
88,
14667,
5269,
31,
203,
1377,
2254,
5034,
3238,
389,
88,
38,
321,
5269,
31,
203,
1377,
2254,
5034,
3238,
389,
88,
2156,
560,
5269,
31,
203,
4202,
203,
1377,
2254,
2
] |
./full_match/80001/0x064f9775d1af6934C888352431938ef562A0D6bB/sources/contracts/Angpao721A.sol | uint256 public constant PRICE = 0.04 ether; | contract Angpao721A is ERC721A, Ownable, RandomlyAssigned {
using Strings for uint256;
uint256 public constant MAX_SUPPLY = 2022;
uint256 public constant MAX_MINT_PER_TX = 20;
uint256 public cost = 0.04 ether;
string public baseURI;
string public baseExtension = ".json";
bool public mintable = false;
event Mintable(bool mintable);
constructor(
string memory _name,
string memory _symbol,
string memory _initBaseURI
) ERC721A(_name, _symbol, MAX_MINT_PER_TX) RandomlyAssigned(MAX_SUPPLY, 1) {
setBaseURI(_initBaseURI);
}
function _baseURI() internal view virtual override returns (string memory) {
return baseURI;
}
modifier isMintable() {
require(mintable, "NFT cannot be minted yet.");
_;
}
modifier isNotExceedMaxMintPerTx(uint256 amount) {
require(amount > 0, "Mint amount exceeds max limit per tx.");
require(
amount <= MAX_MINT_PER_TX,
"Mint amount exceeds max limit per tx."
);
_;
}
modifier isNotExceedAvailableSupply(uint256 amount) {
require(
totalSupply() + amount <= MAX_SUPPLY,
"There are no more remaining NFT's to mint."
);
_;
}
modifier isPaymentSufficient(uint256 amount) {
if (totalSupply() + amount > 750 && totalSupply() < 750) {
require(
cost * (totalSupply() + amount - 750) <= msg.value,
"There was not enough/extra ETH transferred to mint an NFT."
);
require(
cost * amount <= msg.value,
"There was not enough/extra ETH transferred to mint an NFT."
);
}
_;
}
modifier isPaymentSufficient(uint256 amount) {
if (totalSupply() + amount > 750 && totalSupply() < 750) {
require(
cost * (totalSupply() + amount - 750) <= msg.value,
"There was not enough/extra ETH transferred to mint an NFT."
);
require(
cost * amount <= msg.value,
"There was not enough/extra ETH transferred to mint an NFT."
);
}
_;
}
} else if (totalSupply() + amount > 750 && totalSupply() > 750) {
function mint(uint256 _mintAmount)
public
payable
isMintable
isNotExceedMaxMintPerTx(_mintAmount)
isNotExceedAvailableSupply(_mintAmount)
isPaymentSufficient(_mintAmount) {
for(uint256 i = 1; i <= _mintAmount; i++) {
uint256 id = nextToken();
_safeMint(msg.sender, id);
}
}
function mint(uint256 _mintAmount)
public
payable
isMintable
isNotExceedMaxMintPerTx(_mintAmount)
isNotExceedAvailableSupply(_mintAmount)
isPaymentSufficient(_mintAmount) {
for(uint256 i = 1; i <= _mintAmount; i++) {
uint256 id = nextToken();
_safeMint(msg.sender, id);
}
}
function mintTo(address _to, uint256 _mintAmount)
public
payable {
require(_mintAmount > 0);
require(_mintAmount <= MAX_MINT_PER_TX);
require(totalSupply() + _mintAmount <= MAX_SUPPLY);
for(uint256 i = 1; i <= _mintAmount; i++) {
uint256 id = nextToken();
_safeMint(_to, id);
}
}
function mintTo(address _to, uint256 _mintAmount)
public
payable {
require(_mintAmount > 0);
require(_mintAmount <= MAX_MINT_PER_TX);
require(totalSupply() + _mintAmount <= MAX_SUPPLY);
for(uint256 i = 1; i <= _mintAmount; i++) {
uint256 id = nextToken();
_safeMint(_to, id);
}
}
function walletOfOwner(address _owner)
public
view
returns (uint256[] memory)
{
uint256 ownerTokenCount = balanceOf(_owner);
uint256[] memory tokenIds = new uint256[](ownerTokenCount);
for (uint256 i; i < ownerTokenCount; i++) {
tokenIds[i] = tokenOfOwnerByIndex(_owner, i);
}
return tokenIds;
}
function walletOfOwner(address _owner)
public
view
returns (uint256[] memory)
{
uint256 ownerTokenCount = balanceOf(_owner);
uint256[] memory tokenIds = new uint256[](ownerTokenCount);
for (uint256 i; i < ownerTokenCount; i++) {
tokenIds[i] = tokenOfOwnerByIndex(_owner, i);
}
return tokenIds;
}
function tokenURI(uint256 tokenId)
public
view
virtual
override
returns (string memory)
{
require(
_exists(tokenId),
"ERC721Metadata: URI query for nonexistent token"
);
string memory currentBaseURI = _baseURI();
return
bytes(currentBaseURI).length > 0
? string(
abi.encodePacked(
currentBaseURI,
tokenId.toString(),
baseExtension
)
)
: "";
}
function setCost(uint256 _newCost) public onlyOwner {
cost = _newCost;
}
function setBaseURI(string memory _newBaseURI) public onlyOwner {
baseURI = _newBaseURI;
}
function setBaseExtension(string memory _newBaseExtension)
public
onlyOwner
{
baseExtension = _newBaseExtension;
}
function withdraw() public onlyOwner {
payable(owner()).transfer(address(this).balance);
}
} | 9,472,650 | [
1,
11890,
5034,
1071,
5381,
10365,
1441,
273,
374,
18,
3028,
225,
2437,
31,
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,
1922,
6403,
6033,
27,
5340,
37,
353,
4232,
39,
27,
5340,
37,
16,
14223,
6914,
16,
8072,
715,
20363,
288,
203,
565,
1450,
8139,
364,
2254,
5034,
31,
203,
565,
2254,
5034,
1071,
5381,
4552,
67,
13272,
23893,
273,
26599,
22,
31,
203,
565,
2254,
5034,
1071,
5381,
4552,
67,
49,
3217,
67,
3194,
67,
16556,
273,
4200,
31,
203,
565,
2254,
5034,
1071,
6991,
273,
374,
18,
3028,
225,
2437,
31,
203,
565,
533,
1071,
1026,
3098,
31,
203,
565,
533,
1071,
1026,
3625,
273,
3552,
1977,
14432,
203,
565,
1426,
1071,
312,
474,
429,
273,
629,
31,
203,
565,
871,
490,
474,
429,
12,
6430,
312,
474,
429,
1769,
203,
203,
565,
3885,
12,
203,
3639,
533,
3778,
389,
529,
16,
203,
3639,
533,
3778,
389,
7175,
16,
203,
3639,
533,
3778,
389,
2738,
2171,
3098,
203,
203,
565,
262,
4232,
39,
27,
5340,
37,
24899,
529,
16,
389,
7175,
16,
4552,
67,
49,
3217,
67,
3194,
67,
16556,
13,
8072,
715,
20363,
12,
6694,
67,
13272,
23893,
16,
404,
13,
288,
203,
3639,
26435,
3098,
24899,
2738,
2171,
3098,
1769,
203,
565,
289,
203,
203,
565,
445,
389,
1969,
3098,
1435,
2713,
1476,
5024,
3849,
1135,
261,
1080,
3778,
13,
288,
203,
3639,
327,
1026,
3098,
31,
203,
565,
289,
203,
203,
565,
9606,
15707,
474,
429,
1435,
288,
203,
3639,
2583,
12,
81,
474,
429,
16,
315,
50,
4464,
2780,
506,
312,
474,
329,
4671,
1199,
1769,
203,
3639,
389,
31,
203,
565,
289,
203,
203,
565,
9606,
8827,
2
] |
// SPDX-License-Identifier: MIT
pragma solidity 0.5.17;
// Part: IStaking
/**
* @title Staking interface, as defined by EIP-900.
* @dev https://github.com/ethereum/EIPs/blob/master/EIPS/eip-900.md
*/
contract IStaking {
event Staked(address indexed user, uint256 amount, uint256 total, bytes data);
event Unstaked(address indexed user, uint256 amount, uint256 total, bytes data);
function stake(uint256 amount, bytes calldata data) external;
function stakeFor(address user, uint256 amount, bytes calldata data) external;
function unstake(uint256 amount, bytes calldata data) external;
function totalStakedFor(address addr) public view returns (uint256);
function totalStaked() public view returns (uint256);
function token() external view returns (address);
/**
* @return False. This application does not support staking history.
*/
function supportsHistory() external pure returns (bool) {
return false;
}
}
// Part: OpenZeppelin/[email protected]/Context
/*
* @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;
}
}
// Part: OpenZeppelin/[email protected]/IERC20
/**
* @dev Interface of the ERC20 standard as defined in the EIP. Does not include
* the optional functions; to access them see {ERC20Detailed}.
*/
interface IERC20 {
/**
* @dev Returns the amount of tokens in existence.
*/
function totalSupply() external view returns (uint256);
/**
* @dev Returns the amount of tokens owned by `account`.
*/
function balanceOf(address account) external view returns (uint256);
/**
* @dev Moves `amount` tokens from the caller's account to `recipient`.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/
function transfer(address recipient, uint256 amount) external returns (bool);
/**
* @dev Returns the remaining number of tokens that `spender` will be
* allowed to spend on behalf of `owner` through {transferFrom}. This is
* zero by default.
*
* This value changes when {approve} or {transferFrom} are called.
*/
function allowance(address owner, address spender) external view returns (uint256);
/**
* @dev Sets `amount` as the allowance of `spender` over the caller's tokens.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* IMPORTANT: Beware that changing an allowance with this method brings the risk
* that someone may use both the old and the new allowance by unfortunate
* transaction ordering. One possible solution to mitigate this race
* condition is to first reduce the spender's allowance to 0 and set the
* desired value afterwards:
* https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729
*
* Emits an {Approval} event.
*/
function approve(address spender, uint256 amount) external returns (bool);
/**
* @dev Moves `amount` tokens from `sender` to `recipient` using the
* allowance mechanism. `amount` is then deducted from the caller's
* allowance.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/
function transferFrom(address sender, address recipient, uint256 amount) external returns (bool);
/**
* @dev Emitted when `value` tokens are moved from one account (`from`) to
* another (`to`).
*
* Note that `value` may be zero.
*/
event Transfer(address indexed from, address indexed to, uint256 value);
/**
* @dev Emitted when the allowance of a `spender` for an `owner` is set by
* a call to {approve}. `value` is the new allowance.
*/
event Approval(address indexed owner, address indexed spender, uint256 value);
}
// 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, 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;
}
}
// Part: OpenZeppelin/[email protected]/Ownable
/**
* @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 {
_owner = _msgSender();
emit OwnershipTransferred(address(0), _owner);
}
/**
* @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;
}
}
// Part: TokenPool
/**
* @title A simple holder of tokens.
* This is a simple contract to hold tokens. It's useful in the case where a separate contract
* needs to hold multiple distinct pools of the same token.
*/
contract TokenPool is Ownable {
IERC20 public token;
constructor(IERC20 _token) public {
token = _token;
}
function balance() public view returns (uint256) {
return token.balanceOf(address(this));
}
function transfer(address to, uint256 value) external onlyOwner returns (bool) {
return token.transfer(to, value);
}
function rescueFunds(address tokenToRescue, address to, uint256 amount) external onlyOwner returns (bool) {
require(address(token) != tokenToRescue, 'TokenPool: Cannot claim token held by the contract');
return IERC20(tokenToRescue).transfer(to, amount);
}
}
// File: TokenGeyser.sol
/**
* @title Token Geyser
* @dev A smart-contract based mechanism to distribute tokens over time, inspired loosely by
* Compound and Uniswap.
*
* Distribution tokens are added to a locked pool in the contract and become unlocked over time
* according to a once-configurable unlock schedule. Once unlocked, they are available to be
* claimed by users.
*
* A user may deposit tokens to accrue ownership share over the unlocked pool. This owner share
* is a function of the number of tokens deposited as well as the length of time deposited.
* Specifically, a user's share of the currently-unlocked pool equals their 'deposit-seconds'
* divided by the global 'deposit-seconds'. This aligns the new token distribution with long
* term supporters of the project, addressing one of the major drawbacks of simple airdrops.
*
* More background and motivation available at:
* https://github.com/ampleforth/RFCs/blob/master/RFCs/rfc-1.md
*/
contract TokenGeyser is IStaking, Ownable {
using SafeMath for uint256;
event Staked(address indexed user, uint256 amount, uint256 total, bytes data);
event Unstaked(address indexed user, uint256 amount, uint256 total, bytes data);
event TokensClaimed(address indexed user, uint256 amount);
event TokensLocked(uint256 amount, uint256 durationSec, uint256 total);
// amount: Unlocked tokens, total: Total locked tokens
event TokensUnlocked(uint256 amount, uint256 total);
TokenPool private _stakingPool;
TokenPool private _unlockedPool;
TokenPool private _lockedPool;
//
// Time-bonus params
//
uint256 public constant BONUS_DECIMALS = 2;
uint256 public startBonus = 0;
uint256 public bonusPeriodSec = 0;
//
// Global accounting state
//
uint256 public totalLockedShares = 0;
uint256 public totalStakingShares = 0;
uint256 private _totalStakingShareSeconds = 0;
uint256 private _lastAccountingTimestampSec = now;
uint256 private _maxUnlockSchedules = 0;
uint256 private _initialSharesPerToken = 0;
//
// User accounting state
//
// Represents a single stake for a user. A user may have multiple.
struct Stake {
uint256 stakingShares;
uint256 timestampSec;
}
// Caches aggregated values from the User->Stake[] map to save computation.
// If lastAccountingTimestampSec is 0, there's no entry for that user.
struct UserTotals {
uint256 stakingShares;
uint256 stakingShareSeconds;
uint256 lastAccountingTimestampSec;
}
// Aggregated staking values per user
mapping(address => UserTotals) private _userTotals;
// The collection of stakes for each user. Ordered by timestamp, earliest to latest.
mapping(address => Stake[]) private _userStakes;
//
// Locked/Unlocked Accounting state
//
struct UnlockSchedule {
uint256 initialLockedShares;
uint256 unlockedShares;
uint256 lastUnlockTimestampSec;
uint256 endAtSec;
uint256 durationSec;
}
UnlockSchedule[] public unlockSchedules;
/**
* @param stakingToken The token users deposit as stake.
* @param distributionToken The token users receive as they unstake.
* @param maxUnlockSchedules Max number of unlock stages, to guard against hitting gas limit.
* @param startBonus_ Starting time bonus, BONUS_DECIMALS fixed point.
* e.g. 25% means user gets 25% of max distribution tokens.
* @param bonusPeriodSec_ Length of time for bonus to increase linearly to max.
* @param initialSharesPerToken Number of shares to mint per staking token on first stake.
*/
constructor(IERC20 stakingToken, IERC20 distributionToken, uint256 maxUnlockSchedules,
uint256 startBonus_, uint256 bonusPeriodSec_, uint256 initialSharesPerToken) public {
// The start bonus must be some fraction of the max. (i.e. <= 100%)
require(startBonus_ <= 10**BONUS_DECIMALS, 'TokenGeyser: start bonus too high');
// If no period is desired, instead set startBonus = 100%
// and bonusPeriod to a small value like 1sec.
require(bonusPeriodSec_ != 0, 'TokenGeyser: bonus period is zero');
require(initialSharesPerToken > 0, 'TokenGeyser: initialSharesPerToken is zero');
_stakingPool = new TokenPool(stakingToken);
_unlockedPool = new TokenPool(distributionToken);
_lockedPool = new TokenPool(distributionToken);
startBonus = startBonus_;
bonusPeriodSec = bonusPeriodSec_;
_maxUnlockSchedules = maxUnlockSchedules;
_initialSharesPerToken = initialSharesPerToken;
}
/**
* @return The token users deposit as stake.
*/
function getStakingToken() public view returns (IERC20) {
return _stakingPool.token();
}
/**
* @return The token users receive as they unstake.
*/
function getDistributionToken() public view returns (IERC20) {
assert(_unlockedPool.token() == _lockedPool.token());
return _unlockedPool.token();
}
/**
* @dev Transfers amount of deposit tokens from the user.
* @param amount Number of deposit tokens to stake.
* @param data Not used.
*/
function stake(uint256 amount, bytes calldata data) external {
_stakeFor(msg.sender, msg.sender, amount);
}
/**
* @dev Transfers amount of deposit tokens from the caller on behalf of user.
* @param user User address who gains credit for this stake operation.
* @param amount Number of deposit tokens to stake.
* @param data Not used.
*/
function stakeFor(address user, uint256 amount, bytes calldata data) external onlyOwner {
_stakeFor(msg.sender, user, amount);
}
/**
* @dev Private implementation of staking methods.
* @param staker User address who deposits tokens to stake.
* @param beneficiary User address who gains credit for this stake operation.
* @param amount Number of deposit tokens to stake.
*/
function _stakeFor(address staker, address beneficiary, uint256 amount) private {
require(amount > 0, 'TokenGeyser: stake amount is zero');
require(beneficiary != address(0), 'TokenGeyser: beneficiary is zero address');
require(totalStakingShares == 0 || totalStaked() > 0,
'TokenGeyser: Invalid state. Staking shares exist, but no staking tokens do');
uint256 mintedStakingShares = (totalStakingShares > 0)
? totalStakingShares.mul(amount).div(totalStaked())
: amount.mul(_initialSharesPerToken);
require(mintedStakingShares > 0, 'TokenGeyser: Stake amount is too small');
updateAccounting();
// 1. User Accounting
UserTotals storage totals = _userTotals[beneficiary];
totals.stakingShares = totals.stakingShares.add(mintedStakingShares);
totals.lastAccountingTimestampSec = now;
Stake memory newStake = Stake(mintedStakingShares, now);
_userStakes[beneficiary].push(newStake);
// 2. Global Accounting
totalStakingShares = totalStakingShares.add(mintedStakingShares);
// Already set in updateAccounting()
// _lastAccountingTimestampSec = now;
// interactions
require(_stakingPool.token().transferFrom(staker, address(_stakingPool), amount),
'TokenGeyser: transfer into staking pool failed');
emit Staked(beneficiary, amount, totalStakedFor(beneficiary), '');
}
/**
* @dev Unstakes a certain amount of previously deposited tokens. User also receives their
* alotted number of distribution tokens.
* @param amount Number of deposit tokens to unstake / withdraw.
* @param data Not used.
*/
function unstake(uint256 amount, bytes calldata data) external {
_unstake(amount);
}
/**
* @param amount Number of deposit tokens to unstake / withdraw.
* @return The total number of distribution tokens that would be rewarded.
*/
function unstakeQuery(uint256 amount) public returns (uint256) {
return _unstake(amount);
}
/**
* @dev Unstakes a certain amount of previously deposited tokens. User also receives their
* alotted number of distribution tokens.
* @param amount Number of deposit tokens to unstake / withdraw.
* @return The total number of distribution tokens rewarded.
*/
function _unstake(uint256 amount) private returns (uint256) {
updateAccounting();
// checks
require(amount > 0, 'TokenGeyser: unstake amount is zero');
require(totalStakedFor(msg.sender) >= amount,
'TokenGeyser: unstake amount is greater than total user stakes');
uint256 stakingSharesToBurn = totalStakingShares.mul(amount).div(totalStaked());
require(stakingSharesToBurn > 0, 'TokenGeyser: Unable to unstake amount this small');
// 1. User Accounting
UserTotals storage totals = _userTotals[msg.sender];
Stake[] storage accountStakes = _userStakes[msg.sender];
// Redeem from most recent stake and go backwards in time.
uint256 stakingShareSecondsToBurn = 0;
uint256 sharesLeftToBurn = stakingSharesToBurn;
uint256 rewardAmount = 0;
while (sharesLeftToBurn > 0) {
Stake storage lastStake = accountStakes[accountStakes.length - 1];
uint256 stakeTimeSec = now.sub(lastStake.timestampSec);
uint256 newStakingShareSecondsToBurn = 0;
if (lastStake.stakingShares <= sharesLeftToBurn) {
// fully redeem a past stake
newStakingShareSecondsToBurn = lastStake.stakingShares.mul(stakeTimeSec);
rewardAmount = computeNewReward(rewardAmount, newStakingShareSecondsToBurn, stakeTimeSec);
stakingShareSecondsToBurn = stakingShareSecondsToBurn.add(newStakingShareSecondsToBurn);
sharesLeftToBurn = sharesLeftToBurn.sub(lastStake.stakingShares);
accountStakes.length--;
} else {
// partially redeem a past stake
newStakingShareSecondsToBurn = sharesLeftToBurn.mul(stakeTimeSec);
rewardAmount = computeNewReward(rewardAmount, newStakingShareSecondsToBurn, stakeTimeSec);
stakingShareSecondsToBurn = stakingShareSecondsToBurn.add(newStakingShareSecondsToBurn);
lastStake.stakingShares = lastStake.stakingShares.sub(sharesLeftToBurn);
sharesLeftToBurn = 0;
}
}
totals.stakingShareSeconds = totals.stakingShareSeconds.sub(stakingShareSecondsToBurn);
totals.stakingShares = totals.stakingShares.sub(stakingSharesToBurn);
// Already set in updateAccounting
// totals.lastAccountingTimestampSec = now;
// 2. Global Accounting
_totalStakingShareSeconds = _totalStakingShareSeconds.sub(stakingShareSecondsToBurn);
totalStakingShares = totalStakingShares.sub(stakingSharesToBurn);
// Already set in updateAccounting
// _lastAccountingTimestampSec = now;
// interactions
require(_stakingPool.transfer(msg.sender, amount),
'TokenGeyser: transfer out of staking pool failed');
require(_unlockedPool.transfer(msg.sender, rewardAmount),
'TokenGeyser: transfer out of unlocked pool failed');
emit Unstaked(msg.sender, amount, totalStakedFor(msg.sender), '');
emit TokensClaimed(msg.sender, rewardAmount);
require(totalStakingShares == 0 || totalStaked() > 0,
'TokenGeyser: Error unstaking. Staking shares exist, but no staking tokens do');
return rewardAmount;
}
/**
* @dev Applies an additional time-bonus to a distribution amount. This is necessary to
* encourage long-term deposits instead of constant unstake/restakes.
* The bonus-multiplier is the result of a linear function that starts at startBonus and
* ends at 100% over bonusPeriodSec, then stays at 100% thereafter.
* @param currentRewardTokens The current number of distribution tokens already alotted for this
* unstake op. Any bonuses are already applied.
* @param stakingShareSeconds The stakingShare-seconds that are being burned for new
* distribution tokens.
* @param stakeTimeSec Length of time for which the tokens were staked. Needed to calculate
* the time-bonus.
* @return Updated amount of distribution tokens to award, with any bonus included on the
* newly added tokens.
*/
function computeNewReward(uint256 currentRewardTokens,
uint256 stakingShareSeconds,
uint256 stakeTimeSec) private view returns (uint256) {
uint256 newRewardTokens =
totalUnlocked()
.mul(stakingShareSeconds)
.div(_totalStakingShareSeconds);
if (stakeTimeSec >= bonusPeriodSec) {
return currentRewardTokens.add(newRewardTokens);
}
uint256 oneHundredPct = 10**BONUS_DECIMALS;
uint256 bonusedReward =
startBonus
.add(oneHundredPct.sub(startBonus).mul(stakeTimeSec).div(bonusPeriodSec))
.mul(newRewardTokens)
.div(oneHundredPct);
return currentRewardTokens.add(bonusedReward);
}
/**
* @param addr The user to look up staking information for.
* @return The number of staking tokens deposited for addr.
*/
function totalStakedFor(address addr) public view returns (uint256) {
return totalStakingShares > 0 ?
totalStaked().mul(_userTotals[addr].stakingShares).div(totalStakingShares) : 0;
}
/**
* @return The total number of deposit tokens staked globally, by all users.
*/
function totalStaked() public view returns (uint256) {
return _stakingPool.balance();
}
/**
* @dev Note that this application has a staking token as well as a distribution token, which
* may be different. This function is required by EIP-900.
* @return The deposit token used for staking.
*/
function token() external view returns (address) {
return address(getStakingToken());
}
/**
* @dev A globally callable function to update the accounting state of the system.
* Global state and state for the caller are updated.
* @return [0] balance of the locked pool
* @return [1] balance of the unlocked pool
* @return [2] caller's staking share seconds
* @return [3] global staking share seconds
* @return [4] Rewards caller has accumulated, optimistically assumes max time-bonus.
* @return [5] block timestamp
*/
function updateAccounting() public returns (
uint256, uint256, uint256, uint256, uint256, uint256) {
unlockTokens();
// Global accounting
uint256 newStakingShareSeconds =
now
.sub(_lastAccountingTimestampSec)
.mul(totalStakingShares);
_totalStakingShareSeconds = _totalStakingShareSeconds.add(newStakingShareSeconds);
_lastAccountingTimestampSec = now;
// User Accounting
UserTotals storage totals = _userTotals[msg.sender];
uint256 newUserStakingShareSeconds =
now
.sub(totals.lastAccountingTimestampSec)
.mul(totals.stakingShares);
totals.stakingShareSeconds =
totals.stakingShareSeconds
.add(newUserStakingShareSeconds);
totals.lastAccountingTimestampSec = now;
uint256 totalUserRewards = (_totalStakingShareSeconds > 0)
? totalUnlocked().mul(totals.stakingShareSeconds).div(_totalStakingShareSeconds)
: 0;
return (
totalLocked(),
totalUnlocked(),
totals.stakingShareSeconds,
_totalStakingShareSeconds,
totalUserRewards,
now
);
}
/**
* @return Total number of locked distribution tokens.
*/
function totalLocked() public view returns (uint256) {
return _lockedPool.balance();
}
/**
* @return Total number of unlocked distribution tokens.
*/
function totalUnlocked() public view returns (uint256) {
return _unlockedPool.balance();
}
/**
* @return Number of unlock schedules.
*/
function unlockScheduleCount() public view returns (uint256) {
return unlockSchedules.length;
}
/**
* @dev This funcion allows the contract owner to add more locked distribution tokens, along
* with the associated 'unlock schedule'. These locked tokens immediately begin unlocking
* linearly over the duraction of durationSec timeframe.
* @param amount Number of distribution tokens to lock. These are transferred from the caller.
* @param durationSec Length of time to linear unlock the tokens.
*/
function lockTokens(uint256 amount, uint256 durationSec) external onlyOwner {
require(unlockSchedules.length < _maxUnlockSchedules,
'TokenGeyser: reached maximum unlock schedules');
// Update lockedTokens amount before using it in computations after.
updateAccounting();
uint256 lockedTokens = totalLocked();
uint256 mintedLockedShares = (lockedTokens > 0)
? totalLockedShares.mul(amount).div(lockedTokens)
: amount.mul(_initialSharesPerToken);
UnlockSchedule memory schedule;
schedule.initialLockedShares = mintedLockedShares;
schedule.lastUnlockTimestampSec = now;
schedule.endAtSec = now.add(durationSec);
schedule.durationSec = durationSec;
unlockSchedules.push(schedule);
totalLockedShares = totalLockedShares.add(mintedLockedShares);
require(_lockedPool.token().transferFrom(msg.sender, address(_lockedPool), amount),
'TokenGeyser: transfer into locked pool failed');
emit TokensLocked(amount, durationSec, totalLocked());
}
/**
* @dev Moves distribution tokens from the locked pool to the unlocked pool, according to the
* previously defined unlock schedules. Publicly callable.
* @return Number of newly unlocked distribution tokens.
*/
function unlockTokens() public returns (uint256) {
uint256 unlockedTokens = 0;
uint256 lockedTokens = totalLocked();
if (totalLockedShares == 0) {
unlockedTokens = lockedTokens;
} else {
uint256 unlockedShares = 0;
for (uint256 s = 0; s < unlockSchedules.length; s++) {
unlockedShares = unlockedShares.add(unlockScheduleShares(s));
}
unlockedTokens = unlockedShares.mul(lockedTokens).div(totalLockedShares);
totalLockedShares = totalLockedShares.sub(unlockedShares);
}
if (unlockedTokens > 0) {
require(_lockedPool.transfer(address(_unlockedPool), unlockedTokens),
'TokenGeyser: transfer out of locked pool failed');
emit TokensUnlocked(unlockedTokens, totalLocked());
}
return unlockedTokens;
}
/**
* @dev Returns the number of unlockable shares from a given schedule. The returned value
* depends on the time since the last unlock. This function updates schedule accounting,
* but does not actually transfer any tokens.
* @param s Index of the unlock schedule.
* @return The number of unlocked shares.
*/
function unlockScheduleShares(uint256 s) private returns (uint256) {
UnlockSchedule storage schedule = unlockSchedules[s];
if(schedule.unlockedShares >= schedule.initialLockedShares) {
return 0;
}
uint256 sharesToUnlock = 0;
// Special case to handle any leftover dust from integer division
if (now >= schedule.endAtSec) {
sharesToUnlock = (schedule.initialLockedShares.sub(schedule.unlockedShares));
schedule.lastUnlockTimestampSec = schedule.endAtSec;
} else {
sharesToUnlock = now.sub(schedule.lastUnlockTimestampSec)
.mul(schedule.initialLockedShares)
.div(schedule.durationSec);
schedule.lastUnlockTimestampSec = now;
}
schedule.unlockedShares = schedule.unlockedShares.add(sharesToUnlock);
return sharesToUnlock;
}
/**
* @dev Lets the owner rescue funds air-dropped to the staking pool.
* @param tokenToRescue Address of the token to be rescued.
* @param to Address to which the rescued funds are to be sent.
* @param amount Amount of tokens to be rescued.
* @return Transfer success.
*/
function rescueFundsFromStakingPool(address tokenToRescue, address to, uint256 amount)
public onlyOwner returns (bool) {
return _stakingPool.rescueFunds(tokenToRescue, to, amount);
}
}
| * @title Staking interface, as defined by EIP-900./ | contract IStaking {
event Staked(address indexed user, uint256 amount, uint256 total, bytes data);
event Unstaked(address indexed user, uint256 amount, uint256 total, bytes data);
function stake(uint256 amount, bytes calldata data) external;
function stakeFor(address user, uint256 amount, bytes calldata data) external;
function unstake(uint256 amount, bytes calldata data) external;
function totalStakedFor(address addr) public view returns (uint256);
function totalStaked() public view returns (uint256);
function token() external view returns (address);
function supportsHistory() external pure returns (bool) {
return false;
}
}
| 638,444 | [
1,
510,
6159,
1560,
16,
487,
2553,
635,
512,
2579,
17,
29,
713,
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,
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,
467,
510,
6159,
288,
203,
565,
871,
934,
9477,
12,
2867,
8808,
729,
16,
2254,
5034,
3844,
16,
2254,
5034,
2078,
16,
1731,
501,
1769,
203,
565,
871,
1351,
334,
9477,
12,
2867,
8808,
729,
16,
2254,
5034,
3844,
16,
2254,
5034,
2078,
16,
1731,
501,
1769,
203,
203,
565,
445,
384,
911,
12,
11890,
5034,
3844,
16,
1731,
745,
892,
501,
13,
3903,
31,
203,
565,
445,
384,
911,
1290,
12,
2867,
729,
16,
2254,
5034,
3844,
16,
1731,
745,
892,
501,
13,
3903,
31,
203,
565,
445,
640,
334,
911,
12,
11890,
5034,
3844,
16,
1731,
745,
892,
501,
13,
3903,
31,
203,
565,
445,
2078,
510,
9477,
1290,
12,
2867,
3091,
13,
1071,
1476,
1135,
261,
11890,
5034,
1769,
203,
565,
445,
2078,
510,
9477,
1435,
1071,
1476,
1135,
261,
11890,
5034,
1769,
203,
565,
445,
1147,
1435,
3903,
1476,
1135,
261,
2867,
1769,
203,
203,
203,
203,
565,
445,
6146,
5623,
1435,
3903,
16618,
1135,
261,
6430,
13,
288,
203,
3639,
327,
629,
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
] |
// SPDX-License-Identifier: MIT
pragma solidity ^0.7.6;
import "../interfaces/IPublicSaleProxy.sol";
import {Address} from "@openzeppelin/contracts/utils/Address.sol";
import "../common/AccessibleCommon.sol";
import "./PublicSaleStorage.sol";
import "../stake/ProxyBase.sol";
contract PublicSaleProxy is
PublicSaleStorage,
AccessibleCommon,
ProxyBase,
IPublicSaleProxy
{
event Upgraded(address indexed implementation);
/// @dev constructor of PublicSaleProxy
/// @param _impl the logic address of PublicSaleProxy
constructor(address _impl, address _admin) {
assert(
IMPLEMENTATION_SLOT ==
bytes32(uint256(keccak256("eip1967.proxy.implementation")) - 1)
);
require(_impl != address(0), "PublicSaleProxy: logic is zero");
_setImplementation(_impl);
_setRoleAdmin(ADMIN_ROLE, ADMIN_ROLE);
_setupRole(ADMIN_ROLE, _admin);
}
/// @notice Set pause state
/// @param _pause true:pause or false:resume
function setProxyPause(bool _pause) external override onlyOwner {
pauseProxy = _pause;
}
/// @notice Set implementation contract
/// @param impl New implementation contract address
function upgradeTo(address impl) external override onlyOwner {
require(impl != address(0), "PublicSaleProxy: input is zero");
require(_implementation() != impl, "PublicSaleProxy: same");
_setImplementation(impl);
emit Upgraded(impl);
}
/// @dev returns the implementation
function implementation() public override view returns (address) {
return _implementation();
}
/// @dev receive ether
receive() external payable {
revert("cannot receive Ether");
}
/// @dev fallback function , execute on undefined function call
fallback() external payable {
_fallback();
}
/// @dev fallback function , execute on undefined function call
function _fallback() internal {
address _impl = _implementation();
require(
_impl != address(0) && !pauseProxy,
"PublicSaleProxy: impl OR proxy is false"
);
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(), _impl, 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 Initialize
function initialize(
address _saleTokenAddress,
address _getTokenAddress,
address _getTokenOwner,
address _sTOS
) external override onlyOwner {
require(snapshot == 0, "possible to setting the snapshot before");
saleToken = IERC20(_saleTokenAddress);
getToken = IERC20(_getTokenAddress);
getTokenOwner = _getTokenOwner;
sTOS = ILockTOS(_sTOS);
}
}
//SPDX-License-Identifier: Unlicense
pragma solidity ^0.7.6;
interface IPublicSaleProxy {
/// @dev Set pause state
/// @param _pause true:pause or false:resume
function setProxyPause(bool _pause) external;
/// @dev Set implementation contract
/// @param _impl New implementation contract address
function upgradeTo(address _impl) external;
/// @dev view implementation address
/// @return the logic address
function implementation() external view returns (address);
/// @dev initialize
function initialize(
address _saleTokenAddress,
address _getTokenAddress,
address _getTokenOwner,
address _sTOS
) external;
}
// SPDX-License-Identifier: MIT
pragma solidity >=0.6.2 <0.8.0;
/**
* @dev Collection of functions related to the address type
*/
library Address {
/**
* @dev Returns true if `account` is a contract.
*
* [IMPORTANT]
* ====
* It is unsafe to assume that an address for which this function returns
* false is an externally-owned account (EOA) and not a contract.
*
* Among others, `isContract` will return false for the following
* types of addresses:
*
* - an externally-owned account
* - a contract in construction
* - an address where a contract will be created
* - an address where a contract lived, but was destroyed
* ====
*/
function isContract(address account) internal view returns (bool) {
// This method relies on extcodesize, which returns 0 for contracts in
// construction, since the code is only stored at the end of the
// constructor execution.
uint256 size;
// solhint-disable-next-line no-inline-assembly
assembly { size := extcodesize(account) }
return size > 0;
}
/**
* @dev Replacement for Solidity's `transfer`: sends `amount` wei to
* `recipient`, forwarding all available gas and reverting on errors.
*
* https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost
* of certain opcodes, possibly making contracts go over the 2300 gas limit
* imposed by `transfer`, making them unable to receive funds via
* `transfer`. {sendValue} removes this limitation.
*
* https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more].
*
* IMPORTANT: because control is transferred to `recipient`, care must be
* taken to not create reentrancy vulnerabilities. Consider using
* {ReentrancyGuard} or the
* https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern].
*/
function sendValue(address payable recipient, uint256 amount) internal {
require(address(this).balance >= amount, "Address: insufficient balance");
// solhint-disable-next-line avoid-low-level-calls, avoid-call-value
(bool success, ) = recipient.call{ value: amount }("");
require(success, "Address: unable to send value, recipient may have reverted");
}
/**
* @dev Performs a Solidity function call using a low level `call`. A
* plain`call` is an unsafe replacement for a function call: use this
* function instead.
*
* If `target` reverts with a revert reason, it is bubbled up by this
* function (like regular Solidity function calls).
*
* Returns the raw returned data. To convert to the expected return value,
* use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`].
*
* Requirements:
*
* - `target` must be a contract.
* - calling `target` with `data` must not revert.
*
* _Available since v3.1._
*/
function functionCall(address target, bytes memory data) internal returns (bytes memory) {
return functionCall(target, data, "Address: low-level call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with
* `errorMessage` as a fallback revert reason when `target` reverts.
*
* _Available since v3.1._
*/
function functionCall(address target, bytes memory data, string memory errorMessage) internal returns (bytes memory) {
return functionCallWithValue(target, data, 0, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but also transferring `value` wei to `target`.
*
* Requirements:
*
* - the calling contract must have an ETH balance of at least `value`.
* - the called Solidity function must be `payable`.
*
* _Available since v3.1._
*/
function functionCallWithValue(address target, bytes memory data, uint256 value) internal returns (bytes memory) {
return functionCallWithValue(target, data, value, "Address: low-level call with value failed");
}
/**
* @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but
* with `errorMessage` as a fallback revert reason when `target` reverts.
*
* _Available since v3.1._
*/
function functionCallWithValue(address target, bytes memory data, uint256 value, string memory errorMessage) internal returns (bytes memory) {
require(address(this).balance >= value, "Address: insufficient balance for call");
require(isContract(target), "Address: call to non-contract");
// solhint-disable-next-line avoid-low-level-calls
(bool success, bytes memory returndata) = target.call{ value: value }(data);
return _verifyCallResult(success, returndata, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but performing a static call.
*
* _Available since v3.3._
*/
function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) {
return functionStaticCall(target, data, "Address: low-level static call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`],
* but performing a static call.
*
* _Available since v3.3._
*/
function functionStaticCall(address target, bytes memory data, string memory errorMessage) internal view returns (bytes memory) {
require(isContract(target), "Address: static call to non-contract");
// solhint-disable-next-line avoid-low-level-calls
(bool success, bytes memory returndata) = target.staticcall(data);
return _verifyCallResult(success, returndata, errorMessage);
}
function _verifyCallResult(bool success, bytes memory returndata, string memory errorMessage) private pure returns(bytes memory) {
if (success) {
return returndata;
} else {
// Look for revert reason and bubble it up if present
if (returndata.length > 0) {
// The easiest way to bubble the revert reason is using memory via assembly
// solhint-disable-next-line no-inline-assembly
assembly {
let returndata_size := mload(returndata)
revert(add(32, returndata), returndata_size)
}
} else {
revert(errorMessage);
}
}
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.7.6;
import "@openzeppelin/contracts/access/AccessControl.sol";
import "./AccessRoleCommon.sol";
contract AccessibleCommon is AccessRoleCommon, AccessControl {
modifier onlyOwner() {
require(isAdmin(msg.sender), "Accessible: Caller is not an admin");
_;
}
/// @dev add admin
/// @param account address to add
function addAdmin(address account) public virtual onlyOwner {
grantRole(ADMIN_ROLE, account);
}
/// @dev remove admin
/// @param account address to remove
function removeAdmin(address account) public virtual onlyOwner {
renounceRole(ADMIN_ROLE, account);
}
/// @dev transfer admin
/// @param newAdmin new admin address
function transferAdmin(address newAdmin) external virtual onlyOwner {
require(newAdmin != address(0), "Accessible: zero address");
require(msg.sender != newAdmin, "Accessible: same admin");
grantRole(ADMIN_ROLE, newAdmin);
renounceRole(ADMIN_ROLE, msg.sender);
}
/// @dev whether admin
/// @param account address to check
function isAdmin(address account) public view virtual returns (bool) {
return hasRole(ADMIN_ROLE, account);
}
}
//SPDX-License-Identifier: Unlicense
pragma solidity ^0.7.6;
import { IERC20 } from "@openzeppelin/contracts/token/ERC20/IERC20.sol";
import "../interfaces/ILockTOS.sol";
contract PublicSaleStorage {
/// @dev flag for pause proxy
bool public pauseProxy;
struct UserInfoEx {
bool join;
uint tier;
uint256 payAmount;
uint256 saleAmount;
}
struct UserInfoOpen {
bool join;
uint256 depositAmount;
uint256 payAmount;
uint256 saleAmount;
}
struct UserClaim {
bool exec;
uint256 claimAmount;
uint256 refundAmount;
}
uint256 public snapshot = 0;
uint256 public startAddWhiteTime = 0;
uint256 public endAddWhiteTime = 0;
uint256 public startExclusiveTime = 0;
uint256 public endExclusiveTime = 0;
uint256 public startDepositTime = 0; //청약 시작시간
uint256 public endDepositTime = 0; //청약 끝시간
uint256 public startClaimTime = 0;
uint256 public totalUsers = 0; //전체 세일 참여자 (라운드1,라운드2 포함, 유니크)
uint256 public totalRound1Users = 0; //라운드 1 참여자
uint256 public totalRound2Users = 0; //라운드 2 참여자
uint256 public totalRound2UsersClaim = 0; //라운드 2 참여자중 claim한사람
uint256 public totalWhitelists = 0; //총 화이트리스트 수 (exclusive)
uint256 public totalExSaleAmount = 0; //총 exclu 실제 판매토큰 양 (exclusive)
uint256 public totalExPurchasedAmount = 0; //총 지불토큰 받은 양 (exclusive)
uint256 public totalDepositAmount; //총 청약 한 양 (openSale)
uint256 public totalExpectSaleAmount; //예정된 판매토큰 양 (exclusive)
uint256 public totalExpectOpenSaleAmount; //예정된 판매 토큰량 (opensale)
uint256 public saleTokenPrice; //판매하는 토큰(DOC)
uint256 public payTokenPrice; //받는 토큰(TON)
uint256 public claimInterval; //클레임 간격 (epochtime)
uint256 public claimPeriod; //클레임 횟수
uint256 public claimFirst; //초기 클레임 percents
address public getTokenOwner;
IERC20 public saleToken;
IERC20 public getToken;
ILockTOS public sTOS;
address[] public depositors;
address[] public whitelists;
bool public adminWithdraw; //withdraw 실행여부
mapping (address => UserInfoEx) public usersEx;
mapping (address => UserInfoOpen) public usersOpen;
mapping (address => UserClaim) public usersClaim;
mapping (uint => uint256) public tiers; //티어별 가격 설정
mapping (uint => uint256) public tiersAccount; //티어별 화이트리스트 참여자 숫자 기록
mapping (uint => uint256) public tiersExAccount; //티어별 exclusiveSale 참여자 숫자 기록
mapping (uint => uint256) public tiersPercents; //티어별 퍼센트 기록
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.7.6;
import {Address} from "@openzeppelin/contracts/utils/Address.sol";
abstract contract ProxyBase {
// bytes32(uint256(keccak256('eip1967.proxy.implementation')) - 1))
bytes32 internal constant IMPLEMENTATION_SLOT =
0x360894a13ba1a3210667c828492db98dca3e2076cc3735a920a3ca505d382bbc;
/// @dev Sets the implementation address of the proxy.
/// @param newImplementation Address of the new implementation.
function _setImplementation(address newImplementation) internal {
require(
Address.isContract(newImplementation),
"ProxyBase: Cannot set a proxy implementation to a non-contract address"
);
bytes32 slot = IMPLEMENTATION_SLOT;
assembly {
sstore(slot, newImplementation)
}
}
function _implementation() internal view returns (address impl) {
bytes32 slot = IMPLEMENTATION_SLOT;
assembly {
impl := sload(slot)
}
}
}
// SPDX-License-Identifier: MIT
pragma solidity >=0.6.0 <0.8.0;
import "../utils/EnumerableSet.sol";
import "../utils/Address.sol";
import "../GSN/Context.sol";
/**
* @dev Contract module that allows children to implement role-based access
* control mechanisms.
*
* 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 {
using EnumerableSet for EnumerableSet.AddressSet;
using Address for address;
struct RoleData {
EnumerableSet.AddressSet members;
bytes32 adminRole;
}
mapping (bytes32 => RoleData) private _roles;
bytes32 public constant DEFAULT_ADMIN_ROLE = 0x00;
/**
* @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 {_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) public view returns (bool) {
return _roles[role].members.contains(account);
}
/**
* @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 returns (uint256) {
return _roles[role].members.length();
}
/**
* @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 returns (address) {
return _roles[role].members.at(index);
}
/**
* @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 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 {
require(hasRole(_roles[role].adminRole, _msgSender()), "AccessControl: sender must be an admin to grant");
_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 {
require(hasRole(_roles[role].adminRole, _msgSender()), "AccessControl: sender must be an admin to revoke");
_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 {
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 {
emit RoleAdminChanged(role, _roles[role].adminRole, adminRole);
_roles[role].adminRole = adminRole;
}
function _grantRole(bytes32 role, address account) private {
if (_roles[role].members.add(account)) {
emit RoleGranted(role, account, _msgSender());
}
}
function _revokeRole(bytes32 role, address account) private {
if (_roles[role].members.remove(account)) {
emit RoleRevoked(role, account, _msgSender());
}
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.7.6;
contract AccessRoleCommon {
bytes32 public constant ADMIN_ROLE = keccak256("ADMIN");
bytes32 public constant MINTER_ROLE = keccak256("MINTER");
bytes32 public constant BURNER_ROLE = keccak256("BURNER");
}
// SPDX-License-Identifier: MIT
pragma solidity >=0.6.0 <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 `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;
// When the value to delete is the last one, the swap operation is unnecessary. However, since this occurs
// so rarely, we still do the swap anyway to avoid the gas cost of adding an 'if' statement.
bytes32 lastvalue = set._values[lastIndex];
// Move the last value to the index where the value to delete is
set._values[toDeleteIndex] = lastvalue;
// Update the index for the moved value
set._indexes[lastvalue] = toDeleteIndex + 1; // All indexes are 1-based
// Delete the slot where the moved value was stored
set._values.pop();
// Delete the index for the deleted slot
delete set._indexes[value];
return true;
} else {
return false;
}
}
/**
* @dev Returns true if the value is in the set. O(1).
*/
function _contains(Set storage set, bytes32 value) private view returns (bool) {
return set._indexes[value] != 0;
}
/**
* @dev Returns the number of values on the set. O(1).
*/
function _length(Set storage set) private view returns (uint256) {
return set._values.length;
}
/**
* @dev Returns the value stored at position `index` in the set. O(1).
*
* Note that there are no guarantees on the ordering of values inside the
* array, and it may change when more values are added or removed.
*
* Requirements:
*
* - `index` must be strictly less than {length}.
*/
function _at(Set storage set, uint256 index) private view returns (bytes32) {
require(set._values.length > index, "EnumerableSet: index out of bounds");
return set._values[index];
}
// 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);
}
// AddressSet
struct AddressSet {
Set _inner;
}
/**
* @dev Add a value to a set. O(1).
*
* Returns true if the value was added to the set, that is if it was not
* already present.
*/
function add(AddressSet storage set, address value) internal returns (bool) {
return _add(set._inner, bytes32(uint256(value)));
}
/**
* @dev Removes a value from a set. O(1).
*
* Returns true if the value was removed from the set, that is if it was
* present.
*/
function remove(AddressSet storage set, address value) internal returns (bool) {
return _remove(set._inner, bytes32(uint256(value)));
}
/**
* @dev Returns true if the value is in the set. O(1).
*/
function contains(AddressSet storage set, address value) internal view returns (bool) {
return _contains(set._inner, bytes32(uint256(value)));
}
/**
* @dev Returns the number of values in the set. O(1).
*/
function length(AddressSet storage set) internal view returns (uint256) {
return _length(set._inner);
}
/**
* @dev Returns the value stored at position `index` in the set. O(1).
*
* Note that there are no guarantees on the ordering of values inside the
* array, and it may change when more values are added or removed.
*
* Requirements:
*
* - `index` must be strictly less than {length}.
*/
function at(AddressSet storage set, uint256 index) internal view returns (address) {
return address(uint256(_at(set._inner, index)));
}
// UintSet
struct UintSet {
Set _inner;
}
/**
* @dev Add a value to a set. O(1).
*
* Returns true if the value was added to the set, that is if it was not
* already present.
*/
function add(UintSet storage set, uint256 value) internal returns (bool) {
return _add(set._inner, bytes32(value));
}
/**
* @dev Removes a value from a set. O(1).
*
* Returns true if the value was removed from the set, that is if it was
* present.
*/
function remove(UintSet storage set, uint256 value) internal returns (bool) {
return _remove(set._inner, bytes32(value));
}
/**
* @dev Returns true if the value is in the set. O(1).
*/
function contains(UintSet storage set, uint256 value) internal view returns (bool) {
return _contains(set._inner, bytes32(value));
}
/**
* @dev Returns the number of values on the set. O(1).
*/
function length(UintSet storage set) internal view returns (uint256) {
return _length(set._inner);
}
/**
* @dev Returns the value stored at position `index` in the set. O(1).
*
* Note that there are no guarantees on the ordering of values inside the
* array, and it may change when more values are added or removed.
*
* Requirements:
*
* - `index` must be strictly less than {length}.
*/
function at(UintSet storage set, uint256 index) internal view returns (uint256) {
return uint256(_at(set._inner, index));
}
}
// SPDX-License-Identifier: MIT
pragma solidity >=0.6.0 <0.8.0;
/*
* @dev Provides information about the current execution context, including the
* sender of the transaction and its data. While these are generally available
* via msg.sender and msg.data, they should not be accessed in such a direct
* manner, since when dealing with GSN meta-transactions the account sending and
* paying for execution may not be the actual sender (as far as an application
* is concerned).
*
* This contract is only required for intermediate, library-like contracts.
*/
abstract contract Context {
function _msgSender() internal view virtual returns (address payable) {
return msg.sender;
}
function _msgData() internal view virtual returns (bytes memory) {
this; // silence state mutability warning without generating bytecode - see https://github.com/ethereum/solidity/issues/2691
return msg.data;
}
}
// SPDX-License-Identifier: MIT
pragma solidity >=0.6.0 <0.8.0;
/**
* @dev Interface of the ERC20 standard as defined in the EIP.
*/
interface IERC20 {
/**
* @dev Returns the amount of tokens in existence.
*/
function totalSupply() external view returns (uint256);
/**
* @dev Returns the amount of tokens owned by `account`.
*/
function balanceOf(address account) external view returns (uint256);
/**
* @dev Moves `amount` tokens from the caller's account to `recipient`.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/
function transfer(address recipient, uint256 amount) external returns (bool);
/**
* @dev Returns the remaining number of tokens that `spender` will be
* allowed to spend on behalf of `owner` through {transferFrom}. This is
* zero by default.
*
* This value changes when {approve} or {transferFrom} are called.
*/
function allowance(address owner, address spender) external view returns (uint256);
/**
* @dev Sets `amount` as the allowance of `spender` over the caller's tokens.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* IMPORTANT: Beware that changing an allowance with this method brings the risk
* that someone may use both the old and the new allowance by unfortunate
* transaction ordering. One possible solution to mitigate this race
* condition is to first reduce the spender's allowance to 0 and set the
* desired value afterwards:
* https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729
*
* Emits an {Approval} event.
*/
function approve(address spender, uint256 amount) external returns (bool);
/**
* @dev Moves `amount` tokens from `sender` to `recipient` using the
* allowance mechanism. `amount` is then deducted from the caller's
* allowance.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/
function transferFrom(address sender, address recipient, uint256 amount) external returns (bool);
/**
* @dev Emitted when `value` tokens are moved from one account (`from`) to
* another (`to`).
*
* Note that `value` may be zero.
*/
event Transfer(address indexed from, address indexed to, uint256 value);
/**
* @dev Emitted when the allowance of a `spender` for an `owner` is set by
* a call to {approve}. `value` is the new allowance.
*/
event Approval(address indexed owner, address indexed spender, uint256 value);
}
// SPDX-License-Identifier: Unlicense
pragma solidity ^0.7.6;
pragma abicoder v2;
import "../libraries/LibLockTOS.sol";
interface ILockTOS {
/// @dev Returns addresses of all holders of LockTOS
function allHolders() external returns (address[] memory);
/// @dev Returns addresses of active holders of LockTOS
function activeHolders() external returns (address[] memory);
/// @dev Returns all withdrawable locks
function withdrawableLocksOf(address user) external view returns (uint256[] memory);
/// @dev Returns all locks of `_addr`
function locksOf(address _addr) external view returns (uint256[] memory);
/// @dev Returns all locks of `_addr`
function activeLocksOf(address _addr) external view returns (uint256[] memory);
/// @dev Total locked amount of `_addr`
function totalLockedAmountOf(address _addr) external view returns (uint256);
/// @dev jhswuqhdiuwjhdoiehdoijijf bhabcgfzvg tqafstqfzys amount of `_addr`
function withdrawableAmountOf(address _addr) external view returns (uint256);
/// @dev Returns all locks of `_addr`
function locksInfo(uint256 _lockId)
external
view
returns (
uint256,
uint256,
uint256
);
/// @dev Returns all history of `_addr`
function pointHistoryOf(uint256 _lockId)
external
view
returns (LibLockTOS.Point[] memory);
/// @dev Total vote weight
function totalSupply() external view returns (uint256);
/// @dev Total vote weight at `_timestamp`
function totalSupplyAt(uint256 _timestamp) external view returns (uint256);
/// @dev Vote weight of lock at `_timestamp`
function balanceOfLockAt(uint256 _lockId, uint256 _timestamp)
external
view
returns (uint256);
/// @dev Vote weight of lock
function balanceOfLock(uint256 _lockId) external view returns (uint256);
/// @dev Vote weight of a user at `_timestamp`
function balanceOfAt(address _addr, uint256 _timestamp)
external
view
returns (uint256 balance);
/// @dev Vote weight of a iser
function balanceOf(address _addr) external view returns (uint256 balance);
/// @dev Increase amount
function increaseAmount(uint256 _lockId, uint256 _value) external;
/// @dev Deposits value for '_addr'
function depositFor(
address _addr,
uint256 _lockId,
uint256 _value
) external;
/// @dev Create lock using permit
function createLockWithPermit(
uint256 _value,
uint256 _unlockTime,
uint256 _deadline,
uint8 _v,
bytes32 _r,
bytes32 _s
) external returns (uint256 lockId);
/// @dev Create lock
function createLock(uint256 _value, uint256 _unlockTime)
external
returns (uint256 lockId);
/// @dev Increase
function increaseUnlockTime(uint256 _lockId, uint256 unlockTime) external;
/// @dev Withdraw all TOS
function withdrawAll() external;
/// @dev Withdraw TOS
function withdraw(uint256 _lockId) external;
/// @dev needCheckpoint
function needCheckpoint() external view returns (bool need);
/// @dev Global checkpoint
function globalCheckpoint() external;
/// @dev set MaxTime
function setMaxTime(uint256 _maxTime) external;
}
// SPDX-License-Identifier: Unlicense
pragma solidity ^0.7.6;
library LibLockTOS {
struct Point {
int256 bias;
int256 slope;
uint256 timestamp;
}
struct LockedBalance {
uint256 start;
uint256 end;
uint256 amount;
bool withdrawn;
}
struct SlopeChange {
int256 bias;
int256 slope;
uint256 changeTime;
}
struct LockedBalanceInfo {
uint256 id;
uint256 start;
uint256 end;
uint256 amount;
uint256 balance;
}
} | @notice Set implementation contract @param impl New implementation contract address | function upgradeTo(address impl) external override onlyOwner {
require(impl != address(0), "PublicSaleProxy: input is zero");
require(_implementation() != impl, "PublicSaleProxy: same");
_setImplementation(impl);
emit Upgraded(impl);
}
| 5,882,298 | [
1,
694,
4471,
6835,
225,
9380,
1166,
4471,
6835,
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
] | [
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,
445,
8400,
774,
12,
2867,
9380,
13,
3903,
3849,
1338,
5541,
288,
203,
3639,
2583,
12,
11299,
480,
1758,
12,
20,
3631,
315,
4782,
30746,
3886,
30,
810,
353,
3634,
8863,
203,
3639,
2583,
24899,
30810,
1435,
480,
9380,
16,
315,
4782,
30746,
3886,
30,
1967,
8863,
203,
3639,
389,
542,
13621,
12,
11299,
1769,
203,
3639,
3626,
1948,
19305,
12,
11299,
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
] |
./full_match/80001/0x1098B35828bf70A2209FC6fEA916f378841d7fdD/sources/contracts/TicTacToe/TicTacToe.sol | calculateWinner returns the winner on the given board. The returned winner can be `None` in which case there is no winner and no draw. First we check if there is a victory in a row. If so, convert `Players` to `Winners` Subsequently we do the same for columns and diagonals. If there is no winner and no more space on the board, then it is a draw. | function calculateWinner(Players[3][3] memory _board) private pure returns (Winners winner) {
Players player = winnerInRow(_board);
if (player == Players.PlayerOne) {
return Winners.PlayerOne;
}
if (player == Players.PlayerTwo) {
return Winners.PlayerTwo;
}
player = winnerInColumn(_board);
if (player == Players.PlayerOne) {
return Winners.PlayerOne;
}
if (player == Players.PlayerTwo) {
return Winners.PlayerTwo;
}
player = winnerInDiagonal(_board);
if (player == Players.PlayerOne) {
return Winners.PlayerOne;
}
if (player == Players.PlayerTwo) {
return Winners.PlayerTwo;
}
if (isBoardFull(_board)) {
return Winners.Draw;
}
return Winners.None;
}
| 9,526,721 | [
1,
11162,
59,
7872,
1135,
326,
5657,
1224,
603,
326,
864,
11094,
18,
1021,
2106,
5657,
1224,
848,
506,
1375,
7036,
68,
316,
1492,
648,
1915,
353,
1158,
5657,
1224,
471,
1158,
3724,
18,
5783,
732,
866,
309,
1915,
353,
279,
28873,
630,
316,
279,
1027,
18,
971,
1427,
16,
1765,
1375,
1749,
3907,
68,
358,
1375,
18049,
9646,
68,
2592,
9116,
715,
732,
741,
326,
1967,
364,
2168,
471,
6643,
265,
1031,
18,
971,
1915,
353,
1158,
5657,
1224,
471,
1158,
1898,
3476,
603,
326,
11094,
16,
1508,
518,
353,
279,
3724,
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
] | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
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
] | [
1,
565,
445,
4604,
59,
7872,
12,
1749,
3907,
63,
23,
6362,
23,
65,
3778,
389,
3752,
13,
3238,
16618,
1135,
261,
18049,
9646,
5657,
1224,
13,
288,
203,
3639,
3008,
3907,
7291,
273,
5657,
1224,
382,
1999,
24899,
3752,
1769,
203,
3639,
309,
261,
14872,
422,
3008,
3907,
18,
12148,
3335,
13,
288,
203,
5411,
327,
21628,
9646,
18,
12148,
3335,
31,
203,
3639,
289,
203,
3639,
309,
261,
14872,
422,
3008,
3907,
18,
12148,
11710,
13,
288,
203,
5411,
327,
21628,
9646,
18,
12148,
11710,
31,
203,
3639,
289,
203,
203,
3639,
7291,
273,
5657,
1224,
382,
1494,
24899,
3752,
1769,
203,
3639,
309,
261,
14872,
422,
3008,
3907,
18,
12148,
3335,
13,
288,
203,
5411,
327,
21628,
9646,
18,
12148,
3335,
31,
203,
3639,
289,
203,
3639,
309,
261,
14872,
422,
3008,
3907,
18,
12148,
11710,
13,
288,
203,
5411,
327,
21628,
9646,
18,
12148,
11710,
31,
203,
3639,
289,
203,
203,
3639,
7291,
273,
5657,
1224,
382,
14058,
9528,
24899,
3752,
1769,
203,
3639,
309,
261,
14872,
422,
3008,
3907,
18,
12148,
3335,
13,
288,
203,
5411,
327,
21628,
9646,
18,
12148,
3335,
31,
203,
3639,
289,
203,
3639,
309,
261,
14872,
422,
3008,
3907,
18,
12148,
11710,
13,
288,
203,
5411,
327,
21628,
9646,
18,
12148,
11710,
31,
203,
3639,
289,
203,
203,
3639,
309,
261,
291,
22233,
5080,
24899,
3752,
3719,
288,
203,
5411,
327,
21628,
9646,
18,
6493,
31,
203,
3639,
289,
203,
203,
3639,
327,
21628,
9646,
18,
7036,
31,
203,
565,
289,
203,
203,
2,
-100,
-100
] |
./full_match/5/0x595931af6D6b9d314e77b257e79fAD36F35611dA/sources/src/token/ERC721/facets/locking/ERC721LockableOwnable.sol | * @inheritdoc IERC721LockableOwnable/ | function lockByOwner(uint256[] memory ids) public virtual onlyOwner {
IERC721LockableExtension(address(this)).lockByFacet(ids);
}
| 7,082,817 | [
1,
36,
10093,
467,
654,
39,
27,
5340,
2531,
429,
5460,
429,
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
] | [
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,
2176,
858,
5541,
12,
11890,
5034,
8526,
3778,
3258,
13,
1071,
5024,
1338,
5541,
288,
203,
3639,
467,
654,
39,
27,
5340,
2531,
429,
3625,
12,
2867,
12,
2211,
13,
2934,
739,
858,
11137,
12,
2232,
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
] |
// SPDX-License-Identifier: MIT
pragma solidity ^0.7.6;
import {DepositsManager} from './DepositsManager.sol';
import {ScryptVerifier} from "./ScryptVerifier.sol";
import {IScryptCheckerListener} from "./IScryptCheckerListener.sol";
import {IScryptChecker} from "./IScryptChecker.sol";
import '@openzeppelin/contracts/math/SafeMath.sol';
// ScryptClaims: queues a sequence of challengers to play with a claimant.
contract ScryptClaims is DepositsManager, IScryptChecker {
using SafeMath for uint;
uint private numClaims = 1; // index as key for the claims mapping.
uint public minDeposit = 1; // TODO: what should the minimum deposit be?
// default initial amount of blocks for challenge timeout
uint public defaultChallengeTimeout = 5;
ScryptVerifier public scryptVerifier;
event DepositBonded(uint claimId, address account, uint amount);
event DepositUnbonded(uint claimId, address account, uint amount);
event ClaimCreated(uint claimId, address claimant, bytes plaintext, bytes blockHash);
event ClaimChallenged(uint claimId, address challenger);
event SessionDecided(uint sessionId, address winner, address loser);
event ClaimSuccessful(uint claimId, address claimant, bytes plaintext, bytes blockHash);
event ClaimFailed(uint claimId, address claimant, bytes plaintext, bytes blockHash);
event VerificationGameStarted(uint claimId, address claimant, address challenger, uint sessionId);//Rename to SessionStarted?
event ClaimVerificationGamesEnded(uint claimId);
struct ScryptClaim {
address claimant;
bytes plaintext; // the plaintext Dogecoin block header.
bytes blockHash; // the Dogecoin blockhash.
uint createdAt; // the block number at which the claim was created.
address[] challengers; // all current challengers.
mapping(address => uint) sessions; //map challengers to sessionId's
uint numChallengers; // is number of challengers always same as challengers.length ?
uint currentChallenger; // index of next challenger to play a verification game.
bool verificationOngoing; // is the claim waiting for results from an ongoing verificationg game.
mapping (address => uint) bondedDeposits; // all deposits bonded in this claim.
bool decided;
bool invalid;
uint challengeTimeoutBlockNumber;
bytes32 proposalId;
IScryptCheckerListener scryptCheckerListener;
}
// mapping(address => uint) public claimantClaims;
mapping(uint => ScryptClaim) private claims;
modifier onlyScryptVerifier() {
require(msg.sender == address(scryptVerifier), "This function is restricted to the scrypt verifier contract.");
_;
}
// @dev – the constructor
constructor(ScryptVerifier _scryptVerifier) {
scryptVerifier = _scryptVerifier;
}
// @dev – locks up part of the user's deposit into a claim.
// @param claimId – the claim id.
// @param account – the user's address.
// @param amount – the amount of deposit to lock up.
// @return – the user's deposit bonded for the claim.
function bondDeposit(uint claimId, address account, uint amount) private returns (uint) {
ScryptClaim storage claim = getValidClaim(claimId);
require(deposits[account] >= amount, "Not enough balance is available. Deposit more ether.");
deposits[account] -= amount;
claim.bondedDeposits[account] = claim.bondedDeposits[account].add(amount);
emit DepositBonded(claimId, account, amount);
return claim.bondedDeposits[account];
}
// @dev – accessor for a claims bonded deposits.
// @param claimId – the claim id.
// @param account – the user's address.
// @return – the user's deposit bonded for the claim.
function getBondedDeposit(uint claimId, address account) public view returns (uint) {
ScryptClaim storage claim = getValidClaim(claimId);
return claim.bondedDeposits[account];
}
// @dev – unlocks a user's bonded deposits from a claim.
// @param claimId – the claim id.
// @param account – the user's address.
// @return – the user's deposit which was unbonded from the claim.
function unbondDeposit(uint claimId, address account) public returns (uint) {
ScryptClaim storage claim = getValidClaim(claimId);
require(claim.decided == true, "The claim is not decided yet.");
uint bondedDeposit = claim.bondedDeposits[account];
delete claim.bondedDeposits[account];
deposits[account] = deposits[account].add(bondedDeposit);
emit DepositUnbonded(claimId, account, bondedDeposit);
return bondedDeposit;
}
// TODO: Is the first parameter necessary?
function calcId(bytes memory, bytes32 _hash, address claimant, bytes32 _proposalId) public pure returns (uint) {
return uint(keccak256(abi.encodePacked(claimant, _hash, _proposalId)));
}
// @dev – check whether a DogeCoin blockHash was calculated correctly from the plaintext block header.
// only callable by the DogeRelay contract.
// @param _plaintext – the plaintext blockHeader.
// @param _blockHash – the blockHash.
// @param claimant – the address of the Dogecoin block submitter.
function checkScrypt(bytes memory _data, bytes32 _hash, bytes32 _proposalId, IScryptCheckerListener _scryptCheckerListener) external override payable {
// dogeRelay can directly make a deposit on behalf of the claimant.
address _submitter = msg.sender;
if (msg.value != 0) {
// only call if eth is included (to save gas)
increaseDeposit(_submitter, msg.value);
}
require(deposits[_submitter] >= minDeposit, "The deposit of the submitter should exceed the minimum deposit.");
// uint claimId = numClaims;
// uint claimId = uint(keccak256(_submitter, _plaintext, _hash, numClaims));
uint claimId = uint(keccak256(abi.encodePacked(_submitter, _hash, _proposalId)));
ScryptClaim storage claim = claims[claimId];
require(!claimExists(claim), "The claim already exists.");
claim.claimant = _submitter;
claim.plaintext = _data;
claim.blockHash = abi.encode(_hash);
claim.numChallengers = 0;
claim.currentChallenger = 0;
claim.verificationOngoing = false;
claim.createdAt = block.number;
claim.decided = false;
claim.invalid = false;
claim.proposalId = _proposalId;
claim.scryptCheckerListener = _scryptCheckerListener;
bondDeposit(claimId, claim.claimant, minDeposit);
emit ClaimCreated(claimId, claim.claimant, claim.plaintext, claim.blockHash);
claim.scryptCheckerListener.scryptSubmitted(claim.proposalId, _hash, _data, msg.sender);
}
// @dev – challenge an existing Scrypt claim.
// triggers a downstream claim computation on the scryptVerifier contract
// where the claimant & the challenger will immediately begin playing a verification.
//
// @param claimId – the claim ID.
function challengeClaim(uint claimId) public {
ScryptClaim storage claim = getValidClaim(claimId);
require(!claim.decided, "The claim is already decided.");
require(claim.sessions[msg.sender] == 0, "The sender is already challenging this claim.");
require(deposits[msg.sender] >= minDeposit, "The challenger deposit should exceed the minimum deposit.");
bondDeposit(claimId, msg.sender, minDeposit);
claim.challengeTimeoutBlockNumber = block.number.add(defaultChallengeTimeout);
claim.challengers.push(msg.sender);
claim.numChallengers = claim.numChallengers.add(1);
emit ClaimChallenged(claimId, msg.sender);
}
// @dev – runs a verification game between the claimant and
// the next queued-up challenger.
// @param claimId – the claim id.
function runNextVerificationGame(uint claimId) public {
ScryptClaim storage claim = getValidClaim(claimId);
require(!claim.decided, "The claim is already decided.");
require(!claim.verificationOngoing, "The claim has an ongoing verification.");
// check if there is a challenger who has not the played verification game yet.
if (claim.numChallengers > claim.currentChallenger) {
// kick off a verification game.
uint sessionId = scryptVerifier.claimComputation(claimId, claim.challengers[claim.currentChallenger], claim.claimant, claim.plaintext, claim.blockHash, 2050);
claim.sessions[claim.challengers[claim.currentChallenger]] = sessionId;
emit VerificationGameStarted(claimId, claim.claimant, claim.challengers[claim.currentChallenger], sessionId);
claim.verificationOngoing = true;
claim.currentChallenger = claim.currentChallenger.add(1);
}
}
// @dev – called when a verification game has ended.
// only callable by the scryptVerifier contract.
//
// @param sessionId – the sessionId.
// @param winner – winner of the verification game.
// @param loser – loser of the verification game.
function sessionDecided(uint sessionId, uint claimId, address winner, address loser) onlyScryptVerifier public {
ScryptClaim storage claim = getValidClaim(claimId);
require(claim.verificationOngoing, "The claim has no verification ongoing.");
claim.verificationOngoing = false;
// reward the winner, with the loser's bonded deposit.
uint depositToTransfer = claim.bondedDeposits[loser];
claim.bondedDeposits[winner] = claim.bondedDeposits[winner].add(depositToTransfer);
delete claim.bondedDeposits[loser];
if (claim.claimant == loser) {
// the claim is over.
// note: no callback needed to the DogeRelay contract,
// because it by default does not save blocks.
//Trigger end of verification game
claim.currentChallenger = claim.numChallengers;
claim.invalid = true;
} else if (claim.claimant == winner) {
// The claim continues in good standing.
runNextVerificationGame(claimId);
} else {
// This can only happen if the scrypt verifier contract decides a session
// with the claimant being neither the winner nor the loser.
revert("Invalid session decision.");
}
emit SessionDecided(sessionId, winner, loser);
}
// @dev – check whether a claim has successfully withstood all challenges.
// if successful, it will trigger a callback to the DogeRelay contract,
// notifying it that the Scrypt blockhash was correctly calculated.
//
// @param claimId – the claim ID.
// @todo There are a couple of problems here:
// First, the challenger never gets his deposits released.
// Second, this function can be called multiple times, so releasing the deposit here seems like a bad idea.
// We could make this function callable only once if successful though.
function checkClaimSuccessful(uint claimId) public {
ScryptClaim storage claim = getValidClaim(claimId);
// check that there is no ongoing verification game.
require(!claim.verificationOngoing, "The claim has an ongoing verification.");
// TODO: do we really want two separate timeouts? A default value should be just a default.
// check that the claim has exceeded the default challenge timeout.
require(
block.number.sub(claim.createdAt) > defaultChallengeTimeout,
"The claim has not exceeded the default challenge timeout."
);
// check that the claim has exceeded the claim's specific challenge timeout.
require(block.number > claim.challengeTimeoutBlockNumber, "The claim has not exceeded the challenge timeout");
// check that all verification games have been played.
require(claim.numChallengers == claim.currentChallenger, "Some verification games are pending.");
claim.decided = true;
if (!claim.invalid) {
claim.scryptCheckerListener.scryptVerified(claim.proposalId);
unbondDeposit(claimId, claim.claimant);
emit ClaimSuccessful(claimId, claim.claimant, claim.plaintext, claim.blockHash);
} else {
claim.scryptCheckerListener.scryptFailed(claim.proposalId);
emit ClaimFailed(claimId, claim.claimant, claim.plaintext, claim.blockHash);
}
}
function claimExists(ScryptClaim storage claim) view private returns(bool) {
return claim.claimant != address(0);
}
function firstChallenger(uint claimId) public view returns(address) {
ScryptClaim storage claim = getValidClaim(claimId);
return claim.challengers[0];
}
function createdAt(uint claimId) public view returns(uint) {
ScryptClaim storage claim = getValidClaim(claimId);
return claim.createdAt;
}
function getSession(uint claimId, address challenger) public view returns(uint) {
ScryptClaim storage claim = getValidClaim(claimId);
return claim.sessions[challenger];
}
function getChallengers(uint claimId) public view returns(address[] memory) {
ScryptClaim storage claim = getValidClaim(claimId);
return claim.challengers;
}
function getCurrentChallenger(uint claimId) public view returns(address) {
ScryptClaim storage claim = getValidClaim(claimId);
return claim.challengers[claim.currentChallenger];
}
function getVerificationOngoing(uint claimId) public view returns(bool) {
ScryptClaim storage claim = getValidClaim(claimId);
return claim.verificationOngoing;
}
function getClaim(uint claimId)
public
view
returns(address claimant, bytes memory plaintext, bytes memory blockHash, bytes32 proposalId)
{
ScryptClaim storage claim = claims[claimId];
return (
claim.claimant,
claim.plaintext,
claim.blockHash,
claim.proposalId
);
}
/**
* This function allows the caller to know if a claim is ready to be closed out.
*
* @dev This function avoids reverting to allow easy query outside of the contract.
*/
function getClaimReady(uint claimId) public view returns(bool) {
ScryptClaim storage claim = claims[claimId];
// check that the claim exists
bool exists = claimExists(claim);
// check that the claim has exceeded the default challenge timeout.
bool pastChallengeTimeout = block.number.sub(claim.createdAt) > defaultChallengeTimeout;
// check that the claim has exceeded the claim's specific challenge timeout.
bool pastClaimTimeout = block.number > claim.challengeTimeoutBlockNumber;
// check that there is no ongoing verification game.
bool noOngoingGames = !claim.verificationOngoing;
// check that all verification games have been played.
bool noPendingGames = claim.numChallengers == claim.currentChallenger;
return exists && pastChallengeTimeout && pastClaimTimeout && noOngoingGames && noPendingGames;
}
function getClaimStatus(uint claimId) public view returns(bool decided, bool invalid) {
decided = claims[claimId].decided;
invalid = claims[claimId].invalid;
}
function getValidClaim(uint claimId) private view returns (ScryptClaim storage claim) {
claim = claims[claimId];
require(claimExists(claim), "The claim doesn't exist.");
return claim;
}
}
| map challengers to sessionId's
| mapping(address => uint) sessions; | 6,417,305 | [
1,
1458,
462,
7862,
6215,
358,
10338,
1807,
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,
2874,
12,
2867,
516,
2254,
13,
8856,
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
] |
./full_match/1/0xc1aAB2dc3Fe5082D2D3eAaf67f4D49619B9862C9/sources/Users/simondos/projects/micobo-security-token/contracts/token/ERC1400Partition.sol | * [ERC1400Partition INTERFACE (3/10)] @dev Transfer tokens from a specific partition. @param partition Name of the partition. @param to Token recipient. @param value Number of tokens to transfer. @param data Information attached to the transfer, by the token holder. @return Destination partition./ | function transferByPartition(
bytes32 partition,
address to,
uint256 value,
bytes calldata data
) external override returns (bytes32) {
return
_transferByPartition(
partition,
_msgSender(),
_msgSender(),
to,
value,
data,
""
);
}
| 3,073,863 | [
1,
63,
654,
39,
3461,
713,
7003,
11391,
11300,
261,
23,
19,
2163,
25887,
225,
12279,
2430,
628,
279,
2923,
3590,
18,
225,
3590,
1770,
434,
326,
3590,
18,
225,
358,
3155,
8027,
18,
225,
460,
3588,
434,
2430,
358,
7412,
18,
225,
501,
15353,
7495,
358,
326,
7412,
16,
635,
326,
1147,
10438,
18,
327,
10691,
3590,
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
] | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
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
] | [
1,
202,
915,
7412,
858,
7003,
12,
203,
202,
202,
3890,
1578,
3590,
16,
203,
202,
202,
2867,
358,
16,
203,
202,
202,
11890,
5034,
460,
16,
203,
202,
202,
3890,
745,
892,
501,
203,
202,
13,
3903,
3849,
1135,
261,
3890,
1578,
13,
288,
203,
202,
202,
2463,
203,
1082,
202,
67,
13866,
858,
7003,
12,
203,
9506,
202,
10534,
16,
203,
9506,
202,
67,
3576,
12021,
9334,
203,
9506,
202,
67,
3576,
12021,
9334,
203,
9506,
202,
869,
16,
203,
9506,
202,
1132,
16,
203,
9506,
202,
892,
16,
203,
9506,
202,
3660,
203,
1082,
202,
1769,
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
] |
// SPDX-License-Identifier: MIT
/**
∩~~~~∩
ξ ・×・ ξ
ξ ~ ξ
ξ ξ
ξ “~~~~〇
ξ ξ
ξ ξ ξ~~~ξ ξ ξ
ξ_ξξ_ξ ξ_ξξ_ξ
Alpaca Fin Corporation
*/
pragma solidity 0.6.6;
import "@openzeppelin/contracts-ethereum-package/contracts/access/Ownable.sol";
import "@openzeppelin/contracts-ethereum-package/contracts/token/ERC20/ERC20.sol";
import "@openzeppelin/contracts-ethereum-package/contracts/token/ERC20/IERC20.sol";
import "@openzeppelin/contracts-ethereum-package/contracts/math/SafeMath.sol";
import "@openzeppelin/contracts-ethereum-package/contracts/math/Math.sol";
import "@openzeppelin/contracts-ethereum-package/contracts/utils/ReentrancyGuard.sol";
import "@openzeppelin/contracts-ethereum-package/contracts/Initializable.sol";
import "../interfaces/IDebtToken.sol";
import "../interfaces/IVaultConfig.sol";
import "../interfaces/IWorker.sol";
import "../interfaces/IVault.sol";
import "../../token/interfaces/IFairLaunch.sol";
import "../../utils/SafeToken.sol";
import "../WNativeRelayer.sol";
contract MockVaultForStrategy is IVault, ERC20UpgradeSafe, ReentrancyGuardUpgradeSafe, OwnableUpgradeSafe {
address public mockOwner;
address public override token;
function initialize() external initializer {}
function setMockOwner(address owner) external {
mockOwner = owner;
}
/// @dev Return the total token entitled to the token holders. Be careful of unaccrued interests.
function totalToken() public view override returns (uint256) {
return 0;
}
/// @dev Add more token to the lending pool. Hope to get some good returns.
function deposit(uint256 amountToken) external payable override {}
/// @dev Withdraw token from the lending and burning ibToken.
function withdraw(uint256 share) external override nonReentrant {}
/// @dev Request Funds from user through Vault
function requestFunds(address targetedToken, uint256 amount) external override {
SafeToken.safeTransferFrom(targetedToken, mockOwner, msg.sender, amount);
}
}
| @dev Add more token to the lending pool. Hope to get some good returns. | function deposit(uint256 amountToken) external payable override {}
| 12,717,303 | [
1,
986,
1898,
1147,
358,
326,
328,
2846,
2845,
18,
670,
1306,
358,
336,
2690,
7494,
1135,
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
] | [
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,
0,
0,
0
] | [
1,
225,
445,
443,
1724,
12,
11890,
5034,
3844,
1345,
13,
3903,
8843,
429,
3849,
2618,
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
] |
pragma solidity ^0.5.16;
pragma experimental ABIEncoderV2;
contract BTRUST {
/// @notice EIP-20 token name for this token
string public constant name = "BTRUST";
/// @notice EIP-20 token symbol for this token
string public constant symbol = "BTRUST";
/// @notice EIP-20 token decimals for this token
uint8 public constant decimals = 18;
/// @notice Total number of tokens in circulation
uint public constant totalSupply = 250000000e18; // 250 million BTRUST
/// @notice Allowance amounts on behalf of others
mapping (address => mapping (address => uint96)) internal allowances;
/// @notice Official record of token balances for each account
mapping (address => uint96) internal balances;
/// @notice A record of each accounts delegate
mapping (address => address) public delegates;
/// @notice A checkpoint for marking number of votes from a given block
struct Checkpoint {
uint32 fromBlock;
uint96 votes;
}
/// @notice A record of votes checkpoints for each account, by index
mapping (address => mapping (uint32 => Checkpoint)) public checkpoints;
/// @notice The number of checkpoints for each account
mapping (address => uint32) public numCheckpoints;
/// @notice The EIP-712 typehash for the contract's domain
bytes32 public constant DOMAIN_TYPEHASH = keccak256("EIP712Domain(string name,uint256 chainId,address verifyingContract)");
/// @notice The EIP-712 typehash for the delegation struct used by the contract
bytes32 public constant DELEGATION_TYPEHASH = keccak256("Delegation(address delegatee,uint256 nonce,uint256 expiry)");
/// @notice A record of states for signing / validating signatures
mapping (address => uint) public nonces;
/// @notice An event thats emitted when an account changes its delegate
event DelegateChanged(address indexed delegator, address indexed fromDelegate, address indexed toDelegate);
/// @notice An event thats emitted when a delegate account's vote balance changes
event DelegateVotesChanged(address indexed delegate, uint previousBalance, uint newBalance);
/// @notice The standard EIP-20 transfer event
event Transfer(address indexed from, address indexed to, uint256 amount);
/// @notice The standard EIP-20 approval event
event Approval(address indexed owner, address indexed spender, uint256 amount);
/**
* @notice Construct a new BTRUST token
* @param account The initial account to grant all the tokens
*/
constructor(address account) public {
balances[account] = uint96(totalSupply);
emit Transfer(address(0), account, totalSupply);
}
/**
* @notice Get the number of tokens `spender` is approved to spend on behalf of `account`
* @param account The address of the account holding the funds
* @param spender The address of the account spending the funds
* @return The number of tokens approved
*/
function allowance(address account, address spender) external view returns (uint) {
return allowances[account][spender];
}
/**
* @notice Approve `spender` to transfer up to `amount` from `src`
* @dev This will overwrite the approval amount for `spender`
* and is subject to issues noted [here](https://eips.ethereum.org/EIPS/eip-20#approve)
* @param spender The address of the account which may transfer tokens
* @param rawAmount The number of tokens that are approved (2^256-1 means infinite)
* @return Whether or not the approval succeeded
*/
function approve(address spender, uint rawAmount) external returns (bool) {
uint96 amount;
if (rawAmount == uint(-1)) {
amount = uint96(-1);
} else {
amount = safe96(rawAmount, "BTRUST::approve: amount exceeds 96 bits");
}
allowances[msg.sender][spender] = amount;
emit Approval(msg.sender, spender, amount);
return true;
}
/**
* @notice Get the number of tokens held by the `account`
* @param account The address of the account to get the balance of
* @return The number of tokens held
*/
function balanceOf(address account) external view returns (uint) {
return balances[account];
}
/**
* @notice Transfer `amount` tokens from `msg.sender` to `dst`
* @param dst The address of the destination account
* @param rawAmount The number of tokens to transfer
* @return Whether or not the transfer succeeded
*/
function transfer(address dst, uint rawAmount) external returns (bool) {
uint96 amount = safe96(rawAmount, "BTRUST::transfer: amount exceeds 96 bits");
_transferTokens(msg.sender, dst, amount);
return true;
}
/**
* @notice Transfer `amount` tokens from `src` to `dst`
* @param src The address of the source account
* @param dst The address of the destination account
* @param rawAmount The number of tokens to transfer
* @return Whether or not the transfer succeeded
*/
function transferFrom(address src, address dst, uint rawAmount) external returns (bool) {
address spender = msg.sender;
uint96 spenderAllowance = allowances[src][spender];
uint96 amount = safe96(rawAmount, "BTRUST::approve: amount exceeds 96 bits");
if (spender != src && spenderAllowance != uint96(-1)) {
uint96 newAllowance = sub96(spenderAllowance, amount, "BTRUST::transferFrom: transfer amount exceeds spender allowance");
allowances[src][spender] = newAllowance;
emit Approval(src, spender, newAllowance);
}
_transferTokens(src, dst, amount);
return true;
}
/**
* @notice Delegate votes from `msg.sender` to `delegatee`
* @param delegatee The address to delegate votes to
*/
function delegate(address delegatee) public {
return _delegate(msg.sender, delegatee);
}
/**
* @notice Delegates votes from signatory to `delegatee`
* @param delegatee The address to delegate votes to
* @param nonce The contract state required to match the signature
* @param expiry The time at which to expire the signature
* @param v The recovery byte of the signature
* @param r Half of the ECDSA signature pair
* @param s Half of the ECDSA signature pair
*/
function delegateBySig(address delegatee, uint nonce, uint expiry, uint8 v, bytes32 r, bytes32 s) public {
bytes32 domainSeparator = keccak256(abi.encode(DOMAIN_TYPEHASH, keccak256(bytes(name)), getChainId(), address(this)));
bytes32 structHash = keccak256(abi.encode(DELEGATION_TYPEHASH, delegatee, nonce, expiry));
bytes32 digest = keccak256(abi.encodePacked("\x19\x01", domainSeparator, structHash));
address signatory = ecrecover(digest, v, r, s);
require(signatory != address(0), "BTRUST::delegateBySig: invalid signature");
require(nonce == nonces[signatory]++, "BTRUST::delegateBySig: invalid nonce");
require(now <= expiry, "BTRUST::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, "BTRUST::getPriorVotes: not yet determined");
uint32 nCheckpoints = numCheckpoints[account];
if (nCheckpoints == 0) {
return 0;
}
// First check most recent balance
if (checkpoints[account][nCheckpoints - 1].fromBlock <= blockNumber) {
return checkpoints[account][nCheckpoints - 1].votes;
}
// Next check implicit zero balance
if (checkpoints[account][0].fromBlock > blockNumber) {
return 0;
}
uint32 lower = 0;
uint32 upper = nCheckpoints - 1;
while (upper > lower) {
uint32 center = upper - (upper - lower) / 2; // ceil, avoiding overflow
Checkpoint memory cp = checkpoints[account][center];
if (cp.fromBlock == blockNumber) {
return cp.votes;
} else if (cp.fromBlock < blockNumber) {
lower = center;
} else {
upper = center - 1;
}
}
return checkpoints[account][lower].votes;
}
function _delegate(address delegator, address delegatee) internal {
address currentDelegate = delegates[delegator];
uint96 delegatorBalance = balances[delegator];
delegates[delegator] = delegatee;
emit DelegateChanged(delegator, currentDelegate, delegatee);
_moveDelegates(currentDelegate, delegatee, delegatorBalance);
}
function _transferTokens(address src, address dst, uint96 amount) internal {
require(src != address(0), "BTRUST::_transferTokens: cannot transfer from the zero address");
require(dst != address(0), "BTRUST::_transferTokens: cannot transfer to the zero address");
balances[src] = sub96(balances[src], amount, "BTRUST::_transferTokens: transfer amount exceeds balance");
balances[dst] = add96(balances[dst], amount, "BTRUST::_transferTokens: transfer amount overflows");
emit Transfer(src, dst, amount);
_moveDelegates(delegates[src], delegates[dst], amount);
}
function _moveDelegates(address srcRep, address dstRep, uint96 amount) internal {
if (srcRep != dstRep && amount > 0) {
if (srcRep != address(0)) {
uint32 srcRepNum = numCheckpoints[srcRep];
uint96 srcRepOld = srcRepNum > 0 ? checkpoints[srcRep][srcRepNum - 1].votes : 0;
uint96 srcRepNew = sub96(srcRepOld, amount, "BTRUST::_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, "BTRUST::_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, "BTRUST::_writeCheckpoint: block number exceeds 32 bits");
if (nCheckpoints > 0 && checkpoints[delegatee][nCheckpoints - 1].fromBlock == blockNumber) {
checkpoints[delegatee][nCheckpoints - 1].votes = newVotes;
} else {
checkpoints[delegatee][nCheckpoints] = Checkpoint(blockNumber, newVotes);
numCheckpoints[delegatee] = nCheckpoints + 1;
}
emit DelegateVotesChanged(delegatee, oldVotes, newVotes);
}
function safe32(uint n, string memory errorMessage) internal pure returns (uint32) {
require(n < 2**32, errorMessage);
return uint32(n);
}
function safe96(uint n, string memory errorMessage) internal pure returns (uint96) {
require(n < 2**96, errorMessage);
return uint96(n);
}
function add96(uint96 a, uint96 b, string memory errorMessage) internal pure returns (uint96) {
uint96 c = a + b;
require(c >= a, errorMessage);
return c;
}
function sub96(uint96 a, uint96 b, string memory errorMessage) internal pure returns (uint96) {
require(b <= a, errorMessage);
return a - b;
}
function getChainId() internal pure returns (uint) {
uint256 chainId;
assembly { chainId := chainid() }
return chainId;
}
}
| * @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/ First check most recent balance Next check implicit zero balance | function getPriorVotes(address account, uint blockNumber) public view returns (uint96) {
require(blockNumber < block.number, "BTRUST::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;
}
| 7,856,043 | [
1,
8519,
326,
6432,
1300,
434,
19588,
364,
392,
2236,
487,
434,
279,
1203,
1300,
225,
3914,
1300,
1297,
506,
279,
727,
1235,
1203,
578,
469,
333,
445,
903,
15226,
358,
5309,
7524,
13117,
18,
225,
2236,
1021,
1758,
434,
326,
2236,
358,
866,
225,
1203,
1854,
1021,
1203,
1300,
358,
336,
326,
12501,
11013,
622,
327,
1021,
1300,
434,
19588,
326,
2236,
9323,
487,
434,
326,
864,
1203,
19,
5783,
866,
4486,
8399,
11013,
4804,
866,
10592,
3634,
11013,
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
] | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
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
] | [
1,
565,
445,
1689,
2432,
29637,
12,
2867,
2236,
16,
2254,
1203,
1854,
13,
1071,
1476,
1135,
261,
11890,
10525,
13,
288,
203,
3639,
2583,
12,
2629,
1854,
411,
1203,
18,
2696,
16,
315,
38,
4349,
5996,
2866,
588,
25355,
29637,
30,
486,
4671,
11383,
8863,
203,
203,
3639,
2254,
1578,
290,
1564,
4139,
273,
818,
1564,
4139,
63,
4631,
15533,
203,
3639,
309,
261,
82,
1564,
4139,
422,
374,
13,
288,
203,
5411,
327,
374,
31,
203,
3639,
289,
203,
203,
3639,
309,
261,
1893,
4139,
63,
4631,
6362,
82,
1564,
4139,
300,
404,
8009,
2080,
1768,
1648,
1203,
1854,
13,
288,
203,
5411,
327,
26402,
63,
4631,
6362,
82,
1564,
4139,
300,
404,
8009,
27800,
31,
203,
3639,
289,
203,
203,
3639,
309,
261,
1893,
4139,
63,
4631,
6362,
20,
8009,
2080,
1768,
405,
1203,
1854,
13,
288,
203,
5411,
327,
374,
31,
203,
3639,
289,
203,
203,
3639,
2254,
1578,
2612,
273,
374,
31,
203,
3639,
2254,
1578,
3854,
273,
290,
1564,
4139,
300,
404,
31,
203,
3639,
1323,
261,
5797,
405,
2612,
13,
288,
203,
5411,
25569,
3778,
3283,
273,
26402,
63,
4631,
6362,
5693,
15533,
203,
5411,
309,
261,
4057,
18,
2080,
1768,
422,
1203,
1854,
13,
288,
203,
7734,
327,
3283,
18,
27800,
31,
203,
7734,
2612,
273,
4617,
31,
203,
7734,
3854,
273,
4617,
300,
404,
31,
203,
5411,
289,
203,
3639,
289,
203,
3639,
327,
26402,
63,
4631,
6362,
8167,
8009,
27800,
31,
203,
565,
289,
203,
203,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
] |
./full_match/4/0xD32AD79c328588f7F0a7256d3Caf2Ec2Ef1eBE76/sources/contracts/MTGYFaaS.sol | TODO Loop through all stakers and harvest their tokens using _contract.harvestTokensForUser(_userAddy) | function removeTokenContract(address _faasTokenAddy) public view {
MTGYFaaSToken _contract = MTGYFaaSToken(_faasTokenAddy);
require(msg.sender == _contract.originalTokenOwnerAddress());
require(block.timestamp > _contract.lockedUntilDate());
}
| 800,555 | [
1,
6241,
9720,
3059,
777,
384,
581,
414,
471,
17895,
26923,
3675,
2430,
1450,
389,
16351,
18,
30250,
26923,
5157,
19894,
24899,
1355,
986,
93,
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
] | [
1,
1,
1,
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,
225,
445,
1206,
1345,
8924,
12,
2867,
389,
507,
345,
1345,
986,
93,
13,
1071,
1476,
288,
203,
565,
22068,
20564,
42,
7598,
882,
969,
389,
16351,
273,
22068,
20564,
42,
7598,
882,
969,
24899,
507,
345,
1345,
986,
93,
1769,
203,
565,
2583,
12,
3576,
18,
15330,
422,
389,
16351,
18,
8830,
1345,
5541,
1887,
10663,
203,
565,
2583,
12,
2629,
18,
5508,
405,
389,
16351,
18,
15091,
9716,
1626,
10663,
203,
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,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-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/0xAef3d07C724CFa27Cd57C5e0a49cE372dA766413/sources/contracts/alloyx/config/AlloyxConfig.sol | * @notice Set the address of certain index @param addressIndex the index to set @param newAddress new address to set/ | function setAddress(uint256 addressIndex, address newAddress) public override onlyAdmin {
require(newAddress != address(0));
emit AddressUpdated(msg.sender, addressIndex, addresses[addressIndex], newAddress);
addresses[addressIndex] = newAddress;
}
| 3,134,235 | [
1,
694,
326,
1758,
434,
8626,
770,
225,
1758,
1016,
326,
770,
358,
444,
225,
394,
1887,
394,
1758,
358,
444,
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,
444,
1887,
12,
11890,
5034,
1758,
1016,
16,
1758,
394,
1887,
13,
1071,
3849,
1338,
4446,
288,
203,
565,
2583,
12,
2704,
1887,
480,
1758,
12,
20,
10019,
203,
565,
3626,
5267,
7381,
12,
3576,
18,
15330,
16,
1758,
1016,
16,
6138,
63,
2867,
1016,
6487,
394,
1887,
1769,
203,
565,
6138,
63,
2867,
1016,
65,
273,
394,
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
] |
//SPDX-License-Identifier: MIT
pragma solidity ^0.6.0;
pragma experimental ABIEncoderV2;
import "@openzeppelin/contracts/math/SafeMath.sol";
import "@openzeppelin/contracts/token/ERC20/ERC20.sol";
contract WaffleMaker {
using SafeMath for uint;
uint constant PRIZE_POOL_COST_PERCENTAGE = 90; // The rest is given to the owner address as a dev fee
uint constant MAX_NAME_BYTES = 32;
uint constant MAX_WAFFLE_LAYERS = 5;
uint constant MAX_VOTES_PER_ACCOUNT = 3;
uint constant LEADERBOARD_WAFFLE_COUNT = 10;
uint constant COMPETITION_DURATION = 60 * 60 * 24 * 30;
uint constant BAKE_DURATION = 60 * 60 * 24;
uint constant CUSTOMIZE_DURATION = 60 * 60 * 24;
uint constant CUSTOMIZATION_STEPS_COUNT = 6;
uint constant CUSTOMIZATION_STEP_WINDOW_DURATION = 60 * 60;
uint constant CREATE_WAFFLE_CURRENCY_COST = 5 * 10 ** 15;
uint[CUSTOMIZATION_STEPS_COUNT] CUSTOMIZATION_STEP_WINDOWS = [
0,
60 * 60,
60 * 60 * 9,
60 * 60 * 17,
60 * 60 * 24,
0
];
address public owner;
address payable public grandPrize;
address payable public dev;
uint public competitionEndTimestamp;
ERC20 currency; // Asset used to pay for waffle creation
WaffleItem[] public toppings;
WaffleItem[] public bases;
WaffleItem[] public plates;
WaffleItem[] public extras;
Waffle[] waffles;
uint[] publishedWaffleIds;
mapping (uint => uint) public leaderboardWaffleIds;
mapping(address => AccountProfile) profiles;
uint finalWeiPrizeAmount;
uint finalCurrencyPrizeAmount;
bool competitionConcluded = false;
event CreateWaffle(address owner, uint waffleId);
event BakeWaffleLayer(address owner, uint waffleId);
event SubmitWaffleCustomization(
address owner,
uint waffleId,
uint baseId,
uint toppingId,
uint extraId,
uint plateId
);
event AdvanceWaffleCustomizationStep(address owner, uint waffleId);
event PublishWaffle(address owner, uint waffleId);
event VoteWaffle(address owner, uint waffleId);
enum CustomizationStep {
NOT_CUSTOMIZED,
PLATE,
BASE,
TOPPING,
EXTRA,
DONE
}
struct WaffleItem {
string name;
uint weiCost;
}
struct WaffleLayer {
uint baseId;
uint toppingId;
}
struct Waffle {
address owner;
uint votes;
string name;
uint plateId;
uint extraId;
mapping(uint => WaffleLayer) layers;
uint layersCount;
bool published;
CustomizationStep customizationStep;
uint processEnd; // Saves the Unix timestamp at which either the baking or customization ends
}
struct AccountProfile {
mapping(uint => uint) ownedWaffleIds;
uint ownedWafflesCount;
mapping(uint => uint) votedWaffleIds;
uint votedWafflesCount;
bool canVote;
}
// ******************** MODIFIERS ***********************\
modifier isOwner {
require(msg.sender == owner, "Caller is not the owner");
_;
}
modifier competitionIsOngoing {
require(block.timestamp < competitionEndTimestamp, "Competition must be ongoing");
_;
}
modifier competitionHasEnded {
require(block.timestamp >= competitionEndTimestamp, "Competition must have ended");
_;
}
modifier waffleExists(uint _waffleId) {
require(_waffleId < waffles.length, "This waffle doesn't exist");
_;
}
modifier waffleIsBeingProcessed(bool _positive, uint _waffleId) {
require((block.timestamp < waffles[_waffleId].processEnd) == _positive, "Invalid waffle processing state");
_;
}
modifier waffleIsPublished(bool _positive, uint _waffleId) {
require(waffles[_waffleId].published == _positive, "Invalid published state");
_;
}
modifier senderOwnsWaffle(bool _positive, uint _waffleId) {
bool waffleOwned = false;
for (uint i = 0; i < profiles[msg.sender].ownedWafflesCount; i++) {
if (profiles[msg.sender].ownedWaffleIds[i] == _waffleId) {
waffleOwned = true;
}
}
require(waffleOwned == _positive, "Invalid waffle owner");
_;
}
constructor (ERC20 _currency, address _grandPrize, address _dev) public {
require(_grandPrize != address(0), "_grandPrize is zero");
require(_dev != address(0), "_dev is zero");
owner = msg.sender;
grandPrize = payable(_grandPrize);
dev = payable(_dev);
competitionEndTimestamp = block.timestamp + COMPETITION_DURATION;
currency = _currency;
bases.push(WaffleItem('Empty', 0));
toppings.push(WaffleItem('Empty', 0));
plates.push(WaffleItem('Plain Plate', 0));
extras.push(WaffleItem('Empty', 0));
}
/**
* Add a new topping that can be used by waffles
**/
function createTopping (string memory _name, uint _weiCost) external isOwner {
toppings.push(WaffleItem(_name, _weiCost));
}
/**
* Add a new base that can be used by waffles
**/
function createBase (string memory _name, uint _weiCost) external isOwner {
bases.push(WaffleItem(_name, _weiCost));
}
/**
* Add a new extra that can be used by waffles
**/
function createExtra (string memory _name, uint _weiCost) external isOwner {
extras.push(WaffleItem(_name, _weiCost));
}
/**
* Add a new plate that can be used by waffles
**/
function createPlate (string memory _name, uint _weiCost) external isOwner {
plates.push(WaffleItem(_name, _weiCost));
}
/**
* Bake a new waffle with a BAKE_DURATION time to completion
*
* Costs CREATE_WAFFLE_CURRENCY_COST of the contract currency
**/
function createWaffle() external competitionIsOngoing {
waffles.push(Waffle({
owner: msg.sender,
votes: 0,
name: "",
plateId: 0,
extraId: 0,
layersCount: 0,
published: false,
processEnd: block.timestamp + BAKE_DURATION,
customizationStep: CustomizationStep.NOT_CUSTOMIZED
}));
addWaffleLayer(waffles.length - 1);
profiles[msg.sender].ownedWaffleIds[profiles[msg.sender].ownedWafflesCount++] = waffles.length - 1;
emit CreateWaffle(msg.sender, waffles.length - 1);
}
/**
* Add a new layer to the waffleId provided if the waffle is owned by the sender and if last
* layer has been customized
**/
function bakeWaffleLayer(uint _waffleId)
external
competitionIsOngoing
waffleExists(_waffleId)
senderOwnsWaffle(true, _waffleId)
waffleIsBeingProcessed(false, _waffleId)
{
require(waffles[_waffleId].customizationStep == CustomizationStep.DONE, "Last layer must be customized");
waffles[_waffleId].processEnd = block.timestamp + BAKE_DURATION;
addWaffleLayer(_waffleId);
emit BakeWaffleLayer(msg.sender, _waffleId);
}
/**
* Submit the customization for the top layer of a waffle if the top layer is not yet customized
*
* Every layer can be given a base and a topping, but only the first layer can be given an extra and a plate
**/
function submitWaffleCustomization
(
uint _waffleId,
string memory _name,
uint _baseId,
uint _toppingId,
uint _extraId,
uint _plateId
)
external
payable
competitionIsOngoing
waffleExists(_waffleId)
senderOwnsWaffle(true, _waffleId)
waffleIsBeingProcessed(false, _waffleId)
{
require(waffles[_waffleId].customizationStep == CustomizationStep.NOT_CUSTOMIZED, "Last layer must not already be customized");
require(_baseId < bases.length, "Invalid base");
require(_toppingId < toppings.length, "Invalid topping");
checkCustomizationCosts(_waffleId, _baseId, _toppingId, _extraId, _plateId);
if (waffles[_waffleId].layersCount <= 1) {
require(bytes(_name).length > 0, "Waffle name can't be empty");
require(bytes(_name).length <= MAX_NAME_BYTES, "Max name length exceeded");
require(_extraId < extras.length, "Invalid extra");
require(_plateId < plates.length, "Invalid plate");
waffles[_waffleId].name = _name;
waffles[_waffleId].plateId = _plateId;
waffles[_waffleId].extraId = _extraId;
}
uint lastLayerIndex = waffles[_waffleId].layersCount - 1;
waffles[_waffleId].layers[lastLayerIndex].baseId = _baseId;
waffles[_waffleId].layers[lastLayerIndex].toppingId = _toppingId;
waffles[_waffleId].processEnd = block.timestamp + CUSTOMIZE_DURATION;
calculateNextWaffleCustomizationStep(_waffleId);
emit SubmitWaffleCustomization(msg.sender, _waffleId, _baseId, _toppingId, _extraId, _plateId);
}
/**
* Adds the ingredient of a waffle if within a customization window
*
* This needs to be called once for every ingredient added to a waffle
*
* If not called in time, the waffle will burn
**/
function advanceWaffleCustomizationStep(uint _waffleId)
external
competitionIsOngoing
waffleExists(_waffleId)
senderOwnsWaffle(true, _waffleId)
waffleIsPublished(false, _waffleId)
{
require(waffles[_waffleId].customizationStep < CustomizationStep.DONE, 'All customization steps done');
uint stepNumber = uint(waffles[_waffleId].customizationStep);
uint processStart = waffles[_waffleId].processEnd - CUSTOMIZE_DURATION;
uint customizationWindowEnd = processStart + CUSTOMIZATION_STEP_WINDOWS[stepNumber];
uint customizationWindowStart = customizationWindowEnd - CUSTOMIZATION_STEP_WINDOW_DURATION;
require(block.timestamp > customizationWindowStart, 'Cannot advance customization step yet');
require(block.timestamp < customizationWindowEnd, 'Waffle burned');
calculateNextWaffleCustomizationStep(_waffleId);
emit AdvanceWaffleCustomizationStep(msg.sender, _waffleId);
}
/**
* Makes a waffle available for voting and blocks further customization
**/
function publishWaffle(uint _waffleId)
external
competitionIsOngoing
waffleExists(_waffleId)
senderOwnsWaffle(true, _waffleId)
waffleIsPublished(false, _waffleId)
waffleIsBeingProcessed(false, _waffleId)
{
require(waffles[_waffleId].customizationStep == CustomizationStep.DONE, 'At least one layer must be customized');
waffles[_waffleId].published = true;
publishedWaffleIds.push(_waffleId);
profiles[msg.sender].canVote = true;
emit PublishWaffle(msg.sender, _waffleId);
}
/**
* Cast a vote for the waffleId provided from the sender account.
*
* Waffle must be published by calling publishWaffle to be voted on
*
* No more than MAX_VOTES_PER_ACCOUNT votes can be cast per account.
**/
function voteWaffle(uint _waffleId)
external
competitionIsOngoing
waffleExists(_waffleId)
senderOwnsWaffle(false, _waffleId)
waffleIsPublished(true, _waffleId)
{
require(profiles[msg.sender].canVote, "Must have published at least one waffle to vote");
require(profiles[msg.sender].votedWafflesCount < MAX_VOTES_PER_ACCOUNT, "Max votes on this account exceeded");
require(!addressHasVotedOnWaffle(msg.sender, _waffleId), "Can't vote for the same waffle twice");
waffles[_waffleId].votes++;
profiles[msg.sender].votedWaffleIds[profiles[msg.sender].votedWafflesCount++] = _waffleId;
uint votes = waffles[_waffleId].votes;
uint lastWaffleId = leaderboardWaffleIds[LEADERBOARD_WAFFLE_COUNT - 1];
if (waffles[lastWaffleId].votes >= votes) return;
for (uint i = 0; i < LEADERBOARD_WAFFLE_COUNT; i++) {
// find where to insert the new score
if (waffles[leaderboardWaffleIds[i]].votes < votes) {
for (uint j = LEADERBOARD_WAFFLE_COUNT; i < j; j--) {
leaderboardWaffleIds[j] = leaderboardWaffleIds[j - 1];
}
// insert
leaderboardWaffleIds[i] = _waffleId;
// delete last from list
delete leaderboardWaffleIds[LEADERBOARD_WAFFLE_COUNT];
return;
}
}
emit VoteWaffle(msg.sender, _waffleId);
}
/**
* Transfer the accumulated funds to the dev address and the grand prize address
* and save the final prize pool values
*
* Can be called by anyone
**/
function concludeCompetition()
external
competitionHasEnded
{
require(!competitionConcluded, "Competition has already been concluded");
uint weiBalance = address(this).balance;
uint poolWeiAmount = weiBalance.mul(PRIZE_POOL_COST_PERCENTAGE).div(100);
uint devWeiAmount = weiBalance - poolWeiAmount;
uint currencyBalance = currency.balanceOf(address(this));
uint poolCurrencyAmount = currencyBalance.mul(PRIZE_POOL_COST_PERCENTAGE).div(100);
uint devCurrencyAmount = currencyBalance - poolCurrencyAmount;
competitionConcluded = true;
finalWeiPrizeAmount = poolWeiAmount;
finalCurrencyPrizeAmount = poolCurrencyAmount;
grandPrize.transfer(poolWeiAmount);
dev.transfer(devWeiAmount);
require(currency.transfer(grandPrize, poolCurrencyAmount), "Something went wrong with the prize pool currency transfer");
require(currency.transfer(dev, devCurrencyAmount), "Something went wrong with the dev currency transfer");
}
/**
* Returns either the wei grand prize to be or the final recorded wei prize
* pool if the competition is over
**/
function getWeiPrizeAmount() external view returns(uint)
{
if (competitionConcluded) {
return finalWeiPrizeAmount;
} else {
uint weiBalance = address(this).balance;
return weiBalance.mul(PRIZE_POOL_COST_PERCENTAGE).div(100);
}
}
/**
* Returns either the currency grand prize to be or the final recorded currency prize
* pool if the competition is over
**/
function getCurrencyPrizeAmount() external view returns(uint)
{
if (competitionConcluded) {
return finalCurrencyPrizeAmount;
} else {
uint currencyBalance = currency.balanceOf(address(this));
return currencyBalance.mul(PRIZE_POOL_COST_PERCENTAGE).div(100);
}
}
/**
* Returns the address of the creator of a waffle
**/
function getWaffleOwner(uint _waffleId)
external
view
waffleExists(_waffleId)
returns (address)
{
return waffles[_waffleId].owner;
}
/**
* Returns the data of the waffle associated to a waffle id
**/
function getWaffleInfo(uint _waffleId)
public
view
waffleExists(_waffleId)
returns (
uint id,
string memory name,
uint votes,
uint extraId,
uint plateId,
uint processEnd,
bool published,
CustomizationStep customizationStep,
WaffleLayer[] memory layers
)
{
Waffle memory waffle = waffles[_waffleId];
WaffleLayer[] memory waffleLayers = new WaffleLayer[](waffle.layersCount);
for (uint i = 0; i < waffle.layersCount; i++) {
waffleLayers[i] = waffles[_waffleId].layers[i];
}
return (
_waffleId,
waffle.name,
waffle.votes,
waffle.extraId,
waffle.plateId,
waffle.processEnd,
waffle.published,
waffle.customizationStep,
waffleLayers
);
}
/**
* Returns the data of the waffle associated to a published waffle index
**/
function getPublishedWaffleInfo(uint _publishedWaffleIndex)
external
view
returns (
uint id,
string memory name,
uint votes,
uint extraId,
uint plateId,
uint processEnd,
bool published,
CustomizationStep customizationStep,
WaffleLayer[] memory layers
)
{
require(_publishedWaffleIndex < publishedWaffleIds.length, "Published waffle doesn't exist");
uint waffleId = publishedWaffleIds[_publishedWaffleIndex];
return getWaffleInfo(waffleId);
}
/**
* Returns the data of the waffle associated to a leaderboard index
**/
function getLeaderboardWaffleInfo(uint _leaderboardWaffleIndex)
external
view
returns (
uint id,
string memory name,
uint votes,
uint extraId,
uint plateId,
uint processEnd,
bool published,
CustomizationStep customizationStep,
WaffleLayer[] memory layers
)
{
require(_leaderboardWaffleIndex < LEADERBOARD_WAFFLE_COUNT && _leaderboardWaffleIndex < waffles.length, "Leaderboard waffle doesn't exist");
uint waffleId = leaderboardWaffleIds[_leaderboardWaffleIndex];
return getWaffleInfo(waffleId);
}
/**
* Returns the profile data associated to an address
**/
function getProfileInfo(address _addr)
external
view
returns (
uint[] memory ownedWaffleIds,
uint[] memory votedWaffleIds,
bool canVote
)
{
uint[] memory profileOwnedWaffles = new uint[](profiles[_addr].ownedWafflesCount);
for (uint i = 0; i < profiles[_addr].ownedWafflesCount; i++) {
profileOwnedWaffles[i] = profiles[_addr].ownedWaffleIds[i];
}
uint[] memory profileVotedWaffles = new uint[](profiles[_addr].votedWafflesCount);
for (uint i = 0; i < profiles[_addr].votedWafflesCount; i++) {
profileVotedWaffles[i] = profiles[_addr].votedWaffleIds[i];
}
return (profileOwnedWaffles, profileVotedWaffles, profiles[_addr].canVote);
}
/**
* Returns the number of published waffles
**/
function getPublishedWafflesCount() external view returns(uint) {
return publishedWaffleIds.length;
}
/**
* Returns the number of possible toppings for waffles
**/
function getToppingsCount() external view returns(uint) {
return toppings.length;
}
/**
* Returns the number of possible bases for waffles
**/
function getBasesCount() external view returns(uint) {
return bases.length;
}
/**
* Returns the number of possible plates for waffles
**/
function getPlatesCount() external view returns(uint) {
return plates.length;
}
/**
* Returns the number of possible extras for waffles
**/
function getExtrasCount() external view returns(uint) {
return extras.length;
}
function getWaffleLayers(uint _waffleId) internal view returns(WaffleLayer[] memory) {
uint layersCount = waffles[_waffleId].layersCount;
WaffleLayer[] memory waffleLayers = new WaffleLayer[](layersCount);
for (uint i = 0; i < layersCount; i++) {
waffleLayers[i] = waffles[_waffleId].layers[i];
}
return waffleLayers;
}
function spendCurrency(uint amount) internal {
uint balance = currency.balanceOf(address(msg.sender));
require(balance >= amount, "Currency balance too low for this action");
uint allowance = currency.allowance(address(msg.sender), address(this));
require(allowance >= amount, "Currency allowance too low for this action");
bool returnValue = currency.transferFrom(address(msg.sender), address(this), amount);
require(returnValue, "Something went wrong in the currency transfer");
}
function checkCustomizationCosts
(
uint _waffleId,
uint _baseId,
uint _toppingId,
uint _extraId,
uint _plateId
)
internal
{
uint weiCost = 0;
if (waffles[_waffleId].layersCount <= 1) {
weiCost = weiCost.add(plates[_plateId].weiCost + extras[_extraId].weiCost);
}
weiCost = weiCost.add(bases[_baseId].weiCost + toppings[_toppingId].weiCost);
require(msg.sender.balance >= weiCost, "Wei balance too low for this customization");
require(msg.value == weiCost, "Sent value doesn't match expected value for this waffle customization");
}
function addWaffleLayer(uint _waffleId) internal {
require(waffles[_waffleId].layersCount < MAX_WAFFLE_LAYERS, "You can't add more layers to this waffle");
waffles[_waffleId].layers[waffles[_waffleId].layersCount++] = WaffleLayer(0,0);
waffles[_waffleId].customizationStep = CustomizationStep.NOT_CUSTOMIZED;
spendCurrency(CREATE_WAFFLE_CURRENCY_COST);
}
function waffleCustomizationStepCanBeSkipped(uint _waffleId) internal view returns(bool) {
if (waffles[_waffleId].layersCount == 1) {
if (waffles[_waffleId].customizationStep == CustomizationStep.PLATE && waffles[_waffleId].plateId == 0) {
return true;
} else if(waffles[_waffleId].customizationStep == CustomizationStep.EXTRA && waffles[_waffleId].extraId == 0) {
return true;
} else if(waffles[_waffleId].customizationStep == CustomizationStep.BASE && waffles[_waffleId].layers[waffles[_waffleId].layersCount - 1].baseId == 0) {
return true;
} else if(waffles[_waffleId].customizationStep == CustomizationStep.TOPPING && waffles[_waffleId].layers[waffles[_waffleId].layersCount - 1].toppingId == 0) {
return true;
} else {
return false;
}
} else {
if (waffles[_waffleId].customizationStep == CustomizationStep.PLATE) {
return true;
} else if(waffles[_waffleId].customizationStep == CustomizationStep.EXTRA) {
return true;
} else if(waffles[_waffleId].customizationStep == CustomizationStep.BASE && waffles[_waffleId].layers[waffles[_waffleId].layersCount - 1].baseId == 0) {
return true;
} else if(waffles[_waffleId].customizationStep == CustomizationStep.TOPPING && waffles[_waffleId].layers[waffles[_waffleId].layersCount - 1].toppingId == 0) {
return true;
} else {
return false;
}
}
}
function calculateNextWaffleCustomizationStep(uint _waffleId) internal {
do {
uint newStepNumber = uint(waffles[_waffleId].customizationStep) + 1;
waffles[_waffleId].customizationStep = CustomizationStep(newStepNumber);
} while (waffleCustomizationStepCanBeSkipped(_waffleId));
}
function addressHasVotedOnWaffle(address _addr, uint _waffleId) internal view returns(bool) {
for (uint i = 0; i < profiles[_addr].votedWafflesCount; i++) {
if (profiles[_addr].votedWaffleIds[i] == _waffleId) {
return true;
}
}
return false;
}
}
| * Returns the number of possible bases for waffles/ | function getBasesCount() external view returns(uint) {
return bases.length;
}
| 7,230,165 | [
1,
1356,
326,
1300,
434,
3323,
8337,
364,
341,
7329,
1040,
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
] | [
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,
565,
445,
2882,
3304,
1380,
1435,
3903,
1476,
1135,
12,
11890,
13,
288,
203,
3639,
327,
8337,
18,
2469,
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
] |
// SPDX-License-Identifier: MIT
// File: @openzeppelin/contracts/utils/Context.sol
pragma solidity >=0.6.0 <0.8.0;
/*
* @dev Provides information about the current execution context, including the
* sender of the transaction and its data. While these are generally available
* via msg.sender and msg.data, they should not be accessed in such a direct
* manner, since when dealing with GSN meta-transactions the account sending and
* paying for execution may not be the actual sender (as far as an application
* is concerned).
*
* This contract is only required for intermediate, library-like contracts.
*/
abstract contract Context {
function _msgSender() internal view virtual returns (address payable) {
return msg.sender;
}
function _msgData() internal view virtual returns (bytes memory) {
this; // silence state mutability warning without generating bytecode - see https://github.com/ethereum/solidity/issues/2691
return msg.data;
}
}
// File: @openzeppelin/contracts/introspection/IERC165.sol
pragma solidity >=0.6.0 <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);
}
// File: @openzeppelin/contracts/token/ERC721/IERC721.sol
pragma solidity >=0.6.2 <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: @openzeppelin/contracts/token/ERC721/IERC721Metadata.sol
pragma solidity >=0.6.2 <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: @openzeppelin/contracts/token/ERC721/IERC721Enumerable.sol
pragma solidity >=0.6.2 <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 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);
}
// File: @openzeppelin/contracts/token/ERC721/IERC721Receiver.sol
pragma solidity >=0.6.0 <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: @openzeppelin/contracts/introspection/ERC165.sol
pragma solidity >=0.6.0 <0.8.0;
/**
* @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(keccak256('supportsInterface(bytes4)')) == 0x01ffc9a7
*/
bytes4 private constant _INTERFACE_ID_ERC165 = 0x01ffc9a7;
/**
* @dev Mapping of interface ids to whether or not it's supported.
*/
mapping(bytes4 => bool) private _supportedInterfaces;
constructor () internal {
// Derived contracts need only register support for their own interfaces,
// we register support for ERC165 itself here
_registerInterface(_INTERFACE_ID_ERC165);
}
/**
* @dev See {IERC165-supportsInterface}.
*
* Time complexity O(1), guaranteed to always use less than 30 000 gas.
*/
function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) {
return _supportedInterfaces[interfaceId];
}
/**
* @dev Registers the contract as an implementer of the interface defined by
* `interfaceId`. Support of the actual ERC165 interface is automatic and
* registering its interface id is not required.
*
* See {IERC165-supportsInterface}.
*
* Requirements:
*
* - `interfaceId` cannot be the ERC165 invalid interface (`0xffffffff`).
*/
function _registerInterface(bytes4 interfaceId) internal virtual {
require(interfaceId != 0xffffffff, "ERC165: invalid interface id");
_supportedInterfaces[interfaceId] = true;
}
}
// File: @openzeppelin/contracts/math/SafeMath.sol
pragma solidity >=0.6.0 <0.8.0;
/**
* @dev Wrappers over Solidity's arithmetic operations with added overflow
* checks.
*
* Arithmetic operations in Solidity wrap on overflow. This can easily result
* in bugs, because programmers usually assume that an overflow raises an
* error, which is the standard behavior in high level programming languages.
* `SafeMath` restores this intuition by reverting the transaction when an
* operation overflows.
*
* Using this library instead of the unchecked operations eliminates an entire
* class of bugs, so it's recommended to use it always.
*/
library SafeMath {
/**
* @dev Returns the addition of two unsigned integers, 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;
}
}
// File: @openzeppelin/contracts/utils/Address.sol
pragma solidity >=0.6.2 <0.8.0;
/**
* @dev Collection of functions related to the address type
*/
library Address {
/**
* @dev Returns true if `account` is a contract.
*
* [IMPORTANT]
* ====
* It is unsafe to assume that an address for which this function returns
* false is an externally-owned account (EOA) and not a contract.
*
* Among others, `isContract` will return false for the following
* types of addresses:
*
* - an externally-owned account
* - a contract in construction
* - an address where a contract will be created
* - an address where a contract lived, but was destroyed
* ====
*/
function isContract(address account) internal view returns (bool) {
// This method relies on extcodesize, which returns 0 for contracts in
// construction, since the code is only stored at the end of the
// constructor execution.
uint256 size;
// solhint-disable-next-line no-inline-assembly
assembly { size := extcodesize(account) }
return size > 0;
}
/**
* @dev Replacement for Solidity's `transfer`: sends `amount` wei to
* `recipient`, forwarding all available gas and reverting on errors.
*
* https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost
* of certain opcodes, possibly making contracts go over the 2300 gas limit
* imposed by `transfer`, making them unable to receive funds via
* `transfer`. {sendValue} removes this limitation.
*
* https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more].
*
* IMPORTANT: because control is transferred to `recipient`, care must be
* taken to not create reentrancy vulnerabilities. Consider using
* {ReentrancyGuard} or the
* https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern].
*/
function sendValue(address payable recipient, uint256 amount) internal {
require(address(this).balance >= amount, "Address: insufficient balance");
// solhint-disable-next-line avoid-low-level-calls, avoid-call-value
(bool success, ) = recipient.call{ value: amount }("");
require(success, "Address: unable to send value, recipient may have reverted");
}
/**
* @dev Performs a Solidity function call using a low level `call`. A
* plain`call` is an unsafe replacement for a function call: use this
* function instead.
*
* If `target` reverts with a revert reason, it is bubbled up by this
* function (like regular Solidity function calls).
*
* Returns the raw returned data. To convert to the expected return value,
* use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`].
*
* Requirements:
*
* - `target` must be a contract.
* - calling `target` with `data` must not revert.
*
* _Available since v3.1._
*/
function functionCall(address target, bytes memory data) internal returns (bytes memory) {
return functionCall(target, data, "Address: low-level call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with
* `errorMessage` as a fallback revert reason when `target` reverts.
*
* _Available since v3.1._
*/
function functionCall(address target, bytes memory data, string memory errorMessage) internal returns (bytes memory) {
return functionCallWithValue(target, data, 0, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but also transferring `value` wei to `target`.
*
* Requirements:
*
* - the calling contract must have an ETH balance of at least `value`.
* - the called Solidity function must be `payable`.
*
* _Available since v3.1._
*/
function functionCallWithValue(address target, bytes memory data, uint256 value) internal returns (bytes memory) {
return functionCallWithValue(target, data, value, "Address: low-level call with value failed");
}
/**
* @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but
* with `errorMessage` as a fallback revert reason when `target` reverts.
*
* _Available since v3.1._
*/
function functionCallWithValue(address target, bytes memory data, uint256 value, string memory errorMessage) internal returns (bytes memory) {
require(address(this).balance >= value, "Address: insufficient balance for call");
require(isContract(target), "Address: call to non-contract");
// solhint-disable-next-line avoid-low-level-calls
(bool success, bytes memory returndata) = target.call{ value: value }(data);
return _verifyCallResult(success, returndata, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but performing a static call.
*
* _Available since v3.3._
*/
function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) {
return functionStaticCall(target, data, "Address: low-level static call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`],
* but performing a static call.
*
* _Available since v3.3._
*/
function functionStaticCall(address target, bytes memory data, string memory errorMessage) internal view returns (bytes memory) {
require(isContract(target), "Address: static call to non-contract");
// solhint-disable-next-line avoid-low-level-calls
(bool success, bytes memory returndata) = target.staticcall(data);
return _verifyCallResult(success, returndata, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but performing a delegate call.
*
* _Available since v3.4._
*/
function functionDelegateCall(address target, bytes memory data) internal returns (bytes memory) {
return functionDelegateCall(target, data, "Address: low-level delegate call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`],
* but performing a delegate call.
*
* _Available since v3.4._
*/
function functionDelegateCall(address target, bytes memory data, string memory errorMessage) internal returns (bytes memory) {
require(isContract(target), "Address: delegate call to non-contract");
// solhint-disable-next-line avoid-low-level-calls
(bool success, bytes memory returndata) = target.delegatecall(data);
return _verifyCallResult(success, returndata, errorMessage);
}
function _verifyCallResult(bool success, bytes memory returndata, string memory errorMessage) private pure returns(bytes memory) {
if (success) {
return returndata;
} else {
// Look for revert reason and bubble it up if present
if (returndata.length > 0) {
// The easiest way to bubble the revert reason is using memory via assembly
// solhint-disable-next-line no-inline-assembly
assembly {
let returndata_size := mload(returndata)
revert(add(32, returndata), returndata_size)
}
} else {
revert(errorMessage);
}
}
}
}
// File: @openzeppelin/contracts/utils/EnumerableSet.sol
pragma solidity >=0.6.0 <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 `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;
// When the value to delete is the last one, the swap operation is unnecessary. However, since this occurs
// so rarely, we still do the swap anyway to avoid the gas cost of adding an 'if' statement.
bytes32 lastvalue = set._values[lastIndex];
// Move the last value to the index where the value to delete is
set._values[toDeleteIndex] = lastvalue;
// Update the index for the moved value
set._indexes[lastvalue] = toDeleteIndex + 1; // All indexes are 1-based
// Delete the slot where the moved value was stored
set._values.pop();
// Delete the index for the deleted slot
delete set._indexes[value];
return true;
} else {
return false;
}
}
/**
* @dev Returns true if the value is in the set. O(1).
*/
function _contains(Set storage set, bytes32 value) private view returns (bool) {
return set._indexes[value] != 0;
}
/**
* @dev Returns the number of values on the set. O(1).
*/
function _length(Set storage set) private view returns (uint256) {
return set._values.length;
}
/**
* @dev Returns the value stored at position `index` in the set. O(1).
*
* Note that there are no guarantees on the ordering of values inside the
* array, and it may change when more values are added or removed.
*
* Requirements:
*
* - `index` must be strictly less than {length}.
*/
function _at(Set storage set, uint256 index) private view returns (bytes32) {
require(set._values.length > index, "EnumerableSet: index out of bounds");
return set._values[index];
}
// 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);
}
// 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))));
}
// UintSet
struct UintSet {
Set _inner;
}
/**
* @dev Add a value to a set. O(1).
*
* Returns true if the value was added to the set, that is if it was not
* already present.
*/
function add(UintSet storage set, uint256 value) internal returns (bool) {
return _add(set._inner, bytes32(value));
}
/**
* @dev Removes a value from a set. O(1).
*
* Returns true if the value was removed from the set, that is if it was
* present.
*/
function remove(UintSet storage set, uint256 value) internal returns (bool) {
return _remove(set._inner, bytes32(value));
}
/**
* @dev Returns true if the value is in the set. O(1).
*/
function contains(UintSet storage set, uint256 value) internal view returns (bool) {
return _contains(set._inner, bytes32(value));
}
/**
* @dev Returns the number of values on the set. O(1).
*/
function length(UintSet storage set) internal view returns (uint256) {
return _length(set._inner);
}
/**
* @dev Returns the value stored at position `index` in the set. O(1).
*
* Note that there are no guarantees on the ordering of values inside the
* array, and it may change when more values are added or removed.
*
* Requirements:
*
* - `index` must be strictly less than {length}.
*/
function at(UintSet storage set, uint256 index) internal view returns (uint256) {
return uint256(_at(set._inner, index));
}
}
// File: @openzeppelin/contracts/utils/EnumerableMap.sol
pragma solidity >=0.6.0 <0.8.0;
/**
* @dev Library for managing an enumerable variant of Solidity's
* https://solidity.readthedocs.io/en/latest/types.html#mapping-types[`mapping`]
* type.
*
* Maps have the following properties:
*
* - Entries are added, removed, and checked for existence in constant time
* (O(1)).
* - Entries are enumerated in O(n). No guarantees are made on the ordering.
*
* ```
* contract Example {
* // Add the library methods
* using EnumerableMap for EnumerableMap.UintToAddressMap;
*
* // Declare a set state variable
* EnumerableMap.UintToAddressMap private myMap;
* }
* ```
*
* As of v3.0.0, only maps of type `uint256 -> address` (`UintToAddressMap`) are
* supported.
*/
library EnumerableMap {
// To implement this library for multiple types with as little code
// repetition as possible, we write it in terms of a generic Map type with
// bytes32 keys and values.
// The Map implementation uses private functions, and user-facing
// implementations (such as Uint256ToAddressMap) are just wrappers around
// the underlying Map.
// This means that we can only create new EnumerableMaps for types that fit
// in bytes32.
struct MapEntry {
bytes32 _key;
bytes32 _value;
}
struct Map {
// Storage of map keys and values
MapEntry[] _entries;
// Position of the entry defined by a key in the `entries` array, plus 1
// because index 0 means a key is not in the map.
mapping (bytes32 => uint256) _indexes;
}
/**
* @dev Adds a key-value pair to a map, or updates the value for an existing
* key. O(1).
*
* Returns true if the key was added to the map, that is if it was not
* already present.
*/
function _set(Map storage map, bytes32 key, bytes32 value) private returns (bool) {
// We read and store the key's index to prevent multiple reads from the same storage slot
uint256 keyIndex = map._indexes[key];
if (keyIndex == 0) { // Equivalent to !contains(map, key)
map._entries.push(MapEntry({ _key: key, _value: value }));
// The entry is stored at length-1, but we add 1 to all indexes
// and use 0 as a sentinel value
map._indexes[key] = map._entries.length;
return true;
} else {
map._entries[keyIndex - 1]._value = value;
return false;
}
}
/**
* @dev Removes a key-value pair from a map. O(1).
*
* Returns true if the key was removed from the map, that is if it was present.
*/
function _remove(Map storage map, bytes32 key) private returns (bool) {
// We read and store the key's index to prevent multiple reads from the same storage slot
uint256 keyIndex = map._indexes[key];
if (keyIndex != 0) { // Equivalent to contains(map, key)
// To delete a key-value pair from the _entries array in O(1), we swap the entry to delete with the last one
// in the array, and then remove the last entry (sometimes called as 'swap and pop').
// This modifies the order of the array, as noted in {at}.
uint256 toDeleteIndex = keyIndex - 1;
uint256 lastIndex = map._entries.length - 1;
// When the entry to delete is the last one, the swap operation is unnecessary. However, since this occurs
// so rarely, we still do the swap anyway to avoid the gas cost of adding an 'if' statement.
MapEntry storage lastEntry = map._entries[lastIndex];
// Move the last entry to the index where the entry to delete is
map._entries[toDeleteIndex] = lastEntry;
// Update the index for the moved entry
map._indexes[lastEntry._key] = toDeleteIndex + 1; // All indexes are 1-based
// Delete the slot where the moved entry was stored
map._entries.pop();
// Delete the index for the deleted slot
delete map._indexes[key];
return true;
} else {
return false;
}
}
/**
* @dev Returns true if the key is in the map. O(1).
*/
function _contains(Map storage map, bytes32 key) private view returns (bool) {
return map._indexes[key] != 0;
}
/**
* @dev Returns the number of key-value pairs in the map. O(1).
*/
function _length(Map storage map) private view returns (uint256) {
return map._entries.length;
}
/**
* @dev Returns the key-value pair stored at position `index` in the map. O(1).
*
* Note that there are no guarantees on the ordering of entries inside the
* array, and it may change when more entries are added or removed.
*
* Requirements:
*
* - `index` must be strictly less than {length}.
*/
function _at(Map storage map, uint256 index) private view returns (bytes32, bytes32) {
require(map._entries.length > index, "EnumerableMap: index out of bounds");
MapEntry storage entry = map._entries[index];
return (entry._key, entry._value);
}
/**
* @dev Tries to returns the value associated with `key`. O(1).
* Does not revert if `key` is not in the map.
*/
function _tryGet(Map storage map, bytes32 key) private view returns (bool, bytes32) {
uint256 keyIndex = map._indexes[key];
if (keyIndex == 0) return (false, 0); // Equivalent to contains(map, key)
return (true, map._entries[keyIndex - 1]._value); // All indexes are 1-based
}
/**
* @dev Returns the value associated with `key`. O(1).
*
* Requirements:
*
* - `key` must be in the map.
*/
function _get(Map storage map, bytes32 key) private view returns (bytes32) {
uint256 keyIndex = map._indexes[key];
require(keyIndex != 0, "EnumerableMap: nonexistent key"); // Equivalent to contains(map, key)
return map._entries[keyIndex - 1]._value; // All indexes are 1-based
}
/**
* @dev Same as {_get}, with a custom error message when `key` is not in the map.
*
* CAUTION: This function is deprecated because it requires allocating memory for the error
* message unnecessarily. For custom revert reasons use {_tryGet}.
*/
function _get(Map storage map, bytes32 key, string memory errorMessage) private view returns (bytes32) {
uint256 keyIndex = map._indexes[key];
require(keyIndex != 0, errorMessage); // Equivalent to contains(map, key)
return map._entries[keyIndex - 1]._value; // All indexes are 1-based
}
// UintToAddressMap
struct UintToAddressMap {
Map _inner;
}
/**
* @dev Adds a key-value pair to a map, or updates the value for an existing
* key. O(1).
*
* Returns true if the key was added to the map, that is if it was not
* already present.
*/
function set(UintToAddressMap storage map, uint256 key, address value) internal returns (bool) {
return _set(map._inner, bytes32(key), bytes32(uint256(uint160(value))));
}
/**
* @dev Removes a value from a set. O(1).
*
* Returns true if the key was removed from the map, that is if it was present.
*/
function remove(UintToAddressMap storage map, uint256 key) internal returns (bool) {
return _remove(map._inner, bytes32(key));
}
/**
* @dev Returns true if the key is in the map. O(1).
*/
function contains(UintToAddressMap storage map, uint256 key) internal view returns (bool) {
return _contains(map._inner, bytes32(key));
}
/**
* @dev Returns the number of elements in the map. O(1).
*/
function length(UintToAddressMap storage map) internal view returns (uint256) {
return _length(map._inner);
}
/**
* @dev Returns the element 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(UintToAddressMap storage map, uint256 index) internal view returns (uint256, address) {
(bytes32 key, bytes32 value) = _at(map._inner, index);
return (uint256(key), address(uint160(uint256(value))));
}
/**
* @dev Tries to returns the value associated with `key`. O(1).
* Does not revert if `key` is not in the map.
*
* _Available since v3.4._
*/
function tryGet(UintToAddressMap storage map, uint256 key) internal view returns (bool, address) {
(bool success, bytes32 value) = _tryGet(map._inner, bytes32(key));
return (success, address(uint160(uint256(value))));
}
/**
* @dev Returns the value associated with `key`. O(1).
*
* Requirements:
*
* - `key` must be in the map.
*/
function get(UintToAddressMap storage map, uint256 key) internal view returns (address) {
return address(uint160(uint256(_get(map._inner, bytes32(key)))));
}
/**
* @dev Same as {get}, with a custom error message when `key` is not in the map.
*
* CAUTION: This function is deprecated because it requires allocating memory for the error
* message unnecessarily. For custom revert reasons use {tryGet}.
*/
function get(UintToAddressMap storage map, uint256 key, string memory errorMessage) internal view returns (address) {
return address(uint160(uint256(_get(map._inner, bytes32(key), errorMessage))));
}
}
// File: @openzeppelin/contracts/utils/Strings.sol
pragma solidity >=0.6.0 <0.8.0;
/**
* @dev String operations.
*/
library Strings {
/**
* @dev Converts a `uint256` to its ASCII `string` 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);
uint256 index = digits - 1;
temp = value;
while (temp != 0) {
buffer[index--] = bytes1(uint8(48 + temp % 10));
temp /= 10;
}
return string(buffer);
}
}
// File: @openzeppelin/contracts/token/ERC721/ERC721.sol
pragma solidity >=0.6.0 <0.8.0;
/**
* @title ERC721 Non-Fungible Token Standard basic implementation
* @dev see https://eips.ethereum.org/EIPS/eip-721
*/
contract ERC721 is Context, ERC165, IERC721, IERC721Metadata, IERC721Enumerable {
using SafeMath for uint256;
using Address for address;
using EnumerableSet for EnumerableSet.UintSet;
using EnumerableMap for EnumerableMap.UintToAddressMap;
using Strings for uint256;
// Equals to `bytes4(keccak256("onERC721Received(address,address,uint256,bytes)"))`
// which can be also obtained as `IERC721Receiver(0).onERC721Received.selector`
bytes4 private constant _ERC721_RECEIVED = 0x150b7a02;
// Mapping from holder address to their (enumerable) set of owned tokens
mapping (address => EnumerableSet.UintSet) private _holderTokens;
// Enumerable mapping from token ids to their owners
EnumerableMap.UintToAddressMap private _tokenOwners;
// 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;
// Token name
string private _name;
// Token symbol
string private _symbol;
// Optional mapping for token URIs
mapping (uint256 => string) private _tokenURIs;
// Base URI
string private _baseURI;
/*
* bytes4(keccak256('balanceOf(address)')) == 0x70a08231
* bytes4(keccak256('ownerOf(uint256)')) == 0x6352211e
* bytes4(keccak256('approve(address,uint256)')) == 0x095ea7b3
* bytes4(keccak256('getApproved(uint256)')) == 0x081812fc
* bytes4(keccak256('setApprovalForAll(address,bool)')) == 0xa22cb465
* bytes4(keccak256('isApprovedForAll(address,address)')) == 0xe985e9c5
* bytes4(keccak256('transferFrom(address,address,uint256)')) == 0x23b872dd
* bytes4(keccak256('safeTransferFrom(address,address,uint256)')) == 0x42842e0e
* bytes4(keccak256('safeTransferFrom(address,address,uint256,bytes)')) == 0xb88d4fde
*
* => 0x70a08231 ^ 0x6352211e ^ 0x095ea7b3 ^ 0x081812fc ^
* 0xa22cb465 ^ 0xe985e9c5 ^ 0x23b872dd ^ 0x42842e0e ^ 0xb88d4fde == 0x80ac58cd
*/
bytes4 private constant _INTERFACE_ID_ERC721 = 0x80ac58cd;
/*
* bytes4(keccak256('name()')) == 0x06fdde03
* bytes4(keccak256('symbol()')) == 0x95d89b41
* bytes4(keccak256('tokenURI(uint256)')) == 0xc87b56dd
*
* => 0x06fdde03 ^ 0x95d89b41 ^ 0xc87b56dd == 0x5b5e139f
*/
bytes4 private constant _INTERFACE_ID_ERC721_METADATA = 0x5b5e139f;
/*
* bytes4(keccak256('totalSupply()')) == 0x18160ddd
* bytes4(keccak256('tokenOfOwnerByIndex(address,uint256)')) == 0x2f745c59
* bytes4(keccak256('tokenByIndex(uint256)')) == 0x4f6ccce7
*
* => 0x18160ddd ^ 0x2f745c59 ^ 0x4f6ccce7 == 0x780e9d63
*/
bytes4 private constant _INTERFACE_ID_ERC721_ENUMERABLE = 0x780e9d63;
/**
* @dev Initializes the contract by setting a `name` and a `symbol` to the token collection.
*/
constructor (string memory name_, string memory symbol_) public {
_name = name_;
_symbol = symbol_;
// register the supported interfaces to conform to ERC721 via ERC165
_registerInterface(_INTERFACE_ID_ERC721);
_registerInterface(_INTERFACE_ID_ERC721_METADATA);
_registerInterface(_INTERFACE_ID_ERC721_ENUMERABLE);
}
/**
* @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 _holderTokens[owner].length();
}
/**
* @dev See {IERC721-ownerOf}.
*/
function ownerOf(uint256 tokenId) public view virtual override returns (address) {
return _tokenOwners.get(tokenId, "ERC721: owner query for nonexistent token");
}
/**
* @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 _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));
}
// If there is a baseURI but no tokenURI, concatenate the tokenID to the baseURI.
return string(abi.encodePacked(base, tokenId.toString()));
}
/**
* @dev Returns the base URI set via {_setBaseURI}. This will be
* automatically added as a prefix in {tokenURI} to each token's URI, or
* to the token ID if no specific URI is set for that token ID.
*/
function baseURI() public view virtual returns (string memory) {
return _baseURI;
}
/**
* @dev See {IERC721Enumerable-tokenOfOwnerByIndex}.
*/
function tokenOfOwnerByIndex(address owner, uint256 index) public view virtual override returns (uint256) {
return _holderTokens[owner].at(index);
}
/**
* @dev See {IERC721Enumerable-totalSupply}.
*/
function totalSupply() public view virtual override returns (uint256) {
// _tokenOwners are indexed by tokenIds, so .length() returns the number of tokenIds
return _tokenOwners.length();
}
/**
* @dev See {IERC721Enumerable-tokenByIndex}.
*/
function tokenByIndex(uint256 index) public view virtual override returns (uint256) {
(uint256 tokenId, ) = _tokenOwners.at(index);
return tokenId;
}
/**
* @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 || ERC721.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 _tokenOwners.contains(tokenId);
}
/**
* @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 || ERC721.isApprovedForAll(owner, spender));
}
/**
* @dev Safely mints `tokenId` and transfers it to `to`.
*
* Requirements:
d*
* - `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);
_holderTokens[to].add(tokenId);
_tokenOwners.set(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); // internal owner
_beforeTokenTransfer(owner, address(0), tokenId);
// Clear approvals
_approve(address(0), tokenId);
// Clear metadata (if any)
if (bytes(_tokenURIs[tokenId]).length != 0) {
delete _tokenURIs[tokenId];
}
_holderTokens[owner].remove(tokenId);
_tokenOwners.remove(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"); // internal owner
require(to != address(0), "ERC721: transfer to the zero address");
_beforeTokenTransfer(from, to, tokenId);
// Clear approvals from the previous owner
_approve(address(0), tokenId);
_holderTokens[from].remove(tokenId);
_holderTokens[to].add(tokenId);
_tokenOwners.set(tokenId, to);
emit Transfer(from, to, 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), "ERC721Metadata: URI set of nonexistent token");
_tokenURIs[tokenId] = _tokenURI;
}
/**
* @dev Internal function to set the base URI for all token IDs. It is
* automatically added as a prefix to the value returned in {tokenURI},
* or to the token ID if {tokenURI} is empty.
*/
function _setBaseURI(string memory baseURI_) internal virtual {
_baseURI = baseURI_;
}
/**
* @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()) {
return true;
}
bytes memory returndata = to.functionCall(abi.encodeWithSelector(
IERC721Receiver(to).onERC721Received.selector,
_msgSender(),
from,
tokenId,
_data
), "ERC721: transfer to non ERC721Receiver implementer");
bytes4 retval = abi.decode(returndata, (bytes4));
return (retval == _ERC721_RECEIVED);
}
/**
* @dev Approve `to` to operate on `tokenId`
*
* Emits an {Approval} event.
*/
function _approve(address to, uint256 tokenId) internal virtual {
_tokenApprovals[tokenId] = to;
emit Approval(ERC721.ownerOf(tokenId), to, tokenId); // internal owner
}
/**
* @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 { }
}
// File: @openzeppelin/contracts/access/Ownable.sol
pragma solidity >=0.6.0 <0.8.0;
/**
* @dev Contract module which provides a basic access control mechanism, where
* there is an account (an owner) that can be granted exclusive access to
* specific functions.
*
* By default, the owner account will be the one that deploys the contract. This
* can later be changed with {transferOwnership}.
*
* This module is used through inheritance. It will make available the modifier
* `onlyOwner`, which can be applied to your functions to restrict their use to
* the owner.
*/
abstract contract Ownable is Context {
address private _owner;
event OwnershipTransferred(address indexed previousOwner, address indexed newOwner);
/**
* @dev Initializes the contract setting the deployer as the initial owner.
*/
constructor () internal {
address msgSender = _msgSender();
_owner = msgSender;
emit OwnershipTransferred(address(0), msgSender);
}
/**
* @dev Returns the address of the current owner.
*/
function owner() public view 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;
}
}
// PIXMONS CONTRACT
pragma solidity ^0.7.0;
pragma abicoder v2;
contract PixMons is ERC721, Ownable {
using SafeMath for uint256;
string public PIXMON_PROVENANCE = ""; // IPFS URL WILL BE ADDED WHEN PIXMONS ARE ALL SOLD OUT
string public LICENSE_TEXT = ""; // IT IS WHAT IT SAYS
bool licenseLocked = false; // TEAM CAN'T EDIT THE LICENSE AFTER THIS GETS TRUE
uint256 public constant pixmonPrice = 30000000000000000; // 0.03 ETH
uint public constant maxPixmonPurchase = 20;
uint256 public constant MAX_PIXMONS = 512;
bool public saleIsActive = false;
mapping(uint => string) public pixmonNames;
// Reserve 25 PIXMONS for team - Giveaways/Prizes etc
uint public pixmonReserve = 25;
event pixmonNameChange(address _by, uint _tokenId, string _name);
event licenseisLocked(string _licenseText);
constructor() ERC721("PixMons", "PM") { }
function withdraw() public onlyOwner {
uint balance = address(this).balance;
msg.sender.transfer(balance);
}
function reservePixmons(address _to, uint256 _reserveAmount) public onlyOwner {
uint supply = totalSupply();
require(_reserveAmount > 0 && _reserveAmount <= pixmonReserve, "Not enough reserve left for team");
for (uint i = 0; i < _reserveAmount; i++) {
_safeMint(_to, supply + i);
}
pixmonReserve = pixmonReserve.sub(_reserveAmount);
}
function setProvenanceHash(string memory provenanceHash) public onlyOwner {
PIXMON_PROVENANCE = provenanceHash;
}
function setBaseURI(string memory baseURI) public onlyOwner {
_setBaseURI(baseURI);
}
function flipSaleState() public onlyOwner {
saleIsActive = !saleIsActive;
}
function tokensOfOwner(address _owner) external view returns(uint256[] memory ) {
uint256 tokenCount = balanceOf(_owner);
if (tokenCount == 0) {
// Return an empty array
return new uint256[](0);
} else {
uint256[] memory result = new uint256[](tokenCount);
uint256 index;
for (index = 0; index < tokenCount; index++) {
result[index] = tokenOfOwnerByIndex(_owner, index);
}
return result;
}
}
// Returns the license for tokens
function tokenLicense(uint _id) public view returns(string memory) {
require(_id < totalSupply(), "CHOOSE A PIXMON WITHIN RANGE");
return LICENSE_TEXT;
}
// Locks the license to prevent further changes
function lockLicense() public onlyOwner {
licenseLocked = true;
emit licenseisLocked(LICENSE_TEXT);
}
// Change the license
function changeLicense(string memory _license) public onlyOwner {
require(licenseLocked == false, "License already locked");
LICENSE_TEXT = _license;
}
function mintPixmon(uint numberOfTokens) public payable {
require(saleIsActive, "Sale must be active to mint a Pixmon");
require(numberOfTokens > 0 && numberOfTokens <= maxPixmonPurchase, "Can only mint 20 tokens at a time");
require(totalSupply().add(numberOfTokens) <= MAX_PIXMONS, "Purchase would exceed max supply of Pixmons");
require(msg.value >= pixmonPrice.mul(numberOfTokens), "Ether value sent is not correct");
for(uint i = 0; i < numberOfTokens; i++) {
uint mintIndex = totalSupply();
if (totalSupply() < MAX_PIXMONS) {
_safeMint(msg.sender, mintIndex);
}
}
}
function changePixmonName(uint _tokenId, string memory _name) public {
require(ownerOf(_tokenId) == msg.sender, "Hey, your wallet doesn't own this pixmon!");
require(sha256(bytes(_name)) != sha256(bytes(pixmonNames[_tokenId])), "New name is same as the current one");
pixmonNames[_tokenId] = _name;
emit pixmonNameChange(msg.sender, _tokenId, _name);
}
function viewPixmonName(uint _tokenId) public view returns( string memory ){
require( _tokenId < totalSupply(), "Choose a pixmon within range" );
return pixmonNames[_tokenId];
}
// GET ALL PIXMONS OF A WALLET AS AN ARRAY OF STRINGS. WOULD BE BETTER MAYBE IF IT RETURNED A STRUCT WITH ID-NAME MATCH
function pixmonNamesOfOwner(address _owner) external view returns(string[] memory ) {
uint256 tokenCount = balanceOf(_owner);
if (tokenCount == 0) {
// Return an empty array
return new string[](0);
} else {
string[] memory result = new string[](tokenCount);
uint256 index;
for (index = 0; index < tokenCount; index++) {
result[index] = pixmonNames[ tokenOfOwnerByIndex(_owner, index) ] ;
}
return result;
}
}
} | GET ALL PIXMONS OF A WALLET AS AN ARRAY OF STRINGS. WOULD BE BETTER MAYBE IF IT RETURNED A STRUCT WITH ID-NAME MATCH Return an empty array | function pixmonNamesOfOwner(address _owner) external view returns(string[] memory ) {
uint256 tokenCount = balanceOf(_owner);
if (tokenCount == 0) {
return new string[](0);
string[] memory result = new string[](tokenCount);
uint256 index;
for (index = 0; index < tokenCount; index++) {
result[index] = pixmonNames[ tokenOfOwnerByIndex(_owner, index) ] ;
}
return result;
}
}
| 13,638,844 | [
1,
3264,
8061,
7024,
60,
17667,
55,
15932,
432,
30293,
15146,
5355,
8175,
14884,
15932,
9469,
55,
18,
678,
31090,
9722,
9722,
11976,
490,
5255,
5948,
11083,
24142,
14780,
2056,
432,
7128,
9749,
13601,
1599,
17,
1985,
16585,
2000,
392,
1008,
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
] | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
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
] | [
1,
565,
445,
11871,
2586,
1557,
951,
5541,
12,
2867,
389,
8443,
13,
3903,
1476,
1135,
12,
1080,
8526,
3778,
262,
288,
203,
3639,
2254,
5034,
1147,
1380,
273,
11013,
951,
24899,
8443,
1769,
203,
3639,
309,
261,
2316,
1380,
422,
374,
13,
288,
203,
5411,
327,
394,
533,
8526,
12,
20,
1769,
203,
5411,
533,
8526,
3778,
563,
273,
394,
533,
8526,
12,
2316,
1380,
1769,
203,
5411,
2254,
5034,
770,
31,
203,
5411,
364,
261,
1615,
273,
374,
31,
770,
411,
1147,
1380,
31,
770,
27245,
288,
203,
7734,
563,
63,
1615,
65,
273,
11871,
2586,
1557,
63,
1147,
951,
5541,
21268,
24899,
8443,
16,
770,
13,
308,
274,
203,
5411,
289,
203,
5411,
327,
563,
31,
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
] |
./full_match/4/0xAafD067754cb94973f33599a3cC2e6f119b99AbB/sources/contracts/EthanolX-01.sol | claim accumulated cashbacks calculate tax from transferred amount transfer tokens to the recipient update allowance refund current gasfee spent on Uniswap sell | function transferFrom(address sender, address recipient, uint256 amount) public virtual override returns (bool) {
_claimCashback(recipient);
(uint256 _finalAmount,) = _taxFee(recipient, amount);
_transfer(sender, recipient, _finalAmount);
uint256 currentAllowance = _allowances[sender][_msgSender()];
require(currentAllowance >= amount, "ERC20: transfer amount exceeds allowance");
_approve(sender, _msgSender(), currentAllowance - amount);
_refundsBuySellGasFee(sender);
return true;
}
| 758,505 | [
1,
14784,
24893,
276,
961,
823,
87,
4604,
5320,
628,
906,
4193,
3844,
7412,
2430,
358,
326,
8027,
1089,
1699,
1359,
16255,
783,
16189,
21386,
26515,
603,
1351,
291,
91,
438,
357,
80,
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,
7412,
1265,
12,
2867,
5793,
16,
1758,
8027,
16,
2254,
5034,
3844,
13,
1071,
5024,
3849,
1135,
261,
6430,
13,
288,
203,
3639,
389,
14784,
39,
961,
823,
12,
20367,
1769,
203,
203,
3639,
261,
11890,
5034,
389,
6385,
6275,
16,
13,
273,
389,
8066,
14667,
12,
20367,
16,
3844,
1769,
203,
203,
3639,
389,
13866,
12,
15330,
16,
8027,
16,
389,
6385,
6275,
1769,
203,
540,
203,
3639,
2254,
5034,
783,
7009,
1359,
273,
389,
5965,
6872,
63,
15330,
6362,
67,
3576,
12021,
1435,
15533,
203,
3639,
2583,
12,
2972,
7009,
1359,
1545,
3844,
16,
315,
654,
39,
3462,
30,
7412,
3844,
14399,
1699,
1359,
8863,
203,
3639,
389,
12908,
537,
12,
15330,
16,
389,
3576,
12021,
9334,
783,
7009,
1359,
300,
3844,
1769,
203,
203,
3639,
389,
1734,
19156,
38,
9835,
55,
1165,
27998,
14667,
12,
15330,
1769,
203,
3639,
327,
638,
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
] |
./partial_match/1313161554/0x2ABB0ea3A5C038f60E677Bf14d2F6095786650Ae/sources/StrategyRoseUSTLP.sol | Tokens used Third party contracts Routes | contract StrategyRoseUSTLP is StratManager, FeeManager, GasThrottler {
using SafeERC20 for IERC20;
using SafeMath for uint256;
address public native;
address public output;
address public reward;
address public stable;
address public want;
address public rewardPool;
address public metaRouter;
uint256 public lastHarvest;
uint256 public liquidityBal;
bool public feesCharged = false;
bool public harvestAndSwapped = false;
bool public swapped = false;
bool public liquidityAdded = false;
bool public harvested = false;
address[] public outputToNativeRoute;
address[] public rewardToOutputRoute;
address[] public outputToStableRoute;
event StratHarvest(address indexed harvester, uint256 wantHarvested, uint256 tvl);
event Deposit(uint256 tvl);
event Withdraw(uint256 tvl);
event ChargedFees(uint256 callFees, uint256 beefyFees, uint256 strategistFees);
constructor(
address _want,
address _rewardPool,
address _metaRouter,
address _vault,
address _unirouter,
address _keeper,
address _strategist,
address _beefyFeeRecipient,
address[] memory _outputToNativeRoute,
address[] memory _rewardToOutputRoute,
address[] memory _outputToStableRoute
) StratManager(_keeper, _strategist, _unirouter, _vault, _beefyFeeRecipient) public {
want = _want;
rewardPool = _rewardPool;
metaRouter = _metaRouter;
output = _outputToNativeRoute[0];
native = _outputToNativeRoute[_outputToNativeRoute.length - 1];
outputToNativeRoute = _outputToNativeRoute;
reward = _rewardToOutputRoute[0];
rewardToOutputRoute = _rewardToOutputRoute;
stable = _outputToStableRoute[_outputToStableRoute.length - 1];
outputToStableRoute = _outputToStableRoute;
_giveAllowances();
}
function deposit() public whenNotPaused {}
function sweep() public whenNotPaused {
if (balanceOfWant() > 0) {
IMultiRewards(rewardPool).stake(balanceOfWant());
emit Deposit(balanceOfWant());
}
}
function sweep() public whenNotPaused {
if (balanceOfWant() > 0) {
IMultiRewards(rewardPool).stake(balanceOfWant());
emit Deposit(balanceOfWant());
}
}
function withdraw(uint256 _amount) external {
require(msg.sender == vault, "!vault");
uint256 wantBal = IERC20(want).balanceOf(address(this));
if (wantBal < _amount) {
IMultiRewards(rewardPool).withdraw(_amount.sub(wantBal));
wantBal = IERC20(want).balanceOf(address(this));
}
if (wantBal > _amount) {
wantBal = _amount;
}
if (tx.origin != owner() && !paused()) {
uint256 withdrawalFeeAmount = wantBal.mul(withdrawalFee).div(WITHDRAWAL_MAX);
wantBal = wantBal.sub(withdrawalFeeAmount);
}
IERC20(want).safeTransfer(vault, wantBal);
emit Withdraw(balanceOf());
}
function withdraw(uint256 _amount) external {
require(msg.sender == vault, "!vault");
uint256 wantBal = IERC20(want).balanceOf(address(this));
if (wantBal < _amount) {
IMultiRewards(rewardPool).withdraw(_amount.sub(wantBal));
wantBal = IERC20(want).balanceOf(address(this));
}
if (wantBal > _amount) {
wantBal = _amount;
}
if (tx.origin != owner() && !paused()) {
uint256 withdrawalFeeAmount = wantBal.mul(withdrawalFee).div(WITHDRAWAL_MAX);
wantBal = wantBal.sub(withdrawalFeeAmount);
}
IERC20(want).safeTransfer(vault, wantBal);
emit Withdraw(balanceOf());
}
function withdraw(uint256 _amount) external {
require(msg.sender == vault, "!vault");
uint256 wantBal = IERC20(want).balanceOf(address(this));
if (wantBal < _amount) {
IMultiRewards(rewardPool).withdraw(_amount.sub(wantBal));
wantBal = IERC20(want).balanceOf(address(this));
}
if (wantBal > _amount) {
wantBal = _amount;
}
if (tx.origin != owner() && !paused()) {
uint256 withdrawalFeeAmount = wantBal.mul(withdrawalFee).div(WITHDRAWAL_MAX);
wantBal = wantBal.sub(withdrawalFeeAmount);
}
IERC20(want).safeTransfer(vault, wantBal);
emit Withdraw(balanceOf());
}
function withdraw(uint256 _amount) external {
require(msg.sender == vault, "!vault");
uint256 wantBal = IERC20(want).balanceOf(address(this));
if (wantBal < _amount) {
IMultiRewards(rewardPool).withdraw(_amount.sub(wantBal));
wantBal = IERC20(want).balanceOf(address(this));
}
if (wantBal > _amount) {
wantBal = _amount;
}
if (tx.origin != owner() && !paused()) {
uint256 withdrawalFeeAmount = wantBal.mul(withdrawalFee).div(WITHDRAWAL_MAX);
wantBal = wantBal.sub(withdrawalFeeAmount);
}
IERC20(want).safeTransfer(vault, wantBal);
emit Withdraw(balanceOf());
}
function harvest() external gasThrottle virtual {
_harvest(tx.origin);
}
function harvest(address callFeeRecipient) external gasThrottle virtual {
_harvest(callFeeRecipient);
}
function managerHarvest() external onlyManager {
_harvest(tx.origin);
}
function _harvest(address callFeeRecipient) internal whenNotPaused {
if (feesCharged) {
if (swapped){
if (liquidityAdded) {
IMultiRewards(rewardPool).stake(balanceOfWant());
toggleHarvest();
lastHarvest = block.timestamp;
emit StratHarvest(msg.sender, balanceOfWant(), balanceOf());
addLiquidity();
}
swap();
}
if (harvestAndSwapped) {
uint256 outputBal = IERC20(output).balanceOf(address(this));
if (outputBal > 0) {
chargeFees(callFeeRecipient);
}
if (harvested) {
uint256 rewardBal = IERC20(reward).balanceOf(address(this));
if (rewardBal > 0 && rewardToOutputRoute.length > 0) {
IUniswapRouterETH(unirouter).swapExactTokensForTokens(rewardBal, 0, rewardToOutputRoute, address(this), now);
}
harvestAndSwapped = true;
IMultiRewards(rewardPool).getReward();
harvested = true;
}
}
}
}
function _harvest(address callFeeRecipient) internal whenNotPaused {
if (feesCharged) {
if (swapped){
if (liquidityAdded) {
IMultiRewards(rewardPool).stake(balanceOfWant());
toggleHarvest();
lastHarvest = block.timestamp;
emit StratHarvest(msg.sender, balanceOfWant(), balanceOf());
addLiquidity();
}
swap();
}
if (harvestAndSwapped) {
uint256 outputBal = IERC20(output).balanceOf(address(this));
if (outputBal > 0) {
chargeFees(callFeeRecipient);
}
if (harvested) {
uint256 rewardBal = IERC20(reward).balanceOf(address(this));
if (rewardBal > 0 && rewardToOutputRoute.length > 0) {
IUniswapRouterETH(unirouter).swapExactTokensForTokens(rewardBal, 0, rewardToOutputRoute, address(this), now);
}
harvestAndSwapped = true;
IMultiRewards(rewardPool).getReward();
harvested = true;
}
}
}
}
function _harvest(address callFeeRecipient) internal whenNotPaused {
if (feesCharged) {
if (swapped){
if (liquidityAdded) {
IMultiRewards(rewardPool).stake(balanceOfWant());
toggleHarvest();
lastHarvest = block.timestamp;
emit StratHarvest(msg.sender, balanceOfWant(), balanceOf());
addLiquidity();
}
swap();
}
if (harvestAndSwapped) {
uint256 outputBal = IERC20(output).balanceOf(address(this));
if (outputBal > 0) {
chargeFees(callFeeRecipient);
}
if (harvested) {
uint256 rewardBal = IERC20(reward).balanceOf(address(this));
if (rewardBal > 0 && rewardToOutputRoute.length > 0) {
IUniswapRouterETH(unirouter).swapExactTokensForTokens(rewardBal, 0, rewardToOutputRoute, address(this), now);
}
harvestAndSwapped = true;
IMultiRewards(rewardPool).getReward();
harvested = true;
}
}
}
}
function _harvest(address callFeeRecipient) internal whenNotPaused {
if (feesCharged) {
if (swapped){
if (liquidityAdded) {
IMultiRewards(rewardPool).stake(balanceOfWant());
toggleHarvest();
lastHarvest = block.timestamp;
emit StratHarvest(msg.sender, balanceOfWant(), balanceOf());
addLiquidity();
}
swap();
}
if (harvestAndSwapped) {
uint256 outputBal = IERC20(output).balanceOf(address(this));
if (outputBal > 0) {
chargeFees(callFeeRecipient);
}
if (harvested) {
uint256 rewardBal = IERC20(reward).balanceOf(address(this));
if (rewardBal > 0 && rewardToOutputRoute.length > 0) {
IUniswapRouterETH(unirouter).swapExactTokensForTokens(rewardBal, 0, rewardToOutputRoute, address(this), now);
}
harvestAndSwapped = true;
IMultiRewards(rewardPool).getReward();
harvested = true;
}
}
}
}
} else {
} else {
} else {
function _harvest(address callFeeRecipient) internal whenNotPaused {
if (feesCharged) {
if (swapped){
if (liquidityAdded) {
IMultiRewards(rewardPool).stake(balanceOfWant());
toggleHarvest();
lastHarvest = block.timestamp;
emit StratHarvest(msg.sender, balanceOfWant(), balanceOf());
addLiquidity();
}
swap();
}
if (harvestAndSwapped) {
uint256 outputBal = IERC20(output).balanceOf(address(this));
if (outputBal > 0) {
chargeFees(callFeeRecipient);
}
if (harvested) {
uint256 rewardBal = IERC20(reward).balanceOf(address(this));
if (rewardBal > 0 && rewardToOutputRoute.length > 0) {
IUniswapRouterETH(unirouter).swapExactTokensForTokens(rewardBal, 0, rewardToOutputRoute, address(this), now);
}
harvestAndSwapped = true;
IMultiRewards(rewardPool).getReward();
harvested = true;
}
}
}
}
function _harvest(address callFeeRecipient) internal whenNotPaused {
if (feesCharged) {
if (swapped){
if (liquidityAdded) {
IMultiRewards(rewardPool).stake(balanceOfWant());
toggleHarvest();
lastHarvest = block.timestamp;
emit StratHarvest(msg.sender, balanceOfWant(), balanceOf());
addLiquidity();
}
swap();
}
if (harvestAndSwapped) {
uint256 outputBal = IERC20(output).balanceOf(address(this));
if (outputBal > 0) {
chargeFees(callFeeRecipient);
}
if (harvested) {
uint256 rewardBal = IERC20(reward).balanceOf(address(this));
if (rewardBal > 0 && rewardToOutputRoute.length > 0) {
IUniswapRouterETH(unirouter).swapExactTokensForTokens(rewardBal, 0, rewardToOutputRoute, address(this), now);
}
harvestAndSwapped = true;
IMultiRewards(rewardPool).getReward();
harvested = true;
}
}
}
}
} else {
function _harvest(address callFeeRecipient) internal whenNotPaused {
if (feesCharged) {
if (swapped){
if (liquidityAdded) {
IMultiRewards(rewardPool).stake(balanceOfWant());
toggleHarvest();
lastHarvest = block.timestamp;
emit StratHarvest(msg.sender, balanceOfWant(), balanceOf());
addLiquidity();
}
swap();
}
if (harvestAndSwapped) {
uint256 outputBal = IERC20(output).balanceOf(address(this));
if (outputBal > 0) {
chargeFees(callFeeRecipient);
}
if (harvested) {
uint256 rewardBal = IERC20(reward).balanceOf(address(this));
if (rewardBal > 0 && rewardToOutputRoute.length > 0) {
IUniswapRouterETH(unirouter).swapExactTokensForTokens(rewardBal, 0, rewardToOutputRoute, address(this), now);
}
harvestAndSwapped = true;
IMultiRewards(rewardPool).getReward();
harvested = true;
}
}
}
}
function _harvest(address callFeeRecipient) internal whenNotPaused {
if (feesCharged) {
if (swapped){
if (liquidityAdded) {
IMultiRewards(rewardPool).stake(balanceOfWant());
toggleHarvest();
lastHarvest = block.timestamp;
emit StratHarvest(msg.sender, balanceOfWant(), balanceOf());
addLiquidity();
}
swap();
}
if (harvestAndSwapped) {
uint256 outputBal = IERC20(output).balanceOf(address(this));
if (outputBal > 0) {
chargeFees(callFeeRecipient);
}
if (harvested) {
uint256 rewardBal = IERC20(reward).balanceOf(address(this));
if (rewardBal > 0 && rewardToOutputRoute.length > 0) {
IUniswapRouterETH(unirouter).swapExactTokensForTokens(rewardBal, 0, rewardToOutputRoute, address(this), now);
}
harvestAndSwapped = true;
IMultiRewards(rewardPool).getReward();
harvested = true;
}
}
}
}
} else {
function chargeFees(address callFeeRecipient) internal {
uint256 toNative = IERC20(output).balanceOf(address(this)).mul(45).div(1000);
IUniswapRouterETH(unirouter).swapExactTokensForTokens(toNative, 0, outputToNativeRoute, address(this), now);
uint256 nativeBal = IERC20(native).balanceOf(address(this));
uint256 callFeeAmount = nativeBal.mul(callFee).div(MAX_FEE);
IERC20(native).safeTransfer(callFeeRecipient, callFeeAmount);
uint256 beefyFeeAmount = nativeBal.mul(beefyFee).div(MAX_FEE);
IERC20(native).safeTransfer(beefyFeeRecipient, beefyFeeAmount);
uint256 strategistFee = nativeBal.mul(STRATEGIST_FEE).div(MAX_FEE);
IERC20(native).safeTransfer(strategist, strategistFee);
feesCharged = true;
liquidityBal = IERC20(output).balanceOf(address(this));
bool trade = canTrade(liquidityBal, outputToStableRoute);
require(trade == true, "Not enough output");
emit ChargedFees(callFeeAmount, beefyFeeAmount, strategistFee);
}
function swap() internal {
uint256 outputRemaining = liquidityBal;
IUniswapRouterETH(unirouter).swapExactTokensForTokens(outputRemaining, 0, outputToStableRoute, address(this), now);
liquidityBal = 0;
swapped = true;
}
function addLiquidity() internal {
uint256 stableBal = IERC20(stable).balanceOf(address(this));
uint256[2] memory amounts;
amounts[0] = stableBal;
ICurveSwap2(metaRouter).add_liquidity(amounts, 0);
liquidityAdded = true;
}
function toggleHarvest() internal {
feesCharged = false;
swapped = false;
harvestAndSwapped = false;
liquidityAdded = false;
harvested = false;
}
function balanceOf() public view returns (uint256) {
return balanceOfWant().add(balanceOfPool());
}
function balanceOfWant() public view returns (uint256) {
return IERC20(want).balanceOf(address(this));
}
function balanceOfPool() public view returns (uint256 _amount) {
_amount = IMultiRewards(rewardPool).balanceOf(address(this));
}
function rewardsAvailable() public view returns (uint256) {
uint256 first = IMultiRewards(rewardPool).earned(address(this), output);
uint256 second;
if (rewardToOutputRoute.length > 0) {
uint256 rewards = IMultiRewards(rewardPool).earned(address(this), reward);
try IUniswapRouterETH(unirouter).getAmountsOut(rewards, rewardToOutputRoute)
returns (uint256[] memory amountOut)
{
second = amountOut[amountOut.length -1];
}
}
return first.add(second);
}
function rewardsAvailable() public view returns (uint256) {
uint256 first = IMultiRewards(rewardPool).earned(address(this), output);
uint256 second;
if (rewardToOutputRoute.length > 0) {
uint256 rewards = IMultiRewards(rewardPool).earned(address(this), reward);
try IUniswapRouterETH(unirouter).getAmountsOut(rewards, rewardToOutputRoute)
returns (uint256[] memory amountOut)
{
second = amountOut[amountOut.length -1];
}
}
return first.add(second);
}
function rewardsAvailable() public view returns (uint256) {
uint256 first = IMultiRewards(rewardPool).earned(address(this), output);
uint256 second;
if (rewardToOutputRoute.length > 0) {
uint256 rewards = IMultiRewards(rewardPool).earned(address(this), reward);
try IUniswapRouterETH(unirouter).getAmountsOut(rewards, rewardToOutputRoute)
returns (uint256[] memory amountOut)
{
second = amountOut[amountOut.length -1];
}
}
return first.add(second);
}
catch {}
function canTrade(uint256 tradeableOutput, address[] memory route) internal view returns (bool tradeable) {
try IUniswapRouterETH(unirouter).getAmountsOut(tradeableOutput, route)
returns (uint256[] memory amountOut)
{
uint256 amount = amountOut[amountOut.length -1];
if (amount > 0) {
tradeable = true;
}
}
catch {
tradeable = false;
}
}
function canTrade(uint256 tradeableOutput, address[] memory route) internal view returns (bool tradeable) {
try IUniswapRouterETH(unirouter).getAmountsOut(tradeableOutput, route)
returns (uint256[] memory amountOut)
{
uint256 amount = amountOut[amountOut.length -1];
if (amount > 0) {
tradeable = true;
}
}
catch {
tradeable = false;
}
}
function canTrade(uint256 tradeableOutput, address[] memory route) internal view returns (bool tradeable) {
try IUniswapRouterETH(unirouter).getAmountsOut(tradeableOutput, route)
returns (uint256[] memory amountOut)
{
uint256 amount = amountOut[amountOut.length -1];
if (amount > 0) {
tradeable = true;
}
}
catch {
tradeable = false;
}
}
function canTrade(uint256 tradeableOutput, address[] memory route) internal view returns (bool tradeable) {
try IUniswapRouterETH(unirouter).getAmountsOut(tradeableOutput, route)
returns (uint256[] memory amountOut)
{
uint256 amount = amountOut[amountOut.length -1];
if (amount > 0) {
tradeable = true;
}
}
catch {
tradeable = false;
}
}
function callReward() public view returns (uint256) {
uint256 outputBal = rewardsAvailable();
uint256 nativeBal;
try IUniswapRouterETH(unirouter).getAmountsOut(outputBal, outputToNativeRoute)
returns (uint256[] memory amountOut)
{
nativeBal = nativeBal.add(amountOut[amountOut.length -1]);
}
return nativeBal.mul(45).div(1000).mul(callFee).div(MAX_FEE);
}
function callReward() public view returns (uint256) {
uint256 outputBal = rewardsAvailable();
uint256 nativeBal;
try IUniswapRouterETH(unirouter).getAmountsOut(outputBal, outputToNativeRoute)
returns (uint256[] memory amountOut)
{
nativeBal = nativeBal.add(amountOut[amountOut.length -1]);
}
return nativeBal.mul(45).div(1000).mul(callFee).div(MAX_FEE);
}
catch {}
function setShouldGasThrottle(bool _shouldGasThrottle) external onlyManager {
shouldGasThrottle = _shouldGasThrottle;
}
function retireStrat() external {
require(msg.sender == vault, "!vault");
IMultiRewards(rewardPool).withdraw(balanceOfPool());
uint256 wantBal = IERC20(want).balanceOf(address(this));
IERC20(want).transfer(vault, wantBal);
}
function panic() public onlyManager {
pause();
IMultiRewards(rewardPool).withdraw(balanceOfPool());
}
function pause() public onlyManager {
_pause();
_removeAllowances();
}
function unpause() external onlyManager {
_unpause();
_giveAllowances();
sweep();
}
function _giveAllowances() internal {
IERC20(want).safeApprove(rewardPool, uint256(-1));
IERC20(output).safeApprove(unirouter, uint256(-1));
IERC20(reward).safeApprove(unirouter, uint256(-1));
IERC20(stable).safeApprove(metaRouter, uint256(-1));
}
function _removeAllowances() internal {
IERC20(want).safeApprove(rewardPool, 0);
IERC20(output).safeApprove(unirouter, 0);
IERC20(reward).safeApprove(unirouter, 0);
IERC20(stable).safeApprove(metaRouter, 0);
}
function outputToNative() external view returns (address[] memory) {
return outputToNativeRoute;
}
function outputToStable() external view returns (address[] memory) {
return outputToStableRoute;
}
function rewardToOutput() external view returns (address[] memory) {
return rewardToOutputRoute;
}
} | 16,946,706 | [
1,
5157,
1399,
935,
6909,
18285,
20092,
23534,
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,
19736,
54,
2584,
5996,
14461,
353,
3978,
270,
1318,
16,
30174,
1318,
16,
31849,
16238,
749,
288,
203,
565,
1450,
14060,
654,
39,
3462,
364,
467,
654,
39,
3462,
31,
203,
565,
1450,
14060,
10477,
364,
2254,
5034,
31,
203,
203,
565,
1758,
1071,
6448,
31,
203,
565,
1758,
1071,
876,
31,
203,
565,
1758,
1071,
19890,
31,
203,
565,
1758,
1071,
14114,
31,
203,
565,
1758,
1071,
2545,
31,
203,
203,
565,
1758,
1071,
19890,
2864,
31,
203,
565,
1758,
1071,
2191,
8259,
31,
203,
203,
565,
2254,
5034,
1071,
1142,
44,
297,
26923,
31,
203,
565,
2254,
5034,
1071,
4501,
372,
24237,
38,
287,
31,
203,
565,
1426,
1071,
1656,
281,
2156,
2423,
273,
629,
31,
203,
565,
1426,
1071,
17895,
26923,
1876,
12521,
1845,
273,
629,
31,
203,
565,
1426,
1071,
7720,
1845,
273,
629,
31,
203,
565,
1426,
1071,
4501,
372,
24237,
8602,
273,
629,
31,
203,
565,
1426,
1071,
17895,
90,
3149,
273,
629,
31,
203,
203,
565,
1758,
8526,
1071,
876,
774,
9220,
3255,
31,
203,
565,
1758,
8526,
1071,
19890,
774,
1447,
3255,
31,
203,
565,
1758,
8526,
1071,
876,
774,
30915,
3255,
31,
203,
203,
565,
871,
3978,
270,
44,
297,
26923,
12,
2867,
8808,
17895,
3324,
387,
16,
2254,
5034,
2545,
44,
297,
90,
3149,
16,
2254,
5034,
268,
10872,
1769,
203,
565,
871,
4019,
538,
305,
12,
11890,
5034,
268,
10872,
1769,
203,
565,
871,
3423,
9446,
12,
11890,
5034,
268,
10872,
1769,
203,
565,
871,
3703,
2423,
2954,
281,
12,
11890,
5034,
2
] |
// SPDX-License-Identifier: No License
pragma solidity ^0.8.0;
import "./ERC20/IERC20.sol";
import "./ERC20/IERC20Permit.sol";
import "./ERC20/SafeERC20.sol";
import "./interfaces/IERC3156FlashBorrower.sol";
import "./interfaces/IERC3156FlashLender.sol";
import "./interfaces/IRERC20.sol";
import "./interfaces/IRTokenProxy.sol";
import "./interfaces/IRulerCore.sol";
import "./interfaces/IOracle.sol";
import "./utils/Clones.sol";
import "./utils/Create2.sol";
import "./utils/Initializable.sol";
import "./utils/Ownable.sol";
import "./utils/ReentrancyGuard.sol";
/**
* @title RulerCore contract
* @author crypto-pumpkin
* Ruler Pair: collateral, paired token, expiry, mintRatio
* - ! Paired Token cannot be a deflationary token !
* - rTokens have same decimals of each paired token
* - all Ratios are 1e18
* - rTokens have same decimals as Paired Token
* - Collateral can be deflationary token, but not rebasing token
*/
contract RulerCore is Ownable, IRulerCore, IERC3156FlashLender, ReentrancyGuard {
using SafeERC20 for IERC20;
// following ERC3156 https://eips.ethereum.org/EIPS/eip-3156
bytes32 public constant FLASHLOAN_CALLBACK_SUCCESS = keccak256("ERC3156FlashBorrower.onFlashLoan");
bool public override paused;
IOracle public override oracle;
address public override responder;
address public override feeReceiver;
address public override rERC20Impl;
uint256 public override flashLoanRate;
address[] public override collaterals;
/// @notice collateral => minimum collateralization ratio, paired token default to 1e18
mapping(address => uint256) public override minColRatioMap;
/// @notice collateral => pairedToken => expiry => mintRatio => Pair
mapping(address => mapping(address => mapping(uint48 => mapping(uint256 => Pair)))) public override pairs;
mapping(address => Pair[]) private pairList;
mapping(address => uint256) public override feesMap;
// v1.0.2
uint256 public override depositPauseWindow;
// v1.0.3
uint256 public override redeemFeeRate;
modifier onlyNotPaused() {
require(!paused, "Ruler: paused");
_;
}
function initialize(address _rERC20Impl, address _feeReceiver) external initializer {
require(_rERC20Impl != address(0), "Ruler: _rERC20Impl cannot be 0");
require(_feeReceiver != address(0), "Ruler: _feeReceiver cannot be 0");
rERC20Impl = _rERC20Impl;
feeReceiver = _feeReceiver;
flashLoanRate = 0.00085 ether;
depositPauseWindow = 24 hours;
initializeOwner();
initializeReentrancyGuard();
}
/// @notice market make deposit, deposit paired Token to received rcTokens, considered as an immediately repaid loan
function mmDeposit(
address _col,
address _paired,
uint48 _expiry,
uint256 _mintRatio,
uint256 _rcTokenAmt
) public override onlyNotPaused nonReentrant {
Pair memory pair = pairs[_col][_paired][_expiry][_mintRatio];
_validateDepositInputs(_col, pair);
pair.rcToken.mint(msg.sender, _rcTokenAmt);
feesMap[_paired] = feesMap[_paired] + _rcTokenAmt * pair.feeRate / 1e18;
// record loan ammount to colTotal as it is equivalent to be an immediately repaid loan
uint256 colAmount = _getColAmtFromRTokenAmt(_rcTokenAmt, _col, address(pair.rcToken), pair.mintRatio);
pairs[_col][_paired][_expiry][_mintRatio].colTotal = pair.colTotal + colAmount;
// receive paired tokens from sender, deflationary token is not allowed
IERC20 pairedToken = IERC20(_paired);
uint256 pairedBalBefore = pairedToken.balanceOf(address(this));
pairedToken.safeTransferFrom(msg.sender, address(this), _rcTokenAmt);
require(pairedToken.balanceOf(address(this)) - pairedBalBefore >= _rcTokenAmt, "Ruler: transfer paired failed");
emit MarketMakeDeposit(msg.sender, _col, _paired, _expiry, _mintRatio, _rcTokenAmt);
}
function mmDepositWithPermit(
address _col,
address _paired,
uint48 _expiry,
uint256 _mintRatio,
uint256 _rcTokenAmt,
Permit calldata _pairedPermit
) external override {
_permit(_paired, _pairedPermit);
mmDeposit(_col, _paired, _expiry, _mintRatio, _rcTokenAmt);
}
/// @notice deposit collateral to a Ruler Pair, sender receives rcTokens and rrTokens
function deposit(
address _col,
address _paired,
uint48 _expiry,
uint256 _mintRatio,
uint256 _colAmt
) public override onlyNotPaused nonReentrant {
Pair memory pair = pairs[_col][_paired][_expiry][_mintRatio];
_validateDepositInputs(_col, pair);
// receive collateral
IERC20 collateral = IERC20(_col);
uint256 colBalBefore = collateral.balanceOf(address(this));
collateral.safeTransferFrom(msg.sender, address(this), _colAmt);
uint256 received = collateral.balanceOf(address(this)) - colBalBefore;
require(received > 0, "Ruler: transfer failed");
pairs[_col][_paired][_expiry][_mintRatio].colTotal = pair.colTotal + received;
// mint rTokens for reveiced collateral
uint256 mintAmount = _getRTokenAmtFromColAmt(received, _col, _paired, pair.mintRatio);
pair.rcToken.mint(msg.sender, mintAmount);
pair.rrToken.mint(msg.sender, mintAmount);
emit Deposit(msg.sender, _col, _paired, _expiry, _mintRatio, received);
}
function depositWithPermit(
address _col,
address _paired,
uint48 _expiry,
uint256 _mintRatio,
uint256 _colAmt,
Permit calldata _colPermit
) external override {
_permit(_col, _colPermit);
deposit(_col, _paired, _expiry, _mintRatio, _colAmt);
}
/// @notice redeem with rrTokens and rcTokens before expiry only, sender receives collateral, fees charged on collateral
function redeem(
address _col,
address _paired,
uint48 _expiry,
uint256 _mintRatio,
uint256 _rTokenAmt
) external override onlyNotPaused nonReentrant {
Pair memory pair = pairs[_col][_paired][_expiry][_mintRatio];
require(pair.mintRatio != 0, "Ruler: pair does not exist");
require(block.timestamp <= pair.expiry, "Ruler: expired, col forfeited");
pair.rrToken.burnByRuler(msg.sender, _rTokenAmt);
pair.rcToken.burnByRuler(msg.sender, _rTokenAmt);
// send collateral to sender
uint256 colAmountToPay = _getColAmtFromRTokenAmt(_rTokenAmt, _col, address(pair.rcToken), pair.mintRatio);
// once redeemed, it won't be considered as a loan for the pair anymore
pairs[_col][_paired][_expiry][_mintRatio].colTotal = pair.colTotal - colAmountToPay;
// accrue fees on payment
_sendAmtPostFeesOptionalAccrue(IERC20(_col), colAmountToPay, redeemFeeRate, true /* accrue */);
emit Redeem(msg.sender, _col, _paired, _expiry, _mintRatio, _rTokenAmt);
}
/// @notice repay with rrTokens and paired token amount, sender receives collateral, no fees charged on collateral
function repay(
address _col,
address _paired,
uint48 _expiry,
uint256 _mintRatio,
uint256 _rrTokenAmt
) public override onlyNotPaused nonReentrant {
Pair memory pair = pairs[_col][_paired][_expiry][_mintRatio];
require(pair.mintRatio != 0, "Ruler: pair does not exist");
require(block.timestamp <= pair.expiry, "Ruler: expired, col forfeited");
pair.rrToken.burnByRuler(msg.sender, _rrTokenAmt);
// receive paired tokens from sender, deflationary token is not allowed
IERC20 pairedToken = IERC20(_paired);
uint256 pairedBalBefore = pairedToken.balanceOf(address(this));
pairedToken.safeTransferFrom(msg.sender, address(this), _rrTokenAmt);
require(pairedToken.balanceOf(address(this)) - pairedBalBefore >= _rrTokenAmt, "Ruler: transfer paired failed");
feesMap[_paired] = feesMap[_paired] + _rrTokenAmt * pair.feeRate / 1e18;
// send collateral back to sender
uint256 colAmountToPay = _getColAmtFromRTokenAmt(_rrTokenAmt, _col, address(pair.rrToken), pair.mintRatio);
_safeTransfer(IERC20(_col), msg.sender, colAmountToPay);
emit Repay(msg.sender, _col, _paired, _expiry, _mintRatio, _rrTokenAmt);
}
function repayWithPermit(
address _col,
address _paired,
uint48 _expiry,
uint256 _mintRatio,
uint256 _rrTokenAmt,
Permit calldata _pairedPermit
) external override {
_permit(_paired, _pairedPermit);
repay(_col, _paired, _expiry, _mintRatio, _rrTokenAmt);
}
/// @notice sender collect paired tokens by returning same amount of rcTokens to Ruler
function collect(
address _col,
address _paired,
uint48 _expiry,
uint256 _mintRatio,
uint256 _rcTokenAmt
) external override onlyNotPaused nonReentrant {
Pair memory pair = pairs[_col][_paired][_expiry][_mintRatio];
require(pair.mintRatio != 0, "Ruler: pair does not exist");
require(block.timestamp > pair.expiry, "Ruler: not ready");
pair.rcToken.burnByRuler(msg.sender, _rcTokenAmt);
IERC20 pairedToken = IERC20(_paired);
uint256 defaultedLoanAmt = pair.rrToken.totalSupply();
if (defaultedLoanAmt == 0) { // no default, send paired Token to sender
// no fees accrued as it is accrued on Borrower payment
_sendAmtPostFeesOptionalAccrue(pairedToken, _rcTokenAmt, pair.feeRate, false /* accrue */);
} else {
// rcTokens eligible to collect at expiry (converted from total collateral received, redeemed collateral not counted) == total loan amount at the moment of expiry
uint256 rcTokensEligibleAtExpiry = _getRTokenAmtFromColAmt(pair.colTotal, _col, _paired, pair.mintRatio);
// paired token amount to pay = rcToken amount * (1 - default ratio)
uint256 pairedTokenAmtToCollect = _rcTokenAmt * (rcTokensEligibleAtExpiry - defaultedLoanAmt) / rcTokensEligibleAtExpiry;
// no fees accrued as it is accrued on Borrower payment
_sendAmtPostFeesOptionalAccrue(pairedToken, pairedTokenAmtToCollect, pair.feeRate, false /* accrue */);
// default collateral amount to pay = converted collateral amount (from rcTokenAmt) * default ratio
uint256 colAmount = _getColAmtFromRTokenAmt(_rcTokenAmt, _col, address(pair.rcToken), pair.mintRatio);
uint256 colAmountToCollect = colAmount * defaultedLoanAmt / rcTokensEligibleAtExpiry;
// accrue fees on defaulted collateral since it was never accrued
_sendAmtPostFeesOptionalAccrue(IERC20(_col), colAmountToCollect, pair.feeRate, true /* accrue */);
}
emit Collect(msg.sender, _col, _paired,_expiry, _mintRatio, _rcTokenAmt);
}
function collectFees(IERC20[] calldata _tokens) external override onlyOwner {
for (uint256 i = 0; i < _tokens.length; i++) {
IERC20 token = _tokens[i];
uint256 fee = feesMap[address(token)];
feesMap[address(token)] = 0;
_safeTransfer(token, feeReceiver, fee);
}
}
/**
* @notice add a new Ruler Pair
* - Paired Token cannot be a deflationary token
* - minColRatio is not respected if collateral is alreay added
* - all Ratios are 1e18
*/
function addPair(
address _col,
address _paired,
uint48 _expiry,
string calldata _expiryStr,
uint256 _mintRatio,
string calldata _mintRatioStr,
uint256 _feeRate
) external override onlyOwner {
require(pairs[_col][_paired][_expiry][_mintRatio].mintRatio == 0, "Ruler: pair exists");
require(_mintRatio > 0, "Ruler: _mintRatio <= 0");
require(_feeRate < 0.1 ether, "Ruler: fee rate must be < 10%");
require(_expiry > block.timestamp, "Ruler: expiry in the past");
require(minColRatioMap[_col] > 0, "Ruler: col not listed");
if (minColRatioMap[_paired] == 0) {
collaterals.push(_paired); // auto add paired token to collateral list
minColRatioMap[_paired] = 1.05 ether; // default paired token to 105% collateralization ratio as most of them are stablecoins, can be updated later.
}
Pair memory pair = Pair({
active: true,
feeRate: _feeRate,
mintRatio: _mintRatio,
expiry: _expiry,
pairedToken: _paired,
rcToken: IRERC20(_createRToken(_col, _paired, _expiry, _expiryStr, _mintRatioStr, "RC_")),
rrToken: IRERC20(_createRToken(_col, _paired, _expiry, _expiryStr, _mintRatioStr, "RR_")),
colTotal: 0
});
pairs[_col][_paired][_expiry][_mintRatio] = pair;
pairList[_col].push(pair);
emit PairAdded(_col, _paired, _expiry, _mintRatio);
}
/**
* @notice allow flash loan borrow allowed tokens up to all core contracts' holdings
* _receiver will received the requested amount, and need to payback the loan amount + fees
* _receiver must implement IERC3156FlashBorrower
* no deflationary tokens
*/
function flashLoan(
IERC3156FlashBorrower _receiver,
address _token,
uint256 _amount,
bytes calldata _data
) public override onlyNotPaused returns (bool) {
require(minColRatioMap[_token] > 0, "Ruler: token not allowed");
IERC20 token = IERC20(_token);
uint256 tokenBalBefore = token.balanceOf(address(this));
token.safeTransfer(address(_receiver), _amount);
uint256 fees = flashFee(_token, _amount);
require(
_receiver.onFlashLoan(msg.sender, _token, _amount, fees, _data) == FLASHLOAN_CALLBACK_SUCCESS,
"IERC3156: Callback failed"
);
// receive loans and fees
token.safeTransferFrom(address(_receiver), address(this), _amount + fees);
require(token.balanceOf(address(this)) - tokenBalBefore >= fees, "Ruler: not enough fees");
feesMap[_token] = feesMap[_token] + fees;
emit FlashLoan(_token, address(_receiver), _amount);
return true;
}
/// @notice flashloan rate can be anything
function setFlashLoanRate(uint256 _newRate) external override onlyOwner {
emit FlashLoanRateUpdated(flashLoanRate, _newRate);
flashLoanRate = _newRate;
}
/// @notice add new or update existing collateral
function updateCollateral(address _col, uint256 _minColRatio) external override onlyOwner {
require(_minColRatio > 0, "Ruler: min colRatio < 0");
emit CollateralUpdated(_col, minColRatioMap[_col], _minColRatio);
if (minColRatioMap[_col] == 0) {
collaterals.push(_col);
}
minColRatioMap[_col] = _minColRatio;
}
function setPairActive(
address _col,
address _paired,
uint48 _expiry,
uint256 _mintRatio,
bool _active
) external override onlyOwner {
pairs[_col][_paired][_expiry][_mintRatio].active = _active;
}
function setFeeReceiver(address _address) external override onlyOwner {
require(_address != address(0), "Ruler: address cannot be 0");
emit AddressUpdated('feeReceiver', feeReceiver, _address);
feeReceiver = _address;
}
/// @dev update this will only affect pools deployed after
function setRERC20Impl(address _newImpl) external override onlyOwner {
require(_newImpl != address(0), "Ruler: _newImpl cannot be 0");
emit RERC20ImplUpdated(rERC20Impl, _newImpl);
rERC20Impl = _newImpl;
}
function setPaused(bool _paused) external override {
require(msg.sender == owner() || msg.sender == responder, "Ruler: not owner/responder");
emit PausedStatusUpdated(paused, _paused);
paused = _paused;
}
function setResponder(address _address) external override onlyOwner {
require(_address != address(0), "Ruler: address cannot be 0");
emit AddressUpdated('responder', responder, _address);
responder = _address;
}
function setOracle(address _address) external override onlyOwner {
require(_address != address(0), "Ruler: address cannot be 0");
emit AddressUpdated('oracle', address(oracle), _address);
oracle = IOracle(_address);
}
/// @notice flashloan rate can be anything
function setDepositPauseWindow(uint256 _newWindow) external override onlyOwner {
emit DepositPauseWindow(depositPauseWindow, _newWindow);
depositPauseWindow = _newWindow;
}
/// @notice redeemFee rate can be anything < 10%
function setRedeemFeeRate(uint256 _newFeeRate) external override onlyOwner {
require(_newFeeRate < 0.1 ether, "Ruler: fee rate must be < 10%");
emit RedeemFeeRateUpdated(redeemFeeRate, _newFeeRate);
redeemFeeRate = _newFeeRate;
}
function getCollaterals() external view override returns (address[] memory) {
return collaterals;
}
function getPairList(address _col) external view override returns (Pair[] memory) {
Pair[] memory colPairList = pairList[_col];
Pair[] memory _pairs = new Pair[](colPairList.length);
for (uint256 i = 0; i < colPairList.length; i++) {
Pair memory pair = colPairList[i];
_pairs[i] = pairs[_col][pair.pairedToken][pair.expiry][pair.mintRatio];
}
return _pairs;
}
/// @notice amount that is eligible to collect
function viewCollectible(
address _col,
address _paired,
uint48 _expiry,
uint256 _mintRatio,
uint256 _rcTokenAmt
) external view override returns (uint256 colAmtToCollect, uint256 pairedAmtToCollect) {
Pair memory pair = pairs[_col][_paired][_expiry][_mintRatio];
if (pair.mintRatio == 0 || block.timestamp < pair.expiry) return (colAmtToCollect, pairedAmtToCollect);
uint256 defaultedLoanAmt = pair.rrToken.totalSupply();
if (defaultedLoanAmt == 0) { // no default, transfer paired Token
pairedAmtToCollect = _rcTokenAmt;
} else {
// rcTokens eligible to collect at expiry (converted from total collateral received, redeemed collateral not counted) == total loan amount at the moment of expiry
uint256 rcTokensEligibleAtExpiry = _getRTokenAmtFromColAmt(pair.colTotal, _col, _paired, pair.mintRatio);
// paired token amount to pay = rcToken amount * (1 - default ratio)
pairedAmtToCollect = _rcTokenAmt * (rcTokensEligibleAtExpiry - defaultedLoanAmt) * (1e18 - pair.feeRate) / 1e18 / rcTokensEligibleAtExpiry;
// default collateral amount to pay = converted collateral amount (from rcTokenAmt) * default ratio
uint256 colAmount = _getColAmtFromRTokenAmt(_rcTokenAmt, _col, address(pair.rcToken), pair.mintRatio);
colAmtToCollect = colAmount * defaultedLoanAmt * (1e18 - pair.feeRate) / 1e18 / rcTokensEligibleAtExpiry;
}
}
function maxFlashLoan(address _token) external view override returns (uint256) {
return IERC20(_token).balanceOf(address(this));
}
/// @notice returns the amount of fees charges by for the loan amount. 0 means no fees charged, may not have the token
function flashFee(address _token, uint256 _amount) public view override returns (uint256 _fees) {
require(minColRatioMap[_token] > 0, "RulerCore: token not supported");
_fees = _amount * flashLoanRate / 1e18;
}
/// @notice version of current Ruler Core hardcoded
function version() external pure override returns (string memory) {
return '1.0.3';
}
function _safeTransfer(IERC20 _token, address _account, uint256 _amount) private {
uint256 bal = _token.balanceOf(address(this));
if (bal < _amount) {
_token.safeTransfer(_account, bal);
} else {
_token.safeTransfer(_account, _amount);
}
}
function _sendAmtPostFeesOptionalAccrue(IERC20 _token, uint256 _amount, uint256 _feeRate, bool _accrue) private {
uint256 fees = _amount * _feeRate / 1e18;
_safeTransfer(_token, msg.sender, _amount - fees);
if (_accrue) {
feesMap[address(_token)] = feesMap[address(_token)] + fees;
}
}
function _createRToken(
address _col,
address _paired,
uint256 _expiry,
string calldata _expiryStr,
string calldata _mintRatioStr,
string memory _prefix
) private returns (address proxyAddr) {
uint8 decimals = uint8(IERC20(_paired).decimals());
require(decimals > 0, "RulerCore: paired decimals is 0");
string memory symbol = string(abi.encodePacked(
_prefix,
IERC20(_col).symbol(), "_",
_mintRatioStr, "_",
IERC20(_paired).symbol(), "_",
_expiryStr
));
bytes32 salt = keccak256(abi.encodePacked(_col, _paired, _expiry, _mintRatioStr, _prefix));
proxyAddr = Clones.cloneDeterministic(rERC20Impl, salt);
IRTokenProxy(proxyAddr).initialize("Ruler Protocol rToken", symbol, decimals);
emit RTokenCreated(proxyAddr);
}
function _getRTokenAmtFromColAmt(uint256 _colAmt, address _col, address _paired, uint256 _mintRatio) private view returns (uint256) {
uint8 colDecimals = IERC20(_col).decimals();
// pairedDecimals is the same as rToken decimals
uint8 pairedDecimals = IERC20(_paired).decimals();
return _colAmt * _mintRatio * (10 ** pairedDecimals) / (10 ** colDecimals) / 1e18;
}
function _getColAmtFromRTokenAmt(uint256 _rTokenAmt, address _col, address _rToken, uint256 _mintRatio) private view returns (uint256) {
uint8 colDecimals = IERC20(_col).decimals();
// pairedDecimals == rToken decimals
uint8 rTokenDecimals = IERC20(_rToken).decimals();
return _rTokenAmt * (10 ** colDecimals) * 1e18 / _mintRatio / (10 ** rTokenDecimals);
}
function _permit(address _token, Permit calldata permit) private {
IERC20Permit(_token).permit(
permit.owner,
permit.spender,
permit.amount,
permit.deadline,
permit.v,
permit.r,
permit.s
);
}
function _validateDepositInputs(address _col, Pair memory _pair) private view {
require(_pair.mintRatio != 0, "Ruler: pair does not exist");
require(_pair.active, "Ruler: pair inactive");
require(_pair.expiry - depositPauseWindow > block.timestamp, "Ruler: deposit ended");
// Oracle price is not required, the consequence is low since it will just allow users to deposit collateral (which can be collected thro repay before expiry. If default, early repayments will be diluted
if (address(oracle) != address(0)) {
uint256 colPrice = oracle.getPriceUSD(_col);
if (colPrice != 0) {
uint256 pairedPrice = oracle.getPriceUSD(_pair.pairedToken);
if (pairedPrice != 0) {
// colPrice / mintRatio (1e18) / pairedPrice > min collateralization ratio (1e18), if yes, revert deposit
require(colPrice * 1e36 > minColRatioMap[_col] * _pair.mintRatio * pairedPrice, "Ruler: collateral price too low");
}
}
}
}
}
// SPDX-License-Identifier: No License
pragma solidity ^0.8.0;
/**
* @title Interface of the ERC20 standard as defined in the EIP.
*/
interface IERC20 {
event Transfer(address indexed from, address indexed to, uint256 value);
event Approval(address indexed owner, address indexed spender, uint256 value);
function name() external view returns (string memory);
function symbol() external view returns (string memory);
function decimals() external view returns (uint8);
function balanceOf(address account) external view returns (uint256);
function transfer(address recipient, uint256 amount) external returns (bool);
function approve(address spender, uint256 amount) external returns (bool);
function allowance(address owner, address spender) external view returns (uint256);
function transferFrom(address sender, address recipient, uint256 amount) external returns (bool);
function totalSupply() external view returns (uint256);
function increaseAllowance(address spender, uint256 addedValue) external returns (bool);
function decreaseAllowance(address spender, uint256 subtractedValue) external returns (bool);
}
// SPDX-License-Identifier: MIT
pragma solidity 0.8.0;
/**
* @dev Interface of the ERC20 Permit extension allowing approvals to be made via signatures, as defined in
* https://eips.ethereum.org/EIPS/eip-2612[EIP-2612].
*
* Adds the {permit} method, which can be used to change an account's ERC20 allowance (see {IERC20-allowance}) by
* presenting a message signed by the account. By not relying on `{IERC20-approve}`, the token holder account doesn't
* need to send a transaction, and thus is not required to hold Ether at all.
*/
interface IERC20Permit {
/**
* @dev Sets `amount` as the allowance of `spender` over `owner`'s tokens,
* given `owner`'s signed approval.
*
* IMPORTANT: The same issues {IERC20-approve} has related to transaction
* ordering also apply here.
*
* Emits an {Approval} event.
*
* Requirements:
*
* - `spender` cannot be the zero address.
* - `deadline` must be a timestamp in the future.
* - `v`, `r` and `s` must be a valid `secp256k1` signature from `owner`
* over the EIP712-formatted function arguments.
* - the signature must use ``owner``'s current nonce (see {nonces}).
*
* For more information on the signature format, see the
* https://eips.ethereum.org/EIPS/eip-2612#specification[relevant EIP
* section].
*/
function permit(address owner, address spender, uint256 amount, uint256 deadline, uint8 v, bytes32 r, bytes32 s) external;
/**
* @dev Returns the current nonce for `owner`. This value must be
* included whenever a signature is generated for {permit}.
*
* Every successful call to {permit} increases ``owner``'s nonce by one. This
* prevents a signature from being used multiple times.
*/
function nonces(address owner) external view returns (uint256);
/**
* @dev Returns the domain separator used in the encoding of the signature for `permit`, as defined by {EIP712}.
*/
// solhint-disable-next-line func-name-mixedcase
function DOMAIN_SEPARATOR() external view returns (bytes32);
}
// 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'
// solhint-disable-next-line max-line-length
require((value == 0) || (token.allowance(address(this), spender) == 0),
"SafeERC20: approve from non-zero to non-zero allowance"
);
_callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, value));
}
function safeIncreaseAllowance(IERC20 token, address spender, uint256 value) internal {
uint256 newAllowance = token.allowance(address(this), spender) + value;
_callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance));
}
function safeDecreaseAllowance(IERC20 token, address spender, uint256 value) internal {
uint256 newAllowance = token.allowance(address(this), spender) - value;
_callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance));
}
/**
* @dev Imitates a Solidity high-level call (i.e. a regular function call to a contract), relaxing the requirement
* on the return value: the return value is optional (but if data is returned, it must not be false).
* @param token The token targeted by the call.
* @param data The call data (encoded using abi.encode or one of its variants).
*/
function _callOptionalReturn(IERC20 token, bytes memory data) private {
// We need to perform a low level call here, to bypass Solidity's return data size checking mechanism, since
// we're implementing it ourselves. We use {Address.functionCall} to perform this call, which verifies that
// the target address contains contract code and also asserts for success in the low-level call.
bytes memory returndata = address(token).functionCall(data, "SafeERC20: low-level call failed");
if (returndata.length > 0) { // Return data is optional
// solhint-disable-next-line max-line-length
require(abi.decode(returndata, (bool)), "SafeERC20: ERC20 operation did not succeed");
}
}
}
// SPDX-License-Identifier: No License
pragma solidity ^0.8.0;
interface IERC3156FlashBorrower {
/**
* @dev Receive a flash loan.
* @param initiator The initiator of the loan.
* @param token The loan currency.
* @param amount The amount of tokens lent.
* @param fee The additional amount of tokens to repay.
* @param data Arbitrary data structure, intended to contain user-defined parameters.
* @return The keccak256 hash of "ERC3156FlashBorrower.onFlashLoan"
*/
function onFlashLoan(
address initiator,
address token,
uint256 amount,
uint256 fee,
bytes calldata data
) external returns (bytes32);
}
// SPDX-License-Identifier: No License
pragma solidity ^0.8.0;
import "./IERC3156FlashBorrower.sol";
interface IERC3156FlashLender {
/**
* @dev The amount of currency available to be lent.
* @param token The loan currency.
* @return The amount of `token` that can be borrowed.
*/
function maxFlashLoan(
address token
) external view returns (uint256);
/**
* @dev The fee to be charged for a given loan.
* @param token The loan currency.
* @param amount The amount of tokens lent.
* @return The amount of `token` to be charged for the loan, on top of the returned principal.
*/
function flashFee(
address token,
uint256 amount
) external view returns (uint256);
/**
* @dev Initiate a flash loan.
* @param receiver The receiver of the tokens in the loan, and the receiver of the callback.
* @param token The loan currency.
* @param amount The amount of tokens lent.
* @param data Arbitrary data structure, intended to contain user-defined parameters.
*/
function flashLoan(
IERC3156FlashBorrower receiver,
address token,
uint256 amount,
bytes calldata data
) external returns (bool);
}
// SPDX-License-Identifier: No License
pragma solidity ^0.8.0;
import "../ERC20/IERC20.sol";
/**
* @title RERC20 contract interface, implements {IERC20}. See {RERC20}.
* @author crypto-pumpkin
*/
interface IRERC20 is IERC20 {
/// @notice access restriction - owner (R)
function mint(address _account, uint256 _amount) external returns (bool);
function burnByRuler(address _account, uint256 _amount) external returns (bool);
}
// SPDX-License-Identifier: No License
pragma solidity ^0.8.0;
/**
* @title Interface of the RTokens Proxy.
*/
interface IRTokenProxy {
function initialize(string calldata _name, string calldata _symbol, uint8 _decimals) external;
}
// SPDX-License-Identifier: No License
pragma solidity ^0.8.0;
import "./IRERC20.sol";
import "./IOracle.sol";
/**
* @title IRulerCore contract interface. See {RulerCore}.
* @author crypto-pumpkin
*/
interface IRulerCore {
event RTokenCreated(address);
event CollateralUpdated(address col, uint256 old, uint256 _new);
event PairAdded(address indexed collateral, address indexed paired, uint48 expiry, uint256 mintRatio);
event MarketMakeDeposit(address indexed user, address indexed collateral, address indexed paired, uint48 expiry, uint256 mintRatio, uint256 amount);
event Deposit(address indexed user, address indexed collateral, address indexed paired, uint48 expiry, uint256 mintRatio, uint256 amount);
event Repay(address indexed user, address indexed collateral, address indexed paired, uint48 expiry, uint256 mintRatio, uint256 amount);
event Redeem(address indexed user, address indexed collateral, address indexed paired, uint48 expiry, uint256 mintRatio, uint256 amount);
event Collect(address indexed user, address indexed collateral, address indexed paired, uint48 expiry, uint256 mintRatio, uint256 amount);
event AddressUpdated(string _type, address old, address _new);
event PausedStatusUpdated(bool old, bool _new);
event RERC20ImplUpdated(address rERC20Impl, address newImpl);
event FlashLoanRateUpdated(uint256 old, uint256 _new);
// v1.0.1
event FlashLoan(address _token, address _borrower, uint256 _amount);
// v1.0.2
event DepositPauseWindow(uint256 old, uint256 _new);
event RedeemFeeRateUpdated(uint256 old, uint256 _new);
struct Pair {
bool active;
uint48 expiry;
address pairedToken;
IRERC20 rcToken; // ruler capitol token, e.g. RC_Dai_wBTC_2_2021
IRERC20 rrToken; // ruler repayment token, e.g. RR_Dai_wBTC_2_2021
uint256 mintRatio; // 1e18, price of collateral / collateralization ratio
uint256 feeRate; // 1e18
uint256 colTotal;
}
struct Permit {
address owner;
address spender;
uint256 amount;
uint256 deadline;
uint8 v;
bytes32 r;
bytes32 s;
}
// state vars
function oracle() external view returns (IOracle);
function version() external pure returns (string memory);
function flashLoanRate() external view returns (uint256);
function paused() external view returns (bool);
function responder() external view returns (address);
function feeReceiver() external view returns (address);
function rERC20Impl() external view returns (address);
function collaterals(uint256 _index) external view returns (address);
function minColRatioMap(address _col) external view returns (uint256);
function feesMap(address _token) external view returns (uint256);
function pairs(address _col, address _paired, uint48 _expiry, uint256 _mintRatio) external view returns (
bool active,
uint48 expiry,
address pairedToken,
IRERC20 rcToken,
IRERC20 rrToken,
uint256 mintRatio,
uint256 feeRate,
uint256 colTotal
);
function depositPauseWindow() external view returns (uint256);
function redeemFeeRate() external view returns (uint256);
// extra view
function getCollaterals() external view returns (address[] memory);
function getPairList(address _col) external view returns (Pair[] memory);
function viewCollectible(
address _col,
address _paired,
uint48 _expiry,
uint256 _mintRatio,
uint256 _rcTokenAmt
) external view returns (uint256 colAmtToCollect, uint256 pairedAmtToCollect);
// user action - only when not paused
function mmDeposit(
address _col,
address _paired,
uint48 _expiry,
uint256 _mintRatio,
uint256 _rcTokenAmt
) external;
function mmDepositWithPermit(
address _col,
address _paired,
uint48 _expiry,
uint256 _mintRatio,
uint256 _rcTokenAmt,
Permit calldata _pairedPermit
) external;
function deposit(
address _col,
address _paired,
uint48 _expiry,
uint256 _mintRatio,
uint256 _colAmt
) external;
function depositWithPermit(
address _col,
address _paired,
uint48 _expiry,
uint256 _mintRatio,
uint256 _colAmt,
Permit calldata _colPermit
) external;
function redeem(
address _col,
address _paired,
uint48 _expiry,
uint256 _mintRatio,
uint256 _rTokenAmt
) external;
function repay(
address _col,
address _paired,
uint48 _expiry,
uint256 _mintRatio,
uint256 _rrTokenAmt
) external;
function repayWithPermit(
address _col,
address _paired,
uint48 _expiry,
uint256 _mintRatio,
uint256 _rrTokenAmt,
Permit calldata _pairedPermit
) external;
function collect(
address _col,
address _paired,
uint48 _expiry,
uint256 _mintRatio,
uint256 _rcTokenAmt
) external;
// access restriction - owner (dev)
function collectFees(IERC20[] calldata _tokens) external;
// access restriction - owner (dev) & responder
function setPaused(bool _paused) external;
// access restriction - owner (dev)
function addPair(
address _col,
address _paired,
uint48 _expiry,
string calldata _expiryStr,
uint256 _mintRatio,
string calldata _mintRatioStr,
uint256 _feeRate
) external;
function setPairActive(
address _col,
address _paired,
uint48 _expiry,
uint256 _mintRatio,
bool _active
) external;
function updateCollateral(address _col, uint256 _minColRatio) external;
function setFeeReceiver(address _addr) external;
function setResponder(address _addr) external;
function setRERC20Impl(address _addr) external;
function setOracle(address _addr) external;
function setFlashLoanRate(uint256 _newRate) external;
function setDepositPauseWindow(uint256 _newWindow) external;
function setRedeemFeeRate(uint256 _newFeeRate) external;
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
interface IOracle {
function getPriceUSD(address _asset) external view returns (uint256 price);
function getPricesUSD(address[] calldata _assets) external view returns (uint256[] memory prices);
// admin functions
function updateFeedETH(address _asset, address _feed) external;
function updateFeedUSD(address _asset, address _feed) external;
function setSushiKeeperOracle(address _sushiOracle) external;
function setUniKeeperOracle(address _uniOracle) external;
}
// SPDX-License-Identifier: MIT
pragma solidity 0.8.0;
/**
* @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.
*/
library Clones {
/**
* @dev Deploys and returns the address of a clone that mimics the behaviour of `master`.
*
* This function uses the create2 opcode and a `salt` to deterministically deploy
* the clone. Using the same `master` and `salt` multiple time will revert, since
* the clones cannot be deployed twice at the same address.
*/
function cloneDeterministic(address master, bytes32 salt) internal returns (address instance) {
// solhint-disable-next-line no-inline-assembly
assembly {
let ptr := mload(0x40)
mstore(ptr, 0x3d602d80600a3d3981f3363d3d373d3d3d363d73000000000000000000000000)
mstore(add(ptr, 0x14), shl(0x60, master))
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 master, bytes32 salt, address deployer) internal pure returns (address predicted) {
// solhint-disable-next-line no-inline-assembly
assembly {
let ptr := mload(0x40)
mstore(ptr, 0x3d602d80600a3d3981f3363d3d373d3d3d363d73000000000000000000000000)
mstore(add(ptr, 0x14), shl(0x60, master))
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 master, bytes32 salt) internal view returns (address predicted) {
return predictDeterministicAddress(master, salt, address(this));
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
/**
* @dev Helper to make usage of the `CREATE2` EVM opcode easier and safer.
* `CREATE2` can be used to compute in advance the address where a smart
* contract will be deployed, which allows for interesting new mechanisms known
* as 'counterfactual interactions'.
*
* See the https://eips.ethereum.org/EIPS/eip-1014#motivation[EIP] for more
* information.
*/
library Create2 {
/**
* @dev Deploys a contract using `CREATE2`. The address where the contract
* will be deployed can be known in advance via {computeAddress}.
*
* The bytecode for a contract can be obtained from Solidity with
* `type(contractName).creationCode`.
*
* Requirements:
*
* - `bytecode` must not be empty.
* - `salt` must have not been used for `bytecode` already.
* - the factory must have a balance of at least `amount`.
* - if `amount` is non-zero, `bytecode` must have a `payable` constructor.
*/
function deploy(uint256 amount, bytes32 salt, bytes memory bytecode) internal returns (address payable) {
address payable addr;
require(address(this).balance >= amount, "Create2: insufficient balance");
require(bytecode.length != 0, "Create2: bytecode length is zero");
// solhint-disable-next-line no-inline-assembly
assembly {
addr := create2(amount, add(bytecode, 0x20), mload(bytecode), salt)
}
require(addr != address(0), "Create2: Failed on deploy");
return addr;
}
/**
* @dev Returns the address where a contract will be stored if deployed via {deploy}. Any change in the
* `bytecodeHash` or `salt` will result in a new destination address.
*/
function computeAddress(bytes32 salt, bytes32 bytecodeHash) internal view returns (address) {
return computeAddress(salt, bytecodeHash, address(this));
}
/**
* @dev Returns the address where a contract will be stored if deployed via {deploy} from a contract located at
* `deployer`. If `deployer` is this contract's address, returns the same value as {computeAddress}.
*/
function computeAddress(bytes32 salt, bytes32 bytecodeHash, address deployer) internal pure returns (address) {
bytes32 _data = keccak256(
abi.encodePacked(bytes1(0xff), deployer, salt, bytecodeHash)
);
return address(uint160(uint256(_data)));
}
}
// SPDX-License-Identifier: MIT
// solhint-disable-next-line compiler-version
pragma solidity ^0.8.0;
/**
* @dev This is a base contract to aid in writing upgradeable contracts, or any kind of contract that will be deployed
* behind a proxy. Since a proxied contract can't have a constructor, it's common to move constructor logic to an
* external initializer function, usually called `initialize`. It then becomes necessary to protect this initializer
* function so it can only be called once. The {initializer} modifier provided by this contract will have this effect.
*
* TIP: To avoid leaving the proxy in an uninitialized state, the initializer function should be called as early as
* possible by providing the encoded function call as the `_data` argument to {UpgradeableProxy-constructor}.
*
* CAUTION: When used with inheritance, manual care must be taken to not invoke a parent initializer twice, or to ensure
* that all initializers are idempotent. This is not verified automatically as constructors are by Solidity.
*/
abstract contract Initializable {
/**
* @dev Indicates that the contract has been initialized.
*/
bool private _initialized;
/**
* @dev Indicates that the contract is in the process of being initialized.
*/
bool private _initializing;
/**
* @dev Modifier to protect an initializer function from being invoked twice.
*/
modifier initializer() {
require(_initializing || _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) {
// extcodesize checks the size of the code stored in an address, and
// address returns the current address. Since the code is still not
// deployed when running a constructor, any checks on its code size will
// yield zero, making it an effective way to detect if a contract is
// under construction or not.
address self = address(this);
uint256 cs;
// solhint-disable-next-line no-inline-assembly
assembly { cs := extcodesize(self) }
return cs == 0;
}
}
// SPDX-License-Identifier: No License
pragma solidity ^0.8.0;
import "./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.
* @author crypto-pumpkin
*
* By initialization, the owner account will be the one that called initializeOwner. 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 Initializable {
address private _owner;
event OwnershipTransferred(address indexed previousOwner, address indexed newOwner);
/**
* @dev Ruler: Initializes the contract setting the deployer as the initial owner.
*/
function initializeOwner() internal initializer {
_owner = msg.sender;
emit OwnershipTransferred(address(0), _owner);
}
/**
* @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 == msg.sender, "Ownable: caller is not the owner");
_;
}
/**
* @dev Leaves the contract without owner. It will not be possible to call
* `onlyOwner` functions anymore. Can only be called by the current owner.
*
* NOTE: Renouncing ownership will leave the contract without an owner,
* thereby removing any functionality that is only available to the owner.
*/
function renounceOwnership() public virtual onlyOwner {
emit OwnershipTransferred(_owner, address(0));
_owner = address(0);
}
/**
* @dev Transfers ownership of the contract to a new account (`newOwner`).
* Can only be called by the current owner.
*/
function transferOwnership(address newOwner) public virtual onlyOwner {
require(newOwner != address(0), "Ownable: new owner is the zero address");
emit OwnershipTransferred(_owner, newOwner);
_owner = newOwner;
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
/**
* @dev Contract module that helps prevent reentrant calls to a function.
*
* Inheriting from `ReentrancyGuard` will make the {nonReentrant} modifier
* available, which can be applied to functions to make sure there are no nested
* (reentrant) calls to them.
*
* Note that because there is a single `nonReentrant` guard, functions marked as
* `nonReentrant` may not call one another. This can be worked around by making
* those functions `private`, and then adding `external` `nonReentrant` entry
* points to them.
*
* TIP: If you would like to learn more about reentrancy and alternative ways
* to protect against it, check out our blog post
* https://blog.openzeppelin.com/reentrancy-after-istanbul/[Reentrancy After Istanbul].
*/
abstract contract ReentrancyGuard {
// Booleans are more expensive than uint256 or any type that takes up a full
// word because each write operation emits an extra SLOAD to first read the
// slot's contents, replace the bits taken up by the boolean, and then write
// back. This is the compiler's defense against contract upgrades and
// pointer aliasing, and it cannot be disabled.
// The values being non-zero value makes deployment a bit more expensive,
// but in exchange the refund on every call to nonReentrant will be lower in
// amount. Since refunds are capped to a percentage of the total
// transaction's gas, it is best to keep them low in cases like this one, to
// increase the likelihood of the full refund coming into effect.
uint256 private constant _NOT_ENTERED = 1;
uint256 private constant _ENTERED = 2;
uint256 private _status;
function initializeReentrancyGuard () internal {
_status = _NOT_ENTERED;
}
/**
* @dev Prevents a contract from calling itself, directly or indirectly.
* Calling a `nonReentrant` function from another `nonReentrant`
* function is not supported. It is possible to prevent this from happening
* by making the `nonReentrant` function external, and make it call a
* `private` function that does the actual work.
*/
modifier nonReentrant() {
// On the first call to nonReentrant, _notEntered will be true
require(_status != _ENTERED, "ReentrancyGuard: reentrant call");
// Any calls to nonReentrant after this point will fail
_status = _ENTERED;
_;
// By storing the original value once again, a refund is triggered (see
// https://eips.ethereum.org/EIPS/eip-2200)
_status = _NOT_ENTERED;
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
library Address {
/**
* @dev Returns true if `account` is a contract.
*
* [IMPORTANT]
* ====
* It is unsafe to assume that an address for which this function returns
* false is an externally-owned account (EOA) and not a contract.
*
* Among others, `isContract` will return false for the following
* types of addresses:
*
* - an externally-owned account
* - a contract in construction
* - an address where a contract will be created
* - an address where a contract lived, but was destroyed
* ====
*/
function isContract(address account) internal view returns (bool) {
// According to EIP-1052, 0x0 is the value returned for not-yet created accounts
// and 0xc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470 is returned
// for accounts without code, i.e. `keccak256('')`
bytes32 codehash;
bytes32 accountHash = 0xc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470;
// solhint-disable-next-line no-inline-assembly
assembly { codehash := extcodehash(account) }
return (codehash != accountHash && codehash != 0x0);
}
/**
* @dev Replacement for Solidity's `transfer`: sends `amount` wei to
* `recipient`, forwarding all available gas and reverting on errors.
*
* https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost
* of certain opcodes, possibly making contracts go over the 2300 gas limit
* imposed by `transfer`, making them unable to receive funds via
* `transfer`. {sendValue} removes this limitation.
*
* https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more].
*
* IMPORTANT: because control is transferred to `recipient`, care must be
* taken to not create reentrancy vulnerabilities. Consider using
* {ReentrancyGuard} or the
* https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern].
*/
function sendValue(address payable recipient, uint256 amount) internal {
require(address(this).balance >= amount, "Address: insufficient balance");
// solhint-disable-next-line avoid-low-level-calls, avoid-call-value
(bool success, ) = recipient.call{ value: amount }("");
require(success, "Address: unable to send value, recipient may have reverted");
}
/**
* @dev Performs a Solidity function call using a low level `call`. A
* plain`call` is an unsafe replacement for a function call: use this
* function instead.
*
* If `target` reverts with a revert reason, it is bubbled up by this
* function (like regular Solidity function calls).
*
* Returns the raw returned data. To convert to the expected return value,
* use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`].
*
* Requirements:
*
* - `target` must be a contract.
* - calling `target` with `data` must not revert.
*
* _Available since v3.1._
*/
function functionCall(address target, bytes memory data) internal returns (bytes memory) {
return functionCall(target, data, "Address: low-level call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with
* `errorMessage` as a fallback revert reason when `target` reverts.
*
* _Available since v3.1._
*/
function functionCall(address target, bytes memory data, string memory errorMessage) internal returns (bytes memory) {
return _functionCallWithValue(target, data, 0, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but also transferring `value` wei to `target`.
*
* Requirements:
*
* - the calling contract must have an ETH balance of at least `value`.
* - the called Solidity function must be `payable`.
*
* _Available since v3.1._
*/
function functionCallWithValue(address target, bytes memory data, uint256 value) internal returns (bytes memory) {
return functionCallWithValue(target, data, value, "Address: low-level call with value failed");
}
/**
* @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but
* with `errorMessage` as a fallback revert reason when `target` reverts.
*
* _Available since v3.1._
*/
function functionCallWithValue(address target, bytes memory data, uint256 value, string memory errorMessage) internal returns (bytes memory) {
require(address(this).balance >= value, "Address: insufficient balance for call");
return _functionCallWithValue(target, data, value, errorMessage);
}
function _functionCallWithValue(address target, bytes memory data, uint256 weiValue, string memory errorMessage) private returns (bytes memory) {
require(isContract(target), "Address: call to non-contract");
// solhint-disable-next-line avoid-low-level-calls
(bool success, bytes memory returndata) = target.call{ value: weiValue }(data);
if (success) {
return returndata;
} else {
// Look for revert reason and bubble it up if present
if (returndata.length > 0) {
// The easiest way to bubble the revert reason is using memory via assembly
// solhint-disable-next-line no-inline-assembly
assembly {
let returndata_size := mload(returndata)
revert(add(32, returndata), returndata_size)
}
} else {
revert(errorMessage);
}
}
}
}
| @notice repay with rrTokens and paired token amount, sender receives collateral, no fees charged on collateral receive paired tokens from sender, deflationary token is not allowed send collateral back to sender | function repay(
address _col,
address _paired,
uint48 _expiry,
uint256 _mintRatio,
uint256 _rrTokenAmt
) public override onlyNotPaused nonReentrant {
Pair memory pair = pairs[_col][_paired][_expiry][_mintRatio];
require(pair.mintRatio != 0, "Ruler: pair does not exist");
require(block.timestamp <= pair.expiry, "Ruler: expired, col forfeited");
pair.rrToken.burnByRuler(msg.sender, _rrTokenAmt);
IERC20 pairedToken = IERC20(_paired);
uint256 pairedBalBefore = pairedToken.balanceOf(address(this));
pairedToken.safeTransferFrom(msg.sender, address(this), _rrTokenAmt);
require(pairedToken.balanceOf(address(this)) - pairedBalBefore >= _rrTokenAmt, "Ruler: transfer paired failed");
feesMap[_paired] = feesMap[_paired] + _rrTokenAmt * pair.feeRate / 1e18;
uint256 colAmountToPay = _getColAmtFromRTokenAmt(_rrTokenAmt, _col, address(pair.rrToken), pair.mintRatio);
_safeTransfer(IERC20(_col), msg.sender, colAmountToPay);
emit Repay(msg.sender, _col, _paired, _expiry, _mintRatio, _rrTokenAmt);
}
| 509,720 | [
1,
266,
10239,
598,
8354,
5157,
471,
18066,
1147,
3844,
16,
5793,
17024,
4508,
2045,
287,
16,
1158,
1656,
281,
1149,
2423,
603,
4508,
2045,
287,
6798,
18066,
2430,
628,
5793,
16,
1652,
80,
367,
814,
1147,
353,
486,
2935,
1366,
4508,
2045,
287,
1473,
358,
5793,
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,
225,
445,
2071,
528,
12,
203,
565,
1758,
389,
1293,
16,
203,
565,
1758,
389,
24197,
16,
203,
565,
2254,
8875,
389,
22409,
16,
203,
565,
2254,
5034,
389,
81,
474,
8541,
16,
203,
565,
2254,
5034,
389,
523,
1345,
31787,
203,
225,
262,
1071,
3849,
1338,
1248,
28590,
1661,
426,
8230,
970,
288,
203,
565,
8599,
3778,
3082,
273,
5574,
63,
67,
1293,
6362,
67,
24197,
6362,
67,
22409,
6362,
67,
81,
474,
8541,
15533,
203,
565,
2583,
12,
6017,
18,
81,
474,
8541,
480,
374,
16,
315,
54,
17040,
30,
3082,
1552,
486,
1005,
8863,
203,
565,
2583,
12,
2629,
18,
5508,
1648,
3082,
18,
22409,
16,
315,
54,
17040,
30,
7708,
16,
645,
364,
3030,
16261,
8863,
203,
565,
3082,
18,
523,
1345,
18,
70,
321,
858,
54,
17040,
12,
3576,
18,
15330,
16,
389,
523,
1345,
31787,
1769,
203,
203,
565,
467,
654,
39,
3462,
18066,
1345,
273,
467,
654,
39,
3462,
24899,
24197,
1769,
203,
565,
2254,
5034,
18066,
38,
287,
4649,
273,
225,
18066,
1345,
18,
12296,
951,
12,
2867,
12,
2211,
10019,
203,
565,
18066,
1345,
18,
4626,
5912,
1265,
12,
3576,
18,
15330,
16,
1758,
12,
2211,
3631,
389,
523,
1345,
31787,
1769,
203,
565,
2583,
12,
24197,
1345,
18,
12296,
951,
12,
2867,
12,
2211,
3719,
300,
18066,
38,
287,
4649,
1545,
389,
523,
1345,
31787,
16,
315,
54,
17040,
30,
7412,
18066,
2535,
8863,
203,
565,
1656,
281,
863,
63,
67,
24197,
65,
273,
1656,
281,
863,
63,
67,
24197,
65,
397,
389,
523,
2
] |
pragma solidity ^0.4.18;
// File: zeppelin-solidity/contracts/math/SafeMath.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;
}
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;
}
}
// File: zeppelin-solidity/contracts/ownership/Ownable.sol
/**
* @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;
}
}
// File: zeppelin-solidity/contracts/token/ERC20Basic.sol
/**
* @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) public view returns (uint256);
function transfer(address to, uint256 value) public returns (bool);
event Transfer(address indexed from, address indexed to, uint256 value);
}
// File: zeppelin-solidity/contracts/token/BasicToken.sol
/**
* @title Basic token
* @dev Basic version of StandardToken, with no allowances.
*/
contract BasicToken is ERC20Basic {
using SafeMath for uint256;
mapping(address => uint256) balances;
/**
* @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];
}
}
// File: contracts/InkPublicPresale.sol
contract InkPublicPresale is Ownable {
using SafeMath for uint256;
// Flag to indicate whether or not the presale is currently active or is paused.
// This flag is used both before the presale is finalized as well as after.
// Pausing the presale before finalize means that no further contributions can
// be made. Pausing the presale after finalize means that no one can claim
// XNK tokens.
bool public active;
// Flag to indicate whether or not contributions can be refunded.
bool private refundable;
// The global minimum contribution (in Wei) imposed on all contributors.
uint256 public globalMin;
// The global maximum contribution (in Wei) imposed on all contributors.
// Contributor also have a personal max. When evaluating whether or not they
// can make a contribution, the lower of the global max and personal max is
// used.
uint256 public globalMax;
// The max amount of Ether (in Wei) that is available for contribution.
uint256 public etherCap;
// The running count of Ether (in Wei) that is already contributed.
uint256 private etherContributed;
// The running count of XNK that is purchased by contributors.
uint256 private xnkPurchased;
// The address of the XNK token contract. When this address is set, the
// presale is considered finalized and no further contributions can be made.
address public tokenAddress;
// Max gas price for contributing transactions.
uint256 public maxGasPrice;
// Contributors storage mapping.
mapping(address => Contributor) private contributors;
struct Contributor {
bool whitelisted;
// The individual rate (in XNK).
uint256 rate;
// The individual max contribution (in Wei).
uint256 max;
// The amount (in Wei) the contributor has contributed.
uint256 balance;
}
// The presale is considered finalized when the token address is set.
modifier finalized {
require(tokenAddress != address(0));
_;
}
// The presale is considered not finalized when the token address is not set.
modifier notFinalized {
require(tokenAddress == address(0));
_;
}
function InkPublicPresale() public {
globalMax = 1000000000000000000; // 1.0 Ether
globalMin = 100000000000000000; // 0.1 Ether
maxGasPrice = 40000000000; // 40 Gwei
}
function updateMaxGasPrice(uint256 _maxGasPrice) public onlyOwner {
require(_maxGasPrice > 0);
maxGasPrice = _maxGasPrice;
}
// Returns the amount of Ether contributed by all contributors.
function getEtherContributed() public view onlyOwner returns (uint256) {
return etherContributed;
}
// Returns the amount of XNK purchased by all contributes.
function getXNKPurchased() public view onlyOwner returns (uint256) {
return xnkPurchased;
}
// Update the global ether cap. If the new cap is set to something less than
// or equal to the current contributed ether (etherContributed), then no
// new contributions can be made.
function updateEtherCap(uint256 _newEtherCap) public notFinalized onlyOwner {
etherCap = _newEtherCap;
}
// Update the global max contribution.
function updateGlobalMax(uint256 _globalMax) public notFinalized onlyOwner {
require(_globalMax > globalMin);
globalMax = _globalMax;
}
// Update the global minimum contribution.
function updateGlobalMin(uint256 _globalMin) public notFinalized onlyOwner {
require(_globalMin > 0);
require(_globalMin < globalMax);
globalMin = _globalMin;
}
function updateTokenAddress(address _tokenAddress) public finalized onlyOwner {
require(_tokenAddress != address(0));
tokenAddress = _tokenAddress;
}
// Pause the presale (disables contributions and token claiming).
function pause() public onlyOwner {
require(active);
active = false;
}
// Resume the presale (enables contributions and token claiming).
function resume() public onlyOwner {
require(!active);
active = true;
}
// Allow contributors to call the refund function to get their contributions
// returned to their whitelisted address.
function enableRefund() public onlyOwner {
require(!refundable);
refundable = true;
}
// Disallow refunds (this is the case by default).
function disableRefund() public onlyOwner {
require(refundable);
refundable = false;
}
// Add a contributor to the whitelist.
function addContributor(address _account, uint256 _rate, uint256 _max) public onlyOwner notFinalized {
require(_account != address(0));
require(_rate > 0);
require(_max >= globalMin);
require(!contributors[_account].whitelisted);
contributors[_account].whitelisted = true;
contributors[_account].max = _max;
contributors[_account].rate = _rate;
}
// Updates a contributor's rate and/or max.
function updateContributor(address _account, uint256 _newRate, uint256 _newMax) public onlyOwner notFinalized {
require(_account != address(0));
require(_newRate > 0);
require(_newMax >= globalMin);
require(contributors[_account].whitelisted);
// Account for any changes in rate since we are keeping track of total XNK
// purchased.
if (contributors[_account].balance > 0 && contributors[_account].rate != _newRate) {
// Put back the purchased XNK for the old rate.
xnkPurchased = xnkPurchased.sub(contributors[_account].balance.mul(contributors[_account].rate));
// Purchase XNK at the new rate.
xnkPurchased = xnkPurchased.add(contributors[_account].balance.mul(_newRate));
}
contributors[_account].rate = _newRate;
contributors[_account].max = _newMax;
}
// Remove the contributor from the whitelist. This also refunds their
// contribution if they have made any.
function removeContributor(address _account) public onlyOwner {
require(_account != address(0));
require(contributors[_account].whitelisted);
// Remove from whitelist.
contributors[_account].whitelisted = false;
// If contributions were made, refund it.
if (contributors[_account].balance > 0) {
uint256 balance = contributors[_account].balance;
contributors[_account].balance = 0;
xnkPurchased = xnkPurchased.sub(balance.mul(contributors[_account].rate));
etherContributed = etherContributed.sub(balance);
// XXX: The exclamation point does nothing. We just want to get rid of the
// compiler warning that we're not using the returned value of the Ether
// transfer. The transfer *can* fail but we don't want it to stop the
// removal of the contributor. We will deal if the transfer failure
// manually outside this contract.
!_account.call.value(balance)();
}
delete contributors[_account];
}
function withdrawXNK(address _to) public onlyOwner {
require(_to != address(0));
BasicToken token = BasicToken(tokenAddress);
assert(token.transfer(_to, token.balanceOf(this)));
}
function withdrawEther(address _to) public finalized onlyOwner {
require(_to != address(0));
assert(_to.call.value(this.balance)());
}
// Returns a contributor's balance.
function balanceOf(address _account) public view returns (uint256) {
require(_account != address(0));
return contributors[_account].balance;
}
// When refunds are enabled, contributors can call this function get their
// contributed Ether back. The contributor must still be whitelisted.
function refund() public {
require(active);
require(refundable);
require(contributors[msg.sender].whitelisted);
uint256 balance = contributors[msg.sender].balance;
require(balance > 0);
contributors[msg.sender].balance = 0;
etherContributed = etherContributed.sub(balance);
xnkPurchased = xnkPurchased.sub(balance.mul(contributors[msg.sender].rate));
assert(msg.sender.call.value(balance)());
}
function airdrop(address _account) public finalized onlyOwner {
_processPayout(_account);
}
// Finalize the presale by specifying the XNK token's contract address.
// No further contributions can be made. The presale will be in the
// "token claiming" phase.
function finalize(address _tokenAddress) public notFinalized onlyOwner {
require(_tokenAddress != address(0));
tokenAddress = _tokenAddress;
}
// Fallback/payable method for contributions and token claiming.
function () public payable {
// Allow the owner to send Ether to the contract arbitrarily.
if (msg.sender == owner && msg.value > 0) {
return;
}
require(active);
require(contributors[msg.sender].whitelisted);
if (tokenAddress == address(0)) {
// Presale is still accepting contributions.
_processContribution();
} else {
// Presale has been finalized and the user is attempting to claim
// XNK tokens.
_processPayout(msg.sender);
}
}
// Process the contribution.
function _processContribution() private {
// Must be contributing a positive amount.
require(msg.value > 0);
// Limit the transaction's gas price.
require(tx.gasprice <= maxGasPrice);
// The sum of the contributor's total contributions must be higher than the
// global minimum.
require(contributors[msg.sender].balance.add(msg.value) >= globalMin);
// The global contribution cap must be higher than what has been contributed
// by everyone. Otherwise, there's zero room for any contribution.
require(etherCap > etherContributed);
// Make sure that this specific contribution does not take the total
// contribution by everyone over the global contribution cap.
require(msg.value <= etherCap.sub(etherContributed));
uint256 newBalance = contributors[msg.sender].balance.add(msg.value);
// We limit the individual's contribution based on whichever is lower
// between their individual max or the global max.
if (globalMax <= contributors[msg.sender].max) {
require(newBalance <= globalMax);
} else {
require(newBalance <= contributors[msg.sender].max);
}
// Increment the contributor's balance.
contributors[msg.sender].balance = newBalance;
// Increment the total amount of Ether contributed by everyone.
etherContributed = etherContributed.add(msg.value);
// Increment the total amount of XNK purchased by everyone.
xnkPurchased = xnkPurchased.add(msg.value.mul(contributors[msg.sender].rate));
}
// Process the token claim.
function _processPayout(address _recipient) private {
// The transaction must be 0 Ether.
require(msg.value == 0);
uint256 balance = contributors[_recipient].balance;
// The contributor must have contributed something.
require(balance > 0);
// Figure out the amount of XNK the contributor will receive.
uint256 amount = balance.mul(contributors[_recipient].rate);
// Zero out the contributor's balance to denote that they have received
// their tokens.
contributors[_recipient].balance = 0;
// Transfer XNK to the contributor.
assert(BasicToken(tokenAddress).transfer(_recipient, amount));
}
} | Add a contributor to the whitelist. | function addContributor(address _account, uint256 _rate, uint256 _max) public onlyOwner notFinalized {
require(_account != address(0));
require(_rate > 0);
require(_max >= globalMin);
require(!contributors[_account].whitelisted);
contributors[_account].whitelisted = true;
contributors[_account].max = _max;
contributors[_account].rate = _rate;
}
| 12,829,355 | [
1,
986,
279,
31123,
358,
326,
10734,
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,
225,
445,
527,
442,
19293,
12,
2867,
389,
4631,
16,
2254,
5034,
389,
5141,
16,
2254,
5034,
389,
1896,
13,
1071,
1338,
5541,
486,
7951,
1235,
288,
203,
565,
2583,
24899,
4631,
480,
1758,
12,
20,
10019,
203,
565,
2583,
24899,
5141,
405,
374,
1769,
203,
565,
2583,
24899,
1896,
1545,
2552,
2930,
1769,
203,
565,
2583,
12,
5,
26930,
13595,
63,
67,
4631,
8009,
20409,
329,
1769,
203,
203,
565,
13608,
13595,
63,
67,
4631,
8009,
20409,
329,
273,
638,
31,
203,
565,
13608,
13595,
63,
67,
4631,
8009,
1896,
273,
389,
1896,
31,
203,
565,
13608,
13595,
63,
67,
4631,
8009,
5141,
273,
389,
5141,
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
] |
pragma solidity ^0.4.13;
interface ERC721Enumerable /* is ERC721 */ {
/// @notice Count NFTs tracked by this contract
/// @return A count of valid NFTs tracked by this contract, where each one of
/// them has an assigned and queryable owner not equal to the zero address
function totalSupply() public view returns (uint256);
/// @notice Enumerate valid NFTs
/// @dev Throws if `_index` >= `totalSupply()`.
/// @param _index A counter less than `totalSupply()`
/// @return The token identifier for the `_index`th NFT,
/// (sort order not specified)
function tokenByIndex(uint256 _index) external view returns (uint256);
/// @notice Enumerate NFTs assigned to an owner
/// @dev Throws if `_index` >= `balanceOf(_owner)` or if
/// `_owner` is the zero address, representing invalid NFTs.
/// @param _owner An address where we are interested in NFTs owned by them
/// @param _index A counter less than `balanceOf(_owner)`
/// @return The token identifier for the `_index`th NFT assigned to `_owner`,
/// (sort order not specified)
function tokenOfOwnerByIndex(address _owner, uint256 _index) external view returns (uint256 _tokenId);
}
interface ERC721Metadata /* is ERC721 */ {
/// @notice A descriptive name for a collection of NFTs in this contract
function name() external pure returns (string _name);
/// @notice An abbreviated name for NFTs in this contract
function symbol() external pure returns (string _symbol);
/// @notice A distinct Uniform Resource Identifier (URI) for a given asset.
/// @dev Throws if `_tokenId` is not a valid NFT. URIs are defined in RFC
/// 3986. The URI may point to a JSON file that conforms to the "ERC721
/// Metadata JSON Schema".
function tokenURI(uint256 _tokenId) external view returns (string);
}
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;
}
}
interface ERC721TokenReceiver {
/// @notice Handle the receipt of an NFT
/// @dev The ERC721 smart contract calls this function on the recipient
/// after a `transfer`. This function MAY throw to revert and reject the
/// transfer. This function MUST use 50,000 gas or less. Return of other
/// than the magic value MUST result in the transaction being reverted.
/// Note: the contract address is always the message sender.
/// @param _from The sending address
/// @param _tokenId The NFT identifier which is being transfered
/// @param _data Additional data with no specified format
/// @return `bytes4(keccak256("onERC721Received(address,uint256,bytes)"))`
/// unless throwing
function onERC721Received(address _from, uint256 _tokenId, bytes _data) external returns(bytes4);
}
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;
}
}
contract LicenseAccessControl {
/**
* @notice ContractUpgrade is the event that will be emitted if we set a new contract address
*/
event ContractUpgrade(address newContract);
event Paused();
event Unpaused();
/**
* @notice CEO's address FOOBAR
*/
address public ceoAddress;
/**
* @notice CFO's address
*/
address public cfoAddress;
/**
* @notice COO's address
*/
address public cooAddress;
/**
* @notice withdrawal address
*/
address public withdrawalAddress;
bool public paused = false;
/**
* @dev Modifier to make a function only callable by the CEO
*/
modifier onlyCEO() {
require(msg.sender == ceoAddress);
_;
}
/**
* @dev Modifier to make a function only callable by the CFO
*/
modifier onlyCFO() {
require(msg.sender == cfoAddress);
_;
}
/**
* @dev Modifier to make a function only callable by the COO
*/
modifier onlyCOO() {
require(msg.sender == cooAddress);
_;
}
/**
* @dev Modifier to make a function only callable by C-level execs
*/
modifier onlyCLevel() {
require(
msg.sender == cooAddress ||
msg.sender == ceoAddress ||
msg.sender == cfoAddress
);
_;
}
/**
* @dev Modifier to make a function only callable by CEO or CFO
*/
modifier onlyCEOOrCFO() {
require(
msg.sender == cfoAddress ||
msg.sender == ceoAddress
);
_;
}
/**
* @dev Modifier to make a function only callable by CEO or COO
*/
modifier onlyCEOOrCOO() {
require(
msg.sender == cooAddress ||
msg.sender == ceoAddress
);
_;
}
/**
* @notice Sets a new CEO
* @param _newCEO - the address of the new CEO
*/
function setCEO(address _newCEO) external onlyCEO {
require(_newCEO != address(0));
ceoAddress = _newCEO;
}
/**
* @notice Sets a new CFO
* @param _newCFO - the address of the new CFO
*/
function setCFO(address _newCFO) external onlyCEO {
require(_newCFO != address(0));
cfoAddress = _newCFO;
}
/**
* @notice Sets a new COO
* @param _newCOO - the address of the new COO
*/
function setCOO(address _newCOO) external onlyCEO {
require(_newCOO != address(0));
cooAddress = _newCOO;
}
/**
* @notice Sets a new withdrawalAddress
* @param _newWithdrawalAddress - the address where we'll send the funds
*/
function setWithdrawalAddress(address _newWithdrawalAddress) external onlyCEO {
require(_newWithdrawalAddress != address(0));
withdrawalAddress = _newWithdrawalAddress;
}
/**
* @notice Withdraw the balance to the withdrawalAddress
* @dev We set a withdrawal address seperate from the CFO because this allows us to withdraw to a cold wallet.
*/
function withdrawBalance() external onlyCEOOrCFO {
require(withdrawalAddress != address(0));
withdrawalAddress.transfer(this.balance);
}
/** Pausable functionality adapted from OpenZeppelin **/
/**
* @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);
_;
}
/**
* @notice called by any C-level to pause, triggers stopped state
*/
function pause() public onlyCLevel whenNotPaused {
paused = true;
Paused();
}
/**
* @notice called by the CEO to unpause, returns to normal state
*/
function unpause() public onlyCEO whenPaused {
paused = false;
Unpaused();
}
}
contract LicenseBase is LicenseAccessControl {
/**
* @notice Issued is emitted when a new license is issued
*/
event LicenseIssued(
address indexed owner,
address indexed purchaser,
uint256 licenseId,
uint256 productId,
uint256 attributes,
uint256 issuedTime,
uint256 expirationTime,
address affiliate
);
event LicenseRenewal(
address indexed owner,
address indexed purchaser,
uint256 licenseId,
uint256 productId,
uint256 expirationTime
);
struct License {
uint256 productId;
uint256 attributes;
uint256 issuedTime;
uint256 expirationTime;
address affiliate;
}
/**
* @notice All licenses in existence.
* @dev The ID of each license is an index in this array.
*/
License[] licenses;
/** internal **/
function _isValidLicense(uint256 _licenseId) internal view returns (bool) {
return licenseProductId(_licenseId) != 0;
}
/** anyone **/
/**
* @notice Get a license's productId
* @param _licenseId the license id
*/
function licenseProductId(uint256 _licenseId) public view returns (uint256) {
return licenses[_licenseId].productId;
}
/**
* @notice Get a license's attributes
* @param _licenseId the license id
*/
function licenseAttributes(uint256 _licenseId) public view returns (uint256) {
return licenses[_licenseId].attributes;
}
/**
* @notice Get a license's issueTime
* @param _licenseId the license id
*/
function licenseIssuedTime(uint256 _licenseId) public view returns (uint256) {
return licenses[_licenseId].issuedTime;
}
/**
* @notice Get a license's issueTime
* @param _licenseId the license id
*/
function licenseExpirationTime(uint256 _licenseId) public view returns (uint256) {
return licenses[_licenseId].expirationTime;
}
/**
* @notice Get a the affiliate credited for the sale of this license
* @param _licenseId the license id
*/
function licenseAffiliate(uint256 _licenseId) public view returns (address) {
return licenses[_licenseId].affiliate;
}
/**
* @notice Get a license's info
* @param _licenseId the license id
*/
function licenseInfo(uint256 _licenseId)
public view returns (uint256, uint256, uint256, uint256, address)
{
return (
licenseProductId(_licenseId),
licenseAttributes(_licenseId),
licenseIssuedTime(_licenseId),
licenseExpirationTime(_licenseId),
licenseAffiliate(_licenseId)
);
}
}
contract Pausable is Ownable {
event Pause();
event Unpause();
bool public paused = false;
/**
* @dev Modifier to make a function callable only when the contract is not paused.
*/
modifier whenNotPaused() {
require(!paused);
_;
}
/**
* @dev Modifier to make a function callable only when the contract is paused.
*/
modifier whenPaused() {
require(paused);
_;
}
/**
* @dev called by the owner to pause, triggers stopped state
*/
function pause() onlyOwner whenNotPaused public {
paused = true;
Pause();
}
/**
* @dev called by the owner to unpause, returns to normal state
*/
function unpause() onlyOwner whenPaused public {
paused = false;
Unpause();
}
}
contract AffiliateProgram is Pausable {
using SafeMath for uint256;
event AffiliateCredit(
// The address of the affiliate
address affiliate,
// The store's ID of what was sold (e.g. a tokenId)
uint256 productId,
// The amount owed this affiliate in this sale
uint256 amount
);
event Withdraw(address affiliate, address to, uint256 amount);
event Whitelisted(address affiliate, uint256 amount);
event RateChanged(uint256 rate, uint256 amount);
// @notice A mapping from affiliate address to their balance
mapping (address => uint256) public balances;
// @notice A mapping from affiliate address to the time of last deposit
mapping (address => uint256) public lastDepositTimes;
// @notice The last deposit globally
uint256 public lastDepositTime;
// @notice The maximum rate for any affiliate
// @dev The hard-coded maximum affiliate rate (in basis points)
// All rates are measured in basis points (1/100 of a percent)
// Values 0-10,000 map to 0%-100%
uint256 private constant hardCodedMaximumRate = 5000;
// @notice The commission exiration time
// @dev Affiliate commissions expire if they are unclaimed after this amount of time
uint256 private constant commissionExpiryTime = 30 days;
// @notice The baseline affiliate rate (in basis points) for non-whitelisted referrals
uint256 public baselineRate = 0;
// @notice A mapping from whitelisted referrals to their individual rates
mapping (address => uint256) public whitelistRates;
// @notice The maximum rate for any affiliate
// @dev overrides individual rates. This can be used to clip the rate used in bulk, if necessary
uint256 public maximumRate = 5000;
// @notice The address of the store selling products
address public storeAddress;
// @notice The contract is retired
// @dev If we decide to retire this program, this value will be set to true
// and then the contract cannot be unpaused
bool public retired = false;
/**
* @dev Modifier to make a function only callable by the store or the owner
*/
modifier onlyStoreOrOwner() {
require(
msg.sender == storeAddress ||
msg.sender == owner);
_;
}
/**
* @dev AffiliateProgram constructor - keeps the address of it's parent store
* and pauses the contract
*/
function AffiliateProgram(address _storeAddress) public {
require(_storeAddress != address(0));
storeAddress = _storeAddress;
paused = true;
}
/**
* @notice Exposes that this contract thinks it is an AffiliateProgram
*/
function isAffiliateProgram() public pure returns (bool) {
return true;
}
/**
* @notice returns the commission rate for a sale
*
* @dev rateFor returns the rate which should be used to calculate the comission
* for this affiliate/sale combination, in basis points (1/100th of a percent).
*
* We may want to completely blacklist a particular address (e.g. a known bad actor affilite).
* To that end, if the whitelistRate is exactly 1bp, we use that as a signal for blacklisting
* and return a rate of zero. The upside is that we can completely turn off
* sending transactions to a particular address when this is needed. The
* downside is that you can't issued 1/100th of a percent commission.
* However, since this is such a small amount its an acceptable tradeoff.
*
* This implementation does not use the _productId, _pruchaseId,
* _purchaseAmount, but we include them here as part of the protocol, because
* they could be useful in more advanced affiliate programs.
*
* @param _affiliate - the address of the affiliate to check for
*/
function rateFor(
address _affiliate,
uint256 /*_productId*/,
uint256 /*_purchaseId*/,
uint256 /*_purchaseAmount*/)
public
view
returns (uint256)
{
uint256 whitelistedRate = whitelistRates[_affiliate];
if(whitelistedRate > 0) {
// use 1 bp as a blacklist signal
if(whitelistedRate == 1) {
return 0;
} else {
return Math.min256(whitelistedRate, maximumRate);
}
} else {
return Math.min256(baselineRate, maximumRate);
}
}
/**
* @notice cutFor returns the affiliate cut for a sale
* @dev cutFor returns the cut (amount in wei) to give in comission to the affiliate
*
* @param _affiliate - the address of the affiliate to check for
* @param _productId - the productId in the sale
* @param _purchaseId - the purchaseId in the sale
* @param _purchaseAmount - the purchaseAmount
*/
function cutFor(
address _affiliate,
uint256 _productId,
uint256 _purchaseId,
uint256 _purchaseAmount)
public
view
returns (uint256)
{
uint256 rate = rateFor(
_affiliate,
_productId,
_purchaseId,
_purchaseAmount);
require(rate <= hardCodedMaximumRate);
return (_purchaseAmount.mul(rate)).div(10000);
}
/**
* @notice credit an affiliate for a purchase
* @dev credit accepts eth and credits the affiliate's balance for the amount
*
* @param _affiliate - the address of the affiliate to credit
* @param _purchaseId - the purchaseId of the sale
*/
function credit(
address _affiliate,
uint256 _purchaseId)
public
onlyStoreOrOwner
whenNotPaused
payable
{
require(msg.value > 0);
require(_affiliate != address(0));
balances[_affiliate] += msg.value;
lastDepositTimes[_affiliate] = now; // solium-disable-line security/no-block-members
lastDepositTime = now; // solium-disable-line security/no-block-members
AffiliateCredit(_affiliate, _purchaseId, msg.value);
}
/**
* @dev _performWithdraw performs a withdrawal from address _from and
* transfers it to _to. This can be different because we allow the owner
* to withdraw unclaimed funds after a period of time.
*
* @param _from - the address to subtract balance from
* @param _to - the address to transfer ETH to
*/
function _performWithdraw(address _from, address _to) private {
require(balances[_from] > 0);
uint256 balanceValue = balances[_from];
balances[_from] = 0;
_to.transfer(balanceValue);
Withdraw(_from, _to, balanceValue);
}
/**
* @notice withdraw
* @dev withdraw the msg.sender's balance
*/
function withdraw() public whenNotPaused {
_performWithdraw(msg.sender, msg.sender);
}
/**
* @notice withdraw from a specific account
* @dev withdrawFrom allows the owner to withdraw an affiliate's unclaimed
* ETH, after the alotted time.
*
* This function can be called even if the contract is paused
*
* @param _affiliate - the address of the affiliate
* @param _to - the address to send ETH to
*/
function withdrawFrom(address _affiliate, address _to) onlyOwner public {
// solium-disable-next-line security/no-block-members
require(now > lastDepositTimes[_affiliate].add(commissionExpiryTime));
_performWithdraw(_affiliate, _to);
}
/**
* @notice retire the contract (dangerous)
* @dev retire - withdraws the entire balance and marks the contract as retired, which
* prevents unpausing.
*
* If no new comissions have been deposited for the alotted time,
* then the owner may pause the program and retire this contract.
* This may only be performed once as the contract cannot be unpaused.
*
* We do this as an alternative to selfdestruct, because certain operations
* can still be performed after the contract has been selfdestructed, such as
* the owner withdrawing ETH accidentally sent here.
*/
function retire(address _to) onlyOwner whenPaused public {
// solium-disable-next-line security/no-block-members
require(now > lastDepositTime.add(commissionExpiryTime));
_to.transfer(this.balance);
retired = true;
}
/**
* @notice whitelist an affiliate address
* @dev whitelist - white listed affiliates can receive a different
* rate than the general public (whitelisted accounts would generally get a
* better rate).
* @param _affiliate - the affiliate address to whitelist
* @param _rate - the rate, in basis-points (1/100th of a percent) to give this affiliate in each sale. NOTE: a rate of exactly 1 is the signal to blacklist this affiliate. That is, a rate of 1 will set the commission to 0.
*/
function whitelist(address _affiliate, uint256 _rate) onlyOwner public {
require(_rate <= hardCodedMaximumRate);
whitelistRates[_affiliate] = _rate;
Whitelisted(_affiliate, _rate);
}
/**
* @notice set the rate for non-whitelisted affiliates
* @dev setBaselineRate - sets the baseline rate for any affiliate that is not whitelisted
* @param _newRate - the rate, in bp (1/100th of a percent) to give any non-whitelisted affiliate. Set to zero to "turn off"
*/
function setBaselineRate(uint256 _newRate) onlyOwner public {
require(_newRate <= hardCodedMaximumRate);
baselineRate = _newRate;
RateChanged(0, _newRate);
}
/**
* @notice set the maximum rate for any affiliate
* @dev setMaximumRate - Set the maximum rate for any affiliate, including whitelists. That is, this overrides individual rates.
* @param _newRate - the rate, in bp (1/100th of a percent)
*/
function setMaximumRate(uint256 _newRate) onlyOwner public {
require(_newRate <= hardCodedMaximumRate);
maximumRate = _newRate;
RateChanged(1, _newRate);
}
/**
* @notice unpause the contract
* @dev called by the owner to unpause, returns to normal state. Will not
* unpause if the contract is retired.
*/
function unpause() onlyOwner whenPaused public {
require(!retired);
paused = false;
Unpause();
}
}
contract ERC721 {
event Transfer(address indexed _from, address indexed _to, uint256 _tokenId);
event Approval(address indexed _owner, address indexed _approved, uint256 _tokenId);
event ApprovalForAll(address indexed _owner, address indexed _operator, bool _approved);
function balanceOf(address _owner) public view returns (uint256 _balance);
function ownerOf(uint256 _tokenId) public view returns (address _owner);
function safeTransferFrom(address _from, address _to, uint256 _tokenId, bytes data) public;
function safeTransferFrom(address _from, address _to, uint256 _tokenId) external;
function transfer(address _to, uint256 _tokenId) external;
function transferFrom(address _from, address _to, uint256 _tokenId) public;
function approve(address _to, uint256 _tokenId) external;
function setApprovalForAll(address _to, bool _approved) external;
function getApproved(uint256 _tokenId) public view returns (address);
function isApprovedForAll(address _owner, address _operator) public view returns (bool);
}
contract LicenseInventory is LicenseBase {
using SafeMath for uint256;
event ProductCreated(
uint256 id,
uint256 price,
uint256 available,
uint256 supply,
uint256 interval,
bool renewable
);
event ProductInventoryAdjusted(uint256 productId, uint256 available);
event ProductPriceChanged(uint256 productId, uint256 price);
event ProductRenewableChanged(uint256 productId, bool renewable);
/**
* @notice Product defines a product
* * renewable: There may come a time when we which to disable the ability to renew a subscription. For example, a plan we no longer wish to support. Obviously care needs to be taken with how we communicate this to customers, but contract-wise, we want to support the ability to discontinue renewal of certain plans.
*/
struct Product {
uint256 id;
uint256 price;
uint256 available;
uint256 supply;
uint256 sold;
uint256 interval;
bool renewable;
}
// @notice All products in existence
uint256[] public allProductIds;
// @notice A mapping from product ids to Products
mapping (uint256 => Product) public products;
/*** internal ***/
/**
* @notice _productExists checks to see if a product exists
*/
function _productExists(uint256 _productId) internal view returns (bool) {
return products[_productId].id != 0;
}
function _productDoesNotExist(uint256 _productId) internal view returns (bool) {
return products[_productId].id == 0;
}
function _createProduct(
uint256 _productId,
uint256 _initialPrice,
uint256 _initialInventoryQuantity,
uint256 _supply,
uint256 _interval)
internal
{
require(_productDoesNotExist(_productId));
require(_initialInventoryQuantity <= _supply);
Product memory _product = Product({
id: _productId,
price: _initialPrice,
available: _initialInventoryQuantity,
supply: _supply,
sold: 0,
interval: _interval,
renewable: _interval == 0 ? false : true
});
products[_productId] = _product;
allProductIds.push(_productId);
ProductCreated(
_product.id,
_product.price,
_product.available,
_product.supply,
_product.interval,
_product.renewable
);
}
function _incrementInventory(
uint256 _productId,
uint256 _inventoryAdjustment)
internal
{
require(_productExists(_productId));
uint256 newInventoryLevel = products[_productId].available.add(_inventoryAdjustment);
// A supply of "0" means "unlimited". Otherwise we need to ensure that we're not over-creating this product
if(products[_productId].supply > 0) {
// you have to take already sold into account
require(products[_productId].sold.add(newInventoryLevel) <= products[_productId].supply);
}
products[_productId].available = newInventoryLevel;
}
function _decrementInventory(
uint256 _productId,
uint256 _inventoryAdjustment)
internal
{
require(_productExists(_productId));
uint256 newInventoryLevel = products[_productId].available.sub(_inventoryAdjustment);
// unnecessary because we're using SafeMath and an unsigned int
// require(newInventoryLevel >= 0);
products[_productId].available = newInventoryLevel;
}
function _clearInventory(uint256 _productId) internal
{
require(_productExists(_productId));
products[_productId].available = 0;
}
function _setPrice(uint256 _productId, uint256 _price) internal
{
require(_productExists(_productId));
products[_productId].price = _price;
}
function _setRenewable(uint256 _productId, bool _isRenewable) internal
{
require(_productExists(_productId));
products[_productId].renewable = _isRenewable;
}
function _purchaseOneUnitInStock(uint256 _productId) internal {
require(_productExists(_productId));
require(availableInventoryOf(_productId) > 0);
// lower inventory
_decrementInventory(_productId, 1);
// record that one was sold
products[_productId].sold = products[_productId].sold.add(1);
}
function _requireRenewableProduct(uint256 _productId) internal view {
// productId must exist
require(_productId != 0);
// You can only renew a subscription product
require(isSubscriptionProduct(_productId));
// The product must currently be renewable
require(renewableOf(_productId));
}
/*** public ***/
/** executives-only **/
/**
* @notice createProduct creates a new product in the system
* @param _productId - the id of the product to use (cannot be changed)
* @param _initialPrice - the starting price (price can be changed)
* @param _initialInventoryQuantity - the initial inventory (inventory can be changed)
* @param _supply - the total supply - use `0` for "unlimited" (cannot be changed)
*/
function createProduct(
uint256 _productId,
uint256 _initialPrice,
uint256 _initialInventoryQuantity,
uint256 _supply,
uint256 _interval)
external
onlyCEOOrCOO
{
_createProduct(
_productId,
_initialPrice,
_initialInventoryQuantity,
_supply,
_interval);
}
/**
* @notice incrementInventory - increments the inventory of a product
* @param _productId - the product id
* @param _inventoryAdjustment - the amount to increment
*/
function incrementInventory(
uint256 _productId,
uint256 _inventoryAdjustment)
external
onlyCLevel
{
_incrementInventory(_productId, _inventoryAdjustment);
ProductInventoryAdjusted(_productId, availableInventoryOf(_productId));
}
/**
* @notice decrementInventory removes inventory levels for a product
* @param _productId - the product id
* @param _inventoryAdjustment - the amount to decrement
*/
function decrementInventory(
uint256 _productId,
uint256 _inventoryAdjustment)
external
onlyCLevel
{
_decrementInventory(_productId, _inventoryAdjustment);
ProductInventoryAdjusted(_productId, availableInventoryOf(_productId));
}
/**
* @notice clearInventory clears the inventory of a product.
* @dev decrementInventory verifies inventory levels, whereas this method
* simply sets the inventory to zero. This is useful, for example, if an
* executive wants to take a product off the market quickly. There could be a
* race condition with decrementInventory where a product is sold, which could
* cause the admins decrement to fail (because it may try to decrement more
* than available).
*
* @param _productId - the product id
*/
function clearInventory(uint256 _productId)
external
onlyCLevel
{
_clearInventory(_productId);
ProductInventoryAdjusted(_productId, availableInventoryOf(_productId));
}
/**
* @notice setPrice - sets the price of a product
* @param _productId - the product id
* @param _price - the product price
*/
function setPrice(uint256 _productId, uint256 _price)
external
onlyCLevel
{
_setPrice(_productId, _price);
ProductPriceChanged(_productId, _price);
}
/**
* @notice setRenewable - sets if a product is renewable
* @param _productId - the product id
* @param _newRenewable - the new renewable setting
*/
function setRenewable(uint256 _productId, bool _newRenewable)
external
onlyCLevel
{
_setRenewable(_productId, _newRenewable);
ProductRenewableChanged(_productId, _newRenewable);
}
/** anyone **/
/**
* @notice The price of a product
* @param _productId - the product id
*/
function priceOf(uint256 _productId) public view returns (uint256) {
return products[_productId].price;
}
/**
* @notice The available inventory of a product
* @param _productId - the product id
*/
function availableInventoryOf(uint256 _productId) public view returns (uint256) {
return products[_productId].available;
}
/**
* @notice The total supply of a product
* @param _productId - the product id
*/
function totalSupplyOf(uint256 _productId) public view returns (uint256) {
return products[_productId].supply;
}
/**
* @notice The total sold of a product
* @param _productId - the product id
*/
function totalSold(uint256 _productId) public view returns (uint256) {
return products[_productId].sold;
}
/**
* @notice The renewal interval of a product in seconds
* @param _productId - the product id
*/
function intervalOf(uint256 _productId) public view returns (uint256) {
return products[_productId].interval;
}
/**
* @notice Is this product renewable?
* @param _productId - the product id
*/
function renewableOf(uint256 _productId) public view returns (bool) {
return products[_productId].renewable;
}
/**
* @notice The product info for a product
* @param _productId - the product id
*/
function productInfo(uint256 _productId)
public
view
returns (uint256, uint256, uint256, uint256, bool)
{
return (
priceOf(_productId),
availableInventoryOf(_productId),
totalSupplyOf(_productId),
intervalOf(_productId),
renewableOf(_productId));
}
/**
* @notice Get all product ids
*/
function getAllProductIds() public view returns (uint256[]) {
return allProductIds;
}
/**
* @notice returns the total cost to renew a product for a number of cycles
* @dev If a product is a subscription, the interval defines the period of
* time, in seconds, users can subscribe for. E.g. 1 month or 1 year.
* _numCycles is the number of these intervals we want to use in the
* calculation of the price.
*
* We require that the end user send precisely the amount required (instead
* of dealing with excess refunds). This method is public so that clients can
* read the exact amount our contract expects to receive.
*
* @param _productId - the product we're calculating for
* @param _numCycles - the number of cycles to calculate for
*/
function costForProductCycles(uint256 _productId, uint256 _numCycles)
public
view
returns (uint256)
{
return priceOf(_productId).mul(_numCycles);
}
/**
* @notice returns if this product is a subscription or not
* @dev Some products are subscriptions and others are not. An interval of 0
* means the product is not a subscription
* @param _productId - the product we're checking
*/
function isSubscriptionProduct(uint256 _productId) public view returns (bool) {
return intervalOf(_productId) > 0;
}
}
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;
}
}
interface ERC165 {
/// @notice Query if a contract implements an interface
/// @param interfaceID The interface identifier, as specified in ERC-165
/// @dev Interface identification is specified in ERC-165. This function
/// uses less than 30,000 gas.
/// @return `true` if the contract implements `interfaceID` and
/// `interfaceID` is not 0xffffffff, `false` otherwise
function supportsInterface(bytes4 interfaceID) external view returns (bool);
}
contract LicenseOwnership is LicenseInventory, ERC721, ERC165, ERC721Metadata, ERC721Enumerable {
using SafeMath for uint256;
// Total amount of tokens
uint256 private totalTokens;
// Mapping from token ID to owner
mapping (uint256 => address) private tokenOwner;
// Mapping from token ID to approved address
mapping (uint256 => address) private tokenApprovals;
// Mapping from owner address to operator address to approval
mapping (address => mapping (address => bool)) private operatorApprovals;
// Mapping from owner to list of owned token IDs
mapping (address => uint256[]) private ownedTokens;
// Mapping from token ID to index of the owner tokens list
mapping(uint256 => uint256) private ownedTokensIndex;
/*** Constants ***/
// Configure these for your own deployment
string public constant NAME = "Dottabot";
string public constant SYMBOL = "DOTTA";
string public tokenMetadataBaseURI = "https://api.dottabot.com/";
/**
* @notice token's name
*/
function name() external pure returns (string) {
return NAME;
}
/**
* @notice symbols's name
*/
function symbol() external pure returns (string) {
return SYMBOL;
}
function implementsERC721() external pure returns (bool) {
return true;
}
function tokenURI(uint256 _tokenId)
external
view
returns (string infoUrl)
{
return Strings.strConcat(
tokenMetadataBaseURI,
Strings.uint2str(_tokenId));
}
function supportsInterface(
bytes4 interfaceID) // solium-disable-line dotta/underscore-function-arguments
external view returns (bool)
{
return
interfaceID == this.supportsInterface.selector || // ERC165
interfaceID == 0x5b5e139f || // ERC721Metadata
interfaceID == 0x6466353c || // ERC-721 on 3/7/2018
interfaceID == 0x780e9d63; // ERC721Enumerable
}
function setTokenMetadataBaseURI(string _newBaseURI) external onlyCEOOrCOO {
tokenMetadataBaseURI = _newBaseURI;
}
/**
* @notice Guarantees msg.sender is owner of the given token
* @param _tokenId uint256 ID of the token to validate its ownership belongs to msg.sender
*/
modifier onlyOwnerOf(uint256 _tokenId) {
require(ownerOf(_tokenId) == msg.sender);
_;
}
/**
* @notice Gets the total amount of tokens stored by the contract
* @return uint256 representing the total amount of tokens
*/
function totalSupply() public view returns (uint256) {
return totalTokens;
}
/**
* @notice Enumerate valid NFTs
* @dev Our Licenses are kept in an array and each new License-token is just
* the next element in the array. This method is required for ERC721Enumerable
* which may support more complicated storage schemes. However, in our case the
* _index is the tokenId
* @param _index A counter less than `totalSupply()`
* @return The token identifier for the `_index`th NFT
*/
function tokenByIndex(uint256 _index) external view returns (uint256) {
require(_index < totalSupply());
return _index;
}
/**
* @notice Gets the balance of the specified address
* @param _owner address to query the balance of
* @return uint256 representing the amount owned by the passed address
*/
function balanceOf(address _owner) public view returns (uint256) {
require(_owner != address(0));
return ownedTokens[_owner].length;
}
/**
* @notice Gets the list of tokens owned by a given address
* @param _owner address to query the tokens of
* @return uint256[] representing the list of tokens owned by the passed address
*/
function tokensOf(address _owner) public view returns (uint256[]) {
return ownedTokens[_owner];
}
/**
* @notice Enumerate NFTs assigned to an owner
* @dev Throws if `_index` >= `balanceOf(_owner)` or if
* `_owner` is the zero address, representing invalid NFTs.
* @param _owner An address where we are interested in NFTs owned by them
* @param _index A counter less than `balanceOf(_owner)`
* @return The token identifier for the `_index`th NFT assigned to `_owner`,
*/
function tokenOfOwnerByIndex(address _owner, uint256 _index)
external
view
returns (uint256 _tokenId)
{
require(_index < balanceOf(_owner));
return ownedTokens[_owner][_index];
}
/**
* @notice Gets the owner of the specified token ID
* @param _tokenId uint256 ID of the token to query the owner of
* @return owner address currently marked as the owner of the given token ID
*/
function ownerOf(uint256 _tokenId) public view returns (address) {
address owner = tokenOwner[_tokenId];
require(owner != address(0));
return owner;
}
/**
* @notice Gets the approved address to take ownership of a given token ID
* @param _tokenId uint256 ID of the token to query the approval of
* @return address currently approved to take ownership of the given token ID
*/
function getApproved(uint256 _tokenId) public view returns (address) {
return tokenApprovals[_tokenId];
}
/**
* @notice Tells whether the msg.sender is approved to transfer the given token ID or not
* Checks both for specific approval and operator approval
* @param _tokenId uint256 ID of the token to query the approval of
* @return bool whether transfer by msg.sender is approved for the given token ID or not
*/
function isSenderApprovedFor(uint256 _tokenId) internal view returns (bool) {
return
ownerOf(_tokenId) == msg.sender ||
isSpecificallyApprovedFor(msg.sender, _tokenId) ||
isApprovedForAll(ownerOf(_tokenId), msg.sender);
}
/**
* @notice Tells whether the msg.sender is approved for the given token ID or not
* @param _asker address of asking for approval
* @param _tokenId uint256 ID of the token to query the approval of
* @return bool whether the msg.sender is approved for the given token ID or not
*/
function isSpecificallyApprovedFor(address _asker, uint256 _tokenId) internal view returns (bool) {
return getApproved(_tokenId) == _asker;
}
/**
* @notice Tells whether an operator is approved by a given owner
* @param _owner owner address which you want to query the approval of
* @param _operator operator address which you want to query the approval of
* @return bool whether the given operator is approved by the given owner
*/
function isApprovedForAll(address _owner, address _operator) public view returns (bool)
{
return operatorApprovals[_owner][_operator];
}
/**
* @notice Transfers the ownership of a given token ID to another address
* @param _to address to receive the ownership of the given token ID
* @param _tokenId uint256 ID of the token to be transferred
*/
function transfer(address _to, uint256 _tokenId)
external
whenNotPaused
onlyOwnerOf(_tokenId)
{
_clearApprovalAndTransfer(msg.sender, _to, _tokenId);
}
/**
* @notice Approves another address to claim for the ownership of the given token ID
* @param _to address to be approved for the given token ID
* @param _tokenId uint256 ID of the token to be approved
*/
function approve(address _to, uint256 _tokenId)
external
whenNotPaused
onlyOwnerOf(_tokenId)
{
address owner = ownerOf(_tokenId);
require(_to != owner);
if (getApproved(_tokenId) != 0 || _to != 0) {
tokenApprovals[_tokenId] = _to;
Approval(owner, _to, _tokenId);
}
}
/**
* @notice Enable or disable approval for a third party ("operator") to manage all your assets
* @dev Emits the ApprovalForAll event
* @param _to Address to add to the set of authorized operators.
* @param _approved True if the operators is approved, false to revoke approval
*/
function setApprovalForAll(address _to, bool _approved)
external
whenNotPaused
{
if(_approved) {
approveAll(_to);
} else {
disapproveAll(_to);
}
}
/**
* @notice Approves another address to claim for the ownership of any tokens owned by this account
* @param _to address to be approved for the given token ID
*/
function approveAll(address _to)
public
whenNotPaused
{
require(_to != msg.sender);
require(_to != address(0));
operatorApprovals[msg.sender][_to] = true;
ApprovalForAll(msg.sender, _to, true);
}
/**
* @notice Removes approval for another address to claim for the ownership of any
* tokens owned by this account.
* @dev Note that this only removes the operator approval and
* does not clear any independent, specific approvals of token transfers to this address
* @param _to address to be disapproved for the given token ID
*/
function disapproveAll(address _to)
public
whenNotPaused
{
require(_to != msg.sender);
delete operatorApprovals[msg.sender][_to];
ApprovalForAll(msg.sender, _to, false);
}
/**
* @notice Claims the ownership of a given token ID
* @param _tokenId uint256 ID of the token being claimed by the msg.sender
*/
function takeOwnership(uint256 _tokenId)
external
whenNotPaused
{
require(isSenderApprovedFor(_tokenId));
_clearApprovalAndTransfer(ownerOf(_tokenId), msg.sender, _tokenId);
}
/**
* @notice Transfer a token owned by another address, for which the calling address has
* previously been granted transfer approval by the owner.
* @param _from The address that owns the token
* @param _to The address that will take ownership of the token. Can be any address, including the caller
* @param _tokenId The ID of the token to be transferred
*/
function transferFrom(
address _from,
address _to,
uint256 _tokenId
)
public
whenNotPaused
{
require(isSenderApprovedFor(_tokenId));
require(ownerOf(_tokenId) == _from);
_clearApprovalAndTransfer(ownerOf(_tokenId), _to, _tokenId);
}
/**
* @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,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 _data
)
public
whenNotPaused
{
require(_to != address(0));
require(_isValidLicense(_tokenId));
transferFrom(_from, _to, _tokenId);
if (_isContract(_to)) {
bytes4 tokenReceiverResponse = ERC721TokenReceiver(_to).onERC721Received.gas(50000)(
_from, _tokenId, _data
);
require(tokenReceiverResponse == bytes4(keccak256("onERC721Received(address,uint256,bytes)")));
}
}
/*
* @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
whenNotPaused
{
safeTransferFrom(_from, _to, _tokenId, "");
}
/**
* @notice Mint token function
* @param _to The address that will own the minted token
* @param _tokenId uint256 ID of the token to be minted by the msg.sender
*/
function _mint(address _to, uint256 _tokenId) internal {
require(_to != address(0));
_addToken(_to, _tokenId);
Transfer(0x0, _to, _tokenId);
}
/**
* @notice Internal function to clear current approval and transfer the ownership of a given token ID
* @param _from address which you want to send tokens from
* @param _to address which you want to transfer the token to
* @param _tokenId uint256 ID of the token to be transferred
*/
function _clearApprovalAndTransfer(address _from, address _to, uint256 _tokenId) internal {
require(_to != address(0));
require(_to != ownerOf(_tokenId));
require(ownerOf(_tokenId) == _from);
require(_isValidLicense(_tokenId));
_clearApproval(_from, _tokenId);
_removeToken(_from, _tokenId);
_addToken(_to, _tokenId);
Transfer(_from, _to, _tokenId);
}
/**
* @notice Internal function to clear current approval of a given token ID
* @param _tokenId uint256 ID of the token to be transferred
*/
function _clearApproval(address _owner, uint256 _tokenId) private {
require(ownerOf(_tokenId) == _owner);
tokenApprovals[_tokenId] = 0;
Approval(_owner, 0, _tokenId);
}
/**
* @notice Internal function to add a token ID to the list of a given address
* @param _to address representing the new owner of the given token ID
* @param _tokenId uint256 ID of the token to be added to the tokens list of the given address
*/
function _addToken(address _to, uint256 _tokenId) private {
require(tokenOwner[_tokenId] == address(0));
tokenOwner[_tokenId] = _to;
uint256 length = balanceOf(_to);
ownedTokens[_to].push(_tokenId);
ownedTokensIndex[_tokenId] = length;
totalTokens = totalTokens.add(1);
}
/**
* @notice Internal function to remove a token ID from the list of a given address
* @param _from address representing the previous owner of the given token ID
* @param _tokenId uint256 ID of the token to be removed from the tokens list of the given address
*/
function _removeToken(address _from, uint256 _tokenId) private {
require(ownerOf(_tokenId) == _from);
uint256 tokenIndex = ownedTokensIndex[_tokenId];
uint256 lastTokenIndex = balanceOf(_from).sub(1);
uint256 lastToken = ownedTokens[_from][lastTokenIndex];
tokenOwner[_tokenId] = 0;
ownedTokens[_from][tokenIndex] = lastToken;
ownedTokens[_from][lastTokenIndex] = 0;
// Note that this will handle single-element arrays. In that case, both tokenIndex and lastTokenIndex are going to
// be zero. Then we can make sure that we will remove _tokenId from the ownedTokens list since we are first swapping
// the lastToken to the first position, and then dropping the element placed in the last position of the list
ownedTokens[_from].length--;
ownedTokensIndex[_tokenId] = 0;
ownedTokensIndex[lastToken] = tokenIndex;
totalTokens = totalTokens.sub(1);
}
function _isContract(address addr) internal view returns (bool) {
uint size;
assembly { size := extcodesize(addr) }
return size > 0;
}
}
contract LicenseSale is LicenseOwnership {
AffiliateProgram public affiliateProgram;
/**
* @notice We credit affiliates for renewals that occur within this time of
* original purchase. E.g. If this is set to 1 year, and someone subscribes to
* a monthly plan, the affiliate will receive credits for that whole year, as
* the user renews their plan
*/
uint256 public renewalsCreditAffiliatesFor = 1 years;
/** internal **/
function _performPurchase(
uint256 _productId,
uint256 _numCycles,
address _assignee,
uint256 _attributes,
address _affiliate)
internal returns (uint)
{
_purchaseOneUnitInStock(_productId);
return _createLicense(
_productId,
_numCycles,
_assignee,
_attributes,
_affiliate
);
}
function _createLicense(
uint256 _productId,
uint256 _numCycles,
address _assignee,
uint256 _attributes,
address _affiliate)
internal
returns (uint)
{
// You cannot create a subscription license with zero cycles
if(isSubscriptionProduct(_productId)) {
require(_numCycles != 0);
}
// Non-subscription products have an expiration time of 0, meaning "no-expiration"
uint256 expirationTime = isSubscriptionProduct(_productId) ?
now.add(intervalOf(_productId).mul(_numCycles)) : // solium-disable-line security/no-block-members
0;
License memory _license = License({
productId: _productId,
attributes: _attributes,
issuedTime: now, // solium-disable-line security/no-block-members
expirationTime: expirationTime,
affiliate: _affiliate
});
uint256 newLicenseId = licenses.push(_license) - 1; // solium-disable-line zeppelin/no-arithmetic-operations
LicenseIssued(
_assignee,
msg.sender,
newLicenseId,
_license.productId,
_license.attributes,
_license.issuedTime,
_license.expirationTime,
_license.affiliate);
_mint(_assignee, newLicenseId);
return newLicenseId;
}
function _handleAffiliate(
address _affiliate,
uint256 _productId,
uint256 _licenseId,
uint256 _purchaseAmount)
internal
{
uint256 affiliateCut = affiliateProgram.cutFor(
_affiliate,
_productId,
_licenseId,
_purchaseAmount);
if(affiliateCut > 0) {
require(affiliateCut < _purchaseAmount);
affiliateProgram.credit.value(affiliateCut)(_affiliate, _licenseId);
}
}
function _performRenewal(uint256 _tokenId, uint256 _numCycles) internal {
// You cannot renew a non-expiring license
// ... but in what scenario can this happen?
// require(licenses[_tokenId].expirationTime != 0);
uint256 productId = licenseProductId(_tokenId);
// If our expiration is in the future, renewing adds time to that future expiration
// If our expiration has passed already, then we use `now` as the base.
uint256 renewalBaseTime = Math.max256(now, licenses[_tokenId].expirationTime);
// We assume that the payment has been validated outside of this function
uint256 newExpirationTime = renewalBaseTime.add(intervalOf(productId).mul(_numCycles));
licenses[_tokenId].expirationTime = newExpirationTime;
LicenseRenewal(
ownerOf(_tokenId),
msg.sender,
_tokenId,
productId,
newExpirationTime
);
}
function _affiliateProgramIsActive() internal view returns (bool) {
return
affiliateProgram != address(0) &&
affiliateProgram.storeAddress() == address(this) &&
!affiliateProgram.paused();
}
/** executives **/
function setAffiliateProgramAddress(address _address) external onlyCEO {
AffiliateProgram candidateContract = AffiliateProgram(_address);
require(candidateContract.isAffiliateProgram());
affiliateProgram = candidateContract;
}
function setRenewalsCreditAffiliatesFor(uint256 _newTime) external onlyCEO {
renewalsCreditAffiliatesFor = _newTime;
}
function createPromotionalPurchase(
uint256 _productId,
uint256 _numCycles,
address _assignee,
uint256 _attributes
)
external
onlyCEOOrCOO
whenNotPaused
returns (uint256)
{
return _performPurchase(
_productId,
_numCycles,
_assignee,
_attributes,
address(0));
}
function createPromotionalRenewal(
uint256 _tokenId,
uint256 _numCycles
)
external
onlyCEOOrCOO
whenNotPaused
{
uint256 productId = licenseProductId(_tokenId);
_requireRenewableProduct(productId);
return _performRenewal(_tokenId, _numCycles);
}
/** anyone **/
/**
* @notice Makes a purchase of a product.
* @dev Requires that the value sent is exactly the price of the product
* @param _productId - the product to purchase
* @param _numCycles - the number of cycles being purchased. This number should be `1` for non-subscription products and the number of cycles for subscriptions.
* @param _assignee - the address to assign the purchase to (doesn't have to be msg.sender)
* @param _affiliate - the address to of the affiliate - use address(0) if none
*/
function purchase(
uint256 _productId,
uint256 _numCycles,
address _assignee,
address _affiliate
)
external
payable
whenNotPaused
returns (uint256)
{
require(_productId != 0);
require(_numCycles != 0);
require(_assignee != address(0));
// msg.value can be zero: free products are supported
// Don't bother dealing with excess payments. Ensure the price paid is
// accurate. No more, no less.
require(msg.value == costForProductCycles(_productId, _numCycles));
// Non-subscription products should send a _numCycle of 1 -- you can't buy a
// multiple quantity of a non-subscription product with this function
if(!isSubscriptionProduct(_productId)) {
require(_numCycles == 1);
}
// this can, of course, be gamed by malicious miners. But it's adequate for our application
// Feel free to add your own strategies for product attributes
// solium-disable-next-line security/no-block-members, zeppelin/no-arithmetic-operations
uint256 attributes = uint256(keccak256(block.blockhash(block.number-1)))^_productId^(uint256(_assignee));
uint256 licenseId = _performPurchase(
_productId,
_numCycles,
_assignee,
attributes,
_affiliate);
if(
priceOf(_productId) > 0 &&
_affiliate != address(0) &&
_affiliateProgramIsActive()
) {
_handleAffiliate(
_affiliate,
_productId,
licenseId,
msg.value);
}
return licenseId;
}
/**
* @notice Renews a subscription
*/
function renew(
uint256 _tokenId,
uint256 _numCycles
)
external
payable
whenNotPaused
{
require(_numCycles != 0);
require(ownerOf(_tokenId) != address(0));
uint256 productId = licenseProductId(_tokenId);
_requireRenewableProduct(productId);
// No excess payments. Ensure the price paid is exactly accurate. No more,
// no less.
uint256 renewalCost = costForProductCycles(productId, _numCycles);
require(msg.value == renewalCost);
_performRenewal(_tokenId, _numCycles);
if(
renewalCost > 0 &&
licenseAffiliate(_tokenId) != address(0) &&
_affiliateProgramIsActive() &&
licenseIssuedTime(_tokenId).add(renewalsCreditAffiliatesFor) > now
) {
_handleAffiliate(
licenseAffiliate(_tokenId),
productId,
_tokenId,
msg.value);
}
}
}
contract LicenseCore is LicenseSale {
address public newContractAddress;
function LicenseCore() public {
paused = true;
ceoAddress = msg.sender;
cooAddress = msg.sender;
cfoAddress = msg.sender;
withdrawalAddress = msg.sender;
}
function setNewAddress(address _v2Address) external onlyCEO whenPaused {
newContractAddress = _v2Address;
ContractUpgrade(_v2Address);
}
function() external {
assert(false);
}
function unpause() public onlyCEO whenPaused {
require(newContractAddress == address(0));
super.unpause();
}
}
library Strings {
// via https://github.com/oraclize/ethereum-api/blob/master/oraclizeAPI_0.5.sol
function strConcat(string _a, string _b, string _c, string _d, string _e) internal pure returns (string) {
bytes memory _ba = bytes(_a);
bytes memory _bb = bytes(_b);
bytes memory _bc = bytes(_c);
bytes memory _bd = bytes(_d);
bytes memory _be = bytes(_e);
string memory abcde = new string(_ba.length + _bb.length + _bc.length + _bd.length + _be.length);
bytes memory babcde = bytes(abcde);
uint k = 0;
for (uint i = 0; i < _ba.length; i++) babcde[k++] = _ba[i];
for (i = 0; i < _bb.length; i++) babcde[k++] = _bb[i];
for (i = 0; i < _bc.length; i++) babcde[k++] = _bc[i];
for (i = 0; i < _bd.length; i++) babcde[k++] = _bd[i];
for (i = 0; i < _be.length; i++) babcde[k++] = _be[i];
return string(babcde);
}
function strConcat(string _a, string _b, string _c, string _d) internal pure returns (string) {
return strConcat(_a, _b, _c, _d, "");
}
function strConcat(string _a, string _b, string _c) internal pure returns (string) {
return strConcat(_a, _b, _c, "", "");
}
function strConcat(string _a, string _b) internal pure returns (string) {
return strConcat(_a, _b, "", "", "");
}
function uint2str(uint i) internal pure returns (string) {
if (i == 0) return "0";
uint j = i;
uint len;
while (j != 0){
len++;
j /= 10;
}
bytes memory bstr = new bytes(len);
uint k = len - 1;
while (i != 0){
bstr[k--] = byte(48 + i % 10);
i /= 10;
}
return string(bstr);
}
} | * @notice Internal function to clear current approval of a given token ID @param _tokenId uint256 ID of the token to be transferred/ | function _clearApproval(address _owner, uint256 _tokenId) private {
require(ownerOf(_tokenId) == _owner);
tokenApprovals[_tokenId] = 0;
Approval(_owner, 0, _tokenId);
}
| 478,495 | [
1,
3061,
445,
358,
2424,
783,
23556,
434,
279,
864,
1147,
1599,
225,
389,
2316,
548,
2254,
5034,
1599,
434,
326,
1147,
358,
506,
906,
4193,
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
] | [
1,
1,
1,
1,
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,
225,
445,
389,
8507,
23461,
12,
2867,
389,
8443,
16,
2254,
5034,
389,
2316,
548,
13,
3238,
288,
203,
565,
2583,
12,
8443,
951,
24899,
2316,
548,
13,
422,
389,
8443,
1769,
203,
565,
1147,
12053,
4524,
63,
67,
2316,
548,
65,
273,
374,
31,
203,
565,
1716,
685,
1125,
24899,
8443,
16,
374,
16,
389,
2316,
548,
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
] |
./full_match/80001/0x3240CbA63FFe32D784173d41844eF8142E001e49/sources/contracts/airdrop/Airdrop.sol | @dev Get the base URI for the contract. | function _baseURI() internal pure override returns (string memory) {
return "";
}
| 5,617,533 | [
1,
967,
326,
1026,
3699,
364,
326,
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,
0,
0,
0,
0,
0,
0,
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,
389,
1969,
3098,
1435,
2713,
16618,
3849,
1135,
261,
1080,
3778,
13,
288,
203,
3639,
327,
1408,
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
] |
./full_match/3/0x38eFa9e8140AfE77b4760376735F0fcd076d7Da8/sources/browser/contracts/1_Storage.sol | * @dev Store value in variable @param num value to store/ | function store(uint256 num) public onlyOwner{
number = num;
}
address owner=0x9E2139c1c7ff6206eEC4984E896d636d4Bd133E7;
| 8,108,729 | [
1,
2257,
460,
316,
2190,
225,
818,
460,
358,
1707,
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,
1707,
12,
11890,
5034,
818,
13,
1071,
1338,
5541,
95,
203,
3639,
1300,
273,
818,
31,
203,
565,
289,
203,
565,
1758,
3410,
33,
20,
92,
29,
41,
22,
24347,
71,
21,
71,
27,
1403,
26,
3462,
26,
73,
7228,
7616,
5193,
41,
6675,
26,
72,
4449,
26,
72,
24,
38,
72,
28615,
41,
27,
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
] |
./partial_match/1/0xCD3b1E16DA80337Bf3BCCCA53a93889bC81F4A96/sources/contracts/Inscription.sol | This contract is extended from ERC20 | contract Inscription is ERC20 {
using Logarithm for int256;
address payable public inscriptionFactory;
constructor(
address payable _inscriptionFactory
) ERC20(_name, _tick) {
require(_cap >= _limitPerMint, "Limit per mint exceed cap");
cap = _cap;
limitPerMint = _limitPerMint;
inscriptionId = _inscriptionId;
maxMintSize = _maxMintSize;
freezeTime = _freezeTime;
onlyContractAddress = _onlyContractAddress;
onlyMinQuantity = _onlyMinQuantity;
baseFee = _baseFee;
fundingCommission = _fundingCommission;
crowdFundingRate = _crowdFundingRate;
crowdfundingAddress = _crowdFundingAddress;
inscriptionFactory = _inscriptionFactory;
}
function mint(address _to) payable public {
require(totalSupply() + limitPerMint <= cap, "Touched cap");
require(onlyContractAddress == address(0x0) || ICommonToken(onlyContractAddress).balanceOf(msg.sender) >= onlyMinQuantity, "You don't have required assets");
if(lastMintTimestamp[msg.sender] + freezeTime > block.timestamp) {
lastMintFee[msg.sender] = lastMintFee[msg.sender] == 0 ? baseFee : lastMintFee[msg.sender] * 2;
if(crowdFundingRate > 0) {
require(msg.value >= crowdFundingRate + lastMintFee[msg.sender], "Send some ETH as fee and crowdfunding");
_dispatchFunding(crowdFundingRate);
}
if(crowdFundingRate > 0) {
require(msg.value >= crowdFundingRate, "Send some ETH as crowdfunding");
_dispatchFunding(msg.value);
}
lastMintTimestamp[msg.sender] = block.timestamp;
}
}
function mint(address _to) payable public {
require(totalSupply() + limitPerMint <= cap, "Touched cap");
require(onlyContractAddress == address(0x0) || ICommonToken(onlyContractAddress).balanceOf(msg.sender) >= onlyMinQuantity, "You don't have required assets");
if(lastMintTimestamp[msg.sender] + freezeTime > block.timestamp) {
lastMintFee[msg.sender] = lastMintFee[msg.sender] == 0 ? baseFee : lastMintFee[msg.sender] * 2;
if(crowdFundingRate > 0) {
require(msg.value >= crowdFundingRate + lastMintFee[msg.sender], "Send some ETH as fee and crowdfunding");
_dispatchFunding(crowdFundingRate);
}
if(crowdFundingRate > 0) {
require(msg.value >= crowdFundingRate, "Send some ETH as crowdfunding");
_dispatchFunding(msg.value);
}
lastMintTimestamp[msg.sender] = block.timestamp;
}
}
function mint(address _to) payable public {
require(totalSupply() + limitPerMint <= cap, "Touched cap");
require(onlyContractAddress == address(0x0) || ICommonToken(onlyContractAddress).balanceOf(msg.sender) >= onlyMinQuantity, "You don't have required assets");
if(lastMintTimestamp[msg.sender] + freezeTime > block.timestamp) {
lastMintFee[msg.sender] = lastMintFee[msg.sender] == 0 ? baseFee : lastMintFee[msg.sender] * 2;
if(crowdFundingRate > 0) {
require(msg.value >= crowdFundingRate + lastMintFee[msg.sender], "Send some ETH as fee and crowdfunding");
_dispatchFunding(crowdFundingRate);
}
if(crowdFundingRate > 0) {
require(msg.value >= crowdFundingRate, "Send some ETH as crowdfunding");
_dispatchFunding(msg.value);
}
lastMintTimestamp[msg.sender] = block.timestamp;
}
}
if(msg.value - crowdFundingRate > 0) TransferHelper.safeTransferETH(inscriptionFactory, msg.value - crowdFundingRate);
} else {
function mint(address _to) payable public {
require(totalSupply() + limitPerMint <= cap, "Touched cap");
require(onlyContractAddress == address(0x0) || ICommonToken(onlyContractAddress).balanceOf(msg.sender) >= onlyMinQuantity, "You don't have required assets");
if(lastMintTimestamp[msg.sender] + freezeTime > block.timestamp) {
lastMintFee[msg.sender] = lastMintFee[msg.sender] == 0 ? baseFee : lastMintFee[msg.sender] * 2;
if(crowdFundingRate > 0) {
require(msg.value >= crowdFundingRate + lastMintFee[msg.sender], "Send some ETH as fee and crowdfunding");
_dispatchFunding(crowdFundingRate);
}
if(crowdFundingRate > 0) {
require(msg.value >= crowdFundingRate, "Send some ETH as crowdfunding");
_dispatchFunding(msg.value);
}
lastMintTimestamp[msg.sender] = block.timestamp;
}
}
lastMintFee[msg.sender] = 0;
_mint(_to, limitPerMint);
function batchMint(address _to, uint256 _num) payable public {
require(_num <= maxMintSize, "exceed max mint size");
require(totalSupply() + _num * limitPerMint <= cap, "Touch cap");
require(freezeTime == 0, "Batch mint only for non-frozen token");
require(onlyContractAddress == address(0x0) || ICommonToken(onlyContractAddress).balanceOf(msg.sender) >= onlyMinQuantity, "You don't have required assets");
if(crowdFundingRate > 0) {
require(msg.value >= crowdFundingRate * _num, "Crowdfunding ETH not enough");
_dispatchFunding(msg.value);
}
for(uint256 i = 0; i < _num; i++) _mint(_to, limitPerMint);
}
function batchMint(address _to, uint256 _num) payable public {
require(_num <= maxMintSize, "exceed max mint size");
require(totalSupply() + _num * limitPerMint <= cap, "Touch cap");
require(freezeTime == 0, "Batch mint only for non-frozen token");
require(onlyContractAddress == address(0x0) || ICommonToken(onlyContractAddress).balanceOf(msg.sender) >= onlyMinQuantity, "You don't have required assets");
if(crowdFundingRate > 0) {
require(msg.value >= crowdFundingRate * _num, "Crowdfunding ETH not enough");
_dispatchFunding(msg.value);
}
for(uint256 i = 0; i < _num; i++) _mint(_to, limitPerMint);
}
function getMintFee(address _addr) public view returns(uint256 mintedTimes, uint256 nextMintFee) {
if(lastMintTimestamp[_addr] + freezeTime > block.timestamp) {
int256 scale = 1e18;
int256 halfScale = 5e17;
nextMintFee = lastMintFee[_addr] == 0 ? baseFee : lastMintFee[_addr] * 2;
mintedTimes = uint256((Logarithm.log2(int256(nextMintFee / baseFee) * scale, scale, halfScale) + 1) / scale) + 1;
}
}
function getMintFee(address _addr) public view returns(uint256 mintedTimes, uint256 nextMintFee) {
if(lastMintTimestamp[_addr] + freezeTime > block.timestamp) {
int256 scale = 1e18;
int256 halfScale = 5e17;
nextMintFee = lastMintFee[_addr] == 0 ? baseFee : lastMintFee[_addr] * 2;
mintedTimes = uint256((Logarithm.log2(int256(nextMintFee / baseFee) * scale, scale, halfScale) + 1) / scale) + 1;
}
}
function _dispatchFunding(uint256 _amount) private {
uint256 commission = _amount * fundingCommission / 10000;
TransferHelper.safeTransferETH(crowdfundingAddress, _amount - commission);
if(commission > 0) TransferHelper.safeTransferETH(inscriptionFactory, commission);
}
}
| 15,670,917 | [
1,
2503,
6835,
353,
7021,
628,
4232,
39,
3462,
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,
16351,
657,
3100,
353,
4232,
39,
3462,
288,
203,
565,
1450,
1827,
31249,
364,
509,
5034,
31,
203,
565,
1758,
8843,
429,
1071,
316,
3100,
1733,
31,
203,
203,
203,
565,
3885,
12,
203,
3639,
1758,
8843,
429,
389,
267,
3100,
1733,
203,
565,
262,
4232,
39,
3462,
24899,
529,
16,
389,
6470,
13,
288,
203,
3639,
2583,
24899,
5909,
1545,
389,
3595,
2173,
49,
474,
16,
315,
3039,
1534,
312,
474,
9943,
3523,
8863,
203,
3639,
3523,
273,
389,
5909,
31,
203,
3639,
1800,
2173,
49,
474,
273,
389,
3595,
2173,
49,
474,
31,
203,
3639,
316,
3100,
548,
273,
389,
267,
3100,
548,
31,
203,
3639,
943,
49,
474,
1225,
273,
389,
1896,
49,
474,
1225,
31,
203,
3639,
16684,
950,
273,
389,
29631,
950,
31,
203,
3639,
1338,
8924,
1887,
273,
389,
3700,
8924,
1887,
31,
203,
3639,
1338,
2930,
12035,
273,
389,
3700,
2930,
12035,
31,
203,
3639,
1026,
14667,
273,
389,
1969,
14667,
31,
203,
3639,
22058,
799,
3951,
273,
389,
74,
14351,
799,
3951,
31,
203,
3639,
276,
492,
72,
42,
14351,
4727,
273,
389,
71,
492,
72,
42,
14351,
4727,
31,
203,
3639,
276,
492,
2180,
14351,
1887,
273,
389,
71,
492,
72,
42,
14351,
1887,
31,
203,
3639,
316,
3100,
1733,
273,
389,
267,
3100,
1733,
31,
203,
565,
289,
203,
203,
565,
445,
312,
474,
12,
2867,
389,
869,
13,
8843,
429,
1071,
288,
203,
3639,
2583,
12,
4963,
3088,
1283,
1435,
397,
1800,
2173,
49,
474,
1648,
3523,
16,
315,
774,
19370,
3523,
8863,
2
] |
./full_match/1/0x2445F5dD31df8e7b0bfBFacFD7357e58a51D147d/sources/Users/tudorg/Desktop/projects/DeBa/contracts/deba/FeeRewardForwarder.sol | Is always the RewardPool.rewardToken()
| address public targetToken; | 4,870,286 | [
1,
2520,
3712,
326,
534,
359,
1060,
2864,
18,
266,
2913,
1345,
1435,
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,
1758,
1071,
1018,
1345,
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
] |
./partial_match/4/0xF857F36B15F4aDCc08B300c9b72b6C8a7f6F6b76/sources/SimplePOS.sol | you don't really need this if you are using the approve/transferFrom method because you control the flow of tokens by approving this contract address, but to make the contract an extensible example for later user I'll add thisthe signature must be validmake sure it's the subscribernextValidTimestamp should be a timestamp that will neverbe reached during the brief window human existence | function cancelSubscription(
)
external
returns (bool success)
{
bytes32 subscriptionHash = getSubscriptionHash(
from, to, tokenAddress, tokenAmount, periodSeconds, gasPrice, nonce
);
address signer = getSubscriptionSigner(subscriptionHash, signature);
require(signer == from, "Invalid Signature for subscription cancellation");
require(from == msg.sender, 'msg.sender is not the subscriber');
nextValidTimestamp[subscriptionHash]=uint256(-1);
emit CancelSubscription(
from, to, tokenAddress, tokenAmount, periodSeconds, gasPrice, nonce
);
return true;
}
| 8,529,108 | [
1,
19940,
2727,
1404,
8654,
1608,
333,
309,
1846,
854,
1450,
326,
6617,
537,
19,
13866,
1265,
707,
2724,
1846,
3325,
326,
4693,
434,
2430,
635,
6617,
6282,
333,
6835,
1758,
16,
1496,
358,
1221,
326,
6835,
392,
1110,
773,
1523,
3454,
364,
5137,
729,
467,
5614,
527,
333,
5787,
3372,
1297,
506,
923,
6540,
3071,
518,
1807,
326,
9467,
4285,
1556,
4921,
1410,
506,
279,
2858,
716,
903,
5903,
2196,
8675,
4982,
326,
324,
17802,
2742,
8672,
15782,
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
] | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
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
] | [
1,
565,
445,
3755,
6663,
12,
203,
565,
262,
203,
3639,
3903,
203,
3639,
1135,
261,
6430,
2216,
13,
203,
565,
288,
203,
3639,
1731,
1578,
4915,
2310,
273,
7040,
3100,
2310,
12,
203,
5411,
628,
16,
358,
16,
1147,
1887,
16,
1147,
6275,
16,
3879,
6762,
16,
16189,
5147,
16,
7448,
203,
3639,
11272,
203,
3639,
1758,
10363,
273,
7040,
3100,
15647,
12,
11185,
2310,
16,
3372,
1769,
203,
203,
3639,
2583,
12,
2977,
264,
422,
628,
16,
315,
1941,
9249,
364,
4915,
7272,
8863,
203,
203,
3639,
2583,
12,
2080,
422,
1234,
18,
15330,
16,
296,
3576,
18,
15330,
353,
486,
326,
9467,
8284,
203,
203,
3639,
1024,
1556,
4921,
63,
11185,
2310,
65,
33,
11890,
5034,
19236,
21,
1769,
203,
203,
3639,
3626,
10347,
6663,
12,
203,
5411,
628,
16,
358,
16,
1147,
1887,
16,
1147,
6275,
16,
3879,
6762,
16,
16189,
5147,
16,
7448,
203,
3639,
11272,
203,
203,
3639,
327,
638,
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
] |
./partial_match/1/0xC8Eb057f5e38F71FE42a9E59d51ac60926Ec933D/sources/JarvisRewardToken.sol | * @title Pausable token @dev ERC20 modified with pausable transfers./ | contract ERC20Pausable is Initializable, ERC20, 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 increaseAllowance(address spender, uint256 addedValue)
public
whenNotPaused
returns (bool success)
{
return super.increaseAllowance(spender, addedValue);
}
function decreaseAllowance(address spender, uint256 subtractedValue)
public
whenNotPaused
returns (bool success)
{
return super.decreaseAllowance(spender, subtractedValue);
}
uint256[50] private ______gap;
}
| 2,697,554 | [
1,
16507,
16665,
1147,
225,
4232,
39,
3462,
4358,
598,
6790,
16665,
29375,
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,
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,
4232,
39,
3462,
16507,
16665,
353,
10188,
6934,
16,
4232,
39,
3462,
16,
21800,
16665,
288,
203,
225,
445,
7412,
12,
2867,
358,
16,
2254,
5034,
460,
13,
203,
565,
1071,
203,
565,
1347,
1248,
28590,
203,
565,
1135,
261,
6430,
13,
203,
203,
225,
288,
203,
565,
327,
2240,
18,
13866,
12,
869,
16,
460,
1769,
203,
225,
289,
203,
203,
225,
445,
7412,
1265,
12,
203,
565,
1758,
628,
16,
203,
565,
1758,
358,
16,
203,
565,
2254,
5034,
460,
203,
225,
262,
1071,
1347,
1248,
28590,
1135,
261,
6430,
13,
288,
203,
565,
327,
2240,
18,
13866,
1265,
12,
2080,
16,
358,
16,
460,
1769,
203,
225,
289,
203,
203,
225,
445,
6617,
537,
12,
2867,
17571,
264,
16,
2254,
5034,
460,
13,
203,
565,
1071,
203,
565,
1347,
1248,
28590,
203,
565,
1135,
261,
6430,
13,
203,
225,
288,
203,
565,
327,
2240,
18,
12908,
537,
12,
87,
1302,
264,
16,
460,
1769,
203,
225,
289,
203,
203,
225,
445,
10929,
7009,
1359,
12,
2867,
17571,
264,
16,
2254,
5034,
3096,
620,
13,
203,
565,
1071,
203,
565,
1347,
1248,
28590,
203,
565,
1135,
261,
6430,
2216,
13,
203,
225,
288,
203,
565,
327,
2240,
18,
267,
11908,
7009,
1359,
12,
87,
1302,
264,
16,
3096,
620,
1769,
203,
225,
289,
203,
203,
225,
445,
20467,
7009,
1359,
12,
2867,
17571,
264,
16,
2254,
5034,
10418,
329,
620,
13,
203,
565,
1071,
203,
565,
1347,
1248,
28590,
203,
565,
1135,
261,
6430,
2216,
13,
203,
225,
288,
203,
565,
2
] |
/**
*Submitted for verification at Etherscan.io on 2021-12-07
*/
// Sources flattened with hardhat v2.1.1 https://hardhat.org
// File contracts/Interfaces/IBorrowerOperations.sol
// SPDX-License-Identifier: MIT
pragma solidity 0.6.11;
// Common interface for the Trove Manager.
interface IBorrowerOperations {
// --- Events ---
event TroveManagerAddressChanged(address _newTroveManagerAddress);
event ActivePoolAddressChanged(address _activePoolAddress);
event DefaultPoolAddressChanged(address _defaultPoolAddress);
event StabilityPoolAddressChanged(address _stabilityPoolAddress);
event GasPoolAddressChanged(address _gasPoolAddress);
event CollSurplusPoolAddressChanged(address _collSurplusPoolAddress);
event PriceFeedAddressChanged(address _newPriceFeedAddress);
event SortedTrovesAddressChanged(address _sortedTrovesAddress);
event WETHTokenAddressChanged(address _wethTokenAddress);
event FeeAdminAddressChanged(address _feeAdminAddress);
event BorrowingFeePoolAddressChanged(address _borrowingFeePoolAddress);
event TroveCreated(address indexed _borrower, uint arrayIndex);
event TroveUpdated(address indexed _borrower, uint _debt, uint _coll, uint stake, uint8 operation);
event LUSDBorrowingFeePaid(address indexed _borrower, uint _LUSDFee);
// --- Functions ---
function setAddresses(
address _troveManagerAddress,
address _activePoolAddress,
address _defaultPoolAddress,
address _stabilityPoolAddress,
address _gasPoolAddress,
address _collSurplusPoolAddress,
address _priceFeedAddress,
address _sortedTrovesAddress,
address _lusdTokenAddress,
address _wethTokenAddress,
uint collDecimalAdjustment
) external;
function setBorrowingFeePoolAddress(address _borrowingFeePoolAddress) external;
function openTrove(uint _maxFee, uint _LUSDAmount, uint _WETHAmount, address _upperHint, address _lowerHint) external;
function addColl(uint _WETHAmount, address _upperHint, address _lowerHint) external;
function moveETHGainToTrove(address _user, uint _WETHAmount, address _upperHint, address _lowerHint) external;
function withdrawColl(uint _amount, address _upperHint, address _lowerHint) external;
function withdrawLUSD(uint _maxFee, uint _amount, address _upperHint, address _lowerHint) external;
function repayLUSD(uint _amount, address _upperHint, address _lowerHint) external;
function closeTrove() external;
function adjustTrove(uint _maxFee, uint _WETHAmount, uint _collWithdrawal, uint _debtChange, bool isDebtIncrease, address _upperHint, address _lowerHint) external;
function claimCollateral() external;
function getCompositeDebt(uint _debt) external pure returns (uint);
}
// File contracts/Interfaces/IPriceFeed.sol
interface IPriceFeed {
// --- Events ---
event LastGoodPriceUpdated(uint _lastGoodPrice);
// --- Function ---
function fetchPrice() external returns (uint);
}
// File contracts/Interfaces/ILiquityBase.sol
interface ILiquityBase {
function priceFeed() external view returns (IPriceFeed);
}
// File contracts/Interfaces/IStabilityPool.sol
/*
* The Stability Pool holds LUSD tokens deposited by Stability Pool depositors.
*
* When a trove is liquidated, then depending on system conditions, some of its LUSD debt gets offset with
* LUSD in the Stability Pool: that is, the offset debt evaporates, and an equal amount of LUSD tokens in the Stability Pool is burned.
*
* Thus, a liquidation causes each depositor to receive a LUSD loss, in proportion to their deposit as a share of total deposits.
* They also receive an ETH gain, as the ETH collateral of the liquidated trove is distributed among Stability depositors,
* in the same proportion.
*
* When a liquidation occurs, it depletes every deposit by the same fraction: for example, a liquidation that depletes 40%
* of the total LUSD in the Stability Pool, depletes 40% of each deposit.
*
* A deposit that has experienced a series of liquidations is termed a "compounded deposit": each liquidation depletes the deposit,
* multiplying it by some factor in range ]0,1[
*
* Please see the implementation spec in the proof document, which closely follows on from the compounded deposit / ETH gain derivations:
* https://github.com/liquity/liquity/blob/master/papers/Scalable_Reward_Distribution_with_Compounding_Stakes.pdf
*
* --- LQTY ISSUANCE TO STABILITY POOL DEPOSITORS ---
*
* An LQTY issuance event occurs at every deposit operation, and every liquidation.
*
* Each deposit is tagged with the address of the front end through which it was made.
*
* All deposits earn a share of the issued LQTY in proportion to the deposit as a share of total deposits. The LQTY earned
* by a given deposit, is split between the depositor and the front end through which the deposit was made, based on the front end's kickbackRate.
*
* Please see the system Readme for an overview:
* https://github.com/liquity/dev/blob/main/README.md#lqty-issuance-to-stability-providers
*/
interface IStabilityPool {
// --- Events ---
event StabilityPoolETHBalanceUpdated(uint _newBalance);
event StabilityPoolLUSDBalanceUpdated(uint _newBalance);
event BorrowerOperationsAddressChanged(address _newBorrowerOperationsAddress);
event TroveManagerAddressChanged(address _newTroveManagerAddress);
event ActivePoolAddressChanged(address _newActivePoolAddress);
event DefaultPoolAddressChanged(address _newDefaultPoolAddress);
event LUSDTokenAddressChanged(address _newLUSDTokenAddress);
event CollAddressChanged(address _collTokenAddress);
event SortedTrovesAddressChanged(address _newSortedTrovesAddress);
event PriceFeedAddressChanged(address _newPriceFeedAddress);
event CommunityIssuanceAddressChanged(address _newCommunityIssuanceAddress);
event P_Updated(uint _P);
event S_Updated(uint _S, uint128 _epoch, uint128 _scale);
event G_Updated(uint _G, uint128 _epoch, uint128 _scale);
event EpochUpdated(uint128 _currentEpoch);
event ScaleUpdated(uint128 _currentScale);
event FrontEndRegistered(address indexed _frontEnd, uint _kickbackRate);
event FrontEndTagSet(address indexed _depositor, address indexed _frontEnd);
event DepositSnapshotUpdated(address indexed _depositor, uint _P, uint _S, uint _G);
event FrontEndSnapshotUpdated(address indexed _frontEnd, uint _P, uint _G);
event UserDepositChanged(address indexed _depositor, uint _newDeposit);
event FrontEndStakeChanged(address indexed _frontEnd, uint _newFrontEndStake, address _depositor);
event ETHGainWithdrawn(address indexed _depositor, uint _ETH, uint _LUSDLoss);
event LQTYPaidToDepositor(address indexed _depositor, uint _LQTY);
event LQTYPaidToFrontEnd(address indexed _frontEnd, uint _LQTY);
event EtherSent(address _to, uint _amount);
// --- Functions ---
/*
* Called only once on init, to set addresses of other Liquity contracts
* Callable only by owner, renounces ownership at the end
*/
function setAddresses(
address _borrowerOperationsAddress,
address _troveManagerAddress,
address _activePoolAddress,
address _LUSDTokenAddress,
address _sortedTrovesAddress,
address _priceFeedAddress,
address _communityIssuanceAddress,
address _collTokenAddress,
uint _collDecimalAdjustment
) external;
/*
* Initial checks:
* - Frontend is registered or zero address
* - Sender is not a registered frontend
* - _amount is not zero
* ---
* - Triggers a LQTY issuance, based on time passed since the last issuance. The LQTY issuance is shared between *all* depositors and front ends
* - Tags the deposit with the provided front end tag param, if it's a new deposit
* - Sends depositor's accumulated gains (LQTY, ETH) to depositor
* - Sends the tagged front end's accumulated LQTY gains to the tagged front end
* - Increases deposit and tagged front end's stake, and takes new snapshots for each.
*/
function provideToSP(uint _amount, address _frontEndTag) external;
/*
* Initial checks:
* - _amount is zero or there are no under collateralized troves left in the system
* - User has a non zero deposit
* ---
* - Triggers a LQTY issuance, based on time passed since the last issuance. The LQTY issuance is shared between *all* depositors and front ends
* - Removes the deposit's front end tag if it is a full withdrawal
* - Sends all depositor's accumulated gains (LQTY, ETH) to depositor
* - Sends the tagged front end's accumulated LQTY gains to the tagged front end
* - Decreases deposit and tagged front end's stake, and takes new snapshots for each.
*
* If _amount > userDeposit, the user withdraws all of their compounded deposit.
*/
function withdrawFromSP(uint _amount) external;
/*
* Initial checks:
* - User has a non zero deposit
* - User has an open trove
* - User has some ETH gain
* ---
* - Triggers a LQTY issuance, based on time passed since the last issuance. The LQTY issuance is shared between *all* depositors and front ends
* - Sends all depositor's LQTY gain to depositor
* - Sends all tagged front end's LQTY gain to the tagged front end
* - Transfers the depositor's entire ETH gain from the Stability Pool to the caller's trove
* - Leaves their compounded deposit in the Stability Pool
* - Updates snapshots for deposit and tagged front end stake
*/
function withdrawETHGainToTrove(address _upperHint, address _lowerHint) external;
/*
* Initial checks:
* - Frontend (sender) not already registered
* - User (sender) has no deposit
* - _kickbackRate is in the range [0, 100%]
* ---
* Front end makes a one-time selection of kickback rate upon registering
*/
function registerFrontEnd(uint _kickbackRate) external;
/*
* Initial checks:
* - Caller is TroveManager
* ---
* Cancels out the specified debt against the LUSD contained in the Stability Pool (as far as possible)
* and transfers the Trove's ETH collateral from ActivePool to StabilityPool.
* Only called by liquidation functions in the TroveManager.
*/
function offset(uint _debt, uint _coll) external;
/*
* Returns the total amount of ETH held by the pool, accounted in an internal variable instead of `balance`,
* to exclude edge cases like ETH received from a self-destruct.
*/
function getETH() external view returns (uint);
/*
* Returns LUSD held in the pool. Changes when users deposit/withdraw, and when Trove debt is offset.
*/
function getTotalLUSDDeposits() external view returns (uint);
/*
* Calculates the ETH gain earned by the deposit since its last snapshots were taken.
*/
function getDepositorETHGain(address _depositor) external view returns (uint);
/*
* Calculate the LQTY gain earned by a deposit since its last snapshots were taken.
* If not tagged with a front end, the depositor gets a 100% cut of what their deposit earned.
* Otherwise, their cut of the deposit's earnings is equal to the kickbackRate, set by the front end through
* which they made their deposit.
*/
function getDepositorLQTYGain(address _depositor) external view returns (uint);
/*
* Return the LQTY gain earned by the front end.
*/
function getFrontEndLQTYGain(address _frontEnd) external view returns (uint);
/*
* Return the user's compounded deposit.
*/
function getCompoundedLUSDDeposit(address _depositor) external view returns (uint);
/*
* Return the front end's compounded stake.
*
* The front end's compounded stake is equal to the sum of its depositors' compounded deposits.
*/
function getCompoundedFrontEndStake(address _frontEnd) external view returns (uint);
function depositColl(uint _amount) external;
/*
* Fallback function
* Only callable by Active Pool, it just accounts for ETH received
* receive() external payable;
*/
}
// File contracts/Dependencies/IERC20.sol
/**
* Based on the OpenZeppelin IER20 interface:
* https://github.com/OpenZeppelin/openzeppelin-contracts/blob/master/contracts/token/ERC20/IERC20.sol
*
* @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);
function increaseAllowance(address spender, uint256 addedValue) external returns (bool);
function decreaseAllowance(address spender, uint256 subtractedValue) external returns (bool);
/**
* @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);
function name() external view returns (string memory);
function symbol() external view returns (string memory);
function decimals() external view returns (uint8);
/**
* @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/Dependencies/IERC2612.sol
/**
* @dev Interface of the ERC2612 standard as defined in the EIP.
*
* Adds the {permit} method, which can be used to change one's
* {IERC20-allowance} without having to send a transaction, by signing a
* message. This allows users to spend tokens without having to hold Ether.
*
* See https://eips.ethereum.org/EIPS/eip-2612.
*
* Code adapted from https://github.com/OpenZeppelin/openzeppelin-contracts/pull/2237/
*/
interface IERC2612 {
/**
* @dev Sets `amount` as the allowance of `spender` over `owner`'s tokens,
* given `owner`'s signed approval.
*
* IMPORTANT: The same issues {IERC20-approve} has related to transaction
* ordering also apply here.
*
* Emits an {Approval} event.
*
* Requirements:
*
* - `owner` cannot be the zero address.
* - `spender` cannot be the zero address.
* - `deadline` must be a timestamp in the future.
* - `v`, `r` and `s` must be a valid `secp256k1` signature from `owner`
* over the EIP712-formatted function arguments.
* - the signature must use ``owner``'s current nonce (see {nonces}).
*
* For more information on the signature format, see the
* https://eips.ethereum.org/EIPS/eip-2612#specification[relevant EIP
* section].
*/
function permit(address owner, address spender, uint256 amount,
uint256 deadline, uint8 v, bytes32 r, bytes32 s) external;
/**
* @dev Returns the current ERC2612 nonce for `owner`. This value must be
* included whenever a signature is generated for {permit}.
*
* Every successful call to {permit} increases `owner`'s nonce by one. This
* prevents a signature from being used multiple times.
*
* `owner` can limit the time a Permit is valid for by setting `deadline` to
* a value in the near future. The deadline argument can be set to uint(-1) to
* create Permits that effectively never expire.
*/
function nonces(address owner) external view returns (uint256);
function version() external view returns (string memory);
function permitTypeHash() external view returns (bytes32);
function domainSeparator() external view returns (bytes32);
}
// File contracts/Interfaces/ILUSDToken.sol
interface ILUSDToken is IERC20, IERC2612 {
// --- Events ---
event LUSDTokenBalanceUpdated(address _user, uint256 _amount);
event CollateralAdded(
address _troveManagerAddress,
address _stabilityPoolAddress,
address _borrowerOperationsAddress
);
event ColllateralRemoved(
address _troveManagerAddress,
address _stabilityPoolAddress,
address _borrowerOperationsAddress
);
// --- Functions ---
function addAddressesForColl(
address _troveManagerAddress,
address _stabilityPoolAddress,
address _borrowerOperationsAddress
) external;
function removeAddressesForColl(
address _troveManagerAddress,
address _stabilityPoolAddress,
address _borrowerOperationsAddress
) external;
function mint(address _account, uint256 _amount) external;
function burn(address _account, uint256 _amount) external;
function sendToPool(
address _sender,
address poolAddress,
uint256 _amount
) external;
function returnFromPool(
address poolAddress,
address user,
uint256 _amount
) external;
}
// File contracts/Interfaces/ILQTYToken.sol
interface ILQTYToken is IERC20, IERC2612 {
// --- Events ---
event CommunityIssuanceAddressSet(address _communityIssuanceAddress);
event LockupContractFactoryAddressSet(address _lockupContractFactoryAddress);
// --- Functions ---
function getDeploymentStartTime() external view returns (uint256);
function getLpRewardsEntitlement() external view returns (uint256);
}
// File contracts/Interfaces/ITroveManager.sol
// Common interface for the Trove Manager.
interface ITroveManager is ILiquityBase {
// --- Events ---
event BorrowerOperationsAddressChanged(address _newBorrowerOperationsAddress);
event PriceFeedAddressChanged(address _newPriceFeedAddress);
event LUSDTokenAddressChanged(address _newLUSDTokenAddress);
event ActivePoolAddressChanged(address _activePoolAddress);
event DefaultPoolAddressChanged(address _defaultPoolAddress);
event StabilityPoolAddressChanged(address _stabilityPoolAddress);
event GasPoolAddressChanged(address _gasPoolAddress);
event CollSurplusPoolAddressChanged(address _collSurplusPoolAddress);
event SortedTrovesAddressChanged(address _sortedTrovesAddress);
event LQTYTokenAddressChanged(address _lqtyTokenAddress);
event RedemptionFeePoolParamsChanged(address _redemptionFeePoolAddress, uint _redemptionFeePoolRate);
event FeeAdminAddressChanged(address _feeAdminAddress);
event Liquidation(uint _liquidatedDebt, uint _liquidatedColl, uint _collGasCompensation, uint _LUSDGasCompensation);
event Redemption(uint _attemptedLUSDAmount, uint _actualLUSDAmount, uint _ETHSent, uint _ETHFee);
event TroveUpdated(address indexed _borrower, uint _debt, uint _coll, uint stake, uint8 operation);
event TroveLiquidated(address indexed _borrower, uint _debt, uint _coll, uint8 operation);
event BaseRateUpdated(uint _baseRate);
event LastFeeOpTimeUpdated(uint _lastFeeOpTime);
event TotalStakesUpdated(uint _newTotalStakes);
event SystemSnapshotsUpdated(uint _totalStakesSnapshot, uint _totalCollateralSnapshot);
event LTermsUpdated(uint _L_ETH, uint _L_LUSDDebt);
event TroveSnapshotsUpdated(uint _L_ETH, uint _L_LUSDDebt);
event TroveIndexUpdated(address _borrower, uint _newIndex);
// --- Functions ---
function setAddresses(
address _borrowerOperationsAddress,
address _activePoolAddress,
address _defaultPoolAddress,
address _stabilityPoolAddress,
address _gasPoolAddress,
address _collSurplusPoolAddress,
address _priceFeedAddress,
address _lusdTokenAddress,
address _sortedTrovesAddress,
address _lqtyTokenAddress,
address _collTokenAddress,
uint collDecimalAdjustment
) external;
function stabilityPool() external view returns (IStabilityPool);
function lusdToken() external view returns (ILUSDToken);
function lqtyToken() external view returns (ILQTYToken);
function getTroveOwnersCount() external view returns (uint);
function getTroveFromTroveOwnersArray(uint _index) external view returns (address);
function getNominalICR(address _borrower) external view returns (uint);
function getCurrentICR(address _borrower, uint _price) external view returns (uint);
function liquidate(address _borrower) external;
function liquidateTroves(uint _n) external;
function batchLiquidateTroves(address[] calldata _troveArray) external;
function redeemCollateral(
uint _LUSDAmount,
address _firstRedemptionHint,
address _upperPartialRedemptionHint,
address _lowerPartialRedemptionHint,
uint _partialRedemptionHintNICR,
uint _maxIterations,
uint _maxFee
) external;
function updateStakeAndTotalStakes(address _borrower) external returns (uint);
function updateTroveRewardSnapshots(address _borrower) external;
function addTroveOwnerToArray(address _borrower) external returns (uint index);
function applyPendingRewards(address _borrower) external;
function getPendingETHReward(address _borrower) external view returns (uint);
function getPendingLUSDDebtReward(address _borrower) external view returns (uint);
function hasPendingRewards(address _borrower) external view returns (bool);
function getEntireDebtAndColl(address _borrower) external view returns (
uint debt,
uint coll,
uint pendingLUSDDebtReward,
uint pendingETHReward
);
function closeTrove(address _borrower) external;
function removeStake(address _borrower) external;
function getRedemptionRate() external view returns (uint);
function getRedemptionRateWithDecay() external view returns (uint);
function getRedemptionFeeWithDecay(uint _ETHDrawn) external view returns (uint);
function getBorrowingRate() external view returns (uint);
function getBorrowingRateWithDecay() external view returns (uint);
function getBorrowingFee(uint LUSDDebt) external view returns (uint);
function getBorrowingFeeWithDecay(uint _LUSDDebt) external view returns (uint);
function getDebtCeiling() external view returns (uint);
function decayBaseRateFromBorrowing() external;
function getTroveStatus(address _borrower) external view returns (uint);
function getTroveStake(address _borrower) external view returns (uint);
function getTroveDebt(address _borrower) external view returns (uint);
function getTroveColl(address _borrower) external view returns (uint);
function setTroveStatus(address _borrower, uint num) external;
function increaseTroveColl(address _borrower, uint _collIncrease) external returns (uint);
function decreaseTroveColl(address _borrower, uint _collDecrease) external returns (uint);
function increaseTroveDebt(address _borrower, uint _debtIncrease) external returns (uint);
function decreaseTroveDebt(address _borrower, uint _collDecrease) external returns (uint);
function getTCR(uint _price) external view returns (uint);
function checkRecoveryMode(uint _price) external view returns (bool);
}
// File contracts/Interfaces/ICollSurplusPool.sol
interface ICollSurplusPool {
// --- Events ---
event BorrowerOperationsAddressChanged(address _newBorrowerOperationsAddress);
event TroveManagerAddressChanged(address _newTroveManagerAddress);
event ActivePoolAddressChanged(address _newActivePoolAddress);
event CollTokenAddressChanged(address _collTokenAddress);
event CollBalanceUpdated(address indexed _account, uint _newBalance);
event EtherSent(address _to, uint _amount);
// --- Contract setters ---
function setAddresses(
address _borrowerOperationsAddress,
address _troveManagerAddress,
address _activePoolAddress,
address _collTokenAddress
) external;
function getETH() external view returns (uint);
function getCollateral(address _account) external view returns (uint);
function accountSurplus(address _account, uint _amount) external;
function claimColl(address _account) external;
function depositColl(uint _amount) external;
}
// File contracts/Interfaces/ISortedTroves.sol
// Common interface for the SortedTroves Doubly Linked List.
interface ISortedTroves {
// --- Events ---
event SortedTrovesAddressChanged(address _sortedDoublyLLAddress);
event BorrowerOperationsAddressChanged(address _borrowerOperationsAddress);
event NodeAdded(address _id, uint _NICR);
event NodeRemoved(address _id);
// --- Functions ---
function setParams(uint256 _size, address _TroveManagerAddress, address _borrowerOperationsAddress) external;
function insert(address _id, uint256 _ICR, address _prevId, address _nextId) external;
function remove(address _id) external;
function reInsert(address _id, uint256 _newICR, address _prevId, address _nextId) external;
function contains(address _id) external view returns (bool);
function isFull() external view returns (bool);
function isEmpty() external view returns (bool);
function getSize() external view returns (uint256);
function getMaxSize() external view returns (uint256);
function getFirst() external view returns (address);
function getLast() external view returns (address);
function getNext(address _id) external view returns (address);
function getPrev(address _id) external view returns (address);
function validInsertPosition(uint256 _ICR, address _prevId, address _nextId) external view returns (bool);
function findInsertPosition(uint256 _ICR, address _prevId, address _nextId) external view returns (address, address);
}
// File contracts/Dependencies/BaseMath.sol
contract BaseMath {
uint constant public DECIMAL_PRECISION = 1e18;
}
// File contracts/Dependencies/SafeMath.sol
/**
* Based on OpenZeppelin's SafeMath:
* https://github.com/OpenZeppelin/openzeppelin-contracts/blob/master/contracts/math/SafeMath.sol
*
* @dev Wrappers over Solidity's arithmetic operations with added overflow
* checks.
*
* Arithmetic operations in Solidity wrap on overflow. This can easily result
* in bugs, because programmers usually assume that an overflow raises an
* error, which is the standard behavior in high level programming languages.
* `SafeMath` restores this intuition by reverting the transaction when an
* operation overflows.
*
* Using this library instead of the unchecked operations eliminates an entire
* class of bugs, so it's recommended to use it always.
*/
library SafeMath {
/**
* @dev Returns the addition of two unsigned integers, reverting on
* overflow.
*
* Counterpart to Solidity's `+` operator.
*
* Requirements:
* - Addition cannot overflow.
*/
function add(uint256 a, uint256 b) internal pure returns (uint256) {
uint256 c = a + b;
require(c >= a, "SafeMath: addition overflow");
return c;
}
/**
* @dev Returns the subtraction of two unsigned integers, reverting on
* overflow (when the result is negative).
*
* Counterpart to Solidity's `-` operator.
*
* Requirements:
* - Subtraction cannot overflow.
*/
function sub(uint256 a, uint256 b) internal pure returns (uint256) {
return sub(a, b, "SafeMath: subtraction overflow");
}
/**
* @dev Returns the subtraction of two unsigned integers, reverting with custom message on
* overflow (when the result is negative).
*
* Counterpart to Solidity's `-` operator.
*
* Requirements:
* - Subtraction cannot overflow.
*
* _Available since v2.4.0._
*/
function sub(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
require(b <= a, errorMessage);
uint256 c = a - b;
return c;
}
/**
* @dev Returns the multiplication of two unsigned integers, reverting on
* overflow.
*
* Counterpart to Solidity's `*` operator.
*
* Requirements:
* - Multiplication cannot overflow.
*/
function mul(uint256 a, uint256 b) internal pure returns (uint256) {
// Gas optimization: this is cheaper than requiring 'a' not being zero, but the
// benefit is lost if 'b' is also tested.
// See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522
if (a == 0) {
return 0;
}
uint256 c = a * b;
require(c / a == b, "SafeMath: multiplication overflow");
return c;
}
/**
* @dev Returns the integer division of two unsigned integers. Reverts on
* division by zero. The result is rounded towards zero.
*
* Counterpart to Solidity's `/` operator. Note: this function uses a
* `revert` opcode (which leaves remaining gas untouched) while Solidity
* uses an invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
* - The divisor cannot be zero.
*/
function div(uint256 a, uint256 b) internal pure returns (uint256) {
return div(a, b, "SafeMath: division by zero");
}
/**
* @dev Returns the integer division of two unsigned integers. Reverts with custom message on
* division by zero. The result is rounded towards zero.
*
* Counterpart to Solidity's `/` operator. Note: this function uses a
* `revert` opcode (which leaves remaining gas untouched) while Solidity
* uses an invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
* - The divisor cannot be zero.
*
* _Available since v2.4.0._
*/
function div(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
// Solidity only automatically asserts when dividing by 0
require(b > 0, errorMessage);
uint256 c = a / b;
// assert(a == b * c + a % b); // There is no case in which this doesn't hold
return c;
}
/**
* @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo),
* Reverts when dividing by zero.
*
* Counterpart to Solidity's `%` operator. This function uses a `revert`
* opcode (which leaves remaining gas untouched) while Solidity uses an
* invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
* - The divisor cannot be zero.
*/
function mod(uint256 a, uint256 b) internal pure returns (uint256) {
return mod(a, b, "SafeMath: modulo by zero");
}
/**
* @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo),
* Reverts with custom message when dividing by zero.
*
* Counterpart to Solidity's `%` operator. This function uses a `revert`
* opcode (which leaves remaining gas untouched) while Solidity uses an
* invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
* - The divisor cannot be zero.
*
* _Available since v2.4.0._
*/
function mod(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
require(b != 0, errorMessage);
return a % b;
}
}
// File contracts/Dependencies/console.sol
// Buidler's helper contract for console logging
library console {
address constant CONSOLE_ADDRESS = address(0x000000000000000000636F6e736F6c652e6c6f67);
function log() internal view {
(bool ignored, ) = CONSOLE_ADDRESS.staticcall(abi.encodeWithSignature("log()"));
ignored;
} function logInt(int p0) internal view {
(bool ignored, ) = CONSOLE_ADDRESS.staticcall(abi.encodeWithSignature("log(int)", p0));
ignored;
}
function logUint(uint p0) internal view {
(bool ignored, ) = CONSOLE_ADDRESS.staticcall(abi.encodeWithSignature("log(uint)", p0));
ignored;
}
function logString(string memory p0) internal view {
(bool ignored, ) = CONSOLE_ADDRESS.staticcall(abi.encodeWithSignature("log(string)", p0));
ignored;
}
function logBool(bool p0) internal view {
(bool ignored, ) = CONSOLE_ADDRESS.staticcall(abi.encodeWithSignature("log(bool)", p0));
ignored;
}
function logAddress(address p0) internal view {
(bool ignored, ) = CONSOLE_ADDRESS.staticcall(abi.encodeWithSignature("log(address)", p0));
ignored;
}
function logBytes(bytes memory p0) internal view {
(bool ignored, ) = CONSOLE_ADDRESS.staticcall(abi.encodeWithSignature("log(bytes)", p0));
ignored;
}
function logByte(byte p0) internal view {
(bool ignored, ) = CONSOLE_ADDRESS.staticcall(abi.encodeWithSignature("log(byte)", p0));
ignored;
}
function logBytes1(bytes1 p0) internal view {
(bool ignored, ) = CONSOLE_ADDRESS.staticcall(abi.encodeWithSignature("log(bytes1)", p0));
ignored;
}
function logBytes2(bytes2 p0) internal view {
(bool ignored, ) = CONSOLE_ADDRESS.staticcall(abi.encodeWithSignature("log(bytes2)", p0));
ignored;
}
function logBytes3(bytes3 p0) internal view {
(bool ignored, ) = CONSOLE_ADDRESS.staticcall(abi.encodeWithSignature("log(bytes3)", p0));
ignored;
}
function logBytes4(bytes4 p0) internal view {
(bool ignored, ) = CONSOLE_ADDRESS.staticcall(abi.encodeWithSignature("log(bytes4)", p0));
ignored;
}
function logBytes5(bytes5 p0) internal view {
(bool ignored, ) = CONSOLE_ADDRESS.staticcall(abi.encodeWithSignature("log(bytes5)", p0));
ignored;
}
function logBytes6(bytes6 p0) internal view {
(bool ignored, ) = CONSOLE_ADDRESS.staticcall(abi.encodeWithSignature("log(bytes6)", p0));
ignored;
}
function logBytes7(bytes7 p0) internal view {
(bool ignored, ) = CONSOLE_ADDRESS.staticcall(abi.encodeWithSignature("log(bytes7)", p0));
ignored;
}
function logBytes8(bytes8 p0) internal view {
(bool ignored, ) = CONSOLE_ADDRESS.staticcall(abi.encodeWithSignature("log(bytes8)", p0));
ignored;
}
function logBytes9(bytes9 p0) internal view {
(bool ignored, ) = CONSOLE_ADDRESS.staticcall(abi.encodeWithSignature("log(bytes9)", p0));
ignored;
}
function logBytes10(bytes10 p0) internal view {
(bool ignored, ) = CONSOLE_ADDRESS.staticcall(abi.encodeWithSignature("log(bytes10)", p0));
ignored;
}
function logBytes11(bytes11 p0) internal view {
(bool ignored, ) = CONSOLE_ADDRESS.staticcall(abi.encodeWithSignature("log(bytes11)", p0));
ignored;
}
function logBytes12(bytes12 p0) internal view {
(bool ignored, ) = CONSOLE_ADDRESS.staticcall(abi.encodeWithSignature("log(bytes12)", p0));
ignored;
}
function logBytes13(bytes13 p0) internal view {
(bool ignored, ) = CONSOLE_ADDRESS.staticcall(abi.encodeWithSignature("log(bytes13)", p0));
ignored;
}
function logBytes14(bytes14 p0) internal view {
(bool ignored, ) = CONSOLE_ADDRESS.staticcall(abi.encodeWithSignature("log(bytes14)", p0));
ignored;
}
function logBytes15(bytes15 p0) internal view {
(bool ignored, ) = CONSOLE_ADDRESS.staticcall(abi.encodeWithSignature("log(bytes15)", p0));
ignored;
}
function logBytes16(bytes16 p0) internal view {
(bool ignored, ) = CONSOLE_ADDRESS.staticcall(abi.encodeWithSignature("log(bytes16)", p0));
ignored;
}
function logBytes17(bytes17 p0) internal view {
(bool ignored, ) = CONSOLE_ADDRESS.staticcall(abi.encodeWithSignature("log(bytes17)", p0));
ignored;
}
function logBytes18(bytes18 p0) internal view {
(bool ignored, ) = CONSOLE_ADDRESS.staticcall(abi.encodeWithSignature("log(bytes18)", p0));
ignored;
}
function logBytes19(bytes19 p0) internal view {
(bool ignored, ) = CONSOLE_ADDRESS.staticcall(abi.encodeWithSignature("log(bytes19)", p0));
ignored;
}
function logBytes20(bytes20 p0) internal view {
(bool ignored, ) = CONSOLE_ADDRESS.staticcall(abi.encodeWithSignature("log(bytes20)", p0));
ignored;
}
function logBytes21(bytes21 p0) internal view {
(bool ignored, ) = CONSOLE_ADDRESS.staticcall(abi.encodeWithSignature("log(bytes21)", p0));
ignored;
}
function logBytes22(bytes22 p0) internal view {
(bool ignored, ) = CONSOLE_ADDRESS.staticcall(abi.encodeWithSignature("log(bytes22)", p0));
ignored;
}
function logBytes23(bytes23 p0) internal view {
(bool ignored, ) = CONSOLE_ADDRESS.staticcall(abi.encodeWithSignature("log(bytes23)", p0));
ignored;
}
function logBytes24(bytes24 p0) internal view {
(bool ignored, ) = CONSOLE_ADDRESS.staticcall(abi.encodeWithSignature("log(bytes24)", p0));
ignored;
}
function logBytes25(bytes25 p0) internal view {
(bool ignored, ) = CONSOLE_ADDRESS.staticcall(abi.encodeWithSignature("log(bytes25)", p0));
ignored;
}
function logBytes26(bytes26 p0) internal view {
(bool ignored, ) = CONSOLE_ADDRESS.staticcall(abi.encodeWithSignature("log(bytes26)", p0));
ignored;
}
function logBytes27(bytes27 p0) internal view {
(bool ignored, ) = CONSOLE_ADDRESS.staticcall(abi.encodeWithSignature("log(bytes27)", p0));
ignored;
}
function logBytes28(bytes28 p0) internal view {
(bool ignored, ) = CONSOLE_ADDRESS.staticcall(abi.encodeWithSignature("log(bytes28)", p0));
ignored;
}
function logBytes29(bytes29 p0) internal view {
(bool ignored, ) = CONSOLE_ADDRESS.staticcall(abi.encodeWithSignature("log(bytes29)", p0));
ignored;
}
function logBytes30(bytes30 p0) internal view {
(bool ignored, ) = CONSOLE_ADDRESS.staticcall(abi.encodeWithSignature("log(bytes30)", p0));
ignored;
}
function logBytes31(bytes31 p0) internal view {
(bool ignored, ) = CONSOLE_ADDRESS.staticcall(abi.encodeWithSignature("log(bytes31)", p0));
ignored;
}
function logBytes32(bytes32 p0) internal view {
(bool ignored, ) = CONSOLE_ADDRESS.staticcall(abi.encodeWithSignature("log(bytes32)", p0));
ignored;
}
function log(uint p0) internal view {
(bool ignored, ) = CONSOLE_ADDRESS.staticcall(abi.encodeWithSignature("log(uint)", p0));
ignored;
}
function log(string memory p0) internal view {
(bool ignored, ) = CONSOLE_ADDRESS.staticcall(abi.encodeWithSignature("log(string)", p0));
ignored;
}
function log(bool p0) internal view {
(bool ignored, ) = CONSOLE_ADDRESS.staticcall(abi.encodeWithSignature("log(bool)", p0));
ignored;
}
function log(address p0) internal view {
(bool ignored, ) = CONSOLE_ADDRESS.staticcall(abi.encodeWithSignature("log(address)", p0));
ignored;
}
function log(uint p0, uint p1) internal view {
(bool ignored, ) = CONSOLE_ADDRESS.staticcall(abi.encodeWithSignature("log(uint,uint)", p0, p1));
ignored;
}
function log(uint p0, string memory p1) internal view {
(bool ignored, ) = CONSOLE_ADDRESS.staticcall(abi.encodeWithSignature("log(uint,string)", p0, p1));
ignored;
}
function log(uint p0, bool p1) internal view {
(bool ignored, ) = CONSOLE_ADDRESS.staticcall(abi.encodeWithSignature("log(uint,bool)", p0, p1));
ignored;
}
function log(uint p0, address p1) internal view {
(bool ignored, ) = CONSOLE_ADDRESS.staticcall(abi.encodeWithSignature("log(uint,address)", p0, p1));
ignored;
}
function log(string memory p0, uint p1) internal view {
(bool ignored, ) = CONSOLE_ADDRESS.staticcall(abi.encodeWithSignature("log(string,uint)", p0, p1));
ignored;
}
function log(string memory p0, string memory p1) internal view {
(bool ignored, ) = CONSOLE_ADDRESS.staticcall(abi.encodeWithSignature("log(string,string)", p0, p1));
ignored;
}
function log(string memory p0, bool p1) internal view {
(bool ignored, ) = CONSOLE_ADDRESS.staticcall(abi.encodeWithSignature("log(string,bool)", p0, p1));
ignored;
}
function log(string memory p0, address p1) internal view {
(bool ignored, ) = CONSOLE_ADDRESS.staticcall(abi.encodeWithSignature("log(string,address)", p0, p1));
ignored;
}
function log(bool p0, uint p1) internal view {
(bool ignored, ) = CONSOLE_ADDRESS.staticcall(abi.encodeWithSignature("log(bool,uint)", p0, p1));
ignored;
}
function log(bool p0, string memory p1) internal view {
(bool ignored, ) = CONSOLE_ADDRESS.staticcall(abi.encodeWithSignature("log(bool,string)", p0, p1));
ignored;
}
function log(bool p0, bool p1) internal view {
(bool ignored, ) = CONSOLE_ADDRESS.staticcall(abi.encodeWithSignature("log(bool,bool)", p0, p1));
ignored;
}
function log(bool p0, address p1) internal view {
(bool ignored, ) = CONSOLE_ADDRESS.staticcall(abi.encodeWithSignature("log(bool,address)", p0, p1));
ignored;
}
function log(address p0, uint p1) internal view {
(bool ignored, ) = CONSOLE_ADDRESS.staticcall(abi.encodeWithSignature("log(address,uint)", p0, p1));
ignored;
}
function log(address p0, string memory p1) internal view {
(bool ignored, ) = CONSOLE_ADDRESS.staticcall(abi.encodeWithSignature("log(address,string)", p0, p1));
ignored;
}
function log(address p0, bool p1) internal view {
(bool ignored, ) = CONSOLE_ADDRESS.staticcall(abi.encodeWithSignature("log(address,bool)", p0, p1));
ignored;
}
function log(address p0, address p1) internal view {
(bool ignored, ) = CONSOLE_ADDRESS.staticcall(abi.encodeWithSignature("log(address,address)", p0, p1));
ignored;
}
function log(uint p0, uint p1, uint p2) internal view {
(bool ignored, ) = CONSOLE_ADDRESS.staticcall(abi.encodeWithSignature("log(uint,uint,uint)", p0, p1, p2));
ignored;
}
function log(uint p0, uint p1, string memory p2) internal view {
(bool ignored, ) = CONSOLE_ADDRESS.staticcall(abi.encodeWithSignature("log(uint,uint,string)", p0, p1, p2));
ignored;
}
function log(uint p0, uint p1, bool p2) internal view {
(bool ignored, ) = CONSOLE_ADDRESS.staticcall(abi.encodeWithSignature("log(uint,uint,bool)", p0, p1, p2));
ignored;
}
function log(uint p0, uint p1, address p2) internal view {
(bool ignored, ) = CONSOLE_ADDRESS.staticcall(abi.encodeWithSignature("log(uint,uint,address)", p0, p1, p2));
ignored;
}
function log(uint p0, string memory p1, uint p2) internal view {
(bool ignored, ) = CONSOLE_ADDRESS.staticcall(abi.encodeWithSignature("log(uint,string,uint)", p0, p1, p2));
ignored;
}
function log(uint p0, string memory p1, string memory p2) internal view {
(bool ignored, ) = CONSOLE_ADDRESS.staticcall(abi.encodeWithSignature("log(uint,string,string)", p0, p1, p2));
ignored;
}
function log(uint p0, string memory p1, bool p2) internal view {
(bool ignored, ) = CONSOLE_ADDRESS.staticcall(abi.encodeWithSignature("log(uint,string,bool)", p0, p1, p2));
ignored;
}
function log(uint p0, string memory p1, address p2) internal view {
(bool ignored, ) = CONSOLE_ADDRESS.staticcall(abi.encodeWithSignature("log(uint,string,address)", p0, p1, p2));
ignored;
}
function log(uint p0, bool p1, uint p2) internal view {
(bool ignored, ) = CONSOLE_ADDRESS.staticcall(abi.encodeWithSignature("log(uint,bool,uint)", p0, p1, p2));
ignored;
}
function log(uint p0, bool p1, string memory p2) internal view {
(bool ignored, ) = CONSOLE_ADDRESS.staticcall(abi.encodeWithSignature("log(uint,bool,string)", p0, p1, p2));
ignored;
}
function log(uint p0, bool p1, bool p2) internal view {
(bool ignored, ) = CONSOLE_ADDRESS.staticcall(abi.encodeWithSignature("log(uint,bool,bool)", p0, p1, p2));
ignored;
}
function log(uint p0, bool p1, address p2) internal view {
(bool ignored, ) = CONSOLE_ADDRESS.staticcall(abi.encodeWithSignature("log(uint,bool,address)", p0, p1, p2));
ignored;
}
function log(uint p0, address p1, uint p2) internal view {
(bool ignored, ) = CONSOLE_ADDRESS.staticcall(abi.encodeWithSignature("log(uint,address,uint)", p0, p1, p2));
ignored;
}
function log(uint p0, address p1, string memory p2) internal view {
(bool ignored, ) = CONSOLE_ADDRESS.staticcall(abi.encodeWithSignature("log(uint,address,string)", p0, p1, p2));
ignored;
}
function log(uint p0, address p1, bool p2) internal view {
(bool ignored, ) = CONSOLE_ADDRESS.staticcall(abi.encodeWithSignature("log(uint,address,bool)", p0, p1, p2));
ignored;
}
function log(uint p0, address p1, address p2) internal view {
(bool ignored, ) = CONSOLE_ADDRESS.staticcall(abi.encodeWithSignature("log(uint,address,address)", p0, p1, p2));
ignored;
}
function log(string memory p0, uint p1, uint p2) internal view {
(bool ignored, ) = CONSOLE_ADDRESS.staticcall(abi.encodeWithSignature("log(string,uint,uint)", p0, p1, p2));
ignored;
}
function log(string memory p0, uint p1, string memory p2) internal view {
(bool ignored, ) = CONSOLE_ADDRESS.staticcall(abi.encodeWithSignature("log(string,uint,string)", p0, p1, p2));
ignored;
}
function log(string memory p0, uint p1, bool p2) internal view {
(bool ignored, ) = CONSOLE_ADDRESS.staticcall(abi.encodeWithSignature("log(string,uint,bool)", p0, p1, p2));
ignored;
}
function log(string memory p0, uint p1, address p2) internal view {
(bool ignored, ) = CONSOLE_ADDRESS.staticcall(abi.encodeWithSignature("log(string,uint,address)", p0, p1, p2));
ignored;
}
function log(string memory p0, string memory p1, uint p2) internal view {
(bool ignored, ) = CONSOLE_ADDRESS.staticcall(abi.encodeWithSignature("log(string,string,uint)", p0, p1, p2));
ignored;
}
function log(string memory p0, string memory p1, string memory p2) internal view {
(bool ignored, ) = CONSOLE_ADDRESS.staticcall(abi.encodeWithSignature("log(string,string,string)", p0, p1, p2));
ignored;
}
function log(string memory p0, string memory p1, bool p2) internal view {
(bool ignored, ) = CONSOLE_ADDRESS.staticcall(abi.encodeWithSignature("log(string,string,bool)", p0, p1, p2));
ignored;
}
function log(string memory p0, string memory p1, address p2) internal view {
(bool ignored, ) = CONSOLE_ADDRESS.staticcall(abi.encodeWithSignature("log(string,string,address)", p0, p1, p2));
ignored;
}
function log(string memory p0, bool p1, uint p2) internal view {
(bool ignored, ) = CONSOLE_ADDRESS.staticcall(abi.encodeWithSignature("log(string,bool,uint)", p0, p1, p2));
ignored;
}
function log(string memory p0, bool p1, string memory p2) internal view {
(bool ignored, ) = CONSOLE_ADDRESS.staticcall(abi.encodeWithSignature("log(string,bool,string)", p0, p1, p2));
ignored;
}
function log(string memory p0, bool p1, bool p2) internal view {
(bool ignored, ) = CONSOLE_ADDRESS.staticcall(abi.encodeWithSignature("log(string,bool,bool)", p0, p1, p2));
ignored;
}
function log(string memory p0, bool p1, address p2) internal view {
(bool ignored, ) = CONSOLE_ADDRESS.staticcall(abi.encodeWithSignature("log(string,bool,address)", p0, p1, p2));
ignored;
}
function log(string memory p0, address p1, uint p2) internal view {
(bool ignored, ) = CONSOLE_ADDRESS.staticcall(abi.encodeWithSignature("log(string,address,uint)", p0, p1, p2));
ignored;
}
function log(string memory p0, address p1, string memory p2) internal view {
(bool ignored, ) = CONSOLE_ADDRESS.staticcall(abi.encodeWithSignature("log(string,address,string)", p0, p1, p2));
ignored;
}
function log(string memory p0, address p1, bool p2) internal view {
(bool ignored, ) = CONSOLE_ADDRESS.staticcall(abi.encodeWithSignature("log(string,address,bool)", p0, p1, p2));
ignored;
}
function log(string memory p0, address p1, address p2) internal view {
(bool ignored, ) = CONSOLE_ADDRESS.staticcall(abi.encodeWithSignature("log(string,address,address)", p0, p1, p2));
ignored;
}
function log(bool p0, uint p1, uint p2) internal view {
(bool ignored, ) = CONSOLE_ADDRESS.staticcall(abi.encodeWithSignature("log(bool,uint,uint)", p0, p1, p2));
ignored;
}
function log(bool p0, uint p1, string memory p2) internal view {
(bool ignored, ) = CONSOLE_ADDRESS.staticcall(abi.encodeWithSignature("log(bool,uint,string)", p0, p1, p2));
ignored;
}
function log(bool p0, uint p1, bool p2) internal view {
(bool ignored, ) = CONSOLE_ADDRESS.staticcall(abi.encodeWithSignature("log(bool,uint,bool)", p0, p1, p2));
ignored;
}
function log(bool p0, uint p1, address p2) internal view {
(bool ignored, ) = CONSOLE_ADDRESS.staticcall(abi.encodeWithSignature("log(bool,uint,address)", p0, p1, p2));
ignored;
}
function log(bool p0, string memory p1, uint p2) internal view {
(bool ignored, ) = CONSOLE_ADDRESS.staticcall(abi.encodeWithSignature("log(bool,string,uint)", p0, p1, p2));
ignored;
}
function log(bool p0, string memory p1, string memory p2) internal view {
(bool ignored, ) = CONSOLE_ADDRESS.staticcall(abi.encodeWithSignature("log(bool,string,string)", p0, p1, p2));
ignored;
}
function log(bool p0, string memory p1, bool p2) internal view {
(bool ignored, ) = CONSOLE_ADDRESS.staticcall(abi.encodeWithSignature("log(bool,string,bool)", p0, p1, p2));
ignored;
}
function log(bool p0, string memory p1, address p2) internal view {
(bool ignored, ) = CONSOLE_ADDRESS.staticcall(abi.encodeWithSignature("log(bool,string,address)", p0, p1, p2));
ignored;
}
function log(bool p0, bool p1, uint p2) internal view {
(bool ignored, ) = CONSOLE_ADDRESS.staticcall(abi.encodeWithSignature("log(bool,bool,uint)", p0, p1, p2));
ignored;
}
function log(bool p0, bool p1, string memory p2) internal view {
(bool ignored, ) = CONSOLE_ADDRESS.staticcall(abi.encodeWithSignature("log(bool,bool,string)", p0, p1, p2));
ignored;
}
function log(bool p0, bool p1, bool p2) internal view {
(bool ignored, ) = CONSOLE_ADDRESS.staticcall(abi.encodeWithSignature("log(bool,bool,bool)", p0, p1, p2));
ignored;
}
function log(bool p0, bool p1, address p2) internal view {
(bool ignored, ) = CONSOLE_ADDRESS.staticcall(abi.encodeWithSignature("log(bool,bool,address)", p0, p1, p2));
ignored;
}
function log(bool p0, address p1, uint p2) internal view {
(bool ignored, ) = CONSOLE_ADDRESS.staticcall(abi.encodeWithSignature("log(bool,address,uint)", p0, p1, p2));
ignored;
}
function log(bool p0, address p1, string memory p2) internal view {
(bool ignored, ) = CONSOLE_ADDRESS.staticcall(abi.encodeWithSignature("log(bool,address,string)", p0, p1, p2));
ignored;
}
function log(bool p0, address p1, bool p2) internal view {
(bool ignored, ) = CONSOLE_ADDRESS.staticcall(abi.encodeWithSignature("log(bool,address,bool)", p0, p1, p2));
ignored;
}
function log(bool p0, address p1, address p2) internal view {
(bool ignored, ) = CONSOLE_ADDRESS.staticcall(abi.encodeWithSignature("log(bool,address,address)", p0, p1, p2));
ignored;
}
function log(address p0, uint p1, uint p2) internal view {
(bool ignored, ) = CONSOLE_ADDRESS.staticcall(abi.encodeWithSignature("log(address,uint,uint)", p0, p1, p2));
ignored;
}
function log(address p0, uint p1, string memory p2) internal view {
(bool ignored, ) = CONSOLE_ADDRESS.staticcall(abi.encodeWithSignature("log(address,uint,string)", p0, p1, p2));
ignored;
}
function log(address p0, uint p1, bool p2) internal view {
(bool ignored, ) = CONSOLE_ADDRESS.staticcall(abi.encodeWithSignature("log(address,uint,bool)", p0, p1, p2));
ignored;
}
function log(address p0, uint p1, address p2) internal view {
(bool ignored, ) = CONSOLE_ADDRESS.staticcall(abi.encodeWithSignature("log(address,uint,address)", p0, p1, p2));
ignored;
}
function log(address p0, string memory p1, uint p2) internal view {
(bool ignored, ) = CONSOLE_ADDRESS.staticcall(abi.encodeWithSignature("log(address,string,uint)", p0, p1, p2));
ignored;
}
function log(address p0, string memory p1, string memory p2) internal view {
(bool ignored, ) = CONSOLE_ADDRESS.staticcall(abi.encodeWithSignature("log(address,string,string)", p0, p1, p2));
ignored;
}
function log(address p0, string memory p1, bool p2) internal view {
(bool ignored, ) = CONSOLE_ADDRESS.staticcall(abi.encodeWithSignature("log(address,string,bool)", p0, p1, p2));
ignored;
}
function log(address p0, string memory p1, address p2) internal view {
(bool ignored, ) = CONSOLE_ADDRESS.staticcall(abi.encodeWithSignature("log(address,string,address)", p0, p1, p2));
ignored;
}
function log(address p0, bool p1, uint p2) internal view {
(bool ignored, ) = CONSOLE_ADDRESS.staticcall(abi.encodeWithSignature("log(address,bool,uint)", p0, p1, p2));
ignored;
}
function log(address p0, bool p1, string memory p2) internal view {
(bool ignored, ) = CONSOLE_ADDRESS.staticcall(abi.encodeWithSignature("log(address,bool,string)", p0, p1, p2));
ignored;
}
function log(address p0, bool p1, bool p2) internal view {
(bool ignored, ) = CONSOLE_ADDRESS.staticcall(abi.encodeWithSignature("log(address,bool,bool)", p0, p1, p2));
ignored;
}
function log(address p0, bool p1, address p2) internal view {
(bool ignored, ) = CONSOLE_ADDRESS.staticcall(abi.encodeWithSignature("log(address,bool,address)", p0, p1, p2));
ignored;
}
function log(address p0, address p1, uint p2) internal view {
(bool ignored, ) = CONSOLE_ADDRESS.staticcall(abi.encodeWithSignature("log(address,address,uint)", p0, p1, p2));
ignored;
}
function log(address p0, address p1, string memory p2) internal view {
(bool ignored, ) = CONSOLE_ADDRESS.staticcall(abi.encodeWithSignature("log(address,address,string)", p0, p1, p2));
ignored;
}
function log(address p0, address p1, bool p2) internal view {
(bool ignored, ) = CONSOLE_ADDRESS.staticcall(abi.encodeWithSignature("log(address,address,bool)", p0, p1, p2));
ignored;
}
function log(address p0, address p1, address p2) internal view {
(bool ignored, ) = CONSOLE_ADDRESS.staticcall(abi.encodeWithSignature("log(address,address,address)", p0, p1, p2));
ignored;
}
function log(uint p0, uint p1, uint p2, uint p3) internal view {
(bool ignored, ) = CONSOLE_ADDRESS.staticcall(abi.encodeWithSignature("log(uint,uint,uint,uint)", p0, p1, p2, p3));
ignored;
}
function log(uint p0, uint p1, uint p2, string memory p3) internal view {
(bool ignored, ) = CONSOLE_ADDRESS.staticcall(abi.encodeWithSignature("log(uint,uint,uint,string)", p0, p1, p2, p3));
ignored;
}
function log(uint p0, uint p1, uint p2, bool p3) internal view {
(bool ignored, ) = CONSOLE_ADDRESS.staticcall(abi.encodeWithSignature("log(uint,uint,uint,bool)", p0, p1, p2, p3));
ignored;
}
function log(uint p0, uint p1, uint p2, address p3) internal view {
(bool ignored, ) = CONSOLE_ADDRESS.staticcall(abi.encodeWithSignature("log(uint,uint,uint,address)", p0, p1, p2, p3));
ignored;
}
function log(uint p0, uint p1, string memory p2, uint p3) internal view {
(bool ignored, ) = CONSOLE_ADDRESS.staticcall(abi.encodeWithSignature("log(uint,uint,string,uint)", p0, p1, p2, p3));
ignored;
}
function log(uint p0, uint p1, string memory p2, string memory p3) internal view {
(bool ignored, ) = CONSOLE_ADDRESS.staticcall(abi.encodeWithSignature("log(uint,uint,string,string)", p0, p1, p2, p3));
ignored;
}
function log(uint p0, uint p1, string memory p2, bool p3) internal view {
(bool ignored, ) = CONSOLE_ADDRESS.staticcall(abi.encodeWithSignature("log(uint,uint,string,bool)", p0, p1, p2, p3));
ignored;
}
function log(uint p0, uint p1, string memory p2, address p3) internal view {
(bool ignored, ) = CONSOLE_ADDRESS.staticcall(abi.encodeWithSignature("log(uint,uint,string,address)", p0, p1, p2, p3));
ignored;
}
function log(uint p0, uint p1, bool p2, uint p3) internal view {
(bool ignored, ) = CONSOLE_ADDRESS.staticcall(abi.encodeWithSignature("log(uint,uint,bool,uint)", p0, p1, p2, p3));
ignored;
}
function log(uint p0, uint p1, bool p2, string memory p3) internal view {
(bool ignored, ) = CONSOLE_ADDRESS.staticcall(abi.encodeWithSignature("log(uint,uint,bool,string)", p0, p1, p2, p3));
ignored;
}
function log(uint p0, uint p1, bool p2, bool p3) internal view {
(bool ignored, ) = CONSOLE_ADDRESS.staticcall(abi.encodeWithSignature("log(uint,uint,bool,bool)", p0, p1, p2, p3));
ignored;
}
function log(uint p0, uint p1, bool p2, address p3) internal view {
(bool ignored, ) = CONSOLE_ADDRESS.staticcall(abi.encodeWithSignature("log(uint,uint,bool,address)", p0, p1, p2, p3));
ignored;
}
function log(uint p0, uint p1, address p2, uint p3) internal view {
(bool ignored, ) = CONSOLE_ADDRESS.staticcall(abi.encodeWithSignature("log(uint,uint,address,uint)", p0, p1, p2, p3));
ignored;
}
function log(uint p0, uint p1, address p2, string memory p3) internal view {
(bool ignored, ) = CONSOLE_ADDRESS.staticcall(abi.encodeWithSignature("log(uint,uint,address,string)", p0, p1, p2, p3));
ignored;
}
function log(uint p0, uint p1, address p2, bool p3) internal view {
(bool ignored, ) = CONSOLE_ADDRESS.staticcall(abi.encodeWithSignature("log(uint,uint,address,bool)", p0, p1, p2, p3));
ignored;
}
function log(uint p0, uint p1, address p2, address p3) internal view {
(bool ignored, ) = CONSOLE_ADDRESS.staticcall(abi.encodeWithSignature("log(uint,uint,address,address)", p0, p1, p2, p3));
ignored;
}
function log(uint p0, string memory p1, uint p2, uint p3) internal view {
(bool ignored, ) = CONSOLE_ADDRESS.staticcall(abi.encodeWithSignature("log(uint,string,uint,uint)", p0, p1, p2, p3));
ignored;
}
function log(uint p0, string memory p1, uint p2, string memory p3) internal view {
(bool ignored, ) = CONSOLE_ADDRESS.staticcall(abi.encodeWithSignature("log(uint,string,uint,string)", p0, p1, p2, p3));
ignored;
}
function log(uint p0, string memory p1, uint p2, bool p3) internal view {
(bool ignored, ) = CONSOLE_ADDRESS.staticcall(abi.encodeWithSignature("log(uint,string,uint,bool)", p0, p1, p2, p3));
ignored;
}
function log(uint p0, string memory p1, uint p2, address p3) internal view {
(bool ignored, ) = CONSOLE_ADDRESS.staticcall(abi.encodeWithSignature("log(uint,string,uint,address)", p0, p1, p2, p3));
ignored;
}
function log(uint p0, string memory p1, string memory p2, uint p3) internal view {
(bool ignored, ) = CONSOLE_ADDRESS.staticcall(abi.encodeWithSignature("log(uint,string,string,uint)", p0, p1, p2, p3));
ignored;
}
function log(uint p0, string memory p1, string memory p2, string memory p3) internal view {
(bool ignored, ) = CONSOLE_ADDRESS.staticcall(abi.encodeWithSignature("log(uint,string,string,string)", p0, p1, p2, p3));
ignored;
}
function log(uint p0, string memory p1, string memory p2, bool p3) internal view {
(bool ignored, ) = CONSOLE_ADDRESS.staticcall(abi.encodeWithSignature("log(uint,string,string,bool)", p0, p1, p2, p3));
ignored;
}
function log(uint p0, string memory p1, string memory p2, address p3) internal view {
(bool ignored, ) = CONSOLE_ADDRESS.staticcall(abi.encodeWithSignature("log(uint,string,string,address)", p0, p1, p2, p3));
ignored;
}
function log(uint p0, string memory p1, bool p2, uint p3) internal view {
(bool ignored, ) = CONSOLE_ADDRESS.staticcall(abi.encodeWithSignature("log(uint,string,bool,uint)", p0, p1, p2, p3));
ignored;
}
function log(uint p0, string memory p1, bool p2, string memory p3) internal view {
(bool ignored, ) = CONSOLE_ADDRESS.staticcall(abi.encodeWithSignature("log(uint,string,bool,string)", p0, p1, p2, p3));
ignored;
}
function log(uint p0, string memory p1, bool p2, bool p3) internal view {
(bool ignored, ) = CONSOLE_ADDRESS.staticcall(abi.encodeWithSignature("log(uint,string,bool,bool)", p0, p1, p2, p3));
ignored;
}
function log(uint p0, string memory p1, bool p2, address p3) internal view {
(bool ignored, ) = CONSOLE_ADDRESS.staticcall(abi.encodeWithSignature("log(uint,string,bool,address)", p0, p1, p2, p3));
ignored;
}
function log(uint p0, string memory p1, address p2, uint p3) internal view {
(bool ignored, ) = CONSOLE_ADDRESS.staticcall(abi.encodeWithSignature("log(uint,string,address,uint)", p0, p1, p2, p3));
ignored;
}
function log(uint p0, string memory p1, address p2, string memory p3) internal view {
(bool ignored, ) = CONSOLE_ADDRESS.staticcall(abi.encodeWithSignature("log(uint,string,address,string)", p0, p1, p2, p3));
ignored;
}
function log(uint p0, string memory p1, address p2, bool p3) internal view {
(bool ignored, ) = CONSOLE_ADDRESS.staticcall(abi.encodeWithSignature("log(uint,string,address,bool)", p0, p1, p2, p3));
ignored;
}
function log(uint p0, string memory p1, address p2, address p3) internal view {
(bool ignored, ) = CONSOLE_ADDRESS.staticcall(abi.encodeWithSignature("log(uint,string,address,address)", p0, p1, p2, p3));
ignored;
}
function log(uint p0, bool p1, uint p2, uint p3) internal view {
(bool ignored, ) = CONSOLE_ADDRESS.staticcall(abi.encodeWithSignature("log(uint,bool,uint,uint)", p0, p1, p2, p3));
ignored;
}
function log(uint p0, bool p1, uint p2, string memory p3) internal view {
(bool ignored, ) = CONSOLE_ADDRESS.staticcall(abi.encodeWithSignature("log(uint,bool,uint,string)", p0, p1, p2, p3));
ignored;
}
function log(uint p0, bool p1, uint p2, bool p3) internal view {
(bool ignored, ) = CONSOLE_ADDRESS.staticcall(abi.encodeWithSignature("log(uint,bool,uint,bool)", p0, p1, p2, p3));
ignored;
}
function log(uint p0, bool p1, uint p2, address p3) internal view {
(bool ignored, ) = CONSOLE_ADDRESS.staticcall(abi.encodeWithSignature("log(uint,bool,uint,address)", p0, p1, p2, p3));
ignored;
}
function log(uint p0, bool p1, string memory p2, uint p3) internal view {
(bool ignored, ) = CONSOLE_ADDRESS.staticcall(abi.encodeWithSignature("log(uint,bool,string,uint)", p0, p1, p2, p3));
ignored;
}
function log(uint p0, bool p1, string memory p2, string memory p3) internal view {
(bool ignored, ) = CONSOLE_ADDRESS.staticcall(abi.encodeWithSignature("log(uint,bool,string,string)", p0, p1, p2, p3));
ignored;
}
function log(uint p0, bool p1, string memory p2, bool p3) internal view {
(bool ignored, ) = CONSOLE_ADDRESS.staticcall(abi.encodeWithSignature("log(uint,bool,string,bool)", p0, p1, p2, p3));
ignored;
}
function log(uint p0, bool p1, string memory p2, address p3) internal view {
(bool ignored, ) = CONSOLE_ADDRESS.staticcall(abi.encodeWithSignature("log(uint,bool,string,address)", p0, p1, p2, p3));
ignored;
}
function log(uint p0, bool p1, bool p2, uint p3) internal view {
(bool ignored, ) = CONSOLE_ADDRESS.staticcall(abi.encodeWithSignature("log(uint,bool,bool,uint)", p0, p1, p2, p3));
ignored;
}
function log(uint p0, bool p1, bool p2, string memory p3) internal view {
(bool ignored, ) = CONSOLE_ADDRESS.staticcall(abi.encodeWithSignature("log(uint,bool,bool,string)", p0, p1, p2, p3));
ignored;
}
function log(uint p0, bool p1, bool p2, bool p3) internal view {
(bool ignored, ) = CONSOLE_ADDRESS.staticcall(abi.encodeWithSignature("log(uint,bool,bool,bool)", p0, p1, p2, p3));
ignored;
}
function log(uint p0, bool p1, bool p2, address p3) internal view {
(bool ignored, ) = CONSOLE_ADDRESS.staticcall(abi.encodeWithSignature("log(uint,bool,bool,address)", p0, p1, p2, p3));
ignored;
}
function log(uint p0, bool p1, address p2, uint p3) internal view {
(bool ignored, ) = CONSOLE_ADDRESS.staticcall(abi.encodeWithSignature("log(uint,bool,address,uint)", p0, p1, p2, p3));
ignored;
}
function log(uint p0, bool p1, address p2, string memory p3) internal view {
(bool ignored, ) = CONSOLE_ADDRESS.staticcall(abi.encodeWithSignature("log(uint,bool,address,string)", p0, p1, p2, p3));
ignored;
}
function log(uint p0, bool p1, address p2, bool p3) internal view {
(bool ignored, ) = CONSOLE_ADDRESS.staticcall(abi.encodeWithSignature("log(uint,bool,address,bool)", p0, p1, p2, p3));
ignored;
}
function log(uint p0, bool p1, address p2, address p3) internal view {
(bool ignored, ) = CONSOLE_ADDRESS.staticcall(abi.encodeWithSignature("log(uint,bool,address,address)", p0, p1, p2, p3));
ignored;
}
function log(uint p0, address p1, uint p2, uint p3) internal view {
(bool ignored, ) = CONSOLE_ADDRESS.staticcall(abi.encodeWithSignature("log(uint,address,uint,uint)", p0, p1, p2, p3));
ignored;
}
function log(uint p0, address p1, uint p2, string memory p3) internal view {
(bool ignored, ) = CONSOLE_ADDRESS.staticcall(abi.encodeWithSignature("log(uint,address,uint,string)", p0, p1, p2, p3));
ignored;
}
function log(uint p0, address p1, uint p2, bool p3) internal view {
(bool ignored, ) = CONSOLE_ADDRESS.staticcall(abi.encodeWithSignature("log(uint,address,uint,bool)", p0, p1, p2, p3));
ignored;
}
function log(uint p0, address p1, uint p2, address p3) internal view {
(bool ignored, ) = CONSOLE_ADDRESS.staticcall(abi.encodeWithSignature("log(uint,address,uint,address)", p0, p1, p2, p3));
ignored;
}
function log(uint p0, address p1, string memory p2, uint p3) internal view {
(bool ignored, ) = CONSOLE_ADDRESS.staticcall(abi.encodeWithSignature("log(uint,address,string,uint)", p0, p1, p2, p3));
ignored;
}
function log(uint p0, address p1, string memory p2, string memory p3) internal view {
(bool ignored, ) = CONSOLE_ADDRESS.staticcall(abi.encodeWithSignature("log(uint,address,string,string)", p0, p1, p2, p3));
ignored;
}
function log(uint p0, address p1, string memory p2, bool p3) internal view {
(bool ignored, ) = CONSOLE_ADDRESS.staticcall(abi.encodeWithSignature("log(uint,address,string,bool)", p0, p1, p2, p3));
ignored;
}
function log(uint p0, address p1, string memory p2, address p3) internal view {
(bool ignored, ) = CONSOLE_ADDRESS.staticcall(abi.encodeWithSignature("log(uint,address,string,address)", p0, p1, p2, p3));
ignored;
}
function log(uint p0, address p1, bool p2, uint p3) internal view {
(bool ignored, ) = CONSOLE_ADDRESS.staticcall(abi.encodeWithSignature("log(uint,address,bool,uint)", p0, p1, p2, p3));
ignored;
}
function log(uint p0, address p1, bool p2, string memory p3) internal view {
(bool ignored, ) = CONSOLE_ADDRESS.staticcall(abi.encodeWithSignature("log(uint,address,bool,string)", p0, p1, p2, p3));
ignored;
}
function log(uint p0, address p1, bool p2, bool p3) internal view {
(bool ignored, ) = CONSOLE_ADDRESS.staticcall(abi.encodeWithSignature("log(uint,address,bool,bool)", p0, p1, p2, p3));
ignored;
}
function log(uint p0, address p1, bool p2, address p3) internal view {
(bool ignored, ) = CONSOLE_ADDRESS.staticcall(abi.encodeWithSignature("log(uint,address,bool,address)", p0, p1, p2, p3));
ignored;
}
function log(uint p0, address p1, address p2, uint p3) internal view {
(bool ignored, ) = CONSOLE_ADDRESS.staticcall(abi.encodeWithSignature("log(uint,address,address,uint)", p0, p1, p2, p3));
ignored;
}
function log(uint p0, address p1, address p2, string memory p3) internal view {
(bool ignored, ) = CONSOLE_ADDRESS.staticcall(abi.encodeWithSignature("log(uint,address,address,string)", p0, p1, p2, p3));
ignored;
}
function log(uint p0, address p1, address p2, bool p3) internal view {
(bool ignored, ) = CONSOLE_ADDRESS.staticcall(abi.encodeWithSignature("log(uint,address,address,bool)", p0, p1, p2, p3));
ignored;
}
function log(uint p0, address p1, address p2, address p3) internal view {
(bool ignored, ) = CONSOLE_ADDRESS.staticcall(abi.encodeWithSignature("log(uint,address,address,address)", p0, p1, p2, p3));
ignored;
}
function log(string memory p0, uint p1, uint p2, uint p3) internal view {
(bool ignored, ) = CONSOLE_ADDRESS.staticcall(abi.encodeWithSignature("log(string,uint,uint,uint)", p0, p1, p2, p3));
ignored;
}
function log(string memory p0, uint p1, uint p2, string memory p3) internal view {
(bool ignored, ) = CONSOLE_ADDRESS.staticcall(abi.encodeWithSignature("log(string,uint,uint,string)", p0, p1, p2, p3));
ignored;
}
function log(string memory p0, uint p1, uint p2, bool p3) internal view {
(bool ignored, ) = CONSOLE_ADDRESS.staticcall(abi.encodeWithSignature("log(string,uint,uint,bool)", p0, p1, p2, p3));
ignored;
}
function log(string memory p0, uint p1, uint p2, address p3) internal view {
(bool ignored, ) = CONSOLE_ADDRESS.staticcall(abi.encodeWithSignature("log(string,uint,uint,address)", p0, p1, p2, p3));
ignored;
}
function log(string memory p0, uint p1, string memory p2, uint p3) internal view {
(bool ignored, ) = CONSOLE_ADDRESS.staticcall(abi.encodeWithSignature("log(string,uint,string,uint)", p0, p1, p2, p3));
ignored;
}
function log(string memory p0, uint p1, string memory p2, string memory p3) internal view {
(bool ignored, ) = CONSOLE_ADDRESS.staticcall(abi.encodeWithSignature("log(string,uint,string,string)", p0, p1, p2, p3));
ignored;
}
function log(string memory p0, uint p1, string memory p2, bool p3) internal view {
(bool ignored, ) = CONSOLE_ADDRESS.staticcall(abi.encodeWithSignature("log(string,uint,string,bool)", p0, p1, p2, p3));
ignored;
}
function log(string memory p0, uint p1, string memory p2, address p3) internal view {
(bool ignored, ) = CONSOLE_ADDRESS.staticcall(abi.encodeWithSignature("log(string,uint,string,address)", p0, p1, p2, p3));
ignored;
}
function log(string memory p0, uint p1, bool p2, uint p3) internal view {
(bool ignored, ) = CONSOLE_ADDRESS.staticcall(abi.encodeWithSignature("log(string,uint,bool,uint)", p0, p1, p2, p3));
ignored;
}
function log(string memory p0, uint p1, bool p2, string memory p3) internal view {
(bool ignored, ) = CONSOLE_ADDRESS.staticcall(abi.encodeWithSignature("log(string,uint,bool,string)", p0, p1, p2, p3));
ignored;
}
function log(string memory p0, uint p1, bool p2, bool p3) internal view {
(bool ignored, ) = CONSOLE_ADDRESS.staticcall(abi.encodeWithSignature("log(string,uint,bool,bool)", p0, p1, p2, p3));
ignored;
}
function log(string memory p0, uint p1, bool p2, address p3) internal view {
(bool ignored, ) = CONSOLE_ADDRESS.staticcall(abi.encodeWithSignature("log(string,uint,bool,address)", p0, p1, p2, p3));
ignored;
}
function log(string memory p0, uint p1, address p2, uint p3) internal view {
(bool ignored, ) = CONSOLE_ADDRESS.staticcall(abi.encodeWithSignature("log(string,uint,address,uint)", p0, p1, p2, p3));
ignored;
}
function log(string memory p0, uint p1, address p2, string memory p3) internal view {
(bool ignored, ) = CONSOLE_ADDRESS.staticcall(abi.encodeWithSignature("log(string,uint,address,string)", p0, p1, p2, p3));
ignored;
}
function log(string memory p0, uint p1, address p2, bool p3) internal view {
(bool ignored, ) = CONSOLE_ADDRESS.staticcall(abi.encodeWithSignature("log(string,uint,address,bool)", p0, p1, p2, p3));
ignored;
}
function log(string memory p0, uint p1, address p2, address p3) internal view {
(bool ignored, ) = CONSOLE_ADDRESS.staticcall(abi.encodeWithSignature("log(string,uint,address,address)", p0, p1, p2, p3));
ignored;
}
function log(string memory p0, string memory p1, uint p2, uint p3) internal view {
(bool ignored, ) = CONSOLE_ADDRESS.staticcall(abi.encodeWithSignature("log(string,string,uint,uint)", p0, p1, p2, p3));
ignored;
}
function log(string memory p0, string memory p1, uint p2, string memory p3) internal view {
(bool ignored, ) = CONSOLE_ADDRESS.staticcall(abi.encodeWithSignature("log(string,string,uint,string)", p0, p1, p2, p3));
ignored;
}
function log(string memory p0, string memory p1, uint p2, bool p3) internal view {
(bool ignored, ) = CONSOLE_ADDRESS.staticcall(abi.encodeWithSignature("log(string,string,uint,bool)", p0, p1, p2, p3));
ignored;
}
function log(string memory p0, string memory p1, uint p2, address p3) internal view {
(bool ignored, ) = CONSOLE_ADDRESS.staticcall(abi.encodeWithSignature("log(string,string,uint,address)", p0, p1, p2, p3));
ignored;
}
function log(string memory p0, string memory p1, string memory p2, uint p3) internal view {
(bool ignored, ) = CONSOLE_ADDRESS.staticcall(abi.encodeWithSignature("log(string,string,string,uint)", p0, p1, p2, p3));
ignored;
}
function log(string memory p0, string memory p1, string memory p2, string memory p3) internal view {
(bool ignored, ) = CONSOLE_ADDRESS.staticcall(abi.encodeWithSignature("log(string,string,string,string)", p0, p1, p2, p3));
ignored;
}
function log(string memory p0, string memory p1, string memory p2, bool p3) internal view {
(bool ignored, ) = CONSOLE_ADDRESS.staticcall(abi.encodeWithSignature("log(string,string,string,bool)", p0, p1, p2, p3));
ignored;
}
function log(string memory p0, string memory p1, string memory p2, address p3) internal view {
(bool ignored, ) = CONSOLE_ADDRESS.staticcall(abi.encodeWithSignature("log(string,string,string,address)", p0, p1, p2, p3));
ignored;
}
function log(string memory p0, string memory p1, bool p2, uint p3) internal view {
(bool ignored, ) = CONSOLE_ADDRESS.staticcall(abi.encodeWithSignature("log(string,string,bool,uint)", p0, p1, p2, p3));
ignored;
}
function log(string memory p0, string memory p1, bool p2, string memory p3) internal view {
(bool ignored, ) = CONSOLE_ADDRESS.staticcall(abi.encodeWithSignature("log(string,string,bool,string)", p0, p1, p2, p3));
ignored;
}
function log(string memory p0, string memory p1, bool p2, bool p3) internal view {
(bool ignored, ) = CONSOLE_ADDRESS.staticcall(abi.encodeWithSignature("log(string,string,bool,bool)", p0, p1, p2, p3));
ignored;
}
function log(string memory p0, string memory p1, bool p2, address p3) internal view {
(bool ignored, ) = CONSOLE_ADDRESS.staticcall(abi.encodeWithSignature("log(string,string,bool,address)", p0, p1, p2, p3));
ignored;
}
function log(string memory p0, string memory p1, address p2, uint p3) internal view {
(bool ignored, ) = CONSOLE_ADDRESS.staticcall(abi.encodeWithSignature("log(string,string,address,uint)", p0, p1, p2, p3));
ignored;
}
function log(string memory p0, string memory p1, address p2, string memory p3) internal view {
(bool ignored, ) = CONSOLE_ADDRESS.staticcall(abi.encodeWithSignature("log(string,string,address,string)", p0, p1, p2, p3));
ignored;
}
function log(string memory p0, string memory p1, address p2, bool p3) internal view {
(bool ignored, ) = CONSOLE_ADDRESS.staticcall(abi.encodeWithSignature("log(string,string,address,bool)", p0, p1, p2, p3));
ignored;
}
function log(string memory p0, string memory p1, address p2, address p3) internal view {
(bool ignored, ) = CONSOLE_ADDRESS.staticcall(abi.encodeWithSignature("log(string,string,address,address)", p0, p1, p2, p3));
ignored;
}
function log(string memory p0, bool p1, uint p2, uint p3) internal view {
(bool ignored, ) = CONSOLE_ADDRESS.staticcall(abi.encodeWithSignature("log(string,bool,uint,uint)", p0, p1, p2, p3));
ignored;
}
function log(string memory p0, bool p1, uint p2, string memory p3) internal view {
(bool ignored, ) = CONSOLE_ADDRESS.staticcall(abi.encodeWithSignature("log(string,bool,uint,string)", p0, p1, p2, p3));
ignored;
}
function log(string memory p0, bool p1, uint p2, bool p3) internal view {
(bool ignored, ) = CONSOLE_ADDRESS.staticcall(abi.encodeWithSignature("log(string,bool,uint,bool)", p0, p1, p2, p3));
ignored;
}
function log(string memory p0, bool p1, uint p2, address p3) internal view {
(bool ignored, ) = CONSOLE_ADDRESS.staticcall(abi.encodeWithSignature("log(string,bool,uint,address)", p0, p1, p2, p3));
ignored;
}
function log(string memory p0, bool p1, string memory p2, uint p3) internal view {
(bool ignored, ) = CONSOLE_ADDRESS.staticcall(abi.encodeWithSignature("log(string,bool,string,uint)", p0, p1, p2, p3));
ignored;
}
function log(string memory p0, bool p1, string memory p2, string memory p3) internal view {
(bool ignored, ) = CONSOLE_ADDRESS.staticcall(abi.encodeWithSignature("log(string,bool,string,string)", p0, p1, p2, p3));
ignored;
}
function log(string memory p0, bool p1, string memory p2, bool p3) internal view {
(bool ignored, ) = CONSOLE_ADDRESS.staticcall(abi.encodeWithSignature("log(string,bool,string,bool)", p0, p1, p2, p3));
ignored;
}
function log(string memory p0, bool p1, string memory p2, address p3) internal view {
(bool ignored, ) = CONSOLE_ADDRESS.staticcall(abi.encodeWithSignature("log(string,bool,string,address)", p0, p1, p2, p3));
ignored;
}
function log(string memory p0, bool p1, bool p2, uint p3) internal view {
(bool ignored, ) = CONSOLE_ADDRESS.staticcall(abi.encodeWithSignature("log(string,bool,bool,uint)", p0, p1, p2, p3));
ignored;
}
function log(string memory p0, bool p1, bool p2, string memory p3) internal view {
(bool ignored, ) = CONSOLE_ADDRESS.staticcall(abi.encodeWithSignature("log(string,bool,bool,string)", p0, p1, p2, p3));
ignored;
}
function log(string memory p0, bool p1, bool p2, bool p3) internal view {
(bool ignored, ) = CONSOLE_ADDRESS.staticcall(abi.encodeWithSignature("log(string,bool,bool,bool)", p0, p1, p2, p3));
ignored;
}
function log(string memory p0, bool p1, bool p2, address p3) internal view {
(bool ignored, ) = CONSOLE_ADDRESS.staticcall(abi.encodeWithSignature("log(string,bool,bool,address)", p0, p1, p2, p3));
ignored;
}
function log(string memory p0, bool p1, address p2, uint p3) internal view {
(bool ignored, ) = CONSOLE_ADDRESS.staticcall(abi.encodeWithSignature("log(string,bool,address,uint)", p0, p1, p2, p3));
ignored;
}
function log(string memory p0, bool p1, address p2, string memory p3) internal view {
(bool ignored, ) = CONSOLE_ADDRESS.staticcall(abi.encodeWithSignature("log(string,bool,address,string)", p0, p1, p2, p3));
ignored;
}
function log(string memory p0, bool p1, address p2, bool p3) internal view {
(bool ignored, ) = CONSOLE_ADDRESS.staticcall(abi.encodeWithSignature("log(string,bool,address,bool)", p0, p1, p2, p3));
ignored;
}
function log(string memory p0, bool p1, address p2, address p3) internal view {
(bool ignored, ) = CONSOLE_ADDRESS.staticcall(abi.encodeWithSignature("log(string,bool,address,address)", p0, p1, p2, p3));
ignored;
}
function log(string memory p0, address p1, uint p2, uint p3) internal view {
(bool ignored, ) = CONSOLE_ADDRESS.staticcall(abi.encodeWithSignature("log(string,address,uint,uint)", p0, p1, p2, p3));
ignored;
}
function log(string memory p0, address p1, uint p2, string memory p3) internal view {
(bool ignored, ) = CONSOLE_ADDRESS.staticcall(abi.encodeWithSignature("log(string,address,uint,string)", p0, p1, p2, p3));
ignored;
}
function log(string memory p0, address p1, uint p2, bool p3) internal view {
(bool ignored, ) = CONSOLE_ADDRESS.staticcall(abi.encodeWithSignature("log(string,address,uint,bool)", p0, p1, p2, p3));
ignored;
}
function log(string memory p0, address p1, uint p2, address p3) internal view {
(bool ignored, ) = CONSOLE_ADDRESS.staticcall(abi.encodeWithSignature("log(string,address,uint,address)", p0, p1, p2, p3));
ignored;
}
function log(string memory p0, address p1, string memory p2, uint p3) internal view {
(bool ignored, ) = CONSOLE_ADDRESS.staticcall(abi.encodeWithSignature("log(string,address,string,uint)", p0, p1, p2, p3));
ignored;
}
function log(string memory p0, address p1, string memory p2, string memory p3) internal view {
(bool ignored, ) = CONSOLE_ADDRESS.staticcall(abi.encodeWithSignature("log(string,address,string,string)", p0, p1, p2, p3));
ignored;
}
function log(string memory p0, address p1, string memory p2, bool p3) internal view {
(bool ignored, ) = CONSOLE_ADDRESS.staticcall(abi.encodeWithSignature("log(string,address,string,bool)", p0, p1, p2, p3));
ignored;
}
function log(string memory p0, address p1, string memory p2, address p3) internal view {
(bool ignored, ) = CONSOLE_ADDRESS.staticcall(abi.encodeWithSignature("log(string,address,string,address)", p0, p1, p2, p3));
ignored;
}
function log(string memory p0, address p1, bool p2, uint p3) internal view {
(bool ignored, ) = CONSOLE_ADDRESS.staticcall(abi.encodeWithSignature("log(string,address,bool,uint)", p0, p1, p2, p3));
ignored;
}
function log(string memory p0, address p1, bool p2, string memory p3) internal view {
(bool ignored, ) = CONSOLE_ADDRESS.staticcall(abi.encodeWithSignature("log(string,address,bool,string)", p0, p1, p2, p3));
ignored;
}
function log(string memory p0, address p1, bool p2, bool p3) internal view {
(bool ignored, ) = CONSOLE_ADDRESS.staticcall(abi.encodeWithSignature("log(string,address,bool,bool)", p0, p1, p2, p3));
ignored;
}
function log(string memory p0, address p1, bool p2, address p3) internal view {
(bool ignored, ) = CONSOLE_ADDRESS.staticcall(abi.encodeWithSignature("log(string,address,bool,address)", p0, p1, p2, p3));
ignored;
}
function log(string memory p0, address p1, address p2, uint p3) internal view {
(bool ignored, ) = CONSOLE_ADDRESS.staticcall(abi.encodeWithSignature("log(string,address,address,uint)", p0, p1, p2, p3));
ignored;
}
function log(string memory p0, address p1, address p2, string memory p3) internal view {
(bool ignored, ) = CONSOLE_ADDRESS.staticcall(abi.encodeWithSignature("log(string,address,address,string)", p0, p1, p2, p3));
ignored;
}
function log(string memory p0, address p1, address p2, bool p3) internal view {
(bool ignored, ) = CONSOLE_ADDRESS.staticcall(abi.encodeWithSignature("log(string,address,address,bool)", p0, p1, p2, p3));
ignored;
}
function log(string memory p0, address p1, address p2, address p3) internal view {
(bool ignored, ) = CONSOLE_ADDRESS.staticcall(abi.encodeWithSignature("log(string,address,address,address)", p0, p1, p2, p3));
ignored;
}
function log(bool p0, uint p1, uint p2, uint p3) internal view {
(bool ignored, ) = CONSOLE_ADDRESS.staticcall(abi.encodeWithSignature("log(bool,uint,uint,uint)", p0, p1, p2, p3));
ignored;
}
function log(bool p0, uint p1, uint p2, string memory p3) internal view {
(bool ignored, ) = CONSOLE_ADDRESS.staticcall(abi.encodeWithSignature("log(bool,uint,uint,string)", p0, p1, p2, p3));
ignored;
}
function log(bool p0, uint p1, uint p2, bool p3) internal view {
(bool ignored, ) = CONSOLE_ADDRESS.staticcall(abi.encodeWithSignature("log(bool,uint,uint,bool)", p0, p1, p2, p3));
ignored;
}
function log(bool p0, uint p1, uint p2, address p3) internal view {
(bool ignored, ) = CONSOLE_ADDRESS.staticcall(abi.encodeWithSignature("log(bool,uint,uint,address)", p0, p1, p2, p3));
ignored;
}
function log(bool p0, uint p1, string memory p2, uint p3) internal view {
(bool ignored, ) = CONSOLE_ADDRESS.staticcall(abi.encodeWithSignature("log(bool,uint,string,uint)", p0, p1, p2, p3));
ignored;
}
function log(bool p0, uint p1, string memory p2, string memory p3) internal view {
(bool ignored, ) = CONSOLE_ADDRESS.staticcall(abi.encodeWithSignature("log(bool,uint,string,string)", p0, p1, p2, p3));
ignored;
}
function log(bool p0, uint p1, string memory p2, bool p3) internal view {
(bool ignored, ) = CONSOLE_ADDRESS.staticcall(abi.encodeWithSignature("log(bool,uint,string,bool)", p0, p1, p2, p3));
ignored;
}
function log(bool p0, uint p1, string memory p2, address p3) internal view {
(bool ignored, ) = CONSOLE_ADDRESS.staticcall(abi.encodeWithSignature("log(bool,uint,string,address)", p0, p1, p2, p3));
ignored;
}
function log(bool p0, uint p1, bool p2, uint p3) internal view {
(bool ignored, ) = CONSOLE_ADDRESS.staticcall(abi.encodeWithSignature("log(bool,uint,bool,uint)", p0, p1, p2, p3));
ignored;
}
function log(bool p0, uint p1, bool p2, string memory p3) internal view {
(bool ignored, ) = CONSOLE_ADDRESS.staticcall(abi.encodeWithSignature("log(bool,uint,bool,string)", p0, p1, p2, p3));
ignored;
}
function log(bool p0, uint p1, bool p2, bool p3) internal view {
(bool ignored, ) = CONSOLE_ADDRESS.staticcall(abi.encodeWithSignature("log(bool,uint,bool,bool)", p0, p1, p2, p3));
ignored;
}
function log(bool p0, uint p1, bool p2, address p3) internal view {
(bool ignored, ) = CONSOLE_ADDRESS.staticcall(abi.encodeWithSignature("log(bool,uint,bool,address)", p0, p1, p2, p3));
ignored;
}
function log(bool p0, uint p1, address p2, uint p3) internal view {
(bool ignored, ) = CONSOLE_ADDRESS.staticcall(abi.encodeWithSignature("log(bool,uint,address,uint)", p0, p1, p2, p3));
ignored;
}
function log(bool p0, uint p1, address p2, string memory p3) internal view {
(bool ignored, ) = CONSOLE_ADDRESS.staticcall(abi.encodeWithSignature("log(bool,uint,address,string)", p0, p1, p2, p3));
ignored;
}
function log(bool p0, uint p1, address p2, bool p3) internal view {
(bool ignored, ) = CONSOLE_ADDRESS.staticcall(abi.encodeWithSignature("log(bool,uint,address,bool)", p0, p1, p2, p3));
ignored;
}
function log(bool p0, uint p1, address p2, address p3) internal view {
(bool ignored, ) = CONSOLE_ADDRESS.staticcall(abi.encodeWithSignature("log(bool,uint,address,address)", p0, p1, p2, p3));
ignored;
}
function log(bool p0, string memory p1, uint p2, uint p3) internal view {
(bool ignored, ) = CONSOLE_ADDRESS.staticcall(abi.encodeWithSignature("log(bool,string,uint,uint)", p0, p1, p2, p3));
ignored;
}
function log(bool p0, string memory p1, uint p2, string memory p3) internal view {
(bool ignored, ) = CONSOLE_ADDRESS.staticcall(abi.encodeWithSignature("log(bool,string,uint,string)", p0, p1, p2, p3));
ignored;
}
function log(bool p0, string memory p1, uint p2, bool p3) internal view {
(bool ignored, ) = CONSOLE_ADDRESS.staticcall(abi.encodeWithSignature("log(bool,string,uint,bool)", p0, p1, p2, p3));
ignored;
}
function log(bool p0, string memory p1, uint p2, address p3) internal view {
(bool ignored, ) = CONSOLE_ADDRESS.staticcall(abi.encodeWithSignature("log(bool,string,uint,address)", p0, p1, p2, p3));
ignored;
}
function log(bool p0, string memory p1, string memory p2, uint p3) internal view {
(bool ignored, ) = CONSOLE_ADDRESS.staticcall(abi.encodeWithSignature("log(bool,string,string,uint)", p0, p1, p2, p3));
ignored;
}
function log(bool p0, string memory p1, string memory p2, string memory p3) internal view {
(bool ignored, ) = CONSOLE_ADDRESS.staticcall(abi.encodeWithSignature("log(bool,string,string,string)", p0, p1, p2, p3));
ignored;
}
function log(bool p0, string memory p1, string memory p2, bool p3) internal view {
(bool ignored, ) = CONSOLE_ADDRESS.staticcall(abi.encodeWithSignature("log(bool,string,string,bool)", p0, p1, p2, p3));
ignored;
}
function log(bool p0, string memory p1, string memory p2, address p3) internal view {
(bool ignored, ) = CONSOLE_ADDRESS.staticcall(abi.encodeWithSignature("log(bool,string,string,address)", p0, p1, p2, p3));
ignored;
}
function log(bool p0, string memory p1, bool p2, uint p3) internal view {
(bool ignored, ) = CONSOLE_ADDRESS.staticcall(abi.encodeWithSignature("log(bool,string,bool,uint)", p0, p1, p2, p3));
ignored;
}
function log(bool p0, string memory p1, bool p2, string memory p3) internal view {
(bool ignored, ) = CONSOLE_ADDRESS.staticcall(abi.encodeWithSignature("log(bool,string,bool,string)", p0, p1, p2, p3));
ignored;
}
function log(bool p0, string memory p1, bool p2, bool p3) internal view {
(bool ignored, ) = CONSOLE_ADDRESS.staticcall(abi.encodeWithSignature("log(bool,string,bool,bool)", p0, p1, p2, p3));
ignored;
}
function log(bool p0, string memory p1, bool p2, address p3) internal view {
(bool ignored, ) = CONSOLE_ADDRESS.staticcall(abi.encodeWithSignature("log(bool,string,bool,address)", p0, p1, p2, p3));
ignored;
}
function log(bool p0, string memory p1, address p2, uint p3) internal view {
(bool ignored, ) = CONSOLE_ADDRESS.staticcall(abi.encodeWithSignature("log(bool,string,address,uint)", p0, p1, p2, p3));
ignored;
}
function log(bool p0, string memory p1, address p2, string memory p3) internal view {
(bool ignored, ) = CONSOLE_ADDRESS.staticcall(abi.encodeWithSignature("log(bool,string,address,string)", p0, p1, p2, p3));
ignored;
}
function log(bool p0, string memory p1, address p2, bool p3) internal view {
(bool ignored, ) = CONSOLE_ADDRESS.staticcall(abi.encodeWithSignature("log(bool,string,address,bool)", p0, p1, p2, p3));
ignored;
}
function log(bool p0, string memory p1, address p2, address p3) internal view {
(bool ignored, ) = CONSOLE_ADDRESS.staticcall(abi.encodeWithSignature("log(bool,string,address,address)", p0, p1, p2, p3));
ignored;
}
function log(bool p0, bool p1, uint p2, uint p3) internal view {
(bool ignored, ) = CONSOLE_ADDRESS.staticcall(abi.encodeWithSignature("log(bool,bool,uint,uint)", p0, p1, p2, p3));
ignored;
}
function log(bool p0, bool p1, uint p2, string memory p3) internal view {
(bool ignored, ) = CONSOLE_ADDRESS.staticcall(abi.encodeWithSignature("log(bool,bool,uint,string)", p0, p1, p2, p3));
ignored;
}
function log(bool p0, bool p1, uint p2, bool p3) internal view {
(bool ignored, ) = CONSOLE_ADDRESS.staticcall(abi.encodeWithSignature("log(bool,bool,uint,bool)", p0, p1, p2, p3));
ignored;
}
function log(bool p0, bool p1, uint p2, address p3) internal view {
(bool ignored, ) = CONSOLE_ADDRESS.staticcall(abi.encodeWithSignature("log(bool,bool,uint,address)", p0, p1, p2, p3));
ignored;
}
function log(bool p0, bool p1, string memory p2, uint p3) internal view {
(bool ignored, ) = CONSOLE_ADDRESS.staticcall(abi.encodeWithSignature("log(bool,bool,string,uint)", p0, p1, p2, p3));
ignored;
}
function log(bool p0, bool p1, string memory p2, string memory p3) internal view {
(bool ignored, ) = CONSOLE_ADDRESS.staticcall(abi.encodeWithSignature("log(bool,bool,string,string)", p0, p1, p2, p3));
ignored;
}
function log(bool p0, bool p1, string memory p2, bool p3) internal view {
(bool ignored, ) = CONSOLE_ADDRESS.staticcall(abi.encodeWithSignature("log(bool,bool,string,bool)", p0, p1, p2, p3));
ignored;
}
function log(bool p0, bool p1, string memory p2, address p3) internal view {
(bool ignored, ) = CONSOLE_ADDRESS.staticcall(abi.encodeWithSignature("log(bool,bool,string,address)", p0, p1, p2, p3));
ignored;
}
function log(bool p0, bool p1, bool p2, uint p3) internal view {
(bool ignored, ) = CONSOLE_ADDRESS.staticcall(abi.encodeWithSignature("log(bool,bool,bool,uint)", p0, p1, p2, p3));
ignored;
}
function log(bool p0, bool p1, bool p2, string memory p3) internal view {
(bool ignored, ) = CONSOLE_ADDRESS.staticcall(abi.encodeWithSignature("log(bool,bool,bool,string)", p0, p1, p2, p3));
ignored;
}
function log(bool p0, bool p1, bool p2, bool p3) internal view {
(bool ignored, ) = CONSOLE_ADDRESS.staticcall(abi.encodeWithSignature("log(bool,bool,bool,bool)", p0, p1, p2, p3));
ignored;
}
function log(bool p0, bool p1, bool p2, address p3) internal view {
(bool ignored, ) = CONSOLE_ADDRESS.staticcall(abi.encodeWithSignature("log(bool,bool,bool,address)", p0, p1, p2, p3));
ignored;
}
function log(bool p0, bool p1, address p2, uint p3) internal view {
(bool ignored, ) = CONSOLE_ADDRESS.staticcall(abi.encodeWithSignature("log(bool,bool,address,uint)", p0, p1, p2, p3));
ignored;
}
function log(bool p0, bool p1, address p2, string memory p3) internal view {
(bool ignored, ) = CONSOLE_ADDRESS.staticcall(abi.encodeWithSignature("log(bool,bool,address,string)", p0, p1, p2, p3));
ignored;
}
function log(bool p0, bool p1, address p2, bool p3) internal view {
(bool ignored, ) = CONSOLE_ADDRESS.staticcall(abi.encodeWithSignature("log(bool,bool,address,bool)", p0, p1, p2, p3));
ignored;
}
function log(bool p0, bool p1, address p2, address p3) internal view {
(bool ignored, ) = CONSOLE_ADDRESS.staticcall(abi.encodeWithSignature("log(bool,bool,address,address)", p0, p1, p2, p3));
ignored;
}
function log(bool p0, address p1, uint p2, uint p3) internal view {
(bool ignored, ) = CONSOLE_ADDRESS.staticcall(abi.encodeWithSignature("log(bool,address,uint,uint)", p0, p1, p2, p3));
ignored;
}
function log(bool p0, address p1, uint p2, string memory p3) internal view {
(bool ignored, ) = CONSOLE_ADDRESS.staticcall(abi.encodeWithSignature("log(bool,address,uint,string)", p0, p1, p2, p3));
ignored;
}
function log(bool p0, address p1, uint p2, bool p3) internal view {
(bool ignored, ) = CONSOLE_ADDRESS.staticcall(abi.encodeWithSignature("log(bool,address,uint,bool)", p0, p1, p2, p3));
ignored;
}
function log(bool p0, address p1, uint p2, address p3) internal view {
(bool ignored, ) = CONSOLE_ADDRESS.staticcall(abi.encodeWithSignature("log(bool,address,uint,address)", p0, p1, p2, p3));
ignored;
}
function log(bool p0, address p1, string memory p2, uint p3) internal view {
(bool ignored, ) = CONSOLE_ADDRESS.staticcall(abi.encodeWithSignature("log(bool,address,string,uint)", p0, p1, p2, p3));
ignored;
}
function log(bool p0, address p1, string memory p2, string memory p3) internal view {
(bool ignored, ) = CONSOLE_ADDRESS.staticcall(abi.encodeWithSignature("log(bool,address,string,string)", p0, p1, p2, p3));
ignored;
}
function log(bool p0, address p1, string memory p2, bool p3) internal view {
(bool ignored, ) = CONSOLE_ADDRESS.staticcall(abi.encodeWithSignature("log(bool,address,string,bool)", p0, p1, p2, p3));
ignored;
}
function log(bool p0, address p1, string memory p2, address p3) internal view {
(bool ignored, ) = CONSOLE_ADDRESS.staticcall(abi.encodeWithSignature("log(bool,address,string,address)", p0, p1, p2, p3));
ignored;
}
function log(bool p0, address p1, bool p2, uint p3) internal view {
(bool ignored, ) = CONSOLE_ADDRESS.staticcall(abi.encodeWithSignature("log(bool,address,bool,uint)", p0, p1, p2, p3));
ignored;
}
function log(bool p0, address p1, bool p2, string memory p3) internal view {
(bool ignored, ) = CONSOLE_ADDRESS.staticcall(abi.encodeWithSignature("log(bool,address,bool,string)", p0, p1, p2, p3));
ignored;
}
function log(bool p0, address p1, bool p2, bool p3) internal view {
(bool ignored, ) = CONSOLE_ADDRESS.staticcall(abi.encodeWithSignature("log(bool,address,bool,bool)", p0, p1, p2, p3));
ignored;
}
function log(bool p0, address p1, bool p2, address p3) internal view {
(bool ignored, ) = CONSOLE_ADDRESS.staticcall(abi.encodeWithSignature("log(bool,address,bool,address)", p0, p1, p2, p3));
ignored;
}
function log(bool p0, address p1, address p2, uint p3) internal view {
(bool ignored, ) = CONSOLE_ADDRESS.staticcall(abi.encodeWithSignature("log(bool,address,address,uint)", p0, p1, p2, p3));
ignored;
}
function log(bool p0, address p1, address p2, string memory p3) internal view {
(bool ignored, ) = CONSOLE_ADDRESS.staticcall(abi.encodeWithSignature("log(bool,address,address,string)", p0, p1, p2, p3));
ignored;
}
function log(bool p0, address p1, address p2, bool p3) internal view {
(bool ignored, ) = CONSOLE_ADDRESS.staticcall(abi.encodeWithSignature("log(bool,address,address,bool)", p0, p1, p2, p3));
ignored;
}
function log(bool p0, address p1, address p2, address p3) internal view {
(bool ignored, ) = CONSOLE_ADDRESS.staticcall(abi.encodeWithSignature("log(bool,address,address,address)", p0, p1, p2, p3));
ignored;
}
function log(address p0, uint p1, uint p2, uint p3) internal view {
(bool ignored, ) = CONSOLE_ADDRESS.staticcall(abi.encodeWithSignature("log(address,uint,uint,uint)", p0, p1, p2, p3));
ignored;
}
function log(address p0, uint p1, uint p2, string memory p3) internal view {
(bool ignored, ) = CONSOLE_ADDRESS.staticcall(abi.encodeWithSignature("log(address,uint,uint,string)", p0, p1, p2, p3));
ignored;
}
function log(address p0, uint p1, uint p2, bool p3) internal view {
(bool ignored, ) = CONSOLE_ADDRESS.staticcall(abi.encodeWithSignature("log(address,uint,uint,bool)", p0, p1, p2, p3));
ignored;
}
function log(address p0, uint p1, uint p2, address p3) internal view {
(bool ignored, ) = CONSOLE_ADDRESS.staticcall(abi.encodeWithSignature("log(address,uint,uint,address)", p0, p1, p2, p3));
ignored;
}
function log(address p0, uint p1, string memory p2, uint p3) internal view {
(bool ignored, ) = CONSOLE_ADDRESS.staticcall(abi.encodeWithSignature("log(address,uint,string,uint)", p0, p1, p2, p3));
ignored;
}
function log(address p0, uint p1, string memory p2, string memory p3) internal view {
(bool ignored, ) = CONSOLE_ADDRESS.staticcall(abi.encodeWithSignature("log(address,uint,string,string)", p0, p1, p2, p3));
ignored;
}
function log(address p0, uint p1, string memory p2, bool p3) internal view {
(bool ignored, ) = CONSOLE_ADDRESS.staticcall(abi.encodeWithSignature("log(address,uint,string,bool)", p0, p1, p2, p3));
ignored;
}
function log(address p0, uint p1, string memory p2, address p3) internal view {
(bool ignored, ) = CONSOLE_ADDRESS.staticcall(abi.encodeWithSignature("log(address,uint,string,address)", p0, p1, p2, p3));
ignored;
}
function log(address p0, uint p1, bool p2, uint p3) internal view {
(bool ignored, ) = CONSOLE_ADDRESS.staticcall(abi.encodeWithSignature("log(address,uint,bool,uint)", p0, p1, p2, p3));
ignored;
}
function log(address p0, uint p1, bool p2, string memory p3) internal view {
(bool ignored, ) = CONSOLE_ADDRESS.staticcall(abi.encodeWithSignature("log(address,uint,bool,string)", p0, p1, p2, p3));
ignored;
}
function log(address p0, uint p1, bool p2, bool p3) internal view {
(bool ignored, ) = CONSOLE_ADDRESS.staticcall(abi.encodeWithSignature("log(address,uint,bool,bool)", p0, p1, p2, p3));
ignored;
}
function log(address p0, uint p1, bool p2, address p3) internal view {
(bool ignored, ) = CONSOLE_ADDRESS.staticcall(abi.encodeWithSignature("log(address,uint,bool,address)", p0, p1, p2, p3));
ignored;
}
function log(address p0, uint p1, address p2, uint p3) internal view {
(bool ignored, ) = CONSOLE_ADDRESS.staticcall(abi.encodeWithSignature("log(address,uint,address,uint)", p0, p1, p2, p3));
ignored;
}
function log(address p0, uint p1, address p2, string memory p3) internal view {
(bool ignored, ) = CONSOLE_ADDRESS.staticcall(abi.encodeWithSignature("log(address,uint,address,string)", p0, p1, p2, p3));
ignored;
}
function log(address p0, uint p1, address p2, bool p3) internal view {
(bool ignored, ) = CONSOLE_ADDRESS.staticcall(abi.encodeWithSignature("log(address,uint,address,bool)", p0, p1, p2, p3));
ignored;
}
function log(address p0, uint p1, address p2, address p3) internal view {
(bool ignored, ) = CONSOLE_ADDRESS.staticcall(abi.encodeWithSignature("log(address,uint,address,address)", p0, p1, p2, p3));
ignored;
}
function log(address p0, string memory p1, uint p2, uint p3) internal view {
(bool ignored, ) = CONSOLE_ADDRESS.staticcall(abi.encodeWithSignature("log(address,string,uint,uint)", p0, p1, p2, p3));
ignored;
}
function log(address p0, string memory p1, uint p2, string memory p3) internal view {
(bool ignored, ) = CONSOLE_ADDRESS.staticcall(abi.encodeWithSignature("log(address,string,uint,string)", p0, p1, p2, p3));
ignored;
}
function log(address p0, string memory p1, uint p2, bool p3) internal view {
(bool ignored, ) = CONSOLE_ADDRESS.staticcall(abi.encodeWithSignature("log(address,string,uint,bool)", p0, p1, p2, p3));
ignored;
}
function log(address p0, string memory p1, uint p2, address p3) internal view {
(bool ignored, ) = CONSOLE_ADDRESS.staticcall(abi.encodeWithSignature("log(address,string,uint,address)", p0, p1, p2, p3));
ignored;
}
function log(address p0, string memory p1, string memory p2, uint p3) internal view {
(bool ignored, ) = CONSOLE_ADDRESS.staticcall(abi.encodeWithSignature("log(address,string,string,uint)", p0, p1, p2, p3));
ignored;
}
function log(address p0, string memory p1, string memory p2, string memory p3) internal view {
(bool ignored, ) = CONSOLE_ADDRESS.staticcall(abi.encodeWithSignature("log(address,string,string,string)", p0, p1, p2, p3));
ignored;
}
function log(address p0, string memory p1, string memory p2, bool p3) internal view {
(bool ignored, ) = CONSOLE_ADDRESS.staticcall(abi.encodeWithSignature("log(address,string,string,bool)", p0, p1, p2, p3));
ignored;
}
function log(address p0, string memory p1, string memory p2, address p3) internal view {
(bool ignored, ) = CONSOLE_ADDRESS.staticcall(abi.encodeWithSignature("log(address,string,string,address)", p0, p1, p2, p3));
ignored;
}
function log(address p0, string memory p1, bool p2, uint p3) internal view {
(bool ignored, ) = CONSOLE_ADDRESS.staticcall(abi.encodeWithSignature("log(address,string,bool,uint)", p0, p1, p2, p3));
ignored;
}
function log(address p0, string memory p1, bool p2, string memory p3) internal view {
(bool ignored, ) = CONSOLE_ADDRESS.staticcall(abi.encodeWithSignature("log(address,string,bool,string)", p0, p1, p2, p3));
ignored;
}
function log(address p0, string memory p1, bool p2, bool p3) internal view {
(bool ignored, ) = CONSOLE_ADDRESS.staticcall(abi.encodeWithSignature("log(address,string,bool,bool)", p0, p1, p2, p3));
ignored;
}
function log(address p0, string memory p1, bool p2, address p3) internal view {
(bool ignored, ) = CONSOLE_ADDRESS.staticcall(abi.encodeWithSignature("log(address,string,bool,address)", p0, p1, p2, p3));
ignored;
}
function log(address p0, string memory p1, address p2, uint p3) internal view {
(bool ignored, ) = CONSOLE_ADDRESS.staticcall(abi.encodeWithSignature("log(address,string,address,uint)", p0, p1, p2, p3));
ignored;
}
function log(address p0, string memory p1, address p2, string memory p3) internal view {
(bool ignored, ) = CONSOLE_ADDRESS.staticcall(abi.encodeWithSignature("log(address,string,address,string)", p0, p1, p2, p3));
ignored;
}
function log(address p0, string memory p1, address p2, bool p3) internal view {
(bool ignored, ) = CONSOLE_ADDRESS.staticcall(abi.encodeWithSignature("log(address,string,address,bool)", p0, p1, p2, p3));
ignored;
}
function log(address p0, string memory p1, address p2, address p3) internal view {
(bool ignored, ) = CONSOLE_ADDRESS.staticcall(abi.encodeWithSignature("log(address,string,address,address)", p0, p1, p2, p3));
ignored;
}
function log(address p0, bool p1, uint p2, uint p3) internal view {
(bool ignored, ) = CONSOLE_ADDRESS.staticcall(abi.encodeWithSignature("log(address,bool,uint,uint)", p0, p1, p2, p3));
ignored;
}
function log(address p0, bool p1, uint p2, string memory p3) internal view {
(bool ignored, ) = CONSOLE_ADDRESS.staticcall(abi.encodeWithSignature("log(address,bool,uint,string)", p0, p1, p2, p3));
ignored;
}
function log(address p0, bool p1, uint p2, bool p3) internal view {
(bool ignored, ) = CONSOLE_ADDRESS.staticcall(abi.encodeWithSignature("log(address,bool,uint,bool)", p0, p1, p2, p3));
ignored;
}
function log(address p0, bool p1, uint p2, address p3) internal view {
(bool ignored, ) = CONSOLE_ADDRESS.staticcall(abi.encodeWithSignature("log(address,bool,uint,address)", p0, p1, p2, p3));
ignored;
}
function log(address p0, bool p1, string memory p2, uint p3) internal view {
(bool ignored, ) = CONSOLE_ADDRESS.staticcall(abi.encodeWithSignature("log(address,bool,string,uint)", p0, p1, p2, p3));
ignored;
}
function log(address p0, bool p1, string memory p2, string memory p3) internal view {
(bool ignored, ) = CONSOLE_ADDRESS.staticcall(abi.encodeWithSignature("log(address,bool,string,string)", p0, p1, p2, p3));
ignored;
}
function log(address p0, bool p1, string memory p2, bool p3) internal view {
(bool ignored, ) = CONSOLE_ADDRESS.staticcall(abi.encodeWithSignature("log(address,bool,string,bool)", p0, p1, p2, p3));
ignored;
}
function log(address p0, bool p1, string memory p2, address p3) internal view {
(bool ignored, ) = CONSOLE_ADDRESS.staticcall(abi.encodeWithSignature("log(address,bool,string,address)", p0, p1, p2, p3));
ignored;
}
function log(address p0, bool p1, bool p2, uint p3) internal view {
(bool ignored, ) = CONSOLE_ADDRESS.staticcall(abi.encodeWithSignature("log(address,bool,bool,uint)", p0, p1, p2, p3));
ignored;
}
function log(address p0, bool p1, bool p2, string memory p3) internal view {
(bool ignored, ) = CONSOLE_ADDRESS.staticcall(abi.encodeWithSignature("log(address,bool,bool,string)", p0, p1, p2, p3));
ignored;
}
function log(address p0, bool p1, bool p2, bool p3) internal view {
(bool ignored, ) = CONSOLE_ADDRESS.staticcall(abi.encodeWithSignature("log(address,bool,bool,bool)", p0, p1, p2, p3));
ignored;
}
function log(address p0, bool p1, bool p2, address p3) internal view {
(bool ignored, ) = CONSOLE_ADDRESS.staticcall(abi.encodeWithSignature("log(address,bool,bool,address)", p0, p1, p2, p3));
ignored;
}
function log(address p0, bool p1, address p2, uint p3) internal view {
(bool ignored, ) = CONSOLE_ADDRESS.staticcall(abi.encodeWithSignature("log(address,bool,address,uint)", p0, p1, p2, p3));
ignored;
}
function log(address p0, bool p1, address p2, string memory p3) internal view {
(bool ignored, ) = CONSOLE_ADDRESS.staticcall(abi.encodeWithSignature("log(address,bool,address,string)", p0, p1, p2, p3));
ignored;
}
function log(address p0, bool p1, address p2, bool p3) internal view {
(bool ignored, ) = CONSOLE_ADDRESS.staticcall(abi.encodeWithSignature("log(address,bool,address,bool)", p0, p1, p2, p3));
ignored;
}
function log(address p0, bool p1, address p2, address p3) internal view {
(bool ignored, ) = CONSOLE_ADDRESS.staticcall(abi.encodeWithSignature("log(address,bool,address,address)", p0, p1, p2, p3));
ignored;
}
function log(address p0, address p1, uint p2, uint p3) internal view {
(bool ignored, ) = CONSOLE_ADDRESS.staticcall(abi.encodeWithSignature("log(address,address,uint,uint)", p0, p1, p2, p3));
ignored;
}
function log(address p0, address p1, uint p2, string memory p3) internal view {
(bool ignored, ) = CONSOLE_ADDRESS.staticcall(abi.encodeWithSignature("log(address,address,uint,string)", p0, p1, p2, p3));
ignored;
}
function log(address p0, address p1, uint p2, bool p3) internal view {
(bool ignored, ) = CONSOLE_ADDRESS.staticcall(abi.encodeWithSignature("log(address,address,uint,bool)", p0, p1, p2, p3));
ignored;
}
function log(address p0, address p1, uint p2, address p3) internal view {
(bool ignored, ) = CONSOLE_ADDRESS.staticcall(abi.encodeWithSignature("log(address,address,uint,address)", p0, p1, p2, p3));
ignored;
}
function log(address p0, address p1, string memory p2, uint p3) internal view {
(bool ignored, ) = CONSOLE_ADDRESS.staticcall(abi.encodeWithSignature("log(address,address,string,uint)", p0, p1, p2, p3));
ignored;
}
function log(address p0, address p1, string memory p2, string memory p3) internal view {
(bool ignored, ) = CONSOLE_ADDRESS.staticcall(abi.encodeWithSignature("log(address,address,string,string)", p0, p1, p2, p3));
ignored;
}
function log(address p0, address p1, string memory p2, bool p3) internal view {
(bool ignored, ) = CONSOLE_ADDRESS.staticcall(abi.encodeWithSignature("log(address,address,string,bool)", p0, p1, p2, p3));
ignored;
}
function log(address p0, address p1, string memory p2, address p3) internal view {
(bool ignored, ) = CONSOLE_ADDRESS.staticcall(abi.encodeWithSignature("log(address,address,string,address)", p0, p1, p2, p3));
ignored;
}
function log(address p0, address p1, bool p2, uint p3) internal view {
(bool ignored, ) = CONSOLE_ADDRESS.staticcall(abi.encodeWithSignature("log(address,address,bool,uint)", p0, p1, p2, p3));
ignored;
}
function log(address p0, address p1, bool p2, string memory p3) internal view {
(bool ignored, ) = CONSOLE_ADDRESS.staticcall(abi.encodeWithSignature("log(address,address,bool,string)", p0, p1, p2, p3));
ignored;
}
function log(address p0, address p1, bool p2, bool p3) internal view {
(bool ignored, ) = CONSOLE_ADDRESS.staticcall(abi.encodeWithSignature("log(address,address,bool,bool)", p0, p1, p2, p3));
ignored;
}
function log(address p0, address p1, bool p2, address p3) internal view {
(bool ignored, ) = CONSOLE_ADDRESS.staticcall(abi.encodeWithSignature("log(address,address,bool,address)", p0, p1, p2, p3));
ignored;
}
function log(address p0, address p1, address p2, uint p3) internal view {
(bool ignored, ) = CONSOLE_ADDRESS.staticcall(abi.encodeWithSignature("log(address,address,address,uint)", p0, p1, p2, p3));
ignored;
}
function log(address p0, address p1, address p2, string memory p3) internal view {
(bool ignored, ) = CONSOLE_ADDRESS.staticcall(abi.encodeWithSignature("log(address,address,address,string)", p0, p1, p2, p3));
ignored;
}
function log(address p0, address p1, address p2, bool p3) internal view {
(bool ignored, ) = CONSOLE_ADDRESS.staticcall(abi.encodeWithSignature("log(address,address,address,bool)", p0, p1, p2, p3));
ignored;
}
function log(address p0, address p1, address p2, address p3) internal view {
(bool ignored, ) = CONSOLE_ADDRESS.staticcall(abi.encodeWithSignature("log(address,address,address,address)", p0, p1, p2, p3));
ignored;
}
}
// File contracts/Dependencies/LiquityMath.sol
library LiquityMath {
using SafeMath for uint;
uint internal constant DECIMAL_PRECISION = 1e18;
/* Precision for Nominal ICR (independent of price). Rationale for the value:
*
* - Making it “too high” could lead to overflows.
* - Making it “too low” could lead to an ICR equal to zero, due to truncation from Solidity floor division.
*
* This value of 1e20 is chosen for safety: the NICR will only overflow for numerator > ~1e39 ETH,
* and will only truncate to 0 if the denominator is at least 1e20 times greater than the numerator.
*
*/
uint internal constant NICR_PRECISION = 1e20;
function _min(uint _a, uint _b) internal pure returns (uint) {
return (_a < _b) ? _a : _b;
}
function _max(uint _a, uint _b) internal pure returns (uint) {
return (_a >= _b) ? _a : _b;
}
/*
* Multiply two decimal numbers and use normal rounding rules:
* -round product up if 19'th mantissa digit >= 5
* -round product down if 19'th mantissa digit < 5
*
* Used only inside the exponentiation, _decPow().
*/
function decMul(uint x, uint y) internal pure returns (uint decProd) {
uint prod_xy = x.mul(y);
decProd = prod_xy.add(DECIMAL_PRECISION / 2).div(DECIMAL_PRECISION);
}
/*
* _decPow: Exponentiation function for 18-digit decimal base, and integer exponent n.
*
* Uses the efficient "exponentiation by squaring" algorithm. O(log(n)) complexity.
*
* Called by two functions that represent time in units of minutes:
* 1) TroveManager._calcDecayedBaseRate
* 2) CommunityIssuance._getCumulativeIssuanceFraction
*
* The exponent is capped to avoid reverting due to overflow. The cap 525600000 equals
* "minutes in 1000 years": 60 * 24 * 365 * 1000
*
* If a period of > 1000 years is ever used as an exponent in either of the above functions, the result will be
* negligibly different from just passing the cap, since:
*
* In function 1), the decayed base rate will be 0 for 1000 years or > 1000 years
* In function 2), the difference in tokens issued at 1000 years and any time > 1000 years, will be negligible
*/
function _decPow(uint _base, uint _minutes) internal pure returns (uint) {
if (_minutes > 525600000) {_minutes = 525600000;} // cap to avoid overflow
if (_minutes == 0) {return DECIMAL_PRECISION;}
uint y = DECIMAL_PRECISION;
uint x = _base;
uint n = _minutes;
// Exponentiation-by-squaring
while (n > 1) {
if (n % 2 == 0) {
x = decMul(x, x);
n = n.div(2);
} else { // if (n % 2 != 0)
y = decMul(x, y);
x = decMul(x, x);
n = (n.sub(1)).div(2);
}
}
return decMul(x, y);
}
function _getAbsoluteDifference(uint _a, uint _b) internal pure returns (uint) {
return (_a >= _b) ? _a.sub(_b) : _b.sub(_a);
}
function _computeNominalCR(uint _coll, uint _debt, uint _collDecimalAdjustment) internal pure returns (uint) {
if (_debt > 0) {
return _coll.mul(_collDecimalAdjustment).mul(NICR_PRECISION).div(_debt);
}
// Return the maximal value for uint256 if the Trove has a debt of 0. Represents "infinite" CR.
else { // if (_debt == 0)
return 2**256 - 1;
}
}
function _computeCR(uint _coll, uint _debt, uint _price, uint _collDecimalAdjustment) internal pure returns (uint) {
if (_debt > 0) {
uint newCollRatio = _coll.mul(_collDecimalAdjustment).mul(_price).div(_debt);
return newCollRatio;
}
// Return the maximal value for uint256 if the Trove has a debt of 0. Represents "infinite" CR.
else { // if (_debt == 0)
return 2**256 - 1;
}
}
}
// File contracts/Interfaces/IPool.sol
// Common interface for the Pools.
interface IPool {
// --- Events ---
event ETHBalanceUpdated(uint _newBalance);
event LUSDBalanceUpdated(uint _newBalance);
event ActivePoolAddressChanged(address _newActivePoolAddress);
event DefaultPoolAddressChanged(address _newDefaultPoolAddress);
event StabilityPoolAddressChanged(address _newStabilityPoolAddress);
event EtherSent(address _to, uint _amount);
// --- Functions ---
function getETH() external view returns (uint);
function getLUSDDebt() external view returns (uint);
function increaseLUSDDebt(uint _amount) external;
function depositColl(uint _amount) external;
function decreaseLUSDDebt(uint _amount) external;
}
// File contracts/Interfaces/IActivePool.sol
interface IActivePool is IPool {
// --- Events ---
event BorrowerOperationsAddressChanged(address _newBorrowerOperationsAddress);
event TroveManagerAddressChanged(address _newTroveManagerAddress);
event ActivePoolLUSDDebtUpdated(uint _LUSDDebt);
event ActivePoolETHBalanceUpdated(uint _ETH);
event CollAddressChanged(address _wethTokenAddress);
// --- Functions ---
function sendETH(address _account, uint _amount) external;
function notifyFee(address _feeForwarderAddress, uint _amount) external;
}
// File contracts/Interfaces/IStableCollActivePool.sol
interface IStableCollActivePool is IPool {
// --- Events ---
event StableCollBorrowerOperationsAddressChanged(address _newStableCollBorrowerOperationsAddress);
event StableCollTroveManagerAddressChanged(address _newStableCollTroveManagerAddress);
event StableCollActivePoolLUSDDebtUpdated(uint _LUSDDebt);
event StableCollActivePoolETHBalanceUpdated(uint _ETH);
event CollAddressChanged(address _collTokenAddress);
// --- Functions ---
function sendETH(address _account, uint _amount) external;
}
// File contracts/Interfaces/IDefaultPool.sol
interface IDefaultPool is IPool {
// --- Events ---
event TroveManagerAddressChanged(address _newTroveManagerAddress);
event DefaultPoolLUSDDebtUpdated(uint _LUSDDebt);
event DefaultPoolETHBalanceUpdated(uint _ETH);
event CollTokenAddressUpdated(address _collTokenAddress);
// --- Functions ---
function sendETHToActivePool(uint _amount) external;
}
// File contracts/Dependencies/LiquityBase.sol
/*
* Base contract for TroveManager, BorrowerOperations and StabilityPool. Contains global system constants and
* common functions.
*/
contract LiquityBase is BaseMath, ILiquityBase {
using SafeMath for uint;
uint constant public _100pct = 1000000000000000000; // 1e18 == 100%
// Minimum collateral ratio for individual troves
uint constant public MCR = 1100000000000000000; // 110%
// Minimum stablecoin collateral ratio for individual troves
uint constant public MSCR = 1000000000000000000; // 100%
// Critical system collateral ratio. If the system's total collateral ratio (TCR) falls below the CCR, Recovery Mode is triggered.
uint constant public CCR = 1500000000000000000; // 150%
// Amount of LUSD to be locked in gas pool on opening troves
uint constant public LUSD_GAS_COMPENSATION = 400e18;
// Minimum amount of net LUSD debt a trove must have
uint constant public MIN_NET_DEBT = 2000e18;
uint constant public PERCENT_DIVISOR = 200; // dividing by 200 yields 0.5%
uint constant public STABLE_COLL_BORROWING_RATE = DECIMAL_PRECISION / 100; // 1%
uint constant public STABLE_COLL_COLLATERAL_RARIO = 1010000000000000000; // 101%
uint constant public STABLE_COLL_COLLATERAL_RARIO_DIVIDEND = 101;
uint constant public STABLE_COLL_COLLATERAL_RARIO_DIVISOR = 100;
uint constant public STABLE_COLL_DEBT_CEILING = DECIMAL_PRECISION * 1e4; // 10,000
uint constant public COLL_DEBT_CEILING = DECIMAL_PRECISION * 1e4; // 10,000
uint constant public BORROWING_FEE_FLOOR = DECIMAL_PRECISION / 1000 * 4; // 0.4%
IActivePool public activePool;
IStableCollActivePool public stableCollActivePool;
IDefaultPool public defaultPool;
IPriceFeed public override priceFeed;
// --- Gas compensation functions ---
// Returns the composite debt (drawn debt + gas compensation) of a trove, for the purpose of ICR calculation
function _getCompositeDebt(uint _debt) internal pure returns (uint) {
return _debt.add(LUSD_GAS_COMPENSATION);
}
function _getNetDebt(uint _debt) internal pure returns (uint) {
return _debt.sub(LUSD_GAS_COMPENSATION);
}
// Return the amount of ETH to be drawn from a trove's collateral and sent as gas compensation.
function _getCollGasCompensation(uint _entireColl) internal pure returns (uint) {
return _entireColl / PERCENT_DIVISOR;
}
function getEntireSystemColl() public view returns (uint) {
uint activeColl = activePool.getETH();
uint liquidatedColl = defaultPool.getETH();
return activeColl.add(liquidatedColl);
}
function getEntireSystemStableColl() public view returns (uint) {
return stableCollActivePool.getETH();
}
function getEntireSystemDebt() public view returns (uint) {
uint activeDebt = activePool.getLUSDDebt();
uint closedDebt = defaultPool.getLUSDDebt();
return activeDebt.add(closedDebt);
}
function getEntireSystemStableDebt() public view returns (uint) {
return stableCollActivePool.getLUSDDebt();
}
function _getTCR(uint _price, uint _collDecimalAdjustment) internal view returns (uint) {
uint entireSystemColl = getEntireSystemColl();
uint entireSystemDebt = getEntireSystemDebt();
uint TCR = LiquityMath._computeCR(entireSystemColl, entireSystemDebt, _price, _collDecimalAdjustment);
return TCR;
}
function _checkRecoveryMode(uint _price, uint _collDecimalAdjustment) internal view returns (bool) {
uint TCR = _getTCR(_price, _collDecimalAdjustment);
return TCR < CCR;
}
function _requireUserAcceptsFee(uint _fee, uint _amount, uint _maxFeePercentage) internal pure {
uint feePercentage = _fee.mul(DECIMAL_PRECISION).div(_amount);
require(feePercentage <= _maxFeePercentage, "Fee exceeded provided maximum");
}
}
// File contracts/Dependencies/Ownable.sol
/**
* Based on OpenZeppelin's Ownable contract:
* https://github.com/OpenZeppelin/openzeppelin-contracts/blob/master/contracts/access/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.
*
* 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 {
address private _owner;
event OwnershipTransferred(address indexed previousOwner, address indexed newOwner);
/**
* @dev Initializes the contract setting the deployer as the initial owner.
*/
constructor () internal {
_owner = msg.sender;
emit OwnershipTransferred(address(0), msg.sender);
}
/**
* @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 msg.sender == _owner;
}
/**
* @dev Leaves the contract without owner. It will not be possible to call
* `onlyOwner` functions anymore.
*
* NOTE: Renouncing ownership will leave the contract without an owner,
* thereby removing any functionality that is only available to the owner.
*
* NOTE: This function is not safe, as it doesn’t check owner is calling it.
* Make sure you check it before calling it.
*/
function _renounceOwnership() internal {
emit OwnershipTransferred(_owner, address(0));
_owner = address(0);
}
}
// File contracts/Dependencies/CheckContract.sol
contract CheckContract {
/**
* Check that the account is an already deployed non-destroyed contract.
* See: https://github.com/OpenZeppelin/openzeppelin-contracts/blob/master/contracts/utils/Address.sol#L12
*/
function checkContract(address _account) internal view {
require(_account != address(0), "Account cannot be zero address");
uint256 size;
// solhint-disable-next-line no-inline-assembly
assembly { size := extcodesize(_account) }
require(size > 0, "Account code size cannot be zero");
}
}
// File contracts/BorrowerOperations.sol
contract BorrowerOperations is LiquityBase, Ownable, CheckContract, IBorrowerOperations {
string constant public NAME = "BorrowerOperations";
// --- Connected contract declarations ---
ITroveManager public troveManager;
address public stabilityPoolAddress;
address public gasPoolAddress;
ICollSurplusPool public collSurplusPool;
ILUSDToken public LUSDToken;
IERC20 public collToken;
address public borrowingFeePoolAddress;
// A doubly linked list of Troves, sorted by their collateral ratios
ISortedTroves public sortedTroves;
uint internal _collDecimalAdjustment;
bool isAddressesSet = false;
/* --- Variable container structs ---
Used to hold, return and assign variables inside a function, in order to avoid the error:
"CompilerError: Stack too deep". */
struct LocalVariables_adjustTrove {
uint price;
uint collChange;
uint netDebtChange;
bool isCollIncrease;
uint debt;
uint coll;
uint oldICR;
uint newICR;
uint newTCR;
uint LUSDFee;
uint newDebt;
uint newColl;
uint stake;
uint debtCeiling;
}
struct LocalVariables_openTrove {
uint price;
uint LUSDFee;
uint netDebt;
uint compositeDebt;
uint ICR;
uint NICR;
uint stake;
uint arrayIndex;
uint debtCeiling;
}
struct ContractsCache {
ITroveManager troveManager;
IActivePool activePool;
ILUSDToken LUSDToken;
}
enum BorrowerOperation {
openTrove,
closeTrove,
adjustTrove
}
enum Functions { SET_ADDRESS, SET_BORROWING_FEE_POOL }
uint256 private constant _TIMELOCK = 2 days;
mapping(Functions => uint256) public timelock;
event TroveManagerAddressChanged(address _newTroveManagerAddress);
event ActivePoolAddressChanged(address _activePoolAddress);
event DefaultPoolAddressChanged(address _defaultPoolAddress);
event StabilityPoolAddressChanged(address _stabilityPoolAddress);
event GasPoolAddressChanged(address _gasPoolAddress);
event CollSurplusPoolAddressChanged(address _collSurplusPoolAddress);
event PriceFeedAddressChanged(address _newPriceFeedAddress);
event SortedTrovesAddressChanged(address _sortedTrovesAddress);
event CollTokenAddressChanged(address _collTokenAddress);
event BorrowingFeePoolAddressChanged(address _borrowingFeePoolAddress);
event FeeAdminAddressChanged(address _feeAdminAddress);
event TroveCreated(address indexed _borrower, uint arrayIndex);
event TroveUpdated(address indexed _borrower, uint _debt, uint _coll, uint stake, BorrowerOperation operation);
event LUSDBorrowingFeePaid(address indexed _borrower, uint _LUSDFee);
// --- Time lock
modifier notLocked(Functions _fn) {
require(
timelock[_fn] != 1 && timelock[_fn] <= block.timestamp,
"Function is timelocked"
);
_;
}
//unlock timelock
function unlockFunction(Functions _fn) public onlyOwner {
timelock[_fn] = block.timestamp + _TIMELOCK;
}
//lock timelock
function lockFunction(Functions _fn) public onlyOwner {
timelock[_fn] = 1;
}
// --- Dependency setters ---
function setAddresses(
address _troveManagerAddress,
address _activePoolAddress,
address _defaultPoolAddress,
address _stabilityPoolAddress,
address _gasPoolAddress,
address _collSurplusPoolAddress,
address _priceFeedAddress,
address _sortedTrovesAddress,
address _LUSDTokenAddress,
address _collTokenAddress,
uint collDecimalAdjustment
)
external
override
onlyOwner
notLocked(Functions.SET_ADDRESS)
{
require(!isAddressesSet, "BorrowerOperations: Addresses are already set!");
isAddressesSet = true;
// This makes impossible to open a trove with zero withdrawn LUSD
require(MIN_NET_DEBT > 0, "Minimum net debt amount must be larger than zero.");
checkContract(_troveManagerAddress);
checkContract(_activePoolAddress);
checkContract(_defaultPoolAddress);
checkContract(_stabilityPoolAddress);
checkContract(_gasPoolAddress);
checkContract(_collSurplusPoolAddress);
checkContract(_priceFeedAddress);
checkContract(_sortedTrovesAddress);
checkContract(_LUSDTokenAddress);
checkContract(_collTokenAddress);
troveManager = ITroveManager(_troveManagerAddress);
activePool = IActivePool(_activePoolAddress);
defaultPool = IDefaultPool(_defaultPoolAddress);
stabilityPoolAddress = _stabilityPoolAddress;
gasPoolAddress = _gasPoolAddress;
collSurplusPool = ICollSurplusPool(_collSurplusPoolAddress);
priceFeed = IPriceFeed(_priceFeedAddress);
sortedTroves = ISortedTroves(_sortedTrovesAddress);
LUSDToken = ILUSDToken(_LUSDTokenAddress);
collToken = IERC20(_collTokenAddress);
_collDecimalAdjustment = collDecimalAdjustment;
emit TroveManagerAddressChanged(_troveManagerAddress);
emit ActivePoolAddressChanged(_activePoolAddress);
emit DefaultPoolAddressChanged(_defaultPoolAddress);
emit StabilityPoolAddressChanged(_stabilityPoolAddress);
emit GasPoolAddressChanged(_gasPoolAddress);
emit CollSurplusPoolAddressChanged(_collSurplusPoolAddress);
emit PriceFeedAddressChanged(_priceFeedAddress);
emit SortedTrovesAddressChanged(_sortedTrovesAddress);
emit CollTokenAddressChanged(_collTokenAddress);
timelock[Functions.SET_ADDRESS] = 1;
}
function setBorrowingFeePoolAddress(address _borrowingFeePoolAddress) external onlyOwner override notLocked(Functions.SET_BORROWING_FEE_POOL) {
borrowingFeePoolAddress = _borrowingFeePoolAddress;
emit BorrowingFeePoolAddressChanged(_borrowingFeePoolAddress);
timelock[Functions.SET_BORROWING_FEE_POOL] = 1;
}
// --- Borrower Trove Operations ---
function openTrove(uint _maxFeePercentage, uint _LUSDAmount, uint _collAmount, address _upperHint, address _lowerHint) external override {
// Replace payable with an explicit token transfer.
require(collToken.transferFrom(msg.sender, address(this), _collAmount), "BorrowerOps: Collateral transfer failed on openTrove");
ContractsCache memory contractsCache = ContractsCache(troveManager, activePool, LUSDToken);
LocalVariables_openTrove memory vars;
vars.price = priceFeed.fetchPrice();
bool isRecoveryMode = _checkRecoveryMode(vars.price, _collDecimalAdjustment);
_requireValidMaxFeePercentage(_maxFeePercentage, isRecoveryMode);
_requireTroveisNotActive(contractsCache.troveManager, msg.sender);
vars.LUSDFee;
vars.netDebt = _LUSDAmount;
vars.debtCeiling = contractsCache.troveManager.getDebtCeiling();
if (!isRecoveryMode) {
vars.LUSDFee = _triggerBorrowingFee(contractsCache.troveManager, contractsCache.LUSDToken, _LUSDAmount, _maxFeePercentage);
vars.netDebt = vars.netDebt.add(vars.LUSDFee);
}
_requireAtLeastMinNetDebt(vars.netDebt);
_requireActivePoolDebtBelowDebtCeiling(vars.netDebt, getEntireSystemDebt(), vars.debtCeiling);
// ICR is based on the composite debt, i.e. the requested LUSD amount + LUSD borrowing fee + LUSD gas comp.
vars.compositeDebt = _getCompositeDebt(vars.netDebt);
require(vars.compositeDebt > 0, "Debt must be larger than zero.");
vars.ICR = LiquityMath._computeCR(_collAmount, vars.compositeDebt, vars.price, _collDecimalAdjustment);
vars.NICR = LiquityMath._computeNominalCR(_collAmount, vars.compositeDebt, _collDecimalAdjustment);
if (isRecoveryMode) {
_requireICRisAboveCCR(vars.ICR);
} else {
_requireICRisAboveMCR(vars.ICR);
uint newTCR = _getNewTCRFromTroveChange(_collAmount, true, vars.compositeDebt, true, vars.price); // bools: coll increase, debt increase
_requireNewTCRisAboveCCR(newTCR);
}
// Set the trove struct's properties
contractsCache.troveManager.setTroveStatus(msg.sender, 1);
contractsCache.troveManager.increaseTroveColl(msg.sender, _collAmount);
contractsCache.troveManager.increaseTroveDebt(msg.sender, vars.compositeDebt);
contractsCache.troveManager.updateTroveRewardSnapshots(msg.sender);
vars.stake = contractsCache.troveManager.updateStakeAndTotalStakes(msg.sender);
sortedTroves.insert(msg.sender, vars.NICR, _upperHint, _lowerHint);
vars.arrayIndex = contractsCache.troveManager.addTroveOwnerToArray(msg.sender);
emit TroveCreated(msg.sender, vars.arrayIndex);
// Move the ether to the Active Pool, and mint the LUSDAmount to the borrower
_activePoolAddColl(contractsCache.activePool, _collAmount);
_withdrawLUSD(contractsCache.activePool, contractsCache.LUSDToken, msg.sender, _LUSDAmount, vars.netDebt);
// Move the LUSD gas compensation to the Gas Pool
_withdrawLUSD(contractsCache.activePool, contractsCache.LUSDToken, gasPoolAddress, LUSD_GAS_COMPENSATION, LUSD_GAS_COMPENSATION);
emit TroveUpdated(msg.sender, vars.compositeDebt, _collAmount, vars.stake, BorrowerOperation.openTrove);
emit LUSDBorrowingFeePaid(msg.sender, vars.LUSDFee);
}
// Send ETH as collateral to a trove
function addColl(uint _collAmount, address _upperHint, address _lowerHint) external override {
// Replace payable with an explicit token transfer.
require(collToken.transferFrom(msg.sender, address(this), _collAmount), "BorrowerOps: Collateral transfer failed on addColl");
_adjustTrove(msg.sender, _collAmount, 0, 0, false, _upperHint, _lowerHint, 0);
}
// Send ETH as collateral to a trove. Called by only the Stability Pool.
function moveETHGainToTrove(address _borrower, uint _collAmount, address _upperHint, address _lowerHint) external override {
_requireCallerIsStabilityPool();
// Replace payable with an explicit token transfer.
require(collToken.transferFrom(msg.sender, address(this), _collAmount), "BorrowerOps: Collateral transfer failed on moveETHGainToTrove");
_adjustTrove(_borrower, _collAmount, 0, 0, false, _upperHint, _lowerHint, 0);
}
// Withdraw ETH collateral from a trove
function withdrawColl(uint _collWithdrawal, address _upperHint, address _lowerHint) external override {
_adjustTrove(msg.sender, 0, _collWithdrawal, 0, false, _upperHint, _lowerHint, 0);
}
// Withdraw LUSD tokens from a trove: mint new LUSD tokens to the owner, and increase the trove's debt accordingly
function withdrawLUSD(uint _maxFeePercentage, uint _LUSDAmount, address _upperHint, address _lowerHint) external override {
_adjustTrove(msg.sender, 0, 0, _LUSDAmount, true, _upperHint, _lowerHint, _maxFeePercentage);
}
// Repay LUSD tokens to a Trove: Burn the repaid LUSD tokens, and reduce the trove's debt accordingly
function repayLUSD(uint _LUSDAmount, address _upperHint, address _lowerHint) external override {
_adjustTrove(msg.sender, 0, 0, _LUSDAmount, false, _upperHint, _lowerHint, 0);
}
function adjustTrove(uint _maxFeePercentage, uint _collAmount, uint _collWithdrawal, uint _LUSDChange, bool _isDebtIncrease, address _upperHint, address _lowerHint) external override {
// Replace payable with an explicit token transfer.
require(collToken.transferFrom(msg.sender, address(this), _collAmount), "BorrowerOps: Collateral transfer failed on adjustTrove");
_adjustTrove(msg.sender, _collAmount, _collWithdrawal, _LUSDChange, _isDebtIncrease, _upperHint, _lowerHint, _maxFeePercentage);
}
/*
* _adjustTrove(): Alongside a debt change, this function can perform either a collateral top-up or a collateral withdrawal.
*
* It therefore expects either a positive _collAmount, or a positive _collWithdrawal argument.
*
* If both are positive, it will revert.
*/
function _adjustTrove(address _borrower, uint _collAmount, uint _collWithdrawal, uint _LUSDChange, bool _isDebtIncrease, address _upperHint, address _lowerHint, uint _maxFeePercentage) internal {
ContractsCache memory contractsCache = ContractsCache(troveManager, activePool, LUSDToken);
LocalVariables_adjustTrove memory vars;
vars.price = priceFeed.fetchPrice();
bool isRecoveryMode = _checkRecoveryMode(vars.price, _collDecimalAdjustment);
if (_isDebtIncrease) {
_requireValidMaxFeePercentage(_maxFeePercentage, isRecoveryMode);
_requireNonZeroDebtChange(_LUSDChange);
}
_requireSingularCollChange(_collAmount, _collWithdrawal);
_requireNonZeroAdjustment(_collAmount, _collWithdrawal, _LUSDChange);
_requireTroveisActive(contractsCache.troveManager, _borrower);
// Confirm the operation is either a borrower adjusting their own trove, or a pure ETH transfer from the Stability Pool to a trove
require(msg.sender == _borrower || (msg.sender == stabilityPoolAddress && _collAmount > 0 && _LUSDChange == 0), "Adjust trove check failed.");
contractsCache.troveManager.applyPendingRewards(_borrower);
// Get the collChange based on whether or not ETH was sent in the transaction
(vars.collChange, vars.isCollIncrease) = _getCollChange(_collAmount, _collWithdrawal);
vars.debtCeiling = contractsCache.troveManager.getDebtCeiling();
vars.netDebtChange = _LUSDChange;
// If the adjustment incorporates a debt increase and system is in Normal Mode, then trigger a borrowing fee
if (_isDebtIncrease && !isRecoveryMode) {
vars.LUSDFee = _triggerBorrowingFee(contractsCache.troveManager, contractsCache.LUSDToken, _LUSDChange, _maxFeePercentage);
vars.netDebtChange = vars.netDebtChange.add(vars.LUSDFee); // The raw debt change includes the fee
_requireActivePoolDebtBelowDebtCeiling(vars.netDebtChange, getEntireSystemDebt(), vars.debtCeiling);
}
vars.debt = contractsCache.troveManager.getTroveDebt(_borrower);
vars.coll = contractsCache.troveManager.getTroveColl(_borrower);
// Get the trove's old ICR before the adjustment, and what its new ICR will be after the adjustment
vars.oldICR = LiquityMath._computeCR(vars.coll, vars.debt, vars.price, _collDecimalAdjustment);
vars.newICR = _getNewICRFromTroveChange(vars.coll, vars.debt, vars.collChange, vars.isCollIncrease, vars.netDebtChange, _isDebtIncrease, vars.price);
require(_collWithdrawal <= vars.coll, "Collateral withdrawn amount must be less than trove balance.");
// Check the adjustment satisfies all conditions for the current system mode
_requireValidAdjustmentInCurrentMode(isRecoveryMode, _collWithdrawal, _isDebtIncrease, vars);
// When the adjustment is a debt repayment, check it's a valid amount and that the caller has enough LUSD
if (!_isDebtIncrease && _LUSDChange > 0) {
_requireAtLeastMinNetDebt(_getNetDebt(vars.debt).sub(vars.netDebtChange));
_requireValidLUSDRepayment(vars.debt, vars.netDebtChange);
_requireSufficientLUSDBalance(contractsCache.LUSDToken, _borrower, vars.netDebtChange);
}
(vars.newColl, vars.newDebt) = _updateTroveFromAdjustment(contractsCache.troveManager, _borrower, vars.collChange, vars.isCollIncrease, vars.netDebtChange, _isDebtIncrease);
vars.stake = contractsCache.troveManager.updateStakeAndTotalStakes(_borrower);
// Re-insert trove in to the sorted list
uint newNICR = _getNewNominalICRFromTroveChange(vars.coll, vars.debt, vars.collChange, vars.isCollIncrease, vars.netDebtChange, _isDebtIncrease);
sortedTroves.reInsert(_borrower, newNICR, _upperHint, _lowerHint);
emit TroveUpdated(_borrower, vars.newDebt, vars.newColl, vars.stake, BorrowerOperation.adjustTrove);
emit LUSDBorrowingFeePaid(msg.sender, vars.LUSDFee);
// Use the unmodified _LUSDChange here, as we don't send the fee to the user
_moveTokensAndETHfromAdjustment(
contractsCache.activePool,
contractsCache.LUSDToken,
msg.sender,
vars.collChange,
vars.isCollIncrease,
_LUSDChange,
_isDebtIncrease,
vars.netDebtChange
);
}
function closeTrove() external override {
ITroveManager troveManagerCached = troveManager;
IActivePool activePoolCached = activePool;
ILUSDToken LUSDTokenCached = LUSDToken;
_requireTroveisActive(troveManagerCached, msg.sender);
uint price = priceFeed.fetchPrice();
_requireNotInRecoveryMode(price);
troveManagerCached.applyPendingRewards(msg.sender);
uint coll = troveManagerCached.getTroveColl(msg.sender);
uint debt = troveManagerCached.getTroveDebt(msg.sender);
_requireSufficientLUSDBalance(LUSDTokenCached, msg.sender, debt.sub(LUSD_GAS_COMPENSATION));
uint newTCR = _getNewTCRFromTroveChange(coll, false, debt, false, price);
_requireNewTCRisAboveCCR(newTCR);
troveManagerCached.removeStake(msg.sender);
troveManagerCached.closeTrove(msg.sender);
emit TroveUpdated(msg.sender, 0, 0, 0, BorrowerOperation.closeTrove);
// Burn the repaid LUSD from the user's balance and the gas compensation from the Gas Pool
_repayLUSD(activePoolCached, LUSDTokenCached, msg.sender, debt.sub(LUSD_GAS_COMPENSATION));
_repayLUSD(activePoolCached, LUSDTokenCached, gasPoolAddress, LUSD_GAS_COMPENSATION);
// Send the collateral back to the user
activePoolCached.sendETH(msg.sender, coll);
}
/**
* Claim remaining collateral from a redemption or from a liquidation with ICR > MCR in Recovery Mode
*/
function claimCollateral() external override {
// send ETH from CollSurplus Pool to owner
collSurplusPool.claimColl(msg.sender);
}
// --- Helper functions ---
function _triggerBorrowingFee(ITroveManager _troveManager, ILUSDToken _LUSDToken, uint _LUSDAmount, uint _maxFeePercentage) internal returns (uint) {
_troveManager.decayBaseRateFromBorrowing(); // decay the baseRate state variable
uint LUSDFee = _troveManager.getBorrowingFee(_LUSDAmount);
_requireUserAcceptsFee(LUSDFee, _LUSDAmount, _maxFeePercentage);
// Send fee to borrowingFeePoolAddress
_LUSDToken.mint(borrowingFeePoolAddress, LUSDFee);
return LUSDFee;
}
function _getUSDValue(uint _coll, uint _price) internal pure returns (uint) {
uint usdValue = _price.mul(_coll).div(DECIMAL_PRECISION);
return usdValue;
}
function _getCollChange(
uint _collReceived,
uint _requestedCollWithdrawal
)
internal
pure
returns(uint collChange, bool isCollIncrease)
{
if (_collReceived != 0) {
collChange = _collReceived;
isCollIncrease = true;
} else {
collChange = _requestedCollWithdrawal;
}
}
// Update trove's coll and debt based on whether they increase or decrease
function _updateTroveFromAdjustment
(
ITroveManager _troveManager,
address _borrower,
uint _collChange,
bool _isCollIncrease,
uint _debtChange,
bool _isDebtIncrease
)
internal
returns (uint, uint)
{
uint newColl = (_isCollIncrease) ? _troveManager.increaseTroveColl(_borrower, _collChange)
: _troveManager.decreaseTroveColl(_borrower, _collChange);
uint newDebt = (_isDebtIncrease) ? _troveManager.increaseTroveDebt(_borrower, _debtChange)
: _troveManager.decreaseTroveDebt(_borrower, _debtChange);
return (newColl, newDebt);
}
function _moveTokensAndETHfromAdjustment
(
IActivePool _activePool,
ILUSDToken _LUSDToken,
address _borrower,
uint _collChange,
bool _isCollIncrease,
uint _LUSDChange,
bool _isDebtIncrease,
uint _netDebtChange
)
internal
{
if (_isDebtIncrease) {
_withdrawLUSD(_activePool, _LUSDToken, _borrower, _LUSDChange, _netDebtChange);
} else {
_repayLUSD(_activePool, _LUSDToken, _borrower, _LUSDChange);
}
if (_isCollIncrease) {
_activePoolAddColl(_activePool, _collChange);
} else {
_activePool.sendETH(_borrower, _collChange);
}
}
// Send ETH to Active Pool and increase its recorded ETH balance
function _activePoolAddColl(IActivePool _activePool, uint _amount) internal {
uint256 allowance = collToken.allowance(address(this), address(_activePool));
if (allowance < _amount) {
bool success = collToken.approve(address(_activePool), type(uint256).max);
require(success, "BorrowerOperations: Cannot approve ActivePool to spend collateral");
}
_activePool.depositColl(_amount);
}
// Issue the specified amount of LUSD to _account and increases the total active debt (_netDebtIncrease potentially includes a LUSDFee)
function _withdrawLUSD(IActivePool _activePool, ILUSDToken _LUSDToken, address _account, uint _LUSDAmount, uint _netDebtIncrease) internal {
_activePool.increaseLUSDDebt(_netDebtIncrease);
_LUSDToken.mint(_account, _LUSDAmount);
}
// Burn the specified amount of LUSD from _account and decreases the total active debt
function _repayLUSD(IActivePool _activePool, ILUSDToken _LUSDToken, address _account, uint _LUSD) internal {
_activePool.decreaseLUSDDebt(_LUSD);
_LUSDToken.burn(_account, _LUSD);
}
// --- 'Require' wrapper functions ---
function _requireSingularCollChange(uint _collAmount, uint _collWithdrawal) internal view {
require(_collAmount == 0 || _collWithdrawal == 0, "BorrowerOperations: Cannot withdraw and add coll");
}
function _requireCallerIsBorrower(address _borrower) internal view {
require(msg.sender == _borrower, "BorrowerOps: Caller must be the borrower for a withdrawal");
}
function _requireNonZeroAdjustment(uint _collAmount, uint _collWithdrawal, uint _LUSDChange) internal view {
require(_collAmount != 0 || _collWithdrawal != 0 || _LUSDChange != 0, "BorrowerOps: There must be either a collateral change or a debt change");
}
function _requireTroveisActive(ITroveManager _troveManager, address _borrower) internal view {
uint status = _troveManager.getTroveStatus(_borrower);
require(status == 1, "BorrowerOps: Trove does not exist or is closed");
}
function _requireTroveisNotActive(ITroveManager _troveManager, address _borrower) internal view {
uint status = _troveManager.getTroveStatus(_borrower);
require(status != 1, "BorrowerOps: Trove is active");
}
function _requireNonZeroDebtChange(uint _LUSDChange) internal pure {
require(_LUSDChange > 0, "BorrowerOps: Debt increase requires non-zero debtChange");
}
function _requireNotInRecoveryMode(uint _price) internal view {
require(!_checkRecoveryMode(_price, _collDecimalAdjustment), "BorrowerOps: Operation not permitted during Recovery Mode");
}
function _requireNoCollWithdrawal(uint _collWithdrawal) internal pure {
require(_collWithdrawal == 0, "BorrowerOps: Collateral withdrawal not permitted Recovery Mode");
}
function _requireValidAdjustmentInCurrentMode
(
bool _isRecoveryMode,
uint _collWithdrawal,
bool _isDebtIncrease,
LocalVariables_adjustTrove memory _vars
)
internal
view
{
/*
*In Recovery Mode, only allow:
*
* - Pure collateral top-up
* - Pure debt repayment
* - Collateral top-up with debt repayment
* - A debt increase combined with a collateral top-up which makes the ICR >= 150% and improves the ICR (and by extension improves the TCR).
*
* In Normal Mode, ensure:
*
* - The new ICR is above MCR
* - The adjustment won't pull the TCR below CCR
*/
if (_isRecoveryMode) {
_requireNoCollWithdrawal(_collWithdrawal);
if (_isDebtIncrease) {
_requireICRisAboveCCR(_vars.newICR);
_requireNewICRisAboveOldICR(_vars.newICR, _vars.oldICR);
}
} else { // if Normal Mode
_requireICRisAboveMCR(_vars.newICR);
_vars.newTCR = _getNewTCRFromTroveChange(_vars.collChange, _vars.isCollIncrease, _vars.netDebtChange, _isDebtIncrease, _vars.price);
_requireNewTCRisAboveCCR(_vars.newTCR);
}
}
function _requireICRisAboveMCR(uint _newICR) internal pure {
require(_newICR >= MCR, "BorrowerOps: An operation that would result in ICR < MCR is not permitted");
}
function _requireICRisAboveCCR(uint _newICR) internal pure {
require(_newICR >= CCR, "BorrowerOps: Operation must leave trove with ICR >= CCR");
}
function _requireNewICRisAboveOldICR(uint _newICR, uint _oldICR) internal pure {
require(_newICR >= _oldICR, "BorrowerOps: Cannot decrease your Trove's ICR in Recovery Mode");
}
function _requireNewTCRisAboveCCR(uint _newTCR) internal pure {
require(_newTCR >= CCR, "BorrowerOps: An operation that would result in TCR < CCR is not permitted");
}
function _requireAtLeastMinNetDebt(uint _netDebt) internal pure {
require (_netDebt >= MIN_NET_DEBT, "BorrowerOps: Trove's net debt must be greater than minimum");
}
function _requireActivePoolDebtBelowDebtCeiling(uint _netDebt, uint _activePoolLUSDDebt, uint _debtCeiling) internal pure {
require (_netDebt.add(_activePoolLUSDDebt) <= _debtCeiling, "BorrowerOps: Trove's net debt must be less than debt ceiling");
}
function _requireValidLUSDRepayment(uint _currentDebt, uint _debtRepayment) internal pure {
require(_debtRepayment <= _currentDebt.sub(LUSD_GAS_COMPENSATION), "BorrowerOps: Amount repaid must not be larger than the Trove's debt");
}
function _requireCallerIsStabilityPool() internal view {
require(msg.sender == stabilityPoolAddress, "BorrowerOps: Caller is not Stability Pool");
}
function _requireSufficientLUSDBalance(ILUSDToken _LUSDToken, address _borrower, uint _debtRepayment) internal view {
require(_LUSDToken.balanceOf(_borrower) >= _debtRepayment, "BorrowerOps: Caller doesnt have enough LUSD to make repayment");
}
function _requireValidMaxFeePercentage(uint _maxFeePercentage, bool _isRecoveryMode) internal pure {
if (_isRecoveryMode) {
require(_maxFeePercentage <= DECIMAL_PRECISION,
"Max fee percentage must less than or equal to 100%");
} else {
require(_maxFeePercentage >= BORROWING_FEE_FLOOR && _maxFeePercentage <= DECIMAL_PRECISION,
"Max fee percentage must be between 0.5% and 100%");
}
}
// --- ICR and TCR getters ---
// Compute the new collateral ratio, considering the change in coll and debt. Assumes 0 pending rewards.
function _getNewNominalICRFromTroveChange
(
uint _coll,
uint _debt,
uint _collChange,
bool _isCollIncrease,
uint _debtChange,
bool _isDebtIncrease
)
view
internal
returns (uint)
{
(uint newColl, uint newDebt) = _getNewTroveAmounts(_coll, _debt, _collChange, _isCollIncrease, _debtChange, _isDebtIncrease);
uint newNICR = LiquityMath._computeNominalCR(newColl, newDebt, _collDecimalAdjustment);
return newNICR;
}
// Compute the new collateral ratio, considering the change in coll and debt. Assumes 0 pending rewards.
function _getNewICRFromTroveChange
(
uint _coll,
uint _debt,
uint _collChange,
bool _isCollIncrease,
uint _debtChange,
bool _isDebtIncrease,
uint _price
)
view
internal
returns (uint)
{
(uint newColl, uint newDebt) = _getNewTroveAmounts(_coll, _debt, _collChange, _isCollIncrease, _debtChange, _isDebtIncrease);
uint newICR = LiquityMath._computeCR(newColl, newDebt, _price, _collDecimalAdjustment);
return newICR;
}
function _getNewTroveAmounts(
uint _coll,
uint _debt,
uint _collChange,
bool _isCollIncrease,
uint _debtChange,
bool _isDebtIncrease
)
internal
pure
returns (uint, uint)
{
uint newColl = _coll;
uint newDebt = _debt;
newColl = _isCollIncrease ? _coll.add(_collChange) : _coll.sub(_collChange);
newDebt = _isDebtIncrease ? _debt.add(_debtChange) : _debt.sub(_debtChange);
return (newColl, newDebt);
}
function _getNewTCRFromTroveChange
(
uint _collChange,
bool _isCollIncrease,
uint _debtChange,
bool _isDebtIncrease,
uint _price
)
internal
view
returns (uint)
{
uint totalColl = getEntireSystemColl();
uint totalDebt = getEntireSystemDebt();
totalColl = _isCollIncrease ? totalColl.add(_collChange) : totalColl.sub(_collChange);
totalDebt = _isDebtIncrease ? totalDebt.add(_debtChange) : totalDebt.sub(_debtChange);
uint newTCR = LiquityMath._computeCR(totalColl, totalDebt, _price, _collDecimalAdjustment);
return newTCR;
}
function getCompositeDebt(uint _debt) external pure override returns (uint) {
return _getCompositeDebt(_debt);
}
} | --- Events --- --- Contract setters --- | interface ICollSurplusPool {
event BorrowerOperationsAddressChanged(address _newBorrowerOperationsAddress);
event TroveManagerAddressChanged(address _newTroveManagerAddress);
event ActivePoolAddressChanged(address _newActivePoolAddress);
event CollTokenAddressChanged(address _collTokenAddress);
event CollBalanceUpdated(address indexed _account, uint _newBalance);
event EtherSent(address _to, uint _amount);
function setAddresses(
address _borrowerOperationsAddress,
address _troveManagerAddress,
address _activePoolAddress,
address _collTokenAddress
) external;
function getETH() external view returns (uint);
function getCollateral(address _account) external view returns (uint);
function accountSurplus(address _account, uint _amount) external;
function claimColl(address _account) external;
function depositColl(uint _amount) external;
}
| 6,791,206 | [
1,
6062,
9043,
9948,
9948,
13456,
25627,
9948,
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,
5831,
467,
13535,
7719,
10103,
2864,
288,
203,
203,
377,
203,
565,
871,
605,
15318,
264,
9343,
1887,
5033,
12,
2867,
389,
2704,
38,
15318,
264,
9343,
1887,
1769,
203,
565,
871,
399,
303,
537,
1318,
1887,
5033,
12,
2867,
389,
2704,
56,
303,
537,
1318,
1887,
1769,
203,
565,
871,
8857,
2864,
1887,
5033,
12,
2867,
389,
2704,
3896,
2864,
1887,
1769,
203,
565,
871,
17596,
1345,
1887,
5033,
12,
2867,
389,
12910,
1345,
1887,
1769,
203,
203,
565,
871,
17596,
13937,
7381,
12,
2867,
8808,
389,
4631,
16,
2254,
389,
2704,
13937,
1769,
203,
565,
871,
512,
1136,
7828,
12,
2867,
389,
869,
16,
2254,
389,
8949,
1769,
203,
203,
203,
565,
445,
444,
7148,
12,
203,
3639,
1758,
389,
70,
15318,
264,
9343,
1887,
16,
203,
3639,
1758,
389,
88,
303,
537,
1318,
1887,
16,
203,
3639,
1758,
389,
3535,
2864,
1887,
16,
203,
3639,
1758,
389,
12910,
1345,
1887,
203,
565,
262,
3903,
31,
203,
203,
565,
445,
336,
1584,
44,
1435,
3903,
1476,
1135,
261,
11890,
1769,
203,
203,
565,
445,
336,
13535,
2045,
287,
12,
2867,
389,
4631,
13,
3903,
1476,
1135,
261,
11890,
1769,
203,
203,
565,
445,
2236,
7719,
10103,
12,
2867,
389,
4631,
16,
2254,
389,
8949,
13,
3903,
31,
203,
203,
565,
445,
7516,
13535,
12,
2867,
389,
4631,
13,
3903,
31,
203,
203,
565,
445,
443,
1724,
13535,
12,
11890,
389,
8949,
13,
3903,
31,
203,
203,
97,
203,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
] |
// SPDX-License-Identifier: MIT
pragma solidity 0.8.3;
import "../interfaces/IPayment.sol";
import "../libraries/LibDiamond.sol";
import "../libraries/LibPayment.sol";
contract PaymentFacet is IPayment {
/// @notice Adds/removes a payment token
/// @param _token The target token
/// @param _status Whether the token will be added or removed
function setPaymentToken(address _token, bool _status) external override {
require(_token != address(0), "PaymentFacet: _token must not be 0x0");
LibDiamond.enforceIsContractOwner();
LibPayment.updatePaymentToken(_token, _status);
emit SetPaymentToken(_token, _status);
}
/// @notice Gets whether the payment token is supported
/// @param _token The target token
function supportsPaymentToken(address _token)
external
view
override
returns (bool)
{
return LibPayment.containsPaymentToken(_token);
}
/// @notice Gets the total amount of token payments
function totalPaymentTokens() external view override returns (uint256) {
return LibPayment.tokensCount();
}
/// @notice Gets the payment token at a given index
/// @param _index The token index
function paymentTokenAt(uint256 _index)
external
view
override
returns (address)
{
return LibPayment.tokenAt(_index);
}
}
// SPDX-License-Identifier: MIT
pragma solidity 0.8.3;
interface IPayment {
/// @notice An event emitted once a payment token is set
event SetPaymentToken(address _token, bool _status);
/// @notice Adds/removes a payment token
/// @param _token The target token
/// @param _status Whether the token will be added or removed
function setPaymentToken(address _token, bool _status) external;
/// @notice Gets whether the payment token is supported
/// @param _token The target token
function supportsPaymentToken(address _token) external view returns (bool);
/// @notice Gets the total amount of token payments
function totalPaymentTokens() external view returns (uint256);
/// @notice Gets the payment token at a given index
/// @param _index The token index
function paymentTokenAt(uint256 _index) external view returns (address);
}
// SPDX-License-Identifier: MIT
pragma solidity 0.8.3;
import "../interfaces/IDiamondCut.sol";
library LibDiamond {
bytes32 constant DIAMOND_STORAGE_POSITION =
keccak256("diamond.standard.diamond.storage");
struct FacetAddressAndPosition {
address facetAddress;
uint16 functionSelectorPosition; // position in facetFunctionSelectors.functionSelectors array
}
struct FacetFunctionSelectors {
bytes4[] functionSelectors;
uint16 facetAddressPosition; // position of facetAddress in facetAddresses array
}
struct DiamondStorage {
// maps function selector to the facet address and
// the position of the selector in the facetFunctionSelectors.selectors array
mapping(bytes4 => FacetAddressAndPosition) selectorToFacetAndPosition;
// maps facet addresses to function selectors
mapping(address => FacetFunctionSelectors) facetFunctionSelectors;
// facet addresses
address[] facetAddresses;
// Used to query if a contract implements an interface.
// Used to implement ERC-165.
mapping(bytes4 => bool) supportedInterfaces;
// owner of the contract
address contractOwner;
}
function diamondStorage()
internal
pure
returns (DiamondStorage storage ds)
{
bytes32 position = DIAMOND_STORAGE_POSITION;
assembly {
ds.slot := position
}
}
event OwnershipTransferred(
address indexed previousOwner,
address indexed newOwner
);
function setContractOwner(address _newOwner) internal {
DiamondStorage storage ds = diamondStorage();
address previousOwner = ds.contractOwner;
ds.contractOwner = _newOwner;
emit OwnershipTransferred(previousOwner, _newOwner);
}
function contractOwner() internal view returns (address contractOwner_) {
contractOwner_ = diamondStorage().contractOwner;
}
function enforceIsContractOwner() internal view {
require(
msg.sender == diamondStorage().contractOwner,
"LibDiamond: Must be contract owner"
);
}
event DiamondCut(
IDiamondCut.FacetCut[] _diamondCut,
address _init,
bytes _calldata
);
// Internal function version of diamondCut
function diamondCut(
IDiamondCut.FacetCut[] memory _diamondCut,
address _init,
bytes memory _calldata
) internal {
for (
uint256 facetIndex;
facetIndex < _diamondCut.length;
facetIndex++
) {
IDiamondCut.FacetCutAction action = _diamondCut[facetIndex].action;
if (action == IDiamondCut.FacetCutAction.Add) {
addFunctions(
_diamondCut[facetIndex].facetAddress,
_diamondCut[facetIndex].functionSelectors
);
} else if (action == IDiamondCut.FacetCutAction.Replace) {
replaceFunctions(
_diamondCut[facetIndex].facetAddress,
_diamondCut[facetIndex].functionSelectors
);
} else if (action == IDiamondCut.FacetCutAction.Remove) {
removeFunctions(
_diamondCut[facetIndex].facetAddress,
_diamondCut[facetIndex].functionSelectors
);
} else {
revert("LibDiamondCut: Incorrect FacetCutAction");
}
}
emit DiamondCut(_diamondCut, _init, _calldata);
initializeDiamondCut(_init, _calldata);
}
function addFunctions(
address _facetAddress,
bytes4[] memory _functionSelectors
) internal {
require(
_functionSelectors.length > 0,
"LibDiamondCut: No selectors in facet to cut"
);
DiamondStorage storage ds = diamondStorage();
// uint16 selectorCount = uint16(diamondStorage().selectors.length);
require(
_facetAddress != address(0),
"LibDiamondCut: Add facet can't be address(0)"
);
uint16 selectorPosition = uint16(
ds.facetFunctionSelectors[_facetAddress].functionSelectors.length
);
// add new facet address if it does not exist
if (selectorPosition == 0) {
enforceHasContractCode(
_facetAddress,
"LibDiamondCut: New facet has no code"
);
ds
.facetFunctionSelectors[_facetAddress]
.facetAddressPosition = uint16(ds.facetAddresses.length);
ds.facetAddresses.push(_facetAddress);
}
for (
uint256 selectorIndex;
selectorIndex < _functionSelectors.length;
selectorIndex++
) {
bytes4 selector = _functionSelectors[selectorIndex];
address oldFacetAddress = ds
.selectorToFacetAndPosition[selector]
.facetAddress;
require(
oldFacetAddress == address(0),
"LibDiamondCut: Can't add function that already exists"
);
addFunction(ds, selector, selectorPosition, _facetAddress);
selectorPosition++;
}
}
function replaceFunctions(
address _facetAddress,
bytes4[] memory _functionSelectors
) internal {
require(
_functionSelectors.length > 0,
"LibDiamondCut: No selectors in facet to cut"
);
DiamondStorage storage ds = diamondStorage();
require(
_facetAddress != address(0),
"LibDiamondCut: Add facet can't be address(0)"
);
uint16 selectorPosition = uint16(
ds.facetFunctionSelectors[_facetAddress].functionSelectors.length
);
// add new facet address if it does not exist
if (selectorPosition == 0) {
enforceHasContractCode(
_facetAddress,
"LibDiamondCut: New facet has no code"
);
ds
.facetFunctionSelectors[_facetAddress]
.facetAddressPosition = uint16(ds.facetAddresses.length);
ds.facetAddresses.push(_facetAddress);
}
for (
uint256 selectorIndex;
selectorIndex < _functionSelectors.length;
selectorIndex++
) {
bytes4 selector = _functionSelectors[selectorIndex];
address oldFacetAddress = ds
.selectorToFacetAndPosition[selector]
.facetAddress;
require(
oldFacetAddress != _facetAddress,
"LibDiamondCut: Can't replace function with same function"
);
removeFunction(ds, oldFacetAddress, selector);
// add function
addFunction(ds, selector, selectorPosition, _facetAddress);
selectorPosition++;
}
}
function removeFunctions(
address _facetAddress,
bytes4[] memory _functionSelectors
) internal {
require(
_functionSelectors.length > 0,
"LibDiamondCut: No selectors in facet to cut"
);
DiamondStorage storage ds = diamondStorage();
// if function does not exist then do nothing and return
require(
_facetAddress == address(0),
"LibDiamondCut: Remove facet address must be address(0)"
);
for (
uint256 selectorIndex;
selectorIndex < _functionSelectors.length;
selectorIndex++
) {
bytes4 selector = _functionSelectors[selectorIndex];
address oldFacetAddress = ds
.selectorToFacetAndPosition[selector]
.facetAddress;
removeFunction(ds, oldFacetAddress, selector);
}
}
function addFunction(
DiamondStorage storage ds,
bytes4 _selector,
uint16 _selectorPosition,
address _facetAddress
) internal {
ds
.selectorToFacetAndPosition[_selector]
.functionSelectorPosition = _selectorPosition;
ds.facetFunctionSelectors[_facetAddress].functionSelectors.push(
_selector
);
ds.selectorToFacetAndPosition[_selector].facetAddress = _facetAddress;
}
function removeFunction(
DiamondStorage storage ds,
address _facetAddress,
bytes4 _selector
) internal {
require(
_facetAddress != address(0),
"LibDiamondCut: Can't remove function that doesn't exist"
);
// an immutable function is a function defined directly in a diamond
require(
_facetAddress != address(this),
"LibDiamondCut: Can't remove immutable function"
);
// replace selector with last selector, then delete last selector
uint256 selectorPosition = ds
.selectorToFacetAndPosition[_selector]
.functionSelectorPosition;
uint256 lastSelectorPosition = ds
.facetFunctionSelectors[_facetAddress]
.functionSelectors
.length - 1;
// if not the same then replace _selector with lastSelector
if (selectorPosition != lastSelectorPosition) {
bytes4 lastSelector = ds
.facetFunctionSelectors[_facetAddress]
.functionSelectors[lastSelectorPosition];
ds.facetFunctionSelectors[_facetAddress].functionSelectors[
selectorPosition
] = lastSelector;
ds
.selectorToFacetAndPosition[lastSelector]
.functionSelectorPosition = uint16(selectorPosition);
}
// delete the last selector
ds.facetFunctionSelectors[_facetAddress].functionSelectors.pop();
delete ds.selectorToFacetAndPosition[_selector];
// if no more selectors for facet address then delete the facet address
if (lastSelectorPosition == 0) {
// replace facet address with last facet address and delete last facet address
uint256 lastFacetAddressPosition = ds.facetAddresses.length - 1;
uint256 facetAddressPosition = ds
.facetFunctionSelectors[_facetAddress]
.facetAddressPosition;
if (facetAddressPosition != lastFacetAddressPosition) {
address lastFacetAddress = ds.facetAddresses[
lastFacetAddressPosition
];
ds.facetAddresses[facetAddressPosition] = lastFacetAddress;
ds
.facetFunctionSelectors[lastFacetAddress]
.facetAddressPosition = uint16(facetAddressPosition);
}
ds.facetAddresses.pop();
delete ds
.facetFunctionSelectors[_facetAddress]
.facetAddressPosition;
}
}
function initializeDiamondCut(address _init, bytes memory _calldata)
internal
{
if (_init == address(0)) {
require(
_calldata.length == 0,
"LibDiamondCut: _init is address(0) but_calldata is not empty"
);
} else {
require(
_calldata.length > 0,
"LibDiamondCut: _calldata is empty but _init is not address(0)"
);
if (_init != address(this)) {
enforceHasContractCode(
_init,
"LibDiamondCut: _init address has no code"
);
}
(bool success, bytes memory error) = _init.delegatecall(_calldata);
if (!success) {
if (error.length > 0) {
// bubble up the error
revert(string(error));
} else {
revert("LibDiamondCut: _init function reverted");
}
}
}
}
function enforceHasContractCode(
address _contract,
string memory _errorMessage
) internal view {
uint256 contractSize;
assembly {
contractSize := extcodesize(_contract)
}
require(contractSize > 0, _errorMessage);
}
}
// SPDX-License-Identifier: MIT
pragma solidity 0.8.3;
import "@openzeppelin/contracts/utils/structs/EnumerableSet.sol";
// Stores information about Payment Tokens
library LibPayment {
using EnumerableSet for EnumerableSet.AddressSet;
bytes32 constant PAYMENT_STORAGE_POSITION = keccak256("payment.storage");
struct PaymentStorage {
// Stores all supported tokens as payments for ERC-721
EnumerableSet.AddressSet tokens;
}
function paymentStorage()
internal
pure
returns (PaymentStorage storage ps)
{
bytes32 position = PAYMENT_STORAGE_POSITION;
assembly {
ps.slot := position
}
}
/// @notice Returns the count of payment tokens
function tokensCount() internal view returns (uint256) {
PaymentStorage storage ps = paymentStorage();
return ps.tokens.length();
}
/// @notice Returns the address of the payment token at a given index
function tokenAt(uint256 _index) internal view returns (address) {
PaymentStorage storage ps = paymentStorage();
return ps.tokens.at(_index);
}
function updatePaymentToken(address _paymentToken, bool _status) internal {
PaymentStorage storage ps = paymentStorage();
if (_status) {
require(
ps.tokens.add(_paymentToken),
"LibPayment: payment token already added"
);
} else {
require(
ps.tokens.remove(_paymentToken),
"LibPayment: payment token not found"
);
}
}
/// @notice Returns true/false depending on whether a given payment token is found
function containsPaymentToken(address _token) internal view returns (bool) {
PaymentStorage storage ps = paymentStorage();
return ps.tokens.contains(_token);
}
}
// SPDX-License-Identifier: MIT
pragma solidity 0.8.3;
interface IDiamondCut {
enum FacetCutAction {
Add,
Replace,
Remove
}
// Add=0, Replace=1, Remove=2
struct FacetCut {
address facetAddress;
FacetCutAction action;
bytes4[] functionSelectors;
}
/// @notice Add/replace/remove any number of functions and optionally execute
/// a function with delegatecall
/// @param _diamondCut Contains the facet addresses and function selectors
/// @param _init The address of the contract or facet to execute _calldata
/// @param _calldata A function call, including function selector and arguments
/// _calldata is executed with delegatecall on _init
function diamondCut(
FacetCut[] calldata _diamondCut,
address _init,
bytes calldata _calldata
) external;
event DiamondCut(FacetCut[] _diamondCut, address _init, bytes _calldata);
}
// 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 `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];
}
// 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);
}
// 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))));
}
// 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));
}
} | @notice Gets the total amount of token payments | function totalPaymentTokens() external view override returns (uint256) {
return LibPayment.tokensCount();
}
| 1,334,776 | [
1,
3002,
326,
2078,
3844,
434,
1147,
25754,
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,
2078,
6032,
5157,
1435,
3903,
1476,
3849,
1135,
261,
11890,
5034,
13,
288,
203,
3639,
327,
10560,
6032,
18,
7860,
1380,
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,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-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.6.12;
pragma experimental ABIEncoderV2;
contract DSAuthEvents {
event LogSetAuthority(address indexed authority);
event LogSetOwner(address indexed owner);
}
contract DSAuth is DSAuthEvents {
DSAuthority public authority;
address public owner;
constructor() public {
owner = msg.sender;
emit LogSetOwner(msg.sender);
}
function setOwner(address owner_) public auth {
owner = owner_;
emit LogSetOwner(owner);
}
function setAuthority(DSAuthority authority_) public auth {
authority = authority_;
emit LogSetAuthority(address(authority));
}
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 == DSAuthority(0)) {
return false;
} else {
return authority.canCall(src, address(this), sig);
}
}
}
abstract contract DSAuthority {
function canCall(address src, address dst, bytes4 sig) public virtual view returns (bool);
}
abstract contract DSGuard {
function canCall(address src_, address dst_, bytes4 sig) public view virtual returns (bool);
function permit(bytes32 src, bytes32 dst, bytes32 sig) public virtual;
function forbid(bytes32 src, bytes32 dst, bytes32 sig) public virtual;
function permit(address src, address dst, bytes32 sig) public virtual;
function forbid(address src, address dst, bytes32 sig) public virtual;
}
abstract contract DSGuardFactory {
function newGuard() public virtual returns (DSGuard guard);
}
contract DSMath {
function add(uint256 x, uint256 y) internal pure returns (uint256 z) {
require((z = x + y) >= x);
}
function sub(uint256 x, uint256 y) internal pure returns (uint256 z) {
require((z = x - y) <= x);
}
function mul(uint256 x, uint256 y) internal pure returns (uint256 z) {
require(y == 0 || (z = x * y) / y == x);
}
function div(uint256 x, uint256 y) internal pure returns (uint256 z) {
return x / y;
}
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(int256 x, int256 y) internal pure returns (int256 z) {
return x <= y ? x : y;
}
function imax(int256 x, int256 y) internal pure returns (int256 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;
}
// This famous algorithm is called "exponentiation by squaring"
// and calculates x^n with x as fixed-point and n as regular unsigned.
//
// It's O(log n), instead of O(n) for naive repeated multiplication.
//
// These facts are why it works:
//
// If n is even, then x^n = (x^2)^(n/2).
// If n is odd, then x^n = x * x^(n-1),
// and applying the equation for even x gives
// x^n = x * (x^2)^((n-1) / 2).
//
// Also, EVM division is flooring and
// floor[(n-1) / 2] = floor[n / 2].
//
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 DSNote {
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);
_;
}
}
abstract contract DSProxy is DSAuth, DSNote {
DSProxyCache public cache; // global cache for contracts
constructor(address _cacheAddr) public {
require(setCache(_cacheAddr));
}
// solhint-disable-next-line no-empty-blocks
receive() external payable {}
// use the proxy to execute calldata _data on contract _code
// function execute(bytes memory _code, bytes memory _data)
// public
// payable
// virtual
// returns (address target, bytes32 response);
function execute(address _target, bytes memory _data)
public
payable
virtual
returns (bytes32 response);
//set new cache
function setCache(address _cacheAddr) public virtual payable returns (bool);
}
contract DSProxyCache {
mapping(bytes32 => address) cache;
function read(bytes memory _code) public view returns (address) {
bytes32 hash = keccak256(_code);
return cache[hash];
}
function write(bytes memory _code) public returns (address target) {
assembly {
target := create(0, add(_code, 0x20), mload(_code))
switch iszero(extcodesize(target))
case 1 {
// throw if contract failed to deploy
revert(0, 0)
}
}
bytes32 hash = keccak256(_code);
cache[hash] = target;
}
}
abstract contract DSProxyFactoryInterface {
function build(address owner) public virtual returns (DSProxy proxy);
}
contract AaveHelper is DSMath {
using SafeERC20 for ERC20;
address payable public constant WALLET_ADDR = 0x322d58b9E75a6918f7e7849AEe0fF09369977e08;
address public constant DISCOUNT_ADDR = 0x1b14E8D511c9A4395425314f849bD737BAF8208F;
uint public constant MANUAL_SERVICE_FEE = 400; // 0.25% Fee
uint public constant AUTOMATIC_SERVICE_FEE = 333; // 0.3% Fee
address public constant BOT_REGISTRY_ADDRESS = 0x637726f8b08a7ABE3aE3aCaB01A80E2d8ddeF77B;
address public constant ETH_ADDR = 0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE;
address public constant AAVE_LENDING_POOL_ADDRESSES = 0x24a42fD28C976A61Df5D00D0599C34c4f90748c8;
uint public constant NINETY_NINE_PERCENT_WEI = 990000000000000000;
uint16 public constant AAVE_REFERRAL_CODE = 64;
/// @param _collateralAddress underlying token address
/// @param _user users address
function getMaxCollateral(address _collateralAddress, address _user) public view returns (uint256) {
address lendingPoolAddressDataProvider = ILendingPoolAddressesProvider(AAVE_LENDING_POOL_ADDRESSES).getLendingPoolDataProvider();
address lendingPoolCoreAddress = ILendingPoolAddressesProvider(AAVE_LENDING_POOL_ADDRESSES).getLendingPoolCore();
address priceOracleAddress = ILendingPoolAddressesProvider(AAVE_LENDING_POOL_ADDRESSES).getPriceOracle();
uint256 pow10 = 10 ** (18 - _getDecimals(_collateralAddress));
// fetch all needed data
(,uint256 totalCollateralETH, uint256 totalBorrowsETH,,uint256 currentLTV,,,) = ILendingPool(lendingPoolAddressDataProvider).calculateUserGlobalData(_user);
(,uint256 tokenLTV,,) = ILendingPool(lendingPoolCoreAddress).getReserveConfiguration(_collateralAddress);
uint256 collateralPrice = IPriceOracleGetterAave(priceOracleAddress).getAssetPrice(_collateralAddress);
uint256 userTokenBalance = ILendingPool(lendingPoolCoreAddress).getUserUnderlyingAssetBalance(_collateralAddress, _user);
uint256 userTokenBalanceEth = wmul(userTokenBalance * pow10, collateralPrice);
// if borrow is 0, return whole user balance
if (totalBorrowsETH == 0) {
return userTokenBalance;
}
uint256 maxCollateralEth = div(sub(mul(currentLTV, totalCollateralETH), mul(totalBorrowsETH, 100)), currentLTV);
/// @dev final amount can't be higher than users token balance
maxCollateralEth = maxCollateralEth > userTokenBalanceEth ? userTokenBalanceEth : maxCollateralEth;
// might happen due to wmul precision
if (maxCollateralEth >= totalCollateralETH) {
return wdiv(totalCollateralETH, collateralPrice) / pow10;
}
// get sum of all other reserves multiplied with their liquidation thresholds by reversing formula
uint256 a = sub(wmul(currentLTV, totalCollateralETH), wmul(tokenLTV, userTokenBalanceEth));
// add new collateral amount multiplied by its threshold, and then divide with new total collateral
uint256 newLiquidationThreshold = wdiv(add(a, wmul(sub(userTokenBalanceEth, maxCollateralEth), tokenLTV)), sub(totalCollateralETH, maxCollateralEth));
// if new threshold is lower than first one, calculate new max collateral with newLiquidationThreshold
if (newLiquidationThreshold < currentLTV) {
maxCollateralEth = div(sub(mul(newLiquidationThreshold, totalCollateralETH), mul(totalBorrowsETH, 100)), newLiquidationThreshold);
maxCollateralEth = maxCollateralEth > userTokenBalanceEth ? userTokenBalanceEth : maxCollateralEth;
}
return wmul(wdiv(maxCollateralEth, collateralPrice) / pow10, NINETY_NINE_PERCENT_WEI);
}
/// @param _borrowAddress underlying token address
/// @param _user users address
function getMaxBorrow(address _borrowAddress, address _user) public view returns (uint256) {
address lendingPoolAddress = ILendingPoolAddressesProvider(AAVE_LENDING_POOL_ADDRESSES).getLendingPool();
address priceOracleAddress = ILendingPoolAddressesProvider(AAVE_LENDING_POOL_ADDRESSES).getPriceOracle();
(,,,,uint256 availableBorrowsETH,,,) = ILendingPool(lendingPoolAddress).getUserAccountData(_user);
uint256 borrowPrice = IPriceOracleGetterAave(priceOracleAddress).getAssetPrice(_borrowAddress);
return wmul(wdiv(availableBorrowsETH, borrowPrice) / (10 ** (18 - _getDecimals(_borrowAddress))), NINETY_NINE_PERCENT_WEI);
}
function getMaxBoost(address _borrowAddress, address _collateralAddress, address _user) public view returns (uint256) {
address lendingPoolAddressDataProvider = ILendingPoolAddressesProvider(AAVE_LENDING_POOL_ADDRESSES).getLendingPoolDataProvider();
address lendingPoolCoreAddress = ILendingPoolAddressesProvider(AAVE_LENDING_POOL_ADDRESSES).getLendingPoolCore();
address priceOracleAddress = ILendingPoolAddressesProvider(AAVE_LENDING_POOL_ADDRESSES).getPriceOracle();
(,uint256 totalCollateralETH, uint256 totalBorrowsETH,,uint256 currentLTV,,,) = ILendingPool(lendingPoolAddressDataProvider).calculateUserGlobalData(_user);
(,uint256 tokenLTV,,) = ILendingPool(lendingPoolCoreAddress).getReserveConfiguration(_collateralAddress);
totalCollateralETH = div(mul(totalCollateralETH, currentLTV), 100);
uint256 availableBorrowsETH = wmul(mul(div(sub(totalCollateralETH, totalBorrowsETH), sub(100, tokenLTV)), 100), NINETY_NINE_PERCENT_WEI);
uint256 borrowPrice = IPriceOracleGetterAave(priceOracleAddress).getAssetPrice(_borrowAddress);
return wdiv(availableBorrowsETH, borrowPrice) / (10 ** (18 - _getDecimals(_borrowAddress)));
}
/// @notice Calculates the fee amount
/// @param _amount Amount that is converted
/// @param _user Actuall user addr not DSProxy
/// @param _gasCost Ether amount of gas we are spending for tx
/// @param _tokenAddr token addr. of token we are getting for the fee
/// @return feeAmount The amount we took for the fee
function getFee(uint _amount, address _user, uint _gasCost, address _tokenAddr) internal returns (uint feeAmount) {
address priceOracleAddress = ILendingPoolAddressesProvider(AAVE_LENDING_POOL_ADDRESSES).getPriceOracle();
uint fee = MANUAL_SERVICE_FEE;
if (BotRegistry(BOT_REGISTRY_ADDRESS).botList(tx.origin)) {
fee = AUTOMATIC_SERVICE_FEE;
}
if (Discount(DISCOUNT_ADDR).isCustomFeeSet(_user)) {
fee = Discount(DISCOUNT_ADDR).getCustomServiceFee(_user);
}
feeAmount = (fee == 0) ? 0 : (_amount / fee);
if (_gasCost != 0) {
uint256 price = IPriceOracleGetterAave(priceOracleAddress).getAssetPrice(_tokenAddr);
_gasCost = wdiv(_gasCost, price) / (10 ** (18 - _getDecimals(_tokenAddr)));
feeAmount = add(feeAmount, _gasCost);
}
// fee can't go over 20% of the whole amount
if (feeAmount > (_amount / 5)) {
feeAmount = _amount / 5;
}
if (_tokenAddr == ETH_ADDR) {
WALLET_ADDR.transfer(feeAmount);
} else {
ERC20(_tokenAddr).safeTransfer(WALLET_ADDR, feeAmount);
}
}
/// @notice Calculates the gas cost for transaction
/// @param _amount Amount that is converted
/// @param _user Actuall user addr not DSProxy
/// @param _gasCost Ether amount of gas we are spending for tx
/// @param _tokenAddr token addr. of token we are getting for the fee
/// @return gasCost The amount we took for the gas cost
function getGasCost(uint _amount, address _user, uint _gasCost, address _tokenAddr) internal returns (uint gasCost) {
address priceOracleAddress = ILendingPoolAddressesProvider(AAVE_LENDING_POOL_ADDRESSES).getPriceOracle();
if (_gasCost != 0) {
uint256 price = IPriceOracleGetterAave(priceOracleAddress).getAssetPrice(_tokenAddr);
_gasCost = wmul(_gasCost, price);
gasCost = _gasCost;
}
// fee can't go over 20% of the whole amount
if (gasCost > (_amount / 5)) {
gasCost = _amount / 5;
}
if (_tokenAddr == ETH_ADDR) {
WALLET_ADDR.transfer(gasCost);
} else {
ERC20(_tokenAddr).safeTransfer(WALLET_ADDR, gasCost);
}
}
/// @notice Returns the owner of the DSProxy that called the contract
function getUserAddress() internal view returns (address) {
DSProxy proxy = DSProxy(payable(address(this)));
return proxy.owner();
}
/// @notice Approves token contract to pull underlying tokens from the DSProxy
/// @param _tokenAddr Token we are trying to approve
/// @param _caller Address which will gain the approval
function approveToken(address _tokenAddr, address _caller) internal {
if (_tokenAddr != ETH_ADDR) {
ERC20(_tokenAddr).safeApprove(_caller, uint256(-1));
}
}
/// @notice Send specific amount from contract to specific user
/// @param _token Token we are trying to send
/// @param _user User that should receive funds
/// @param _amount Amount that should be sent
function sendContractBalance(address _token, address _user, uint _amount) public {
if (_amount == 0) return;
if (_token == ETH_ADDR) {
payable(_user).transfer(_amount);
} else {
ERC20(_token).safeTransfer(_user, _amount);
}
}
function sendFullContractBalance(address _token, address _user) public {
if (_token == ETH_ADDR) {
sendContractBalance(_token, _user, address(this).balance);
} else {
sendContractBalance(_token, _user, ERC20(_token).balanceOf(address(this)));
}
}
function _getDecimals(address _token) internal view returns (uint256) {
if (_token == ETH_ADDR) return 18;
return ERC20(_token).decimals();
}
}
contract AaveSafetyRatio is AaveHelper {
function getSafetyRatio(address _user) public view returns(uint256) {
address lendingPoolAddress = ILendingPoolAddressesProvider(AAVE_LENDING_POOL_ADDRESSES).getLendingPool();
(,,uint256 totalBorrowsETH,,uint256 availableBorrowsETH,,,) = ILendingPool(lendingPoolAddress).getUserAccountData(_user);
if (totalBorrowsETH == 0) return uint256(0);
return wdiv(add(totalBorrowsETH, availableBorrowsETH), totalBorrowsETH);
}
}
contract AdminAuth {
using SafeERC20 for ERC20;
address public owner;
address public admin;
modifier onlyOwner() {
require(owner == msg.sender);
_;
}
constructor() public {
owner = msg.sender;
}
/// @notice Admin is set by owner first time, after that admin is super role and has permission to change owner
/// @param _admin Address of multisig that becomes admin
function setAdminByOwner(address _admin) public {
require(msg.sender == owner);
require(admin == address(0));
admin = _admin;
}
/// @notice Admin is able to set new admin
/// @param _admin Address of multisig that becomes new admin
function setAdminByAdmin(address _admin) public {
require(msg.sender == admin);
admin = _admin;
}
/// @notice Admin is able to change owner
/// @param _owner Address of new owner
function setOwnerByAdmin(address _owner) public {
require(msg.sender == admin);
owner = _owner;
}
/// @notice Destroy the contract
function kill() public onlyOwner {
selfdestruct(payable(owner));
}
/// @notice withdraw stuck funds
function withdrawStuckFunds(address _token, uint _amount) public onlyOwner {
if (_token == 0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE) {
payable(owner).transfer(_amount);
} else {
ERC20(_token).safeTransfer(owner, _amount);
}
}
}
contract Auth is AdminAuth {
bool public ALL_AUTHORIZED = false;
mapping(address => bool) public authorized;
modifier onlyAuthorized() {
require(ALL_AUTHORIZED || authorized[msg.sender]);
_;
}
constructor() public {
authorized[msg.sender] = true;
}
function setAuthorized(address _user, bool _approved) public onlyOwner {
authorized[_user] = _approved;
}
function setAllAuthorized(bool _authorized) public onlyOwner {
ALL_AUTHORIZED = _authorized;
}
}
contract ProxyPermission {
address public constant FACTORY_ADDRESS = 0x5a15566417e6C1c9546523066500bDDBc53F88C7;
/// @notice Called in the context of DSProxy to authorize an address
/// @param _contractAddr Address which will be authorized
function givePermission(address _contractAddr) public {
address currAuthority = address(DSAuth(address(this)).authority());
DSGuard guard = DSGuard(currAuthority);
if (currAuthority == address(0)) {
guard = DSGuardFactory(FACTORY_ADDRESS).newGuard();
DSAuth(address(this)).setAuthority(DSAuthority(address(guard)));
}
guard.permit(_contractAddr, address(this), bytes4(keccak256("execute(address,bytes)")));
}
/// @notice Called in the context of DSProxy to remove authority of an address
/// @param _contractAddr Auth address which will be removed from authority list
function removePermission(address _contractAddr) public {
address currAuthority = address(DSAuth(address(this)).authority());
// if there is no authority, that means that contract doesn't have permission
if (currAuthority == address(0)) {
return;
}
DSGuard guard = DSGuard(currAuthority);
guard.forbid(_contractAddr, address(this), bytes4(keccak256("execute(address,bytes)")));
}
function proxyOwner() internal returns(address) {
return DSAuth(address(this)).owner();
}
}
contract CompoundMonitorProxy is AdminAuth {
using SafeERC20 for ERC20;
uint public CHANGE_PERIOD;
address public monitor;
address public newMonitor;
address public lastMonitor;
uint public changeRequestedTimestamp;
mapping(address => bool) public allowed;
event MonitorChangeInitiated(address oldMonitor, address newMonitor);
event MonitorChangeCanceled();
event MonitorChangeFinished(address monitor);
event MonitorChangeReverted(address monitor);
// if someone who is allowed become malicious, owner can't be changed
modifier onlyAllowed() {
require(allowed[msg.sender] || msg.sender == owner);
_;
}
modifier onlyMonitor() {
require (msg.sender == monitor);
_;
}
constructor(uint _changePeriod) public {
CHANGE_PERIOD = _changePeriod * 1 days;
}
/// @notice Only monitor contract is able to call execute on users proxy
/// @param _owner Address of cdp owner (users DSProxy address)
/// @param _compoundSaverProxy Address of CompoundSaverProxy
/// @param _data Data to send to CompoundSaverProxy
function callExecute(address _owner, address _compoundSaverProxy, bytes memory _data) public payable onlyMonitor {
// execute reverts if calling specific method fails
DSProxyInterface(_owner).execute{value: msg.value}(_compoundSaverProxy, _data);
// return if anything left
if (address(this).balance > 0) {
msg.sender.transfer(address(this).balance);
}
}
/// @notice Allowed users are able to set Monitor contract without any waiting period first time
/// @param _monitor Address of Monitor contract
function setMonitor(address _monitor) public onlyAllowed {
require(monitor == address(0));
monitor = _monitor;
}
/// @notice Allowed users are able to start procedure for changing monitor
/// @dev after CHANGE_PERIOD needs to call confirmNewMonitor to actually make a change
/// @param _newMonitor address of new monitor
function changeMonitor(address _newMonitor) public onlyAllowed {
require(changeRequestedTimestamp == 0);
changeRequestedTimestamp = now;
lastMonitor = monitor;
newMonitor = _newMonitor;
emit MonitorChangeInitiated(lastMonitor, newMonitor);
}
/// @notice At any point allowed users are able to cancel monitor change
function cancelMonitorChange() public onlyAllowed {
require(changeRequestedTimestamp > 0);
changeRequestedTimestamp = 0;
newMonitor = address(0);
emit MonitorChangeCanceled();
}
/// @notice Anyone is able to confirm new monitor after CHANGE_PERIOD if process is started
function confirmNewMonitor() public onlyAllowed {
require((changeRequestedTimestamp + CHANGE_PERIOD) < now);
require(changeRequestedTimestamp != 0);
require(newMonitor != address(0));
monitor = newMonitor;
newMonitor = address(0);
changeRequestedTimestamp = 0;
emit MonitorChangeFinished(monitor);
}
/// @notice Its possible to revert monitor to last used monitor
function revertMonitor() public onlyAllowed {
require(lastMonitor != address(0));
monitor = lastMonitor;
emit MonitorChangeReverted(monitor);
}
/// @notice Allowed users are able to add new allowed user
/// @param _user Address of user that will be allowed
function addAllowed(address _user) public onlyAllowed {
allowed[_user] = true;
}
/// @notice Allowed users are able to remove allowed user
/// @dev owner is always allowed even if someone tries to remove it from allowed mapping
/// @param _user Address of allowed user
function removeAllowed(address _user) public onlyAllowed {
allowed[_user] = false;
}
function setChangePeriod(uint _periodInDays) public onlyAllowed {
require(_periodInDays * 1 days > CHANGE_PERIOD);
CHANGE_PERIOD = _periodInDays * 1 days;
}
/// @notice In case something is left in contract, owner is able to withdraw it
/// @param _token address of token to withdraw balance
function withdrawToken(address _token) public onlyOwner {
uint balance = ERC20(_token).balanceOf(address(this));
ERC20(_token).safeTransfer(msg.sender, balance);
}
/// @notice In case something is left in contract, owner is able to withdraw it
function withdrawEth() public onlyOwner {
uint balance = address(this).balance;
msg.sender.transfer(balance);
}
}
contract CompoundSubscriptions is AdminAuth {
struct CompoundHolder {
address user;
uint128 minRatio;
uint128 maxRatio;
uint128 optimalRatioBoost;
uint128 optimalRatioRepay;
bool boostEnabled;
}
struct SubPosition {
uint arrPos;
bool subscribed;
}
CompoundHolder[] public subscribers;
mapping (address => SubPosition) public subscribersPos;
uint public changeIndex;
event Subscribed(address indexed user);
event Unsubscribed(address indexed user);
event Updated(address indexed user);
event ParamUpdates(address indexed user, uint128, uint128, uint128, uint128, bool);
/// @dev Called by the DSProxy contract which owns the Compound position
/// @notice Adds the users Compound poistion in the list of subscriptions so it can be monitored
/// @param _minRatio Minimum ratio below which repay is triggered
/// @param _maxRatio Maximum ratio after which boost is triggered
/// @param _optimalBoost Ratio amount which boost should target
/// @param _optimalRepay Ratio amount which repay should target
/// @param _boostEnabled Boolean determing if boost is enabled
function subscribe(uint128 _minRatio, uint128 _maxRatio, uint128 _optimalBoost, uint128 _optimalRepay, bool _boostEnabled) external {
// if boost is not enabled, set max ratio to max uint
uint128 localMaxRatio = _boostEnabled ? _maxRatio : uint128(-1);
require(checkParams(_minRatio, localMaxRatio), "Must be correct params");
SubPosition storage subInfo = subscribersPos[msg.sender];
CompoundHolder memory subscription = CompoundHolder({
minRatio: _minRatio,
maxRatio: localMaxRatio,
optimalRatioBoost: _optimalBoost,
optimalRatioRepay: _optimalRepay,
user: msg.sender,
boostEnabled: _boostEnabled
});
changeIndex++;
if (subInfo.subscribed) {
subscribers[subInfo.arrPos] = subscription;
emit Updated(msg.sender);
emit ParamUpdates(msg.sender, _minRatio, localMaxRatio, _optimalBoost, _optimalRepay, _boostEnabled);
} else {
subscribers.push(subscription);
subInfo.arrPos = subscribers.length - 1;
subInfo.subscribed = true;
emit Subscribed(msg.sender);
}
}
/// @notice Called by the users DSProxy
/// @dev Owner who subscribed cancels his subscription
function unsubscribe() external {
_unsubscribe(msg.sender);
}
/// @dev Checks limit if minRatio is bigger than max
/// @param _minRatio Minimum ratio, bellow which repay can be triggered
/// @param _maxRatio Maximum ratio, over which boost can be triggered
/// @return Returns bool if the params are correct
function checkParams(uint128 _minRatio, uint128 _maxRatio) internal pure returns (bool) {
if (_minRatio > _maxRatio) {
return false;
}
return true;
}
/// @dev Internal method to remove a subscriber from the list
/// @param _user The actual address that owns the Compound position
function _unsubscribe(address _user) internal {
require(subscribers.length > 0, "Must have subscribers in the list");
SubPosition storage subInfo = subscribersPos[_user];
require(subInfo.subscribed, "Must first be subscribed");
address lastOwner = subscribers[subscribers.length - 1].user;
SubPosition storage subInfo2 = subscribersPos[lastOwner];
subInfo2.arrPos = subInfo.arrPos;
subscribers[subInfo.arrPos] = subscribers[subscribers.length - 1];
subscribers.pop(); // remove last element and reduce arr length
changeIndex++;
subInfo.subscribed = false;
subInfo.arrPos = 0;
emit Unsubscribed(msg.sender);
}
/// @dev Checks if the user is subscribed
/// @param _user The actual address that owns the Compound position
/// @return If the user is subscribed
function isSubscribed(address _user) public view returns (bool) {
SubPosition storage subInfo = subscribersPos[_user];
return subInfo.subscribed;
}
/// @dev Returns subscribtion information about a user
/// @param _user The actual address that owns the Compound position
/// @return Subscription information about the user if exists
function getHolder(address _user) public view returns (CompoundHolder memory) {
SubPosition storage subInfo = subscribersPos[_user];
return subscribers[subInfo.arrPos];
}
/// @notice Helper method to return all the subscribed CDPs
/// @return List of all subscribers
function getSubscribers() public view returns (CompoundHolder[] memory) {
return subscribers;
}
/// @notice Helper method for the frontend, returns all the subscribed CDPs paginated
/// @param _page What page of subscribers you want
/// @param _perPage Number of entries per page
/// @return List of all subscribers for that page
function getSubscribersByPage(uint _page, uint _perPage) public view returns (CompoundHolder[] memory) {
CompoundHolder[] memory holders = new CompoundHolder[](_perPage);
uint start = _page * _perPage;
uint end = start + _perPage;
end = (end > holders.length) ? holders.length : end;
uint count = 0;
for (uint i = start; i < end; i++) {
holders[count] = subscribers[i];
count++;
}
return holders;
}
////////////// ADMIN METHODS ///////////////////
/// @notice Admin function to unsubscribe a CDP
/// @param _user The actual address that owns the Compound position
function unsubscribeByAdmin(address _user) public onlyOwner {
SubPosition storage subInfo = subscribersPos[_user];
if (subInfo.subscribed) {
_unsubscribe(_user);
}
}
}
contract CompoundSubscriptionsProxy is ProxyPermission {
address public constant COMPOUND_SUBSCRIPTION_ADDRESS = 0x52015EFFD577E08f498a0CCc11905925D58D6207;
address public constant COMPOUND_MONITOR_PROXY = 0xB1cF8DE8e791E4Ed1Bd86c03E2fc1f14389Cb10a;
/// @notice Calls subscription contract and creates a DSGuard if non existent
/// @param _minRatio Minimum ratio below which repay is triggered
/// @param _maxRatio Maximum ratio after which boost is triggered
/// @param _optimalRatioBoost Ratio amount which boost should target
/// @param _optimalRatioRepay Ratio amount which repay should target
/// @param _boostEnabled Boolean determing if boost is enabled
function subscribe(
uint128 _minRatio,
uint128 _maxRatio,
uint128 _optimalRatioBoost,
uint128 _optimalRatioRepay,
bool _boostEnabled
) public {
givePermission(COMPOUND_MONITOR_PROXY);
ICompoundSubscription(COMPOUND_SUBSCRIPTION_ADDRESS).subscribe(
_minRatio, _maxRatio, _optimalRatioBoost, _optimalRatioRepay, _boostEnabled);
}
/// @notice Calls subscription contract and updated existing parameters
/// @dev If subscription is non existent this will create one
/// @param _minRatio Minimum ratio below which repay is triggered
/// @param _maxRatio Maximum ratio after which boost is triggered
/// @param _optimalRatioBoost Ratio amount which boost should target
/// @param _optimalRatioRepay Ratio amount which repay should target
/// @param _boostEnabled Boolean determing if boost is enabled
function update(
uint128 _minRatio,
uint128 _maxRatio,
uint128 _optimalRatioBoost,
uint128 _optimalRatioRepay,
bool _boostEnabled
) public {
ICompoundSubscription(COMPOUND_SUBSCRIPTION_ADDRESS).subscribe(_minRatio, _maxRatio, _optimalRatioBoost, _optimalRatioRepay, _boostEnabled);
}
/// @notice Calls the subscription contract to unsubscribe the caller
function unsubscribe() public {
removePermission(COMPOUND_MONITOR_PROXY);
ICompoundSubscription(COMPOUND_SUBSCRIPTION_ADDRESS).unsubscribe();
}
}
contract CompoundCreateTaker is ProxyPermission {
using SafeERC20 for ERC20;
address public constant ETH_ADDRESS = 0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE;
ILendingPool public constant lendingPool = ILendingPool(0x398eC7346DcD622eDc5ae82352F02bE94C62d119);
// solhint-disable-next-line const-name-snakecase
DefisaverLogger public constant logger = DefisaverLogger(0x5c55B921f590a89C1Ebe84dF170E655a82b62126);
struct CreateInfo {
address cCollAddress;
address cBorrowAddress;
uint depositAmount;
}
/// @notice Main function which will take a FL and open a leverage position
/// @dev Call through DSProxy, if _exchangeData.destAddr is a token approve DSProxy
/// @param _createInfo [cCollAddress, cBorrowAddress, depositAmount]
/// @param _exchangeData Exchange data struct
function openLeveragedLoan(
CreateInfo memory _createInfo,
SaverExchangeCore.ExchangeData memory _exchangeData,
address payable _compReceiver
) public payable {
uint loanAmount = _exchangeData.srcAmount;
// Pull tokens from user
if (_exchangeData.destAddr != ETH_ADDRESS) {
ERC20(_exchangeData.destAddr).safeTransferFrom(msg.sender, address(this), _createInfo.depositAmount);
} else {
require(msg.value >= _createInfo.depositAmount, "Must send correct amount of eth");
}
// Send tokens to FL receiver
sendDeposit(_compReceiver, _exchangeData.destAddr);
// Pack the struct data
(uint[4] memory numData, address[6] memory cAddresses, bytes memory callData)
= _packData(_createInfo, _exchangeData);
bytes memory paramsData = abi.encode(numData, cAddresses, callData, address(this));
givePermission(_compReceiver);
lendingPool.flashLoan(_compReceiver, _exchangeData.srcAddr, loanAmount, paramsData);
removePermission(_compReceiver);
logger.Log(address(this), msg.sender, "CompoundLeveragedLoan",
abi.encode(_exchangeData.srcAddr, _exchangeData.destAddr, _exchangeData.srcAmount, _exchangeData.destAmount));
}
function sendDeposit(address payable _compoundReceiver, address _token) internal {
if (_token != ETH_ADDRESS) {
ERC20(_token).safeTransfer(_compoundReceiver, ERC20(_token).balanceOf(address(this)));
}
_compoundReceiver.transfer(address(this).balance);
}
function _packData(
CreateInfo memory _createInfo,
SaverExchangeCore.ExchangeData memory exchangeData
) internal pure returns (uint[4] memory numData, address[6] memory cAddresses, bytes memory callData) {
numData = [
exchangeData.srcAmount,
exchangeData.destAmount,
exchangeData.minPrice,
exchangeData.price0x
];
cAddresses = [
_createInfo.cCollAddress,
_createInfo.cBorrowAddress,
exchangeData.srcAddr,
exchangeData.destAddr,
exchangeData.exchangeAddr,
exchangeData.wrapper
];
callData = exchangeData.callData;
}
}
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);
}
}
contract Exponential is CarefulMath {
uint constant expScale = 1e18;
uint constant doubleScale = 1e36;
uint constant halfExpScale = expScale/2;
uint constant mantissaOne = expScale;
struct Exp {
uint mantissa;
}
struct Double {
uint mantissa;
}
/**
* @dev Creates an exponential from numerator and denominator values.
* Note: Returns an error if (`num` * 10e18) > MAX_INT,
* or if `denom` is zero.
*/
function getExp(uint num, uint denom) pure internal returns (MathError, Exp memory) {
(MathError err0, uint scaledNumerator) = mulUInt(num, expScale);
if (err0 != MathError.NO_ERROR) {
return (err0, Exp({mantissa: 0}));
}
(MathError err1, uint rational) = divUInt(scaledNumerator, denom);
if (err1 != MathError.NO_ERROR) {
return (err1, Exp({mantissa: 0}));
}
return (MathError.NO_ERROR, Exp({mantissa: rational}));
}
/**
* @dev Adds two exponentials, returning a new exponential.
*/
function addExp(Exp memory a, Exp memory b) pure internal returns (MathError, Exp memory) {
(MathError error, uint result) = addUInt(a.mantissa, b.mantissa);
return (error, Exp({mantissa: result}));
}
/**
* @dev Subtracts two exponentials, returning a new exponential.
*/
function subExp(Exp memory a, Exp memory b) pure internal returns (MathError, Exp memory) {
(MathError error, uint result) = subUInt(a.mantissa, b.mantissa);
return (error, Exp({mantissa: result}));
}
/**
* @dev Multiply an Exp by a scalar, returning a new Exp.
*/
function mulScalar(Exp memory a, uint scalar) pure internal returns (MathError, Exp memory) {
(MathError err0, uint scaledMantissa) = mulUInt(a.mantissa, scalar);
if (err0 != MathError.NO_ERROR) {
return (err0, Exp({mantissa: 0}));
}
return (MathError.NO_ERROR, Exp({mantissa: scaledMantissa}));
}
/**
* @dev Multiply an Exp by a scalar, then truncate to return an unsigned integer.
*/
function mulScalarTruncate(Exp memory a, uint scalar) pure internal returns (MathError, uint) {
(MathError err, Exp memory product) = mulScalar(a, scalar);
if (err != MathError.NO_ERROR) {
return (err, 0);
}
return (MathError.NO_ERROR, truncate(product));
}
/**
* @dev Multiply an Exp by a scalar, truncate, then add an to an unsigned integer, returning an unsigned integer.
*/
function mulScalarTruncateAddUInt(Exp memory a, uint scalar, uint addend) pure internal returns (MathError, uint) {
(MathError err, Exp memory product) = mulScalar(a, scalar);
if (err != MathError.NO_ERROR) {
return (err, 0);
}
return addUInt(truncate(product), addend);
}
/**
* @dev 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);
}
/**
* @dev Truncates the given exp to a whole number value.
* For example, truncate(Exp{mantissa: 15 * expScale}) = 15
*/
function truncate(Exp memory exp) pure internal returns (uint) {
// Note: We are not using careful math here as we're performing a division that cannot fail
return exp.mantissa / expScale;
}
/**
* @dev Checks if first Exp is less than second Exp.
*/
function lessThanExp(Exp memory left, Exp memory right) pure internal returns (bool) {
return left.mantissa < right.mantissa;
}
/**
* @dev Checks if left Exp <= right Exp.
*/
function lessThanOrEqualExp(Exp memory left, Exp memory right) pure internal returns (bool) {
return left.mantissa <= right.mantissa;
}
/**
* @dev 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 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 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;
}
}
contract CompoundBorrowProxy {
using SafeERC20 for ERC20;
address public constant ETH_ADDR = 0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE;
address public constant COMPTROLLER_ADDR = 0x3d9819210A31b4961b30EF54bE2aeD79B9c9Cd3B;
function borrow(address _cCollToken, address _cBorrowToken, address _borrowToken, uint _amount) public {
address[] memory markets = new address[](2);
markets[0] = _cCollToken;
markets[1] = _cBorrowToken;
ComptrollerInterface(COMPTROLLER_ADDR).enterMarkets(markets);
require(CTokenInterface(_cBorrowToken).borrow(_amount) == 0);
// withdraw funds to msg.sender
if (_borrowToken != ETH_ADDR) {
ERC20(_borrowToken).safeTransfer(msg.sender, ERC20(_borrowToken).balanceOf(address(this)));
} else {
msg.sender.transfer(address(this).balance);
}
}
}
contract CreamSafetyRatio is Exponential, DSMath {
// solhint-disable-next-line const-name-snakecase
ComptrollerInterface public constant comp = ComptrollerInterface(0x3d5BC3c8d13dcB8bF317092d84783c2697AE9258);
/// @notice Calcualted the ratio of debt / adjusted collateral
/// @param _user Address of the user
function getSafetyRatio(address _user) public view returns (uint) {
// For each asset the account is in
address[] memory assets = comp.getAssetsIn(_user);
address oracleAddr = comp.oracle();
uint sumCollateral = 0;
uint sumBorrow = 0;
for (uint i = 0; i < assets.length; i++) {
address asset = assets[i];
(, uint cTokenBalance, uint borrowBalance, uint exchangeRateMantissa)
= CTokenInterface(asset).getAccountSnapshot(_user);
Exp memory oraclePrice;
if (cTokenBalance != 0 || borrowBalance != 0) {
oraclePrice = Exp({mantissa: CompoundOracleInterface(oracleAddr).getUnderlyingPrice(asset)});
}
// Sum up collateral in Eth
if (cTokenBalance != 0) {
(, uint collFactorMantissa) = comp.markets(address(asset));
Exp memory collateralFactor = Exp({mantissa: collFactorMantissa});
Exp memory exchangeRate = Exp({mantissa: exchangeRateMantissa});
(, Exp memory tokensToEther) = mulExp3(collateralFactor, exchangeRate, oraclePrice);
(, sumCollateral) = mulScalarTruncateAddUInt(tokensToEther, cTokenBalance, sumCollateral);
}
// Sum up debt in Eth
if (borrowBalance != 0) {
(, sumBorrow) = mulScalarTruncateAddUInt(oraclePrice, borrowBalance, sumBorrow);
}
}
if (sumBorrow == 0) return uint(-1);
uint borrowPowerUsed = (sumBorrow * 10**18) / sumCollateral;
return wdiv(1e18, borrowPowerUsed);
}
}
contract CreamSaverHelper is DSMath, Exponential {
using SafeERC20 for ERC20;
address payable public constant WALLET_ADDR = 0x322d58b9E75a6918f7e7849AEe0fF09369977e08;
address public constant DISCOUNT_ADDR = 0x1b14E8D511c9A4395425314f849bD737BAF8208F;
uint public constant MANUAL_SERVICE_FEE = 400; // 0.25% Fee
uint public constant AUTOMATIC_SERVICE_FEE = 333; // 0.3% Fee
address public constant ETH_ADDRESS = 0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE;
address public constant CETH_ADDRESS = 0xD06527D5e56A3495252A528C4987003b712860eE;
address public constant COMPTROLLER = 0x3d5BC3c8d13dcB8bF317092d84783c2697AE9258;
address public constant BOT_REGISTRY_ADDRESS = 0x637726f8b08a7ABE3aE3aCaB01A80E2d8ddeF77B;
/// @notice Helper method to payback the cream debt
/// @dev If amount is bigger it will repay the whole debt and send the extra to the _user
/// @param _amount Amount of tokens we want to repay
/// @param _cBorrowToken Ctoken address we are repaying
/// @param _borrowToken Token address we are repaying
/// @param _user Owner of the cream position we are paying back
function paybackDebt(uint _amount, address _cBorrowToken, address _borrowToken, address payable _user) internal {
uint wholeDebt = CTokenInterface(_cBorrowToken).borrowBalanceCurrent(address(this));
if (_amount > wholeDebt) {
if (_borrowToken == ETH_ADDRESS) {
_user.transfer((_amount - wholeDebt));
} else {
ERC20(_borrowToken).safeTransfer(_user, (_amount - wholeDebt));
}
_amount = wholeDebt;
}
approveCToken(_borrowToken, _cBorrowToken);
if (_borrowToken == ETH_ADDRESS) {
CEtherInterface(_cBorrowToken).repayBorrow{value: _amount}();
} else {
require(CTokenInterface(_cBorrowToken).repayBorrow(_amount) == 0);
}
}
/// @notice Calculates the fee amount
/// @param _amount Amount that is converted
/// @param _user Actuall user addr not DSProxy
/// @param _gasCost Ether amount of gas we are spending for tx
/// @param _cTokenAddr CToken addr. of token we are getting for the fee
/// @return feeAmount The amount we took for the fee
function getFee(uint _amount, address _user, uint _gasCost, address _cTokenAddr) internal returns (uint feeAmount) {
uint fee = MANUAL_SERVICE_FEE;
if (BotRegistry(BOT_REGISTRY_ADDRESS).botList(tx.origin)) {
fee = AUTOMATIC_SERVICE_FEE;
}
address tokenAddr = getUnderlyingAddr(_cTokenAddr);
if (Discount(DISCOUNT_ADDR).isCustomFeeSet(_user)) {
fee = Discount(DISCOUNT_ADDR).getCustomServiceFee(_user);
}
feeAmount = (fee == 0) ? 0 : (_amount / fee);
if (_gasCost != 0) {
address oracle = ComptrollerInterface(COMPTROLLER).oracle();
uint ethTokenPrice = CompoundOracleInterface(oracle).getUnderlyingPrice(_cTokenAddr);
_gasCost = wdiv(_gasCost, ethTokenPrice);
feeAmount = add(feeAmount, _gasCost);
}
// fee can't go over 20% of the whole amount
if (feeAmount > (_amount / 5)) {
feeAmount = _amount / 5;
}
if (tokenAddr == ETH_ADDRESS) {
WALLET_ADDR.transfer(feeAmount);
} else {
ERC20(tokenAddr).safeTransfer(WALLET_ADDR, feeAmount);
}
}
/// @notice Calculates the gas cost of transaction and send it to wallet
/// @param _amount Amount that is converted
/// @param _gasCost Ether amount of gas we are spending for tx
/// @param _cTokenAddr CToken addr. of token we are getting for the fee
/// @return feeAmount The amount we took for the fee
function getGasCost(uint _amount, uint _gasCost, address _cTokenAddr) internal returns (uint feeAmount) {
address tokenAddr = getUnderlyingAddr(_cTokenAddr);
if (_gasCost != 0) {
address oracle = ComptrollerInterface(COMPTROLLER).oracle();
uint ethTokenPrice = CompoundOracleInterface(oracle).getUnderlyingPrice(_cTokenAddr);
feeAmount = wdiv(_gasCost, ethTokenPrice);
}
// fee can't go over 20% of the whole amount
if (feeAmount > (_amount / 5)) {
feeAmount = _amount / 5;
}
if (tokenAddr == ETH_ADDRESS) {
WALLET_ADDR.transfer(feeAmount);
} else {
ERC20(tokenAddr).safeTransfer(WALLET_ADDR, feeAmount);
}
}
/// @notice Enters the market for the collatera and borrow tokens
/// @param _cTokenAddrColl Collateral address we are entering the market in
/// @param _cTokenAddrBorrow Borrow address we are entering the market in
function enterMarket(address _cTokenAddrColl, address _cTokenAddrBorrow) internal {
address[] memory markets = new address[](2);
markets[0] = _cTokenAddrColl;
markets[1] = _cTokenAddrBorrow;
ComptrollerInterface(COMPTROLLER).enterMarkets(markets);
}
/// @notice Approves CToken contract to pull underlying tokens from the DSProxy
/// @param _tokenAddr Token we are trying to approve
/// @param _cTokenAddr Address which will gain the approval
function approveCToken(address _tokenAddr, address _cTokenAddr) internal {
if (_tokenAddr != ETH_ADDRESS) {
ERC20(_tokenAddr).safeApprove(_cTokenAddr, uint(-1));
}
}
/// @notice Returns the underlying address of the cToken asset
/// @param _cTokenAddress cToken address
/// @return Token address of the cToken specified
function getUnderlyingAddr(address _cTokenAddress) internal returns (address) {
if (_cTokenAddress == CETH_ADDRESS) {
return ETH_ADDRESS;
} else {
return CTokenInterface(_cTokenAddress).underlying();
}
}
/// @notice Returns the owner of the DSProxy that called the contract
function getUserAddress() internal view returns (address) {
DSProxy proxy = DSProxy(uint160(address(this)));
return proxy.owner();
}
/// @notice Returns the maximum amount of collateral available to withdraw
/// @dev Due to rounding errors the result is - 1% wei from the exact amount
/// @param _cCollAddress Collateral we are getting the max value of
/// @param _account Users account
/// @return Returns the max. collateral amount in that token
function getMaxCollateral(address _cCollAddress, address _account) public returns (uint) {
(, uint liquidityInEth, ) = ComptrollerInterface(COMPTROLLER).getAccountLiquidity(_account);
uint usersBalance = CTokenInterface(_cCollAddress).balanceOfUnderlying(_account);
address oracle = ComptrollerInterface(COMPTROLLER).oracle();
if (liquidityInEth == 0) return usersBalance;
CTokenInterface(_cCollAddress).accrueInterest();
if (_cCollAddress == CETH_ADDRESS) {
if (liquidityInEth > usersBalance) return usersBalance;
return sub(liquidityInEth, (liquidityInEth / 100));
}
uint ethPrice = CompoundOracleInterface(oracle).getUnderlyingPrice(_cCollAddress);
uint liquidityInToken = wdiv(liquidityInEth, ethPrice);
if (liquidityInToken > usersBalance) return usersBalance;
return sub(liquidityInToken, (liquidityInToken / 100)); // cut off 1% due to rounding issues
}
/// @notice Returns the maximum amount of borrow amount available
/// @dev Due to rounding errors the result is - 1% wei from the exact amount
/// @param _cBorrowAddress Borrow token we are getting the max value of
/// @param _account Users account
/// @return Returns the max. borrow amount in that token
function getMaxBorrow(address _cBorrowAddress, address _account) public returns (uint) {
(, uint liquidityInEth, ) = ComptrollerInterface(COMPTROLLER).getAccountLiquidity(_account);
address oracle = ComptrollerInterface(COMPTROLLER).oracle();
CTokenInterface(_cBorrowAddress).accrueInterest();
if (_cBorrowAddress == CETH_ADDRESS) return sub(liquidityInEth, (liquidityInEth / 100));
uint ethPrice = CompoundOracleInterface(oracle).getUnderlyingPrice(_cBorrowAddress);
uint liquidityInToken = wdiv(liquidityInEth, ethPrice);
return sub(liquidityInToken, (liquidityInToken / 100)); // cut off 1% due to rounding issues
}
}
contract CreamBorrowProxy {
using SafeERC20 for ERC20;
address public constant ETH_ADDR = 0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE;
address public constant COMPTROLLER_ADDR = 0x3d5BC3c8d13dcB8bF317092d84783c2697AE9258;
function borrow(address _cCollToken, address _cBorrowToken, address _borrowToken, uint _amount) public {
address[] memory markets = new address[](2);
markets[0] = _cCollToken;
markets[1] = _cBorrowToken;
ComptrollerInterface(COMPTROLLER_ADDR).enterMarkets(markets);
require(CTokenInterface(_cBorrowToken).borrow(_amount) == 0);
// withdraw funds to msg.sender
if (_borrowToken != ETH_ADDR) {
ERC20(_borrowToken).safeTransfer(msg.sender, ERC20(_borrowToken).balanceOf(address(this)));
} else {
msg.sender.transfer(address(this).balance);
}
}
}
contract AllowanceProxy is AdminAuth {
using SafeERC20 for ERC20;
address public constant KYBER_ETH_ADDRESS = 0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE;
// TODO: Real saver exchange address
SaverExchange saverExchange = SaverExchange(0x235abFAd01eb1BDa28Ef94087FBAA63E18074926);
function callSell(SaverExchangeCore.ExchangeData memory exData) public payable {
pullAndSendTokens(exData.srcAddr, exData.srcAmount);
saverExchange.sell{value: msg.value}(exData, msg.sender);
}
function callBuy(SaverExchangeCore.ExchangeData memory exData) public payable {
pullAndSendTokens(exData.srcAddr, exData.srcAmount);
saverExchange.buy{value: msg.value}(exData, msg.sender);
}
function pullAndSendTokens(address _tokenAddr, uint _amount) internal {
if (_tokenAddr == KYBER_ETH_ADDRESS) {
require(msg.value >= _amount, "msg.value smaller than amount");
} else {
ERC20(_tokenAddr).safeTransferFrom(msg.sender, address(saverExchange), _amount);
}
}
function ownerChangeExchange(address payable _newExchange) public onlyOwner {
saverExchange = SaverExchange(_newExchange);
}
}
contract Prices is DSMath {
address public constant KYBER_ETH_ADDRESS = 0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE;
enum ActionType { SELL, BUY }
/// @notice Returns the best estimated price from 2 exchanges
/// @param _amount Amount of source tokens you want to exchange
/// @param _srcToken Address of the source token
/// @param _destToken Address of the destination token
/// @param _type Type of action SELL|BUY
/// @param _wrappers Array of wrapper addresses to compare
/// @return (address, uint) The address of the best exchange and the exchange price
function getBestPrice(
uint256 _amount,
address _srcToken,
address _destToken,
ActionType _type,
address[] memory _wrappers
) public returns (address, uint256) {
uint256[] memory rates = new uint256[](_wrappers.length);
for (uint i=0; i<_wrappers.length; i++) {
rates[i] = getExpectedRate(_wrappers[i], _srcToken, _destToken, _amount, _type);
}
return getBiggestRate(_wrappers, rates);
}
/// @notice Return the expected rate from the exchange wrapper
/// @dev In case of Oasis/Uniswap handles the different precision tokens
/// @param _wrapper Address of exchange wrapper
/// @param _srcToken From token
/// @param _destToken To token
/// @param _amount Amount to be exchanged
/// @param _type Type of action SELL|BUY
function getExpectedRate(
address _wrapper,
address _srcToken,
address _destToken,
uint256 _amount,
ActionType _type
) public returns (uint256) {
bool success;
bytes memory result;
if (_type == ActionType.SELL) {
(success, result) = _wrapper.call(abi.encodeWithSignature(
"getSellRate(address,address,uint256)",
_srcToken,
_destToken,
_amount
));
} else {
(success, result) = _wrapper.call(abi.encodeWithSignature(
"getBuyRate(address,address,uint256)",
_srcToken,
_destToken,
_amount
));
}
if (success) {
return sliceUint(result, 0);
}
return 0;
}
/// @notice Finds the biggest rate between exchanges, needed for sell rate
/// @param _wrappers Array of wrappers to compare
/// @param _rates Array of rates to compare
function getBiggestRate(
address[] memory _wrappers,
uint256[] memory _rates
) internal pure returns (address, uint) {
uint256 maxIndex = 0;
// starting from 0 in case there is only one rate in array
for (uint256 i=0; i<_rates.length; i++) {
if (_rates[i] > _rates[maxIndex]) {
maxIndex = i;
}
}
return (_wrappers[maxIndex], _rates[maxIndex]);
}
function getDecimals(address _token) internal view returns (uint256) {
if (_token == KYBER_ETH_ADDRESS) return 18;
return ERC20(_token).decimals();
}
function sliceUint(bytes memory bs, uint256 start) internal pure returns (uint256) {
require(bs.length >= start + 32, "slicing out of range");
uint256 x;
assembly {
x := mload(add(bs, add(0x20, start)))
}
return x;
}
}
contract SaverExchangeHelper {
using SafeERC20 for ERC20;
address public constant KYBER_ETH_ADDRESS = 0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE;
address public constant WETH_ADDRESS = 0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2;
address payable public constant WALLET_ID = 0x322d58b9E75a6918f7e7849AEe0fF09369977e08;
address public constant DISCOUNT_ADDRESS = 0x1b14E8D511c9A4395425314f849bD737BAF8208F;
address public constant SAVER_EXCHANGE_REGISTRY = 0x25dd3F51e0C3c3Ff164DDC02A8E4D65Bb9cBB12D;
address public constant ERC20_PROXY_0X = 0x95E6F48254609A6ee006F7D493c8e5fB97094ceF;
address public constant ZRX_ALLOWLIST_ADDR = 0x4BA1f38427b33B8ab7Bb0490200dAE1F1C36823F;
function getDecimals(address _token) internal view returns (uint256) {
if (_token == KYBER_ETH_ADDRESS) return 18;
return ERC20(_token).decimals();
}
function getBalance(address _tokenAddr) internal view returns (uint balance) {
if (_tokenAddr == KYBER_ETH_ADDRESS) {
balance = address(this).balance;
} else {
balance = ERC20(_tokenAddr).balanceOf(address(this));
}
}
function approve0xProxy(address _tokenAddr, uint _amount) internal {
if (_tokenAddr != KYBER_ETH_ADDRESS) {
ERC20(_tokenAddr).safeApprove(address(ERC20_PROXY_0X), _amount);
}
}
function sendLeftover(address _srcAddr, address _destAddr, address payable _to) internal {
// send back any leftover ether or tokens
if (address(this).balance > 0) {
_to.transfer(address(this).balance);
}
if (getBalance(_srcAddr) > 0) {
ERC20(_srcAddr).safeTransfer(_to, getBalance(_srcAddr));
}
if (getBalance(_destAddr) > 0) {
ERC20(_destAddr).safeTransfer(_to, getBalance(_destAddr));
}
}
function sliceUint(bytes memory bs, uint256 start) internal pure returns (uint256) {
require(bs.length >= start + 32, "slicing out of range");
uint256 x;
assembly {
x := mload(add(bs, add(0x20, start)))
}
return x;
}
}
contract SaverExchangeRegistry is AdminAuth {
mapping(address => bool) private wrappers;
constructor() public {
wrappers[0x880A845A85F843a5c67DB2061623c6Fc3bB4c511] = true;
wrappers[0x4c9B55f2083629A1F7aDa257ae984E03096eCD25] = true;
wrappers[0x42A9237b872368E1bec4Ca8D26A928D7d39d338C] = true;
}
function addWrapper(address _wrapper) public onlyOwner {
wrappers[_wrapper] = true;
}
function removeWrapper(address _wrapper) public onlyOwner {
wrappers[_wrapper] = false;
}
function isWrapper(address _wrapper) public view returns(bool) {
return wrappers[_wrapper];
}
}
contract DFSExchangeData {
// first is empty to keep the legacy order in place
enum ExchangeType { _, OASIS, KYBER, UNISWAP, ZEROX }
enum ActionType { SELL, BUY }
struct OffchainData {
address exchangeAddr;
address allowanceTarget;
uint256 price;
uint256 protocolFee;
bytes callData;
}
struct ExchangeData {
address srcAddr;
address destAddr;
uint256 srcAmount;
uint256 destAmount;
uint256 minPrice;
uint256 dfsFeeDivider; // service fee divider
address user; // user to check special fee
address wrapper;
bytes wrapperData;
OffchainData offchainData;
}
function packExchangeData(ExchangeData memory _exData) public pure returns(bytes memory) {
return abi.encode(_exData);
}
function unpackExchangeData(bytes memory _data) public pure returns(ExchangeData memory _exData) {
_exData = abi.decode(_data, (ExchangeData));
}
}
contract DFSExchangeHelper {
using SafeERC20 for ERC20;
address public constant KYBER_ETH_ADDRESS = 0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE;
address public constant WETH_ADDRESS = 0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2;
address payable public constant WALLET_ID = 0x322d58b9E75a6918f7e7849AEe0fF09369977e08;
address public constant DISCOUNT_ADDRESS = 0x1b14E8D511c9A4395425314f849bD737BAF8208F;
address public constant SAVER_EXCHANGE_REGISTRY = 0x25dd3F51e0C3c3Ff164DDC02A8E4D65Bb9cBB12D;
address public constant ZRX_ALLOWLIST_ADDR = 0x4BA1f38427b33B8ab7Bb0490200dAE1F1C36823F;
function getDecimals(address _token) internal view returns (uint256) {
if (_token == KYBER_ETH_ADDRESS) return 18;
return ERC20(_token).decimals();
}
function getBalance(address _tokenAddr) internal view returns (uint balance) {
if (_tokenAddr == KYBER_ETH_ADDRESS) {
balance = address(this).balance;
} else {
balance = ERC20(_tokenAddr).balanceOf(address(this));
}
}
function sendLeftover(address _srcAddr, address _destAddr, address payable _to) internal {
// send back any leftover ether or tokens
if (address(this).balance > 0) {
_to.transfer(address(this).balance);
}
if (getBalance(_srcAddr) > 0) {
ERC20(_srcAddr).safeTransfer(_to, getBalance(_srcAddr));
}
if (getBalance(_destAddr) > 0) {
ERC20(_destAddr).safeTransfer(_to, getBalance(_destAddr));
}
}
/// @notice Takes a feePercentage and sends it to wallet
/// @param _amount Dai amount of the whole trade
/// @param _user Address of the user
/// @param _token Address of the token
/// @param _dfsFeeDivider Dfs fee divider
/// @return feeAmount Amount in Dai owner earned on the fee
function getFee(uint256 _amount, address _user, address _token, uint256 _dfsFeeDivider) internal returns (uint256 feeAmount) {
if (_dfsFeeDivider != 0 && Discount(DISCOUNT_ADDRESS).isCustomFeeSet(_user)) {
_dfsFeeDivider = Discount(DISCOUNT_ADDRESS).getCustomServiceFee(_user);
}
if (_dfsFeeDivider == 0) {
feeAmount = 0;
} else {
feeAmount = _amount / _dfsFeeDivider;
// fee can't go over 10% of the whole amount
if (feeAmount > (_amount / 10)) {
feeAmount = _amount / 10;
}
if (_token == KYBER_ETH_ADDRESS) {
WALLET_ID.transfer(feeAmount);
} else {
ERC20(_token).safeTransfer(WALLET_ID, feeAmount);
}
}
}
function sliceUint(bytes memory bs, uint256 start) internal pure returns (uint256) {
require(bs.length >= start + 32, "slicing out of range");
uint256 x;
assembly {
x := mload(add(bs, add(0x20, start)))
}
return x;
}
}
contract DFSPrices is DSMath {
address public constant KYBER_ETH_ADDRESS = 0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE;
enum ActionType { SELL, BUY }
/// @notice Returns the best estimated price from 2 exchanges
/// @param _amount Amount of source tokens you want to exchange
/// @param _srcToken Address of the source token
/// @param _destToken Address of the destination token
/// @param _type Type of action SELL|BUY
/// @param _wrappers Array of wrapper addresses to compare
/// @return (address, uint) The address of the best exchange and the exchange price
function getBestPrice(
uint256 _amount,
address _srcToken,
address _destToken,
ActionType _type,
address[] memory _wrappers,
bytes[] memory _additionalData
) public returns (address, uint256) {
uint256[] memory rates = new uint256[](_wrappers.length);
for (uint i=0; i<_wrappers.length; i++) {
rates[i] = getExpectedRate(_wrappers[i], _srcToken, _destToken, _amount, _type, _additionalData[i]);
}
return getBiggestRate(_wrappers, rates);
}
/// @notice Return the expected rate from the exchange wrapper
/// @dev In case of Oasis/Uniswap handles the different precision tokens
/// @param _wrapper Address of exchange wrapper
/// @param _srcToken From token
/// @param _destToken To token
/// @param _amount Amount to be exchanged
/// @param _type Type of action SELL|BUY
function getExpectedRate(
address _wrapper,
address _srcToken,
address _destToken,
uint256 _amount,
ActionType _type,
bytes memory _additionalData
) public returns (uint256) {
bool success;
bytes memory result;
if (_type == ActionType.SELL) {
(success, result) = _wrapper.call(abi.encodeWithSignature(
"getSellRate(address,address,uint256,bytes)",
_srcToken,
_destToken,
_amount,
_additionalData
));
} else {
(success, result) = _wrapper.call(abi.encodeWithSignature(
"getBuyRate(address,address,uint256,bytes)",
_srcToken,
_destToken,
_amount,
_additionalData
));
}
if (success) {
return sliceUint(result, 0);
}
return 0;
}
/// @notice Finds the biggest rate between exchanges, needed for sell rate
/// @param _wrappers Array of wrappers to compare
/// @param _rates Array of rates to compare
function getBiggestRate(
address[] memory _wrappers,
uint256[] memory _rates
) internal pure returns (address, uint) {
uint256 maxIndex = 0;
// starting from 0 in case there is only one rate in array
for (uint256 i=0; i<_rates.length; i++) {
if (_rates[i] > _rates[maxIndex]) {
maxIndex = i;
}
}
return (_wrappers[maxIndex], _rates[maxIndex]);
}
function getDecimals(address _token) internal view returns (uint256) {
if (_token == KYBER_ETH_ADDRESS) return 18;
return ERC20(_token).decimals();
}
function sliceUint(bytes memory bs, uint256 start) internal pure returns (uint256) {
require(bs.length >= start + 32, "slicing out of range");
uint256 x;
assembly {
x := mload(add(bs, add(0x20, start)))
}
return x;
}
}
abstract contract CEtherInterface {
function mint() external virtual payable;
function repayBorrow() external virtual payable;
}
abstract contract CompoundOracleInterface {
function getUnderlyingPrice(address cToken) external view virtual returns (uint);
}
abstract contract ComptrollerInterface {
struct CompMarketState {
uint224 index;
uint32 block;
}
function claimComp(address holder) public virtual;
function claimComp(address holder, address[] memory cTokens) public virtual;
function claimComp(address[] memory holders, address[] memory cTokens, bool borrowers, bool suppliers) public virtual;
function compSupplyState(address) public view virtual returns (CompMarketState memory);
function compSupplierIndex(address,address) public view virtual returns (uint);
function compAccrued(address) public view virtual returns (uint);
function compBorrowState(address) public view virtual returns (CompMarketState memory);
function compBorrowerIndex(address,address) public view virtual returns (uint);
function enterMarkets(address[] calldata cTokens) external virtual returns (uint256[] memory);
function exitMarket(address cToken) external virtual returns (uint256);
function getAssetsIn(address account) external virtual view returns (address[] memory);
function markets(address account) public virtual view returns (bool, uint256);
function getAccountLiquidity(address account) external virtual view returns (uint256, uint256, uint256);
function oracle() public virtual view returns (address);
}
abstract contract DSProxyInterface {
/// Truffle wont compile if this isn't commented
// function execute(bytes memory _code, bytes memory _data)
// public virtual
// payable
// returns (address, bytes32);
function execute(address _target, bytes memory _data) public virtual payable returns (bytes32);
function setCache(address _cacheAddr) public virtual payable returns (bool);
function owner() public virtual returns (address);
}
abstract contract DaiJoin {
function vat() public virtual returns (Vat);
function dai() public virtual returns (Gem);
function join(address, uint) public virtual payable;
function exit(address, uint) public virtual;
}
interface ERC20 {
function totalSupply() external view returns (uint256 supply);
function balanceOf(address _owner) external view returns (uint256 balance);
function transfer(address _to, uint256 _value) external returns (bool success);
function transferFrom(address _from, address _to, uint256 _value)
external
returns (bool success);
function approve(address _spender, uint256 _value) external returns (bool success);
function allowance(address _owner, address _spender) external view returns (uint256 remaining);
function decimals() external view returns (uint256 digits);
event Approval(address indexed _owner, address indexed _spender, uint256 _value);
}
interface ExchangeInterface {
function swapEtherToToken(uint256 _ethAmount, address _tokenAddress, uint256 _maxAmount)
external
payable
returns (uint256, uint256);
function swapTokenToEther(address _tokenAddress, uint256 _amount, uint256 _maxAmount)
external
returns (uint256);
function swapTokenToToken(address _src, address _dest, uint256 _amount)
external
payable
returns (uint256);
function getExpectedRate(address src, address dest, uint256 srcQty)
external
view
returns (uint256 expectedRate);
}
interface ExchangeInterfaceV2 {
function sell(address _srcAddr, address _destAddr, uint _srcAmount) external payable returns (uint);
function buy(address _srcAddr, address _destAddr, uint _destAmount) external payable returns(uint);
function getSellRate(address _srcAddr, address _destAddr, uint _srcAmount) external view returns (uint);
function getBuyRate(address _srcAddr, address _destAddr, uint _srcAmount) external view returns (uint);
}
interface ExchangeInterfaceV3 {
function sell(address _srcAddr, address _destAddr, uint _srcAmount, bytes memory _additionalData) external payable returns (uint);
function buy(address _srcAddr, address _destAddr, uint _destAmount, bytes memory _additionalData) external payable returns(uint);
function getSellRate(address _srcAddr, address _destAddr, uint _srcAmount, bytes memory _additionalData) external view returns (uint);
function getBuyRate(address _srcAddr, address _destAddr, uint _srcAmount, bytes memory _additionalData) external view returns (uint);
}
abstract contract Flipper {
function bids(uint _bidId) public virtual returns (uint256, uint256, address, uint48, uint48, address, address, uint256);
function tend(uint id, uint lot, uint bid) virtual external;
function dent(uint id, uint lot, uint bid) virtual external;
function deal(uint id) virtual external;
}
abstract contract GasTokenInterface is ERC20 {
function free(uint256 value) public virtual returns (bool success);
function freeUpTo(uint256 value) public virtual returns (uint256 freed);
function freeFrom(address from, uint256 value) public virtual returns (bool success);
function freeFromUpTo(address from, uint256 value) public virtual returns (uint256 freed);
}
abstract contract Gem {
function dec() virtual public returns (uint);
function gem() virtual public returns (Gem);
function join(address, uint) virtual public payable;
function exit(address, uint) virtual public;
function approve(address, uint) virtual public;
function transfer(address, uint) virtual public returns (bool);
function transferFrom(address, address, uint) virtual public returns (bool);
function deposit() virtual public payable;
function withdraw(uint) virtual public;
function allowance(address, address) virtual public returns (uint);
}
abstract contract IAToken {
function redeem(uint256 _amount) external virtual;
function balanceOf(address _owner) external virtual view returns (uint256 balance);
}
abstract contract IAaveSubscription {
function subscribe(uint128 _minRatio, uint128 _maxRatio, uint128 _optimalBoost, uint128 _optimalRepay, bool _boostEnabled) public virtual;
function unsubscribe() public virtual;
}
abstract contract ICompoundSubscription {
function subscribe(uint128 _minRatio, uint128 _maxRatio, uint128 _optimalBoost, uint128 _optimalRepay, bool _boostEnabled) public virtual;
function unsubscribe() public virtual;
}
abstract contract ICompoundSubscriptions {
function unsubscribe() external virtual ;
}
abstract contract ILendingPool {
function flashLoan( address payable _receiver, address _reserve, uint _amount, bytes calldata _params) external virtual;
function deposit(address _reserve, uint256 _amount, uint16 _referralCode) external virtual payable;
function setUserUseReserveAsCollateral(address _reserve, bool _useAsCollateral) external virtual;
function borrow(address _reserve, uint256 _amount, uint256 _interestRateMode, uint16 _referralCode) external virtual;
function repay( address _reserve, uint256 _amount, address payable _onBehalfOf) external virtual payable;
function swapBorrowRateMode(address _reserve) external virtual;
function getReserves() external virtual view returns(address[] memory);
/// @param _reserve underlying token address
function getReserveData(address _reserve)
external virtual
view
returns (
uint256 totalLiquidity, // reserve total liquidity
uint256 availableLiquidity, // reserve available liquidity for borrowing
uint256 totalBorrowsStable, // total amount of outstanding borrows at Stable rate
uint256 totalBorrowsVariable, // total amount of outstanding borrows at Variable rate
uint256 liquidityRate, // current deposit APY of the reserve for depositors, in Ray units.
uint256 variableBorrowRate, // current variable rate APY of the reserve pool, in Ray units.
uint256 stableBorrowRate, // current stable rate APY of the reserve pool, in Ray units.
uint256 averageStableBorrowRate, // current average stable borrow rate
uint256 utilizationRate, // expressed as total borrows/total liquidity.
uint256 liquidityIndex, // cumulative liquidity index
uint256 variableBorrowIndex, // cumulative variable borrow index
address aTokenAddress, // aTokens contract address for the specific _reserve
uint40 lastUpdateTimestamp // timestamp of the last update of reserve data
);
/// @param _user users address
function getUserAccountData(address _user)
external virtual
view
returns (
uint256 totalLiquidityETH, // user aggregated deposits across all the reserves. In Wei
uint256 totalCollateralETH, // user aggregated collateral across all the reserves. In Wei
uint256 totalBorrowsETH, // user aggregated outstanding borrows across all the reserves. In Wei
uint256 totalFeesETH, // user aggregated current outstanding fees in ETH. In Wei
uint256 availableBorrowsETH, // user available amount to borrow in ETH
uint256 currentLiquidationThreshold, // user current average liquidation threshold across all the collaterals deposited
uint256 ltv, // user average Loan-to-Value between all the collaterals
uint256 healthFactor // user current Health Factor
);
/// @param _reserve underlying token address
/// @param _user users address
function getUserReserveData(address _reserve, address _user)
external virtual
view
returns (
uint256 currentATokenBalance, // user current reserve aToken balance
uint256 currentBorrowBalance, // user current reserve outstanding borrow balance
uint256 principalBorrowBalance, // user balance of borrowed asset
uint256 borrowRateMode, // user borrow rate mode either Stable or Variable
uint256 borrowRate, // user current borrow rate APY
uint256 liquidityRate, // user current earn rate on _reserve
uint256 originationFee, // user outstanding loan origination fee
uint256 variableBorrowIndex, // user variable cumulative index
uint256 lastUpdateTimestamp, // Timestamp of the last data update
bool usageAsCollateralEnabled // Whether the user's current reserve is enabled as a collateral
);
function getReserveConfigurationData(address _reserve)
external virtual
view
returns (
uint256 ltv,
uint256 liquidationThreshold,
uint256 liquidationBonus,
address rateStrategyAddress,
bool usageAsCollateralEnabled,
bool borrowingEnabled,
bool stableBorrowRateEnabled,
bool isActive
);
// ------------------ LendingPoolCoreData ------------------------
function getReserveATokenAddress(address _reserve) public virtual view returns (address);
function getReserveConfiguration(address _reserve)
external virtual
view
returns (uint256, uint256, uint256, bool);
function getUserUnderlyingAssetBalance(address _reserve, address _user)
public virtual
view
returns (uint256);
function getReserveCurrentLiquidityRate(address _reserve)
public virtual
view
returns (uint256);
function getReserveCurrentVariableBorrowRate(address _reserve)
public virtual
view
returns (uint256);
function getReserveCurrentStableBorrowRate(address _reserve)
public virtual
view
returns (uint256);
function getReserveTotalLiquidity(address _reserve)
public virtual
view
returns (uint256);
function getReserveAvailableLiquidity(address _reserve)
public virtual
view
returns (uint256);
function getReserveTotalBorrowsVariable(address _reserve)
public virtual
view
returns (uint256);
// ---------------- LendingPoolDataProvider ---------------------
function calculateUserGlobalData(address _user)
public virtual
view
returns (
uint256 totalLiquidityBalanceETH,
uint256 totalCollateralBalanceETH,
uint256 totalBorrowBalanceETH,
uint256 totalFeesETH,
uint256 currentLtv,
uint256 currentLiquidationThreshold,
uint256 healthFactor,
bool healthFactorBelowThreshold
);
}
abstract contract ILendingPoolAddressesProvider {
function getLendingPool() public virtual view returns (address);
function getLendingPoolCore() public virtual view returns (address payable);
function getLendingPoolConfigurator() public virtual view returns (address);
function getLendingPoolDataProvider() public virtual view returns (address);
function getLendingPoolParametersProvider() public virtual view returns (address);
function getTokenDistributor() public virtual view returns (address);
function getFeeProvider() public virtual view returns (address);
function getLendingPoolLiquidationManager() public virtual view returns (address);
function getLendingPoolManager() public virtual view returns (address);
function getPriceOracle() public virtual view returns (address);
function getLendingRateOracle() public virtual view returns (address);
}
abstract contract ILoanShifter {
function getLoanAmount(uint, address) public virtual returns (uint);
function getUnderlyingAsset(address _addr) public view virtual returns (address);
}
abstract contract IMCDSubscriptions {
function unsubscribe(uint256 _cdpId) external virtual ;
function subscribersPos(uint256 _cdpId) external virtual returns (uint256, bool);
}
abstract contract IPriceOracleGetterAave {
function getAssetPrice(address _asset) external virtual view returns (uint256);
function getAssetsPrices(address[] calldata _assets) external virtual view returns(uint256[] memory);
function getSourceOfAsset(address _asset) external virtual view returns(address);
function getFallbackOracle() external virtual view returns(address);
}
abstract contract ITokenInterface is ERC20 {
function assetBalanceOf(address _owner) public virtual view returns (uint256);
function mint(address receiver, uint256 depositAmount) external virtual returns (uint256 mintAmount);
function burn(address receiver, uint256 burnAmount) external virtual returns (uint256 loanAmountPaid);
function tokenPrice() public virtual view returns (uint256 price);
}
abstract contract Join {
bytes32 public ilk;
function dec() virtual public view returns (uint);
function gem() virtual public view returns (Gem);
function join(address, uint) virtual public payable;
function exit(address, uint) virtual public;
}
abstract contract Jug {
struct Ilk {
uint256 duty;
uint256 rho;
}
mapping (bytes32 => Ilk) public ilks;
function drip(bytes32) public virtual returns (uint);
}
abstract contract KyberNetworkProxyInterface {
function maxGasPrice() external virtual view returns (uint256);
function getUserCapInWei(address user) external virtual view returns (uint256);
function getUserCapInTokenWei(address user, ERC20 token) external virtual view returns (uint256);
function enabled() external virtual view returns (bool);
function info(bytes32 id) external virtual view returns (uint256);
function getExpectedRate(ERC20 src, ERC20 dest, uint256 srcQty)
public virtual
view
returns (uint256 expectedRate, uint256 slippageRate);
function tradeWithHint(
ERC20 src,
uint256 srcAmount,
ERC20 dest,
address destAddress,
uint256 maxDestAmount,
uint256 minConversionRate,
address walletId,
bytes memory hint
) public virtual payable returns (uint256);
function trade(
ERC20 src,
uint256 srcAmount,
ERC20 dest,
address destAddress,
uint256 maxDestAmount,
uint256 minConversionRate,
address walletId
) public virtual payable returns (uint256);
function swapEtherToToken(ERC20 token, uint256 minConversionRate)
external virtual
payable
returns (uint256);
function swapTokenToEther(ERC20 token, uint256 tokenQty, uint256 minRate)
external virtual
payable
returns (uint256);
function swapTokenToToken(ERC20 src, uint256 srcAmount, ERC20 dest, uint256 minConversionRate)
public virtual
returns (uint256);
}
abstract contract Manager {
function last(address) virtual public returns (uint);
function cdpCan(address, uint, address) virtual public view returns (uint);
function ilks(uint) virtual public view returns (bytes32);
function owns(uint) virtual public view returns (address);
function urns(uint) virtual public view returns (address);
function vat() virtual public view returns (address);
function open(bytes32, address) virtual public returns (uint);
function give(uint, address) virtual public;
function cdpAllow(uint, address, uint) virtual public;
function urnAllow(address, uint) virtual public;
function frob(uint, int, int) virtual public;
function flux(uint, address, uint) virtual public;
function move(uint, address, uint) virtual public;
function exit(address, uint, address, uint) virtual public;
function quit(uint, address) virtual public;
function enter(address, uint) virtual public;
function shift(uint, uint) virtual public;
}
abstract contract OasisInterface {
function getBuyAmount(address tokenToBuy, address tokenToPay, uint256 amountToPay)
external
virtual
view
returns (uint256 amountBought);
function getPayAmount(address tokenToPay, address tokenToBuy, uint256 amountToBuy)
public virtual
view
returns (uint256 amountPaid);
function sellAllAmount(address pay_gem, uint256 pay_amt, address buy_gem, uint256 min_fill_amount)
public virtual
returns (uint256 fill_amt);
function buyAllAmount(address buy_gem, uint256 buy_amt, address pay_gem, uint256 max_fill_amount)
public virtual
returns (uint256 fill_amt);
}
abstract contract Osm {
mapping(address => uint256) public bud;
function peep() external view virtual returns (bytes32, bool);
}
abstract contract OsmMom {
mapping (bytes32 => address) public osms;
}
abstract contract PipInterface {
function read() public virtual returns (bytes32);
}
abstract contract ProxyRegistryInterface {
function proxies(address _owner) public virtual view returns (address);
function build(address) public virtual returns (address);
}
abstract contract Spotter {
struct Ilk {
PipInterface pip;
uint256 mat;
}
mapping (bytes32 => Ilk) public ilks;
uint256 public par;
}
abstract contract TokenInterface {
function allowance(address, address) public virtual returns (uint256);
function balanceOf(address) public virtual returns (uint256);
function approve(address, uint256) public virtual;
function transfer(address, uint256) public virtual returns (bool);
function transferFrom(address, address, uint256) public virtual returns (bool);
function deposit() public virtual payable;
function withdraw(uint256) public virtual;
}
abstract contract UniswapExchangeInterface {
function getEthToTokenInputPrice(uint256 eth_sold)
external virtual
view
returns (uint256 tokens_bought);
function getEthToTokenOutputPrice(uint256 tokens_bought)
external virtual
view
returns (uint256 eth_sold);
function getTokenToEthInputPrice(uint256 tokens_sold)
external virtual
view
returns (uint256 eth_bought);
function getTokenToEthOutputPrice(uint256 eth_bought)
external virtual
view
returns (uint256 tokens_sold);
function tokenToEthTransferInput(
uint256 tokens_sold,
uint256 min_eth,
uint256 deadline,
address recipient
) external virtual returns (uint256 eth_bought);
function ethToTokenTransferInput(uint256 min_tokens, uint256 deadline, address recipient)
external virtual
payable
returns (uint256 tokens_bought);
function tokenToTokenTransferInput(
uint256 tokens_sold,
uint256 min_tokens_bought,
uint256 min_eth_bought,
uint256 deadline,
address recipient,
address token_addr
) external virtual returns (uint256 tokens_bought);
function ethToTokenTransferOutput(
uint256 tokens_bought,
uint256 deadline,
address recipient
) external virtual payable returns (uint256 eth_sold);
function tokenToEthTransferOutput(
uint256 eth_bought,
uint256 max_tokens,
uint256 deadline,
address recipient
) external virtual returns (uint256 tokens_sold);
function tokenToTokenTransferOutput(
uint256 tokens_bought,
uint256 max_tokens_sold,
uint256 max_eth_sold,
uint256 deadline,
address recipient,
address token_addr
) external virtual returns (uint256 tokens_sold);
}
abstract contract UniswapFactoryInterface {
function getExchange(address token) external view virtual returns (address exchange);
}
abstract contract UniswapRouterInterface {
function swapExactTokensForETH(uint amountIn, uint amountOutMin, address[] calldata path, address to, uint deadline)
external
virtual
returns (uint[] memory amounts);
function swapExactTokensForTokens(
uint amountIn,
uint amountOutMin,
address[] calldata path,
address to,
uint deadline
) external virtual returns (uint[] memory amounts);
function swapTokensForExactETH(uint amountOut, uint amountInMax, address[] calldata path, address to, uint deadline)
external virtual
returns (uint[] memory amounts);
function swapTokensForExactTokens(
uint amountOut,
uint amountInMax,
address[] calldata path,
address to,
uint deadline
) external virtual returns (uint[] memory amounts);
function getAmountsOut(uint amountIn, address[] memory path) public virtual view returns (uint[] memory amounts);
function getAmountsIn(uint amountOut, address[] memory path) public virtual view returns (uint[] memory amounts);
}
abstract contract Vat {
struct Urn {
uint256 ink; // Locked Collateral [wad]
uint256 art; // Normalised Debt [wad]
}
struct Ilk {
uint256 Art; // Total Normalised Debt [wad]
uint256 rate; // Accumulated Rates [ray]
uint256 spot; // Price with Safety Margin [ray]
uint256 line; // Debt Ceiling [rad]
uint256 dust; // Urn Debt Floor [rad]
}
mapping (bytes32 => mapping (address => Urn )) public urns;
mapping (bytes32 => Ilk) public ilks;
mapping (bytes32 => mapping (address => uint)) public gem; // [wad]
function can(address, address) virtual public view returns (uint);
function dai(address) virtual public view returns (uint);
function frob(bytes32, address, address, address, int, int) virtual public;
function hope(address) virtual public;
function move(address, address, uint) virtual public;
function fork(bytes32, address, address, int, int) virtual public;
}
contract DefisaverLogger {
event LogEvent(
address indexed contractAddress,
address indexed caller,
string indexed logName,
bytes data
);
// solhint-disable-next-line func-name-mixedcase
function Log(address _contract, address _caller, string memory _logName, bytes memory _data)
public
{
emit LogEvent(_contract, _caller, _logName, _data);
}
}
contract MCDMonitorProxyV2 is AdminAuth {
uint public CHANGE_PERIOD;
address public monitor;
address public newMonitor;
address public lastMonitor;
uint public changeRequestedTimestamp;
mapping(address => bool) public allowed;
event MonitorChangeInitiated(address oldMonitor, address newMonitor);
event MonitorChangeCanceled();
event MonitorChangeFinished(address monitor);
event MonitorChangeReverted(address monitor);
// if someone who is allowed become malicious, owner can't be changed
modifier onlyAllowed() {
require(allowed[msg.sender] || msg.sender == owner);
_;
}
modifier onlyMonitor() {
require (msg.sender == monitor);
_;
}
constructor(uint _changePeriod) public {
CHANGE_PERIOD = _changePeriod * 1 days;
}
/// @notice Only monitor contract is able to call execute on users proxy
/// @param _owner Address of cdp owner (users DSProxy address)
/// @param _saverProxy Address of MCDSaverProxy
/// @param _data Data to send to MCDSaverProxy
function callExecute(address _owner, address _saverProxy, bytes memory _data) public payable onlyMonitor {
// execute reverts if calling specific method fails
DSProxyInterface(_owner).execute{value: msg.value}(_saverProxy, _data);
// return if anything left
if (address(this).balance > 0) {
msg.sender.transfer(address(this).balance);
}
}
/// @notice Allowed users are able to set Monitor contract without any waiting period first time
/// @param _monitor Address of Monitor contract
function setMonitor(address _monitor) public onlyAllowed {
require(monitor == address(0));
monitor = _monitor;
}
/// @notice Allowed users are able to start procedure for changing monitor
/// @dev after CHANGE_PERIOD needs to call confirmNewMonitor to actually make a change
/// @param _newMonitor address of new monitor
function changeMonitor(address _newMonitor) public onlyAllowed {
require(changeRequestedTimestamp == 0);
changeRequestedTimestamp = now;
lastMonitor = monitor;
newMonitor = _newMonitor;
emit MonitorChangeInitiated(lastMonitor, newMonitor);
}
/// @notice At any point allowed users are able to cancel monitor change
function cancelMonitorChange() public onlyAllowed {
require(changeRequestedTimestamp > 0);
changeRequestedTimestamp = 0;
newMonitor = address(0);
emit MonitorChangeCanceled();
}
/// @notice Anyone is able to confirm new monitor after CHANGE_PERIOD if process is started
function confirmNewMonitor() public onlyAllowed {
require((changeRequestedTimestamp + CHANGE_PERIOD) < now);
require(changeRequestedTimestamp != 0);
require(newMonitor != address(0));
monitor = newMonitor;
newMonitor = address(0);
changeRequestedTimestamp = 0;
emit MonitorChangeFinished(monitor);
}
/// @notice Its possible to revert monitor to last used monitor
function revertMonitor() public onlyAllowed {
require(lastMonitor != address(0));
monitor = lastMonitor;
emit MonitorChangeReverted(monitor);
}
/// @notice Allowed users are able to add new allowed user
/// @param _user Address of user that will be allowed
function addAllowed(address _user) public onlyAllowed {
allowed[_user] = true;
}
/// @notice Allowed users are able to remove allowed user
/// @dev owner is always allowed even if someone tries to remove it from allowed mapping
/// @param _user Address of allowed user
function removeAllowed(address _user) public onlyAllowed {
allowed[_user] = false;
}
function setChangePeriod(uint _periodInDays) public onlyAllowed {
require(_periodInDays * 1 days > CHANGE_PERIOD);
CHANGE_PERIOD = _periodInDays * 1 days;
}
}
contract MCDPriceVerifier is AdminAuth {
OsmMom public osmMom = OsmMom(0x76416A4d5190d071bfed309861527431304aA14f);
Manager public manager = Manager(0x5ef30b9986345249bc32d8928B7ee64DE9435E39);
mapping(address => bool) public authorized;
function verifyVaultNextPrice(uint _nextPrice, uint _cdpId) public view returns(bool) {
require(authorized[msg.sender]);
bytes32 ilk = manager.ilks(_cdpId);
return verifyNextPrice(_nextPrice, ilk);
}
function verifyNextPrice(uint _nextPrice, bytes32 _ilk) public view returns(bool) {
require(authorized[msg.sender]);
address osmAddress = osmMom.osms(_ilk);
uint whitelisted = Osm(osmAddress).bud(address(this));
// If contracts doesn't have access return true
if (whitelisted != 1) return true;
(bytes32 price, bool has) = Osm(osmAddress).peep();
return has ? uint(price) == _nextPrice : false;
}
function setAuthorized(address _address, bool _allowed) public onlyOwner {
authorized[_address] = _allowed;
}
}
abstract contract StaticV2 {
enum Method { Boost, Repay }
struct CdpHolder {
uint128 minRatio;
uint128 maxRatio;
uint128 optimalRatioBoost;
uint128 optimalRatioRepay;
address owner;
uint cdpId;
bool boostEnabled;
bool nextPriceEnabled;
}
struct SubPosition {
uint arrPos;
bool subscribed;
}
}
contract SubscriptionsInterfaceV2 {
function subscribe(uint _cdpId, uint128 _minRatio, uint128 _maxRatio, uint128 _optimalBoost, uint128 _optimalRepay, bool _boostEnabled, bool _nextPriceEnabled) external {}
function unsubscribe(uint _cdpId) external {}
}
contract SubscriptionsProxyV2 {
address public constant MONITOR_PROXY_ADDRESS = 0x7456f4218874eAe1aF8B83a64848A1B89fEB7d7C;
address public constant OLD_SUBSCRIPTION = 0x83152CAA0d344a2Fd428769529e2d490A88f4393;
address public constant FACTORY_ADDRESS = 0x5a15566417e6C1c9546523066500bDDBc53F88C7;
function migrate(uint _cdpId, uint128 _minRatio, uint128 _maxRatio, uint128 _optimalRatioBoost, uint128 _optimalRatioRepay, bool _boostEnabled, bool _nextPriceEnabled, address _subscriptions) public {
SubscriptionsInterfaceV2(OLD_SUBSCRIPTION).unsubscribe(_cdpId);
subscribe(_cdpId, _minRatio, _maxRatio, _optimalRatioBoost, _optimalRatioRepay, _boostEnabled, _nextPriceEnabled, _subscriptions);
}
function subscribe(uint _cdpId, uint128 _minRatio, uint128 _maxRatio, uint128 _optimalRatioBoost, uint128 _optimalRatioRepay, bool _boostEnabled, bool _nextPriceEnabled, address _subscriptions) public {
address currAuthority = address(DSAuth(address(this)).authority());
DSGuard guard = DSGuard(currAuthority);
if (currAuthority == address(0)) {
guard = DSGuardFactory(FACTORY_ADDRESS).newGuard();
DSAuth(address(this)).setAuthority(DSAuthority(address(guard)));
}
guard.permit(MONITOR_PROXY_ADDRESS, address(this), bytes4(keccak256("execute(address,bytes)")));
SubscriptionsInterfaceV2(_subscriptions).subscribe(_cdpId, _minRatio, _maxRatio, _optimalRatioBoost, _optimalRatioRepay, _boostEnabled, _nextPriceEnabled);
}
function update(uint _cdpId, uint128 _minRatio, uint128 _maxRatio, uint128 _optimalRatioBoost, uint128 _optimalRatioRepay, bool _boostEnabled, bool _nextPriceEnabled, address _subscriptions) public {
SubscriptionsInterfaceV2(_subscriptions).subscribe(_cdpId, _minRatio, _maxRatio, _optimalRatioBoost, _optimalRatioRepay, _boostEnabled, _nextPriceEnabled);
}
function unsubscribe(uint _cdpId, address _subscriptions) public {
SubscriptionsInterfaceV2(_subscriptions).unsubscribe(_cdpId);
}
}
contract SubscriptionsV2 is AdminAuth, StaticV2 {
bytes32 internal constant ETH_ILK = 0x4554482d41000000000000000000000000000000000000000000000000000000;
bytes32 internal constant BAT_ILK = 0x4241542d41000000000000000000000000000000000000000000000000000000;
address public constant MANAGER_ADDRESS = 0x5ef30b9986345249bc32d8928B7ee64DE9435E39;
address public constant VAT_ADDRESS = 0x35D1b3F3D7966A1DFe207aa4514C12a259A0492B;
address public constant SPOTTER_ADDRESS = 0x65C79fcB50Ca1594B025960e539eD7A9a6D434A3;
CdpHolder[] public subscribers;
mapping (uint => SubPosition) public subscribersPos;
mapping (bytes32 => uint) public minLimits;
uint public changeIndex;
Manager public manager = Manager(MANAGER_ADDRESS);
Vat public vat = Vat(VAT_ADDRESS);
Spotter public spotter = Spotter(SPOTTER_ADDRESS);
MCDSaverProxy public saverProxy;
event Subscribed(address indexed owner, uint cdpId);
event Unsubscribed(address indexed owner, uint cdpId);
event Updated(address indexed owner, uint cdpId);
event ParamUpdates(address indexed owner, uint cdpId, uint128, uint128, uint128, uint128, bool boostEnabled);
/// @param _saverProxy Address of the MCDSaverProxy contract
constructor(address _saverProxy) public {
saverProxy = MCDSaverProxy(payable(_saverProxy));
minLimits[ETH_ILK] = 1700000000000000000;
minLimits[BAT_ILK] = 1700000000000000000;
}
/// @dev Called by the DSProxy contract which owns the CDP
/// @notice Adds the users CDP in the list of subscriptions so it can be monitored
/// @param _cdpId Id of the CDP
/// @param _minRatio Minimum ratio below which repay is triggered
/// @param _maxRatio Maximum ratio after which boost is triggered
/// @param _optimalBoost Ratio amount which boost should target
/// @param _optimalRepay Ratio amount which repay should target
/// @param _boostEnabled Boolean determing if boost is enabled
/// @param _nextPriceEnabled Boolean determing if we can use nextPrice for this cdp
function subscribe(uint _cdpId, uint128 _minRatio, uint128 _maxRatio, uint128 _optimalBoost, uint128 _optimalRepay, bool _boostEnabled, bool _nextPriceEnabled) external {
require(isOwner(msg.sender, _cdpId), "Must be called by Cdp owner");
// if boost is not enabled, set max ratio to max uint
uint128 localMaxRatio = _boostEnabled ? _maxRatio : uint128(-1);
require(checkParams(manager.ilks(_cdpId), _minRatio, localMaxRatio), "Must be correct params");
SubPosition storage subInfo = subscribersPos[_cdpId];
CdpHolder memory subscription = CdpHolder({
minRatio: _minRatio,
maxRatio: localMaxRatio,
optimalRatioBoost: _optimalBoost,
optimalRatioRepay: _optimalRepay,
owner: msg.sender,
cdpId: _cdpId,
boostEnabled: _boostEnabled,
nextPriceEnabled: _nextPriceEnabled
});
changeIndex++;
if (subInfo.subscribed) {
subscribers[subInfo.arrPos] = subscription;
emit Updated(msg.sender, _cdpId);
emit ParamUpdates(msg.sender, _cdpId, _minRatio, localMaxRatio, _optimalBoost, _optimalRepay, _boostEnabled);
} else {
subscribers.push(subscription);
subInfo.arrPos = subscribers.length - 1;
subInfo.subscribed = true;
emit Subscribed(msg.sender, _cdpId);
}
}
/// @notice Called by the users DSProxy
/// @dev Owner who subscribed cancels his subscription
function unsubscribe(uint _cdpId) external {
require(isOwner(msg.sender, _cdpId), "Must be called by Cdp owner");
_unsubscribe(_cdpId);
}
/// @dev Checks if the _owner is the owner of the CDP
function isOwner(address _owner, uint _cdpId) internal view returns (bool) {
return getOwner(_cdpId) == _owner;
}
/// @dev Checks limit for minimum ratio and if minRatio is bigger than max
function checkParams(bytes32 _ilk, uint128 _minRatio, uint128 _maxRatio) internal view returns (bool) {
if (_minRatio < minLimits[_ilk]) {
return false;
}
if (_minRatio > _maxRatio) {
return false;
}
return true;
}
/// @dev Internal method to remove a subscriber from the list
function _unsubscribe(uint _cdpId) internal {
require(subscribers.length > 0, "Must have subscribers in the list");
SubPosition storage subInfo = subscribersPos[_cdpId];
require(subInfo.subscribed, "Must first be subscribed");
uint lastCdpId = subscribers[subscribers.length - 1].cdpId;
SubPosition storage subInfo2 = subscribersPos[lastCdpId];
subInfo2.arrPos = subInfo.arrPos;
subscribers[subInfo.arrPos] = subscribers[subscribers.length - 1];
subscribers.pop();
changeIndex++;
subInfo.subscribed = false;
subInfo.arrPos = 0;
emit Unsubscribed(msg.sender, _cdpId);
}
/// @notice Returns an address that owns the CDP
/// @param _cdpId Id of the CDP
function getOwner(uint _cdpId) public view returns(address) {
return manager.owns(_cdpId);
}
/// @notice Helper method for the front to get all the info about the subscribed CDP
function getSubscribedInfo(uint _cdpId) public view returns(bool, uint128, uint128, uint128, uint128, address, uint coll, uint debt) {
SubPosition memory subInfo = subscribersPos[_cdpId];
if (!subInfo.subscribed) return (false, 0, 0, 0, 0, address(0), 0, 0);
(coll, debt) = saverProxy.getCdpInfo(manager, _cdpId, manager.ilks(_cdpId));
CdpHolder memory subscriber = subscribers[subInfo.arrPos];
return (
true,
subscriber.minRatio,
subscriber.maxRatio,
subscriber.optimalRatioRepay,
subscriber.optimalRatioBoost,
subscriber.owner,
coll,
debt
);
}
function getCdpHolder(uint _cdpId) public view returns (bool subscribed, CdpHolder memory) {
SubPosition memory subInfo = subscribersPos[_cdpId];
if (!subInfo.subscribed) return (false, CdpHolder(0, 0, 0, 0, address(0), 0, false, false));
CdpHolder memory subscriber = subscribers[subInfo.arrPos];
return (true, subscriber);
}
/// @notice Helper method for the front to get the information about the ilk of a CDP
function getIlkInfo(bytes32 _ilk, uint _cdpId) public view returns(bytes32 ilk, uint art, uint rate, uint spot, uint line, uint dust, uint mat, uint par) {
// send either ilk or cdpId
if (_ilk == bytes32(0)) {
_ilk = manager.ilks(_cdpId);
}
ilk = _ilk;
(,mat) = spotter.ilks(_ilk);
par = spotter.par();
(art, rate, spot, line, dust) = vat.ilks(_ilk);
}
/// @notice Helper method to return all the subscribed CDPs
function getSubscribers() public view returns (CdpHolder[] memory) {
return subscribers;
}
/// @notice Helper method to return all the subscribed CDPs
function getSubscribersByPage(uint _page, uint _perPage) public view returns (CdpHolder[] memory) {
CdpHolder[] memory holders = new CdpHolder[](_perPage);
uint start = _page * _perPage;
uint end = start + _perPage;
uint count = 0;
for (uint i=start; i<end; i++) {
holders[count] = subscribers[i];
count++;
}
return holders;
}
////////////// ADMIN METHODS ///////////////////
/// @notice Admin function to change a min. limit for an asset
function changeMinRatios(bytes32 _ilk, uint _newRatio) public onlyOwner {
minLimits[_ilk] = _newRatio;
}
/// @notice Admin function to unsubscribe a CDP
function unsubscribeByAdmin(uint _cdpId) public onlyOwner {
SubPosition storage subInfo = subscribersPos[_cdpId];
if (subInfo.subscribed) {
_unsubscribe(_cdpId);
}
}
}
contract BidProxy {
address public constant DAI_JOIN = 0x9759A6Ac90977b93B58547b4A71c78317f391A28;
address public constant VAT_ADDRESS = 0x35D1b3F3D7966A1DFe207aa4514C12a259A0492B;
address public constant DAI_ADDRESS = 0x6B175474E89094C44Da98b954EedeAC495271d0F;
function daiBid(uint _bidId, uint _amount, address _flipper) public {
uint tendAmount = _amount * (10 ** 27);
joinDai(_amount);
(, uint lot, , , , , , ) = Flipper(_flipper).bids(_bidId);
Vat(VAT_ADDRESS).hope(_flipper);
Flipper(_flipper).tend(_bidId, lot, tendAmount);
}
function collateralBid(uint _bidId, uint _amount, address _flipper) public {
(uint bid, , , , , , , ) = Flipper(_flipper).bids(_bidId);
joinDai(bid / (10**27));
Vat(VAT_ADDRESS).hope(_flipper);
Flipper(_flipper).dent(_bidId, _amount, bid);
}
function closeBid(uint _bidId, address _flipper, address _joinAddr) public {
bytes32 ilk = Join(_joinAddr).ilk();
Flipper(_flipper).deal(_bidId);
uint amount = Vat(VAT_ADDRESS).gem(ilk, address(this));
Vat(VAT_ADDRESS).hope(_joinAddr);
Gem(_joinAddr).exit(msg.sender, amount);
}
function exitCollateral(address _joinAddr) public {
bytes32 ilk = Join(_joinAddr).ilk();
uint amount = Vat(VAT_ADDRESS).gem(ilk, address(this));
Vat(VAT_ADDRESS).hope(_joinAddr);
Gem(_joinAddr).exit(msg.sender, amount);
}
function exitDai() public {
uint amount = Vat(VAT_ADDRESS).dai(address(this)) / (10**27);
Vat(VAT_ADDRESS).hope(DAI_JOIN);
Gem(DAI_JOIN).exit(msg.sender, amount);
}
function withdrawToken(address _token) public {
uint balance = ERC20(_token).balanceOf(address(this));
ERC20(_token).transfer(msg.sender, balance);
}
function withdrawEth() public {
uint balance = address(this).balance;
msg.sender.transfer(balance);
}
function joinDai(uint _amount) internal {
uint amountInVat = Vat(VAT_ADDRESS).dai(address(this)) / (10**27);
if (_amount > amountInVat) {
uint amountDiff = (_amount - amountInVat) + 1;
ERC20(DAI_ADDRESS).transferFrom(msg.sender, address(this), amountDiff);
ERC20(DAI_ADDRESS).approve(DAI_JOIN, amountDiff);
Join(DAI_JOIN).join(address(this), amountDiff);
}
}
}
abstract contract IMCDSubscriptions {
function unsubscribe(uint256 _cdpId) external virtual ;
function subscribersPos(uint256 _cdpId) external virtual returns (uint256, bool);
}
abstract contract GemLike {
function approve(address, uint256) public virtual;
function transfer(address, uint256) public virtual;
function transferFrom(address, address, uint256) public virtual;
function deposit() public virtual payable;
function withdraw(uint256) public virtual;
}
abstract contract ManagerLike {
function cdpCan(address, uint256, address) public virtual view returns (uint256);
function ilks(uint256) public virtual view returns (bytes32);
function owns(uint256) public virtual view returns (address);
function urns(uint256) public virtual view returns (address);
function vat() public virtual view returns (address);
function open(bytes32, address) public virtual returns (uint256);
function give(uint256, address) public virtual;
function cdpAllow(uint256, address, uint256) public virtual;
function urnAllow(address, uint256) public virtual;
function frob(uint256, int256, int256) public virtual;
function flux(uint256, address, uint256) public virtual;
function move(uint256, address, uint256) public virtual;
function exit(address, uint256, address, uint256) public virtual;
function quit(uint256, address) public virtual;
function enter(address, uint256) public virtual;
function shift(uint256, uint256) public virtual;
}
abstract contract VatLike {
function can(address, address) public virtual view returns (uint256);
function ilks(bytes32) public virtual view returns (uint256, uint256, uint256, uint256, uint256);
function dai(address) public virtual view returns (uint256);
function urns(bytes32, address) public virtual view returns (uint256, uint256);
function frob(bytes32, address, address, address, int256, int256) public virtual;
function hope(address) public virtual;
function move(address, address, uint256) public virtual;
}
abstract contract GemJoinLike {
function dec() public virtual returns (uint256);
function gem() public virtual returns (GemLike);
function join(address, uint256) public virtual payable;
function exit(address, uint256) public virtual;
}
abstract contract GNTJoinLike {
function bags(address) public virtual view returns (address);
function make(address) public virtual returns (address);
}
abstract contract DaiJoinLike {
function vat() public virtual returns (VatLike);
function dai() public virtual returns (GemLike);
function join(address, uint256) public virtual payable;
function exit(address, uint256) public virtual;
}
abstract contract HopeLike {
function hope(address) public virtual;
function nope(address) public virtual;
}
abstract contract ProxyRegistryInterface {
function build(address) public virtual returns (address);
}
abstract contract EndLike {
function fix(bytes32) public virtual view returns (uint256);
function cash(bytes32, uint256) public virtual;
function free(bytes32) public virtual;
function pack(uint256) public virtual;
function skim(bytes32, address) public virtual;
}
abstract contract JugLike {
function drip(bytes32) public virtual returns (uint256);
}
abstract contract PotLike {
function pie(address) public virtual view returns (uint256);
function drip() public virtual returns (uint256);
function join(uint256) public virtual;
function exit(uint256) public virtual;
}
abstract contract ProxyRegistryLike {
function proxies(address) public virtual view returns (address);
function build(address) public virtual returns (address);
}
abstract contract ProxyLike {
function owner() public virtual view returns (address);
}
contract Common {
uint256 constant RAY = 10**27;
// Internal functions
function mul(uint256 x, uint256 y) internal pure returns (uint256 z) {
require(y == 0 || (z = x * y) / y == x, "mul-overflow");
}
// Public functions
// solhint-disable-next-line func-name-mixedcase
function daiJoin_join(address apt, address urn, uint256 wad) public {
// Gets DAI from the user's wallet
DaiJoinLike(apt).dai().transferFrom(msg.sender, address(this), wad);
// Approves adapter to take the DAI amount
DaiJoinLike(apt).dai().approve(apt, wad);
// Joins DAI into the vat
DaiJoinLike(apt).join(urn, wad);
}
}
contract MCDCreateProxyActions is Common {
// Internal functions
function sub(uint256 x, uint256 y) internal pure returns (uint256 z) {
require((z = x - y) <= x, "sub-overflow");
}
function toInt(uint256 x) internal pure returns (int256 y) {
y = int256(x);
require(y >= 0, "int-overflow");
}
function toRad(uint256 wad) internal pure returns (uint256 rad) {
rad = mul(wad, 10**27);
}
function convertTo18(address gemJoin, uint256 amt) internal returns (uint256 wad) {
// For those collaterals that have less than 18 decimals precision we need to do the conversion before passing to frob function
// Adapters will automatically handle the difference of precision
wad = mul(amt, 10**(18 - GemJoinLike(gemJoin).dec()));
}
function _getDrawDart(address vat, address jug, address urn, bytes32 ilk, uint256 wad)
internal
returns (int256 dart)
{
// Updates stability fee rate
uint256 rate = JugLike(jug).drip(ilk);
// Gets DAI balance of the urn in the vat
uint256 dai = VatLike(vat).dai(urn);
// If there was already enough DAI in the vat balance, just exits it without adding more debt
if (dai < mul(wad, RAY)) {
// Calculates the needed dart so together with the existing dai in the vat is enough to exit wad amount of DAI tokens
dart = toInt(sub(mul(wad, RAY), dai) / rate);
// This is neeeded due lack of precision. It might need to sum an extra dart wei (for the given DAI wad amount)
dart = mul(uint256(dart), rate) < mul(wad, RAY) ? dart + 1 : dart;
}
}
function _getWipeDart(address vat, uint256 dai, address urn, bytes32 ilk)
internal
view
returns (int256 dart)
{
// Gets actual rate from the vat
(, uint256 rate, , , ) = VatLike(vat).ilks(ilk);
// Gets actual art value of the urn
(, uint256 art) = VatLike(vat).urns(ilk, urn);
// Uses the whole dai balance in the vat to reduce the debt
dart = toInt(dai / rate);
// Checks the calculated dart is not higher than urn.art (total debt), otherwise uses its value
dart = uint256(dart) <= art ? -dart : -toInt(art);
}
function _getWipeAllWad(address vat, address usr, address urn, bytes32 ilk)
internal
view
returns (uint256 wad)
{
// Gets actual rate from the vat
(, uint256 rate, , , ) = VatLike(vat).ilks(ilk);
// Gets actual art value of the urn
(, uint256 art) = VatLike(vat).urns(ilk, urn);
// Gets actual dai amount in the urn
uint256 dai = VatLike(vat).dai(usr);
uint256 rad = sub(mul(art, rate), dai);
wad = rad / RAY;
// If the rad precision has some dust, it will need to request for 1 extra wad wei
wad = mul(wad, RAY) < rad ? wad + 1 : wad;
}
// Public functions
function transfer(address gem, address dst, uint256 wad) public {
GemLike(gem).transfer(dst, wad);
}
// solhint-disable-next-line func-name-mixedcase
function ethJoin_join(address apt, address urn) public payable {
// Wraps ETH in WETH
GemJoinLike(apt).gem().deposit{value: msg.value}();
// Approves adapter to take the WETH amount
GemJoinLike(apt).gem().approve(address(apt), msg.value);
// Joins WETH collateral into the vat
GemJoinLike(apt).join(urn, msg.value);
}
// solhint-disable-next-line func-name-mixedcase
function gemJoin_join(address apt, address urn, uint256 wad, bool transferFrom) public {
// Only executes for tokens that have approval/transferFrom implementation
if (transferFrom) {
// Gets token from the user's wallet
GemJoinLike(apt).gem().transferFrom(msg.sender, address(this), wad);
// Approves adapter to take the token amount
GemJoinLike(apt).gem().approve(apt, 0);
GemJoinLike(apt).gem().approve(apt, wad);
}
// Joins token collateral into the vat
GemJoinLike(apt).join(urn, wad);
}
function hope(address obj, address usr) public {
HopeLike(obj).hope(usr);
}
function nope(address obj, address usr) public {
HopeLike(obj).nope(usr);
}
function open(address manager, bytes32 ilk, address usr) public returns (uint256 cdp) {
cdp = ManagerLike(manager).open(ilk, usr);
}
function give(address manager, uint256 cdp, address usr) public {
ManagerLike(manager).give(cdp, usr);
}
function move(address manager, uint256 cdp, address dst, uint256 rad) public {
ManagerLike(manager).move(cdp, dst, rad);
}
function frob(address manager, uint256 cdp, int256 dink, int256 dart) public {
ManagerLike(manager).frob(cdp, dink, dart);
}
function lockETH(address manager, address ethJoin, uint256 cdp) public payable {
// Receives ETH amount, converts it to WETH and joins it into the vat
ethJoin_join(ethJoin, address(this));
// Locks WETH amount into the CDP
VatLike(ManagerLike(manager).vat()).frob(
ManagerLike(manager).ilks(cdp),
ManagerLike(manager).urns(cdp),
address(this),
address(this),
toInt(msg.value),
0
);
}
function lockGem(address manager, address gemJoin, uint256 cdp, uint256 wad, bool transferFrom)
public
{
// Takes token amount from user's wallet and joins into the vat
gemJoin_join(gemJoin, address(this), wad, transferFrom);
// Locks token amount into the CDP
VatLike(ManagerLike(manager).vat()).frob(
ManagerLike(manager).ilks(cdp),
ManagerLike(manager).urns(cdp),
address(this),
address(this),
toInt(convertTo18(gemJoin, wad)),
0
);
}
function draw(address manager, address jug, address daiJoin, uint256 cdp, uint256 wad) public {
address urn = ManagerLike(manager).urns(cdp);
address vat = ManagerLike(manager).vat();
bytes32 ilk = ManagerLike(manager).ilks(cdp);
// Generates debt in the CDP
frob(manager, cdp, 0, _getDrawDart(vat, jug, urn, ilk, wad));
// Moves the DAI amount (balance in the vat in rad) to proxy's address
move(manager, cdp, address(this), toRad(wad));
// Allows adapter to access to proxy's DAI balance in the vat
if (VatLike(vat).can(address(this), address(daiJoin)) == 0) {
VatLike(vat).hope(daiJoin);
}
// Exits DAI to the user's wallet as a token
DaiJoinLike(daiJoin).exit(msg.sender, wad);
}
function lockETHAndDraw(
address manager,
address jug,
address ethJoin,
address daiJoin,
uint256 cdp,
uint256 wadD
) public payable {
address urn = ManagerLike(manager).urns(cdp);
address vat = ManagerLike(manager).vat();
bytes32 ilk = ManagerLike(manager).ilks(cdp);
// Receives ETH amount, converts it to WETH and joins it into the vat
ethJoin_join(ethJoin, urn);
// Locks WETH amount into the CDP and generates debt
frob(manager, cdp, toInt(msg.value), _getDrawDart(vat, jug, urn, ilk, wadD));
// Moves the DAI amount (balance in the vat in rad) to proxy's address
move(manager, cdp, address(this), toRad(wadD));
// Allows adapter to access to proxy's DAI balance in the vat
if (VatLike(vat).can(address(this), address(daiJoin)) == 0) {
VatLike(vat).hope(daiJoin);
}
// Exits DAI to the user's wallet as a token
DaiJoinLike(daiJoin).exit(msg.sender, wadD);
}
function openLockETHAndDraw(
address manager,
address jug,
address ethJoin,
address daiJoin,
bytes32 ilk,
uint256 wadD,
address owner
) public payable returns (uint256 cdp) {
cdp = open(manager, ilk, address(this));
lockETHAndDraw(manager, jug, ethJoin, daiJoin, cdp, wadD);
give(manager, cdp, owner);
}
function lockGemAndDraw(
address manager,
address jug,
address gemJoin,
address daiJoin,
uint256 cdp,
uint256 wadC,
uint256 wadD,
bool transferFrom
) public {
address urn = ManagerLike(manager).urns(cdp);
address vat = ManagerLike(manager).vat();
bytes32 ilk = ManagerLike(manager).ilks(cdp);
// Takes token amount from user's wallet and joins into the vat
gemJoin_join(gemJoin, urn, wadC, transferFrom);
// Locks token amount into the CDP and generates debt
frob(
manager,
cdp,
toInt(convertTo18(gemJoin, wadC)),
_getDrawDart(vat, jug, urn, ilk, wadD)
);
// Moves the DAI amount (balance in the vat in rad) to proxy's address
move(manager, cdp, address(this), toRad(wadD));
// Allows adapter to access to proxy's DAI balance in the vat
if (VatLike(vat).can(address(this), address(daiJoin)) == 0) {
VatLike(vat).hope(daiJoin);
}
// Exits DAI to the user's wallet as a token
DaiJoinLike(daiJoin).exit(msg.sender, wadD);
}
function openLockGemAndDraw(
address manager,
address jug,
address gemJoin,
address daiJoin,
bytes32 ilk,
uint256 wadC,
uint256 wadD,
bool transferFrom,
address owner
) public returns (uint256 cdp) {
cdp = open(manager, ilk, address(this));
lockGemAndDraw(manager, jug, gemJoin, daiJoin, cdp, wadC, wadD, transferFrom);
give(manager, cdp, owner);
}
}
contract MCDCreateTaker {
using SafeERC20 for ERC20;
address payable public constant MCD_CREATE_FLASH_LOAN = 0x78aF7A2Ee6C2240c748aDdc42aBc9A693559dcaF;
address public constant DAI_ADDRESS = 0x6B175474E89094C44Da98b954EedeAC495271d0F;
ILendingPool public constant lendingPool = ILendingPool(0x398eC7346DcD622eDc5ae82352F02bE94C62d119);
// solhint-disable-next-line const-name-snakecase
Manager public constant manager = Manager(0x5ef30b9986345249bc32d8928B7ee64DE9435E39);
// solhint-disable-next-line const-name-snakecase
DefisaverLogger public constant logger = DefisaverLogger(0x5c55B921f590a89C1Ebe84dF170E655a82b62126);
struct CreateData {
uint collAmount;
uint daiAmount;
address joinAddr;
}
function openWithLoan(
DFSExchangeData.ExchangeData memory _exchangeData,
CreateData memory _createData
) public payable {
MCD_CREATE_FLASH_LOAN.transfer(msg.value); //0x fee
if (!isEthJoinAddr(_createData.joinAddr)) {
ERC20(getCollateralAddr(_createData.joinAddr)).safeTransferFrom(msg.sender, address(this), _createData.collAmount);
ERC20(getCollateralAddr(_createData.joinAddr)).safeTransfer(MCD_CREATE_FLASH_LOAN, _createData.collAmount);
}
bytes memory packedData = _packData(_createData, _exchangeData);
bytes memory paramsData = abi.encode(address(this), packedData);
lendingPool.flashLoan(MCD_CREATE_FLASH_LOAN, DAI_ADDRESS, _createData.daiAmount, paramsData);
logger.Log(address(this), msg.sender, "MCDCreate", abi.encode(manager.last(address(this)), _createData.collAmount, _createData.daiAmount));
}
function getCollateralAddr(address _joinAddr) internal view returns (address) {
return address(Join(_joinAddr).gem());
}
/// @notice Checks if the join address is one of the Ether coll. types
/// @param _joinAddr Join address to check
function isEthJoinAddr(address _joinAddr) internal view returns (bool) {
// if it's dai_join_addr don't check gem() it will fail
if (_joinAddr == 0x9759A6Ac90977b93B58547b4A71c78317f391A28) return false;
// if coll is weth it's and eth type coll
if (address(Join(_joinAddr).gem()) == 0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2) {
return true;
}
return false;
}
function _packData(
CreateData memory _createData,
DFSExchangeData.ExchangeData memory _exchangeData
) internal pure returns (bytes memory) {
return abi.encode(_createData, _exchangeData);
}
}
contract MCDSaverProxyHelper is DSMath {
/// @notice Returns a normalized debt _amount based on the current rate
/// @param _amount Amount of dai to be normalized
/// @param _rate Current rate of the stability fee
/// @param _daiVatBalance Balance od Dai in the Vat for that CDP
function normalizeDrawAmount(uint _amount, uint _rate, uint _daiVatBalance) internal pure returns (int dart) {
if (_daiVatBalance < mul(_amount, RAY)) {
dart = toPositiveInt(sub(mul(_amount, RAY), _daiVatBalance) / _rate);
dart = mul(uint(dart), _rate) < mul(_amount, RAY) ? dart + 1 : dart;
}
}
/// @notice Converts a number to Rad percision
/// @param _wad The input number in wad percision
function toRad(uint _wad) internal pure returns (uint) {
return mul(_wad, 10 ** 27);
}
/// @notice Converts a number to 18 decimal percision
/// @param _joinAddr Join address of the collateral
/// @param _amount Number to be converted
function convertTo18(address _joinAddr, uint256 _amount) internal view returns (uint256) {
return mul(_amount, 10 ** (18 - Join(_joinAddr).dec()));
}
/// @notice Converts a uint to int and checks if positive
/// @param _x Number to be converted
function toPositiveInt(uint _x) internal pure returns (int y) {
y = int(_x);
require(y >= 0, "int-overflow");
}
/// @notice Gets Dai amount in Vat which can be added to Cdp
/// @param _vat Address of Vat contract
/// @param _urn Urn of the Cdp
/// @param _ilk Ilk of the Cdp
function normalizePaybackAmount(address _vat, address _urn, bytes32 _ilk) internal view returns (int amount) {
uint dai = Vat(_vat).dai(_urn);
(, uint rate,,,) = Vat(_vat).ilks(_ilk);
(, uint art) = Vat(_vat).urns(_ilk, _urn);
amount = toPositiveInt(dai / rate);
amount = uint(amount) <= art ? - amount : - toPositiveInt(art);
}
/// @notice Gets the whole debt of the CDP
/// @param _vat Address of Vat contract
/// @param _usr Address of the Dai holder
/// @param _urn Urn of the Cdp
/// @param _ilk Ilk of the Cdp
function getAllDebt(address _vat, address _usr, address _urn, bytes32 _ilk) internal view returns (uint daiAmount) {
(, uint rate,,,) = Vat(_vat).ilks(_ilk);
(, uint art) = Vat(_vat).urns(_ilk, _urn);
uint dai = Vat(_vat).dai(_usr);
uint rad = sub(mul(art, rate), dai);
daiAmount = rad / RAY;
daiAmount = mul(daiAmount, RAY) < rad ? daiAmount + 1 : daiAmount;
}
/// @notice Gets the token address from the Join contract
/// @param _joinAddr Address of the Join contract
function getCollateralAddr(address _joinAddr) internal view returns (address) {
return address(Join(_joinAddr).gem());
}
/// @notice Checks if the join address is one of the Ether coll. types
/// @param _joinAddr Join address to check
function isEthJoinAddr(address _joinAddr) internal view returns (bool) {
// if it's dai_join_addr don't check gem() it will fail
if (_joinAddr == 0x9759A6Ac90977b93B58547b4A71c78317f391A28) return false;
// if coll is weth it's and eth type coll
if (address(Join(_joinAddr).gem()) == 0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2) {
return true;
}
return false;
}
/// @notice Gets CDP info (collateral, debt)
/// @param _manager Manager contract
/// @param _cdpId Id of the CDP
/// @param _ilk Ilk of the CDP
function getCdpInfo(Manager _manager, uint _cdpId, bytes32 _ilk) public view returns (uint, uint) {
address vat = _manager.vat();
address urn = _manager.urns(_cdpId);
(uint collateral, uint debt) = Vat(vat).urns(_ilk, urn);
(,uint rate,,,) = Vat(vat).ilks(_ilk);
return (collateral, rmul(debt, rate));
}
/// @notice Address that owns the DSProxy that owns the CDP
/// @param _manager Manager contract
/// @param _cdpId Id of the CDP
function getOwner(Manager _manager, uint _cdpId) public view returns (address) {
DSProxy proxy = DSProxy(uint160(_manager.owns(_cdpId)));
return proxy.owner();
}
}
abstract contract ProtocolInterface {
function deposit(address _user, uint256 _amount) public virtual;
function withdraw(address _user, uint256 _amount) public virtual;
}
contract SavingsLogger {
event Deposit(address indexed sender, uint8 protocol, uint256 amount);
event Withdraw(address indexed sender, uint8 protocol, uint256 amount);
event Swap(address indexed sender, uint8 fromProtocol, uint8 toProtocol, uint256 amount);
function logDeposit(address _sender, uint8 _protocol, uint256 _amount) external {
emit Deposit(_sender, _protocol, _amount);
}
function logWithdraw(address _sender, uint8 _protocol, uint256 _amount) external {
emit Withdraw(_sender, _protocol, _amount);
}
function logSwap(address _sender, uint8 _protocolFrom, uint8 _protocolTo, uint256 _amount)
external
{
emit Swap(_sender, _protocolFrom, _protocolTo, _amount);
}
}
contract AaveSavingsProtocol is ProtocolInterface, DSAuth {
address public constant ADAI_ADDRESS = 0xfC1E690f61EFd961294b3e1Ce3313fBD8aa4f85d;
address public constant AAVE_LENDING_POOL = 0x398eC7346DcD622eDc5ae82352F02bE94C62d119;
address public constant AAVE_LENDING_POOL_CORE = 0x3dfd23A6c5E8BbcFc9581d2E864a68feb6a076d3;
address public constant DAI_ADDRESS = 0x6B175474E89094C44Da98b954EedeAC495271d0F;
function deposit(address _user, uint _amount) public override {
require(msg.sender == _user);
// get dai from user
require(ERC20(DAI_ADDRESS).transferFrom(_user, address(this), _amount));
ERC20(DAI_ADDRESS).approve(AAVE_LENDING_POOL_CORE, uint(-1));
ILendingPool(AAVE_LENDING_POOL).deposit(DAI_ADDRESS, _amount, 0);
ERC20(ADAI_ADDRESS).transfer(_user, ERC20(ADAI_ADDRESS).balanceOf(address(this)));
}
function withdraw(address _user, uint _amount) public override {
require(msg.sender == _user);
require(ERC20(ADAI_ADDRESS).transferFrom(_user, address(this), _amount));
IAToken(ADAI_ADDRESS).redeem(_amount);
// return dai we have to user
ERC20(DAI_ADDRESS).transfer(_user, _amount);
}
}
contract CompoundSavingsProtocol {
address public constant NEW_CDAI_ADDRESS = 0x5d3a536E4D6DbD6114cc1Ead35777bAB948E3643;
address public constant DAI_ADDRESS = 0x6B175474E89094C44Da98b954EedeAC495271d0F;
CTokenInterface public constant cDaiContract = CTokenInterface(NEW_CDAI_ADDRESS);
function compDeposit(address _user, uint _amount) internal {
// get dai from user
require(ERC20(DAI_ADDRESS).transferFrom(_user, address(this), _amount));
// mainnet only
ERC20(DAI_ADDRESS).approve(NEW_CDAI_ADDRESS, uint(-1));
// mint cDai
require(cDaiContract.mint(_amount) == 0, "Failed Mint");
}
function compWithdraw(address _user, uint _amount) internal {
// transfer all users balance to this contract
require(cDaiContract.transferFrom(_user, address(this), ERC20(NEW_CDAI_ADDRESS).balanceOf(_user)));
// approve cDai to compound contract
cDaiContract.approve(NEW_CDAI_ADDRESS, uint(-1));
// get dai from cDai contract
require(cDaiContract.redeemUnderlying(_amount) == 0, "Reedem Failed");
// return to user balance we didn't spend
uint cDaiBalance = cDaiContract.balanceOf(address(this));
if (cDaiBalance > 0) {
cDaiContract.transfer(_user, cDaiBalance);
}
// return dai we have to user
ERC20(DAI_ADDRESS).transfer(_user, _amount);
}
}
abstract contract VatLike {
function can(address, address) virtual public view returns (uint);
function ilks(bytes32) virtual public view returns (uint, uint, uint, uint, uint);
function dai(address) virtual public view returns (uint);
function urns(bytes32, address) virtual public view returns (uint, uint);
function frob(bytes32, address, address, address, int, int) virtual public;
function hope(address) virtual public;
function move(address, address, uint) virtual public;
}
abstract contract PotLike {
function pie(address) virtual public view returns (uint);
function drip() virtual public returns (uint);
function join(uint) virtual public;
function exit(uint) virtual public;
}
abstract contract GemLike {
function approve(address, uint) virtual public;
function transfer(address, uint) virtual public;
function transferFrom(address, address, uint) virtual public;
function deposit() virtual public payable;
function withdraw(uint) virtual public;
}
abstract contract DaiJoinLike {
function vat() virtual public returns (VatLike);
function dai() virtual public returns (GemLike);
function join(address, uint) virtual public payable;
function exit(address, uint) virtual public;
}
contract DSRSavingsProtocol is DSMath {
// Mainnet
address public constant POT_ADDRESS = 0x197E90f9FAD81970bA7976f33CbD77088E5D7cf7;
address public constant DAI_JOIN_ADDRESS = 0x9759A6Ac90977b93B58547b4A71c78317f391A28;
function dsrDeposit(uint _amount, bool _fromUser) internal {
VatLike vat = DaiJoinLike(DAI_JOIN_ADDRESS).vat();
uint chi = PotLike(POT_ADDRESS).drip();
daiJoin_join(DAI_JOIN_ADDRESS, address(this), _amount, _fromUser);
if (vat.can(address(this), address(POT_ADDRESS)) == 0) {
vat.hope(POT_ADDRESS);
}
PotLike(POT_ADDRESS).join(mul(_amount, RAY) / chi);
}
function dsrWithdraw(uint _amount, bool _toUser) internal {
VatLike vat = DaiJoinLike(DAI_JOIN_ADDRESS).vat();
uint chi = PotLike(POT_ADDRESS).drip();
uint pie = mul(_amount, RAY) / chi;
PotLike(POT_ADDRESS).exit(pie);
uint balance = DaiJoinLike(DAI_JOIN_ADDRESS).vat().dai(address(this));
if (vat.can(address(this), address(DAI_JOIN_ADDRESS)) == 0) {
vat.hope(DAI_JOIN_ADDRESS);
}
address to;
if (_toUser) {
to = msg.sender;
} else {
to = address(this);
}
if (_amount == uint(-1)) {
DaiJoinLike(DAI_JOIN_ADDRESS).exit(to, mul(chi, pie) / RAY);
} else {
DaiJoinLike(DAI_JOIN_ADDRESS).exit(
to,
balance >= mul(_amount, RAY) ? _amount : balance / RAY
);
}
}
function daiJoin_join(address apt, address urn, uint wad, bool _fromUser) internal {
if (_fromUser) {
DaiJoinLike(apt).dai().transferFrom(msg.sender, address(this), wad);
}
DaiJoinLike(apt).dai().approve(apt, wad);
DaiJoinLike(apt).join(urn, wad);
}
}
contract DydxSavingsProtocol is ProtocolInterface, DSAuth {
address public constant SOLO_MARGIN_ADDRESS = 0x1E0447b19BB6EcFdAe1e4AE1694b0C3659614e4e;
ISoloMargin public soloMargin;
address public savingsProxy;
uint daiMarketId = 3;
constructor() public {
soloMargin = ISoloMargin(SOLO_MARGIN_ADDRESS);
}
function addSavingsProxy(address _savingsProxy) public auth {
savingsProxy = _savingsProxy;
}
function deposit(address _user, uint _amount) public override {
require(msg.sender == _user);
Account.Info[] memory accounts = new Account.Info[](1);
accounts[0] = getAccount(_user, 0);
Actions.ActionArgs[] memory actions = new Actions.ActionArgs[](1);
Types.AssetAmount memory amount = Types.AssetAmount({
sign: true,
denomination: Types.AssetDenomination.Wei,
ref: Types.AssetReference.Delta,
value: _amount
});
actions[0] = Actions.ActionArgs({
actionType: Actions.ActionType.Deposit,
accountId: 0,
amount: amount,
primaryMarketId: daiMarketId,
otherAddress: _user,
secondaryMarketId: 0, //not used
otherAccountId: 0, //not used
data: "" //not used
});
soloMargin.operate(accounts, actions);
}
function withdraw(address _user, uint _amount) public override {
require(msg.sender == _user);
Account.Info[] memory accounts = new Account.Info[](1);
accounts[0] = getAccount(_user, 0);
Actions.ActionArgs[] memory actions = new Actions.ActionArgs[](1);
Types.AssetAmount memory amount = Types.AssetAmount({
sign: false,
denomination: Types.AssetDenomination.Wei,
ref: Types.AssetReference.Delta,
value: _amount
});
actions[0] = Actions.ActionArgs({
actionType: Actions.ActionType.Withdraw,
accountId: 0,
amount: amount,
primaryMarketId: daiMarketId,
otherAddress: _user,
secondaryMarketId: 0, //not used
otherAccountId: 0, //not used
data: "" //not used
});
soloMargin.operate(accounts, actions);
}
function getWeiBalance(address _user, uint _index) public view returns(Types.Wei memory) {
Types.Wei[] memory weiBalances;
(,,weiBalances) = soloMargin.getAccountBalances(getAccount(_user, _index));
return weiBalances[daiMarketId];
}
function getParBalance(address _user, uint _index) public view returns(Types.Par memory) {
Types.Par[] memory parBalances;
(,parBalances,) = soloMargin.getAccountBalances(getAccount(_user, _index));
return parBalances[daiMarketId];
}
function getAccount(address _user, uint _index) public pure returns(Account.Info memory) {
Account.Info memory account = Account.Info({
owner: _user,
number: _index
});
return account;
}
}
abstract contract ISoloMargin {
struct OperatorArg {
address operator;
bool trusted;
}
function operate(
Account.Info[] memory accounts,
Actions.ActionArgs[] memory actions
) public virtual;
function getAccountBalances(
Account.Info memory account
) public view virtual returns (
address[] memory,
Types.Par[] memory,
Types.Wei[] memory
);
function setOperators(
OperatorArg[] memory args
) public virtual;
function getNumMarkets() public view virtual returns (uint256);
function getMarketTokenAddress(uint256 marketId)
public
view
virtual
returns (address);
}
library Account {
// ============ Enums ============
/*
* Most-recently-cached account status.
*
* Normal: Can only be liquidated if the account values are violating the global margin-ratio.
* Liquid: Can be liquidated no matter the account values.
* Can be vaporized if there are no more positive account values.
* Vapor: Has only negative (or zeroed) account values. Can be vaporized.
*
*/
enum Status {
Normal,
Liquid,
Vapor
}
// ============ Structs ============
// Represents the unique key that specifies an account
struct Info {
address owner; // The address that owns the account
uint256 number; // A nonce that allows a single address to control many accounts
}
// The complete storage for any account
struct Storage {
mapping (uint256 => Types.Par) balances; // Mapping from marketId to principal
Status status;
}
// ============ Library Functions ============
function equals(
Info memory a,
Info memory b
)
internal
pure
returns (bool)
{
return a.owner == b.owner && a.number == b.number;
}
}
library Actions {
// ============ Constants ============
bytes32 constant FILE = "Actions";
// ============ Enums ============
enum ActionType {
Deposit, // supply tokens
Withdraw, // borrow tokens
Transfer, // transfer balance between accounts
Buy, // buy an amount of some token (externally)
Sell, // sell an amount of some token (externally)
Trade, // trade tokens against another account
Liquidate, // liquidate an undercollateralized or expiring account
Vaporize, // use excess tokens to zero-out a completely negative account
Call // send arbitrary data to an address
}
enum AccountLayout {
OnePrimary,
TwoPrimary,
PrimaryAndSecondary
}
enum MarketLayout {
ZeroMarkets,
OneMarket,
TwoMarkets
}
// ============ Structs ============
/*
* Arguments that are passed to Solo in an ordered list as part of a single operation.
* Each ActionArgs has an actionType which specifies which action struct that this data will be
* parsed into before being processed.
*/
struct ActionArgs {
ActionType actionType;
uint256 accountId;
Types.AssetAmount amount;
uint256 primaryMarketId;
uint256 secondaryMarketId;
address otherAddress;
uint256 otherAccountId;
bytes data;
}
// ============ Action Types ============
/*
* Moves tokens from an address to Solo. Can either repay a borrow or provide additional supply.
*/
struct DepositArgs {
Types.AssetAmount amount;
Account.Info account;
uint256 market;
address from;
}
/*
* Moves tokens from Solo to another address. Can either borrow tokens or reduce the amount
* previously supplied.
*/
struct WithdrawArgs {
Types.AssetAmount amount;
Account.Info account;
uint256 market;
address to;
}
/*
* Transfers balance between two accounts. The msg.sender must be an operator for both accounts.
* The amount field applies to accountOne.
* This action does not require any token movement since the trade is done internally to Solo.
*/
struct TransferArgs {
Types.AssetAmount amount;
Account.Info accountOne;
Account.Info accountTwo;
uint256 market;
}
/*
* Acquires a certain amount of tokens by spending other tokens. Sends takerMarket tokens to the
* specified exchangeWrapper contract and expects makerMarket tokens in return. The amount field
* applies to the makerMarket.
*/
struct BuyArgs {
Types.AssetAmount amount;
Account.Info account;
uint256 makerMarket;
uint256 takerMarket;
address exchangeWrapper;
bytes orderData;
}
/*
* Spends a certain amount of tokens to acquire other tokens. Sends takerMarket tokens to the
* specified exchangeWrapper and expects makerMarket tokens in return. The amount field applies
* to the takerMarket.
*/
struct SellArgs {
Types.AssetAmount amount;
Account.Info account;
uint256 takerMarket;
uint256 makerMarket;
address exchangeWrapper;
bytes orderData;
}
/*
* Trades balances between two accounts using any external contract that implements the
* AutoTrader interface. The AutoTrader contract must be an operator for the makerAccount (for
* which it is trading on-behalf-of). The amount field applies to the makerAccount and the
* inputMarket. This proposed change to the makerAccount is passed to the AutoTrader which will
* quote a change for the makerAccount in the outputMarket (or will disallow the trade).
* This action does not require any token movement since the trade is done internally to Solo.
*/
struct TradeArgs {
Types.AssetAmount amount;
Account.Info takerAccount;
Account.Info makerAccount;
uint256 inputMarket;
uint256 outputMarket;
address autoTrader;
bytes tradeData;
}
/*
* Each account must maintain a certain margin-ratio (specified globally). If the account falls
* below this margin-ratio, it can be liquidated by any other account. This allows anyone else
* (arbitrageurs) to repay any borrowed asset (owedMarket) of the liquidating account in
* exchange for any collateral asset (heldMarket) of the liquidAccount. The ratio is determined
* by the price ratio (given by the oracles) plus a spread (specified globally). Liquidating an
* account also sets a flag on the account that the account is being liquidated. This allows
* anyone to continue liquidating the account until there are no more borrows being taken by the
* liquidating account. Liquidators do not have to liquidate the entire account all at once but
* can liquidate as much as they choose. The liquidating flag allows liquidators to continue
* liquidating the account even if it becomes collateralized through partial liquidation or
* price movement.
*/
struct LiquidateArgs {
Types.AssetAmount amount;
Account.Info solidAccount;
Account.Info liquidAccount;
uint256 owedMarket;
uint256 heldMarket;
}
/*
* Similar to liquidate, but vaporAccounts are accounts that have only negative balances
* remaining. The arbitrageur pays back the negative asset (owedMarket) of the vaporAccount in
* exchange for a collateral asset (heldMarket) at a favorable spread. However, since the
* liquidAccount has no collateral assets, the collateral must come from Solo's excess tokens.
*/
struct VaporizeArgs {
Types.AssetAmount amount;
Account.Info solidAccount;
Account.Info vaporAccount;
uint256 owedMarket;
uint256 heldMarket;
}
/*
* Passes arbitrary bytes of data to an external contract that implements the Callee interface.
* Does not change any asset amounts. This function may be useful for setting certain variables
* on layer-two contracts for certain accounts without having to make a separate Ethereum
* transaction for doing so. Also, the second-layer contracts can ensure that the call is coming
* from an operator of the particular account.
*/
struct CallArgs {
Account.Info account;
address callee;
bytes data;
}
// ============ Helper Functions ============
function getMarketLayout(
ActionType actionType
)
internal
pure
returns (MarketLayout)
{
if (
actionType == Actions.ActionType.Deposit
|| actionType == Actions.ActionType.Withdraw
|| actionType == Actions.ActionType.Transfer
) {
return MarketLayout.OneMarket;
}
else if (actionType == Actions.ActionType.Call) {
return MarketLayout.ZeroMarkets;
}
return MarketLayout.TwoMarkets;
}
function getAccountLayout(
ActionType actionType
)
internal
pure
returns (AccountLayout)
{
if (
actionType == Actions.ActionType.Transfer
|| actionType == Actions.ActionType.Trade
) {
return AccountLayout.TwoPrimary;
} else if (
actionType == Actions.ActionType.Liquidate
|| actionType == Actions.ActionType.Vaporize
) {
return AccountLayout.PrimaryAndSecondary;
}
return AccountLayout.OnePrimary;
}
// ============ Parsing Functions ============
function parseDepositArgs(
Account.Info[] memory accounts,
ActionArgs memory args
)
internal
pure
returns (DepositArgs memory)
{
assert(args.actionType == ActionType.Deposit);
return DepositArgs({
amount: args.amount,
account: accounts[args.accountId],
market: args.primaryMarketId,
from: args.otherAddress
});
}
function parseWithdrawArgs(
Account.Info[] memory accounts,
ActionArgs memory args
)
internal
pure
returns (WithdrawArgs memory)
{
assert(args.actionType == ActionType.Withdraw);
return WithdrawArgs({
amount: args.amount,
account: accounts[args.accountId],
market: args.primaryMarketId,
to: args.otherAddress
});
}
function parseTransferArgs(
Account.Info[] memory accounts,
ActionArgs memory args
)
internal
pure
returns (TransferArgs memory)
{
assert(args.actionType == ActionType.Transfer);
return TransferArgs({
amount: args.amount,
accountOne: accounts[args.accountId],
accountTwo: accounts[args.otherAccountId],
market: args.primaryMarketId
});
}
function parseBuyArgs(
Account.Info[] memory accounts,
ActionArgs memory args
)
internal
pure
returns (BuyArgs memory)
{
assert(args.actionType == ActionType.Buy);
return BuyArgs({
amount: args.amount,
account: accounts[args.accountId],
makerMarket: args.primaryMarketId,
takerMarket: args.secondaryMarketId,
exchangeWrapper: args.otherAddress,
orderData: args.data
});
}
function parseSellArgs(
Account.Info[] memory accounts,
ActionArgs memory args
)
internal
pure
returns (SellArgs memory)
{
assert(args.actionType == ActionType.Sell);
return SellArgs({
amount: args.amount,
account: accounts[args.accountId],
takerMarket: args.primaryMarketId,
makerMarket: args.secondaryMarketId,
exchangeWrapper: args.otherAddress,
orderData: args.data
});
}
function parseTradeArgs(
Account.Info[] memory accounts,
ActionArgs memory args
)
internal
pure
returns (TradeArgs memory)
{
assert(args.actionType == ActionType.Trade);
return TradeArgs({
amount: args.amount,
takerAccount: accounts[args.accountId],
makerAccount: accounts[args.otherAccountId],
inputMarket: args.primaryMarketId,
outputMarket: args.secondaryMarketId,
autoTrader: args.otherAddress,
tradeData: args.data
});
}
function parseLiquidateArgs(
Account.Info[] memory accounts,
ActionArgs memory args
)
internal
pure
returns (LiquidateArgs memory)
{
assert(args.actionType == ActionType.Liquidate);
return LiquidateArgs({
amount: args.amount,
solidAccount: accounts[args.accountId],
liquidAccount: accounts[args.otherAccountId],
owedMarket: args.primaryMarketId,
heldMarket: args.secondaryMarketId
});
}
function parseVaporizeArgs(
Account.Info[] memory accounts,
ActionArgs memory args
)
internal
pure
returns (VaporizeArgs memory)
{
assert(args.actionType == ActionType.Vaporize);
return VaporizeArgs({
amount: args.amount,
solidAccount: accounts[args.accountId],
vaporAccount: accounts[args.otherAccountId],
owedMarket: args.primaryMarketId,
heldMarket: args.secondaryMarketId
});
}
function parseCallArgs(
Account.Info[] memory accounts,
ActionArgs memory args
)
internal
pure
returns (CallArgs memory)
{
assert(args.actionType == ActionType.Call);
return CallArgs({
account: accounts[args.accountId],
callee: args.otherAddress,
data: args.data
});
}
}
library Math {
using SafeMath for uint256;
// ============ Constants ============
bytes32 constant FILE = "Math";
// ============ Library Functions ============
/*
* Return target * (numerator / denominator).
*/
function getPartial(
uint256 target,
uint256 numerator,
uint256 denominator
)
internal
pure
returns (uint256)
{
return target.mul(numerator).div(denominator);
}
/*
* Return target * (numerator / denominator), but rounded up.
*/
function getPartialRoundUp(
uint256 target,
uint256 numerator,
uint256 denominator
)
internal
pure
returns (uint256)
{
if (target == 0 || numerator == 0) {
// SafeMath will check for zero denominator
return SafeMath.div(0, denominator);
}
return target.mul(numerator).sub(1).div(denominator).add(1);
}
function to128(
uint256 number
)
internal
pure
returns (uint128)
{
uint128 result = uint128(number);
Require.that(
result == number,
FILE,
"Unsafe cast to uint128"
);
return result;
}
function to96(
uint256 number
)
internal
pure
returns (uint96)
{
uint96 result = uint96(number);
Require.that(
result == number,
FILE,
"Unsafe cast to uint96"
);
return result;
}
function to32(
uint256 number
)
internal
pure
returns (uint32)
{
uint32 result = uint32(number);
Require.that(
result == number,
FILE,
"Unsafe cast to uint32"
);
return result;
}
function min(
uint256 a,
uint256 b
)
internal
pure
returns (uint256)
{
return a < b ? a : b;
}
function max(
uint256 a,
uint256 b
)
internal
pure
returns (uint256)
{
return a > b ? a : b;
}
}
library Require {
// ============ Constants ============
uint256 constant ASCII_ZERO = 48; // '0'
uint256 constant ASCII_RELATIVE_ZERO = 87; // 'a' - 10
uint256 constant ASCII_LOWER_EX = 120; // 'x'
bytes2 constant COLON = 0x3a20; // ': '
bytes2 constant COMMA = 0x2c20; // ', '
bytes2 constant LPAREN = 0x203c; // ' <'
byte constant RPAREN = 0x3e; // '>'
uint256 constant FOUR_BIT_MASK = 0xf;
// ============ Library Functions ============
function that(
bool must,
bytes32 file,
bytes32 reason
)
internal
pure
{
if (!must) {
revert(
string(
abi.encodePacked(
stringifyTruncated(file),
COLON,
stringifyTruncated(reason)
)
)
);
}
}
function that(
bool must,
bytes32 file,
bytes32 reason,
uint256 payloadA
)
internal
pure
{
if (!must) {
revert(
string(
abi.encodePacked(
stringifyTruncated(file),
COLON,
stringifyTruncated(reason),
LPAREN,
stringify(payloadA),
RPAREN
)
)
);
}
}
function that(
bool must,
bytes32 file,
bytes32 reason,
uint256 payloadA,
uint256 payloadB
)
internal
pure
{
if (!must) {
revert(
string(
abi.encodePacked(
stringifyTruncated(file),
COLON,
stringifyTruncated(reason),
LPAREN,
stringify(payloadA),
COMMA,
stringify(payloadB),
RPAREN
)
)
);
}
}
function that(
bool must,
bytes32 file,
bytes32 reason,
address payloadA
)
internal
pure
{
if (!must) {
revert(
string(
abi.encodePacked(
stringifyTruncated(file),
COLON,
stringifyTruncated(reason),
LPAREN,
stringify(payloadA),
RPAREN
)
)
);
}
}
function that(
bool must,
bytes32 file,
bytes32 reason,
address payloadA,
uint256 payloadB
)
internal
pure
{
if (!must) {
revert(
string(
abi.encodePacked(
stringifyTruncated(file),
COLON,
stringifyTruncated(reason),
LPAREN,
stringify(payloadA),
COMMA,
stringify(payloadB),
RPAREN
)
)
);
}
}
function that(
bool must,
bytes32 file,
bytes32 reason,
address payloadA,
uint256 payloadB,
uint256 payloadC
)
internal
pure
{
if (!must) {
revert(
string(
abi.encodePacked(
stringifyTruncated(file),
COLON,
stringifyTruncated(reason),
LPAREN,
stringify(payloadA),
COMMA,
stringify(payloadB),
COMMA,
stringify(payloadC),
RPAREN
)
)
);
}
}
function that(
bool must,
bytes32 file,
bytes32 reason,
bytes32 payloadA
)
internal
pure
{
if (!must) {
revert(
string(
abi.encodePacked(
stringifyTruncated(file),
COLON,
stringifyTruncated(reason),
LPAREN,
stringify(payloadA),
RPAREN
)
)
);
}
}
function that(
bool must,
bytes32 file,
bytes32 reason,
bytes32 payloadA,
uint256 payloadB,
uint256 payloadC
)
internal
pure
{
if (!must) {
revert(
string(
abi.encodePacked(
stringifyTruncated(file),
COLON,
stringifyTruncated(reason),
LPAREN,
stringify(payloadA),
COMMA,
stringify(payloadB),
COMMA,
stringify(payloadC),
RPAREN
)
)
);
}
}
// ============ Private Functions ============
function stringifyTruncated(
bytes32 input
)
private
pure
returns (bytes memory)
{
// put the input bytes into the result
bytes memory result = abi.encodePacked(input);
// determine the length of the input by finding the location of the last non-zero byte
for (uint256 i = 32; i > 0; ) {
// reverse-for-loops with unsigned integer
/* solium-disable-next-line security/no-modify-for-iter-var */
i--;
// find the last non-zero byte in order to determine the length
if (result[i] != 0) {
uint256 length = i + 1;
/* solium-disable-next-line security/no-inline-assembly */
assembly {
mstore(result, length) // r.length = length;
}
return result;
}
}
// all bytes are zero
return new bytes(0);
}
function stringify(
uint256 input
)
private
pure
returns (bytes memory)
{
if (input == 0) {
return "0";
}
// get the final string length
uint256 j = input;
uint256 length;
while (j != 0) {
length++;
j /= 10;
}
// allocate the string
bytes memory bstr = new bytes(length);
// populate the string starting with the least-significant character
j = input;
for (uint256 i = length; i > 0; ) {
// reverse-for-loops with unsigned integer
/* solium-disable-next-line security/no-modify-for-iter-var */
i--;
// take last decimal digit
bstr[i] = byte(uint8(ASCII_ZERO + (j % 10)));
// remove the last decimal digit
j /= 10;
}
return bstr;
}
function stringify(
address input
)
private
pure
returns (bytes memory)
{
uint256 z = uint256(input);
// addresses are "0x" followed by 20 bytes of data which take up 2 characters each
bytes memory result = new bytes(42);
// populate the result with "0x"
result[0] = byte(uint8(ASCII_ZERO));
result[1] = byte(uint8(ASCII_LOWER_EX));
// for each byte (starting from the lowest byte), populate the result with two characters
for (uint256 i = 0; i < 20; i++) {
// each byte takes two characters
uint256 shift = i * 2;
// populate the least-significant character
result[41 - shift] = char(z & FOUR_BIT_MASK);
z = z >> 4;
// populate the most-significant character
result[40 - shift] = char(z & FOUR_BIT_MASK);
z = z >> 4;
}
return result;
}
function stringify(
bytes32 input
)
private
pure
returns (bytes memory)
{
uint256 z = uint256(input);
// bytes32 are "0x" followed by 32 bytes of data which take up 2 characters each
bytes memory result = new bytes(66);
// populate the result with "0x"
result[0] = byte(uint8(ASCII_ZERO));
result[1] = byte(uint8(ASCII_LOWER_EX));
// for each byte (starting from the lowest byte), populate the result with two characters
for (uint256 i = 0; i < 32; i++) {
// each byte takes two characters
uint256 shift = i * 2;
// populate the least-significant character
result[65 - shift] = char(z & FOUR_BIT_MASK);
z = z >> 4;
// populate the most-significant character
result[64 - shift] = char(z & FOUR_BIT_MASK);
z = z >> 4;
}
return result;
}
function char(
uint256 input
)
private
pure
returns (byte)
{
// return ASCII digit (0-9)
if (input < 10) {
return byte(uint8(input + ASCII_ZERO));
}
// return ASCII letter (a-f)
return byte(uint8(input + ASCII_RELATIVE_ZERO));
}
}
library Types {
using Math for uint256;
// ============ AssetAmount ============
enum AssetDenomination {
Wei, // the amount is denominated in wei
Par // the amount is denominated in par
}
enum AssetReference {
Delta, // the amount is given as a delta from the current value
Target // the amount is given as an exact number to end up at
}
struct AssetAmount {
bool sign; // true if positive
AssetDenomination denomination;
AssetReference ref;
uint256 value;
}
// ============ Par (Principal Amount) ============
// Total borrow and supply values for a market
struct TotalPar {
uint128 borrow;
uint128 supply;
}
// Individual principal amount for an account
struct Par {
bool sign; // true if positive
uint128 value;
}
function zeroPar()
internal
pure
returns (Par memory)
{
return Par({
sign: false,
value: 0
});
}
function sub(
Par memory a,
Par memory b
)
internal
pure
returns (Par memory)
{
return add(a, negative(b));
}
function add(
Par memory a,
Par memory b
)
internal
pure
returns (Par memory)
{
Par memory result;
if (a.sign == b.sign) {
result.sign = a.sign;
result.value = SafeMath.add(a.value, b.value).to128();
} else {
if (a.value >= b.value) {
result.sign = a.sign;
result.value = SafeMath.sub(a.value, b.value).to128();
} else {
result.sign = b.sign;
result.value = SafeMath.sub(b.value, a.value).to128();
}
}
return result;
}
function equals(
Par memory a,
Par memory b
)
internal
pure
returns (bool)
{
if (a.value == b.value) {
if (a.value == 0) {
return true;
}
return a.sign == b.sign;
}
return false;
}
function negative(
Par memory a
)
internal
pure
returns (Par memory)
{
return Par({
sign: !a.sign,
value: a.value
});
}
function isNegative(
Par memory a
)
internal
pure
returns (bool)
{
return !a.sign && a.value > 0;
}
function isPositive(
Par memory a
)
internal
pure
returns (bool)
{
return a.sign && a.value > 0;
}
function isZero(
Par memory a
)
internal
pure
returns (bool)
{
return a.value == 0;
}
// ============ Wei (Token Amount) ============
// Individual token amount for an account
struct Wei {
bool sign; // true if positive
uint256 value;
}
function zeroWei()
internal
pure
returns (Wei memory)
{
return Wei({
sign: false,
value: 0
});
}
function sub(
Wei memory a,
Wei memory b
)
internal
pure
returns (Wei memory)
{
return add(a, negative(b));
}
function add(
Wei memory a,
Wei memory b
)
internal
pure
returns (Wei memory)
{
Wei memory result;
if (a.sign == b.sign) {
result.sign = a.sign;
result.value = SafeMath.add(a.value, b.value);
} else {
if (a.value >= b.value) {
result.sign = a.sign;
result.value = SafeMath.sub(a.value, b.value);
} else {
result.sign = b.sign;
result.value = SafeMath.sub(b.value, a.value);
}
}
return result;
}
function equals(
Wei memory a,
Wei memory b
)
internal
pure
returns (bool)
{
if (a.value == b.value) {
if (a.value == 0) {
return true;
}
return a.sign == b.sign;
}
return false;
}
function negative(
Wei memory a
)
internal
pure
returns (Wei memory)
{
return Wei({
sign: !a.sign,
value: a.value
});
}
function isNegative(
Wei memory a
)
internal
pure
returns (bool)
{
return !a.sign && a.value > 0;
}
function isPositive(
Wei memory a
)
internal
pure
returns (bool)
{
return a.sign && a.value > 0;
}
function isZero(
Wei memory a
)
internal
pure
returns (bool)
{
return a.value == 0;
}
}
contract FulcrumSavingsProtocol is ProtocolInterface, DSAuth {
address public constant NEW_IDAI_ADDRESS = 0x493C57C4763932315A328269E1ADaD09653B9081;
address public constant DAI_ADDRESS = 0x6B175474E89094C44Da98b954EedeAC495271d0F;
address public savingsProxy;
uint public decimals = 10 ** 18;
function addSavingsProxy(address _savingsProxy) public auth {
savingsProxy = _savingsProxy;
}
function deposit(address _user, uint _amount) public override {
require(msg.sender == _user);
// get dai from user
require(ERC20(DAI_ADDRESS).transferFrom(_user, address(this), _amount));
// approve dai to Fulcrum
ERC20(DAI_ADDRESS).approve(NEW_IDAI_ADDRESS, uint(-1));
// mint iDai
ITokenInterface(NEW_IDAI_ADDRESS).mint(_user, _amount);
}
function withdraw(address _user, uint _amount) public override {
require(msg.sender == _user);
// transfer all users tokens to our contract
require(ERC20(NEW_IDAI_ADDRESS).transferFrom(_user, address(this), ITokenInterface(NEW_IDAI_ADDRESS).balanceOf(_user)));
// approve iDai to that contract
ERC20(NEW_IDAI_ADDRESS).approve(NEW_IDAI_ADDRESS, uint(-1));
uint tokenPrice = ITokenInterface(NEW_IDAI_ADDRESS).tokenPrice();
// get dai from iDai contract
ITokenInterface(NEW_IDAI_ADDRESS).burn(_user, _amount * decimals / tokenPrice);
// return all remaining tokens back to user
require(ERC20(NEW_IDAI_ADDRESS).transfer(_user, ITokenInterface(NEW_IDAI_ADDRESS).balanceOf(address(this))));
}
}
contract ShifterRegistry is AdminAuth {
mapping (string => address) public contractAddresses;
bool public finalized;
function changeContractAddr(string memory _contractName, address _protoAddr) public onlyOwner {
require(!finalized);
contractAddresses[_contractName] = _protoAddr;
}
function lock() public onlyOwner {
finalized = true;
}
function getAddr(string memory _contractName) public view returns (address contractAddr) {
contractAddr = contractAddresses[_contractName];
require(contractAddr != address(0), "No contract address registred");
}
}
library Address {
function isContract(address account) internal view returns (bool) {
// According to EIP-1052, 0x0 is the value returned for not-yet created accounts
// and 0xc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470 is returned
// for accounts without code, i.e. `keccak256('')`
bytes32 codehash;
bytes32 accountHash = 0xc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470;
// solhint-disable-next-line no-inline-assembly
assembly { codehash := extcodehash(account) }
return (codehash != accountHash && codehash != 0x0);
}
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");
}
function functionCall(address target, bytes memory data) internal returns (bytes memory) {
return functionCall(target, data, "Address: low-level call failed");
}
function functionCall(address target, bytes memory data, string memory errorMessage) internal returns (bytes memory) {
return _functionCallWithValue(target, data, 0, errorMessage);
}
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");
}
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);
}
}
}
}
contract BotRegistry is AdminAuth {
mapping (address => bool) public botList;
constructor() public {
botList[0x776B4a13093e30B05781F97F6A4565B6aa8BE330] = true;
botList[0xAED662abcC4FA3314985E67Ea993CAD064a7F5cF] = true;
botList[0xa5d330F6619d6bF892A5B87D80272e1607b3e34D] = true;
botList[0x5feB4DeE5150B589a7f567EA7CADa2759794A90A] = true;
botList[0x7ca06417c1d6f480d3bB195B80692F95A6B66158] = true;
}
function setBot(address _botAddr, bool _state) public onlyOwner {
botList[_botAddr] = _state;
}
}
contract DFSProxy is Auth {
string public constant NAME = "DFSProxy";
string public constant VERSION = "v0.1";
mapping(address => mapping(uint => bool)) public nonces;
// --- EIP712 niceties ---
bytes32 public DOMAIN_SEPARATOR;
bytes32 public constant PERMIT_TYPEHASH = keccak256("callProxy(address _user,address _proxy,address _contract,bytes _txData,uint256 _nonce)");
constructor(uint256 chainId_) public {
DOMAIN_SEPARATOR = keccak256(abi.encode(
keccak256("EIP712Domain(string name,string version,uint256 chainId,address verifyingContract)"),
keccak256(bytes(NAME)),
keccak256(bytes(VERSION)),
chainId_,
address(this)
));
}
function callProxy(address _user, address _proxy, address _contract, bytes calldata _txData, uint256 _nonce,
uint8 _v, bytes32 _r, bytes32 _s) external payable onlyAuthorized
{
bytes32 digest =
keccak256(abi.encodePacked(
"\x19\x01",
DOMAIN_SEPARATOR,
keccak256(abi.encode(PERMIT_TYPEHASH,
_user,
_proxy,
_contract,
_txData,
_nonce))
));
// user must be proxy owner
require(DSProxyInterface(_proxy).owner() == _user);
require(_user == ecrecover(digest, _v, _r, _s), "DFSProxy/user-not-valid");
require(!nonces[_user][_nonce], "DFSProxy/invalid-nonce");
nonces[_user][_nonce] = true;
DSProxyInterface(_proxy).execute{value: msg.value}(_contract, _txData);
}
}
contract Discount {
address public owner;
mapping(address => CustomServiceFee) public serviceFees;
uint256 constant MAX_SERVICE_FEE = 400;
struct CustomServiceFee {
bool active;
uint256 amount;
}
constructor() public {
owner = msg.sender;
}
function isCustomFeeSet(address _user) public view returns (bool) {
return serviceFees[_user].active;
}
function getCustomServiceFee(address _user) public view returns (uint256) {
return serviceFees[_user].amount;
}
function setServiceFee(address _user, uint256 _fee) public {
require(msg.sender == owner, "Only owner");
require(_fee >= MAX_SERVICE_FEE || _fee == 0);
serviceFees[_user] = CustomServiceFee({active: true, amount: _fee});
}
function disableServiceFee(address _user) public {
require(msg.sender == owner, "Only owner");
serviceFees[_user] = CustomServiceFee({active: false, amount: 0});
}
}
contract DydxFlashLoanBase {
using SafeMath for uint256;
address public constant SOLO_MARGIN_ADDRESS = 0x1E0447b19BB6EcFdAe1e4AE1694b0C3659614e4e;
function _getMarketIdFromTokenAddress(address token)
internal
view
returns (uint256)
{
return 0;
}
function _getRepaymentAmountInternal(uint256 amount)
internal
view
returns (uint256)
{
// Needs to be overcollateralize
// Needs to provide +2 wei to be safe
return amount.add(2);
}
function _getAccountInfo() internal view returns (Account.Info memory) {
return Account.Info({owner: address(this), number: 1});
}
function _getWithdrawAction(uint marketId, uint256 amount, address contractAddr)
internal
view
returns (Actions.ActionArgs memory)
{
return
Actions.ActionArgs({
actionType: Actions.ActionType.Withdraw,
accountId: 0,
amount: Types.AssetAmount({
sign: false,
denomination: Types.AssetDenomination.Wei,
ref: Types.AssetReference.Delta,
value: amount
}),
primaryMarketId: marketId,
secondaryMarketId: 0,
otherAddress: contractAddr,
otherAccountId: 0,
data: ""
});
}
function _getCallAction(bytes memory data, address contractAddr)
internal
view
returns (Actions.ActionArgs memory)
{
return
Actions.ActionArgs({
actionType: Actions.ActionType.Call,
accountId: 0,
amount: Types.AssetAmount({
sign: false,
denomination: Types.AssetDenomination.Wei,
ref: Types.AssetReference.Delta,
value: 0
}),
primaryMarketId: 0,
secondaryMarketId: 0,
otherAddress: contractAddr,
otherAccountId: 0,
data: data
});
}
function _getDepositAction(uint marketId, uint256 amount, address contractAddr)
internal
view
returns (Actions.ActionArgs memory)
{
return
Actions.ActionArgs({
actionType: Actions.ActionType.Deposit,
accountId: 0,
amount: Types.AssetAmount({
sign: true,
denomination: Types.AssetDenomination.Wei,
ref: Types.AssetReference.Delta,
value: amount
}),
primaryMarketId: marketId,
secondaryMarketId: 0,
otherAddress: contractAddr,
otherAccountId: 0,
data: ""
});
}
}
contract ExchangeDataParser {
function decodeExchangeData(
SaverExchangeCore.ExchangeData memory exchangeData
) internal pure returns (address[4] memory, uint[4] memory, bytes memory) {
return (
[exchangeData.srcAddr, exchangeData.destAddr, exchangeData.exchangeAddr, exchangeData.wrapper],
[exchangeData.srcAmount, exchangeData.destAmount, exchangeData.minPrice, exchangeData.price0x],
exchangeData.callData
);
}
function encodeExchangeData(
address[4] memory exAddr, uint[4] memory exNum, bytes memory callData
) internal pure returns (SaverExchangeCore.ExchangeData memory) {
return SaverExchangeCore.ExchangeData({
srcAddr: exAddr[0],
destAddr: exAddr[1],
srcAmount: exNum[0],
destAmount: exNum[1],
minPrice: exNum[2],
wrapper: exAddr[3],
exchangeAddr: exAddr[2],
callData: callData,
price0x: exNum[3]
});
}
}
interface IFlashLoanReceiver {
function executeOperation(address _reserve, uint256 _amount, uint256 _fee, bytes calldata _params) external;
}
abstract contract ILendingPoolAddressesProvider {
function getLendingPool() public view virtual returns (address);
function setLendingPoolImpl(address _pool) public virtual;
function getLendingPoolCore() public virtual view returns (address payable);
function setLendingPoolCoreImpl(address _lendingPoolCore) public virtual;
function getLendingPoolConfigurator() public virtual view returns (address);
function setLendingPoolConfiguratorImpl(address _configurator) public virtual;
function getLendingPoolDataProvider() public virtual view returns (address);
function setLendingPoolDataProviderImpl(address _provider) public virtual;
function getLendingPoolParametersProvider() public virtual view returns (address);
function setLendingPoolParametersProviderImpl(address _parametersProvider) public virtual;
function getTokenDistributor() public virtual view returns (address);
function setTokenDistributor(address _tokenDistributor) public virtual;
function getFeeProvider() public virtual view returns (address);
function setFeeProviderImpl(address _feeProvider) public virtual;
function getLendingPoolLiquidationManager() public virtual view returns (address);
function setLendingPoolLiquidationManager(address _manager) public virtual;
function getLendingPoolManager() public virtual view returns (address);
function setLendingPoolManager(address _lendingPoolManager) public virtual;
function getPriceOracle() public virtual view returns (address);
function setPriceOracle(address _priceOracle) public virtual;
function getLendingRateOracle() public view virtual returns (address);
function setLendingRateOracle(address _lendingRateOracle) public virtual;
}
library EthAddressLib {
function ethAddress() internal pure returns(address) {
return 0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE;
}
}
abstract contract FlashLoanReceiverBase is IFlashLoanReceiver {
using SafeERC20 for ERC20;
using SafeMath for uint256;
ILendingPoolAddressesProvider public addressesProvider;
constructor(ILendingPoolAddressesProvider _provider) public {
addressesProvider = _provider;
}
receive () external virtual payable {}
function transferFundsBackToPoolInternal(address _reserve, uint256 _amount) internal {
address payable core = addressesProvider.getLendingPoolCore();
transferInternal(core,_reserve, _amount);
}
function transferInternal(address payable _destination, address _reserve, uint256 _amount) internal {
if(_reserve == EthAddressLib.ethAddress()) {
//solium-disable-next-line
_destination.call{value: _amount}("");
return;
}
ERC20(_reserve).safeTransfer(_destination, _amount);
}
function getBalanceInternal(address _target, address _reserve) internal view returns(uint256) {
if(_reserve == EthAddressLib.ethAddress()) {
return _target.balance;
}
return ERC20(_reserve).balanceOf(_target);
}
}
contract GasBurner {
// solhint-disable-next-line const-name-snakecase
GasTokenInterface public constant gasToken = GasTokenInterface(0x0000000000b3F879cb30FE243b4Dfee438691c04);
modifier burnGas(uint _amount) {
if (gasToken.balanceOf(address(this)) >= _amount) {
gasToken.free(_amount);
}
_;
}
}
library SafeERC20 {
using SafeMath for uint256;
using Address for address;
function safeTransfer(ERC20 token, address to, uint256 value) internal {
_callOptionalReturn(token, abi.encodeWithSelector(token.transfer.selector, to, value));
}
function safeTransferFrom(ERC20 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.
*/
function safeApprove(ERC20 token, address spender, uint256 value) internal {
_callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, 0));
_callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, value));
}
function safeIncreaseAllowance(ERC20 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(ERC20 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));
}
function _callOptionalReturn(ERC20 token, bytes memory data) private {
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");
}
}
}
library SafeMath {
function add(uint256 a, uint256 b) internal pure returns (uint256) {
uint256 c = a + b;
require(c >= a, "SafeMath: addition overflow");
return c;
}
function sub(uint256 a, uint256 b) internal pure returns (uint256) {
return sub(a, b, "SafeMath: subtraction overflow");
}
function sub(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
require(b <= a, errorMessage);
uint256 c = a - b;
return c;
}
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;
}
function div(uint256 a, uint256 b) internal pure returns (uint256) {
return div(a, b, "SafeMath: division by 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;
}
function mod(uint256 a, uint256 b) internal pure returns (uint256) {
return mod(a, b, "SafeMath: modulo by zero");
}
function mod(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
require(b != 0, errorMessage);
return a % b;
}
}
contract ZrxAllowlist is AdminAuth {
mapping (address => bool) public zrxAllowlist;
mapping(address => bool) private nonPayableAddrs;
constructor() public {
zrxAllowlist[0x6958F5e95332D93D21af0D7B9Ca85B8212fEE0A5] = true;
zrxAllowlist[0x61935CbDd02287B511119DDb11Aeb42F1593b7Ef] = true;
zrxAllowlist[0xDef1C0ded9bec7F1a1670819833240f027b25EfF] = true;
zrxAllowlist[0x080bf510FCbF18b91105470639e9561022937712] = true;
nonPayableAddrs[0x080bf510FCbF18b91105470639e9561022937712] = true;
}
function setAllowlistAddr(address _zrxAddr, bool _state) public onlyOwner {
zrxAllowlist[_zrxAddr] = _state;
}
function isZrxAddr(address _zrxAddr) public view returns (bool) {
return zrxAllowlist[_zrxAddr];
}
function addNonPayableAddr(address _nonPayableAddr) public onlyOwner {
nonPayableAddrs[_nonPayableAddr] = true;
}
function removeNonPayableAddr(address _nonPayableAddr) public onlyOwner {
nonPayableAddrs[_nonPayableAddr] = false;
}
function isNonPayableAddr(address _addr) public view returns(bool) {
return nonPayableAddrs[_addr];
}
}
contract AaveBasicProxy is GasBurner {
using SafeERC20 for ERC20;
address public constant ETH_ADDR = 0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE;
address public constant AAVE_LENDING_POOL_ADDRESSES = 0x24a42fD28C976A61Df5D00D0599C34c4f90748c8;
uint16 public constant AAVE_REFERRAL_CODE = 64;
/// @notice User deposits tokens to the Aave protocol
/// @dev User needs to approve the DSProxy to pull the _tokenAddr tokens
/// @param _tokenAddr The address of the token to be deposited
/// @param _amount Amount of tokens to be deposited
function deposit(address _tokenAddr, uint256 _amount) public burnGas(5) payable {
address lendingPoolCore = ILendingPoolAddressesProvider(AAVE_LENDING_POOL_ADDRESSES).getLendingPoolCore();
address lendingPool = ILendingPoolAddressesProvider(AAVE_LENDING_POOL_ADDRESSES).getLendingPool();
uint ethValue = _amount;
if (_tokenAddr != ETH_ADDR) {
ERC20(_tokenAddr).safeTransferFrom(msg.sender, address(this), _amount);
approveToken(_tokenAddr, lendingPoolCore);
ethValue = 0;
}
ILendingPool(lendingPool).deposit{value: ethValue}(_tokenAddr, _amount, AAVE_REFERRAL_CODE);
setUserUseReserveAsCollateralIfNeeded(_tokenAddr);
}
/// @notice User withdraws tokens from the Aave protocol
/// @param _tokenAddr The address of the token to be withdrawn
/// @param _aTokenAddr ATokens to be withdrawn
/// @param _amount Amount of tokens to be withdrawn
/// @param _wholeAmount If true we will take the whole amount on chain
function withdraw(address _tokenAddr, address _aTokenAddr, uint256 _amount, bool _wholeAmount) public burnGas(8) {
uint256 amount = _wholeAmount ? ERC20(_aTokenAddr).balanceOf(address(this)) : _amount;
IAToken(_aTokenAddr).redeem(amount);
withdrawTokens(_tokenAddr);
}
/// @notice User borrows tokens to the Aave protocol
/// @param _tokenAddr The address of the token to be borrowed
/// @param _amount Amount of tokens to be borrowed
/// @param _type Send 1 for variable rate and 2 for fixed rate
function borrow(address _tokenAddr, uint256 _amount, uint256 _type) public burnGas(8) {
address lendingPool = ILendingPoolAddressesProvider(AAVE_LENDING_POOL_ADDRESSES).getLendingPool();
ILendingPool(lendingPool).borrow(_tokenAddr, _amount, _type, AAVE_REFERRAL_CODE);
withdrawTokens(_tokenAddr);
}
/// @dev User needs to approve the DSProxy to pull the _tokenAddr tokens
/// @notice User paybacks tokens to the Aave protocol
/// @param _tokenAddr The address of the token to be paybacked
/// @param _aTokenAddr ATokens to be paybacked
/// @param _amount Amount of tokens to be payed back
/// @param _wholeDebt If true the _amount will be set to the whole amount of the debt
function payback(address _tokenAddr, address _aTokenAddr, uint256 _amount, bool _wholeDebt) public burnGas(3) payable {
address lendingPoolCore = ILendingPoolAddressesProvider(AAVE_LENDING_POOL_ADDRESSES).getLendingPoolCore();
address lendingPool = ILendingPoolAddressesProvider(AAVE_LENDING_POOL_ADDRESSES).getLendingPool();
uint256 amount = _amount;
(,uint256 borrowAmount,,,,,uint256 originationFee,,,) = ILendingPool(lendingPool).getUserReserveData(_tokenAddr, address(this));
if (_wholeDebt) {
amount = borrowAmount + originationFee;
}
if (_tokenAddr != ETH_ADDR) {
ERC20(_tokenAddr).safeTransferFrom(msg.sender, address(this), amount);
approveToken(_tokenAddr, lendingPoolCore);
}
ILendingPool(lendingPool).repay{value: msg.value}(_tokenAddr, amount, payable(address(this)));
withdrawTokens(_tokenAddr);
}
/// @dev User needs to approve the DSProxy to pull the _tokenAddr tokens
/// @notice User paybacks tokens to the Aave protocol
/// @param _tokenAddr The address of the token to be paybacked
/// @param _aTokenAddr ATokens to be paybacked
/// @param _amount Amount of tokens to be payed back
/// @param _wholeDebt If true the _amount will be set to the whole amount of the debt
function paybackOnBehalf(address _tokenAddr, address _aTokenAddr, uint256 _amount, bool _wholeDebt, address payable _onBehalf) public burnGas(3) payable {
address lendingPoolCore = ILendingPoolAddressesProvider(AAVE_LENDING_POOL_ADDRESSES).getLendingPoolCore();
address lendingPool = ILendingPoolAddressesProvider(AAVE_LENDING_POOL_ADDRESSES).getLendingPool();
uint256 amount = _amount;
(,uint256 borrowAmount,,,,,uint256 originationFee,,,) = ILendingPool(lendingPool).getUserReserveData(_tokenAddr, _onBehalf);
if (_wholeDebt) {
amount = borrowAmount + originationFee;
}
if (_tokenAddr != ETH_ADDR) {
ERC20(_tokenAddr).safeTransferFrom(msg.sender, address(this), amount);
if (originationFee > 0) {
ERC20(_tokenAddr).safeTransfer(_onBehalf, originationFee);
}
approveToken(_tokenAddr, lendingPoolCore);
}
ILendingPool(lendingPool).repay{value: msg.value}(_tokenAddr, amount, _onBehalf);
withdrawTokens(_tokenAddr);
}
/// @notice Helper method to withdraw tokens from the DSProxy
/// @param _tokenAddr Address of the token to be withdrawn
function withdrawTokens(address _tokenAddr) public {
uint256 amount = _tokenAddr == ETH_ADDR ? address(this).balance : ERC20(_tokenAddr).balanceOf(address(this));
if (amount > 0) {
if (_tokenAddr != ETH_ADDR) {
ERC20(_tokenAddr).safeTransfer(msg.sender, amount);
} else {
msg.sender.transfer(amount);
}
}
}
/// @notice Approves token contract to pull underlying tokens from the DSProxy
/// @param _tokenAddr Token we are trying to approve
/// @param _caller Address which will gain the approval
function approveToken(address _tokenAddr, address _caller) internal {
if (_tokenAddr != ETH_ADDR) {
ERC20(_tokenAddr).safeApprove(_caller, uint256(-1));
}
}
function setUserUseReserveAsCollateralIfNeeded(address _tokenAddr) public {
address lendingPool = ILendingPoolAddressesProvider(AAVE_LENDING_POOL_ADDRESSES).getLendingPool();
(,,,,,,,,,bool collateralEnabled) = ILendingPool(lendingPool).getUserReserveData(_tokenAddr, address(this));
if (!collateralEnabled) {
ILendingPool(lendingPool).setUserUseReserveAsCollateral(_tokenAddr, true);
}
}
function setUserUseReserveAsCollateral(address _tokenAddr, bool _true) public {
address lendingPool = ILendingPoolAddressesProvider(AAVE_LENDING_POOL_ADDRESSES).getLendingPool();
ILendingPool(lendingPool).setUserUseReserveAsCollateral(_tokenAddr, _true);
}
function swapBorrowRateMode(address _reserve) public {
address lendingPool = ILendingPoolAddressesProvider(AAVE_LENDING_POOL_ADDRESSES).getLendingPool();
ILendingPool(lendingPool).swapBorrowRateMode(_reserve);
}
}
contract AaveLoanInfo is AaveSafetyRatio {
struct LoanData {
address user;
uint128 ratio;
address[] collAddr;
address[] borrowAddr;
uint256[] collAmounts;
uint256[] borrowAmounts;
}
struct TokenInfo {
address aTokenAddress;
address underlyingTokenAddress;
uint256 collateralFactor;
uint256 price;
}
struct TokenInfoFull {
address aTokenAddress;
address underlyingTokenAddress;
uint256 supplyRate;
uint256 borrowRate;
uint256 borrowRateStable;
uint256 totalSupply;
uint256 availableLiquidity;
uint256 totalBorrow;
uint256 collateralFactor;
uint256 liquidationRatio;
uint256 price;
bool usageAsCollateralEnabled;
}
struct UserToken {
address token;
uint256 balance;
uint256 borrows;
uint256 borrowRateMode;
bool enabledAsCollateral;
}
/// @notice Calcualted the ratio of coll/debt for a compound user
/// @param _user Address of the user
function getRatio(address _user) public view returns (uint256) {
// For each asset the account is in
return getSafetyRatio(_user);
}
/// @notice Fetches Aave prices for tokens
/// @param _tokens Arr. of tokens for which to get the prices
/// @return prices Array of prices
function getPrices(address[] memory _tokens) public view returns (uint256[] memory prices) {
address priceOracleAddress = ILendingPoolAddressesProvider(AAVE_LENDING_POOL_ADDRESSES).getPriceOracle();
prices = new uint[](_tokens.length);
for (uint256 i = 0; i < _tokens.length; ++i) {
prices[i] = IPriceOracleGetterAave(priceOracleAddress).getAssetPrice(_tokens[i]);
}
}
/// @notice Fetches Aave collateral factors for tokens
/// @param _tokens Arr. of tokens for which to get the coll. factors
/// @return collFactors Array of coll. factors
function getCollFactors(address[] memory _tokens) public view returns (uint256[] memory collFactors) {
address lendingPoolCoreAddress = ILendingPoolAddressesProvider(AAVE_LENDING_POOL_ADDRESSES).getLendingPoolCore();
collFactors = new uint256[](_tokens.length);
for (uint256 i = 0; i < _tokens.length; ++i) {
(,collFactors[i],,) = ILendingPool(lendingPoolCoreAddress).getReserveConfiguration(_tokens[i]);
}
}
function getTokenBalances(address _user, address[] memory _tokens) public view returns (UserToken[] memory userTokens) {
address lendingPoolAddress = ILendingPoolAddressesProvider(AAVE_LENDING_POOL_ADDRESSES).getLendingPool();
userTokens = new UserToken[](_tokens.length);
for (uint256 i = 0; i < _tokens.length; i++) {
address asset = _tokens[i];
userTokens[i].token = asset;
(userTokens[i].balance, userTokens[i].borrows,,userTokens[i].borrowRateMode,,,,,,userTokens[i].enabledAsCollateral) = ILendingPool(lendingPoolAddress).getUserReserveData(asset, _user);
}
}
/// @notice Calcualted the ratio of coll/debt for an aave user
/// @param _users Addresses of the user
/// @return ratios Array of ratios
function getRatios(address[] memory _users) public view returns (uint256[] memory ratios) {
ratios = new uint256[](_users.length);
for (uint256 i = 0; i < _users.length; ++i) {
ratios[i] = getSafetyRatio(_users[i]);
}
}
/// @notice Information about reserves
/// @param _tokenAddresses Array of tokens addresses
/// @return tokens Array of reserves infomartion
function getTokensInfo(address[] memory _tokenAddresses) public view returns(TokenInfo[] memory tokens) {
address lendingPoolCoreAddress = ILendingPoolAddressesProvider(AAVE_LENDING_POOL_ADDRESSES).getLendingPoolCore();
address priceOracleAddress = ILendingPoolAddressesProvider(AAVE_LENDING_POOL_ADDRESSES).getPriceOracle();
tokens = new TokenInfo[](_tokenAddresses.length);
for (uint256 i = 0; i < _tokenAddresses.length; ++i) {
(,uint256 ltv,,) = ILendingPool(lendingPoolCoreAddress).getReserveConfiguration(_tokenAddresses[i]);
tokens[i] = TokenInfo({
aTokenAddress: ILendingPool(lendingPoolCoreAddress).getReserveATokenAddress(_tokenAddresses[i]),
underlyingTokenAddress: _tokenAddresses[i],
collateralFactor: ltv,
price: IPriceOracleGetterAave(priceOracleAddress).getAssetPrice(_tokenAddresses[i])
});
}
}
/// @notice Information about reserves
/// @param _tokenAddresses Array of token addresses
/// @return tokens Array of reserves infomartion
function getFullTokensInfo(address[] memory _tokenAddresses) public view returns(TokenInfoFull[] memory tokens) {
address lendingPoolCoreAddress = ILendingPoolAddressesProvider(AAVE_LENDING_POOL_ADDRESSES).getLendingPoolCore();
address lendingPoolAddress = ILendingPoolAddressesProvider(AAVE_LENDING_POOL_ADDRESSES).getLendingPool();
address priceOracleAddress = ILendingPoolAddressesProvider(AAVE_LENDING_POOL_ADDRESSES).getPriceOracle();
tokens = new TokenInfoFull[](_tokenAddresses.length);
for (uint256 i = 0; i < _tokenAddresses.length; ++i) {
(uint256 ltv, uint256 liqRatio,,, bool usageAsCollateralEnabled, bool borrowingEnabled, bool stableBorrowingEnabled,) = ILendingPool(lendingPoolAddress).getReserveConfigurationData(_tokenAddresses[i]);
tokens[i] = TokenInfoFull({
aTokenAddress: ILendingPool(lendingPoolCoreAddress).getReserveATokenAddress(_tokenAddresses[i]),
underlyingTokenAddress: _tokenAddresses[i],
supplyRate: ILendingPool(lendingPoolCoreAddress).getReserveCurrentLiquidityRate(_tokenAddresses[i]),
borrowRate: borrowingEnabled ? ILendingPool(lendingPoolCoreAddress).getReserveCurrentVariableBorrowRate(_tokenAddresses[i]) : 0,
borrowRateStable: stableBorrowingEnabled ? ILendingPool(lendingPoolCoreAddress).getReserveCurrentStableBorrowRate(_tokenAddresses[i]) : 0,
totalSupply: ILendingPool(lendingPoolCoreAddress).getReserveTotalLiquidity(_tokenAddresses[i]),
availableLiquidity: ILendingPool(lendingPoolCoreAddress).getReserveAvailableLiquidity(_tokenAddresses[i]),
totalBorrow: ILendingPool(lendingPoolCoreAddress).getReserveTotalBorrowsVariable(_tokenAddresses[i]),
collateralFactor: ltv,
liquidationRatio: liqRatio,
price: IPriceOracleGetterAave(priceOracleAddress).getAssetPrice(_tokenAddresses[i]),
usageAsCollateralEnabled: usageAsCollateralEnabled
});
}
}
/// @notice Fetches all the collateral/debt address and amounts, denominated in ether
/// @param _user Address of the user
/// @return data LoanData information
function getLoanData(address _user) public view returns (LoanData memory data) {
address lendingPoolAddress = ILendingPoolAddressesProvider(AAVE_LENDING_POOL_ADDRESSES).getLendingPool();
address priceOracleAddress = ILendingPoolAddressesProvider(AAVE_LENDING_POOL_ADDRESSES).getPriceOracle();
address[] memory reserves = ILendingPool(lendingPoolAddress).getReserves();
data = LoanData({
user: _user,
ratio: 0,
collAddr: new address[](reserves.length),
borrowAddr: new address[](reserves.length),
collAmounts: new uint[](reserves.length),
borrowAmounts: new uint[](reserves.length)
});
uint64 collPos = 0;
uint64 borrowPos = 0;
for (uint64 i = 0; i < reserves.length; i++) {
address reserve = reserves[i];
(uint256 aTokenBalance, uint256 borrowBalance,,,,,,,,) = ILendingPool(lendingPoolAddress).getUserReserveData(reserve, _user);
uint256 price = IPriceOracleGetterAave(priceOracleAddress).getAssetPrice(reserves[i]);
if (aTokenBalance > 0) {
uint256 userTokenBalanceEth = wmul(aTokenBalance, price) * (10 ** (18 - _getDecimals(reserve)));
data.collAddr[collPos] = reserve;
data.collAmounts[collPos] = userTokenBalanceEth;
collPos++;
}
// Sum up debt in Eth
if (borrowBalance > 0) {
uint256 userBorrowBalanceEth = wmul(borrowBalance, price) * (10 ** (18 - _getDecimals(reserve)));
data.borrowAddr[borrowPos] = reserve;
data.borrowAmounts[borrowPos] = userBorrowBalanceEth;
borrowPos++;
}
}
data.ratio = uint128(getSafetyRatio(_user));
return data;
}
/// @notice Fetches all the collateral/debt address and amounts, denominated in ether
/// @param _users Addresses of the user
/// @return loans Array of LoanData information
function getLoanDataArr(address[] memory _users) public view returns (LoanData[] memory loans) {
loans = new LoanData[](_users.length);
for (uint i = 0; i < _users.length; ++i) {
loans[i] = getLoanData(_users[i]);
}
}
}
contract AaveMonitor is AdminAuth, DSMath, AaveSafetyRatio, GasBurner {
using SafeERC20 for ERC20;
enum Method { Boost, Repay }
uint public REPAY_GAS_TOKEN = 19;
uint public BOOST_GAS_TOKEN = 19;
uint public MAX_GAS_PRICE = 200000000000; // 200 gwei
uint public REPAY_GAS_COST = 2500000;
uint public BOOST_GAS_COST = 2500000;
address public constant DEFISAVER_LOGGER = 0x5c55B921f590a89C1Ebe84dF170E655a82b62126;
AaveMonitorProxy public aaveMonitorProxy;
AaveSubscriptions public subscriptionsContract;
address public aaveSaverProxy;
DefisaverLogger public logger = DefisaverLogger(DEFISAVER_LOGGER);
modifier onlyApproved() {
require(BotRegistry(BOT_REGISTRY_ADDRESS).botList(msg.sender), "Not auth bot");
_;
}
/// @param _aaveMonitorProxy Proxy contracts that actually is authorized to call DSProxy
/// @param _subscriptions Subscriptions contract for Aave positions
/// @param _aaveSaverProxy Contract that actually performs Repay/Boost
constructor(address _aaveMonitorProxy, address _subscriptions, address _aaveSaverProxy) public {
aaveMonitorProxy = AaveMonitorProxy(_aaveMonitorProxy);
subscriptionsContract = AaveSubscriptions(_subscriptions);
aaveSaverProxy = _aaveSaverProxy;
}
/// @notice Bots call this method to repay for user when conditions are met
/// @dev If the contract ownes gas token it will try and use it for gas price reduction
/// @param _exData Exchange data
/// @param _user The actual address that owns the Aave position
function repayFor(
SaverExchangeCore.ExchangeData memory _exData,
address _user
) public payable onlyApproved burnGas(REPAY_GAS_TOKEN) {
(bool isAllowed, uint ratioBefore) = canCall(Method.Repay, _user);
require(isAllowed); // check if conditions are met
uint256 gasCost = calcGasCost(REPAY_GAS_COST);
aaveMonitorProxy.callExecute{value: msg.value}(
_user,
aaveSaverProxy,
abi.encodeWithSignature(
"repay((address,address,uint256,uint256,uint256,address,address,bytes,uint256),uint256)",
_exData,
gasCost
)
);
(bool isGoodRatio, uint ratioAfter) = ratioGoodAfter(Method.Repay, _user);
require(isGoodRatio); // check if the after result of the actions is good
returnEth();
logger.Log(address(this), _user, "AutomaticAaveRepay", abi.encode(ratioBefore, ratioAfter));
}
/// @notice Bots call this method to boost for user when conditions are met
/// @dev If the contract ownes gas token it will try and use it for gas price reduction
/// @param _exData Exchange data
/// @param _user The actual address that owns the Aave position
function boostFor(
SaverExchangeCore.ExchangeData memory _exData,
address _user
) public payable onlyApproved burnGas(BOOST_GAS_TOKEN) {
(bool isAllowed, uint ratioBefore) = canCall(Method.Boost, _user);
require(isAllowed); // check if conditions are met
uint256 gasCost = calcGasCost(BOOST_GAS_COST);
aaveMonitorProxy.callExecute{value: msg.value}(
_user,
aaveSaverProxy,
abi.encodeWithSignature(
"boost((address,address,uint256,uint256,uint256,address,address,bytes,uint256),uint256)",
_exData,
gasCost
)
);
(bool isGoodRatio, uint ratioAfter) = ratioGoodAfter(Method.Boost, _user);
require(isGoodRatio); // check if the after result of the actions is good
returnEth();
logger.Log(address(this), _user, "AutomaticAaveBoost", abi.encode(ratioBefore, ratioAfter));
}
/******************* INTERNAL METHODS ********************************/
function returnEth() internal {
// return if some eth left
if (address(this).balance > 0) {
msg.sender.transfer(address(this).balance);
}
}
/******************* STATIC METHODS ********************************/
/// @notice Checks if Boost/Repay could be triggered for the CDP
/// @dev Called by AaveMonitor to enforce the min/max check
/// @param _method Type of action to be called
/// @param _user The actual address that owns the Aave position
/// @return Boolean if it can be called and the ratio
function canCall(Method _method, address _user) public view returns(bool, uint) {
bool subscribed = subscriptionsContract.isSubscribed(_user);
AaveSubscriptions.AaveHolder memory holder = subscriptionsContract.getHolder(_user);
// check if cdp is subscribed
if (!subscribed) return (false, 0);
// check if boost and boost allowed
if (_method == Method.Boost && !holder.boostEnabled) return (false, 0);
uint currRatio = getSafetyRatio(_user);
if (_method == Method.Repay) {
return (currRatio < holder.minRatio, currRatio);
} else if (_method == Method.Boost) {
return (currRatio > holder.maxRatio, currRatio);
}
}
/// @dev After the Boost/Repay check if the ratio doesn't trigger another call
/// @param _method Type of action to be called
/// @param _user The actual address that owns the Aave position
/// @return Boolean if the recent action preformed correctly and the ratio
function ratioGoodAfter(Method _method, address _user) public view returns(bool, uint) {
AaveSubscriptions.AaveHolder memory holder;
holder= subscriptionsContract.getHolder(_user);
uint currRatio = getSafetyRatio(_user);
if (_method == Method.Repay) {
return (currRatio < holder.maxRatio, currRatio);
} else if (_method == Method.Boost) {
return (currRatio > holder.minRatio, currRatio);
}
}
/// @notice Calculates gas cost (in Eth) of tx
/// @dev Gas price is limited to MAX_GAS_PRICE to prevent attack of draining user CDP
/// @param _gasAmount Amount of gas used for the tx
function calcGasCost(uint _gasAmount) public view returns (uint) {
uint gasPrice = tx.gasprice <= MAX_GAS_PRICE ? tx.gasprice : MAX_GAS_PRICE;
return mul(gasPrice, _gasAmount);
}
/******************* OWNER ONLY OPERATIONS ********************************/
/// @notice Allows owner to change gas cost for boost operation, but only up to 3 millions
/// @param _gasCost New gas cost for boost method
function changeBoostGasCost(uint _gasCost) public onlyOwner {
require(_gasCost < 3000000);
BOOST_GAS_COST = _gasCost;
}
/// @notice Allows owner to change gas cost for repay operation, but only up to 3 millions
/// @param _gasCost New gas cost for repay method
function changeRepayGasCost(uint _gasCost) public onlyOwner {
require(_gasCost < 3000000);
REPAY_GAS_COST = _gasCost;
}
/// @notice Allows owner to change max gas price
/// @param _maxGasPrice New max gas price
function changeMaxGasPrice(uint _maxGasPrice) public onlyOwner {
require(_maxGasPrice < 500000000000);
MAX_GAS_PRICE = _maxGasPrice;
}
/// @notice Allows owner to change gas token amount
/// @param _gasTokenAmount New gas token amount
/// @param _repay true if repay gas token, false if boost gas token
function changeGasTokenAmount(uint _gasTokenAmount, bool _repay) public onlyOwner {
if (_repay) {
REPAY_GAS_TOKEN = _gasTokenAmount;
} else {
BOOST_GAS_TOKEN = _gasTokenAmount;
}
}
}
contract AaveMonitorProxy is AdminAuth {
using SafeERC20 for ERC20;
uint public CHANGE_PERIOD;
address public monitor;
address public newMonitor;
address public lastMonitor;
uint public changeRequestedTimestamp;
mapping(address => bool) public allowed;
event MonitorChangeInitiated(address oldMonitor, address newMonitor);
event MonitorChangeCanceled();
event MonitorChangeFinished(address monitor);
event MonitorChangeReverted(address monitor);
// if someone who is allowed become malicious, owner can't be changed
modifier onlyAllowed() {
require(allowed[msg.sender] || msg.sender == owner);
_;
}
modifier onlyMonitor() {
require (msg.sender == monitor);
_;
}
constructor(uint _changePeriod) public {
CHANGE_PERIOD = _changePeriod * 1 days;
}
/// @notice Only monitor contract is able to call execute on users proxy
/// @param _owner Address of cdp owner (users DSProxy address)
/// @param _aaveSaverProxy Address of AaveSaverProxy
/// @param _data Data to send to AaveSaverProxy
function callExecute(address _owner, address _aaveSaverProxy, bytes memory _data) public payable onlyMonitor {
// execute reverts if calling specific method fails
DSProxyInterface(_owner).execute{value: msg.value}(_aaveSaverProxy, _data);
// return if anything left
if (address(this).balance > 0) {
msg.sender.transfer(address(this).balance);
}
}
/// @notice Allowed users are able to set Monitor contract without any waiting period first time
/// @param _monitor Address of Monitor contract
function setMonitor(address _monitor) public onlyAllowed {
require(monitor == address(0));
monitor = _monitor;
}
/// @notice Allowed users are able to start procedure for changing monitor
/// @dev after CHANGE_PERIOD needs to call confirmNewMonitor to actually make a change
/// @param _newMonitor address of new monitor
function changeMonitor(address _newMonitor) public onlyAllowed {
require(changeRequestedTimestamp == 0);
changeRequestedTimestamp = now;
lastMonitor = monitor;
newMonitor = _newMonitor;
emit MonitorChangeInitiated(lastMonitor, newMonitor);
}
/// @notice At any point allowed users are able to cancel monitor change
function cancelMonitorChange() public onlyAllowed {
require(changeRequestedTimestamp > 0);
changeRequestedTimestamp = 0;
newMonitor = address(0);
emit MonitorChangeCanceled();
}
/// @notice Anyone is able to confirm new monitor after CHANGE_PERIOD if process is started
function confirmNewMonitor() public onlyAllowed {
require((changeRequestedTimestamp + CHANGE_PERIOD) < now);
require(changeRequestedTimestamp != 0);
require(newMonitor != address(0));
monitor = newMonitor;
newMonitor = address(0);
changeRequestedTimestamp = 0;
emit MonitorChangeFinished(monitor);
}
/// @notice Its possible to revert monitor to last used monitor
function revertMonitor() public onlyAllowed {
require(lastMonitor != address(0));
monitor = lastMonitor;
emit MonitorChangeReverted(monitor);
}
/// @notice Allowed users are able to add new allowed user
/// @param _user Address of user that will be allowed
function addAllowed(address _user) public onlyAllowed {
allowed[_user] = true;
}
/// @notice Allowed users are able to remove allowed user
/// @dev owner is always allowed even if someone tries to remove it from allowed mapping
/// @param _user Address of allowed user
function removeAllowed(address _user) public onlyAllowed {
allowed[_user] = false;
}
function setChangePeriod(uint _periodInDays) public onlyAllowed {
require(_periodInDays * 1 days > CHANGE_PERIOD);
CHANGE_PERIOD = _periodInDays * 1 days;
}
/// @notice In case something is left in contract, owner is able to withdraw it
/// @param _token address of token to withdraw balance
function withdrawToken(address _token) public onlyOwner {
uint balance = ERC20(_token).balanceOf(address(this));
ERC20(_token).safeTransfer(msg.sender, balance);
}
/// @notice In case something is left in contract, owner is able to withdraw it
function withdrawEth() public onlyOwner {
uint balance = address(this).balance;
msg.sender.transfer(balance);
}
}
contract AaveSubscriptions is AdminAuth {
struct AaveHolder {
address user;
uint128 minRatio;
uint128 maxRatio;
uint128 optimalRatioBoost;
uint128 optimalRatioRepay;
bool boostEnabled;
}
struct SubPosition {
uint arrPos;
bool subscribed;
}
AaveHolder[] public subscribers;
mapping (address => SubPosition) public subscribersPos;
uint public changeIndex;
event Subscribed(address indexed user);
event Unsubscribed(address indexed user);
event Updated(address indexed user);
event ParamUpdates(address indexed user, uint128, uint128, uint128, uint128, bool);
/// @dev Called by the DSProxy contract which owns the Aave position
/// @notice Adds the users Aave poistion in the list of subscriptions so it can be monitored
/// @param _minRatio Minimum ratio below which repay is triggered
/// @param _maxRatio Maximum ratio after which boost is triggered
/// @param _optimalBoost Ratio amount which boost should target
/// @param _optimalRepay Ratio amount which repay should target
/// @param _boostEnabled Boolean determing if boost is enabled
function subscribe(uint128 _minRatio, uint128 _maxRatio, uint128 _optimalBoost, uint128 _optimalRepay, bool _boostEnabled) external {
// if boost is not enabled, set max ratio to max uint
uint128 localMaxRatio = _boostEnabled ? _maxRatio : uint128(-1);
require(checkParams(_minRatio, localMaxRatio), "Must be correct params");
SubPosition storage subInfo = subscribersPos[msg.sender];
AaveHolder memory subscription = AaveHolder({
minRatio: _minRatio,
maxRatio: localMaxRatio,
optimalRatioBoost: _optimalBoost,
optimalRatioRepay: _optimalRepay,
user: msg.sender,
boostEnabled: _boostEnabled
});
changeIndex++;
if (subInfo.subscribed) {
subscribers[subInfo.arrPos] = subscription;
emit Updated(msg.sender);
emit ParamUpdates(msg.sender, _minRatio, localMaxRatio, _optimalBoost, _optimalRepay, _boostEnabled);
} else {
subscribers.push(subscription);
subInfo.arrPos = subscribers.length - 1;
subInfo.subscribed = true;
emit Subscribed(msg.sender);
}
}
/// @notice Called by the users DSProxy
/// @dev Owner who subscribed cancels his subscription
function unsubscribe() external {
_unsubscribe(msg.sender);
}
/// @dev Checks limit if minRatio is bigger than max
/// @param _minRatio Minimum ratio, bellow which repay can be triggered
/// @param _maxRatio Maximum ratio, over which boost can be triggered
/// @return Returns bool if the params are correct
function checkParams(uint128 _minRatio, uint128 _maxRatio) internal pure returns (bool) {
if (_minRatio > _maxRatio) {
return false;
}
return true;
}
/// @dev Internal method to remove a subscriber from the list
/// @param _user The actual address that owns the Aave position
function _unsubscribe(address _user) internal {
require(subscribers.length > 0, "Must have subscribers in the list");
SubPosition storage subInfo = subscribersPos[_user];
require(subInfo.subscribed, "Must first be subscribed");
address lastOwner = subscribers[subscribers.length - 1].user;
SubPosition storage subInfo2 = subscribersPos[lastOwner];
subInfo2.arrPos = subInfo.arrPos;
subscribers[subInfo.arrPos] = subscribers[subscribers.length - 1];
subscribers.pop(); // remove last element and reduce arr length
changeIndex++;
subInfo.subscribed = false;
subInfo.arrPos = 0;
emit Unsubscribed(msg.sender);
}
/// @dev Checks if the user is subscribed
/// @param _user The actual address that owns the Aave position
/// @return If the user is subscribed
function isSubscribed(address _user) public view returns (bool) {
SubPosition storage subInfo = subscribersPos[_user];
return subInfo.subscribed;
}
/// @dev Returns subscribtion information about a user
/// @param _user The actual address that owns the Aave position
/// @return Subscription information about the user if exists
function getHolder(address _user) public view returns (AaveHolder memory) {
SubPosition storage subInfo = subscribersPos[_user];
return subscribers[subInfo.arrPos];
}
/// @notice Helper method to return all the subscribed CDPs
/// @return List of all subscribers
function getSubscribers() public view returns (AaveHolder[] memory) {
return subscribers;
}
/// @notice Helper method for the frontend, returns all the subscribed CDPs paginated
/// @param _page What page of subscribers you want
/// @param _perPage Number of entries per page
/// @return List of all subscribers for that page
function getSubscribersByPage(uint _page, uint _perPage) public view returns (AaveHolder[] memory) {
AaveHolder[] memory holders = new AaveHolder[](_perPage);
uint start = _page * _perPage;
uint end = start + _perPage;
end = (end > holders.length) ? holders.length : end;
uint count = 0;
for (uint i = start; i < end; i++) {
holders[count] = subscribers[i];
count++;
}
return holders;
}
////////////// ADMIN METHODS ///////////////////
/// @notice Admin function to unsubscribe a position
/// @param _user The actual address that owns the Aave position
function unsubscribeByAdmin(address _user) public onlyOwner {
SubPosition storage subInfo = subscribersPos[_user];
if (subInfo.subscribed) {
_unsubscribe(_user);
}
}
}
contract AaveSubscriptionsProxy is ProxyPermission {
address public constant AAVE_SUBSCRIPTION_ADDRESS = 0xe08ff7A2BADb634F0b581E675E6B3e583De086FC;
address public constant AAVE_MONITOR_PROXY = 0xfA560Dba3a8D0B197cA9505A2B98120DD89209AC;
/// @notice Calls subscription contract and creates a DSGuard if non existent
/// @param _minRatio Minimum ratio below which repay is triggered
/// @param _maxRatio Maximum ratio after which boost is triggered
/// @param _optimalRatioBoost Ratio amount which boost should target
/// @param _optimalRatioRepay Ratio amount which repay should target
/// @param _boostEnabled Boolean determing if boost is enabled
function subscribe(
uint128 _minRatio,
uint128 _maxRatio,
uint128 _optimalRatioBoost,
uint128 _optimalRatioRepay,
bool _boostEnabled
) public {
givePermission(AAVE_MONITOR_PROXY);
IAaveSubscription(AAVE_SUBSCRIPTION_ADDRESS).subscribe(
_minRatio, _maxRatio, _optimalRatioBoost, _optimalRatioRepay, _boostEnabled);
}
/// @notice Calls subscription contract and updated existing parameters
/// @dev If subscription is non existent this will create one
/// @param _minRatio Minimum ratio below which repay is triggered
/// @param _maxRatio Maximum ratio after which boost is triggered
/// @param _optimalRatioBoost Ratio amount which boost should target
/// @param _optimalRatioRepay Ratio amount which repay should target
/// @param _boostEnabled Boolean determing if boost is enabled
function update(
uint128 _minRatio,
uint128 _maxRatio,
uint128 _optimalRatioBoost,
uint128 _optimalRatioRepay,
bool _boostEnabled
) public {
IAaveSubscription(AAVE_SUBSCRIPTION_ADDRESS).subscribe(_minRatio, _maxRatio, _optimalRatioBoost, _optimalRatioRepay, _boostEnabled);
}
/// @notice Calls the subscription contract to unsubscribe the caller
function unsubscribe() public {
removePermission(AAVE_MONITOR_PROXY);
IAaveSubscription(AAVE_SUBSCRIPTION_ADDRESS).unsubscribe();
}
}
contract AaveImport is AaveHelper, AdminAuth {
using SafeERC20 for ERC20;
address public constant WETH_ADDRESS = 0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2;
address public constant BASIC_PROXY = 0x29F4af15ad64C509c4140324cFE71FB728D10d2B;
address public constant AETH_ADDRESS = 0x3a3A65aAb0dd2A17E3F1947bA16138cd37d08c04;
function callFunction(
address sender,
Account.Info memory account,
bytes memory data
) public {
(
address collateralToken,
address borrowToken,
uint256 ethAmount,
address user,
address proxy
)
= abi.decode(data, (address,address,uint256,address,address));
// withdraw eth
TokenInterface(WETH_ADDRESS).withdraw(ethAmount);
address lendingPoolCoreAddress = ILendingPoolAddressesProvider(AAVE_LENDING_POOL_ADDRESSES).getLendingPoolCore();
address lendingPool = ILendingPoolAddressesProvider(AAVE_LENDING_POOL_ADDRESSES).getLendingPool();
address aCollateralToken = ILendingPool(lendingPoolCoreAddress).getReserveATokenAddress(collateralToken);
address aBorrowToken = ILendingPool(lendingPoolCoreAddress).getReserveATokenAddress(borrowToken);
uint256 globalBorrowAmount = 0;
{ // avoid stack too deep
// deposit eth on behalf of proxy
DSProxy(payable(proxy)).execute{value: ethAmount}(BASIC_PROXY, abi.encodeWithSignature("deposit(address,uint256)", ETH_ADDR, ethAmount));
// borrow needed amount to repay users borrow
(,uint256 borrowAmount,,uint256 borrowRateMode,,,uint256 originationFee,,,) = ILendingPool(lendingPool).getUserReserveData(borrowToken, user);
borrowAmount += originationFee;
DSProxy(payable(proxy)).execute(BASIC_PROXY, abi.encodeWithSignature("borrow(address,uint256,uint256)", borrowToken, borrowAmount, borrowRateMode));
globalBorrowAmount = borrowAmount;
}
// payback on behalf of user
if (borrowToken != ETH_ADDR) {
ERC20(borrowToken).safeApprove(proxy, globalBorrowAmount);
DSProxy(payable(proxy)).execute(BASIC_PROXY, abi.encodeWithSignature("paybackOnBehalf(address,address,uint256,bool,address)", borrowToken, aBorrowToken, 0, true, user));
} else {
DSProxy(payable(proxy)).execute{value: globalBorrowAmount}(BASIC_PROXY, abi.encodeWithSignature("paybackOnBehalf(address,address,uint256,bool,address)", borrowToken, aBorrowToken, 0, true, user));
}
// pull tokens from user to proxy
ERC20(aCollateralToken).safeTransferFrom(user, proxy, ERC20(aCollateralToken).balanceOf(user));
// enable as collateral
DSProxy(payable(proxy)).execute(BASIC_PROXY, abi.encodeWithSignature("setUserUseReserveAsCollateralIfNeeded(address)", collateralToken));
// withdraw deposited eth
DSProxy(payable(proxy)).execute(BASIC_PROXY, abi.encodeWithSignature("withdraw(address,address,uint256,bool)", ETH_ADDR, AETH_ADDRESS, ethAmount, false));
// deposit eth, get weth and return to sender
TokenInterface(WETH_ADDRESS).deposit.value(address(this).balance)();
ERC20(WETH_ADDRESS).safeTransfer(proxy, ethAmount+2);
}
/// @dev if contract receive eth, convert it to WETH
receive() external payable {
// deposit eth and get weth
if (msg.sender == owner) {
TokenInterface(WETH_ADDRESS).deposit.value(address(this).balance)();
}
}
}
contract AaveImportTaker is DydxFlashLoanBase, ProxyPermission {
address public constant WETH_ADDR = 0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2;
address payable public constant AAVE_IMPORT = 0x7b856af5753a9f80968EA002641E69AdF1d795aB;
address public constant DEFISAVER_LOGGER = 0x5c55B921f590a89C1Ebe84dF170E655a82b62126;
address public constant PROXY_REGISTRY_ADDRESS = 0x4678f0a6958e4D2Bc4F1BAF7Bc52E8F3564f3fE4;
/// @notice Starts the process to move users position 1 collateral and 1 borrow
/// @dev User must send 2 wei with this transaction
/// @dev User must approve AaveImport to pull _aCollateralToken
/// @param _collateralToken Collateral token we are moving to DSProxy
/// @param _borrowToken Borrow token we are moving to DSProxy
/// @param _ethAmount ETH amount that needs to be pulled from dydx
function importLoan(address _collateralToken, address _borrowToken, uint _ethAmount) public {
ISoloMargin solo = ISoloMargin(SOLO_MARGIN_ADDRESS);
// Get marketId from token address
uint256 marketId = _getMarketIdFromTokenAddress(WETH_ADDR);
// Calculate repay amount (_amount + (2 wei))
// Approve transfer from
uint256 repayAmount = _getRepaymentAmountInternal(_ethAmount);
ERC20(WETH_ADDR).approve(SOLO_MARGIN_ADDRESS, repayAmount);
Actions.ActionArgs[] memory operations = new Actions.ActionArgs[](3);
operations[0] = _getWithdrawAction(marketId, _ethAmount, AAVE_IMPORT);
operations[1] = _getCallAction(
abi.encode(_collateralToken, _borrowToken, _ethAmount, msg.sender, address(this)),
AAVE_IMPORT
);
operations[2] = _getDepositAction(marketId, repayAmount, address(this));
Account.Info[] memory accountInfos = new Account.Info[](1);
accountInfos[0] = _getAccountInfo();
givePermission(AAVE_IMPORT);
solo.operate(accountInfos, operations);
removePermission(AAVE_IMPORT);
DefisaverLogger(DEFISAVER_LOGGER).Log(address(this), msg.sender, "AaveImport", abi.encode(_collateralToken, _borrowToken));
}
}
contract CompoundBasicProxy is GasBurner {
address public constant ETH_ADDR = 0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE;
address public constant COMPTROLLER_ADDR = 0x3d9819210A31b4961b30EF54bE2aeD79B9c9Cd3B;
using SafeERC20 for ERC20;
/// @notice User deposits tokens to the Compound protocol
/// @dev User needs to approve the DSProxy to pull the _tokenAddr tokens
/// @param _tokenAddr The address of the token to be deposited
/// @param _cTokenAddr CTokens to be deposited
/// @param _amount Amount of tokens to be deposited
/// @param _inMarket True if the token is already in market for that address
function deposit(address _tokenAddr, address _cTokenAddr, uint _amount, bool _inMarket) public burnGas(5) payable {
if (_tokenAddr != ETH_ADDR) {
ERC20(_tokenAddr).safeTransferFrom(msg.sender, address(this), _amount);
}
approveToken(_tokenAddr, _cTokenAddr);
if (!_inMarket) {
enterMarket(_cTokenAddr);
}
if (_tokenAddr != ETH_ADDR) {
require(CTokenInterface(_cTokenAddr).mint(_amount) == 0);
} else {
CEtherInterface(_cTokenAddr).mint{value: msg.value}(); // reverts on fail
}
}
/// @notice User withdraws tokens to the Compound protocol
/// @param _tokenAddr The address of the token to be withdrawn
/// @param _cTokenAddr CTokens to be withdrawn
/// @param _amount Amount of tokens to be withdrawn
/// @param _isCAmount If true _amount is cTokens if falls _amount is underlying tokens
function withdraw(address _tokenAddr, address _cTokenAddr, uint _amount, bool _isCAmount) public burnGas(5) {
if (_isCAmount) {
require(CTokenInterface(_cTokenAddr).redeem(_amount) == 0);
} else {
require(CTokenInterface(_cTokenAddr).redeemUnderlying(_amount) == 0);
}
// withdraw funds to msg.sender
if (_tokenAddr != ETH_ADDR) {
ERC20(_tokenAddr).safeTransfer(msg.sender, ERC20(_tokenAddr).balanceOf(address(this)));
} else {
msg.sender.transfer(address(this).balance);
}
}
/// @notice User borrows tokens to the Compound protocol
/// @param _tokenAddr The address of the token to be borrowed
/// @param _cTokenAddr CTokens to be borrowed
/// @param _amount Amount of tokens to be borrowed
/// @param _inMarket True if the token is already in market for that address
function borrow(address _tokenAddr, address _cTokenAddr, uint _amount, bool _inMarket) public burnGas(8) {
if (!_inMarket) {
enterMarket(_cTokenAddr);
}
require(CTokenInterface(_cTokenAddr).borrow(_amount) == 0);
// withdraw funds to msg.sender
if (_tokenAddr != ETH_ADDR) {
ERC20(_tokenAddr).safeTransfer(msg.sender, ERC20(_tokenAddr).balanceOf(address(this)));
} else {
msg.sender.transfer(address(this).balance);
}
}
/// @dev User needs to approve the DSProxy to pull the _tokenAddr tokens
/// @notice User paybacks tokens to the Compound protocol
/// @param _tokenAddr The address of the token to be paybacked
/// @param _cTokenAddr CTokens to be paybacked
/// @param _amount Amount of tokens to be payedback
/// @param _wholeDebt If true the _amount will be set to the whole amount of the debt
function payback(address _tokenAddr, address _cTokenAddr, uint _amount, bool _wholeDebt) public burnGas(5) payable {
approveToken(_tokenAddr, _cTokenAddr);
if (_wholeDebt) {
_amount = CTokenInterface(_cTokenAddr).borrowBalanceCurrent(address(this));
}
if (_tokenAddr != ETH_ADDR) {
ERC20(_tokenAddr).safeTransferFrom(msg.sender, address(this), _amount);
require(CTokenInterface(_cTokenAddr).repayBorrow(_amount) == 0);
} else {
CEtherInterface(_cTokenAddr).repayBorrow{value: msg.value}();
msg.sender.transfer(address(this).balance); // send back the extra eth
}
}
/// @notice Helper method to withdraw tokens from the DSProxy
/// @param _tokenAddr Address of the token to be withdrawn
function withdrawTokens(address _tokenAddr) public {
if (_tokenAddr != ETH_ADDR) {
ERC20(_tokenAddr).safeTransfer(msg.sender, ERC20(_tokenAddr).balanceOf(address(this)));
} else {
msg.sender.transfer(address(this).balance);
}
}
/// @notice Enters the Compound market so it can be deposited/borrowed
/// @param _cTokenAddr CToken address of the token
function enterMarket(address _cTokenAddr) public {
address[] memory markets = new address[](1);
markets[0] = _cTokenAddr;
ComptrollerInterface(COMPTROLLER_ADDR).enterMarkets(markets);
}
/// @notice Exits the Compound market so it can't be deposited/borrowed
/// @param _cTokenAddr CToken address of the token
function exitMarket(address _cTokenAddr) public {
ComptrollerInterface(COMPTROLLER_ADDR).exitMarket(_cTokenAddr);
}
/// @notice Approves CToken contract to pull underlying tokens from the DSProxy
/// @param _tokenAddr Token we are trying to approve
/// @param _cTokenAddr Address which will gain the approval
function approveToken(address _tokenAddr, address _cTokenAddr) internal {
if (_tokenAddr != ETH_ADDR) {
ERC20(_tokenAddr).safeApprove(_cTokenAddr, uint(-1));
}
}
}
contract CompoundSafetyRatio is Exponential, DSMath {
// solhint-disable-next-line const-name-snakecase
ComptrollerInterface public constant comp = ComptrollerInterface(0x3d9819210A31b4961b30EF54bE2aeD79B9c9Cd3B);
/// @notice Calcualted the ratio of debt / adjusted collateral
/// @param _user Address of the user
function getSafetyRatio(address _user) public view returns (uint) {
// For each asset the account is in
address[] memory assets = comp.getAssetsIn(_user);
address oracleAddr = comp.oracle();
uint sumCollateral = 0;
uint sumBorrow = 0;
for (uint i = 0; i < assets.length; i++) {
address asset = assets[i];
(, uint cTokenBalance, uint borrowBalance, uint exchangeRateMantissa)
= CTokenInterface(asset).getAccountSnapshot(_user);
Exp memory oraclePrice;
if (cTokenBalance != 0 || borrowBalance != 0) {
oraclePrice = Exp({mantissa: CompoundOracleInterface(oracleAddr).getUnderlyingPrice(asset)});
}
// Sum up collateral in Usd
if (cTokenBalance != 0) {
(, uint collFactorMantissa) = comp.markets(address(asset));
Exp memory collateralFactor = Exp({mantissa: collFactorMantissa});
Exp memory exchangeRate = Exp({mantissa: exchangeRateMantissa});
(, Exp memory tokensToUsd) = mulExp3(collateralFactor, exchangeRate, oraclePrice);
(, sumCollateral) = mulScalarTruncateAddUInt(tokensToUsd, cTokenBalance, sumCollateral);
}
// Sum up debt in Usd
if (borrowBalance != 0) {
(, sumBorrow) = mulScalarTruncateAddUInt(oraclePrice, borrowBalance, sumBorrow);
}
}
if (sumBorrow == 0) return uint(-1);
uint borrowPowerUsed = (sumBorrow * 10**18) / sumCollateral;
return wdiv(1e18, borrowPowerUsed);
}
}
contract CompoundMonitor is AdminAuth, DSMath, CompoundSafetyRatio, GasBurner {
using SafeERC20 for ERC20;
enum Method { Boost, Repay }
uint public REPAY_GAS_TOKEN = 20;
uint public BOOST_GAS_TOKEN = 20;
uint constant public MAX_GAS_PRICE = 500000000000; // 500 gwei
uint public REPAY_GAS_COST = 2000000;
uint public BOOST_GAS_COST = 2000000;
address public constant GAS_TOKEN_INTERFACE_ADDRESS = 0x0000000000b3F879cb30FE243b4Dfee438691c04;
address public constant DEFISAVER_LOGGER = 0x5c55B921f590a89C1Ebe84dF170E655a82b62126;
address public constant BOT_REGISTRY_ADDRESS = 0x637726f8b08a7ABE3aE3aCaB01A80E2d8ddeF77B;
CompoundMonitorProxy public compoundMonitorProxy;
CompoundSubscriptions public subscriptionsContract;
address public compoundFlashLoanTakerAddress;
DefisaverLogger public logger = DefisaverLogger(DEFISAVER_LOGGER);
modifier onlyApproved() {
require(BotRegistry(BOT_REGISTRY_ADDRESS).botList(msg.sender), "Not auth bot");
_;
}
/// @param _compoundMonitorProxy Proxy contracts that actually is authorized to call DSProxy
/// @param _subscriptions Subscriptions contract for Compound positions
/// @param _compoundFlashLoanTaker Contract that actually performs Repay/Boost
constructor(address _compoundMonitorProxy, address _subscriptions, address _compoundFlashLoanTaker) public {
compoundMonitorProxy = CompoundMonitorProxy(_compoundMonitorProxy);
subscriptionsContract = CompoundSubscriptions(_subscriptions);
compoundFlashLoanTakerAddress = _compoundFlashLoanTaker;
}
/// @notice Bots call this method to repay for user when conditions are met
/// @dev If the contract ownes gas token it will try and use it for gas price reduction
/// @param _exData Exchange data
/// @param _cAddresses cTokens addreses and exchange [cCollAddress, cBorrowAddress, exchangeAddress]
/// @param _user The actual address that owns the Compound position
function repayFor(
SaverExchangeCore.ExchangeData memory _exData,
address[2] memory _cAddresses, // cCollAddress, cBorrowAddress
address _user
) public payable onlyApproved burnGas(REPAY_GAS_TOKEN) {
(bool isAllowed, uint ratioBefore) = canCall(Method.Repay, _user);
require(isAllowed); // check if conditions are met
uint256 gasCost = calcGasCost(REPAY_GAS_COST);
compoundMonitorProxy.callExecute{value: msg.value}(
_user,
compoundFlashLoanTakerAddress,
abi.encodeWithSignature(
"repayWithLoan((address,address,uint256,uint256,uint256,address,address,bytes,uint256),address[2],uint256)",
_exData,
_cAddresses,
gasCost
)
);
(bool isGoodRatio, uint ratioAfter) = ratioGoodAfter(Method.Repay, _user);
require(isGoodRatio); // check if the after result of the actions is good
returnEth();
logger.Log(address(this), _user, "AutomaticCompoundRepay", abi.encode(ratioBefore, ratioAfter));
}
/// @notice Bots call this method to boost for user when conditions are met
/// @dev If the contract ownes gas token it will try and use it for gas price reduction
/// @param _exData Exchange data
/// @param _cAddresses cTokens addreses and exchange [cCollAddress, cBorrowAddress, exchangeAddress]
/// @param _user The actual address that owns the Compound position
function boostFor(
SaverExchangeCore.ExchangeData memory _exData,
address[2] memory _cAddresses, // cCollAddress, cBorrowAddress
address _user
) public payable onlyApproved burnGas(BOOST_GAS_TOKEN) {
(bool isAllowed, uint ratioBefore) = canCall(Method.Boost, _user);
require(isAllowed); // check if conditions are met
uint256 gasCost = calcGasCost(BOOST_GAS_COST);
compoundMonitorProxy.callExecute{value: msg.value}(
_user,
compoundFlashLoanTakerAddress,
abi.encodeWithSignature(
"boostWithLoan((address,address,uint256,uint256,uint256,address,address,bytes,uint256),address[2],uint256)",
_exData,
_cAddresses,
gasCost
)
);
(bool isGoodRatio, uint ratioAfter) = ratioGoodAfter(Method.Boost, _user);
require(isGoodRatio); // check if the after result of the actions is good
returnEth();
logger.Log(address(this), _user, "AutomaticCompoundBoost", abi.encode(ratioBefore, ratioAfter));
}
/******************* INTERNAL METHODS ********************************/
function returnEth() internal {
// return if some eth left
if (address(this).balance > 0) {
msg.sender.transfer(address(this).balance);
}
}
/******************* STATIC METHODS ********************************/
/// @notice Checks if Boost/Repay could be triggered for the CDP
/// @dev Called by MCDMonitor to enforce the min/max check
/// @param _method Type of action to be called
/// @param _user The actual address that owns the Compound position
/// @return Boolean if it can be called and the ratio
function canCall(Method _method, address _user) public view returns(bool, uint) {
bool subscribed = subscriptionsContract.isSubscribed(_user);
CompoundSubscriptions.CompoundHolder memory holder = subscriptionsContract.getHolder(_user);
// check if cdp is subscribed
if (!subscribed) return (false, 0);
// check if boost and boost allowed
if (_method == Method.Boost && !holder.boostEnabled) return (false, 0);
uint currRatio = getSafetyRatio(_user);
if (_method == Method.Repay) {
return (currRatio < holder.minRatio, currRatio);
} else if (_method == Method.Boost) {
return (currRatio > holder.maxRatio, currRatio);
}
}
/// @dev After the Boost/Repay check if the ratio doesn't trigger another call
/// @param _method Type of action to be called
/// @param _user The actual address that owns the Compound position
/// @return Boolean if the recent action preformed correctly and the ratio
function ratioGoodAfter(Method _method, address _user) public view returns(bool, uint) {
CompoundSubscriptions.CompoundHolder memory holder;
holder= subscriptionsContract.getHolder(_user);
uint currRatio = getSafetyRatio(_user);
if (_method == Method.Repay) {
return (currRatio < holder.maxRatio, currRatio);
} else if (_method == Method.Boost) {
return (currRatio > holder.minRatio, currRatio);
}
}
/// @notice Calculates gas cost (in Eth) of tx
/// @dev Gas price is limited to MAX_GAS_PRICE to prevent attack of draining user CDP
/// @param _gasAmount Amount of gas used for the tx
function calcGasCost(uint _gasAmount) public view returns (uint) {
uint gasPrice = tx.gasprice <= MAX_GAS_PRICE ? tx.gasprice : MAX_GAS_PRICE;
return mul(gasPrice, _gasAmount);
}
/******************* OWNER ONLY OPERATIONS ********************************/
/// @notice Allows owner to change gas cost for boost operation, but only up to 3 millions
/// @param _gasCost New gas cost for boost method
function changeBoostGasCost(uint _gasCost) public onlyOwner {
require(_gasCost < 3000000);
BOOST_GAS_COST = _gasCost;
}
/// @notice Allows owner to change gas cost for repay operation, but only up to 3 millions
/// @param _gasCost New gas cost for repay method
function changeRepayGasCost(uint _gasCost) public onlyOwner {
require(_gasCost < 3000000);
REPAY_GAS_COST = _gasCost;
}
/// @notice If any tokens gets stuck in the contract owner can withdraw it
/// @param _tokenAddress Address of the ERC20 token
/// @param _to Address of the receiver
/// @param _amount The amount to be sent
function transferERC20(address _tokenAddress, address _to, uint _amount) public onlyOwner {
ERC20(_tokenAddress).safeTransfer(_to, _amount);
}
/// @notice If any Eth gets stuck in the contract owner can withdraw it
/// @param _to Address of the receiver
/// @param _amount The amount to be sent
function transferEth(address payable _to, uint _amount) public onlyOwner {
_to.transfer(_amount);
}
}
contract CompBalance is Exponential, GasBurner {
ComptrollerInterface public constant comp = ComptrollerInterface(0x3d9819210A31b4961b30EF54bE2aeD79B9c9Cd3B);
address public constant COMP_ADDR = 0xc00e94Cb662C3520282E6f5717214004A7f26888;
uint224 public constant compInitialIndex = 1e36;
function claimComp(address _user, address[] memory _cTokensSupply, address[] memory _cTokensBorrow) public burnGas(8) {
_claim(_user, _cTokensSupply, _cTokensBorrow);
ERC20(COMP_ADDR).transfer(msg.sender, ERC20(COMP_ADDR).balanceOf(address(this)));
}
function _claim(address _user, address[] memory _cTokensSupply, address[] memory _cTokensBorrow) internal {
address[] memory u = new address[](1);
u[0] = _user;
comp.claimComp(u, _cTokensSupply, false, true);
comp.claimComp(u, _cTokensBorrow, true, false);
}
function getBalance(address _user, address[] memory _cTokens) public view returns (uint) {
uint compBalance = 0;
for(uint i = 0; i < _cTokens.length; ++i) {
compBalance += getSuppyBalance(_cTokens[i], _user);
compBalance += getBorrowBalance(_cTokens[i], _user);
}
compBalance += ERC20(COMP_ADDR).balanceOf(_user);
return compBalance;
}
function getSuppyBalance(address _cToken, address _supplier) public view returns (uint supplierAccrued) {
ComptrollerInterface.CompMarketState memory supplyState = comp.compSupplyState(_cToken);
Double memory supplyIndex = Double({mantissa: supplyState.index});
Double memory supplierIndex = Double({mantissa: comp.compSupplierIndex(_cToken, _supplier)});
if (supplierIndex.mantissa == 0 && supplyIndex.mantissa > 0) {
supplierIndex.mantissa = compInitialIndex;
}
Double memory deltaIndex = sub_(supplyIndex, supplierIndex);
uint supplierTokens = CTokenInterface(_cToken).balanceOf(_supplier);
uint supplierDelta = mul_(supplierTokens, deltaIndex);
supplierAccrued = add_(comp.compAccrued(_supplier), supplierDelta);
}
function getBorrowBalance(address _cToken, address _borrower) public view returns (uint borrowerAccrued) {
ComptrollerInterface.CompMarketState memory borrowState = comp.compBorrowState(_cToken);
Double memory borrowIndex = Double({mantissa: borrowState.index});
Double memory borrowerIndex = Double({mantissa: comp.compBorrowerIndex(_cToken, _borrower)});
Exp memory marketBorrowIndex = Exp({mantissa: CTokenInterface(_cToken).borrowIndex()});
if (borrowerIndex.mantissa > 0) {
Double memory deltaIndex = sub_(borrowIndex, borrowerIndex);
uint borrowerAmount = div_(CTokenInterface(_cToken).borrowBalanceStored(_borrower), marketBorrowIndex);
uint borrowerDelta = mul_(borrowerAmount, deltaIndex);
borrowerAccrued = add_(comp.compAccrued(_borrower), borrowerDelta);
}
}
}
contract CompoundSaverHelper is DSMath, Exponential {
using SafeERC20 for ERC20;
address payable public constant WALLET_ADDR = 0x322d58b9E75a6918f7e7849AEe0fF09369977e08;
address public constant DISCOUNT_ADDR = 0x1b14E8D511c9A4395425314f849bD737BAF8208F;
uint public constant MANUAL_SERVICE_FEE = 400; // 0.25% Fee
uint public constant AUTOMATIC_SERVICE_FEE = 333; // 0.3% Fee
address public constant ETH_ADDRESS = 0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE;
address public constant CETH_ADDRESS = 0x4Ddc2D193948926D02f9B1fE9e1daa0718270ED5;
address public constant COMPTROLLER = 0x3d9819210A31b4961b30EF54bE2aeD79B9c9Cd3B;
address public constant COMPOUND_LOGGER = 0x3DD0CDf5fFA28C6847B4B276e2fD256046a44bb7;
address public constant BOT_REGISTRY_ADDRESS = 0x637726f8b08a7ABE3aE3aCaB01A80E2d8ddeF77B;
/// @notice Helper method to payback the Compound debt
/// @dev If amount is bigger it will repay the whole debt and send the extra to the _user
/// @param _amount Amount of tokens we want to repay
/// @param _cBorrowToken Ctoken address we are repaying
/// @param _borrowToken Token address we are repaying
/// @param _user Owner of the compound position we are paying back
function paybackDebt(uint _amount, address _cBorrowToken, address _borrowToken, address payable _user) internal {
uint wholeDebt = CTokenInterface(_cBorrowToken).borrowBalanceCurrent(address(this));
if (_amount > wholeDebt) {
if (_borrowToken == ETH_ADDRESS) {
_user.transfer((_amount - wholeDebt));
} else {
ERC20(_borrowToken).safeTransfer(_user, (_amount - wholeDebt));
}
_amount = wholeDebt;
}
approveCToken(_borrowToken, _cBorrowToken);
if (_borrowToken == ETH_ADDRESS) {
CEtherInterface(_cBorrowToken).repayBorrow{value: _amount}();
} else {
require(CTokenInterface(_cBorrowToken).repayBorrow(_amount) == 0);
}
}
/// @notice Calculates the fee amount
/// @param _amount Amount that is converted
/// @param _user Actuall user addr not DSProxy
/// @param _gasCost Ether amount of gas we are spending for tx
/// @param _cTokenAddr CToken addr. of token we are getting for the fee
/// @return feeAmount The amount we took for the fee
function getFee(uint _amount, address _user, uint _gasCost, address _cTokenAddr) internal returns (uint feeAmount) {
uint fee = MANUAL_SERVICE_FEE;
if (BotRegistry(BOT_REGISTRY_ADDRESS).botList(tx.origin)) {
fee = AUTOMATIC_SERVICE_FEE;
}
address tokenAddr = getUnderlyingAddr(_cTokenAddr);
if (Discount(DISCOUNT_ADDR).isCustomFeeSet(_user)) {
fee = Discount(DISCOUNT_ADDR).getCustomServiceFee(_user);
}
feeAmount = (fee == 0) ? 0 : (_amount / fee);
if (_gasCost != 0) {
address oracle = ComptrollerInterface(COMPTROLLER).oracle();
uint usdTokenPrice = CompoundOracleInterface(oracle).getUnderlyingPrice(_cTokenAddr);
uint ethPrice = CompoundOracleInterface(oracle).getUnderlyingPrice(CETH_ADDRESS);
uint tokenPriceInEth = wdiv(usdTokenPrice, ethPrice);
_gasCost = wdiv(_gasCost, tokenPriceInEth);
feeAmount = add(feeAmount, _gasCost);
}
// fee can't go over 20% of the whole amount
if (feeAmount > (_amount / 5)) {
feeAmount = _amount / 5;
}
if (tokenAddr == ETH_ADDRESS) {
WALLET_ADDR.transfer(feeAmount);
} else {
ERC20(tokenAddr).safeTransfer(WALLET_ADDR, feeAmount);
}
}
/// @notice Calculates the gas cost of transaction and send it to wallet
/// @param _amount Amount that is converted
/// @param _gasCost Ether amount of gas we are spending for tx
/// @param _cTokenAddr CToken addr. of token we are getting for the fee
/// @return feeAmount The amount we took for the fee
function getGasCost(uint _amount, uint _gasCost, address _cTokenAddr) internal returns (uint feeAmount) {
address tokenAddr = getUnderlyingAddr(_cTokenAddr);
if (_gasCost != 0) {
address oracle = ComptrollerInterface(COMPTROLLER).oracle();
uint usdTokenPrice = CompoundOracleInterface(oracle).getUnderlyingPrice(_cTokenAddr);
uint ethPrice = CompoundOracleInterface(oracle).getUnderlyingPrice(CETH_ADDRESS);
uint tokenPriceInEth = wdiv(usdTokenPrice, ethPrice);
feeAmount = wdiv(_gasCost, tokenPriceInEth);
}
// fee can't go over 20% of the whole amount
if (feeAmount > (_amount / 5)) {
feeAmount = _amount / 5;
}
if (tokenAddr == ETH_ADDRESS) {
WALLET_ADDR.transfer(feeAmount);
} else {
ERC20(tokenAddr).safeTransfer(WALLET_ADDR, feeAmount);
}
}
/// @notice Enters the market for the collatera and borrow tokens
/// @param _cTokenAddrColl Collateral address we are entering the market in
/// @param _cTokenAddrBorrow Borrow address we are entering the market in
function enterMarket(address _cTokenAddrColl, address _cTokenAddrBorrow) internal {
address[] memory markets = new address[](2);
markets[0] = _cTokenAddrColl;
markets[1] = _cTokenAddrBorrow;
ComptrollerInterface(COMPTROLLER).enterMarkets(markets);
}
/// @notice Approves CToken contract to pull underlying tokens from the DSProxy
/// @param _tokenAddr Token we are trying to approve
/// @param _cTokenAddr Address which will gain the approval
function approveCToken(address _tokenAddr, address _cTokenAddr) internal {
if (_tokenAddr != ETH_ADDRESS) {
ERC20(_tokenAddr).safeApprove(_cTokenAddr, uint(-1));
}
}
/// @notice Returns the underlying address of the cToken asset
/// @param _cTokenAddress cToken address
/// @return Token address of the cToken specified
function getUnderlyingAddr(address _cTokenAddress) internal returns (address) {
if (_cTokenAddress == CETH_ADDRESS) {
return ETH_ADDRESS;
} else {
return CTokenInterface(_cTokenAddress).underlying();
}
}
/// @notice Returns the owner of the DSProxy that called the contract
function getUserAddress() internal view returns (address) {
DSProxy proxy = DSProxy(uint160(address(this)));
return proxy.owner();
}
/// @notice Returns the maximum amount of collateral available to withdraw
/// @dev Due to rounding errors the result is - 1% wei from the exact amount
/// @param _cCollAddress Collateral we are getting the max value of
/// @param _account Users account
/// @return Returns the max. collateral amount in that token
function getMaxCollateral(address _cCollAddress, address _account) public returns (uint) {
(, uint liquidityInUsd, ) = ComptrollerInterface(COMPTROLLER).getAccountLiquidity(_account);
uint usersBalance = CTokenInterface(_cCollAddress).balanceOfUnderlying(_account);
address oracle = ComptrollerInterface(COMPTROLLER).oracle();
if (liquidityInUsd == 0) return usersBalance;
CTokenInterface(_cCollAddress).accrueInterest();
(, uint collFactorMantissa) = ComptrollerInterface(COMPTROLLER).markets(_cCollAddress);
Exp memory collateralFactor = Exp({mantissa: collFactorMantissa});
(, uint tokensToUsd) = divScalarByExpTruncate(liquidityInUsd, collateralFactor);
uint usdPrice = CompoundOracleInterface(oracle).getUnderlyingPrice(_cCollAddress);
uint liqInToken = wdiv(tokensToUsd, usdPrice);
if (liqInToken > usersBalance) return usersBalance;
return sub(liqInToken, (liqInToken / 100)); // cut off 1% due to rounding issues
}
/// @notice Returns the maximum amount of borrow amount available
/// @dev Due to rounding errors the result is - 1% wei from the exact amount
/// @param _cBorrowAddress Borrow token we are getting the max value of
/// @param _account Users account
/// @return Returns the max. borrow amount in that token
function getMaxBorrow(address _cBorrowAddress, address _account) public returns (uint) {
(, uint liquidityInUsd, ) = ComptrollerInterface(COMPTROLLER).getAccountLiquidity(_account);
address oracle = ComptrollerInterface(COMPTROLLER).oracle();
CTokenInterface(_cBorrowAddress).accrueInterest();
uint usdPrice = CompoundOracleInterface(oracle).getUnderlyingPrice(_cBorrowAddress);
uint liquidityInToken = wdiv(liquidityInUsd, usdPrice);
return sub(liquidityInToken, (liquidityInToken / 100)); // cut off 1% due to rounding issues
}
}
contract CompoundImportFlashLoan is FlashLoanReceiverBase {
using SafeERC20 for ERC20;
ILendingPoolAddressesProvider public LENDING_POOL_ADDRESS_PROVIDER = ILendingPoolAddressesProvider(0x24a42fD28C976A61Df5D00D0599C34c4f90748c8);
address public constant COMPOUND_BORROW_PROXY = 0xb7EDC39bE76107e2Cc645f0f6a3D164f5e173Ee2;
address public owner;
constructor()
FlashLoanReceiverBase(LENDING_POOL_ADDRESS_PROVIDER)
public {
owner = msg.sender;
}
/// @notice Called by Aave when sending back the FL amount
/// @param _reserve The address of the borrowed token
/// @param _amount Amount of FL tokens received
/// @param _fee FL Aave fee
/// @param _params The params that are sent from the original FL caller contract
function executeOperation(
address _reserve,
uint256 _amount,
uint256 _fee,
bytes calldata _params)
external override {
(
address cCollateralToken,
address cBorrowToken,
address user,
address proxy
)
= abi.decode(_params, (address,address,address,address));
// approve FL tokens so we can repay them
ERC20(_reserve).safeApprove(cBorrowToken, 0);
ERC20(_reserve).safeApprove(cBorrowToken, uint(-1));
// repay compound debt
require(CTokenInterface(cBorrowToken).repayBorrowBehalf(user, uint(-1)) == 0, "Repay borrow behalf fail");
// transfer cTokens to proxy
uint cTokenBalance = CTokenInterface(cCollateralToken).balanceOf(user);
require(CTokenInterface(cCollateralToken).transferFrom(user, proxy, cTokenBalance));
// borrow
bytes memory proxyData = getProxyData(cCollateralToken, cBorrowToken, _reserve, (_amount + _fee));
DSProxyInterface(proxy).execute(COMPOUND_BORROW_PROXY, proxyData);
// Repay the loan with the money DSProxy sent back
transferFundsBackToPoolInternal(_reserve, _amount.add(_fee));
}
/// @notice Formats function data call so we can call it through DSProxy
/// @param _cCollToken CToken address of collateral
/// @param _cBorrowToken CToken address we will borrow
/// @param _borrowToken Token address we will borrow
/// @param _amount Amount that will be borrowed
/// @return proxyData Formated function call data
function getProxyData(address _cCollToken, address _cBorrowToken, address _borrowToken, uint _amount) internal pure returns (bytes memory proxyData) {
proxyData = abi.encodeWithSignature(
"borrow(address,address,address,uint256)",
_cCollToken, _cBorrowToken, _borrowToken, _amount);
}
function withdrawStuckFunds(address _tokenAddr, uint _amount) public {
require(owner == msg.sender, "Must be owner");
if (_tokenAddr == 0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE) {
msg.sender.transfer(_amount);
} else {
ERC20(_tokenAddr).safeTransfer(owner, _amount);
}
}
}
contract CompoundImportTaker is CompoundSaverHelper, ProxyPermission, GasBurner {
ILendingPool public constant lendingPool = ILendingPool(0x398eC7346DcD622eDc5ae82352F02bE94C62d119);
address payable public constant COMPOUND_IMPORT_FLASH_LOAN = 0xaf9f8781A4c39Ce2122019fC05F22e3a662B0A32;
address public constant PROXY_REGISTRY_ADDRESS = 0x4678f0a6958e4D2Bc4F1BAF7Bc52E8F3564f3fE4;
DefisaverLogger public constant logger = DefisaverLogger(0x5c55B921f590a89C1Ebe84dF170E655a82b62126);
/// @notice Starts the process to move users position 1 collateral and 1 borrow
/// @dev User must approve COMPOUND_IMPORT_FLASH_LOAN to pull _cCollateralToken
/// @param _cCollateralToken Collateral we are moving to DSProxy
/// @param _cBorrowToken Borrow token we are moving to DSProxy
function importLoan(address _cCollateralToken, address _cBorrowToken) external burnGas(20) {
address proxy = getProxy();
uint loanAmount = CTokenInterface(_cBorrowToken).borrowBalanceCurrent(msg.sender);
bytes memory paramsData = abi.encode(_cCollateralToken, _cBorrowToken, msg.sender, proxy);
givePermission(COMPOUND_IMPORT_FLASH_LOAN);
lendingPool.flashLoan(COMPOUND_IMPORT_FLASH_LOAN, getUnderlyingAddr(_cBorrowToken), loanAmount, paramsData);
removePermission(COMPOUND_IMPORT_FLASH_LOAN);
logger.Log(address(this), msg.sender, "CompoundImport", abi.encode(loanAmount, 0, _cCollateralToken));
}
/// @notice Gets proxy address, if user doesn't has DSProxy build it
/// @return proxy DsProxy address
function getProxy() internal returns (address proxy) {
proxy = ProxyRegistryInterface(PROXY_REGISTRY_ADDRESS).proxies(msg.sender);
if (proxy == address(0)) {
proxy = ProxyRegistryInterface(PROXY_REGISTRY_ADDRESS).build(msg.sender);
}
}
}
contract CreamBasicProxy is GasBurner {
address public constant ETH_ADDR = 0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE;
address public constant COMPTROLLER_ADDR = 0x3d5BC3c8d13dcB8bF317092d84783c2697AE9258;
using SafeERC20 for ERC20;
/// @notice User deposits tokens to the cream protocol
/// @dev User needs to approve the DSProxy to pull the _tokenAddr tokens
/// @param _tokenAddr The address of the token to be deposited
/// @param _cTokenAddr CTokens to be deposited
/// @param _amount Amount of tokens to be deposited
/// @param _inMarket True if the token is already in market for that address
function deposit(address _tokenAddr, address _cTokenAddr, uint _amount, bool _inMarket) public burnGas(5) payable {
if (_tokenAddr != ETH_ADDR) {
ERC20(_tokenAddr).safeTransferFrom(msg.sender, address(this), _amount);
}
approveToken(_tokenAddr, _cTokenAddr);
if (!_inMarket) {
enterMarket(_cTokenAddr);
}
if (_tokenAddr != ETH_ADDR) {
require(CTokenInterface(_cTokenAddr).mint(_amount) == 0);
} else {
CEtherInterface(_cTokenAddr).mint{value: msg.value}(); // reverts on fail
}
}
/// @notice User withdraws tokens to the cream protocol
/// @param _tokenAddr The address of the token to be withdrawn
/// @param _cTokenAddr CTokens to be withdrawn
/// @param _amount Amount of tokens to be withdrawn
/// @param _isCAmount If true _amount is cTokens if falls _amount is underlying tokens
function withdraw(address _tokenAddr, address _cTokenAddr, uint _amount, bool _isCAmount) public burnGas(5) {
if (_isCAmount) {
require(CTokenInterface(_cTokenAddr).redeem(_amount) == 0);
} else {
require(CTokenInterface(_cTokenAddr).redeemUnderlying(_amount) == 0);
}
// withdraw funds to msg.sender
if (_tokenAddr != ETH_ADDR) {
ERC20(_tokenAddr).safeTransfer(msg.sender, ERC20(_tokenAddr).balanceOf(address(this)));
} else {
msg.sender.transfer(address(this).balance);
}
}
/// @notice User borrows tokens to the cream protocol
/// @param _tokenAddr The address of the token to be borrowed
/// @param _cTokenAddr CTokens to be borrowed
/// @param _amount Amount of tokens to be borrowed
/// @param _inMarket True if the token is already in market for that address
function borrow(address _tokenAddr, address _cTokenAddr, uint _amount, bool _inMarket) public burnGas(8) {
if (!_inMarket) {
enterMarket(_cTokenAddr);
}
require(CTokenInterface(_cTokenAddr).borrow(_amount) == 0);
// withdraw funds to msg.sender
if (_tokenAddr != ETH_ADDR) {
ERC20(_tokenAddr).safeTransfer(msg.sender, ERC20(_tokenAddr).balanceOf(address(this)));
} else {
msg.sender.transfer(address(this).balance);
}
}
/// @dev User needs to approve the DSProxy to pull the _tokenAddr tokens
/// @notice User paybacks tokens to the cream protocol
/// @param _tokenAddr The address of the token to be paybacked
/// @param _cTokenAddr CTokens to be paybacked
/// @param _amount Amount of tokens to be payedback
/// @param _wholeDebt If true the _amount will be set to the whole amount of the debt
function payback(address _tokenAddr, address _cTokenAddr, uint _amount, bool _wholeDebt) public burnGas(5) payable {
approveToken(_tokenAddr, _cTokenAddr);
if (_wholeDebt) {
_amount = CTokenInterface(_cTokenAddr).borrowBalanceCurrent(address(this));
}
if (_tokenAddr != ETH_ADDR) {
ERC20(_tokenAddr).safeTransferFrom(msg.sender, address(this), _amount);
require(CTokenInterface(_cTokenAddr).repayBorrow(_amount) == 0);
} else {
CEtherInterface(_cTokenAddr).repayBorrow{value: msg.value}();
msg.sender.transfer(address(this).balance); // send back the extra eth
}
}
/// @notice Helper method to withdraw tokens from the DSProxy
/// @param _tokenAddr Address of the token to be withdrawn
function withdrawTokens(address _tokenAddr) public {
if (_tokenAddr != ETH_ADDR) {
ERC20(_tokenAddr).safeTransfer(msg.sender, ERC20(_tokenAddr).balanceOf(address(this)));
} else {
msg.sender.transfer(address(this).balance);
}
}
/// @notice Enters the cream market so it can be deposited/borrowed
/// @param _cTokenAddr CToken address of the token
function enterMarket(address _cTokenAddr) public {
address[] memory markets = new address[](1);
markets[0] = _cTokenAddr;
ComptrollerInterface(COMPTROLLER_ADDR).enterMarkets(markets);
}
/// @notice Exits the cream market so it can't be deposited/borrowed
/// @param _cTokenAddr CToken address of the token
function exitMarket(address _cTokenAddr) public {
ComptrollerInterface(COMPTROLLER_ADDR).exitMarket(_cTokenAddr);
}
/// @notice Approves CToken contract to pull underlying tokens from the DSProxy
/// @param _tokenAddr Token we are trying to approve
/// @param _cTokenAddr Address which will gain the approval
function approveToken(address _tokenAddr, address _cTokenAddr) internal {
if (_tokenAddr != ETH_ADDR) {
ERC20(_tokenAddr).safeApprove(_cTokenAddr, uint(-1));
}
}
}
contract CreamLoanInfo is CreamSafetyRatio {
struct LoanData {
address user;
uint128 ratio;
address[] collAddr;
address[] borrowAddr;
uint[] collAmounts;
uint[] borrowAmounts;
}
struct TokenInfo {
address cTokenAddress;
address underlyingTokenAddress;
uint collateralFactor;
uint price;
}
struct TokenInfoFull {
address underlyingTokenAddress;
uint supplyRate;
uint borrowRate;
uint exchangeRate;
uint marketLiquidity;
uint totalSupply;
uint totalBorrow;
uint collateralFactor;
uint price;
}
address public constant ETH_ADDRESS = 0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE;
address public constant CETH_ADDRESS = 0xD06527D5e56A3495252A528C4987003b712860eE;
/// @notice Calcualted the ratio of coll/debt for a cream user
/// @param _user Address of the user
function getRatio(address _user) public view returns (uint) {
// For each asset the account is in
return getSafetyRatio(_user);
}
/// @notice Fetches cream prices for tokens
/// @param _cTokens Arr. of cTokens for which to get the prices
/// @return prices Array of prices
function getPrices(address[] memory _cTokens) public view returns (uint[] memory prices) {
prices = new uint[](_cTokens.length);
address oracleAddr = comp.oracle();
for (uint i = 0; i < _cTokens.length; ++i) {
prices[i] = CompoundOracleInterface(oracleAddr).getUnderlyingPrice(_cTokens[i]);
}
}
/// @notice Fetches cream collateral factors for tokens
/// @param _cTokens Arr. of cTokens for which to get the coll. factors
/// @return collFactors Array of coll. factors
function getCollFactors(address[] memory _cTokens) public view returns (uint[] memory collFactors) {
collFactors = new uint[](_cTokens.length);
for (uint i = 0; i < _cTokens.length; ++i) {
(, collFactors[i]) = comp.markets(_cTokens[i]);
}
}
/// @notice Fetches all the collateral/debt address and amounts, denominated in eth
/// @param _user Address of the user
/// @return data LoanData information
function getLoanData(address _user) public view returns (LoanData memory data) {
address[] memory assets = comp.getAssetsIn(_user);
address oracleAddr = comp.oracle();
data = LoanData({
user: _user,
ratio: 0,
collAddr: new address[](assets.length),
borrowAddr: new address[](assets.length),
collAmounts: new uint[](assets.length),
borrowAmounts: new uint[](assets.length)
});
uint collPos = 0;
uint borrowPos = 0;
for (uint i = 0; i < assets.length; i++) {
address asset = assets[i];
(, uint cTokenBalance, uint borrowBalance, uint exchangeRateMantissa)
= CTokenInterface(asset).getAccountSnapshot(_user);
Exp memory oraclePrice;
if (cTokenBalance != 0 || borrowBalance != 0) {
oraclePrice = Exp({mantissa: CompoundOracleInterface(oracleAddr).getUnderlyingPrice(asset)});
}
// Sum up collateral in eth
if (cTokenBalance != 0) {
Exp memory exchangeRate = Exp({mantissa: exchangeRateMantissa});
(, Exp memory tokensToEth) = mulExp(exchangeRate, oraclePrice);
data.collAddr[collPos] = asset;
(, data.collAmounts[collPos]) = mulScalarTruncate(tokensToEth, cTokenBalance);
collPos++;
}
// Sum up debt in eth
if (borrowBalance != 0) {
data.borrowAddr[borrowPos] = asset;
(, data.borrowAmounts[borrowPos]) = mulScalarTruncate(oraclePrice, borrowBalance);
borrowPos++;
}
}
data.ratio = uint128(getSafetyRatio(_user));
return data;
}
function getTokenBalances(address _user, address[] memory _cTokens) public view returns (uint[] memory balances, uint[] memory borrows) {
balances = new uint[](_cTokens.length);
borrows = new uint[](_cTokens.length);
for (uint i = 0; i < _cTokens.length; i++) {
address asset = _cTokens[i];
(, uint cTokenBalance, uint borrowBalance, uint exchangeRateMantissa)
= CTokenInterface(asset).getAccountSnapshot(_user);
Exp memory exchangeRate = Exp({mantissa: exchangeRateMantissa});
(, balances[i]) = mulScalarTruncate(exchangeRate, cTokenBalance);
borrows[i] = borrowBalance;
}
}
/// @notice Fetches all the collateral/debt address and amounts, denominated in eth
/// @param _users Addresses of the user
/// @return loans Array of LoanData information
function getLoanDataArr(address[] memory _users) public view returns (LoanData[] memory loans) {
loans = new LoanData[](_users.length);
for (uint i = 0; i < _users.length; ++i) {
loans[i] = getLoanData(_users[i]);
}
}
/// @notice Calcualted the ratio of coll/debt for a cream user
/// @param _users Addresses of the user
/// @return ratios Array of ratios
function getRatios(address[] memory _users) public view returns (uint[] memory ratios) {
ratios = new uint[](_users.length);
for (uint i = 0; i < _users.length; ++i) {
ratios[i] = getSafetyRatio(_users[i]);
}
}
/// @notice Information about cTokens
/// @param _cTokenAddresses Array of cTokens addresses
/// @return tokens Array of cTokens infomartion
function getTokensInfo(address[] memory _cTokenAddresses) public returns(TokenInfo[] memory tokens) {
tokens = new TokenInfo[](_cTokenAddresses.length);
address oracleAddr = comp.oracle();
for (uint i = 0; i < _cTokenAddresses.length; ++i) {
(, uint collFactor) = comp.markets(_cTokenAddresses[i]);
tokens[i] = TokenInfo({
cTokenAddress: _cTokenAddresses[i],
underlyingTokenAddress: getUnderlyingAddr(_cTokenAddresses[i]),
collateralFactor: collFactor,
price: CompoundOracleInterface(oracleAddr).getUnderlyingPrice(_cTokenAddresses[i])
});
}
}
/// @notice Information about cTokens
/// @param _cTokenAddresses Array of cTokens addresses
/// @return tokens Array of cTokens infomartion
function getFullTokensInfo(address[] memory _cTokenAddresses) public returns(TokenInfoFull[] memory tokens) {
tokens = new TokenInfoFull[](_cTokenAddresses.length);
address oracleAddr = comp.oracle();
for (uint i = 0; i < _cTokenAddresses.length; ++i) {
(, uint collFactor) = comp.markets(_cTokenAddresses[i]);
CTokenInterface cToken = CTokenInterface(_cTokenAddresses[i]);
tokens[i] = TokenInfoFull({
underlyingTokenAddress: getUnderlyingAddr(_cTokenAddresses[i]),
supplyRate: cToken.supplyRatePerBlock(),
borrowRate: cToken.borrowRatePerBlock(),
exchangeRate: cToken.exchangeRateCurrent(),
marketLiquidity: cToken.getCash(),
totalSupply: cToken.totalSupply(),
totalBorrow: cToken.totalBorrowsCurrent(),
collateralFactor: collFactor,
price: CompoundOracleInterface(oracleAddr).getUnderlyingPrice(_cTokenAddresses[i])
});
}
}
/// @notice Returns the underlying address of the cToken asset
/// @param _cTokenAddress cToken address
/// @return Token address of the cToken specified
function getUnderlyingAddr(address _cTokenAddress) internal returns (address) {
if (_cTokenAddress == CETH_ADDRESS) {
return ETH_ADDRESS;
} else {
return CTokenInterface(_cTokenAddress).underlying();
}
}
}
contract CreamImportFlashLoan is FlashLoanReceiverBase {
using SafeERC20 for ERC20;
ILendingPoolAddressesProvider public LENDING_POOL_ADDRESS_PROVIDER = ILendingPoolAddressesProvider(0x24a42fD28C976A61Df5D00D0599C34c4f90748c8);
address public constant CREAM_BORROW_PROXY = 0x87F198Ef6116CdBC5f36B581d212ad950b7e2Ddd;
address public owner;
constructor()
FlashLoanReceiverBase(LENDING_POOL_ADDRESS_PROVIDER)
public {
owner = msg.sender;
}
/// @notice Called by Aave when sending back the FL amount
/// @param _reserve The address of the borrowed token
/// @param _amount Amount of FL tokens received
/// @param _fee FL Aave fee
/// @param _params The params that are sent from the original FL caller contract
function executeOperation(
address _reserve,
uint256 _amount,
uint256 _fee,
bytes calldata _params)
external override {
(
address cCollateralToken,
address cBorrowToken,
address user,
address proxy
)
= abi.decode(_params, (address,address,address,address));
// approve FL tokens so we can repay them
ERC20(_reserve).safeApprove(cBorrowToken, uint(-1));
// repay cream debt
require(CTokenInterface(cBorrowToken).repayBorrowBehalf(user, uint(-1)) == 0, "Repay borrow behalf fail");
// transfer cTokens to proxy
uint cTokenBalance = CTokenInterface(cCollateralToken).balanceOf(user);
require(CTokenInterface(cCollateralToken).transferFrom(user, proxy, cTokenBalance));
// borrow
bytes memory proxyData = getProxyData(cCollateralToken, cBorrowToken, _reserve, (_amount + _fee));
DSProxyInterface(proxy).execute(CREAM_BORROW_PROXY, proxyData);
// Repay the loan with the money DSProxy sent back
transferFundsBackToPoolInternal(_reserve, _amount.add(_fee));
}
/// @notice Formats function data call so we can call it through DSProxy
/// @param _cCollToken CToken address of collateral
/// @param _cBorrowToken CToken address we will borrow
/// @param _borrowToken Token address we will borrow
/// @param _amount Amount that will be borrowed
/// @return proxyData Formated function call data
function getProxyData(address _cCollToken, address _cBorrowToken, address _borrowToken, uint _amount) internal pure returns (bytes memory proxyData) {
proxyData = abi.encodeWithSignature(
"borrow(address,address,address,uint256)",
_cCollToken, _cBorrowToken, _borrowToken, _amount);
}
function withdrawStuckFunds(address _tokenAddr, uint _amount) public {
require(owner == msg.sender, "Must be owner");
if (_tokenAddr == 0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE) {
msg.sender.transfer(_amount);
} else {
ERC20(_tokenAddr).safeTransfer(owner, _amount);
}
}
}
contract CreamImportTaker is CreamSaverHelper, ProxyPermission, GasBurner {
ILendingPool public constant lendingPool = ILendingPool(0x398eC7346DcD622eDc5ae82352F02bE94C62d119);
address payable public constant CREAM_IMPORT_FLASH_LOAN = 0x24F4aC0Fe758c45cf8425D8Fbdd608cca9A7dBf8;
address public constant PROXY_REGISTRY_ADDRESS = 0x4678f0a6958e4D2Bc4F1BAF7Bc52E8F3564f3fE4;
DefisaverLogger public constant logger = DefisaverLogger(0x5c55B921f590a89C1Ebe84dF170E655a82b62126);
/// @notice Starts the process to move users position 1 collateral and 1 borrow
/// @dev User must approve cream_IMPORT_FLASH_LOAN to pull _cCollateralToken
/// @param _cCollateralToken Collateral we are moving to DSProxy
/// @param _cBorrowToken Borrow token we are moving to DSProxy
function importLoan(address _cCollateralToken, address _cBorrowToken) external burnGas(20) {
address proxy = getProxy();
uint loanAmount = CTokenInterface(_cBorrowToken).borrowBalanceCurrent(msg.sender);
bytes memory paramsData = abi.encode(_cCollateralToken, _cBorrowToken, msg.sender, proxy);
givePermission(CREAM_IMPORT_FLASH_LOAN);
lendingPool.flashLoan(CREAM_IMPORT_FLASH_LOAN, getUnderlyingAddr(_cBorrowToken), loanAmount, paramsData);
removePermission(CREAM_IMPORT_FLASH_LOAN);
logger.Log(address(this), msg.sender, "CreamImport", abi.encode(loanAmount, 0, _cCollateralToken));
}
/// @notice Gets proxy address, if user doesn't has DSProxy build it
/// @return proxy DsProxy address
function getProxy() internal returns (address proxy) {
proxy = ProxyRegistryInterface(PROXY_REGISTRY_ADDRESS).proxies(msg.sender);
if (proxy == address(0)) {
proxy = ProxyRegistryInterface(PROXY_REGISTRY_ADDRESS).build(msg.sender);
}
}
}
contract SaverExchangeCore is SaverExchangeHelper, DSMath {
// first is empty to keep the legacy order in place
enum ExchangeType { _, OASIS, KYBER, UNISWAP, ZEROX }
enum ActionType { SELL, BUY }
struct ExchangeData {
address srcAddr;
address destAddr;
uint srcAmount;
uint destAmount;
uint minPrice;
address wrapper;
address exchangeAddr;
bytes callData;
uint256 price0x;
}
/// @notice Internal method that preforms a sell on 0x/on-chain
/// @dev Usefull for other DFS contract to integrate for exchanging
/// @param exData Exchange data struct
/// @return (address, uint) Address of the wrapper used and destAmount
function _sell(ExchangeData memory exData) internal returns (address, uint) {
address wrapper;
uint swapedTokens;
bool success;
uint tokensLeft = exData.srcAmount;
// if selling eth, convert to weth
if (exData.srcAddr == KYBER_ETH_ADDRESS) {
exData.srcAddr = ethToWethAddr(exData.srcAddr);
TokenInterface(WETH_ADDRESS).deposit.value(exData.srcAmount)();
}
// Try 0x first and then fallback on specific wrapper
if (exData.price0x > 0) {
approve0xProxy(exData.srcAddr, exData.srcAmount);
uint ethAmount = getProtocolFee(exData.srcAddr, exData.srcAmount);
(success, swapedTokens, tokensLeft) = takeOrder(exData, ethAmount, ActionType.SELL);
if (success) {
wrapper = exData.exchangeAddr;
}
}
// fallback to desired wrapper if 0x failed
if (!success) {
swapedTokens = saverSwap(exData, ActionType.SELL);
wrapper = exData.wrapper;
}
require(getBalance(exData.destAddr) >= wmul(exData.minPrice, exData.srcAmount), "Final amount isn't correct");
// if anything is left in weth, pull it to user as eth
if (getBalance(WETH_ADDRESS) > 0) {
TokenInterface(WETH_ADDRESS).withdraw(
TokenInterface(WETH_ADDRESS).balanceOf(address(this))
);
}
return (wrapper, swapedTokens);
}
/// @notice Internal method that preforms a buy on 0x/on-chain
/// @dev Usefull for other DFS contract to integrate for exchanging
/// @param exData Exchange data struct
/// @return (address, uint) Address of the wrapper used and srcAmount
function _buy(ExchangeData memory exData) internal returns (address, uint) {
address wrapper;
uint swapedTokens;
bool success;
require(exData.destAmount != 0, "Dest amount must be specified");
// if selling eth, convert to weth
if (exData.srcAddr == KYBER_ETH_ADDRESS) {
exData.srcAddr = ethToWethAddr(exData.srcAddr);
TokenInterface(WETH_ADDRESS).deposit.value(exData.srcAmount)();
}
if (exData.price0x > 0) {
approve0xProxy(exData.srcAddr, exData.srcAmount);
uint ethAmount = getProtocolFee(exData.srcAddr, exData.srcAmount);
(success, swapedTokens,) = takeOrder(exData, ethAmount, ActionType.BUY);
if (success) {
wrapper = exData.exchangeAddr;
}
}
// fallback to desired wrapper if 0x failed
if (!success) {
swapedTokens = saverSwap(exData, ActionType.BUY);
wrapper = exData.wrapper;
}
require(getBalance(exData.destAddr) >= exData.destAmount, "Final amount isn't correct");
// if anything is left in weth, pull it to user as eth
if (getBalance(WETH_ADDRESS) > 0) {
TokenInterface(WETH_ADDRESS).withdraw(
TokenInterface(WETH_ADDRESS).balanceOf(address(this))
);
}
return (wrapper, getBalance(exData.destAddr));
}
/// @notice Takes order from 0x and returns bool indicating if it is successful
/// @param _exData Exchange data
/// @param _ethAmount Ether fee needed for 0x order
function takeOrder(
ExchangeData memory _exData,
uint256 _ethAmount,
ActionType _type
) private returns (bool success, uint256, uint256) {
// write in the exact amount we are selling/buing in an order
if (_type == ActionType.SELL) {
writeUint256(_exData.callData, 36, _exData.srcAmount);
} else {
writeUint256(_exData.callData, 36, _exData.destAmount);
}
if (ZrxAllowlist(ZRX_ALLOWLIST_ADDR).isNonPayableAddr(_exData.exchangeAddr)) {
_ethAmount = 0;
}
uint256 tokensBefore = getBalance(_exData.destAddr);
if (ZrxAllowlist(ZRX_ALLOWLIST_ADDR).isZrxAddr(_exData.exchangeAddr)) {
(success, ) = _exData.exchangeAddr.call{value: _ethAmount}(_exData.callData);
} else {
success = false;
}
uint256 tokensSwaped = 0;
uint256 tokensLeft = _exData.srcAmount;
if (success) {
// check to see if any _src tokens are left over after exchange
tokensLeft = getBalance(_exData.srcAddr);
// convert weth -> eth if needed
if (_exData.destAddr == KYBER_ETH_ADDRESS) {
TokenInterface(WETH_ADDRESS).withdraw(
TokenInterface(WETH_ADDRESS).balanceOf(address(this))
);
}
// get the current balance of the swaped tokens
tokensSwaped = getBalance(_exData.destAddr) - tokensBefore;
}
return (success, tokensSwaped, tokensLeft);
}
/// @notice Calls wraper contract for exchage to preform an on-chain swap
/// @param _exData Exchange data struct
/// @param _type Type of action SELL|BUY
/// @return swapedTokens For Sell that the destAmount, for Buy thats the srcAmount
function saverSwap(ExchangeData memory _exData, ActionType _type) internal returns (uint swapedTokens) {
require(SaverExchangeRegistry(SAVER_EXCHANGE_REGISTRY).isWrapper(_exData.wrapper), "Wrapper is not valid");
uint ethValue = 0;
ERC20(_exData.srcAddr).safeTransfer(_exData.wrapper, _exData.srcAmount);
if (_type == ActionType.SELL) {
swapedTokens = ExchangeInterfaceV2(_exData.wrapper).
sell{value: ethValue}(_exData.srcAddr, _exData.destAddr, _exData.srcAmount);
} else {
swapedTokens = ExchangeInterfaceV2(_exData.wrapper).
buy{value: ethValue}(_exData.srcAddr, _exData.destAddr, _exData.destAmount);
}
}
function writeUint256(bytes memory _b, uint256 _index, uint _input) internal pure {
if (_b.length < _index + 32) {
revert("Incorrent lengt while writting bytes32");
}
bytes32 input = bytes32(_input);
_index += 32;
// Read the bytes32 from array memory
assembly {
mstore(add(_b, _index), input)
}
}
/// @notice Converts Kybers Eth address -> Weth
/// @param _src Input address
function ethToWethAddr(address _src) internal pure returns (address) {
return _src == KYBER_ETH_ADDRESS ? WETH_ADDRESS : _src;
}
/// @notice Calculates protocol fee
/// @param _srcAddr selling token address (if eth should be WETH)
/// @param _srcAmount amount we are selling
function getProtocolFee(address _srcAddr, uint256 _srcAmount) internal view returns(uint256) {
// if we are not selling ETH msg value is always the protocol fee
if (_srcAddr != WETH_ADDRESS) return address(this).balance;
// if msg value is larger than srcAmount, that means that msg value is protocol fee + srcAmount, so we subsctract srcAmount from msg value
// we have an edge case here when protocol fee is higher than selling amount
if (address(this).balance > _srcAmount) return address(this).balance - _srcAmount;
// if msg value is lower than src amount, that means that srcAmount isn't included in msg value, so we return msg value
return address(this).balance;
}
function packExchangeData(ExchangeData memory _exData) public pure returns(bytes memory) {
// splitting in two different bytes and encoding all because of stack too deep in decoding part
bytes memory part1 = abi.encode(
_exData.srcAddr,
_exData.destAddr,
_exData.srcAmount,
_exData.destAmount
);
bytes memory part2 = abi.encode(
_exData.minPrice,
_exData.wrapper,
_exData.exchangeAddr,
_exData.callData,
_exData.price0x
);
return abi.encode(part1, part2);
}
function unpackExchangeData(bytes memory _data) public pure returns(ExchangeData memory _exData) {
(
bytes memory part1,
bytes memory part2
) = abi.decode(_data, (bytes,bytes));
(
_exData.srcAddr,
_exData.destAddr,
_exData.srcAmount,
_exData.destAmount
) = abi.decode(part1, (address,address,uint256,uint256));
(
_exData.minPrice,
_exData.wrapper,
_exData.exchangeAddr,
_exData.callData,
_exData.price0x
)
= abi.decode(part2, (uint256,address,address,bytes,uint256));
}
// solhint-disable-next-line no-empty-blocks
receive() external virtual payable {}
}
contract KyberWrapper is DSMath, ExchangeInterfaceV2, AdminAuth {
address public constant KYBER_ETH_ADDRESS = 0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE;
address public constant KYBER_INTERFACE = 0x9AAb3f75489902f3a48495025729a0AF77d4b11e;
address payable public constant WALLET_ID = 0x322d58b9E75a6918f7e7849AEe0fF09369977e08;
using SafeERC20 for ERC20;
/// @notice Sells a _srcAmount of tokens at Kyber
/// @param _srcAddr From token
/// @param _destAddr To token
/// @param _srcAmount From amount
/// @return uint Destination amount
function sell(address _srcAddr, address _destAddr, uint _srcAmount) external override payable returns (uint) {
ERC20 srcToken = ERC20(_srcAddr);
ERC20 destToken = ERC20(_destAddr);
KyberNetworkProxyInterface kyberNetworkProxy = KyberNetworkProxyInterface(KYBER_INTERFACE);
if (_srcAddr != KYBER_ETH_ADDRESS) {
srcToken.safeApprove(address(kyberNetworkProxy), _srcAmount);
}
uint destAmount = kyberNetworkProxy.trade{value: msg.value}(
srcToken,
_srcAmount,
destToken,
msg.sender,
uint(-1),
0,
WALLET_ID
);
return destAmount;
}
/// @notice Buys a _destAmount of tokens at Kyber
/// @param _srcAddr From token
/// @param _destAddr To token
/// @param _destAmount To amount
/// @return uint srcAmount
function buy(address _srcAddr, address _destAddr, uint _destAmount) external override payable returns(uint) {
ERC20 srcToken = ERC20(_srcAddr);
ERC20 destToken = ERC20(_destAddr);
uint srcAmount = 0;
if (_srcAddr != KYBER_ETH_ADDRESS) {
srcAmount = srcToken.balanceOf(address(this));
} else {
srcAmount = msg.value;
}
KyberNetworkProxyInterface kyberNetworkProxy = KyberNetworkProxyInterface(KYBER_INTERFACE);
if (_srcAddr != KYBER_ETH_ADDRESS) {
srcToken.safeApprove(address(kyberNetworkProxy), srcAmount);
}
uint destAmount = kyberNetworkProxy.trade{value: msg.value}(
srcToken,
srcAmount,
destToken,
msg.sender,
_destAmount,
0,
WALLET_ID
);
require(destAmount == _destAmount, "Wrong dest amount");
uint srcAmountAfter = 0;
if (_srcAddr != KYBER_ETH_ADDRESS) {
srcAmountAfter = srcToken.balanceOf(address(this));
} else {
srcAmountAfter = address(this).balance;
}
// Send the leftover from the source token back
sendLeftOver(_srcAddr);
return (srcAmount - srcAmountAfter);
}
/// @notice Return a rate for which we can sell an amount of tokens
/// @param _srcAddr From token
/// @param _destAddr To token
/// @param _srcAmount From amount
/// @return rate Rate
function getSellRate(address _srcAddr, address _destAddr, uint _srcAmount) public override view returns (uint rate) {
(rate, ) = KyberNetworkProxyInterface(KYBER_INTERFACE)
.getExpectedRate(ERC20(_srcAddr), ERC20(_destAddr), _srcAmount);
// multiply with decimal difference in src token
rate = rate * (10**(18 - getDecimals(_srcAddr)));
// divide with decimal difference in dest token
rate = rate / (10**(18 - getDecimals(_destAddr)));
}
/// @notice Return a rate for which we can buy an amount of tokens
/// @param _srcAddr From token
/// @param _destAddr To token
/// @param _destAmount To amount
/// @return rate Rate
function getBuyRate(address _srcAddr, address _destAddr, uint _destAmount) public override view returns (uint rate) {
uint256 srcRate = getSellRate(_destAddr, _srcAddr, _destAmount);
uint256 srcAmount = wmul(srcRate, _destAmount);
rate = getSellRate(_srcAddr, _destAddr, srcAmount);
// increase rate by 3% too account for inaccuracy between sell/buy conversion
rate = rate + (rate / 30);
}
/// @notice Send any leftover tokens, we use to clear out srcTokens after buy
/// @param _srcAddr Source token address
function sendLeftOver(address _srcAddr) internal {
msg.sender.transfer(address(this).balance);
if (_srcAddr != KYBER_ETH_ADDRESS) {
ERC20(_srcAddr).safeTransfer(msg.sender, ERC20(_srcAddr).balanceOf(address(this)));
}
}
receive() payable external {}
function getDecimals(address _token) internal view returns (uint256) {
if (_token == KYBER_ETH_ADDRESS) return 18;
return ERC20(_token).decimals();
}
}
contract OasisTradeWrapper is DSMath, ExchangeInterfaceV2, AdminAuth {
using SafeERC20 for ERC20;
address public constant OTC_ADDRESS = 0x794e6e91555438aFc3ccF1c5076A74F42133d08D;
address public constant WETH_ADDRESS = 0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2;
address public constant KYBER_ETH_ADDRESS = 0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE;
/// @notice Sells a _srcAmount of tokens at Oasis
/// @param _srcAddr From token
/// @param _destAddr To token
/// @param _srcAmount From amount
/// @return uint Destination amount
function sell(address _srcAddr, address _destAddr, uint _srcAmount) external override payable returns (uint) {
address srcAddr = ethToWethAddr(_srcAddr);
address destAddr = ethToWethAddr(_destAddr);
ERC20(srcAddr).safeApprove(OTC_ADDRESS, _srcAmount);
uint destAmount = OasisInterface(OTC_ADDRESS).sellAllAmount(srcAddr, _srcAmount, destAddr, 0);
// convert weth -> eth and send back
if (destAddr == WETH_ADDRESS) {
TokenInterface(WETH_ADDRESS).withdraw(destAmount);
msg.sender.transfer(destAmount);
} else {
ERC20(destAddr).safeTransfer(msg.sender, destAmount);
}
return destAmount;
}
/// @notice Buys a _destAmount of tokens at Oasis
/// @param _srcAddr From token
/// @param _destAddr To token
/// @param _destAmount To amount
/// @return uint srcAmount
function buy(address _srcAddr, address _destAddr, uint _destAmount) external override payable returns(uint) {
address srcAddr = ethToWethAddr(_srcAddr);
address destAddr = ethToWethAddr(_destAddr);
ERC20(srcAddr).safeApprove(OTC_ADDRESS, uint(-1));
uint srcAmount = OasisInterface(OTC_ADDRESS).buyAllAmount(destAddr, _destAmount, srcAddr, uint(-1));
// convert weth -> eth and send back
if (destAddr == WETH_ADDRESS) {
TokenInterface(WETH_ADDRESS).withdraw(_destAmount);
msg.sender.transfer(_destAmount);
} else {
ERC20(destAddr).safeTransfer(msg.sender, _destAmount);
}
// Send the leftover from the source token back
sendLeftOver(srcAddr);
return srcAmount;
}
/// @notice Return a rate for which we can sell an amount of tokens
/// @param _srcAddr From token
/// @param _destAddr To token
/// @param _srcAmount From amount
/// @return uint Rate
function getSellRate(address _srcAddr, address _destAddr, uint _srcAmount) public override view returns (uint) {
address srcAddr = ethToWethAddr(_srcAddr);
address destAddr = ethToWethAddr(_destAddr);
return wdiv(OasisInterface(OTC_ADDRESS).getBuyAmount(destAddr, srcAddr, _srcAmount), _srcAmount);
}
/// @notice Return a rate for which we can buy an amount of tokens
/// @param _srcAddr From token
/// @param _destAddr To token
/// @param _destAmount To amount
/// @return uint Rate
function getBuyRate(address _srcAddr, address _destAddr, uint _destAmount) public override view returns (uint) {
address srcAddr = ethToWethAddr(_srcAddr);
address destAddr = ethToWethAddr(_destAddr);
return wdiv(1 ether, wdiv(OasisInterface(OTC_ADDRESS).getPayAmount(srcAddr, destAddr, _destAmount), _destAmount));
}
/// @notice Send any leftover tokens, we use to clear out srcTokens after buy
/// @param _srcAddr Source token address
function sendLeftOver(address _srcAddr) internal {
msg.sender.transfer(address(this).balance);
if (_srcAddr != KYBER_ETH_ADDRESS) {
ERC20(_srcAddr).safeTransfer(msg.sender, ERC20(_srcAddr).balanceOf(address(this)));
}
}
/// @notice Converts Kybers Eth address -> Weth
/// @param _src Input address
function ethToWethAddr(address _src) internal pure returns (address) {
return _src == KYBER_ETH_ADDRESS ? WETH_ADDRESS : _src;
}
receive() payable external {}
}
contract UniswapV2Wrapper is DSMath, ExchangeInterfaceV2, AdminAuth {
address public constant WETH_ADDRESS = 0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2;
address public constant KYBER_ETH_ADDRESS = 0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE;
UniswapRouterInterface public constant router = UniswapRouterInterface(0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D);
using SafeERC20 for ERC20;
/// @notice Sells a _srcAmount of tokens at UniswapV2
/// @param _srcAddr From token
/// @param _destAddr To token
/// @param _srcAmount From amount
/// @return uint Destination amount
function sell(address _srcAddr, address _destAddr, uint _srcAmount) external payable override returns (uint) {
_srcAddr = ethToWethAddr(_srcAddr);
_destAddr = ethToWethAddr(_destAddr);
uint[] memory amounts;
address[] memory path = new address[](2);
path[0] = _srcAddr;
path[1] = _destAddr;
ERC20(_srcAddr).safeApprove(address(router), _srcAmount);
// if we are buying ether
if (_destAddr == WETH_ADDRESS) {
amounts = router.swapExactTokensForETH(_srcAmount, 1, path, msg.sender, block.timestamp + 1);
}
// if we are selling token to token
else {
amounts = router.swapExactTokensForTokens(_srcAmount, 1, path, msg.sender, block.timestamp + 1);
}
return amounts[amounts.length - 1];
}
/// @notice Buys a _destAmount of tokens at UniswapV2
/// @param _srcAddr From token
/// @param _destAddr To token
/// @param _destAmount To amount
/// @return uint srcAmount
function buy(address _srcAddr, address _destAddr, uint _destAmount) external override payable returns(uint) {
_srcAddr = ethToWethAddr(_srcAddr);
_destAddr = ethToWethAddr(_destAddr);
uint[] memory amounts;
address[] memory path = new address[](2);
path[0] = _srcAddr;
path[1] = _destAddr;
ERC20(_srcAddr).safeApprove(address(router), uint(-1));
// if we are buying ether
if (_destAddr == WETH_ADDRESS) {
amounts = router.swapTokensForExactETH(_destAmount, uint(-1), path, msg.sender, block.timestamp + 1);
}
// if we are buying token to token
else {
amounts = router.swapTokensForExactTokens(_destAmount, uint(-1), path, msg.sender, block.timestamp + 1);
}
// Send the leftover from the source token back
sendLeftOver(_srcAddr);
return amounts[0];
}
/// @notice Return a rate for which we can sell an amount of tokens
/// @param _srcAddr From token
/// @param _destAddr To token
/// @param _srcAmount From amount
/// @return uint Rate
function getSellRate(address _srcAddr, address _destAddr, uint _srcAmount) public override view returns (uint) {
_srcAddr = ethToWethAddr(_srcAddr);
_destAddr = ethToWethAddr(_destAddr);
address[] memory path = new address[](2);
path[0] = _srcAddr;
path[1] = _destAddr;
uint[] memory amounts = router.getAmountsOut(_srcAmount, path);
return wdiv(amounts[amounts.length - 1], _srcAmount);
}
/// @notice Return a rate for which we can buy an amount of tokens
/// @param _srcAddr From token
/// @param _destAddr To token
/// @param _destAmount To amount
/// @return uint Rate
function getBuyRate(address _srcAddr, address _destAddr, uint _destAmount) public override view returns (uint) {
_srcAddr = ethToWethAddr(_srcAddr);
_destAddr = ethToWethAddr(_destAddr);
address[] memory path = new address[](2);
path[0] = _srcAddr;
path[1] = _destAddr;
uint[] memory amounts = router.getAmountsIn(_destAmount, path);
return wdiv(_destAmount, amounts[0]);
}
/// @notice Send any leftover tokens, we use to clear out srcTokens after buy
/// @param _srcAddr Source token address
function sendLeftOver(address _srcAddr) internal {
msg.sender.transfer(address(this).balance);
if (_srcAddr != KYBER_ETH_ADDRESS) {
ERC20(_srcAddr).safeTransfer(msg.sender, ERC20(_srcAddr).balanceOf(address(this)));
}
}
/// @notice Converts Kybers Eth address -> Weth
/// @param _src Input address
function ethToWethAddr(address _src) internal pure returns (address) {
return _src == KYBER_ETH_ADDRESS ? WETH_ADDRESS : _src;
}
function getDecimals(address _token) internal view returns (uint256) {
if (_token == KYBER_ETH_ADDRESS) return 18;
return ERC20(_token).decimals();
}
receive() payable external {}
}
contract UniswapWrapper is DSMath, ExchangeInterfaceV2, AdminAuth {
address public constant WETH_ADDRESS = 0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2;
address public constant KYBER_ETH_ADDRESS = 0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE;
address public constant UNISWAP_FACTORY = 0xc0a47dFe034B400B47bDaD5FecDa2621de6c4d95;
using SafeERC20 for ERC20;
/// @notice Sells a _srcAmount of tokens at Uniswap
/// @param _srcAddr From token
/// @param _destAddr To token
/// @param _srcAmount From amount
/// @return uint Destination amount
function sell(address _srcAddr, address _destAddr, uint _srcAmount) external payable override returns (uint) {
address uniswapExchangeAddr;
uint destAmount;
_srcAddr = ethToWethAddr(_srcAddr);
_destAddr = ethToWethAddr(_destAddr);
// if we are buying ether
if (_destAddr == WETH_ADDRESS) {
uniswapExchangeAddr = UniswapFactoryInterface(UNISWAP_FACTORY).getExchange(_srcAddr);
ERC20(_srcAddr).safeApprove(uniswapExchangeAddr, _srcAmount);
destAmount = UniswapExchangeInterface(uniswapExchangeAddr).
tokenToEthTransferInput(_srcAmount, 1, block.timestamp + 1, msg.sender);
}
// if we are selling token to token
else {
uniswapExchangeAddr = UniswapFactoryInterface(UNISWAP_FACTORY).getExchange(_srcAddr);
ERC20(_srcAddr).safeApprove(uniswapExchangeAddr, _srcAmount);
destAmount = UniswapExchangeInterface(uniswapExchangeAddr).
tokenToTokenTransferInput(_srcAmount, 1, 1, block.timestamp + 1, msg.sender, _destAddr);
}
return destAmount;
}
/// @notice Buys a _destAmount of tokens at Uniswap
/// @param _srcAddr From token
/// @param _destAddr To token
/// @param _destAmount To amount
/// @return uint srcAmount
function buy(address _srcAddr, address _destAddr, uint _destAmount) external override payable returns(uint) {
address uniswapExchangeAddr;
uint srcAmount;
_srcAddr = ethToWethAddr(_srcAddr);
_destAddr = ethToWethAddr(_destAddr);
// if we are buying ether
if (_destAddr == WETH_ADDRESS) {
uniswapExchangeAddr = UniswapFactoryInterface(UNISWAP_FACTORY).getExchange(_srcAddr);
ERC20(_srcAddr).safeApprove(uniswapExchangeAddr, uint(-1));
srcAmount = UniswapExchangeInterface(uniswapExchangeAddr).
tokenToEthTransferOutput(_destAmount, uint(-1), block.timestamp + 1, msg.sender);
}
// if we are buying token to token
else {
uniswapExchangeAddr = UniswapFactoryInterface(UNISWAP_FACTORY).getExchange(_srcAddr);
ERC20(_srcAddr).safeApprove(uniswapExchangeAddr, uint(-1));
srcAmount = UniswapExchangeInterface(uniswapExchangeAddr).
tokenToTokenTransferOutput(_destAmount, uint(-1), uint(-1), block.timestamp + 1, msg.sender, _destAddr);
}
// Send the leftover from the source token back
sendLeftOver(_srcAddr);
return srcAmount;
}
/// @notice Return a rate for which we can sell an amount of tokens
/// @param _srcAddr From token
/// @param _destAddr To token
/// @param _srcAmount From amount
/// @return uint Rate
function getSellRate(address _srcAddr, address _destAddr, uint _srcAmount) public override view returns (uint) {
_srcAddr = ethToWethAddr(_srcAddr);
_destAddr = ethToWethAddr(_destAddr);
if(_srcAddr == WETH_ADDRESS) {
address uniswapTokenAddress = UniswapFactoryInterface(UNISWAP_FACTORY).getExchange(_destAddr);
return wdiv(UniswapExchangeInterface(uniswapTokenAddress).getEthToTokenInputPrice(_srcAmount), _srcAmount);
} else if (_destAddr == WETH_ADDRESS) {
address uniswapTokenAddress = UniswapFactoryInterface(UNISWAP_FACTORY).getExchange(_srcAddr);
return wdiv(UniswapExchangeInterface(uniswapTokenAddress).getTokenToEthInputPrice(_srcAmount), _srcAmount);
} else {
uint ethBought = UniswapExchangeInterface(UniswapFactoryInterface(UNISWAP_FACTORY).getExchange(_srcAddr)).getTokenToEthInputPrice(_srcAmount);
return wdiv(UniswapExchangeInterface(UniswapFactoryInterface(UNISWAP_FACTORY).getExchange(_destAddr)).getEthToTokenInputPrice(ethBought), _srcAmount);
}
}
/// @notice Return a rate for which we can buy an amount of tokens
/// @param _srcAddr From token
/// @param _destAddr To token
/// @param _destAmount To amount
/// @return uint Rate
function getBuyRate(address _srcAddr, address _destAddr, uint _destAmount) public override view returns (uint) {
_srcAddr = ethToWethAddr(_srcAddr);
_destAddr = ethToWethAddr(_destAddr);
if(_srcAddr == WETH_ADDRESS) {
address uniswapTokenAddress = UniswapFactoryInterface(UNISWAP_FACTORY).getExchange(_destAddr);
return wdiv(1 ether, wdiv(UniswapExchangeInterface(uniswapTokenAddress).getEthToTokenOutputPrice(_destAmount), _destAmount));
} else if (_destAddr == WETH_ADDRESS) {
address uniswapTokenAddress = UniswapFactoryInterface(UNISWAP_FACTORY).getExchange(_srcAddr);
return wdiv(1 ether, wdiv(UniswapExchangeInterface(uniswapTokenAddress).getTokenToEthOutputPrice(_destAmount), _destAmount));
} else {
uint ethNeeded = UniswapExchangeInterface(UniswapFactoryInterface(UNISWAP_FACTORY).getExchange(_destAddr)).getTokenToEthOutputPrice(_destAmount);
return wdiv(1 ether, wdiv(UniswapExchangeInterface(UniswapFactoryInterface(UNISWAP_FACTORY).getExchange(_srcAddr)).getEthToTokenOutputPrice(ethNeeded), _destAmount));
}
}
/// @notice Send any leftover tokens, we use to clear out srcTokens after buy
/// @param _srcAddr Source token address
function sendLeftOver(address _srcAddr) internal {
msg.sender.transfer(address(this).balance);
if (_srcAddr != KYBER_ETH_ADDRESS) {
ERC20(_srcAddr).safeTransfer(msg.sender, ERC20(_srcAddr).balanceOf(address(this)));
}
}
/// @notice Converts Kybers Eth address -> Weth
/// @param _src Input address
function ethToWethAddr(address _src) internal pure returns (address) {
return _src == KYBER_ETH_ADDRESS ? WETH_ADDRESS : _src;
}
receive() payable external {}
}
contract DFSExchangeCore is DFSExchangeHelper, DSMath, DFSExchangeData {
string public constant ERR_SLIPPAGE_HIT = "Slippage hit";
string public constant ERR_DEST_AMOUNT_MISSING = "Dest amount missing";
string public constant ERR_WRAPPER_INVALID = "Wrapper invalid";
string public constant ERR_OFFCHAIN_DATA_INVALID = "Offchain data invalid";
/// @notice Internal method that preforms a sell on 0x/on-chain
/// @dev Usefull for other DFS contract to integrate for exchanging
/// @param exData Exchange data struct
/// @return (address, uint) Address of the wrapper used and destAmount
function _sell(ExchangeData memory exData) internal returns (address, uint) {
address wrapper;
uint swapedTokens;
bool success;
// if selling eth, convert to weth
if (exData.srcAddr == KYBER_ETH_ADDRESS) {
exData.srcAddr = ethToWethAddr(exData.srcAddr);
TokenInterface(WETH_ADDRESS).deposit.value(exData.srcAmount)();
}
exData.srcAmount -= getFee(exData.srcAmount, exData.user, exData.srcAddr, exData.dfsFeeDivider);
// Try 0x first and then fallback on specific wrapper
if (exData.offchainData.price > 0) {
(success, swapedTokens) = takeOrder(exData, ActionType.SELL);
if (success) {
wrapper = exData.offchainData.exchangeAddr;
}
}
// fallback to desired wrapper if 0x failed
if (!success) {
swapedTokens = saverSwap(exData, ActionType.SELL);
wrapper = exData.wrapper;
}
require(getBalance(exData.destAddr) >= wmul(exData.minPrice, exData.srcAmount), ERR_SLIPPAGE_HIT);
// if anything is left in weth, pull it to user as eth
if (getBalance(WETH_ADDRESS) > 0) {
TokenInterface(WETH_ADDRESS).withdraw(
TokenInterface(WETH_ADDRESS).balanceOf(address(this))
);
}
return (wrapper, swapedTokens);
}
/// @notice Internal method that preforms a buy on 0x/on-chain
/// @dev Usefull for other DFS contract to integrate for exchanging
/// @param exData Exchange data struct
/// @return (address, uint) Address of the wrapper used and srcAmount
function _buy(ExchangeData memory exData) internal returns (address, uint) {
address wrapper;
uint swapedTokens;
bool success;
require(exData.destAmount != 0, ERR_DEST_AMOUNT_MISSING);
exData.srcAmount -= getFee(exData.srcAmount, exData.user, exData.srcAddr, exData.dfsFeeDivider);
// if selling eth, convert to weth
if (exData.srcAddr == KYBER_ETH_ADDRESS) {
exData.srcAddr = ethToWethAddr(exData.srcAddr);
TokenInterface(WETH_ADDRESS).deposit.value(exData.srcAmount)();
}
if (exData.offchainData.price > 0) {
(success, swapedTokens) = takeOrder(exData, ActionType.BUY);
if (success) {
wrapper = exData.offchainData.exchangeAddr;
}
}
// fallback to desired wrapper if 0x failed
if (!success) {
swapedTokens = saverSwap(exData, ActionType.BUY);
wrapper = exData.wrapper;
}
require(getBalance(exData.destAddr) >= exData.destAmount, ERR_SLIPPAGE_HIT);
// if anything is left in weth, pull it to user as eth
if (getBalance(WETH_ADDRESS) > 0) {
TokenInterface(WETH_ADDRESS).withdraw(
TokenInterface(WETH_ADDRESS).balanceOf(address(this))
);
}
return (wrapper, getBalance(exData.destAddr));
}
/// @notice Takes order from 0x and returns bool indicating if it is successful
/// @param _exData Exchange data
function takeOrder(
ExchangeData memory _exData,
ActionType _type
) private returns (bool success, uint256) {
if (_exData.srcAddr != KYBER_ETH_ADDRESS) {
ERC20(_exData.srcAddr).safeApprove(_exData.offchainData.allowanceTarget, _exData.srcAmount);
}
// write in the exact amount we are selling/buing in an order
if (_type == ActionType.SELL) {
writeUint256(_exData.offchainData.callData, 36, _exData.srcAmount);
} else {
writeUint256(_exData.offchainData.callData, 36, _exData.destAmount);
}
uint256 tokensBefore = getBalance(_exData.destAddr);
if (ZrxAllowlist(ZRX_ALLOWLIST_ADDR).isZrxAddr(_exData.offchainData.exchangeAddr)) {
(success, ) = _exData.offchainData.exchangeAddr.call{value: _exData.offchainData.protocolFee}(_exData.offchainData.callData);
} else {
success = false;
}
uint256 tokensSwaped = 0;
if (success) {
// convert weth -> eth if needed
if (_exData.destAddr == KYBER_ETH_ADDRESS) {
TokenInterface(WETH_ADDRESS).withdraw(
TokenInterface(WETH_ADDRESS).balanceOf(address(this))
);
}
// get the current balance of the swaped tokens
tokensSwaped = getBalance(_exData.destAddr) - tokensBefore;
}
return (success, tokensSwaped);
}
/// @notice Calls wraper contract for exchage to preform an on-chain swap
/// @param _exData Exchange data struct
/// @param _type Type of action SELL|BUY
/// @return swapedTokens For Sell that the destAmount, for Buy thats the srcAmount
function saverSwap(ExchangeData memory _exData, ActionType _type) internal returns (uint swapedTokens) {
require(SaverExchangeRegistry(SAVER_EXCHANGE_REGISTRY).isWrapper(_exData.wrapper), ERR_WRAPPER_INVALID);
ERC20(_exData.srcAddr).safeTransfer(_exData.wrapper, _exData.srcAmount);
if (_type == ActionType.SELL) {
swapedTokens = ExchangeInterfaceV3(_exData.wrapper).
sell(_exData.srcAddr, _exData.destAddr, _exData.srcAmount, _exData.wrapperData);
} else {
swapedTokens = ExchangeInterfaceV3(_exData.wrapper).
buy(_exData.srcAddr, _exData.destAddr, _exData.destAmount, _exData.wrapperData);
}
}
function writeUint256(bytes memory _b, uint256 _index, uint _input) internal pure {
if (_b.length < _index + 32) {
revert(ERR_OFFCHAIN_DATA_INVALID);
}
bytes32 input = bytes32(_input);
_index += 32;
// Read the bytes32 from array memory
assembly {
mstore(add(_b, _index), input)
}
}
/// @notice Converts Kybers Eth address -> Weth
/// @param _src Input address
function ethToWethAddr(address _src) internal pure returns (address) {
return _src == KYBER_ETH_ADDRESS ? WETH_ADDRESS : _src;
}
// solhint-disable-next-line no-empty-blocks
receive() external virtual payable {}
}
contract KyberWrapperV3 is DSMath, ExchangeInterfaceV3, AdminAuth {
address public constant KYBER_ETH_ADDRESS = 0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE;
address public constant KYBER_INTERFACE = 0x9AAb3f75489902f3a48495025729a0AF77d4b11e;
address payable public constant WALLET_ID = 0x322d58b9E75a6918f7e7849AEe0fF09369977e08;
using SafeERC20 for ERC20;
/// @notice Sells a _srcAmount of tokens at Kyber
/// @param _srcAddr From token
/// @param _destAddr To token
/// @param _srcAmount From amount
/// @return uint Destination amount
function sell(address _srcAddr, address _destAddr, uint _srcAmount, bytes memory _additionalData) external override payable returns (uint) {
ERC20 srcToken = ERC20(_srcAddr);
ERC20 destToken = ERC20(_destAddr);
KyberNetworkProxyInterface kyberNetworkProxy = KyberNetworkProxyInterface(KYBER_INTERFACE);
if (_srcAddr != KYBER_ETH_ADDRESS) {
srcToken.safeApprove(address(kyberNetworkProxy), _srcAmount);
}
uint destAmount = kyberNetworkProxy.trade{value: msg.value}(
srcToken,
_srcAmount,
destToken,
msg.sender,
uint(-1),
0,
WALLET_ID
);
return destAmount;
}
/// @notice Buys a _destAmount of tokens at Kyber
/// @param _srcAddr From token
/// @param _destAddr To token
/// @param _destAmount To amount
/// @return uint srcAmount
function buy(address _srcAddr, address _destAddr, uint _destAmount, bytes memory _additionalData) external override payable returns(uint) {
ERC20 srcToken = ERC20(_srcAddr);
ERC20 destToken = ERC20(_destAddr);
uint srcAmount = 0;
if (_srcAddr != KYBER_ETH_ADDRESS) {
srcAmount = srcToken.balanceOf(address(this));
} else {
srcAmount = msg.value;
}
KyberNetworkProxyInterface kyberNetworkProxy = KyberNetworkProxyInterface(KYBER_INTERFACE);
if (_srcAddr != KYBER_ETH_ADDRESS) {
srcToken.safeApprove(address(kyberNetworkProxy), srcAmount);
}
uint destAmount = kyberNetworkProxy.trade{value: msg.value}(
srcToken,
srcAmount,
destToken,
msg.sender,
_destAmount,
0,
WALLET_ID
);
require(destAmount == _destAmount, "Wrong dest amount");
uint srcAmountAfter = 0;
if (_srcAddr != KYBER_ETH_ADDRESS) {
srcAmountAfter = srcToken.balanceOf(address(this));
} else {
srcAmountAfter = address(this).balance;
}
// Send the leftover from the source token back
sendLeftOver(_srcAddr);
return (srcAmount - srcAmountAfter);
}
/// @notice Return a rate for which we can sell an amount of tokens
/// @param _srcAddr From token
/// @param _destAddr To token
/// @param _srcAmount From amount
/// @return rate Rate
function getSellRate(address _srcAddr, address _destAddr, uint _srcAmount, bytes memory _additionalData) public override view returns (uint rate) {
(rate, ) = KyberNetworkProxyInterface(KYBER_INTERFACE)
.getExpectedRate(ERC20(_srcAddr), ERC20(_destAddr), _srcAmount);
// multiply with decimal difference in src token
rate = rate * (10**(18 - getDecimals(_srcAddr)));
// divide with decimal difference in dest token
rate = rate / (10**(18 - getDecimals(_destAddr)));
}
/// @notice Return a rate for which we can buy an amount of tokens
/// @param _srcAddr From token
/// @param _destAddr To token
/// @param _destAmount To amount
/// @return rate Rate
function getBuyRate(address _srcAddr, address _destAddr, uint _destAmount, bytes memory _additionalData) public override view returns (uint rate) {
uint256 srcRate = getSellRate(_destAddr, _srcAddr, _destAmount, _additionalData);
uint256 srcAmount = wmul(srcRate, _destAmount);
rate = getSellRate(_srcAddr, _destAddr, srcAmount, _additionalData);
// increase rate by 3% too account for inaccuracy between sell/buy conversion
rate = rate + (rate / 30);
}
/// @notice Send any leftover tokens, we use to clear out srcTokens after buy
/// @param _srcAddr Source token address
function sendLeftOver(address _srcAddr) internal {
msg.sender.transfer(address(this).balance);
if (_srcAddr != KYBER_ETH_ADDRESS) {
ERC20(_srcAddr).safeTransfer(msg.sender, ERC20(_srcAddr).balanceOf(address(this)));
}
}
receive() payable external {}
function getDecimals(address _token) internal view returns (uint256) {
if (_token == KYBER_ETH_ADDRESS) return 18;
return ERC20(_token).decimals();
}
}
contract OasisTradeWrapperV3 is DSMath, ExchangeInterfaceV3, AdminAuth {
using SafeERC20 for ERC20;
address public constant OTC_ADDRESS = 0x794e6e91555438aFc3ccF1c5076A74F42133d08D;
address public constant WETH_ADDRESS = 0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2;
address public constant KYBER_ETH_ADDRESS = 0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE;
/// @notice Sells a _srcAmount of tokens at Oasis
/// @param _srcAddr From token
/// @param _destAddr To token
/// @param _srcAmount From amount
/// @return uint Destination amount
function sell(address _srcAddr, address _destAddr, uint _srcAmount, bytes memory _additionalData) external override payable returns (uint) {
address srcAddr = ethToWethAddr(_srcAddr);
address destAddr = ethToWethAddr(_destAddr);
ERC20(srcAddr).safeApprove(OTC_ADDRESS, _srcAmount);
uint destAmount = OasisInterface(OTC_ADDRESS).sellAllAmount(srcAddr, _srcAmount, destAddr, 0);
// convert weth -> eth and send back
if (destAddr == WETH_ADDRESS) {
TokenInterface(WETH_ADDRESS).withdraw(destAmount);
msg.sender.transfer(destAmount);
} else {
ERC20(destAddr).safeTransfer(msg.sender, destAmount);
}
return destAmount;
}
/// @notice Buys a _destAmount of tokens at Oasis
/// @param _srcAddr From token
/// @param _destAddr To token
/// @param _destAmount To amount
/// @return uint srcAmount
function buy(address _srcAddr, address _destAddr, uint _destAmount, bytes memory _additionalData) external override payable returns(uint) {
address srcAddr = ethToWethAddr(_srcAddr);
address destAddr = ethToWethAddr(_destAddr);
ERC20(srcAddr).safeApprove(OTC_ADDRESS, uint(-1));
uint srcAmount = OasisInterface(OTC_ADDRESS).buyAllAmount(destAddr, _destAmount, srcAddr, uint(-1));
// convert weth -> eth and send back
if (destAddr == WETH_ADDRESS) {
TokenInterface(WETH_ADDRESS).withdraw(_destAmount);
msg.sender.transfer(_destAmount);
} else {
ERC20(destAddr).safeTransfer(msg.sender, _destAmount);
}
// Send the leftover from the source token back
sendLeftOver(srcAddr);
return srcAmount;
}
/// @notice Return a rate for which we can sell an amount of tokens
/// @param _srcAddr From token
/// @param _destAddr To token
/// @param _srcAmount From amount
/// @return uint Rate
function getSellRate(address _srcAddr, address _destAddr, uint _srcAmount, bytes memory _additionalData) public override view returns (uint) {
address srcAddr = ethToWethAddr(_srcAddr);
address destAddr = ethToWethAddr(_destAddr);
return wdiv(OasisInterface(OTC_ADDRESS).getBuyAmount(destAddr, srcAddr, _srcAmount), _srcAmount);
}
/// @notice Return a rate for which we can buy an amount of tokens
/// @param _srcAddr From token
/// @param _destAddr To token
/// @param _destAmount To amount
/// @return uint Rate
function getBuyRate(address _srcAddr, address _destAddr, uint _destAmount, bytes memory _additionalData) public override view returns (uint) {
address srcAddr = ethToWethAddr(_srcAddr);
address destAddr = ethToWethAddr(_destAddr);
return wdiv(1 ether, wdiv(OasisInterface(OTC_ADDRESS).getPayAmount(srcAddr, destAddr, _destAmount), _destAmount));
}
/// @notice Send any leftover tokens, we use to clear out srcTokens after buy
/// @param _srcAddr Source token address
function sendLeftOver(address _srcAddr) internal {
msg.sender.transfer(address(this).balance);
if (_srcAddr != KYBER_ETH_ADDRESS) {
ERC20(_srcAddr).safeTransfer(msg.sender, ERC20(_srcAddr).balanceOf(address(this)));
}
}
/// @notice Converts Kybers Eth address -> Weth
/// @param _src Input address
function ethToWethAddr(address _src) internal pure returns (address) {
return _src == KYBER_ETH_ADDRESS ? WETH_ADDRESS : _src;
}
receive() payable external {}
}
contract UniswapWrapperV3 is DSMath, ExchangeInterfaceV3, AdminAuth {
address public constant WETH_ADDRESS = 0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2;
address public constant KYBER_ETH_ADDRESS = 0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE;
UniswapRouterInterface public constant router = UniswapRouterInterface(0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D);
using SafeERC20 for ERC20;
/// @notice Sells a _srcAmount of tokens at UniswapV2
/// @param _srcAddr From token
/// @param _destAddr To token
/// @param _srcAmount From amount
/// @return uint Destination amount
function sell(address _srcAddr, address _destAddr, uint _srcAmount, bytes memory _additionalData) external payable override returns (uint) {
_srcAddr = ethToWethAddr(_srcAddr);
_destAddr = ethToWethAddr(_destAddr);
uint[] memory amounts;
address[] memory path = abi.decode(_additionalData, (address[]));
ERC20(_srcAddr).safeApprove(address(router), _srcAmount);
// if we are buying ether
if (_destAddr == WETH_ADDRESS) {
amounts = router.swapExactTokensForETH(_srcAmount, 1, path, msg.sender, block.timestamp + 1);
}
// if we are selling token to token
else {
amounts = router.swapExactTokensForTokens(_srcAmount, 1, path, msg.sender, block.timestamp + 1);
}
return amounts[amounts.length - 1];
}
/// @notice Buys a _destAmount of tokens at UniswapV2
/// @param _srcAddr From token
/// @param _destAddr To token
/// @param _destAmount To amount
/// @return uint srcAmount
function buy(address _srcAddr, address _destAddr, uint _destAmount, bytes memory _additionalData) external override payable returns(uint) {
_srcAddr = ethToWethAddr(_srcAddr);
_destAddr = ethToWethAddr(_destAddr);
uint[] memory amounts;
address[] memory path = abi.decode(_additionalData, (address[]));
ERC20(_srcAddr).safeApprove(address(router), uint(-1));
// if we are buying ether
if (_destAddr == WETH_ADDRESS) {
amounts = router.swapTokensForExactETH(_destAmount, uint(-1), path, msg.sender, block.timestamp + 1);
}
// if we are buying token to token
else {
amounts = router.swapTokensForExactTokens(_destAmount, uint(-1), path, msg.sender, block.timestamp + 1);
}
// Send the leftover from the source token back
sendLeftOver(_srcAddr);
return amounts[0];
}
/// @notice Return a rate for which we can sell an amount of tokens
/// @param _srcAddr From token
/// @param _destAddr To token
/// @param _srcAmount From amount
/// @return uint Rate
function getSellRate(address _srcAddr, address _destAddr, uint _srcAmount, bytes memory _additionalData) public override view returns (uint) {
_srcAddr = ethToWethAddr(_srcAddr);
_destAddr = ethToWethAddr(_destAddr);
address[] memory path = abi.decode(_additionalData, (address[]));
uint[] memory amounts = router.getAmountsOut(_srcAmount, path);
return wdiv(amounts[amounts.length - 1], _srcAmount);
}
/// @notice Return a rate for which we can buy an amount of tokens
/// @param _srcAddr From token
/// @param _destAddr To token
/// @param _destAmount To amount
/// @return uint Rate
function getBuyRate(address _srcAddr, address _destAddr, uint _destAmount, bytes memory _additionalData) public override view returns (uint) {
_srcAddr = ethToWethAddr(_srcAddr);
_destAddr = ethToWethAddr(_destAddr);
address[] memory path = abi.decode(_additionalData, (address[]));
uint[] memory amounts = router.getAmountsIn(_destAmount, path);
return wdiv(_destAmount, amounts[0]);
}
/// @notice Send any leftover tokens, we use to clear out srcTokens after buy
/// @param _srcAddr Source token address
function sendLeftOver(address _srcAddr) internal {
msg.sender.transfer(address(this).balance);
if (_srcAddr != KYBER_ETH_ADDRESS) {
ERC20(_srcAddr).safeTransfer(msg.sender, ERC20(_srcAddr).balanceOf(address(this)));
}
}
/// @notice Converts Kybers Eth address -> Weth
/// @param _src Input address
function ethToWethAddr(address _src) internal pure returns (address) {
return _src == KYBER_ETH_ADDRESS ? WETH_ADDRESS : _src;
}
function getDecimals(address _token) internal view returns (uint256) {
if (_token == KYBER_ETH_ADDRESS) return 18;
return ERC20(_token).decimals();
}
receive() payable external {}
}
contract DyDxFlashLoanTaker is DydxFlashLoanBase, ProxyPermission {
address public constant WETH_ADDR = 0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2;
address public constant DEFISAVER_LOGGER = 0x5c55B921f590a89C1Ebe84dF170E655a82b62126;
/// @notice Takes flash loan for _receiver
/// @dev Receiver must send back WETH + 2 wei after executing transaction
/// @dev Method is meant to be called from proxy and proxy will give authorization to _receiver
/// @param _receiver Address of funds receiver
/// @param _ethAmount ETH amount that needs to be pulled from dydx
/// @param _encodedData Bytes with packed data
function takeLoan(address _receiver, uint256 _ethAmount, bytes memory _encodedData) public {
ISoloMargin solo = ISoloMargin(SOLO_MARGIN_ADDRESS);
// Get marketId from token address
uint256 marketId = _getMarketIdFromTokenAddress(WETH_ADDR);
// Calculate repay amount (_amount + (2 wei))
// Approve transfer from
uint256 repayAmount = _getRepaymentAmountInternal(_ethAmount);
ERC20(WETH_ADDR).approve(SOLO_MARGIN_ADDRESS, repayAmount);
Actions.ActionArgs[] memory operations = new Actions.ActionArgs[](3);
operations[0] = _getWithdrawAction(marketId, _ethAmount, _receiver);
operations[1] = _getCallAction(
_encodedData,
_receiver
);
operations[2] = _getDepositAction(marketId, repayAmount, address(this));
Account.Info[] memory accountInfos = new Account.Info[](1);
accountInfos[0] = _getAccountInfo();
givePermission(_receiver);
solo.operate(accountInfos, operations);
removePermission(_receiver);
DefisaverLogger(DEFISAVER_LOGGER).Log(address(this), msg.sender, "DyDxFlashLoanTaken", abi.encode(_receiver, _ethAmount, _encodedData));
}
}
abstract contract CTokenInterface is ERC20 {
function mint(uint256 mintAmount) external virtual returns (uint256);
// function mint() external virtual payable;
function accrueInterest() public virtual returns (uint);
function redeem(uint256 redeemTokens) external virtual returns (uint256);
function redeemUnderlying(uint256 redeemAmount) external virtual returns (uint256);
function borrow(uint256 borrowAmount) external virtual returns (uint256);
function borrowIndex() public view virtual returns (uint);
function borrowBalanceStored(address) public view virtual returns(uint);
function repayBorrow(uint256 repayAmount) external virtual returns (uint256);
function repayBorrow() external virtual payable;
function repayBorrowBehalf(address borrower, uint256 repayAmount) external virtual returns (uint256);
function repayBorrowBehalf(address borrower) external virtual payable;
function liquidateBorrow(address borrower, uint256 repayAmount, address cTokenCollateral)
external virtual
returns (uint256);
function liquidateBorrow(address borrower, address cTokenCollateral) external virtual payable;
function exchangeRateCurrent() external virtual returns (uint256);
function supplyRatePerBlock() external virtual returns (uint256);
function borrowRatePerBlock() external virtual returns (uint256);
function totalReserves() external virtual returns (uint256);
function reserveFactorMantissa() external virtual returns (uint256);
function borrowBalanceCurrent(address account) external virtual returns (uint256);
function totalBorrowsCurrent() external virtual returns (uint256);
function getCash() external virtual returns (uint256);
function balanceOfUnderlying(address owner) external virtual returns (uint256);
function underlying() external virtual returns (address);
function getAccountSnapshot(address account) external virtual view returns (uint, uint, uint, uint);
}
abstract contract ISubscriptionsV2 is StaticV2 {
function getOwner(uint _cdpId) external view virtual returns(address);
function getSubscribedInfo(uint _cdpId) public view virtual returns(bool, uint128, uint128, uint128, uint128, address, uint coll, uint debt);
function getCdpHolder(uint _cdpId) public view virtual returns (bool subscribed, CdpHolder memory);
}
contract MCDMonitorV2 is DSMath, AdminAuth, GasBurner, StaticV2 {
uint public REPAY_GAS_TOKEN = 25;
uint public BOOST_GAS_TOKEN = 25;
uint public MAX_GAS_PRICE = 500000000000; // 500 gwei
uint public REPAY_GAS_COST = 1800000;
uint public BOOST_GAS_COST = 1800000;
MCDMonitorProxyV2 public monitorProxyContract;
ISubscriptionsV2 public subscriptionsContract;
address public mcdSaverTakerAddress;
address public constant BOT_REGISTRY_ADDRESS = 0x637726f8b08a7ABE3aE3aCaB01A80E2d8ddeF77B;
Manager public manager = Manager(0x5ef30b9986345249bc32d8928B7ee64DE9435E39);
Vat public vat = Vat(0x35D1b3F3D7966A1DFe207aa4514C12a259A0492B);
Spotter public spotter = Spotter(0x65C79fcB50Ca1594B025960e539eD7A9a6D434A3);
DefisaverLogger public constant logger = DefisaverLogger(0x5c55B921f590a89C1Ebe84dF170E655a82b62126);
modifier onlyApproved() {
require(BotRegistry(BOT_REGISTRY_ADDRESS).botList(msg.sender), "Not auth bot");
_;
}
constructor(address _monitorProxy, address _subscriptions, address _mcdSaverTakerAddress) public {
monitorProxyContract = MCDMonitorProxyV2(_monitorProxy);
subscriptionsContract = ISubscriptionsV2(_subscriptions);
mcdSaverTakerAddress = _mcdSaverTakerAddress;
}
/// @notice Bots call this method to repay for user when conditions are met
/// @dev If the contract ownes gas token it will try and use it for gas price reduction
function repayFor(
SaverExchangeCore.ExchangeData memory _exchangeData,
uint _cdpId,
uint _nextPrice,
address _joinAddr
) public payable onlyApproved burnGas(REPAY_GAS_TOKEN) {
(bool isAllowed, uint ratioBefore) = canCall(Method.Repay, _cdpId, _nextPrice);
require(isAllowed);
uint gasCost = calcGasCost(REPAY_GAS_COST);
address owner = subscriptionsContract.getOwner(_cdpId);
monitorProxyContract.callExecute{value: msg.value}(
owner,
mcdSaverTakerAddress,
abi.encodeWithSignature(
"repayWithLoan((address,address,uint256,uint256,uint256,address,address,bytes,uint256),uint256,uint256,address)",
_exchangeData, _cdpId, gasCost, _joinAddr));
(bool isGoodRatio, uint ratioAfter) = ratioGoodAfter(Method.Repay, _cdpId, _nextPrice);
require(isGoodRatio);
returnEth();
logger.Log(address(this), owner, "AutomaticMCDRepay", abi.encode(ratioBefore, ratioAfter));
}
/// @notice Bots call this method to boost for user when conditions are met
/// @dev If the contract ownes gas token it will try and use it for gas price reduction
function boostFor(
SaverExchangeCore.ExchangeData memory _exchangeData,
uint _cdpId,
uint _nextPrice,
address _joinAddr
) public payable onlyApproved burnGas(BOOST_GAS_TOKEN) {
(bool isAllowed, uint ratioBefore) = canCall(Method.Boost, _cdpId, _nextPrice);
require(isAllowed);
uint gasCost = calcGasCost(BOOST_GAS_COST);
address owner = subscriptionsContract.getOwner(_cdpId);
monitorProxyContract.callExecute{value: msg.value}(
owner,
mcdSaverTakerAddress,
abi.encodeWithSignature(
"boostWithLoan((address,address,uint256,uint256,uint256,address,address,bytes,uint256),uint256,uint256,address)",
_exchangeData, _cdpId, gasCost, _joinAddr));
(bool isGoodRatio, uint ratioAfter) = ratioGoodAfter(Method.Boost, _cdpId, _nextPrice);
require(isGoodRatio);
returnEth();
logger.Log(address(this), owner, "AutomaticMCDBoost", abi.encode(ratioBefore, ratioAfter));
}
/******************* INTERNAL METHODS ********************************/
function returnEth() internal {
// return if some eth left
if (address(this).balance > 0) {
msg.sender.transfer(address(this).balance);
}
}
/******************* STATIC METHODS ********************************/
/// @notice Returns an address that owns the CDP
/// @param _cdpId Id of the CDP
function getOwner(uint _cdpId) public view returns(address) {
return manager.owns(_cdpId);
}
/// @notice Gets CDP info (collateral, debt)
/// @param _cdpId Id of the CDP
/// @param _ilk Ilk of the CDP
function getCdpInfo(uint _cdpId, bytes32 _ilk) public view returns (uint, uint) {
address urn = manager.urns(_cdpId);
(uint collateral, uint debt) = vat.urns(_ilk, urn);
(,uint rate,,,) = vat.ilks(_ilk);
return (collateral, rmul(debt, rate));
}
/// @notice Gets a price of the asset
/// @param _ilk Ilk of the CDP
function getPrice(bytes32 _ilk) public view returns (uint) {
(, uint mat) = spotter.ilks(_ilk);
(,,uint spot,,) = vat.ilks(_ilk);
return rmul(rmul(spot, spotter.par()), mat);
}
/// @notice Gets CDP ratio
/// @param _cdpId Id of the CDP
/// @param _nextPrice Next price for user
function getRatio(uint _cdpId, uint _nextPrice) public view returns (uint) {
bytes32 ilk = manager.ilks(_cdpId);
uint price = (_nextPrice == 0) ? getPrice(ilk) : _nextPrice;
(uint collateral, uint debt) = getCdpInfo(_cdpId, ilk);
if (debt == 0) return 0;
return rdiv(wmul(collateral, price), debt) / (10 ** 18);
}
/// @notice Checks if Boost/Repay could be triggered for the CDP
/// @dev Called by MCDMonitor to enforce the min/max check
function canCall(Method _method, uint _cdpId, uint _nextPrice) public view returns(bool, uint) {
bool subscribed;
CdpHolder memory holder;
(subscribed, holder) = subscriptionsContract.getCdpHolder(_cdpId);
// check if cdp is subscribed
if (!subscribed) return (false, 0);
// check if using next price is allowed
if (_nextPrice > 0 && !holder.nextPriceEnabled) return (false, 0);
// check if boost and boost allowed
if (_method == Method.Boost && !holder.boostEnabled) return (false, 0);
// check if owner is still owner
if (getOwner(_cdpId) != holder.owner) return (false, 0);
uint currRatio = getRatio(_cdpId, _nextPrice);
if (_method == Method.Repay) {
return (currRatio < holder.minRatio, currRatio);
} else if (_method == Method.Boost) {
return (currRatio > holder.maxRatio, currRatio);
}
}
/// @dev After the Boost/Repay check if the ratio doesn't trigger another call
function ratioGoodAfter(Method _method, uint _cdpId, uint _nextPrice) public view returns(bool, uint) {
CdpHolder memory holder;
(, holder) = subscriptionsContract.getCdpHolder(_cdpId);
uint currRatio = getRatio(_cdpId, _nextPrice);
if (_method == Method.Repay) {
return (currRatio < holder.maxRatio, currRatio);
} else if (_method == Method.Boost) {
return (currRatio > holder.minRatio, currRatio);
}
}
/// @notice Calculates gas cost (in Eth) of tx
/// @dev Gas price is limited to MAX_GAS_PRICE to prevent attack of draining user CDP
/// @param _gasAmount Amount of gas used for the tx
function calcGasCost(uint _gasAmount) public view returns (uint) {
uint gasPrice = tx.gasprice <= MAX_GAS_PRICE ? tx.gasprice : MAX_GAS_PRICE;
return mul(gasPrice, _gasAmount);
}
/******************* OWNER ONLY OPERATIONS ********************************/
/// @notice Allows owner to change gas cost for boost operation, but only up to 3 millions
/// @param _gasCost New gas cost for boost method
function changeBoostGasCost(uint _gasCost) public onlyOwner {
require(_gasCost < 3000000);
BOOST_GAS_COST = _gasCost;
}
/// @notice Allows owner to change gas cost for repay operation, but only up to 3 millions
/// @param _gasCost New gas cost for repay method
function changeRepayGasCost(uint _gasCost) public onlyOwner {
require(_gasCost < 3000000);
REPAY_GAS_COST = _gasCost;
}
/// @notice Allows owner to change max gas price
/// @param _maxGasPrice New max gas price
function changeMaxGasPrice(uint _maxGasPrice) public onlyOwner {
require(_maxGasPrice < 500000000000);
MAX_GAS_PRICE = _maxGasPrice;
}
/// @notice Allows owner to change the amount of gas token burned per function call
/// @param _gasAmount Amount of gas token
/// @param _isRepay Flag to know for which function we are setting the gas token amount
function changeGasTokenAmount(uint _gasAmount, bool _isRepay) public onlyOwner {
if (_isRepay) {
REPAY_GAS_TOKEN = _gasAmount;
} else {
BOOST_GAS_TOKEN = _gasAmount;
}
}
}
contract MCDCloseFlashLoan is DFSExchangeCore, MCDSaverProxyHelper, FlashLoanReceiverBase, AdminAuth {
ILendingPoolAddressesProvider public LENDING_POOL_ADDRESS_PROVIDER = ILendingPoolAddressesProvider(0x24a42fD28C976A61Df5D00D0599C34c4f90748c8);
uint public constant SERVICE_FEE = 400; // 0.25% Fee
bytes32 internal constant ETH_ILK = 0x4554482d41000000000000000000000000000000000000000000000000000000;
address public constant DAI_ADDRESS = 0x6B175474E89094C44Da98b954EedeAC495271d0F;
address public constant DAI_JOIN_ADDRESS = 0x9759A6Ac90977b93B58547b4A71c78317f391A28;
address public constant SPOTTER_ADDRESS = 0x65C79fcB50Ca1594B025960e539eD7A9a6D434A3;
address public constant VAT_ADDRESS = 0x35D1b3F3D7966A1DFe207aa4514C12a259A0492B;
Manager public constant manager = Manager(0x5ef30b9986345249bc32d8928B7ee64DE9435E39);
DaiJoin public constant daiJoin = DaiJoin(DAI_JOIN_ADDRESS);
Spotter public constant spotter = Spotter(SPOTTER_ADDRESS);
Vat public constant vat = Vat(VAT_ADDRESS);
struct CloseData {
uint cdpId;
uint collAmount;
uint daiAmount;
uint minAccepted;
address joinAddr;
address proxy;
uint flFee;
bool toDai;
address reserve;
uint amount;
}
constructor() FlashLoanReceiverBase(LENDING_POOL_ADDRESS_PROVIDER) public {}
function executeOperation(
address _reserve,
uint256 _amount,
uint256 _fee,
bytes calldata _params)
external override {
(address proxy, bytes memory packedData) = abi.decode(_params, (address,bytes));
(MCDCloseTaker.CloseData memory closeDataSent, ExchangeData memory exchangeData) = abi.decode(packedData, (MCDCloseTaker.CloseData,ExchangeData));
CloseData memory closeData = CloseData({
cdpId: closeDataSent.cdpId,
collAmount: closeDataSent.collAmount,
daiAmount: closeDataSent.daiAmount,
minAccepted: closeDataSent.minAccepted,
joinAddr: closeDataSent.joinAddr,
proxy: proxy,
flFee: _fee,
toDai: closeDataSent.toDai,
reserve: _reserve,
amount: _amount
});
address user = DSProxy(payable(closeData.proxy)).owner();
exchangeData.dfsFeeDivider = SERVICE_FEE;
exchangeData.user = user;
closeCDP(closeData, exchangeData, user);
}
function closeCDP(
CloseData memory _closeData,
ExchangeData memory _exchangeData,
address _user
) internal {
paybackDebt(_closeData.cdpId, manager.ilks(_closeData.cdpId), _closeData.daiAmount); // payback whole debt
uint drawnAmount = drawMaxCollateral(_closeData.cdpId, _closeData.joinAddr, _closeData.collAmount); // draw whole collateral
uint daiSwaped = 0;
if (_closeData.toDai) {
_exchangeData.srcAmount = drawnAmount;
(, daiSwaped) = _sell(_exchangeData);
} else {
_exchangeData.destAmount = _closeData.daiAmount;
(, daiSwaped) = _buy(_exchangeData);
}
address tokenAddr = getVaultCollAddr(_closeData.joinAddr);
if (_closeData.toDai) {
tokenAddr = DAI_ADDRESS;
}
require(getBalance(tokenAddr) >= _closeData.minAccepted, "Below min. number of eth specified");
transferFundsBackToPoolInternal(_closeData.reserve, _closeData.amount.add(_closeData.flFee));
sendLeftover(tokenAddr, DAI_ADDRESS, payable(_user));
}
function drawMaxCollateral(uint _cdpId, address _joinAddr, uint _amount) internal returns (uint) {
manager.frob(_cdpId, -toPositiveInt(_amount), 0);
manager.flux(_cdpId, address(this), _amount);
uint joinAmount = _amount;
if (Join(_joinAddr).dec() != 18) {
joinAmount = _amount / (10 ** (18 - Join(_joinAddr).dec()));
}
Join(_joinAddr).exit(address(this), joinAmount);
if (isEthJoinAddr(_joinAddr)) {
Join(_joinAddr).gem().withdraw(joinAmount); // Weth -> Eth
}
return joinAmount;
}
function paybackDebt(uint _cdpId, bytes32 _ilk, uint _daiAmount) internal {
address urn = manager.urns(_cdpId);
daiJoin.dai().approve(DAI_JOIN_ADDRESS, _daiAmount);
daiJoin.join(urn, _daiAmount);
manager.frob(_cdpId, 0, normalizePaybackAmount(VAT_ADDRESS, urn, _ilk));
}
function getVaultCollAddr(address _joinAddr) internal view returns (address) {
address tokenAddr = address(Join(_joinAddr).gem());
if (tokenAddr == WETH_ADDRESS) {
return KYBER_ETH_ADDRESS;
}
return tokenAddr;
}
function getPrice(bytes32 _ilk) public view returns (uint256) {
(, uint256 mat) = spotter.ilks(_ilk);
(, , uint256 spot, , ) = vat.ilks(_ilk);
return rmul(rmul(spot, spotter.par()), mat);
}
receive() external override(FlashLoanReceiverBase, DFSExchangeCore) payable {}
}
contract MCDCloseTaker is MCDSaverProxyHelper {
address public constant SUBSCRIPTION_ADDRESS_NEW = 0xC45d4f6B6bf41b6EdAA58B01c4298B8d9078269a;
address public constant DEFISAVER_LOGGER = 0x5c55B921f590a89C1Ebe84dF170E655a82b62126;
ILendingPool public constant lendingPool = ILendingPool(0x398eC7346DcD622eDc5ae82352F02bE94C62d119);
// solhint-disable-next-line const-name-snakecase
Manager public constant manager = Manager(0x5ef30b9986345249bc32d8928B7ee64DE9435E39);
address public constant SPOTTER_ADDRESS = 0x65C79fcB50Ca1594B025960e539eD7A9a6D434A3;
address public constant VAT_ADDRESS = 0x35D1b3F3D7966A1DFe207aa4514C12a259A0492B;
address public constant DAI_ADDRESS = 0x6B175474E89094C44Da98b954EedeAC495271d0F;
// solhint-disable-next-line const-name-snakecase
DefisaverLogger public constant logger = DefisaverLogger(DEFISAVER_LOGGER);
struct CloseData {
uint cdpId;
address joinAddr;
uint collAmount;
uint daiAmount;
uint minAccepted;
bool wholeDebt;
bool toDai;
}
Vat public constant vat = Vat(VAT_ADDRESS);
Spotter public constant spotter = Spotter(SPOTTER_ADDRESS);
function closeWithLoan(
DFSExchangeData.ExchangeData memory _exchangeData,
CloseData memory _closeData,
address payable mcdCloseFlashLoan
) public payable {
mcdCloseFlashLoan.transfer(msg.value); // 0x fee
if (_closeData.wholeDebt) {
_closeData.daiAmount = getAllDebt(
VAT_ADDRESS,
manager.urns(_closeData.cdpId),
manager.urns(_closeData.cdpId),
manager.ilks(_closeData.cdpId)
);
(_closeData.collAmount, )
= getCdpInfo(manager, _closeData.cdpId, manager.ilks(_closeData.cdpId));
}
manager.cdpAllow(_closeData.cdpId, mcdCloseFlashLoan, 1);
bytes memory packedData = _packData(_closeData, _exchangeData);
bytes memory paramsData = abi.encode(address(this), packedData);
lendingPool.flashLoan(mcdCloseFlashLoan, DAI_ADDRESS, _closeData.daiAmount, paramsData);
manager.cdpAllow(_closeData.cdpId, mcdCloseFlashLoan, 0);
// If sub. to automatic protection unsubscribe
unsubscribe(SUBSCRIPTION_ADDRESS_NEW, _closeData.cdpId);
logger.Log(address(this), msg.sender, "MCDClose", abi.encode(_closeData.cdpId, _closeData.collAmount, _closeData.daiAmount, _closeData.toDai));
}
/// @notice Gets the maximum amount of debt available to generate
/// @param _cdpId Id of the CDP
/// @param _ilk Ilk of the CDP
function getMaxDebt(uint256 _cdpId, bytes32 _ilk) public view returns (uint256) {
uint256 price = getPrice(_ilk);
(, uint256 mat) = spotter.ilks(_ilk);
(uint256 collateral, uint256 debt) = getCdpInfo(manager, _cdpId, _ilk);
return sub(wdiv(wmul(collateral, price), mat), debt);
}
/// @notice Gets a price of the asset
/// @param _ilk Ilk of the CDP
function getPrice(bytes32 _ilk) public view returns (uint256) {
(, uint256 mat) = spotter.ilks(_ilk);
(, , uint256 spot, , ) = vat.ilks(_ilk);
return rmul(rmul(spot, spotter.par()), mat);
}
function unsubscribe(address _subContract, uint _cdpId) internal {
(, bool isSubscribed) = IMCDSubscriptions(_subContract).subscribersPos(_cdpId);
if (isSubscribed) {
IMCDSubscriptions(_subContract).unsubscribe(_cdpId);
}
}
function _packData(
CloseData memory _closeData,
DFSExchangeData.ExchangeData memory _exchangeData
) internal pure returns (bytes memory) {
return abi.encode(_closeData, _exchangeData);
}
}
contract MCDCreateFlashLoan is DFSExchangeCore, AdminAuth, FlashLoanReceiverBase {
address public constant CREATE_PROXY_ACTIONS = 0x6d0984E80a86f26c0dd564ca0CF74a8E9Da03305;
uint public constant SERVICE_FEE = 400; // 0.25% Fee
address public constant DAI_ADDRESS = 0x6B175474E89094C44Da98b954EedeAC495271d0F;
ILendingPoolAddressesProvider public LENDING_POOL_ADDRESS_PROVIDER = ILendingPoolAddressesProvider(0x24a42fD28C976A61Df5D00D0599C34c4f90748c8);
address public constant DAI_JOIN_ADDRESS = 0x9759A6Ac90977b93B58547b4A71c78317f391A28;
address public constant JUG_ADDRESS = 0x19c0976f590D67707E62397C87829d896Dc0f1F1;
address public constant MANAGER_ADDRESS = 0x5ef30b9986345249bc32d8928B7ee64DE9435E39;
constructor() FlashLoanReceiverBase(LENDING_POOL_ADDRESS_PROVIDER) public {}
function executeOperation(
address _reserve,
uint256 _amount,
uint256 _fee,
bytes calldata _params)
external override {
//check the contract has the specified balance
require(_amount <= getBalanceInternal(address(this), _reserve),
"Invalid balance for the contract");
(address proxy, bytes memory packedData) = abi.decode(_params, (address,bytes));
(MCDCreateTaker.CreateData memory createData, ExchangeData memory exchangeData) = abi.decode(packedData, (MCDCreateTaker.CreateData,ExchangeData));
exchangeData.dfsFeeDivider = SERVICE_FEE;
exchangeData.user = DSProxy(payable(proxy)).owner();
openAndLeverage(createData.collAmount, createData.daiAmount + _fee, createData.joinAddr, proxy, exchangeData);
transferFundsBackToPoolInternal(_reserve, _amount.add(_fee));
// if there is some eth left (0x fee), return it to user
if (address(this).balance > 0) {
tx.origin.transfer(address(this).balance);
}
}
function openAndLeverage(
uint _collAmount,
uint _daiAmountAndFee,
address _joinAddr,
address _proxy,
ExchangeData memory _exchangeData
) public {
(, uint256 collSwaped) = _sell(_exchangeData);
bytes32 ilk = Join(_joinAddr).ilk();
if (isEthJoinAddr(_joinAddr)) {
MCDCreateProxyActions(CREATE_PROXY_ACTIONS).openLockETHAndDraw{value: address(this).balance}(
MANAGER_ADDRESS,
JUG_ADDRESS,
_joinAddr,
DAI_JOIN_ADDRESS,
ilk,
_daiAmountAndFee,
_proxy
);
} else {
ERC20(address(Join(_joinAddr).gem())).safeApprove(CREATE_PROXY_ACTIONS, uint256(-1));
MCDCreateProxyActions(CREATE_PROXY_ACTIONS).openLockGemAndDraw(
MANAGER_ADDRESS,
JUG_ADDRESS,
_joinAddr,
DAI_JOIN_ADDRESS,
ilk,
(_collAmount + collSwaped),
_daiAmountAndFee,
true,
_proxy
);
}
}
/// @notice Checks if the join address is one of the Ether coll. types
/// @param _joinAddr Join address to check
function isEthJoinAddr(address _joinAddr) internal view returns (bool) {
// if it's dai_join_addr don't check gem() it will fail
if (_joinAddr == 0x9759A6Ac90977b93B58547b4A71c78317f391A28) return false;
// if coll is weth it's and eth type coll
if (address(Join(_joinAddr).gem()) == 0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2) {
return true;
}
return false;
}
receive() external override(FlashLoanReceiverBase, DFSExchangeCore) payable {}
}
contract MCDSaverProxy is DFSExchangeCore, MCDSaverProxyHelper {
uint public constant MANUAL_SERVICE_FEE = 400; // 0.25% Fee
uint public constant AUTOMATIC_SERVICE_FEE = 333; // 0.3% Fee
bytes32 public constant ETH_ILK = 0x4554482d41000000000000000000000000000000000000000000000000000000;
address public constant MANAGER_ADDRESS = 0x5ef30b9986345249bc32d8928B7ee64DE9435E39;
address public constant VAT_ADDRESS = 0x35D1b3F3D7966A1DFe207aa4514C12a259A0492B;
address public constant SPOTTER_ADDRESS = 0x65C79fcB50Ca1594B025960e539eD7A9a6D434A3;
address public constant DAI_JOIN_ADDRESS = 0x9759A6Ac90977b93B58547b4A71c78317f391A28;
address public constant JUG_ADDRESS = 0x19c0976f590D67707E62397C87829d896Dc0f1F1;
address public constant DAI_ADDRESS = 0x6B175474E89094C44Da98b954EedeAC495271d0F;
address public constant BOT_REGISTRY_ADDRESS = 0x637726f8b08a7ABE3aE3aCaB01A80E2d8ddeF77B;
Manager public constant manager = Manager(MANAGER_ADDRESS);
Vat public constant vat = Vat(VAT_ADDRESS);
DaiJoin public constant daiJoin = DaiJoin(DAI_JOIN_ADDRESS);
Spotter public constant spotter = Spotter(SPOTTER_ADDRESS);
DefisaverLogger public constant logger = DefisaverLogger(0x5c55B921f590a89C1Ebe84dF170E655a82b62126);
/// @notice Repay - draws collateral, converts to Dai and repays the debt
/// @dev Must be called by the DSProxy contract that owns the CDP
function repay(
ExchangeData memory _exchangeData,
uint _cdpId,
uint _gasCost,
address _joinAddr
) public payable {
address user = getOwner(manager, _cdpId);
bytes32 ilk = manager.ilks(_cdpId);
drawCollateral(_cdpId, _joinAddr, _exchangeData.srcAmount);
_exchangeData.user = user;
_exchangeData.dfsFeeDivider = isAutomation() ? AUTOMATIC_SERVICE_FEE : MANUAL_SERVICE_FEE;
(, uint daiAmount) = _sell(_exchangeData);
daiAmount -= takeFee(_gasCost, daiAmount);
paybackDebt(_cdpId, ilk, daiAmount, user);
// if there is some eth left (0x fee), return it to user
if (address(this).balance > 0) {
tx.origin.transfer(address(this).balance);
}
logger.Log(address(this), msg.sender, "MCDRepay", abi.encode(_cdpId, user, _exchangeData.srcAmount, daiAmount));
}
/// @notice Boost - draws Dai, converts to collateral and adds to CDP
/// @dev Must be called by the DSProxy contract that owns the CDP
function boost(
ExchangeData memory _exchangeData,
uint _cdpId,
uint _gasCost,
address _joinAddr
) public payable {
address user = getOwner(manager, _cdpId);
bytes32 ilk = manager.ilks(_cdpId);
uint daiDrawn = drawDai(_cdpId, ilk, _exchangeData.srcAmount);
_exchangeData.user = user;
_exchangeData.dfsFeeDivider = isAutomation() ? AUTOMATIC_SERVICE_FEE : MANUAL_SERVICE_FEE;
_exchangeData.srcAmount = daiDrawn - takeFee(_gasCost, daiDrawn);
(, uint swapedColl) = _sell(_exchangeData);
addCollateral(_cdpId, _joinAddr, swapedColl);
// if there is some eth left (0x fee), return it to user
if (address(this).balance > 0) {
tx.origin.transfer(address(this).balance);
}
logger.Log(address(this), msg.sender, "MCDBoost", abi.encode(_cdpId, user, _exchangeData.srcAmount, swapedColl));
}
/// @notice Draws Dai from the CDP
/// @dev If _daiAmount is bigger than max available we'll draw max
/// @param _cdpId Id of the CDP
/// @param _ilk Ilk of the CDP
/// @param _daiAmount Amount of Dai to draw
function drawDai(uint _cdpId, bytes32 _ilk, uint _daiAmount) internal returns (uint) {
uint rate = Jug(JUG_ADDRESS).drip(_ilk);
uint daiVatBalance = vat.dai(manager.urns(_cdpId));
uint maxAmount = getMaxDebt(_cdpId, _ilk);
if (_daiAmount >= maxAmount) {
_daiAmount = sub(maxAmount, 1);
}
manager.frob(_cdpId, int(0), normalizeDrawAmount(_daiAmount, rate, daiVatBalance));
manager.move(_cdpId, address(this), toRad(_daiAmount));
if (vat.can(address(this), address(DAI_JOIN_ADDRESS)) == 0) {
vat.hope(DAI_JOIN_ADDRESS);
}
DaiJoin(DAI_JOIN_ADDRESS).exit(address(this), _daiAmount);
return _daiAmount;
}
/// @notice Adds collateral to the CDP
/// @param _cdpId Id of the CDP
/// @param _joinAddr Address of the join contract for the CDP collateral
/// @param _amount Amount of collateral to add
function addCollateral(uint _cdpId, address _joinAddr, uint _amount) internal {
int convertAmount = 0;
if (isEthJoinAddr(_joinAddr)) {
Join(_joinAddr).gem().deposit{value: _amount}();
convertAmount = toPositiveInt(_amount);
} else {
convertAmount = toPositiveInt(convertTo18(_joinAddr, _amount));
}
ERC20(address(Join(_joinAddr).gem())).safeApprove(_joinAddr, _amount);
Join(_joinAddr).join(address(this), _amount);
vat.frob(
manager.ilks(_cdpId),
manager.urns(_cdpId),
address(this),
address(this),
convertAmount,
0
);
}
/// @notice Draws collateral and returns it to DSProxy
/// @dev If _amount is bigger than max available we'll draw max
/// @param _cdpId Id of the CDP
/// @param _joinAddr Address of the join contract for the CDP collateral
/// @param _amount Amount of collateral to draw
function drawCollateral(uint _cdpId, address _joinAddr, uint _amount) internal returns (uint) {
uint frobAmount = _amount;
if (Join(_joinAddr).dec() != 18) {
frobAmount = _amount * (10 ** (18 - Join(_joinAddr).dec()));
}
manager.frob(_cdpId, -toPositiveInt(frobAmount), 0);
manager.flux(_cdpId, address(this), frobAmount);
Join(_joinAddr).exit(address(this), _amount);
if (isEthJoinAddr(_joinAddr)) {
Join(_joinAddr).gem().withdraw(_amount); // Weth -> Eth
}
return _amount;
}
/// @notice Paybacks Dai debt
/// @dev If the _daiAmount is bigger than the whole debt, returns extra Dai
/// @param _cdpId Id of the CDP
/// @param _ilk Ilk of the CDP
/// @param _daiAmount Amount of Dai to payback
/// @param _owner Address that owns the DSProxy that owns the CDP
function paybackDebt(uint _cdpId, bytes32 _ilk, uint _daiAmount, address _owner) internal {
address urn = manager.urns(_cdpId);
uint wholeDebt = getAllDebt(VAT_ADDRESS, urn, urn, _ilk);
if (_daiAmount > wholeDebt) {
ERC20(DAI_ADDRESS).transfer(_owner, sub(_daiAmount, wholeDebt));
_daiAmount = wholeDebt;
}
if (ERC20(DAI_ADDRESS).allowance(address(this), DAI_JOIN_ADDRESS) == 0) {
ERC20(DAI_ADDRESS).approve(DAI_JOIN_ADDRESS, uint(-1));
}
daiJoin.join(urn, _daiAmount);
manager.frob(_cdpId, 0, normalizePaybackAmount(VAT_ADDRESS, urn, _ilk));
}
/// @notice Gets the maximum amount of collateral available to draw
/// @param _cdpId Id of the CDP
/// @param _ilk Ilk of the CDP
/// @param _joinAddr Joind address of collateral
/// @dev Substracts 10 wei to aviod rounding error later on
function getMaxCollateral(uint _cdpId, bytes32 _ilk, address _joinAddr) public view returns (uint) {
uint price = getPrice(_ilk);
(uint collateral, uint debt) = getCdpInfo(manager, _cdpId, _ilk);
(, uint mat) = Spotter(SPOTTER_ADDRESS).ilks(_ilk);
uint maxCollateral = sub(collateral, (div(mul(mat, debt), price)));
uint normalizeMaxCollateral = maxCollateral / (10 ** (18 - Join(_joinAddr).dec()));
// take one percent due to precision issues
return normalizeMaxCollateral * 99 / 100;
}
/// @notice Gets the maximum amount of debt available to generate
/// @param _cdpId Id of the CDP
/// @param _ilk Ilk of the CDP
/// @dev Substracts 10 wei to aviod rounding error later on
function getMaxDebt(uint _cdpId, bytes32 _ilk) public virtual view returns (uint) {
uint price = getPrice(_ilk);
(, uint mat) = spotter.ilks(_ilk);
(uint collateral, uint debt) = getCdpInfo(manager, _cdpId, _ilk);
return sub(sub(div(mul(collateral, price), mat), debt), 10);
}
/// @notice Gets a price of the asset
/// @param _ilk Ilk of the CDP
function getPrice(bytes32 _ilk) public view returns (uint) {
(, uint mat) = spotter.ilks(_ilk);
(,,uint spot,,) = vat.ilks(_ilk);
return rmul(rmul(spot, spotter.par()), mat);
}
/// @notice Gets CDP ratio
/// @param _cdpId Id of the CDP
/// @param _ilk Ilk of the CDP
function getRatio(uint _cdpId, bytes32 _ilk) public view returns (uint) {
uint price = getPrice( _ilk);
(uint collateral, uint debt) = getCdpInfo(manager, _cdpId, _ilk);
if (debt == 0) return 0;
return rdiv(wmul(collateral, price), debt);
}
/// @notice Gets CDP info (collateral, debt, price, ilk)
/// @param _cdpId Id of the CDP
function getCdpDetailedInfo(uint _cdpId) public view returns (uint collateral, uint debt, uint price, bytes32 ilk) {
address urn = manager.urns(_cdpId);
ilk = manager.ilks(_cdpId);
(collateral, debt) = vat.urns(ilk, urn);
(,uint rate,,,) = vat.ilks(ilk);
debt = rmul(debt, rate);
price = getPrice(ilk);
}
function isAutomation() internal view returns(bool) {
return BotRegistry(BOT_REGISTRY_ADDRESS).botList(tx.origin);
}
function takeFee(uint256 _gasCost, uint _amount) internal returns(uint) {
if (_gasCost > 0) {
uint ethDaiPrice = getPrice(ETH_ILK);
uint feeAmount = rmul(_gasCost, ethDaiPrice);
uint balance = ERC20(DAI_ADDRESS).balanceOf(address(this));
if (feeAmount > _amount / 10) {
feeAmount = _amount / 10;
}
ERC20(DAI_ADDRESS).transfer(WALLET_ID, feeAmount);
return feeAmount;
}
return 0;
}
}
contract MCDSaverTaker is MCDSaverProxy, GasBurner {
address payable public constant MCD_SAVER_FLASH_LOAN = 0xD0eB57ff3eA4Def2b74dc29681fd529D1611880f;
address public constant AAVE_POOL_CORE = 0x3dfd23A6c5E8BbcFc9581d2E864a68feb6a076d3;
ILendingPool public constant lendingPool = ILendingPool(0x398eC7346DcD622eDc5ae82352F02bE94C62d119);
function boostWithLoan(
ExchangeData memory _exchangeData,
uint _cdpId,
uint _gasCost,
address _joinAddr
) public payable burnGas(25) {
uint256 maxDebt = getMaxDebt(_cdpId, manager.ilks(_cdpId));
uint maxLiq = getAvailableLiquidity(DAI_JOIN_ADDRESS);
if (maxDebt >= _exchangeData.srcAmount || maxLiq == 0) {
if (_exchangeData.srcAmount > maxDebt) {
_exchangeData.srcAmount = maxDebt;
}
boost(_exchangeData, _cdpId, _gasCost, _joinAddr);
return;
}
uint256 loanAmount = sub(_exchangeData.srcAmount, maxDebt);
loanAmount = loanAmount > maxLiq ? maxLiq : loanAmount;
MCD_SAVER_FLASH_LOAN.transfer(msg.value); // 0x fee
manager.cdpAllow(_cdpId, MCD_SAVER_FLASH_LOAN, 1);
bytes memory paramsData = abi.encode(packExchangeData(_exchangeData), _cdpId, _gasCost, _joinAddr, false);
lendingPool.flashLoan(MCD_SAVER_FLASH_LOAN, DAI_ADDRESS, loanAmount, paramsData);
manager.cdpAllow(_cdpId, MCD_SAVER_FLASH_LOAN, 0);
}
function repayWithLoan(
ExchangeData memory _exchangeData,
uint _cdpId,
uint _gasCost,
address _joinAddr
) public payable burnGas(25) {
uint256 maxColl = getMaxCollateral(_cdpId, manager.ilks(_cdpId), _joinAddr);
uint maxLiq = getAvailableLiquidity(_joinAddr);
if (maxColl >= _exchangeData.srcAmount || maxLiq == 0) {
if (_exchangeData.srcAmount > maxColl) {
_exchangeData.srcAmount = maxColl;
}
repay(_exchangeData, _cdpId, _gasCost, _joinAddr);
return;
}
uint256 loanAmount = sub(_exchangeData.srcAmount, maxColl);
loanAmount = loanAmount > maxLiq ? maxLiq : loanAmount;
MCD_SAVER_FLASH_LOAN.transfer(msg.value); // 0x fee
manager.cdpAllow(_cdpId, MCD_SAVER_FLASH_LOAN, 1);
bytes memory paramsData = abi.encode(packExchangeData(_exchangeData), _cdpId, _gasCost, _joinAddr, true);
lendingPool.flashLoan(MCD_SAVER_FLASH_LOAN, getAaveCollAddr(_joinAddr), loanAmount, paramsData);
manager.cdpAllow(_cdpId, MCD_SAVER_FLASH_LOAN, 0);
}
/// @notice Gets the maximum amount of debt available to generate
/// @param _cdpId Id of the CDP
/// @param _ilk Ilk of the CDP
function getMaxDebt(uint256 _cdpId, bytes32 _ilk) public override view returns (uint256) {
uint256 price = getPrice(_ilk);
(, uint256 mat) = spotter.ilks(_ilk);
(uint256 collateral, uint256 debt) = getCdpInfo(manager, _cdpId, _ilk);
return sub(wdiv(wmul(collateral, price), mat), debt);
}
function getAaveCollAddr(address _joinAddr) internal view returns (address) {
if (isEthJoinAddr(_joinAddr)
|| _joinAddr == 0x775787933e92b709f2a3C70aa87999696e74A9F8) {
return KYBER_ETH_ADDRESS;
} else if (_joinAddr == DAI_JOIN_ADDRESS) {
return DAI_ADDRESS;
} else
{
return getCollateralAddr(_joinAddr);
}
}
function getAvailableLiquidity(address _joinAddr) internal view returns (uint liquidity) {
address tokenAddr = getAaveCollAddr(_joinAddr);
if (tokenAddr == KYBER_ETH_ADDRESS) {
liquidity = AAVE_POOL_CORE.balance;
} else {
liquidity = ERC20(tokenAddr).balanceOf(AAVE_POOL_CORE);
}
}
}
contract SavingsProxy is DSRSavingsProtocol, CompoundSavingsProtocol {
address public constant ADAI_ADDRESS = 0xfC1E690f61EFd961294b3e1Ce3313fBD8aa4f85d;
address public constant SAVINGS_DYDX_ADDRESS = 0x03b1565e070df392e48e7a8e01798C4B00E534A5;
address public constant SAVINGS_AAVE_ADDRESS = 0x535B9035E9bA8D7efe0FeAEac885fb65b303E37C;
address public constant NEW_IDAI_ADDRESS = 0x493C57C4763932315A328269E1ADaD09653B9081;
address public constant COMP_ADDRESS = 0x3d9819210A31b4961b30EF54bE2aeD79B9c9Cd3B;
address public constant SAVINGS_LOGGER_ADDRESS = 0x89b3635BD2bAD145C6f92E82C9e83f06D5654984;
address public constant SOLO_MARGIN_ADDRESS = 0x1E0447b19BB6EcFdAe1e4AE1694b0C3659614e4e;
enum SavingsProtocol {Compound, Dydx, Fulcrum, Dsr, Aave}
function deposit(SavingsProtocol _protocol, uint256 _amount) public {
if (_protocol == SavingsProtocol.Dsr) {
dsrDeposit(_amount, true);
} else if (_protocol == SavingsProtocol.Compound) {
compDeposit(msg.sender, _amount);
} else {
_deposit(_protocol, _amount, true);
}
SavingsLogger(SAVINGS_LOGGER_ADDRESS).logDeposit(msg.sender, uint8(_protocol), _amount);
}
function withdraw(SavingsProtocol _protocol, uint256 _amount) public {
if (_protocol == SavingsProtocol.Dsr) {
dsrWithdraw(_amount, true);
} else if (_protocol == SavingsProtocol.Compound) {
compWithdraw(msg.sender, _amount);
} else {
_withdraw(_protocol, _amount, true);
}
SavingsLogger(SAVINGS_LOGGER_ADDRESS).logWithdraw(msg.sender, uint8(_protocol), _amount);
}
function swap(SavingsProtocol _from, SavingsProtocol _to, uint256 _amount) public {
if (_from == SavingsProtocol.Dsr) {
dsrWithdraw(_amount, false);
} else if (_from == SavingsProtocol.Compound) {
compWithdraw(msg.sender, _amount);
} else {
_withdraw(_from, _amount, false);
}
// possible to withdraw 1-2 wei less than actual amount due to division precision
// so we deposit all amount on DSProxy
uint256 amountToDeposit = ERC20(DAI_ADDRESS).balanceOf(address(this));
if (_to == SavingsProtocol.Dsr) {
dsrDeposit(amountToDeposit, false);
} else if (_from == SavingsProtocol.Compound) {
compDeposit(msg.sender, _amount);
} else {
_deposit(_to, amountToDeposit, false);
}
SavingsLogger(SAVINGS_LOGGER_ADDRESS).logSwap(
msg.sender,
uint8(_from),
uint8(_to),
_amount
);
}
function withdrawDai() public {
ERC20(DAI_ADDRESS).transfer(msg.sender, ERC20(DAI_ADDRESS).balanceOf(address(this)));
}
function claimComp() public {
ComptrollerInterface(COMP_ADDRESS).claimComp(address(this));
}
function getAddress(SavingsProtocol _protocol) public pure returns (address) {
if (_protocol == SavingsProtocol.Dydx) {
return SAVINGS_DYDX_ADDRESS;
}
if (_protocol == SavingsProtocol.Aave) {
return SAVINGS_AAVE_ADDRESS;
}
}
function _deposit(SavingsProtocol _protocol, uint256 _amount, bool _fromUser) internal {
if (_fromUser) {
ERC20(DAI_ADDRESS).transferFrom(msg.sender, address(this), _amount);
}
approveDeposit(_protocol);
ProtocolInterface(getAddress(_protocol)).deposit(address(this), _amount);
endAction(_protocol);
}
function _withdraw(SavingsProtocol _protocol, uint256 _amount, bool _toUser) public {
approveWithdraw(_protocol);
ProtocolInterface(getAddress(_protocol)).withdraw(address(this), _amount);
endAction(_protocol);
if (_toUser) {
withdrawDai();
}
}
function endAction(SavingsProtocol _protocol) internal {
if (_protocol == SavingsProtocol.Dydx) {
setDydxOperator(false);
}
}
function approveDeposit(SavingsProtocol _protocol) internal {
if (_protocol == SavingsProtocol.Compound || _protocol == SavingsProtocol.Fulcrum || _protocol == SavingsProtocol.Aave) {
ERC20(DAI_ADDRESS).approve(getAddress(_protocol), uint256(-1));
}
if (_protocol == SavingsProtocol.Dydx) {
ERC20(DAI_ADDRESS).approve(SOLO_MARGIN_ADDRESS, uint256(-1));
setDydxOperator(true);
}
}
function approveWithdraw(SavingsProtocol _protocol) internal {
if (_protocol == SavingsProtocol.Compound) {
ERC20(NEW_CDAI_ADDRESS).approve(getAddress(_protocol), uint256(-1));
}
if (_protocol == SavingsProtocol.Dydx) {
setDydxOperator(true);
}
if (_protocol == SavingsProtocol.Fulcrum) {
ERC20(NEW_IDAI_ADDRESS).approve(getAddress(_protocol), uint256(-1));
}
if (_protocol == SavingsProtocol.Aave) {
ERC20(ADAI_ADDRESS).approve(getAddress(_protocol), uint256(-1));
}
}
function setDydxOperator(bool _trusted) internal {
ISoloMargin.OperatorArg[] memory operatorArgs = new ISoloMargin.OperatorArg[](1);
operatorArgs[0] = ISoloMargin.OperatorArg({
operator: getAddress(SavingsProtocol.Dydx),
trusted: _trusted
});
ISoloMargin(SOLO_MARGIN_ADDRESS).setOperators(operatorArgs);
}
}
contract LoanShifterReceiver is SaverExchangeCore, FlashLoanReceiverBase, AdminAuth {
address payable public constant WALLET_ADDR = 0x322d58b9E75a6918f7e7849AEe0fF09369977e08;
address public constant DISCOUNT_ADDR = 0x1b14E8D511c9A4395425314f849bD737BAF8208F;
ILendingPoolAddressesProvider public LENDING_POOL_ADDRESS_PROVIDER = ILendingPoolAddressesProvider(0x24a42fD28C976A61Df5D00D0599C34c4f90748c8);
address public constant ETH_ADDRESS = 0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE;
ShifterRegistry public constant shifterRegistry = ShifterRegistry(0x597C52281b31B9d949a9D8fEbA08F7A2530a965e);
struct ParamData {
bytes proxyData1;
bytes proxyData2;
address proxy;
address debtAddr;
uint8 protocol1;
uint8 protocol2;
uint8 swapType;
}
constructor() FlashLoanReceiverBase(LENDING_POOL_ADDRESS_PROVIDER) public {}
function executeOperation(
address _reserve,
uint256 _amount,
uint256 _fee,
bytes calldata _params)
external override {
// Format the call data for DSProxy
(ParamData memory paramData, ExchangeData memory exchangeData)
= packFunctionCall(_amount, _fee, _params);
address protocolAddr1 = shifterRegistry.getAddr(getNameByProtocol(paramData.protocol1));
address protocolAddr2 = shifterRegistry.getAddr(getNameByProtocol(paramData.protocol2));
// Send Flash loan amount to DSProxy
sendToProxy(payable(paramData.proxy), _reserve, _amount);
// Execute the Close/Change debt operation
DSProxyInterface(paramData.proxy).execute(protocolAddr1, paramData.proxyData1);
if (paramData.swapType == 1) { // COLL_SWAP
exchangeData.srcAmount -= getFee(getBalance(exchangeData.srcAddr), exchangeData.srcAddr, paramData.proxy);
(, uint amount) = _sell(exchangeData);
sendToProxy(payable(paramData.proxy), exchangeData.destAddr, amount);
} else if (paramData.swapType == 2) { // DEBT_SWAP
exchangeData.srcAmount -= getFee(exchangeData.srcAmount, exchangeData.srcAddr, paramData.proxy);
exchangeData.destAmount = (_amount + _fee);
_buy(exchangeData);
// Send extra to DSProxy
sendToProxy(payable(paramData.proxy), exchangeData.srcAddr, ERC20(exchangeData.srcAddr).balanceOf(address(this)));
} else { // NO_SWAP just send tokens to proxy
sendToProxy(payable(paramData.proxy), exchangeData.srcAddr, getBalance(exchangeData.srcAddr));
}
// Execute the Open operation
DSProxyInterface(paramData.proxy).execute(protocolAddr2, paramData.proxyData2);
// Repay FL
transferFundsBackToPoolInternal(_reserve, _amount.add(_fee));
// if there is some eth left (0x fee), return it to user
if (address(this).balance > 0) {
tx.origin.transfer(address(this).balance);
}
}
function packFunctionCall(uint _amount, uint _fee, bytes memory _params)
internal pure returns (ParamData memory paramData, ExchangeData memory exchangeData) {
(
uint[8] memory numData, // collAmount, debtAmount, id1, id2, srcAmount, destAmount, minPrice, price0x
address[8] memory addrData, // addrLoan1, addrLoan2, debtAddr1, debtAddr2, srcAddr, destAddr, exchangeAddr, wrapper
uint8[3] memory enumData, // fromProtocol, toProtocol, swapType
bytes memory callData,
address proxy
)
= abi.decode(_params, (uint256[8],address[8],uint8[3],bytes,address));
bytes memory proxyData1;
bytes memory proxyData2;
uint openDebtAmount = (_amount + _fee);
if (enumData[0] == 0) { // MAKER FROM
proxyData1 = abi.encodeWithSignature("close(uint256,address,uint256,uint256)", numData[2], addrData[0], _amount, numData[0]);
} else if(enumData[0] == 1) { // COMPOUND FROM
if (enumData[2] == 2) { // DEBT_SWAP
proxyData1 = abi.encodeWithSignature("changeDebt(address,address,uint256,uint256)", addrData[2], addrData[3], _amount, numData[4]);
} else {
proxyData1 = abi.encodeWithSignature("close(address,address,uint256,uint256)", addrData[0], addrData[2], numData[0], numData[1]);
}
}
if (enumData[1] == 0) { // MAKER TO
proxyData2 = abi.encodeWithSignature("open(uint256,address,uint256)", numData[3], addrData[1], openDebtAmount);
} else if(enumData[1] == 1) { // COMPOUND TO
if (enumData[2] == 2) { // DEBT_SWAP
proxyData2 = abi.encodeWithSignature("repayAll(address)", addrData[3]);
} else {
proxyData2 = abi.encodeWithSignature("open(address,address,uint256)", addrData[1], addrData[3], openDebtAmount);
}
}
paramData = ParamData({
proxyData1: proxyData1,
proxyData2: proxyData2,
proxy: proxy,
debtAddr: addrData[2],
protocol1: enumData[0],
protocol2: enumData[1],
swapType: enumData[2]
});
exchangeData = SaverExchangeCore.ExchangeData({
srcAddr: addrData[4],
destAddr: addrData[5],
srcAmount: numData[4],
destAmount: numData[5],
minPrice: numData[6],
wrapper: addrData[7],
exchangeAddr: addrData[6],
callData: callData,
price0x: numData[7]
});
}
function sendToProxy(address payable _proxy, address _reserve, uint _amount) internal {
if (_reserve != ETH_ADDRESS) {
ERC20(_reserve).safeTransfer(_proxy, _amount);
}
_proxy.transfer(address(this).balance);
}
function getNameByProtocol(uint8 _proto) internal pure returns (string memory) {
if (_proto == 0) {
return "MCD_SHIFTER";
} else if (_proto == 1) {
return "COMP_SHIFTER";
}
}
function getFee(uint _amount, address _tokenAddr, address _proxy) internal returns (uint feeAmount) {
uint fee = 400;
DSProxyInterface proxy = DSProxyInterface(payable(_proxy));
address user = proxy.owner();
if (Discount(DISCOUNT_ADDR).isCustomFeeSet(user)) {
fee = Discount(DISCOUNT_ADDR).getCustomServiceFee(user);
}
feeAmount = (fee == 0) ? 0 : (_amount / fee);
// fee can't go over 20% of the whole amount
if (feeAmount > (_amount / 5)) {
feeAmount = _amount / 5;
}
if (_tokenAddr == ETH_ADDRESS) {
WALLET_ADDR.transfer(feeAmount);
} else {
ERC20(_tokenAddr).safeTransfer(WALLET_ADDR, feeAmount);
}
}
receive() external override(FlashLoanReceiverBase, SaverExchangeCore) payable {}
}
contract LoanShifterTaker is AdminAuth, ProxyPermission, GasBurner {
ILendingPool public constant lendingPool = ILendingPool(0x398eC7346DcD622eDc5ae82352F02bE94C62d119);
address public constant ETH_ADDRESS = 0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE;
address public constant DAI_ADDRESS = 0x6B175474E89094C44Da98b954EedeAC495271d0F;
address public constant MCD_SUB_ADDRESS = 0xC45d4f6B6bf41b6EdAA58B01c4298B8d9078269a;
address public constant COMPOUND_SUB_ADDRESS = 0x52015EFFD577E08f498a0CCc11905925D58D6207;
address public constant MANAGER_ADDRESS = 0x5ef30b9986345249bc32d8928B7ee64DE9435E39;
address public constant DEFISAVER_LOGGER = 0x5c55B921f590a89C1Ebe84dF170E655a82b62126;
Manager public constant manager = Manager(MANAGER_ADDRESS);
ShifterRegistry public constant shifterRegistry = ShifterRegistry(0x597C52281b31B9d949a9D8fEbA08F7A2530a965e);
enum Protocols { MCD, COMPOUND }
enum SwapType { NO_SWAP, COLL_SWAP, DEBT_SWAP }
enum Unsub { NO_UNSUB, FIRST_UNSUB, SECOND_UNSUB, BOTH_UNSUB }
struct LoanShiftData {
Protocols fromProtocol;
Protocols toProtocol;
SwapType swapType;
Unsub unsub;
bool wholeDebt;
uint collAmount;
uint debtAmount;
address debtAddr1;
address debtAddr2;
address addrLoan1;
address addrLoan2;
uint id1;
uint id2;
}
/// @notice Main entry point, it will move or transform a loan
/// @dev Called through DSProxy
function moveLoan(
SaverExchangeCore.ExchangeData memory _exchangeData,
LoanShiftData memory _loanShift
) public payable burnGas(20) {
if (_isSameTypeVaults(_loanShift)) {
_forkVault(_loanShift);
logEvent(_exchangeData, _loanShift);
return;
}
_callCloseAndOpen(_exchangeData, _loanShift);
}
//////////////////////// INTERNAL FUNCTIONS //////////////////////////
function _callCloseAndOpen(
SaverExchangeCore.ExchangeData memory _exchangeData,
LoanShiftData memory _loanShift
) internal {
address protoAddr = shifterRegistry.getAddr(getNameByProtocol(uint8(_loanShift.fromProtocol)));
if (_loanShift.wholeDebt) {
_loanShift.debtAmount = ILoanShifter(protoAddr).getLoanAmount(_loanShift.id1, _loanShift.debtAddr1);
}
(
uint[8] memory numData,
address[8] memory addrData,
uint8[3] memory enumData,
bytes memory callData
)
= _packData(_loanShift, _exchangeData);
// encode data
bytes memory paramsData = abi.encode(numData, addrData, enumData, callData, address(this));
address payable loanShifterReceiverAddr = payable(shifterRegistry.getAddr("LOAN_SHIFTER_RECEIVER"));
loanShifterReceiverAddr.transfer(address(this).balance);
// call FL
givePermission(loanShifterReceiverAddr);
lendingPool.flashLoan(loanShifterReceiverAddr,
getLoanAddr(_loanShift.debtAddr1, _loanShift.fromProtocol), _loanShift.debtAmount, paramsData);
removePermission(loanShifterReceiverAddr);
unsubFromAutomation(
_loanShift.unsub,
_loanShift.id1,
_loanShift.id2,
_loanShift.fromProtocol,
_loanShift.toProtocol
);
logEvent(_exchangeData, _loanShift);
}
function _forkVault(LoanShiftData memory _loanShift) internal {
// Create new Vault to move to
if (_loanShift.id2 == 0) {
_loanShift.id2 = manager.open(manager.ilks(_loanShift.id1), address(this));
}
if (_loanShift.wholeDebt) {
manager.shift(_loanShift.id1, _loanShift.id2);
}
}
function _isSameTypeVaults(LoanShiftData memory _loanShift) internal pure returns (bool) {
return _loanShift.fromProtocol == Protocols.MCD && _loanShift.toProtocol == Protocols.MCD
&& _loanShift.addrLoan1 == _loanShift.addrLoan2;
}
function getNameByProtocol(uint8 _proto) internal pure returns (string memory) {
if (_proto == 0) {
return "MCD_SHIFTER";
} else if (_proto == 1) {
return "COMP_SHIFTER";
}
}
function getLoanAddr(address _address, Protocols _fromProtocol) internal returns (address) {
if (_fromProtocol == Protocols.COMPOUND) {
return CTokenInterface(_address).underlying();
} else if (_fromProtocol == Protocols.MCD) {
return DAI_ADDRESS;
} else {
return address(0);
}
}
function logEvent(
SaverExchangeCore.ExchangeData memory _exchangeData,
LoanShiftData memory _loanShift
) internal {
address srcAddr = _exchangeData.srcAddr;
address destAddr = _exchangeData.destAddr;
uint collAmount = _exchangeData.srcAmount;
uint debtAmount = _exchangeData.destAmount;
if (_loanShift.swapType == SwapType.NO_SWAP) {
srcAddr = _loanShift.addrLoan1;
destAddr = _loanShift.debtAddr1;
collAmount = _loanShift.collAmount;
debtAmount = _loanShift.debtAmount;
}
DefisaverLogger(DEFISAVER_LOGGER)
.Log(address(this), msg.sender, "LoanShifter",
abi.encode(
_loanShift.fromProtocol,
_loanShift.toProtocol,
_loanShift.swapType,
srcAddr,
destAddr,
collAmount,
debtAmount
));
}
function unsubFromAutomation(Unsub _unsub, uint _cdp1, uint _cdp2, Protocols _from, Protocols _to) internal {
if (_unsub != Unsub.NO_UNSUB) {
if (_unsub == Unsub.FIRST_UNSUB || _unsub == Unsub.BOTH_UNSUB) {
unsubscribe(_cdp1, _from);
}
if (_unsub == Unsub.SECOND_UNSUB || _unsub == Unsub.BOTH_UNSUB) {
unsubscribe(_cdp2, _to);
}
}
}
function unsubscribe(uint _cdpId, Protocols _protocol) internal {
if (_cdpId != 0 && _protocol == Protocols.MCD) {
IMCDSubscriptions(MCD_SUB_ADDRESS).unsubscribe(_cdpId);
}
if (_protocol == Protocols.COMPOUND) {
ICompoundSubscriptions(COMPOUND_SUB_ADDRESS).unsubscribe();
}
}
function _packData(
LoanShiftData memory _loanShift,
SaverExchangeCore.ExchangeData memory exchangeData
) internal pure returns (uint[8] memory numData, address[8] memory addrData, uint8[3] memory enumData, bytes memory callData) {
numData = [
_loanShift.collAmount,
_loanShift.debtAmount,
_loanShift.id1,
_loanShift.id2,
exchangeData.srcAmount,
exchangeData.destAmount,
exchangeData.minPrice,
exchangeData.price0x
];
addrData = [
_loanShift.addrLoan1,
_loanShift.addrLoan2,
_loanShift.debtAddr1,
_loanShift.debtAddr2,
exchangeData.srcAddr,
exchangeData.destAddr,
exchangeData.exchangeAddr,
exchangeData.wrapper
];
enumData = [
uint8(_loanShift.fromProtocol),
uint8(_loanShift.toProtocol),
uint8(_loanShift.swapType)
];
callData = exchangeData.callData;
}
}
contract CompShifter is CompoundSaverHelper {
using SafeERC20 for ERC20;
address public constant COMPTROLLER_ADDR = 0x3d9819210A31b4961b30EF54bE2aeD79B9c9Cd3B;
function getLoanAmount(uint _cdpId, address _joinAddr) public returns(uint loanAmount) {
return getWholeDebt(_cdpId, _joinAddr);
}
function getWholeDebt(uint _cdpId, address _joinAddr) public returns(uint loanAmount) {
return CTokenInterface(_joinAddr).borrowBalanceCurrent(msg.sender);
}
function close(
address _cCollAddr,
address _cBorrowAddr,
uint _collAmount,
uint _debtAmount
) public {
address collAddr = getUnderlyingAddr(_cCollAddr);
// payback debt
paybackDebt(_debtAmount, _cBorrowAddr, getUnderlyingAddr(_cBorrowAddr), tx.origin);
require(CTokenInterface(_cCollAddr).redeemUnderlying(_collAmount) == 0);
// Send back money to repay FL
if (collAddr == ETH_ADDRESS) {
msg.sender.transfer(address(this).balance);
} else {
ERC20(collAddr).safeTransfer(msg.sender, ERC20(collAddr).balanceOf(address(this)));
}
}
function changeDebt(
address _cBorrowAddrOld,
address _cBorrowAddrNew,
uint _debtAmountOld,
uint _debtAmountNew
) public {
address borrowAddrNew = getUnderlyingAddr(_cBorrowAddrNew);
// payback debt in one token
paybackDebt(_debtAmountOld, _cBorrowAddrOld, getUnderlyingAddr(_cBorrowAddrOld), tx.origin);
// draw debt in another one
borrowCompound(_cBorrowAddrNew, _debtAmountNew);
// Send back money to repay FL
if (borrowAddrNew == ETH_ADDRESS) {
msg.sender.transfer(address(this).balance);
} else {
ERC20(borrowAddrNew).safeTransfer(msg.sender, ERC20(borrowAddrNew).balanceOf(address(this)));
}
}
function open(
address _cCollAddr,
address _cBorrowAddr,
uint _debtAmount
) public {
address collAddr = getUnderlyingAddr(_cCollAddr);
address borrowAddr = getUnderlyingAddr(_cBorrowAddr);
uint collAmount = 0;
if (collAddr == ETH_ADDRESS) {
collAmount = address(this).balance;
} else {
collAmount = ERC20(collAddr).balanceOf(address(this));
}
depositCompound(collAddr, _cCollAddr, collAmount);
// draw debt
borrowCompound(_cBorrowAddr, _debtAmount);
// Send back money to repay FL
if (borrowAddr == ETH_ADDRESS) {
msg.sender.transfer(address(this).balance);
} else {
ERC20(borrowAddr).safeTransfer(msg.sender, ERC20(borrowAddr).balanceOf(address(this)));
}
}
function repayAll(address _cTokenAddr) public {
address tokenAddr = getUnderlyingAddr(_cTokenAddr);
uint amount = ERC20(tokenAddr).balanceOf(address(this));
if (amount != 0) {
paybackDebt(amount, _cTokenAddr, tokenAddr, tx.origin);
}
}
function depositCompound(address _tokenAddr, address _cTokenAddr, uint _amount) internal {
approveCToken(_tokenAddr, _cTokenAddr);
enterMarket(_cTokenAddr);
if (_tokenAddr != ETH_ADDRESS) {
require(CTokenInterface(_cTokenAddr).mint(_amount) == 0, "mint error");
} else {
CEtherInterface(_cTokenAddr).mint{value: _amount}();
}
}
function borrowCompound(address _cTokenAddr, uint _amount) internal {
enterMarket(_cTokenAddr);
require(CTokenInterface(_cTokenAddr).borrow(_amount) == 0);
}
function enterMarket(address _cTokenAddr) public {
address[] memory markets = new address[](1);
markets[0] = _cTokenAddr;
ComptrollerInterface(COMPTROLLER_ADDR).enterMarkets(markets);
}
}
contract McdShifter is MCDSaverProxy {
using SafeERC20 for ERC20;
address public constant OPEN_PROXY_ACTIONS = 0x6d0984E80a86f26c0dd564ca0CF74a8E9Da03305;
function getLoanAmount(uint _cdpId, address _joinAddr) public view virtual returns(uint loanAmount) {
bytes32 ilk = manager.ilks(_cdpId);
(, uint rate,,,) = vat.ilks(ilk);
(, uint art) = vat.urns(ilk, manager.urns(_cdpId));
uint dai = vat.dai(manager.urns(_cdpId));
uint rad = sub(mul(art, rate), dai);
loanAmount = rad / RAY;
loanAmount = mul(loanAmount, RAY) < rad ? loanAmount + 1 : loanAmount;
}
function close(
uint _cdpId,
address _joinAddr,
uint _loanAmount,
uint _collateral
) public {
address owner = getOwner(manager, _cdpId);
bytes32 ilk = manager.ilks(_cdpId);
(uint maxColl, ) = getCdpInfo(manager, _cdpId, ilk);
// repay dai debt cdp
paybackDebt(_cdpId, ilk, _loanAmount, owner);
maxColl = _collateral > maxColl ? maxColl : _collateral;
// withdraw collateral from cdp
drawCollateral(_cdpId, _joinAddr, maxColl);
// send back to msg.sender
if (isEthJoinAddr(_joinAddr)) {
msg.sender.transfer(address(this).balance);
} else {
ERC20 collToken = ERC20(getCollateralAddr(_joinAddr));
collToken.safeTransfer(msg.sender, collToken.balanceOf(address(this)));
}
}
function open(
uint _cdpId,
address _joinAddr,
uint _debtAmount
) public {
uint collAmount = 0;
if (isEthJoinAddr(_joinAddr)) {
collAmount = address(this).balance;
} else {
collAmount = ERC20(address(Join(_joinAddr).gem())).balanceOf(address(this));
}
if (_cdpId == 0) {
openAndWithdraw(collAmount, _debtAmount, address(this), _joinAddr);
} else {
// add collateral
addCollateral(_cdpId, _joinAddr, collAmount);
// draw debt
drawDai(_cdpId, manager.ilks(_cdpId), _debtAmount);
}
// transfer to repay FL
ERC20(DAI_ADDRESS).transfer(msg.sender, ERC20(DAI_ADDRESS).balanceOf(address(this)));
if (address(this).balance > 0) {
tx.origin.transfer(address(this).balance);
}
}
function openAndWithdraw(uint _collAmount, uint _debtAmount, address _proxy, address _joinAddrTo) internal {
bytes32 ilk = Join(_joinAddrTo).ilk();
if (isEthJoinAddr(_joinAddrTo)) {
MCDCreateProxyActions(OPEN_PROXY_ACTIONS).openLockETHAndDraw{value: address(this).balance}(
address(manager),
JUG_ADDRESS,
_joinAddrTo,
DAI_JOIN_ADDRESS,
ilk,
_debtAmount,
_proxy
);
} else {
ERC20(getCollateralAddr(_joinAddrTo)).approve(OPEN_PROXY_ACTIONS, uint256(-1));
MCDCreateProxyActions(OPEN_PROXY_ACTIONS).openLockGemAndDraw(
address(manager),
JUG_ADDRESS,
_joinAddrTo,
DAI_JOIN_ADDRESS,
ilk,
_collAmount,
_debtAmount,
true,
_proxy
);
}
}
}
contract AaveSaverProxy is GasBurner, SaverExchangeCore, AaveHelper {
address public constant DEFISAVER_LOGGER = 0x5c55B921f590a89C1Ebe84dF170E655a82b62126;
uint public constant VARIABLE_RATE = 2;
function repay(ExchangeData memory _data, uint _gasCost) public payable burnGas(20) {
address lendingPoolCore = ILendingPoolAddressesProvider(AAVE_LENDING_POOL_ADDRESSES).getLendingPoolCore();
address lendingPool = ILendingPoolAddressesProvider(AAVE_LENDING_POOL_ADDRESSES).getLendingPool();
address payable user = payable(getUserAddress());
// redeem collateral
address aTokenCollateral = ILendingPool(lendingPoolCore).getReserveATokenAddress(_data.srcAddr);
// uint256 maxCollateral = IAToken(aTokenCollateral).balanceOf(address(this));
// don't swap more than maxCollateral
// _data.srcAmount = _data.srcAmount > maxCollateral ? maxCollateral : _data.srcAmount;
IAToken(aTokenCollateral).redeem(_data.srcAmount);
uint256 destAmount = _data.srcAmount;
if (_data.srcAddr != _data.destAddr) {
// swap
(, destAmount) = _sell(_data);
destAmount -= getFee(destAmount, user, _gasCost, _data.destAddr);
} else {
destAmount -= getGasCost(destAmount, user, _gasCost, _data.destAddr);
}
// payback
if (_data.destAddr == ETH_ADDR) {
ILendingPool(lendingPool).repay{value: destAmount}(_data.destAddr, destAmount, payable(address(this)));
} else {
approveToken(_data.destAddr, lendingPoolCore);
ILendingPool(lendingPool).repay(_data.destAddr, destAmount, payable(address(this)));
}
// first return 0x fee to msg.sender as it is the address that actually sent 0x fee
sendContractBalance(ETH_ADDR, tx.origin, min(address(this).balance, msg.value));
// send all leftovers from dest addr to proxy owner
sendFullContractBalance(_data.destAddr, user);
DefisaverLogger(DEFISAVER_LOGGER).Log(address(this), msg.sender, "AaveRepay", abi.encode(_data.srcAddr, _data.destAddr, _data.srcAmount, destAmount));
}
function boost(ExchangeData memory _data, uint _gasCost) public payable burnGas(20) {
address lendingPoolCore = ILendingPoolAddressesProvider(AAVE_LENDING_POOL_ADDRESSES).getLendingPoolCore();
address lendingPool = ILendingPoolAddressesProvider(AAVE_LENDING_POOL_ADDRESSES).getLendingPool();
(,,,uint256 borrowRateMode,,,,,,bool collateralEnabled) = ILendingPool(lendingPool).getUserReserveData(_data.destAddr, address(this));
address payable user = payable(getUserAddress());
// skipping this check as its too expensive
// uint256 maxBorrow = getMaxBoost(_data.srcAddr, _data.destAddr, address(this));
// _data.srcAmount = _data.srcAmount > maxBorrow ? maxBorrow : _data.srcAmount;
// borrow amount
ILendingPool(lendingPool).borrow(_data.srcAddr, _data.srcAmount, borrowRateMode == 0 ? VARIABLE_RATE : borrowRateMode, AAVE_REFERRAL_CODE);
uint256 destAmount;
if (_data.destAddr != _data.srcAddr) {
_data.srcAmount -= getFee(_data.srcAmount, user, _gasCost, _data.srcAddr);
// swap
(, destAmount) = _sell(_data);
} else {
_data.srcAmount -= getGasCost(_data.srcAmount, user, _gasCost, _data.srcAddr);
destAmount = _data.srcAmount;
}
if (_data.destAddr == ETH_ADDR) {
ILendingPool(lendingPool).deposit{value: destAmount}(_data.destAddr, destAmount, AAVE_REFERRAL_CODE);
} else {
approveToken(_data.destAddr, lendingPoolCore);
ILendingPool(lendingPool).deposit(_data.destAddr, destAmount, AAVE_REFERRAL_CODE);
}
if (!collateralEnabled) {
ILendingPool(lendingPool).setUserUseReserveAsCollateral(_data.destAddr, true);
}
// returning to msg.sender as it is the address that actually sent 0x fee
sendContractBalance(ETH_ADDR, tx.origin, min(address(this).balance, msg.value));
// send all leftovers from dest addr to proxy owner
sendFullContractBalance(_data.destAddr, user);
DefisaverLogger(DEFISAVER_LOGGER).Log(address(this), msg.sender, "AaveBoost", abi.encode(_data.srcAddr, _data.destAddr, _data.srcAmount, destAmount));
}
}
contract AaveSaverReceiver is AaveHelper, AdminAuth, SaverExchangeCore {
using SafeERC20 for ERC20;
address public constant AAVE_SAVER_PROXY = 0xCab7ce9148499E0dD8228c3c8cDb9B56Ac2bb57a;
address public constant AAVE_BASIC_PROXY = 0xd042D4E9B4186c545648c7FfFe87125c976D110B;
address public constant AETH_ADDRESS = 0x3a3A65aAb0dd2A17E3F1947bA16138cd37d08c04;
function callFunction(
address sender,
Account.Info memory account,
bytes memory data
) public {
(
bytes memory exchangeDataBytes,
uint256 gasCost,
bool isRepay,
uint256 ethAmount,
uint256 txValue,
address user,
address proxy
)
= abi.decode(data, (bytes,uint256,bool,uint256,uint256,address,address));
// withdraw eth
TokenInterface(WETH_ADDRESS).withdraw(ethAmount);
address lendingPoolCoreAddress = ILendingPoolAddressesProvider(AAVE_LENDING_POOL_ADDRESSES).getLendingPoolCore();
address lendingPool = ILendingPoolAddressesProvider(AAVE_LENDING_POOL_ADDRESSES).getLendingPool();
// deposit eth on behalf of proxy
DSProxy(payable(proxy)).execute{value: ethAmount}(AAVE_BASIC_PROXY, abi.encodeWithSignature("deposit(address,uint256)", ETH_ADDR, ethAmount));
bytes memory functionData = packFunctionCall(exchangeDataBytes, gasCost, isRepay);
DSProxy(payable(proxy)).execute{value: txValue}(AAVE_SAVER_PROXY, functionData);
// withdraw deposited eth
DSProxy(payable(proxy)).execute(AAVE_BASIC_PROXY, abi.encodeWithSignature("withdraw(address,address,uint256,bool)", ETH_ADDR, AETH_ADDRESS, ethAmount, false));
// deposit eth, get weth and return to sender
TokenInterface(WETH_ADDRESS).deposit.value(address(this).balance)();
ERC20(WETH_ADDRESS).safeTransfer(proxy, ethAmount+2);
}
function packFunctionCall(bytes memory _exchangeDataBytes, uint256 _gasCost, bool _isRepay) internal returns (bytes memory) {
ExchangeData memory exData = unpackExchangeData(_exchangeDataBytes);
bytes memory functionData;
if (_isRepay) {
functionData = abi.encodeWithSignature("repay((address,address,uint256,uint256,uint256,address,address,bytes,uint256),uint256)", exData, _gasCost);
} else {
functionData = abi.encodeWithSignature("boost((address,address,uint256,uint256,uint256,address,address,bytes,uint256),uint256)", exData, _gasCost);
}
return functionData;
}
/// @dev if contract receive eth, convert it to WETH
receive() external override payable {
// deposit eth and get weth
if (msg.sender == owner) {
TokenInterface(WETH_ADDRESS).deposit.value(address(this).balance)();
}
}
}
contract AaveSaverTaker is DydxFlashLoanBase, ProxyPermission, GasBurner, SaverExchangeCore {
address public constant WETH_ADDR = 0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2;
address payable public constant AAVE_RECEIVER = 0x969DfE84ac318531f13B731c7f21af9918802B94;
address public constant DEFISAVER_LOGGER = 0x5c55B921f590a89C1Ebe84dF170E655a82b62126;
address public constant PROXY_REGISTRY_ADDRESS = 0x4678f0a6958e4D2Bc4F1BAF7Bc52E8F3564f3fE4;
function repay(ExchangeData memory _data, uint256 _gasCost) public payable {
_flashLoan(_data, _gasCost, true);
}
function boost(ExchangeData memory _data, uint256 _gasCost) public payable {
_flashLoan(_data, _gasCost, false);
}
/// @notice Starts the process to move users position 1 collateral and 1 borrow
/// @dev User must send 2 wei with this transaction
function _flashLoan(ExchangeData memory _data, uint _gasCost, bool _isRepay) internal {
ISoloMargin solo = ISoloMargin(SOLO_MARGIN_ADDRESS);
uint256 ethAmount = ERC20(WETH_ADDR).balanceOf(SOLO_MARGIN_ADDRESS);
// Get marketId from token address
uint256 marketId = _getMarketIdFromTokenAddress(WETH_ADDR);
// Calculate repay amount (_amount + (2 wei))
// Approve transfer from
uint256 repayAmount = _getRepaymentAmountInternal(ethAmount);
ERC20(WETH_ADDR).approve(SOLO_MARGIN_ADDRESS, repayAmount);
Actions.ActionArgs[] memory operations = new Actions.ActionArgs[](3);
operations[0] = _getWithdrawAction(marketId, ethAmount, AAVE_RECEIVER);
AAVE_RECEIVER.transfer(msg.value);
bytes memory encodedData = packExchangeData(_data);
operations[1] = _getCallAction(
abi.encode(encodedData, _gasCost, _isRepay, ethAmount, msg.value, proxyOwner(), address(this)),
AAVE_RECEIVER
);
operations[2] = _getDepositAction(marketId, repayAmount, address(this));
Account.Info[] memory accountInfos = new Account.Info[](1);
accountInfos[0] = _getAccountInfo();
givePermission(AAVE_RECEIVER);
solo.operate(accountInfos, operations);
removePermission(AAVE_RECEIVER);
}
}
contract CompoundLoanInfo is CompoundSafetyRatio {
struct LoanData {
address user;
uint128 ratio;
address[] collAddr;
address[] borrowAddr;
uint[] collAmounts;
uint[] borrowAmounts;
}
struct TokenInfo {
address cTokenAddress;
address underlyingTokenAddress;
uint collateralFactor;
uint price;
}
struct TokenInfoFull {
address underlyingTokenAddress;
uint supplyRate;
uint borrowRate;
uint exchangeRate;
uint marketLiquidity;
uint totalSupply;
uint totalBorrow;
uint collateralFactor;
uint price;
}
address public constant ETH_ADDRESS = 0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE;
address public constant CETH_ADDRESS = 0x4Ddc2D193948926D02f9B1fE9e1daa0718270ED5;
/// @notice Calcualted the ratio of coll/debt for a compound user
/// @param _user Address of the user
function getRatio(address _user) public view returns (uint) {
// For each asset the account is in
return getSafetyRatio(_user);
}
/// @notice Fetches Compound prices for tokens
/// @param _cTokens Arr. of cTokens for which to get the prices
/// @return prices Array of prices
function getPrices(address[] memory _cTokens) public view returns (uint[] memory prices) {
prices = new uint[](_cTokens.length);
address oracleAddr = comp.oracle();
for (uint i = 0; i < _cTokens.length; ++i) {
prices[i] = CompoundOracleInterface(oracleAddr).getUnderlyingPrice(_cTokens[i]);
}
}
/// @notice Fetches Compound collateral factors for tokens
/// @param _cTokens Arr. of cTokens for which to get the coll. factors
/// @return collFactors Array of coll. factors
function getCollFactors(address[] memory _cTokens) public view returns (uint[] memory collFactors) {
collFactors = new uint[](_cTokens.length);
for (uint i = 0; i < _cTokens.length; ++i) {
(, collFactors[i]) = comp.markets(_cTokens[i]);
}
}
/// @notice Fetches all the collateral/debt address and amounts, denominated in usd
/// @param _user Address of the user
/// @return data LoanData information
function getLoanData(address _user) public view returns (LoanData memory data) {
address[] memory assets = comp.getAssetsIn(_user);
address oracleAddr = comp.oracle();
data = LoanData({
user: _user,
ratio: 0,
collAddr: new address[](assets.length),
borrowAddr: new address[](assets.length),
collAmounts: new uint[](assets.length),
borrowAmounts: new uint[](assets.length)
});
uint collPos = 0;
uint borrowPos = 0;
for (uint i = 0; i < assets.length; i++) {
address asset = assets[i];
(, uint cTokenBalance, uint borrowBalance, uint exchangeRateMantissa)
= CTokenInterface(asset).getAccountSnapshot(_user);
Exp memory oraclePrice;
if (cTokenBalance != 0 || borrowBalance != 0) {
oraclePrice = Exp({mantissa: CompoundOracleInterface(oracleAddr).getUnderlyingPrice(asset)});
}
// Sum up collateral in Usd
if (cTokenBalance != 0) {
Exp memory exchangeRate = Exp({mantissa: exchangeRateMantissa});
(, Exp memory tokensToUsd) = mulExp(exchangeRate, oraclePrice);
data.collAddr[collPos] = asset;
(, data.collAmounts[collPos]) = mulScalarTruncate(tokensToUsd, cTokenBalance);
collPos++;
}
// Sum up debt in Usd
if (borrowBalance != 0) {
data.borrowAddr[borrowPos] = asset;
(, data.borrowAmounts[borrowPos]) = mulScalarTruncate(oraclePrice, borrowBalance);
borrowPos++;
}
}
data.ratio = uint128(getSafetyRatio(_user));
return data;
}
function getTokenBalances(address _user, address[] memory _cTokens) public view returns (uint[] memory balances, uint[] memory borrows) {
balances = new uint[](_cTokens.length);
borrows = new uint[](_cTokens.length);
for (uint i = 0; i < _cTokens.length; i++) {
address asset = _cTokens[i];
(, uint cTokenBalance, uint borrowBalance, uint exchangeRateMantissa)
= CTokenInterface(asset).getAccountSnapshot(_user);
Exp memory exchangeRate = Exp({mantissa: exchangeRateMantissa});
(, balances[i]) = mulScalarTruncate(exchangeRate, cTokenBalance);
borrows[i] = borrowBalance;
}
}
/// @notice Fetches all the collateral/debt address and amounts, denominated in usd
/// @param _users Addresses of the user
/// @return loans Array of LoanData information
function getLoanDataArr(address[] memory _users) public view returns (LoanData[] memory loans) {
loans = new LoanData[](_users.length);
for (uint i = 0; i < _users.length; ++i) {
loans[i] = getLoanData(_users[i]);
}
}
/// @notice Calcualted the ratio of coll/debt for a compound user
/// @param _users Addresses of the user
/// @return ratios Array of ratios
function getRatios(address[] memory _users) public view returns (uint[] memory ratios) {
ratios = new uint[](_users.length);
for (uint i = 0; i < _users.length; ++i) {
ratios[i] = getSafetyRatio(_users[i]);
}
}
/// @notice Information about cTokens
/// @param _cTokenAddresses Array of cTokens addresses
/// @return tokens Array of cTokens infomartion
function getTokensInfo(address[] memory _cTokenAddresses) public returns(TokenInfo[] memory tokens) {
tokens = new TokenInfo[](_cTokenAddresses.length);
address oracleAddr = comp.oracle();
for (uint i = 0; i < _cTokenAddresses.length; ++i) {
(, uint collFactor) = comp.markets(_cTokenAddresses[i]);
tokens[i] = TokenInfo({
cTokenAddress: _cTokenAddresses[i],
underlyingTokenAddress: getUnderlyingAddr(_cTokenAddresses[i]),
collateralFactor: collFactor,
price: CompoundOracleInterface(oracleAddr).getUnderlyingPrice(_cTokenAddresses[i])
});
}
}
/// @notice Information about cTokens
/// @param _cTokenAddresses Array of cTokens addresses
/// @return tokens Array of cTokens infomartion
function getFullTokensInfo(address[] memory _cTokenAddresses) public returns(TokenInfoFull[] memory tokens) {
tokens = new TokenInfoFull[](_cTokenAddresses.length);
address oracleAddr = comp.oracle();
for (uint i = 0; i < _cTokenAddresses.length; ++i) {
(, uint collFactor) = comp.markets(_cTokenAddresses[i]);
CTokenInterface cToken = CTokenInterface(_cTokenAddresses[i]);
tokens[i] = TokenInfoFull({
underlyingTokenAddress: getUnderlyingAddr(_cTokenAddresses[i]),
supplyRate: cToken.supplyRatePerBlock(),
borrowRate: cToken.borrowRatePerBlock(),
exchangeRate: cToken.exchangeRateCurrent(),
marketLiquidity: cToken.getCash(),
totalSupply: cToken.totalSupply(),
totalBorrow: cToken.totalBorrowsCurrent(),
collateralFactor: collFactor,
price: CompoundOracleInterface(oracleAddr).getUnderlyingPrice(_cTokenAddresses[i])
});
}
}
/// @notice Returns the underlying address of the cToken asset
/// @param _cTokenAddress cToken address
/// @return Token address of the cToken specified
function getUnderlyingAddr(address _cTokenAddress) internal returns (address) {
if (_cTokenAddress == CETH_ADDRESS) {
return ETH_ADDRESS;
} else {
return CTokenInterface(_cTokenAddress).underlying();
}
}
}
contract CompLeverage is DFSExchangeCore, CompBalance {
address public constant C_COMP_ADDR = 0x70e36f6BF80a52b3B46b3aF8e106CC0ed743E8e4;
address public constant ETH_ADDRESS = 0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE;
address public constant CETH_ADDRESS = 0x4Ddc2D193948926D02f9B1fE9e1daa0718270ED5;
address payable public constant WALLET_ADDR = 0x322d58b9E75a6918f7e7849AEe0fF09369977e08;
address public constant DISCOUNT_ADDR = 0x1b14E8D511c9A4395425314f849bD737BAF8208F;
address public constant COMPTROLLER_ADDR = 0x3d9819210A31b4961b30EF54bE2aeD79B9c9Cd3B;
address public constant DEFISAVER_LOGGER = 0x5c55B921f590a89C1Ebe84dF170E655a82b62126;
DefisaverLogger public constant logger = DefisaverLogger(0x5c55B921f590a89C1Ebe84dF170E655a82b62126);
/// @notice Should claim COMP and sell it to the specified token and deposit it back
/// @param exchangeData Standard Exchange struct
/// @param _cTokensSupply List of cTokens user is supplying
/// @param _cTokensBorrow List of cTokens user is borrowing
/// @param _cDepositAddr The cToken address of the asset you want to deposit
/// @param _inMarket Flag if the cToken is used as collateral
function claimAndSell(
ExchangeData memory exchangeData,
address[] memory _cTokensSupply,
address[] memory _cTokensBorrow,
address _cDepositAddr,
bool _inMarket
) public payable {
// Claim COMP token
_claim(address(this), _cTokensSupply, _cTokensBorrow);
uint compBalance = ERC20(COMP_ADDR).balanceOf(address(this));
uint depositAmount = 0;
// Exchange COMP
if (exchangeData.srcAddr != address(0)) {
exchangeData.dfsFeeDivider = 400; // 0.25%
exchangeData.srcAmount = compBalance;
(, depositAmount) = _sell(exchangeData);
// if we have no deposit after, send back tokens to the user
if (_cDepositAddr == address(0)) {
if (exchangeData.destAddr != ETH_ADDRESS) {
ERC20(exchangeData.destAddr).safeTransfer(msg.sender, depositAmount);
} else {
msg.sender.transfer(address(this).balance);
}
}
}
// Deposit back a token
if (_cDepositAddr != address(0)) {
// if we are just depositing COMP without a swap
if (_cDepositAddr == C_COMP_ADDR) {
depositAmount = compBalance;
}
address tokenAddr = getUnderlyingAddr(_cDepositAddr);
deposit(tokenAddr, _cDepositAddr, depositAmount, _inMarket);
}
logger.Log(address(this), msg.sender, "CompLeverage", abi.encode(compBalance, depositAmount, _cDepositAddr, exchangeData.destAmount));
}
function getUnderlyingAddr(address _cTokenAddress) internal returns (address) {
if (_cTokenAddress == CETH_ADDRESS) {
return ETH_ADDRESS;
} else {
return CTokenInterface(_cTokenAddress).underlying();
}
}
function deposit(address _tokenAddr, address _cTokenAddr, uint _amount, bool _inMarket) public burnGas(5) payable {
approveToken(_tokenAddr, _cTokenAddr);
if (!_inMarket) {
enterMarket(_cTokenAddr);
}
if (_tokenAddr != ETH_ADDRESS) {
require(CTokenInterface(_cTokenAddr).mint(_amount) == 0);
} else {
CEtherInterface(_cTokenAddr).mint{value: msg.value}(); // reverts on fail
}
}
function enterMarket(address _cTokenAddr) public {
address[] memory markets = new address[](1);
markets[0] = _cTokenAddr;
ComptrollerInterface(COMPTROLLER_ADDR).enterMarkets(markets);
}
function approveToken(address _tokenAddr, address _cTokenAddr) internal {
if (_tokenAddr != ETH_ADDRESS) {
ERC20(_tokenAddr).safeApprove(_cTokenAddr, uint(-1));
}
}
}
contract CompoundCreateReceiver is FlashLoanReceiverBase, SaverExchangeCore {
ILendingPoolAddressesProvider public LENDING_POOL_ADDRESS_PROVIDER = ILendingPoolAddressesProvider(0x24a42fD28C976A61Df5D00D0599C34c4f90748c8);
ShifterRegistry public constant shifterRegistry = ShifterRegistry(0x2E82103bD91053C781aaF39da17aE58ceE39d0ab);
address public constant ETH_ADDRESS = 0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE;
address payable public constant WALLET_ADDR = 0x322d58b9E75a6918f7e7849AEe0fF09369977e08;
address public constant DISCOUNT_ADDR = 0x1b14E8D511c9A4395425314f849bD737BAF8208F;
// solhint-disable-next-line no-empty-blocks
constructor() public FlashLoanReceiverBase(LENDING_POOL_ADDRESS_PROVIDER) {}
struct CompCreateData {
address payable proxyAddr;
bytes proxyData;
address cCollAddr;
address cDebtAddr;
}
/// @notice Called by Aave when sending back the FL amount
/// @param _reserve The address of the borrowed token
/// @param _amount Amount of FL tokens received
/// @param _fee FL Aave fee
/// @param _params The params that are sent from the original FL caller contract
function executeOperation(
address _reserve,
uint256 _amount,
uint256 _fee,
bytes calldata _params)
external override {
// Format the call data for DSProxy
(CompCreateData memory compCreate, ExchangeData memory exchangeData)
= packFunctionCall(_amount, _fee, _params);
address leveragedAsset = _reserve;
// If the assets are different
if (compCreate.cCollAddr != compCreate.cDebtAddr) {
(, uint sellAmount) = _sell(exchangeData);
getFee(sellAmount, exchangeData.destAddr, compCreate.proxyAddr);
leveragedAsset = exchangeData.destAddr;
}
// Send amount to DSProxy
sendToProxy(compCreate.proxyAddr, leveragedAsset);
address compOpenProxy = shifterRegistry.getAddr("COMP_SHIFTER");
// Execute the DSProxy call
DSProxyInterface(compCreate.proxyAddr).execute(compOpenProxy, compCreate.proxyData);
// Repay the loan with the money DSProxy sent back
transferFundsBackToPoolInternal(_reserve, _amount.add(_fee));
// if there is some eth left (0x fee), return it to user
if (address(this).balance > 0) {
// solhint-disable-next-line avoid-tx-origin
tx.origin.transfer(address(this).balance);
}
}
/// @notice Formats function data call so we can call it through DSProxy
/// @param _amount Amount of FL
/// @param _fee Fee of the FL
/// @param _params Saver proxy params
function packFunctionCall(uint _amount, uint _fee, bytes memory _params) internal pure returns (CompCreateData memory compCreate, ExchangeData memory exchangeData) {
(
uint[4] memory numData, // srcAmount, destAmount, minPrice, price0x
address[6] memory cAddresses, // cCollAddr, cDebtAddr, srcAddr, destAddr, exchangeAddr, wrapper
bytes memory callData,
address proxy
)
= abi.decode(_params, (uint256[4],address[6],bytes,address));
bytes memory proxyData = abi.encodeWithSignature(
"open(address,address,uint256)",
cAddresses[0], cAddresses[1], (_amount + _fee));
exchangeData = SaverExchangeCore.ExchangeData({
srcAddr: cAddresses[2],
destAddr: cAddresses[3],
srcAmount: numData[0],
destAmount: numData[1],
minPrice: numData[2],
wrapper: cAddresses[5],
exchangeAddr: cAddresses[4],
callData: callData,
price0x: numData[3]
});
compCreate = CompCreateData({
proxyAddr: payable(proxy),
proxyData: proxyData,
cCollAddr: cAddresses[0],
cDebtAddr: cAddresses[1]
});
return (compCreate, exchangeData);
}
/// @notice Send the FL funds received to DSProxy
/// @param _proxy DSProxy address
/// @param _reserve Token address
function sendToProxy(address payable _proxy, address _reserve) internal {
if (_reserve != ETH_ADDRESS) {
ERC20(_reserve).safeTransfer(_proxy, ERC20(_reserve).balanceOf(address(this)));
} else {
_proxy.transfer(address(this).balance);
}
}
function getFee(uint _amount, address _tokenAddr, address _proxy) internal returns (uint feeAmount) {
uint fee = 400;
DSProxy proxy = DSProxy(payable(_proxy));
address user = proxy.owner();
if (Discount(DISCOUNT_ADDR).isCustomFeeSet(user)) {
fee = Discount(DISCOUNT_ADDR).getCustomServiceFee(user);
}
feeAmount = (fee == 0) ? 0 : (_amount / fee);
// fee can't go over 20% of the whole amount
if (feeAmount > (_amount / 5)) {
feeAmount = _amount / 5;
}
if (_tokenAddr == ETH_ADDRESS) {
WALLET_ADDR.transfer(feeAmount);
} else {
ERC20(_tokenAddr).safeTransfer(WALLET_ADDR, feeAmount);
}
}
// solhint-disable-next-line no-empty-blocks
receive() external override(FlashLoanReceiverBase, SaverExchangeCore) payable {}
}
contract CompoundSaverFlashLoan is FlashLoanReceiverBase, SaverExchangeCore {
ILendingPoolAddressesProvider public LENDING_POOL_ADDRESS_PROVIDER = ILendingPoolAddressesProvider(0x24a42fD28C976A61Df5D00D0599C34c4f90748c8);
address payable public COMPOUND_SAVER_FLASH_PROXY = 0xcEAb38B5C88F33Dabe4D31BDD384E08215526632;
address public constant ETH_ADDRESS = 0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE;
address public owner;
using SafeERC20 for ERC20;
constructor()
FlashLoanReceiverBase(LENDING_POOL_ADDRESS_PROVIDER)
public {
owner = msg.sender;
}
/// @notice Called by Aave when sending back the FL amount
/// @param _reserve The address of the borrowed token
/// @param _amount Amount of FL tokens received
/// @param _fee FL Aave fee
/// @param _params The params that are sent from the original FL caller contract
function executeOperation(
address _reserve,
uint256 _amount,
uint256 _fee,
bytes calldata _params)
external override {
// Format the call data for DSProxy
(bytes memory proxyData, address payable proxyAddr) = packFunctionCall(_amount, _fee, _params);
// Send Flash loan amount to DSProxy
sendLoanToProxy(proxyAddr, _reserve, _amount);
// Execute the DSProxy call
DSProxyInterface(proxyAddr).execute(COMPOUND_SAVER_FLASH_PROXY, proxyData);
// Repay the loan with the money DSProxy sent back
transferFundsBackToPoolInternal(_reserve, _amount.add(_fee));
// if there is some eth left (0x fee), return it to user
if (address(this).balance > 0) {
tx.origin.transfer(address(this).balance);
}
}
/// @notice Formats function data call so we can call it through DSProxy
/// @param _amount Amount of FL
/// @param _fee Fee of the FL
/// @param _params Saver proxy params
/// @return proxyData Formated function call data
function packFunctionCall(uint _amount, uint _fee, bytes memory _params) internal pure returns (bytes memory proxyData, address payable) {
(
bytes memory exDataBytes,
address[2] memory cAddresses, // cCollAddress, cBorrowAddress
uint256 gasCost,
bool isRepay,
address payable proxyAddr
)
= abi.decode(_params, (bytes,address[2],uint256,bool,address));
ExchangeData memory _exData = unpackExchangeData(exDataBytes);
uint[2] memory flashLoanData = [_amount, _fee];
if (isRepay) {
proxyData = abi.encodeWithSignature("flashRepay((address,address,uint256,uint256,uint256,address,address,bytes,uint256),address[2],uint256,uint256[2])", _exData, cAddresses, gasCost, flashLoanData);
} else {
proxyData = abi.encodeWithSignature("flashBoost((address,address,uint256,uint256,uint256,address,address,bytes,uint256),address[2],uint256,uint256[2])", _exData, cAddresses, gasCost, flashLoanData);
}
return (proxyData, proxyAddr);
}
/// @notice Send the FL funds received to DSProxy
/// @param _proxy DSProxy address
/// @param _reserve Token address
/// @param _amount Amount of tokens
function sendLoanToProxy(address payable _proxy, address _reserve, uint _amount) internal {
if (_reserve != ETH_ADDRESS) {
ERC20(_reserve).safeTransfer(_proxy, _amount);
}
_proxy.transfer(address(this).balance);
}
receive() external override(SaverExchangeCore, FlashLoanReceiverBase) payable {}
}
contract CompoundSaverFlashProxy is SaverExchangeCore, CompoundSaverHelper {
address public constant DEFISAVER_LOGGER = 0x5c55B921f590a89C1Ebe84dF170E655a82b62126;
using SafeERC20 for ERC20;
/// @notice Repays the position and sends tokens back for FL
/// @param _exData Exchange data
/// @param _cAddresses cTokens addreses and exchange [cCollAddress, cBorrowAddress]
/// @param _gasCost Gas cost for transaction
/// @param _flashLoanData Data about FL [amount, fee]
function flashRepay(
ExchangeData memory _exData,
address[2] memory _cAddresses, // cCollAddress, cBorrowAddress
uint256 _gasCost,
uint[2] memory _flashLoanData // amount, fee
) public payable {
enterMarket(_cAddresses[0], _cAddresses[1]);
address payable user = payable(getUserAddress());
uint flashBorrowed = _flashLoanData[0] + _flashLoanData[1];
uint maxColl = getMaxCollateral(_cAddresses[0], address(this));
// draw max coll
require(CTokenInterface(_cAddresses[0]).redeemUnderlying(maxColl) == 0);
address collToken = getUnderlyingAddr(_cAddresses[0]);
address borrowToken = getUnderlyingAddr(_cAddresses[1]);
uint swapAmount = 0;
if (collToken != borrowToken) {
// swap max coll + loanAmount
_exData.srcAmount = maxColl + _flashLoanData[0];
(,swapAmount) = _sell(_exData);
// get fee
swapAmount -= getFee(swapAmount, user, _gasCost, _cAddresses[1]);
} else {
swapAmount = (maxColl + _flashLoanData[0]);
swapAmount -= getGasCost(swapAmount, _gasCost, _cAddresses[1]);
}
// payback debt
paybackDebt(swapAmount, _cAddresses[1], borrowToken, user);
// draw collateral for loanAmount + loanFee
require(CTokenInterface(_cAddresses[0]).redeemUnderlying(flashBorrowed) == 0);
// repay flash loan
returnFlashLoan(collToken, flashBorrowed);
DefisaverLogger(DEFISAVER_LOGGER).Log(address(this), msg.sender, "CompoundRepay", abi.encode(_exData.srcAmount, swapAmount, collToken, borrowToken));
}
/// @notice Boosts the position and sends tokens back for FL
/// @param _exData Exchange data
/// @param _cAddresses cTokens addreses and exchange [cCollAddress, cBorrowAddress]
/// @param _gasCost Gas cost for specific transaction
/// @param _flashLoanData Data about FL [amount, fee]
function flashBoost(
ExchangeData memory _exData,
address[2] memory _cAddresses, // cCollAddress, cBorrowAddress
uint256 _gasCost,
uint[2] memory _flashLoanData // amount, fee
) public payable {
enterMarket(_cAddresses[0], _cAddresses[1]);
address payable user = payable(getUserAddress());
uint flashBorrowed = _flashLoanData[0] + _flashLoanData[1];
// borrow max amount
uint borrowAmount = getMaxBorrow(_cAddresses[1], address(this));
require(CTokenInterface(_cAddresses[1]).borrow(borrowAmount) == 0);
address collToken = getUnderlyingAddr(_cAddresses[0]);
address borrowToken = getUnderlyingAddr(_cAddresses[1]);
uint swapAmount = 0;
if (collToken != borrowToken) {
// get dfs fee
borrowAmount -= getFee((borrowAmount + _flashLoanData[0]), user, _gasCost, _cAddresses[1]);
_exData.srcAmount = (borrowAmount + _flashLoanData[0]);
(,swapAmount) = _sell(_exData);
} else {
swapAmount = (borrowAmount + _flashLoanData[0]);
swapAmount -= getGasCost(swapAmount, _gasCost, _cAddresses[1]);
}
// deposit swaped collateral
depositCollateral(collToken, _cAddresses[0], swapAmount);
// borrow token to repay flash loan
require(CTokenInterface(_cAddresses[1]).borrow(flashBorrowed) == 0);
// repay flash loan
returnFlashLoan(borrowToken, flashBorrowed);
DefisaverLogger(DEFISAVER_LOGGER).Log(address(this), msg.sender, "CompoundBoost", abi.encode(_exData.srcAmount, swapAmount, collToken, borrowToken));
}
/// @notice Helper method to deposit tokens in Compound
/// @param _collToken Token address of the collateral
/// @param _cCollToken CToken address of the collateral
/// @param _depositAmount Amount to deposit
function depositCollateral(address _collToken, address _cCollToken, uint _depositAmount) internal {
approveCToken(_collToken, _cCollToken);
if (_collToken != ETH_ADDRESS) {
require(CTokenInterface(_cCollToken).mint(_depositAmount) == 0);
} else {
CEtherInterface(_cCollToken).mint{value: _depositAmount}(); // reverts on fail
}
}
/// @notice Returns the tokens/ether to the msg.sender which is the FL contract
/// @param _tokenAddr Address of token which we return
/// @param _amount Amount to return
function returnFlashLoan(address _tokenAddr, uint _amount) internal {
if (_tokenAddr != ETH_ADDRESS) {
ERC20(_tokenAddr).safeTransfer(msg.sender, _amount);
}
msg.sender.transfer(address(this).balance);
}
}
contract CompoundSaverProxy is CompoundSaverHelper, SaverExchangeCore {
DefisaverLogger public constant logger = DefisaverLogger(0x5c55B921f590a89C1Ebe84dF170E655a82b62126);
/// @notice Withdraws collateral, converts to borrowed token and repays debt
/// @dev Called through the DSProxy
/// @param _exData Exchange data
/// @param _cAddresses Coll/Debt addresses [cCollAddress, cBorrowAddress]
/// @param _gasCost Gas cost for specific transaction
function repay(
ExchangeData memory _exData,
address[2] memory _cAddresses, // cCollAddress, cBorrowAddress
uint256 _gasCost
) public payable {
enterMarket(_cAddresses[0], _cAddresses[1]);
address payable user = payable(getUserAddress());
uint maxColl = getMaxCollateral(_cAddresses[0], address(this));
uint collAmount = (_exData.srcAmount > maxColl) ? maxColl : _exData.srcAmount;
require(CTokenInterface(_cAddresses[0]).redeemUnderlying(collAmount) == 0);
address collToken = getUnderlyingAddr(_cAddresses[0]);
address borrowToken = getUnderlyingAddr(_cAddresses[1]);
uint swapAmount = 0;
if (collToken != borrowToken) {
_exData.srcAmount = collAmount;
(, swapAmount) = _sell(_exData);
swapAmount -= getFee(swapAmount, user, _gasCost, _cAddresses[1]);
} else {
swapAmount = collAmount;
swapAmount -= getGasCost(swapAmount, _gasCost, _cAddresses[1]);
}
paybackDebt(swapAmount, _cAddresses[1], borrowToken, user);
// handle 0x fee
tx.origin.transfer(address(this).balance);
// log amount, collToken, borrowToken
logger.Log(address(this), msg.sender, "CompoundRepay", abi.encode(_exData.srcAmount, swapAmount, collToken, borrowToken));
}
/// @notice Borrows token, converts to collateral, and adds to position
/// @dev Called through the DSProxy
/// @param _exData Exchange data
/// @param _cAddresses Coll/Debt addresses [cCollAddress, cBorrowAddress]
/// @param _gasCost Gas cost for specific transaction
function boost(
ExchangeData memory _exData,
address[2] memory _cAddresses, // cCollAddress, cBorrowAddress
uint256 _gasCost
) public payable {
enterMarket(_cAddresses[0], _cAddresses[1]);
address payable user = payable(getUserAddress());
uint maxBorrow = getMaxBorrow(_cAddresses[1], address(this));
uint borrowAmount = (_exData.srcAmount > maxBorrow) ? maxBorrow : _exData.srcAmount;
require(CTokenInterface(_cAddresses[1]).borrow(borrowAmount) == 0);
address collToken = getUnderlyingAddr(_cAddresses[0]);
address borrowToken = getUnderlyingAddr(_cAddresses[1]);
uint swapAmount = 0;
if (collToken != borrowToken) {
borrowAmount -= getFee(borrowAmount, user, _gasCost, _cAddresses[1]);
_exData.srcAmount = borrowAmount;
(,swapAmount) = _sell(_exData);
} else {
swapAmount = borrowAmount;
swapAmount -= getGasCost(swapAmount, _gasCost, _cAddresses[1]);
}
approveCToken(collToken, _cAddresses[0]);
if (collToken != ETH_ADDRESS) {
require(CTokenInterface(_cAddresses[0]).mint(swapAmount) == 0);
} else {
CEtherInterface(_cAddresses[0]).mint{value: swapAmount}(); // reverts on fail
}
// handle 0x fee
tx.origin.transfer(address(this).balance);
// log amount, collToken, borrowToken
logger.Log(address(this), msg.sender, "CompoundBoost", abi.encode(_exData.srcAmount, swapAmount, collToken, borrowToken));
}
}
contract CreamSaverFlashLoan is FlashLoanReceiverBase, SaverExchangeCore {
ILendingPoolAddressesProvider public LENDING_POOL_ADDRESS_PROVIDER = ILendingPoolAddressesProvider(0x24a42fD28C976A61Df5D00D0599C34c4f90748c8);
address payable public COMPOUND_SAVER_FLASH_PROXY = 0x1e012554891d271eDc80ba8eB146EA5FF596fA51;
address public constant ETH_ADDRESS = 0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE;
address public owner;
using SafeERC20 for ERC20;
constructor()
FlashLoanReceiverBase(LENDING_POOL_ADDRESS_PROVIDER)
public {
owner = msg.sender;
}
/// @notice Called by Aave when sending back the FL amount
/// @param _reserve The address of the borrowed token
/// @param _amount Amount of FL tokens received
/// @param _fee FL Aave fee
/// @param _params The params that are sent from the original FL caller contract
function executeOperation(
address _reserve,
uint256 _amount,
uint256 _fee,
bytes calldata _params)
external override {
// Format the call data for DSProxy
(bytes memory proxyData, address payable proxyAddr) = packFunctionCall(_amount, _fee, _params);
// Send Flash loan amount to DSProxy
sendLoanToProxy(proxyAddr, _reserve, _amount);
// Execute the DSProxy call
DSProxyInterface(proxyAddr).execute(COMPOUND_SAVER_FLASH_PROXY, proxyData);
// Repay the loan with the money DSProxy sent back
transferFundsBackToPoolInternal(_reserve, _amount.add(_fee));
// if there is some eth left (0x fee), return it to user
if (address(this).balance > 0) {
tx.origin.transfer(address(this).balance);
}
}
/// @notice Formats function data call so we can call it through DSProxy
/// @param _amount Amount of FL
/// @param _fee Fee of the FL
/// @param _params Saver proxy params
/// @return proxyData Formated function call data
function packFunctionCall(uint _amount, uint _fee, bytes memory _params) internal pure returns (bytes memory proxyData, address payable) {
(
bytes memory exDataBytes,
address[2] memory cAddresses, // cCollAddress, cBorrowAddress
uint256 gasCost,
bool isRepay,
address payable proxyAddr
)
= abi.decode(_params, (bytes,address[2],uint256,bool,address));
ExchangeData memory _exData = unpackExchangeData(exDataBytes);
uint[2] memory flashLoanData = [_amount, _fee];
if (isRepay) {
proxyData = abi.encodeWithSignature("flashRepay((address,address,uint256,uint256,uint256,address,address,bytes,uint256),address[2],uint256,uint256[2])", _exData, cAddresses, gasCost, flashLoanData);
} else {
proxyData = abi.encodeWithSignature("flashBoost((address,address,uint256,uint256,uint256,address,address,bytes,uint256),address[2],uint256,uint256[2])", _exData, cAddresses, gasCost, flashLoanData);
}
return (proxyData, proxyAddr);
}
/// @notice Send the FL funds received to DSProxy
/// @param _proxy DSProxy address
/// @param _reserve Token address
/// @param _amount Amount of tokens
function sendLoanToProxy(address payable _proxy, address _reserve, uint _amount) internal {
if (_reserve != ETH_ADDRESS) {
ERC20(_reserve).safeTransfer(_proxy, _amount);
}
_proxy.transfer(address(this).balance);
}
receive() external override(SaverExchangeCore, FlashLoanReceiverBase) payable {}
}
contract CreamSaverFlashProxy is SaverExchangeCore, CreamSaverHelper {
address public constant DEFISAVER_LOGGER = 0x5c55B921f590a89C1Ebe84dF170E655a82b62126;
using SafeERC20 for ERC20;
/// @notice Repays the position and sends tokens back for FL
/// @param _exData Exchange data
/// @param _cAddresses cTokens addreses and exchange [cCollAddress, cBorrowAddress]
/// @param _gasCost Gas cost for transaction
/// @param _flashLoanData Data about FL [amount, fee]
function flashRepay(
ExchangeData memory _exData,
address[2] memory _cAddresses, // cCollAddress, cBorrowAddress
uint256 _gasCost,
uint[2] memory _flashLoanData // amount, fee
) public payable {
enterMarket(_cAddresses[0], _cAddresses[1]);
address payable user = payable(getUserAddress());
uint flashBorrowed = _flashLoanData[0] + _flashLoanData[1];
uint maxColl = getMaxCollateral(_cAddresses[0], address(this));
// draw max coll
require(CTokenInterface(_cAddresses[0]).redeemUnderlying(maxColl) == 0);
address collToken = getUnderlyingAddr(_cAddresses[0]);
address borrowToken = getUnderlyingAddr(_cAddresses[1]);
uint swapAmount = 0;
if (collToken != borrowToken) {
// swap max coll + loanAmount
_exData.srcAmount = maxColl + _flashLoanData[0];
(,swapAmount) = _sell(_exData);
// get fee
swapAmount -= getFee(swapAmount, user, _gasCost, _cAddresses[1]);
} else {
swapAmount = (maxColl + _flashLoanData[0]);
swapAmount -= getGasCost(swapAmount, _gasCost, _cAddresses[1]);
}
// payback debt
paybackDebt(swapAmount, _cAddresses[1], borrowToken, user);
// draw collateral for loanAmount + loanFee
require(CTokenInterface(_cAddresses[0]).redeemUnderlying(flashBorrowed) == 0);
// repay flash loan
returnFlashLoan(collToken, flashBorrowed);
DefisaverLogger(DEFISAVER_LOGGER).Log(address(this), msg.sender, "CreamRepay", abi.encode(_exData.srcAmount, swapAmount, collToken, borrowToken));
}
/// @notice Boosts the position and sends tokens back for FL
/// @param _exData Exchange data
/// @param _cAddresses cTokens addreses and exchange [cCollAddress, cBorrowAddress]
/// @param _gasCost Gas cost for specific transaction
/// @param _flashLoanData Data about FL [amount, fee]
function flashBoost(
ExchangeData memory _exData,
address[2] memory _cAddresses, // cCollAddress, cBorrowAddress
uint256 _gasCost,
uint[2] memory _flashLoanData // amount, fee
) public payable {
enterMarket(_cAddresses[0], _cAddresses[1]);
address payable user = payable(getUserAddress());
uint flashBorrowed = _flashLoanData[0] + _flashLoanData[1];
// borrow max amount
uint borrowAmount = getMaxBorrow(_cAddresses[1], address(this));
require(CTokenInterface(_cAddresses[1]).borrow(borrowAmount) == 0);
address collToken = getUnderlyingAddr(_cAddresses[0]);
address borrowToken = getUnderlyingAddr(_cAddresses[1]);
uint swapAmount = 0;
if (collToken != borrowToken) {
// get dfs fee
borrowAmount -= getFee((borrowAmount + _flashLoanData[0]), user, _gasCost, _cAddresses[1]);
_exData.srcAmount = (borrowAmount + _flashLoanData[0]);
(,swapAmount) = _sell(_exData);
} else {
swapAmount = (borrowAmount + _flashLoanData[0]);
swapAmount -= getGasCost(swapAmount, _gasCost, _cAddresses[1]);
}
// deposit swaped collateral
depositCollateral(collToken, _cAddresses[0], swapAmount);
// borrow token to repay flash loan
require(CTokenInterface(_cAddresses[1]).borrow(flashBorrowed) == 0);
// repay flash loan
returnFlashLoan(borrowToken, flashBorrowed);
DefisaverLogger(DEFISAVER_LOGGER).Log(address(this), msg.sender, "CreamBoost", abi.encode(_exData.srcAmount, swapAmount, collToken, borrowToken));
}
/// @notice Helper method to deposit tokens in Compound
/// @param _collToken Token address of the collateral
/// @param _cCollToken CToken address of the collateral
/// @param _depositAmount Amount to deposit
function depositCollateral(address _collToken, address _cCollToken, uint _depositAmount) internal {
approveCToken(_collToken, _cCollToken);
if (_collToken != ETH_ADDRESS) {
require(CTokenInterface(_cCollToken).mint(_depositAmount) == 0);
} else {
CEtherInterface(_cCollToken).mint{value: _depositAmount}(); // reverts on fail
}
}
/// @notice Returns the tokens/ether to the msg.sender which is the FL contract
/// @param _tokenAddr Address of token which we return
/// @param _amount Amount to return
function returnFlashLoan(address _tokenAddr, uint _amount) internal {
if (_tokenAddr != ETH_ADDRESS) {
ERC20(_tokenAddr).safeTransfer(msg.sender, _amount);
}
msg.sender.transfer(address(this).balance);
}
}
contract CreamSaverProxy is CreamSaverHelper, SaverExchangeCore {
DefisaverLogger public constant logger = DefisaverLogger(0x5c55B921f590a89C1Ebe84dF170E655a82b62126);
/// @notice Withdraws collateral, converts to borrowed token and repays debt
/// @dev Called through the DSProxy
/// @param _exData Exchange data
/// @param _cAddresses Coll/Debt addresses [cCollAddress, cBorrowAddress]
/// @param _gasCost Gas cost for specific transaction
function repay(
ExchangeData memory _exData,
address[2] memory _cAddresses, // cCollAddress, cBorrowAddress
uint256 _gasCost
) public payable {
enterMarket(_cAddresses[0], _cAddresses[1]);
address payable user = payable(getUserAddress());
uint maxColl = getMaxCollateral(_cAddresses[0], address(this));
uint collAmount = (_exData.srcAmount > maxColl) ? maxColl : _exData.srcAmount;
require(CTokenInterface(_cAddresses[0]).redeemUnderlying(collAmount) == 0);
address collToken = getUnderlyingAddr(_cAddresses[0]);
address borrowToken = getUnderlyingAddr(_cAddresses[1]);
uint swapAmount = 0;
if (collToken != borrowToken) {
(, swapAmount) = _sell(_exData);
swapAmount -= getFee(swapAmount, user, _gasCost, _cAddresses[1]);
} else {
swapAmount = collAmount;
swapAmount -= getGasCost(swapAmount, _gasCost, _cAddresses[1]);
}
paybackDebt(swapAmount, _cAddresses[1], borrowToken, user);
// handle 0x fee
tx.origin.transfer(address(this).balance);
// log amount, collToken, borrowToken
logger.Log(address(this), msg.sender, "CreamRepay", abi.encode(_exData.srcAmount, swapAmount, collToken, borrowToken));
}
/// @notice Borrows token, converts to collateral, and adds to position
/// @dev Called through the DSProxy
/// @param _exData Exchange data
/// @param _cAddresses Coll/Debt addresses [cCollAddress, cBorrowAddress]
/// @param _gasCost Gas cost for specific transaction
function boost(
ExchangeData memory _exData,
address[2] memory _cAddresses, // cCollAddress, cBorrowAddress
uint256 _gasCost
) public payable {
enterMarket(_cAddresses[0], _cAddresses[1]);
address payable user = payable(getUserAddress());
uint maxBorrow = getMaxBorrow(_cAddresses[1], address(this));
uint borrowAmount = (_exData.srcAmount > maxBorrow) ? maxBorrow : _exData.srcAmount;
require(CTokenInterface(_cAddresses[1]).borrow(borrowAmount) == 0);
address collToken = getUnderlyingAddr(_cAddresses[0]);
address borrowToken = getUnderlyingAddr(_cAddresses[1]);
uint swapAmount = 0;
if (collToken != borrowToken) {
borrowAmount -= getFee(borrowAmount, user, _gasCost, _cAddresses[1]);
_exData.srcAmount = borrowAmount;
(,swapAmount) = _sell(_exData);
} else {
swapAmount = borrowAmount;
swapAmount -= getGasCost(swapAmount, _gasCost, _cAddresses[1]);
}
approveCToken(collToken, _cAddresses[0]);
if (collToken != ETH_ADDRESS) {
require(CTokenInterface(_cAddresses[0]).mint(swapAmount) == 0);
} else {
CEtherInterface(_cAddresses[0]).mint{value: swapAmount}(); // reverts on fail
}
// handle 0x fee
tx.origin.transfer(address(this).balance);
// log amount, collToken, borrowToken
logger.Log(address(this), msg.sender, "CreamBoost", abi.encode(_exData.srcAmount, swapAmount, collToken, borrowToken));
}
}
contract SaverExchange is SaverExchangeCore, AdminAuth, GasBurner {
using SafeERC20 for ERC20;
uint256 public constant SERVICE_FEE = 800; // 0.125% Fee
// solhint-disable-next-line const-name-snakecase
DefisaverLogger public constant logger = DefisaverLogger(0x5c55B921f590a89C1Ebe84dF170E655a82b62126);
uint public burnAmount = 10;
/// @notice Takes a src amount of tokens and converts it into the dest token
/// @dev Takes fee from the _srcAmount before the exchange
/// @param exData [srcAddr, destAddr, srcAmount, destAmount, minPrice, exchangeType, exchangeAddr, callData, price0x]
/// @param _user User address who called the exchange
function sell(ExchangeData memory exData, address payable _user) public payable burnGas(burnAmount) {
// take fee
uint dfsFee = getFee(exData.srcAmount, exData.srcAddr);
exData.srcAmount = sub(exData.srcAmount, dfsFee);
// Perform the exchange
(address wrapper, uint destAmount) = _sell(exData);
// send back any leftover ether or tokens
sendLeftover(exData.srcAddr, exData.destAddr, _user);
// log the event
logger.Log(address(this), msg.sender, "ExchangeSell", abi.encode(wrapper, exData.srcAddr, exData.destAddr, exData.srcAmount, destAmount));
}
/// @notice Takes a dest amount of tokens and converts it from the src token
/// @dev Send always more than needed for the swap, extra will be returned
/// @param exData [srcAddr, destAddr, srcAmount, destAmount, minPrice, exchangeType, exchangeAddr, callData, price0x]
/// @param _user User address who called the exchange
function buy(ExchangeData memory exData, address payable _user) public payable burnGas(burnAmount){
uint dfsFee = getFee(exData.srcAmount, exData.srcAddr);
exData.srcAmount = sub(exData.srcAmount, dfsFee);
// Perform the exchange
(address wrapper, uint srcAmount) = _buy(exData);
// send back any leftover ether or tokens
sendLeftover(exData.srcAddr, exData.destAddr, _user);
// log the event
logger.Log(address(this), msg.sender, "ExchangeBuy", abi.encode(wrapper, exData.srcAddr, exData.destAddr, srcAmount, exData.destAmount));
}
/// @notice Takes a feePercentage and sends it to wallet
/// @param _amount Dai amount of the whole trade
/// @param _token Address of the token
/// @return feeAmount Amount in Dai owner earned on the fee
function getFee(uint256 _amount, address _token) internal returns (uint256 feeAmount) {
uint256 fee = SERVICE_FEE;
if (Discount(DISCOUNT_ADDRESS).isCustomFeeSet(msg.sender)) {
fee = Discount(DISCOUNT_ADDRESS).getCustomServiceFee(msg.sender);
}
if (fee == 0) {
feeAmount = 0;
} else {
feeAmount = _amount / fee;
if (_token == KYBER_ETH_ADDRESS) {
WALLET_ID.transfer(feeAmount);
} else {
ERC20(_token).safeTransfer(WALLET_ID, feeAmount);
}
}
}
/// @notice Changes the amount of gas token we burn for each call
/// @dev Only callable by the owner
/// @param _newBurnAmount New amount of gas tokens to be burned
function changeBurnAmount(uint _newBurnAmount) public {
require(owner == msg.sender);
burnAmount = _newBurnAmount;
}
}
contract DFSExchange is DFSExchangeCore, AdminAuth, GasBurner {
using SafeERC20 for ERC20;
uint256 public constant SERVICE_FEE = 800; // 0.125% Fee
// solhint-disable-next-line const-name-snakecase
DefisaverLogger public constant logger = DefisaverLogger(0x5c55B921f590a89C1Ebe84dF170E655a82b62126);
uint public burnAmount = 10;
/// @notice Takes a src amount of tokens and converts it into the dest token
/// @dev Takes fee from the _srcAmount before the exchange
/// @param exData [srcAddr, destAddr, srcAmount, destAmount, minPrice, exchangeType, exchangeAddr, callData, price0x]
/// @param _user User address who called the exchange
function sell(ExchangeData memory exData, address payable _user) public payable burnGas(burnAmount) {
exData.dfsFeeDivider = SERVICE_FEE;
// Perform the exchange
(address wrapper, uint destAmount) = _sell(exData);
// send back any leftover ether or tokens
sendLeftover(exData.srcAddr, exData.destAddr, _user);
// log the event
logger.Log(address(this), msg.sender, "ExchangeSell", abi.encode(wrapper, exData.srcAddr, exData.destAddr, exData.srcAmount, destAmount));
}
/// @notice Takes a dest amount of tokens and converts it from the src token
/// @dev Send always more than needed for the swap, extra will be returned
/// @param exData [srcAddr, destAddr, srcAmount, destAmount, minPrice, exchangeType, exchangeAddr, callData, price0x]
/// @param _user User address who called the exchange
function buy(ExchangeData memory exData, address payable _user) public payable burnGas(burnAmount){
exData.dfsFeeDivider = SERVICE_FEE;
// Perform the exchange
(address wrapper, uint srcAmount) = _buy(exData);
// send back any leftover ether or tokens
sendLeftover(exData.srcAddr, exData.destAddr, _user);
// log the event
logger.Log(address(this), msg.sender, "ExchangeBuy", abi.encode(wrapper, exData.srcAddr, exData.destAddr, srcAmount, exData.destAmount));
}
/// @notice Changes the amount of gas token we burn for each call
/// @dev Only callable by the owner
/// @param _newBurnAmount New amount of gas tokens to be burned
function changeBurnAmount(uint _newBurnAmount) public {
require(owner == msg.sender);
burnAmount = _newBurnAmount;
}
}
contract MCDSaverFlashLoan is MCDSaverProxy, AdminAuth, FlashLoanReceiverBase {
ILendingPoolAddressesProvider public LENDING_POOL_ADDRESS_PROVIDER = ILendingPoolAddressesProvider(0x24a42fD28C976A61Df5D00D0599C34c4f90748c8);
constructor() FlashLoanReceiverBase(LENDING_POOL_ADDRESS_PROVIDER) public {}
struct SaverData {
uint cdpId;
uint gasCost;
uint loanAmount;
uint fee;
address joinAddr;
}
function executeOperation(
address _reserve,
uint256 _amount,
uint256 _fee,
bytes calldata _params)
external override {
//check the contract has the specified balance
require(_amount <= getBalanceInternal(address(this), _reserve),
"Invalid balance for the contract");
(
bytes memory exDataBytes,
uint cdpId,
uint gasCost,
address joinAddr,
bool isRepay
)
= abi.decode(_params, (bytes,uint256,uint256,address,bool));
ExchangeData memory exchangeData = unpackExchangeData(exDataBytes);
SaverData memory saverData = SaverData({
cdpId: cdpId,
gasCost: gasCost,
loanAmount: _amount,
fee: _fee,
joinAddr: joinAddr
});
if (isRepay) {
repayWithLoan(exchangeData, saverData);
} else {
boostWithLoan(exchangeData, saverData);
}
transferFundsBackToPoolInternal(_reserve, _amount.add(_fee));
// if there is some eth left (0x fee), return it to user
if (address(this).balance > 0) {
tx.origin.transfer(address(this).balance);
}
}
function boostWithLoan(
ExchangeData memory _exchangeData,
SaverData memory _saverData
) internal {
address user = getOwner(manager, _saverData.cdpId);
// Draw users Dai
uint maxDebt = getMaxDebt(_saverData.cdpId, manager.ilks(_saverData.cdpId));
uint daiDrawn = drawDai(_saverData.cdpId, manager.ilks(_saverData.cdpId), maxDebt);
// Swap
_exchangeData.srcAmount = daiDrawn + _saverData.loanAmount - takeFee(_saverData.gasCost, daiDrawn + _saverData.loanAmount);
_exchangeData.user = user;
_exchangeData.dfsFeeDivider = isAutomation() ? AUTOMATIC_SERVICE_FEE : MANUAL_SERVICE_FEE;
(, uint swapedAmount) = _sell(_exchangeData);
// Return collateral
addCollateral(_saverData.cdpId, _saverData.joinAddr, swapedAmount);
// Draw Dai to repay the flash loan
drawDai(_saverData.cdpId, manager.ilks(_saverData.cdpId), (_saverData.loanAmount + _saverData.fee));
logger.Log(address(this), msg.sender, "MCDFlashBoost", abi.encode(_saverData.cdpId, user, _exchangeData.srcAmount, swapedAmount));
}
function repayWithLoan(
ExchangeData memory _exchangeData,
SaverData memory _saverData
) internal {
address user = getOwner(manager, _saverData.cdpId);
bytes32 ilk = manager.ilks(_saverData.cdpId);
// Draw collateral
uint maxColl = getMaxCollateral(_saverData.cdpId, ilk, _saverData.joinAddr);
uint collDrawn = drawCollateral(_saverData.cdpId, _saverData.joinAddr, maxColl);
// Swap
_exchangeData.srcAmount = (_saverData.loanAmount + collDrawn);
_exchangeData.user = user;
_exchangeData.dfsFeeDivider = isAutomation() ? AUTOMATIC_SERVICE_FEE : MANUAL_SERVICE_FEE;
(, uint paybackAmount) = _sell(_exchangeData);
paybackAmount -= takeFee(_saverData.gasCost, paybackAmount);
paybackAmount = limitLoanAmount(_saverData.cdpId, ilk, paybackAmount, user);
// Payback the debt
paybackDebt(_saverData.cdpId, ilk, paybackAmount, user);
// Draw collateral to repay the flash loan
drawCollateral(_saverData.cdpId, _saverData.joinAddr, (_saverData.loanAmount + _saverData.fee));
logger.Log(address(this), msg.sender, "MCDFlashRepay", abi.encode(_saverData.cdpId, user, _exchangeData.srcAmount, paybackAmount));
}
/// @notice Handles that the amount is not bigger than cdp debt and not dust
function limitLoanAmount(uint _cdpId, bytes32 _ilk, uint _paybackAmount, address _owner) internal returns (uint256) {
uint debt = getAllDebt(address(vat), manager.urns(_cdpId), manager.urns(_cdpId), _ilk);
if (_paybackAmount > debt) {
ERC20(DAI_ADDRESS).transfer(_owner, (_paybackAmount - debt));
return debt;
}
uint debtLeft = debt - _paybackAmount;
(,,,, uint dust) = vat.ilks(_ilk);
dust = dust / 10**27;
// Less than dust value
if (debtLeft < dust) {
uint amountOverDust = (dust - debtLeft);
ERC20(DAI_ADDRESS).transfer(_owner, amountOverDust);
return (_paybackAmount - amountOverDust);
}
return _paybackAmount;
}
receive() external override(FlashLoanReceiverBase, DFSExchangeCore) payable {}
}
contract CompoundFlashLoanTaker is CompoundSaverProxy, ProxyPermission, GasBurner {
ILendingPool public constant lendingPool = ILendingPool(0x398eC7346DcD622eDc5ae82352F02bE94C62d119);
address payable public constant COMPOUND_SAVER_FLASH_LOAN = 0xCeB190A35D9D4804b9CE8d0CF79239f6949BfCcB;
address public constant AAVE_POOL_CORE = 0x3dfd23A6c5E8BbcFc9581d2E864a68feb6a076d3;
/// @notice Repays the position with it's own fund or with FL if needed
/// @param _exData Exchange data
/// @param _cAddresses cTokens addreses and exchange [cCollAddress, cBorrowAddress, exchangeAddress]
/// @param _gasCost Gas cost for specific transaction
function repayWithLoan(
ExchangeData memory _exData,
address[2] memory _cAddresses, // cCollAddress, cBorrowAddress
uint256 _gasCost
) public payable burnGas(25) {
uint maxColl = getMaxCollateral(_cAddresses[0], address(this));
uint availableLiquidity = getAvailableLiquidity(_exData.srcAddr);
if (_exData.srcAmount <= maxColl || availableLiquidity == 0) {
repay(_exData, _cAddresses, _gasCost);
} else {
// 0x fee
COMPOUND_SAVER_FLASH_LOAN.transfer(msg.value);
uint loanAmount = (_exData.srcAmount - maxColl);
if (loanAmount > availableLiquidity) loanAmount = availableLiquidity;
bytes memory encoded = packExchangeData(_exData);
bytes memory paramsData = abi.encode(encoded, _cAddresses, _gasCost, true, address(this));
givePermission(COMPOUND_SAVER_FLASH_LOAN);
lendingPool.flashLoan(COMPOUND_SAVER_FLASH_LOAN, getUnderlyingAddr(_cAddresses[0]), loanAmount, paramsData);
removePermission(COMPOUND_SAVER_FLASH_LOAN);
logger.Log(address(this), msg.sender, "CompoundFlashRepay", abi.encode(loanAmount, _exData.srcAmount, _cAddresses[0]));
}
}
/// @notice Boosts the position with it's own fund or with FL if needed
/// @param _exData Exchange data
/// @param _cAddresses cTokens addreses and exchange [cCollAddress, cBorrowAddress, exchangeAddress]
/// @param _gasCost Gas cost for specific transaction
function boostWithLoan(
ExchangeData memory _exData,
address[2] memory _cAddresses, // cCollAddress, cBorrowAddress
uint256 _gasCost
) public payable burnGas(20) {
uint maxBorrow = getMaxBorrow(_cAddresses[1], address(this));
uint availableLiquidity = getAvailableLiquidity(_exData.srcAddr);
if (_exData.srcAmount <= maxBorrow || availableLiquidity == 0) {
boost(_exData, _cAddresses, _gasCost);
} else {
// 0x fee
COMPOUND_SAVER_FLASH_LOAN.transfer(msg.value);
uint loanAmount = (_exData.srcAmount - maxBorrow);
if (loanAmount > availableLiquidity) loanAmount = availableLiquidity;
bytes memory paramsData = abi.encode(packExchangeData(_exData), _cAddresses, _gasCost, false, address(this));
givePermission(COMPOUND_SAVER_FLASH_LOAN);
lendingPool.flashLoan(COMPOUND_SAVER_FLASH_LOAN, getUnderlyingAddr(_cAddresses[1]), loanAmount, paramsData);
removePermission(COMPOUND_SAVER_FLASH_LOAN);
logger.Log(address(this), msg.sender, "CompoundFlashBoost", abi.encode(loanAmount, _exData.srcAmount, _cAddresses[1]));
}
}
function getAvailableLiquidity(address _tokenAddr) internal view returns (uint liquidity) {
if (_tokenAddr == KYBER_ETH_ADDRESS) {
liquidity = AAVE_POOL_CORE.balance;
} else {
liquidity = ERC20(_tokenAddr).balanceOf(AAVE_POOL_CORE);
}
}
}
contract CreamFlashLoanTaker is CreamSaverProxy, ProxyPermission, GasBurner {
ILendingPool public constant lendingPool = ILendingPool(0x398eC7346DcD622eDc5ae82352F02bE94C62d119);
address payable public constant COMPOUND_SAVER_FLASH_LOAN = 0x3ceD2067c0B057611e4E2686Dbe40028962Cc625;
address public constant AAVE_POOL_CORE = 0x3dfd23A6c5E8BbcFc9581d2E864a68feb6a076d3;
/// @notice Repays the position with it's own fund or with FL if needed
/// @param _exData Exchange data
/// @param _cAddresses cTokens addreses and exchange [cCollAddress, cBorrowAddress, exchangeAddress]
/// @param _gasCost Gas cost for specific transaction
function repayWithLoan(
ExchangeData memory _exData,
address[2] memory _cAddresses, // cCollAddress, cBorrowAddress
uint256 _gasCost
) public payable burnGas(25) {
uint maxColl = getMaxCollateral(_cAddresses[0], address(this));
uint availableLiquidity = getAvailableLiquidity(_exData.srcAddr);
if (_exData.srcAmount <= maxColl || availableLiquidity == 0) {
repay(_exData, _cAddresses, _gasCost);
} else {
// 0x fee
COMPOUND_SAVER_FLASH_LOAN.transfer(msg.value);
uint loanAmount = (_exData.srcAmount - maxColl);
bytes memory encoded = packExchangeData(_exData);
bytes memory paramsData = abi.encode(encoded, _cAddresses, _gasCost, true, address(this));
givePermission(COMPOUND_SAVER_FLASH_LOAN);
lendingPool.flashLoan(COMPOUND_SAVER_FLASH_LOAN, getUnderlyingAddr(_cAddresses[0]), loanAmount, paramsData);
removePermission(COMPOUND_SAVER_FLASH_LOAN);
logger.Log(address(this), msg.sender, "CreamFlashRepay", abi.encode(loanAmount, _exData.srcAmount, _cAddresses[0]));
}
}
/// @notice Boosts the position with it's own fund or with FL if needed
/// @param _exData Exchange data
/// @param _cAddresses cTokens addreses and exchange [cCollAddress, cBorrowAddress, exchangeAddress]
/// @param _gasCost Gas cost for specific transaction
function boostWithLoan(
ExchangeData memory _exData,
address[2] memory _cAddresses, // cCollAddress, cBorrowAddress
uint256 _gasCost
) public payable burnGas(20) {
uint maxBorrow = getMaxBorrow(_cAddresses[1], address(this));
uint availableLiquidity = getAvailableLiquidity(_exData.srcAddr);
if (_exData.srcAmount <= maxBorrow || availableLiquidity == 0) {
boost(_exData, _cAddresses, _gasCost);
} else {
// 0x fee
COMPOUND_SAVER_FLASH_LOAN.transfer(msg.value);
uint loanAmount = (_exData.srcAmount - maxBorrow);
bytes memory paramsData = abi.encode(packExchangeData(_exData), _cAddresses, _gasCost, false, address(this));
givePermission(COMPOUND_SAVER_FLASH_LOAN);
lendingPool.flashLoan(COMPOUND_SAVER_FLASH_LOAN, getUnderlyingAddr(_cAddresses[1]), loanAmount, paramsData);
removePermission(COMPOUND_SAVER_FLASH_LOAN);
logger.Log(address(this), msg.sender, "CreamFlashBoost", abi.encode(loanAmount, _exData.srcAmount, _cAddresses[1]));
}
}
function getAvailableLiquidity(address _tokenAddr) internal view returns (uint liquidity) {
if (_tokenAddr == KYBER_ETH_ADDRESS) {
liquidity = AAVE_POOL_CORE.balance;
} else {
liquidity = ERC20(_tokenAddr).balanceOf(AAVE_POOL_CORE);
}
}
}
| increase rate by 3% too account for inaccuracy between sell/buy conversion | function getBuyRate(address _srcAddr, address _destAddr, uint _destAmount) public override view returns (uint rate) {
uint256 srcRate = getSellRate(_destAddr, _srcAddr, _destAmount);
uint256 srcAmount = wmul(srcRate, _destAmount);
rate = getSellRate(_srcAddr, _destAddr, srcAmount);
rate = rate + (rate / 30);
}
| 7,334,019 | [
1,
267,
11908,
4993,
635,
890,
9,
4885,
2236,
364,
316,
25010,
3086,
357,
80,
19,
70,
9835,
4105,
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
] | [
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,
0,
0
] | [
1,
565,
445,
2882,
9835,
4727,
12,
2867,
389,
4816,
3178,
16,
1758,
389,
10488,
3178,
16,
2254,
389,
10488,
6275,
13,
1071,
3849,
1476,
1135,
261,
11890,
4993,
13,
288,
203,
203,
3639,
2254,
5034,
1705,
4727,
273,
1322,
1165,
4727,
24899,
10488,
3178,
16,
389,
4816,
3178,
16,
389,
10488,
6275,
1769,
203,
203,
3639,
2254,
5034,
1705,
6275,
273,
341,
16411,
12,
4816,
4727,
16,
389,
10488,
6275,
1769,
203,
203,
203,
203,
3639,
4993,
273,
1322,
1165,
4727,
24899,
4816,
3178,
16,
389,
10488,
3178,
16,
1705,
6275,
1769,
203,
203,
203,
203,
203,
3639,
4993,
273,
4993,
397,
261,
5141,
342,
5196,
1769,
203,
203,
565,
289,
203,
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
] |
./full_match/4/0xeFb2Cf382872f4382F328D16e6986dA6114C149a/sources/Slimeys.sol | 7500-9500: 0.12 ETH
| return 160000000000000000; | 12,360,116 | [
1,
5877,
713,
17,
8778,
713,
30,
225,
374,
18,
2138,
512,
2455,
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,
5411,
327,
2872,
12648,
12648,
31,
540,
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
] |
// File: openzeppelin-solidity/contracts/token/ERC20/IERC20.sol
pragma solidity >=0.6.0 <0.8.0;
/**
* @dev Interface of the ERC20 standard as defined in the EIP.
*/
interface IERC20 {
/**
* @dev Returns the amount of tokens in existence.
*/
function totalSupply() external view returns (uint256);
/**
* @dev Returns the amount of tokens owned by `account`.
*/
function balanceOf(address account) external view returns (uint256);
/**
* @dev Moves `amount` tokens from the caller's account to `recipient`.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/
function transfer(address recipient, uint256 amount) external returns (bool);
/**
* @dev Returns the remaining number of tokens that `spender` will be
* allowed to spend on behalf of `owner` through {transferFrom}. This is
* zero by default.
*
* This value changes when {approve} or {transferFrom} are called.
*/
function allowance(address owner, address spender) external view returns (uint256);
/**
* @dev Sets `amount` as the allowance of `spender` over the caller's tokens.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* IMPORTANT: Beware that changing an allowance with this method brings the risk
* that someone may use both the old and the new allowance by unfortunate
* transaction ordering. One possible solution to mitigate this race
* condition is to first reduce the spender's allowance to 0 and set the
* desired value afterwards:
* https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729
*
* Emits an {Approval} event.
*/
function approve(address spender, uint256 amount) external returns (bool);
/**
* @dev Moves `amount` tokens from `sender` to `recipient` using the
* allowance mechanism. `amount` is then deducted from the caller's
* allowance.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/
function transferFrom(address sender, address recipient, uint256 amount) external returns (bool);
/**
* @dev Emitted when `value` tokens are moved from one account (`from`) to
* another (`to`).
*
* Note that `value` may be zero.
*/
event Transfer(address indexed from, address indexed to, uint256 value);
/**
* @dev Emitted when the allowance of a `spender` for an `owner` is set by
* a call to {approve}. `value` is the new allowance.
*/
event Approval(address indexed owner, address indexed spender, uint256 value);
}
// File: original_contracts/IWETH.sol
pragma solidity 0.7.5;
abstract contract IWETH is IERC20 {
function deposit() external virtual payable;
function withdraw(uint256 amount) external virtual;
}
// File: original_contracts/lib/zeroxv2/LibOrderV2.sol
/* solium-disable */
pragma solidity 0.7.5;
//Taken from 0x exchange
library LibOrderV2{
struct Order {
address makerAddress; // Address that created the order.
address takerAddress; // Address that is allowed to fill the order. If set to 0, any address is allowed to fill the order.
address feeRecipientAddress; // Address that will recieve fees when order is filled.
address senderAddress; // Address that is allowed to call Exchange contract methods that affect this order. If set to 0, any address is allowed to call these methods.
uint256 makerAssetAmount; // Amount of makerAsset being offered by maker. Must be greater than 0.
uint256 takerAssetAmount; // Amount of takerAsset being bid on by maker. Must be greater than 0.
uint256 makerFee; // Amount of ZRX paid to feeRecipient by maker when order is filled. If set to 0, no transfer of ZRX from maker to feeRecipient will be attempted.
uint256 takerFee; // Amount of ZRX paid to feeRecipient by taker when order is filled. If set to 0, no transfer of ZRX from taker to feeRecipient will be attempted.
uint256 expirationTimeSeconds; // Timestamp in seconds at which order expires.
uint256 salt; // Arbitrary number to facilitate uniqueness of the order's hash.
bytes makerAssetData; // Encoded data that can be decoded by a specified proxy contract when transferring makerAsset. The last byte references the id of this proxy.
bytes takerAssetData; // Encoded data that can be decoded by a specified proxy contract when transferring takerAsset. The last byte references the id of this proxy.
}
struct FillResults {
uint256 makerAssetFilledAmount; // Total amount of makerAsset(s) filled.
uint256 takerAssetFilledAmount; // Total amount of takerAsset(s) filled.
uint256 makerFeePaid; // Total amount of ZRX paid by maker(s) to feeRecipient(s).
uint256 takerFeePaid; // Total amount of ZRX paid by taker to feeRecipients(s).
}
}
// File: original_contracts/lib/zeroxv2/IZeroxV2.sol
pragma solidity 0.7.5;
pragma experimental ABIEncoderV2;
interface IZeroxV2 {
function marketSellOrdersNoThrow(
LibOrderV2.Order[] calldata orders,
uint256 takerAssetFillAmount,
bytes[] calldata signatures
)
external
returns(LibOrderV2.FillResults memory);
}
// File: openzeppelin-solidity/contracts/math/SafeMath.sol
pragma solidity >=0.6.0 <0.8.0;
/**
* @dev Wrappers over Solidity's arithmetic operations with added overflow
* checks.
*
* Arithmetic operations in Solidity wrap on overflow. This can easily result
* in bugs, because programmers usually assume that an overflow raises an
* error, which is the standard behavior in high level programming languages.
* `SafeMath` restores this intuition by reverting the transaction when an
* operation overflows.
*
* Using this library instead of the unchecked operations eliminates an entire
* class of bugs, so it's recommended to use it always.
*/
library SafeMath {
/**
* @dev Returns the addition of two unsigned integers, reverting on
* overflow.
*
* Counterpart to Solidity's `+` operator.
*
* Requirements:
*
* - Addition cannot overflow.
*/
function add(uint256 a, uint256 b) internal pure returns (uint256) {
uint256 c = a + b;
require(c >= a, "SafeMath: addition overflow");
return c;
}
/**
* @dev Returns the subtraction of two unsigned integers, reverting on
* overflow (when the result is negative).
*
* Counterpart to Solidity's `-` operator.
*
* Requirements:
*
* - Subtraction cannot overflow.
*/
function sub(uint256 a, uint256 b) internal pure returns (uint256) {
return sub(a, b, "SafeMath: subtraction overflow");
}
/**
* @dev Returns the subtraction of two unsigned integers, reverting with custom message on
* overflow (when the result is negative).
*
* Counterpart to Solidity's `-` operator.
*
* Requirements:
*
* - Subtraction cannot overflow.
*/
function sub(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
require(b <= a, errorMessage);
uint256 c = a - b;
return c;
}
/**
* @dev Returns the multiplication of two unsigned integers, reverting on
* overflow.
*
* Counterpart to Solidity's `*` operator.
*
* Requirements:
*
* - Multiplication cannot overflow.
*/
function mul(uint256 a, uint256 b) internal pure returns (uint256) {
// Gas optimization: this is cheaper than requiring 'a' not being zero, but the
// benefit is lost if 'b' is also tested.
// See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522
if (a == 0) {
return 0;
}
uint256 c = a * b;
require(c / a == b, "SafeMath: multiplication overflow");
return c;
}
/**
* @dev Returns the integer division of two unsigned integers. Reverts on
* division by zero. The result is rounded towards zero.
*
* Counterpart to Solidity's `/` operator. Note: this function uses a
* `revert` opcode (which leaves remaining gas untouched) while Solidity
* uses an invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function div(uint256 a, uint256 b) internal pure returns (uint256) {
return div(a, b, "SafeMath: division by zero");
}
/**
* @dev Returns the integer division of two unsigned integers. Reverts with custom message on
* division by zero. The result is rounded towards zero.
*
* Counterpart to Solidity's `/` operator. Note: this function uses a
* `revert` opcode (which leaves remaining gas untouched) while Solidity
* uses an invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function div(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
require(b > 0, errorMessage);
uint256 c = a / b;
// assert(a == b * c + a % b); // There is no case in which this doesn't hold
return c;
}
/**
* @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo),
* Reverts when dividing by zero.
*
* Counterpart to Solidity's `%` operator. This function uses a `revert`
* opcode (which leaves remaining gas untouched) while Solidity uses an
* invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function mod(uint256 a, uint256 b) internal pure returns (uint256) {
return mod(a, b, "SafeMath: modulo by zero");
}
/**
* @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo),
* Reverts with custom message when dividing by zero.
*
* Counterpart to Solidity's `%` operator. This function uses a `revert`
* opcode (which leaves remaining gas untouched) while Solidity uses an
* invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function mod(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
require(b != 0, errorMessage);
return a % b;
}
}
// File: original_contracts/lib/SafeERC20.sol
pragma solidity 0.7.5;
library Address {
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;
}
function functionCall(address target, bytes memory data, string memory errorMessage) internal returns (bytes memory) {
return functionCallWithValue(target, data, 0, errorMessage);
}
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);
}
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);
}
}
}
}
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));
}
/**
* @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: original_contracts/ITokenTransferProxy.sol
pragma solidity 0.7.5;
interface ITokenTransferProxy {
function transferFrom(
address token,
address from,
address to,
uint256 amount
)
external;
function freeReduxTokens(address user, uint256 tokensToFree) external;
}
// File: original_contracts/lib/Utils.sol
pragma solidity 0.7.5;
library Utils {
using SafeMath for uint256;
using SafeERC20 for IERC20;
address constant ETH_ADDRESS = address(
0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE
);
address constant WETH_ADDRESS = address(
0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2
);
uint256 constant MAX_UINT = 2 ** 256 - 1;
/**
* @param fromToken Address of the source token
* @param toToken Address of the destination token
* @param fromAmount Amount of source tokens to be swapped
* @param toAmount Minimum destination token amount expected out of this swap
* @param expectedAmount Expected amount of destination tokens without slippage
* @param beneficiary Beneficiary address
* 0 then 100% will be transferred to beneficiary. Pass 10000 for 100%
* @param referrer referral id
* @param path Route to be taken for this swap to take place
*/
struct SellData {
address fromToken;
uint256 fromAmount;
uint256 toAmount;
uint256 expectedAmount;
address payable beneficiary;
string referrer;
bool useReduxToken;
Utils.Path[] path;
}
struct MegaSwapSellData {
address fromToken;
uint256 fromAmount;
uint256 toAmount;
uint256 expectedAmount;
address payable beneficiary;
string referrer;
bool useReduxToken;
Utils.MegaSwapPath[] path;
}
struct BuyData {
address fromToken;
address toToken;
uint256 fromAmount;
uint256 toAmount;
address payable beneficiary;
string referrer;
bool useReduxToken;
Utils.BuyRoute[] route;
}
struct Route {
address payable exchange;
address targetExchange;
uint percent;
bytes payload;
uint256 networkFee;//Network fee is associated with 0xv3 trades
}
struct MegaSwapPath {
uint256 fromAmountPercent;
Path[] path;
}
struct Path {
address to;
uint256 totalNetworkFee;//Network fee is associated with 0xv3 trades
Route[] routes;
}
struct BuyRoute {
address payable exchange;
address targetExchange;
uint256 fromAmount;
uint256 toAmount;
bytes payload;
uint256 networkFee;//Network fee is associated with 0xv3 trades
}
function ethAddress() internal pure returns (address) {return ETH_ADDRESS;}
function wethAddress() internal pure returns (address) {return WETH_ADDRESS;}
function maxUint() internal pure returns (uint256) {return MAX_UINT;}
function approve(
address addressToApprove,
address token,
uint256 amount
) internal {
if (token != ETH_ADDRESS) {
IERC20 _token = IERC20(token);
uint allowance = _token.allowance(address(this), addressToApprove);
if (allowance < amount) {
_token.safeApprove(addressToApprove, 0);
_token.safeIncreaseAllowance(addressToApprove, MAX_UINT);
}
}
}
function transferTokens(
address token,
address payable destination,
uint256 amount
)
internal
{
if (amount > 0) {
if (token == ETH_ADDRESS) {
(bool result, ) = destination.call{value: amount, gas: 4000}("");
require(result, "Failed to transfer Ether");
}
else {
IERC20(token).safeTransfer(destination, amount);
}
}
}
function tokenBalance(
address token,
address account
)
internal
view
returns (uint256)
{
if (token == ETH_ADDRESS) {
return account.balance;
} else {
return IERC20(token).balanceOf(account);
}
}
/**
* @dev Helper method to refund gas using gas tokens
*/
function refundGas(
address account,
address tokenTransferProxy,
uint256 initialGas
)
internal
{
uint256 freeBase = 14154;
uint256 freeToken = 6870;
uint256 reimburse = 24000;
uint256 tokens = initialGas.sub(
gasleft()).add(freeBase).div(reimburse.mul(2).sub(freeToken)
);
freeGasTokens(account, tokenTransferProxy, tokens);
}
/**
* @dev Helper method to free gas tokens
*/
function freeGasTokens(address account, address tokenTransferProxy, uint256 tokens) internal {
uint256 tokensToFree = tokens;
uint256 safeNumTokens = 0;
uint256 gas = gasleft();
if (gas >= 27710) {
safeNumTokens = gas.sub(27710).div(1148 + 5722 + 150);
}
if (tokensToFree > safeNumTokens) {
tokensToFree = safeNumTokens;
}
ITokenTransferProxy(tokenTransferProxy).freeReduxTokens(account, tokensToFree);
}
}
// File: original_contracts/lib/IExchange.sol
pragma solidity 0.7.5;
/**
* @dev This interface should be implemented by all exchanges which needs to integrate with the paraswap protocol
*/
interface IExchange {
/**
* @dev The function which performs the swap on an exchange.
* Exchange needs to implement this method in order to support swapping of tokens through it
* @param fromToken Address of the source token
* @param toToken Address of the destination token
* @param fromAmount Amount of source tokens to be swapped
* @param toAmount Minimum destination token amount expected out of this swap
* @param exchange Internal exchange or factory contract address for the exchange. For example Registry address for the Uniswap
* @param payload Any exchange specific data which is required can be passed in this argument in encoded format which
* will be decoded by the exchange. Each exchange will publish it's own decoding/encoding mechanism
*/
//TODO: REMOVE RETURN STATEMENT
function swap(
IERC20 fromToken,
IERC20 toToken,
uint256 fromAmount,
uint256 toAmount,
address exchange,
bytes calldata payload) external payable;
/**
* @dev The function which performs the swap on an exchange.
* Exchange needs to implement this method in order to support swapping of tokens through it
* @param fromToken Address of the source token
* @param toToken Address of the destination token
* @param fromAmount Max Amount of source tokens to be swapped
* @param toAmount Destination token amount expected out of this swap
* @param exchange Internal exchange or factory contract address for the exchange. For example Registry address for the Uniswap
* @param payload Any exchange specific data which is required can be passed in this argument in encoded format which
* will be decoded by the exchange. Each exchange will publish it's own decoding/encoding mechanism
*/
function buy(
IERC20 fromToken,
IERC20 toToken,
uint256 fromAmount,
uint256 toAmount,
address exchange,
bytes calldata payload) external payable;
/**
* @dev This function is used to perform onChainSwap. It build all the parameters onchain. Basically the information
* encoded in payload param of swap will calculated in this case
* Exchange needs to implement this method in order to support swapping of tokens through it
* @param fromToken Address of the source token
* @param toToken Address of the destination token
* @param fromAmount Amount of source tokens to be swapped
* @param toAmount Minimum destination token amount expected out of this swap
*/
function onChainSwap(
IERC20 fromToken,
IERC20 toToken,
uint256 fromAmount,
uint256 toAmount
) external payable returns (uint256);
/**
* @dev Certain adapters/exchanges needs to be initialized.
* This method will be called from Augustus
*/
function initialize(bytes calldata data) external;
/**
* @dev Returns unique identifier for the adapter
*/
function getKey() external pure returns(bytes32);
}
// File: original_contracts/lib/libraries/LibBytesRichErrors.sol
/*
Copyright 2019 ZeroEx Intl.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
pragma solidity 0.7.5;
library LibBytesRichErrors {
enum InvalidByteOperationErrorCodes {
FromLessThanOrEqualsToRequired,
ToLessThanOrEqualsLengthRequired,
LengthGreaterThanZeroRequired,
LengthGreaterThanOrEqualsFourRequired,
LengthGreaterThanOrEqualsTwentyRequired,
LengthGreaterThanOrEqualsThirtyTwoRequired,
LengthGreaterThanOrEqualsNestedBytesLengthRequired,
DestinationLengthGreaterThanOrEqualSourceLengthRequired
}
// bytes4(keccak256("InvalidByteOperationError(uint8,uint256,uint256)"))
bytes4 internal constant INVALID_BYTE_OPERATION_ERROR_SELECTOR =
0x28006595;
// solhint-disable func-name-mixedcase
function InvalidByteOperationError(
InvalidByteOperationErrorCodes errorCode,
uint256 offset,
uint256 required
)
internal
pure
returns (bytes memory)
{
return abi.encodeWithSelector(
INVALID_BYTE_OPERATION_ERROR_SELECTOR,
errorCode,
offset,
required
);
}
}
// File: original_contracts/lib/libraries/LibRichErrors.sol
/*
Copyright 2019 ZeroEx Intl.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
pragma solidity 0.7.5;
library LibRichErrors {
// bytes4(keccak256("Error(string)"))
bytes4 internal constant STANDARD_ERROR_SELECTOR = 0x08c379a0;
// solhint-disable func-name-mixedcase
/// @dev ABI encode a standard, string revert error payload.
/// This is the same payload that would be included by a `revert(string)`
/// solidity statement. It has the function signature `Error(string)`.
/// @param message The error string.
/// @return The ABI encoded error.
function StandardError(
string memory message
)
internal
pure
returns (bytes memory)
{
return abi.encodeWithSelector(
STANDARD_ERROR_SELECTOR,
bytes(message)
);
}
// solhint-enable func-name-mixedcase
/// @dev Reverts an encoded rich revert reason `errorData`.
/// @param errorData ABI encoded error data.
function rrevert(bytes memory errorData)
internal
pure
{
assembly {
revert(add(errorData, 0x20), mload(errorData))
}
}
}
// File: original_contracts/lib/libraries/LibBytes.sol
/*
Copyright 2019 ZeroEx Intl.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
pragma solidity 0.7.5;
library LibBytes {
using LibBytes for bytes;
/// @dev Reads an address from a position in a byte array.
/// @param b Byte array containing an address.
/// @param index Index in byte array of address.
/// @return result address from byte array.
function readAddress(
bytes memory b,
uint256 index
)
internal
pure
returns (address result)
{
if (b.length < index + 20) {
LibRichErrors.rrevert(LibBytesRichErrors.InvalidByteOperationError(
LibBytesRichErrors.InvalidByteOperationErrorCodes.LengthGreaterThanOrEqualsTwentyRequired,
b.length,
index + 20 // 20 is length of address
));
}
// Add offset to index:
// 1. Arrays are prefixed by 32-byte length parameter (add 32 to index)
// 2. Account for size difference between address length and 32-byte storage word (subtract 12 from index)
index += 20;
// Read address from array memory
assembly {
// 1. Add index to address of bytes array
// 2. Load 32-byte word from memory
// 3. Apply 20-byte mask to obtain address
result := and(mload(add(b, index)), 0xffffffffffffffffffffffffffffffffffffffff)
}
return result;
}
}
// File: original_contracts/AdapterStorage.sol
pragma solidity 0.7.5;
contract AdapterStorage {
mapping (bytes32 => bool) internal adapterInitialized;
mapping (bytes32 => bytes) internal adapterVsData;
ITokenTransferProxy internal _tokenTransferProxy;
function isInitialized(bytes32 key) public view returns(bool) {
return adapterInitialized[key];
}
function getData(bytes32 key) public view returns(bytes memory) {
return adapterVsData[key];
}
function getTokenTransferProxy() public view returns (address) {
return address(_tokenTransferProxy);
}
}
// File: original_contracts/lib/zeroxv2/ZeroxV2.sol
pragma solidity 0.7.5;
contract ZeroxV2 is IExchange, AdapterStorage {
using LibBytes for bytes;
struct ZeroxData {
LibOrderV2.Order[] orders;
bytes[] signatures;
}
struct LocalData {
address erc20Proxy;
}
function initialize(bytes calldata data) external override {
bytes32 key = getKey();
require(!adapterInitialized[key], "Adapter already initialized");
abi.decode(data, (LocalData));
adapterInitialized[key] = true;
adapterVsData[key] = data;
}
function swap(
IERC20 fromToken,
IERC20 toToken,
uint256 fromAmount,
uint256 toAmount,
address exchange,
bytes calldata payload
)
external
payable
override
{
address _fromToken = address(fromToken);
if (address(fromToken) == Utils.ethAddress()) {
IWETH(Utils.wethAddress()).deposit{value: fromAmount}();
}
_swap(
fromToken,
toToken,
fromAmount,
toAmount,
exchange,
payload
);
}
function buy(
IERC20 fromToken,
IERC20 toToken,
uint256 fromAmount,
uint256 toAmount,
address exchange,
bytes calldata payload
)
external
payable
override
{
address _fromToken = address(fromToken);
if (address(fromToken) == Utils.ethAddress()) {
IWETH(Utils.wethAddress()).deposit{value: fromAmount}();
_fromToken = Utils.wethAddress();
}
_swap(
fromToken,
toToken,
fromAmount,
toAmount,
exchange,
payload
);
if (address(fromToken) == Utils.ethAddress()) {
uint256 remainingAmount = Utils.tokenBalance(address(_fromToken), address(this));
if (remainingAmount > 0) {
IWETH(Utils.wethAddress()).withdraw(remainingAmount);
}
}
}
function onChainSwap(
IERC20 fromToken,
IERC20 toToken,
uint256 fromAmount,
uint256 toAmount
)
external
override
payable
returns (uint256)
{
revert("METHOD NOT SUPPORTED");
}
function getKey() public override pure returns(bytes32) {
return keccak256(abi.encodePacked("0XV2", "1.0.0"));
}
function _swap(
IERC20 fromToken,
IERC20 toToken,
uint256 fromAmount,
uint256 toAmount,
address exchange,
bytes memory payload
)
private
{
address _fromToken = address(fromToken);
address _toToken = address(toToken);
if (_fromToken == Utils.ethAddress()) {
_fromToken = Utils.wethAddress();
}
else if (_toToken == Utils.ethAddress()) {
_toToken = Utils.wethAddress();
}
ZeroxData memory data = abi.decode(payload, (ZeroxData));
bytes32 key = getKey();
bytes memory localData = adapterVsData[key];
LocalData memory lData = abi.decode(localData, (LocalData));
for (uint256 i = 0; i < data.orders.length; i++) {
address srcToken = data.orders[i].takerAssetData.readAddress(16);
require(srcToken == address(_fromToken), "Invalid from token!!");
address destToken = data.orders[i].makerAssetData.readAddress(16);
require(destToken == address(_toToken), "Invalid to token!!");
}
Utils.approve(lData.erc20Proxy, address(_fromToken), fromAmount);
IZeroxV2(exchange).marketSellOrdersNoThrow(
data.orders,
fromAmount,
data.signatures
);
if (address(toToken) == Utils.ethAddress()) {
uint256 receivedAmount = Utils.tokenBalance(Utils.wethAddress(), address(this));
IWETH(Utils.wethAddress()).withdraw(receivedAmount);
}
}
} | Total amount of makerAsset(s) filled.
| uint256 makerAssetFilledAmount; | 185,431 | [
1,
5269,
3844,
434,
312,
6388,
6672,
12,
87,
13,
6300,
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
] | [
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,
3639,
2254,
5034,
312,
6388,
6672,
29754,
6275,
31,
282,
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
] |
/////////////////////////////////////
//|________________________________//
// SPDX-License-Identifier: MIT
//|________________________________//
// A Mystery Cubes Club!
//|________________________________//
// May we choose loving expression //
// May we express creation forever //
// May a light penetrate eternity //
// May art resound through beauty //
// May we find the sight and voice //
// of our deepest creative selves //
//|________________________________//
//| with love as my intention, //
// 🧞✨💚 Divenie the Blessed
//|_______________________________//
//|______________________________//
//|_____________________________//
pragma solidity ^0.8.2;
import "@openzeppelin/contracts/token/ERC721/ERC721.sol";
import "@openzeppelin/contracts/token/ERC721/extensions/ERC721Enumerable.sol";
import "@openzeppelin/contracts/token/ERC721/extensions/ERC721URIStorage.sol";
import "@openzeppelin/contracts/access/Ownable.sol";
import "@openzeppelin/contracts/utils/math/SafeMath.sol";
import "@openzeppelin/contracts/security/ReentrancyGuard.sol";
contract MYSC is ERC721, ERC721Enumerable, ERC721URIStorage, Ownable, ReentrancyGuard {
using SafeMath for uint256;
string public baseURI = "ipfs://QmVirC6GTvMwWAqyoy5vYNXPDqtS5t4pJyCxW4ZfnaoXMY/";
uint256 public constant price = 25000000000000000; // 0.025 ETH
uint256 public constant max_Cubes = 412; ///@dev Minter mints < max_Cubes = last mint is 411
uint public cubesReserve = 22; ///@dev dev supply
uint public ticketsCount = 22; ///@dev initial ticket counter must start at reserve
uint public maxTickets = 412; ///@dev assets are 0-411, tickets are 1-412
mapping(address => uint256) public ticketbalance;
event ticketChange(address _by, uint _status);
event mintSuccess(address);
bool public ticketSaleIsActive = false;
bool public mintingSaleIsActive = false;
mapping(uint => string) public member_Name; ///@notice Club Member Name
mapping(uint => string) public cube_Quote; ///@notice Cube Wisdom Quote
mapping(uint => string) public art_Path; ///@notice Cube Art Path
mapping(uint => string) public metaverse_Path; /// @notice Metaverse Integration Ready
event cubeNameChange(address _by, uint _tokenId, string _name);
event cubeQuoteChange(address _by, uint _tokenId, string _quote);
event cubeArtChange(address _by, uint _tokenId, string _art_path);
event cubeMetaverseChange(address _by, uint _tokenId, string _quote);
constructor(string memory _URI) ERC721("A Mystery Cubes Club!", "MYSC") {
//setbaseURI(_URI);
//ticketSaleIsActive = !ticketSaleIsActive;
//mintingSaleIsActive = !mintingSaleIsActive;
}
function setbaseURI(string memory _baseURI) public onlyOwner {
baseURI = _baseURI;
}
///////////////
// TICKETS ///
/////////////
function setTicketSaleIsActive() external onlyOwner {
ticketSaleIsActive = !ticketSaleIsActive;
}
function buy_Ticket() public payable {
require(ticketSaleIsActive, "Sale must be active to acquire ticket");
require(ticketsCount < maxTickets, "There are no more tickets");
require(msg.value == price, "Not enough Ether sent");
if (ticketsCount < maxTickets) {
ticketsCount++;
ticketbalance[msg.sender]++;
emit ticketChange(msg.sender, ticketbalance[msg.sender]);
}
}
function get_My_Ticket_Balance() public view returns(uint) {
return ticketbalance[msg.sender];
}
///////////////
// MINTING ///
/////////////
function setMintingSaleIsActive() external onlyOwner {
mintingSaleIsActive = !mintingSaleIsActive;
}
///@dev main minting function
function mint_Cubes(uint amount) public {
require(mintingSaleIsActive, "Minting is not active yet"); //is minting active
_mint_With_Tickets(msg.sender, amount);
}
///@dev internal mint with number of tickets function
function _mint_With_Tickets(address account, uint256 amount) internal { //user, qty
require(amount > 0, "Invalid amount"); ///@dev qty cannot be less than 1
require(amount <= ticketbalance[account], "Not enough tickets!");
ticketbalance[account] -= amount; ///@dev subtract amount of tickets from users account balance.
for (uint256 i = 0; i < amount; i++) { //from the qty user has requested to mint, run minter
_mint();
}
}
function _mint() internal {
require(totalSupply() <= max_Cubes, "Critical, mint would exceed max supply of Cubes, please contact dev immediately");
uint mintIndex = totalSupply();
if (totalSupply() < max_Cubes) { ///@dev adds until the last asset
_safeMint(msg.sender, mintIndex);
}
emit mintSuccess(msg.sender); //event
}
///////////////
// SET ///
/////////////
///@dev metaverse_Path
function setMetaversePath(uint _tokenId, string memory _metaverse_path) public {
require(ownerOf(_tokenId) == msg.sender, "Hey, your wallet doesn't own this cube!");
require(sha256(bytes(_metaverse_path)) != sha256(bytes(metaverse_Path[_tokenId])), "Same as current");
metaverse_Path[_tokenId] = _metaverse_path;
emit cubeMetaverseChange(msg.sender, _tokenId, _metaverse_path);
}
///@dev art_Path
function setArtPath(uint _tokenId, string memory _art) public {
require(ownerOf(_tokenId) == msg.sender, "Hey, your wallet doesn't own this cube!");
require(sha256(bytes(_art)) != sha256(bytes(art_Path[_tokenId])), "Same as current");
art_Path[_tokenId] = _art;
emit cubeArtChange(msg.sender, _tokenId, _art);
}
///@dev member_Name
function setMemberName(uint _tokenId, string memory _name) public {
require(ownerOf(_tokenId) == msg.sender, "Hey, your wallet doesn't own this cube!");
require(sha256(bytes(_name)) != sha256(bytes(member_Name[_tokenId])), "Same as current");
member_Name[_tokenId] = _name;
emit cubeNameChange(msg.sender, _tokenId, _name);
}
///@dev cube_Quote
function setCubeQuote(uint _tokenId, string memory _quote) public {
require(ownerOf(_tokenId) == msg.sender, "Hey, your wallet doesn't own this cube!");
require(sha256(bytes(_quote)) != sha256(bytes(cube_Quote[_tokenId])), "Same as current");
cube_Quote[_tokenId] = _quote;
emit cubeQuoteChange(msg.sender, _tokenId, _quote);
}
///////////////
// GET ///
/////////////
function getMetaversePath(uint _tokenId) public view returns( string memory ){
require( _tokenId < totalSupply(), "Choose a cube within range" );
return metaverse_Path[_tokenId];
}
function getCubeData(uint _tokenId) public view returns( string memory, string memory, string memory){
require( _tokenId < totalSupply(), "Choose a cube within range" );
return(member_Name[_tokenId], cube_Quote[_tokenId], art_Path[_tokenId]);
}
///////////////
// GET ALL ///
/////////////
///@dev get all names in all cubes
function allName() public view returns( string[] memory ){
uint cubecount = totalSupply();
string[] memory result_Name = new string[](cubecount);
uint256 index;
for (index = 0; index < cubecount; index++) {
result_Name[index] = member_Name[index];
}
return result_Name;
}
///@dev get all quotes in all cubes
function allCubeQuote() public view returns( string[] memory ){
uint cubecount = totalSupply();
string[] memory result = new string[](cubecount);
uint256 index;
for (index = 0; index < cubecount; index++) {
result[index] = cube_Quote[index];
}
return result;
}
///@dev get all metaverse links in all cubes
function allMetaverse() public view returns(string[] memory){
uint cubecount = totalSupply();
string[] memory result_Metaverse = new string[](cubecount);
uint256 index;
for (index = 0; index < cubecount; index++) {
result_Metaverse[index] = metaverse_Path[index];
}
return (result_Metaverse);
}
///////////////
// OWNER ///
/////////////
/// Withdraw contract balance to creator (mnemonic seed address 0) // from Bauhaus
function withdraw() public onlyOwner {
uint256 balance = address(this).balance;
payable(msg.sender).transfer(balance);
}
///@dev Owner reserve NFT function
function reserveCubes(address _to, uint256 _reserveAmount) public onlyOwner {
uint supply = totalSupply();
require(_reserveAmount > 0 && _reserveAmount <= cubesReserve, "Not enough reserve left");
for (uint i = 0; i < _reserveAmount; i++) {
_safeMint(_to, supply + i);
}
cubesReserve = cubesReserve.sub(_reserveAmount);
}
///////////////
// OVERRIDES /
/////////////
function tokenURI(uint256 tokenId) ///@dev Bauhaus TokenURI
public
view
override(ERC721, ERC721URIStorage)
returns (string memory)
{
return string(abi.encodePacked(baseURI, Strings.toString(tokenId)));
}
function _beforeTokenTransfer(address from, address to, uint256 tokenId)
internal
override(ERC721, ERC721Enumerable)
{
super._beforeTokenTransfer(from, to, tokenId);
}
function _burn(uint256 tokenId) internal override(ERC721, ERC721URIStorage) {
super._burn(tokenId);
}
function supportsInterface(bytes4 interfaceId)
public
view
override(ERC721, ERC721Enumerable)
returns (bool)
{
return super.supportsInterface(interfaceId);
}
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.0 (token/ERC721/ERC721.sol)
pragma solidity ^0.8.0;
import "./IERC721.sol";
import "./IERC721Receiver.sol";
import "./extensions/IERC721Metadata.sol";
import "../../utils/Address.sol";
import "../../utils/Context.sol";
import "../../utils/Strings.sol";
import "../../utils/introspection/ERC165.sol";
/**
* @dev Implementation of https://eips.ethereum.org/EIPS/eip-721[ERC721] Non-Fungible Token Standard, including
* the Metadata extension, but not including the Enumerable extension, which is available separately as
* {ERC721Enumerable}.
*/
contract ERC721 is Context, ERC165, IERC721, IERC721Metadata {
using Address for address;
using Strings for uint256;
// Token name
string private _name;
// Token symbol
string private _symbol;
// Mapping from token ID to owner address
mapping(uint256 => address) private _owners;
// Mapping owner address to token count
mapping(address => uint256) private _balances;
// Mapping from token ID to approved address
mapping(uint256 => address) private _tokenApprovals;
// Mapping from owner to operator approvals
mapping(address => mapping(address => bool)) private _operatorApprovals;
/**
* @dev Initializes the contract by setting a `name` and a `symbol` to the token collection.
*/
constructor(string memory name_, string memory symbol_) {
_name = name_;
_symbol = symbol_;
}
/**
* @dev See {IERC165-supportsInterface}.
*/
function supportsInterface(bytes4 interfaceId) public view virtual override(ERC165, IERC165) returns (bool) {
return
interfaceId == type(IERC721).interfaceId ||
interfaceId == type(IERC721Metadata).interfaceId ||
super.supportsInterface(interfaceId);
}
/**
* @dev See {IERC721-balanceOf}.
*/
function balanceOf(address owner) public view virtual override returns (uint256) {
require(owner != address(0), "ERC721: balance query for the zero address");
return _balances[owner];
}
/**
* @dev See {IERC721-ownerOf}.
*/
function ownerOf(uint256 tokenId) public view virtual override returns (address) {
address owner = _owners[tokenId];
require(owner != address(0), "ERC721: owner query for nonexistent token");
return owner;
}
/**
* @dev See {IERC721Metadata-name}.
*/
function name() public view virtual override returns (string memory) {
return _name;
}
/**
* @dev See {IERC721Metadata-symbol}.
*/
function symbol() public view virtual override returns (string memory) {
return _symbol;
}
/**
* @dev See {IERC721Metadata-tokenURI}.
*/
function tokenURI(uint256 tokenId) public view virtual override returns (string memory) {
require(_exists(tokenId), "ERC721Metadata: URI query for nonexistent token");
string memory baseURI = _baseURI();
return bytes(baseURI).length > 0 ? string(abi.encodePacked(baseURI, tokenId.toString())) : "";
}
/**
* @dev Base URI for computing {tokenURI}. If set, the resulting URI for each
* token will be the concatenation of the `baseURI` and the `tokenId`. Empty
* by default, can be overriden in child contracts.
*/
function _baseURI() internal view virtual returns (string memory) {
return "";
}
/**
* @dev See {IERC721-approve}.
*/
function approve(address to, uint256 tokenId) public virtual override {
address owner = ERC721.ownerOf(tokenId);
require(to != owner, "ERC721: approval to current owner");
require(
_msgSender() == owner || isApprovedForAll(owner, _msgSender()),
"ERC721: approve caller is not owner nor approved for all"
);
_approve(to, tokenId);
}
/**
* @dev See {IERC721-getApproved}.
*/
function getApproved(uint256 tokenId) public view virtual override returns (address) {
require(_exists(tokenId), "ERC721: approved query for nonexistent token");
return _tokenApprovals[tokenId];
}
/**
* @dev See {IERC721-setApprovalForAll}.
*/
function setApprovalForAll(address operator, bool approved) public virtual override {
_setApprovalForAll(_msgSender(), operator, approved);
}
/**
* @dev See {IERC721-isApprovedForAll}.
*/
function isApprovedForAll(address owner, address operator) public view virtual override returns (bool) {
return _operatorApprovals[owner][operator];
}
/**
* @dev See {IERC721-transferFrom}.
*/
function transferFrom(
address from,
address to,
uint256 tokenId
) public virtual override {
//solhint-disable-next-line max-line-length
require(_isApprovedOrOwner(_msgSender(), tokenId), "ERC721: transfer caller is not owner nor approved");
_transfer(from, to, tokenId);
}
/**
* @dev See {IERC721-safeTransferFrom}.
*/
function safeTransferFrom(
address from,
address to,
uint256 tokenId
) public virtual override {
safeTransferFrom(from, to, tokenId, "");
}
/**
* @dev See {IERC721-safeTransferFrom}.
*/
function safeTransferFrom(
address from,
address to,
uint256 tokenId,
bytes memory _data
) public virtual override {
require(_isApprovedOrOwner(_msgSender(), tokenId), "ERC721: transfer caller is not owner nor approved");
_safeTransfer(from, to, tokenId, _data);
}
/**
* @dev Safely transfers `tokenId` token from `from` to `to`, checking first that contract recipients
* are aware of the ERC721 protocol to prevent tokens from being forever locked.
*
* `_data` is additional data, it has no specified format and it is sent in call to `to`.
*
* This internal function is equivalent to {safeTransferFrom}, and can be used to e.g.
* implement alternative mechanisms to perform token transfer, such as signature-based.
*
* Requirements:
*
* - `from` cannot be the zero address.
* - `to` cannot be the zero address.
* - `tokenId` token must exist and be owned by `from`.
* - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer.
*
* Emits a {Transfer} event.
*/
function _safeTransfer(
address from,
address to,
uint256 tokenId,
bytes memory _data
) internal virtual {
_transfer(from, to, tokenId);
require(_checkOnERC721Received(from, to, tokenId, _data), "ERC721: transfer to non ERC721Receiver implementer");
}
/**
* @dev Returns whether `tokenId` exists.
*
* Tokens can be managed by their owner or approved accounts via {approve} or {setApprovalForAll}.
*
* Tokens start existing when they are minted (`_mint`),
* and stop existing when they are burned (`_burn`).
*/
function _exists(uint256 tokenId) internal view virtual returns (bool) {
return _owners[tokenId] != address(0);
}
/**
* @dev Returns whether `spender` is allowed to manage `tokenId`.
*
* Requirements:
*
* - `tokenId` must exist.
*/
function _isApprovedOrOwner(address spender, uint256 tokenId) internal view virtual returns (bool) {
require(_exists(tokenId), "ERC721: operator query for nonexistent token");
address owner = ERC721.ownerOf(tokenId);
return (spender == owner || getApproved(tokenId) == spender || isApprovedForAll(owner, spender));
}
/**
* @dev Safely mints `tokenId` and transfers it to `to`.
*
* Requirements:
*
* - `tokenId` must not exist.
* - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer.
*
* Emits a {Transfer} event.
*/
function _safeMint(address to, uint256 tokenId) internal virtual {
_safeMint(to, tokenId, "");
}
/**
* @dev Same as {xref-ERC721-_safeMint-address-uint256-}[`_safeMint`], with an additional `data` parameter which is
* forwarded in {IERC721Receiver-onERC721Received} to contract recipients.
*/
function _safeMint(
address to,
uint256 tokenId,
bytes memory _data
) internal virtual {
_mint(to, tokenId);
require(
_checkOnERC721Received(address(0), to, tokenId, _data),
"ERC721: transfer to non ERC721Receiver implementer"
);
}
/**
* @dev Mints `tokenId` and transfers it to `to`.
*
* WARNING: Usage of this method is discouraged, use {_safeMint} whenever possible
*
* Requirements:
*
* - `tokenId` must not exist.
* - `to` cannot be the zero address.
*
* Emits a {Transfer} event.
*/
function _mint(address to, uint256 tokenId) internal virtual {
require(to != address(0), "ERC721: mint to the zero address");
require(!_exists(tokenId), "ERC721: token already minted");
_beforeTokenTransfer(address(0), to, tokenId);
_balances[to] += 1;
_owners[tokenId] = to;
emit Transfer(address(0), to, tokenId);
}
/**
* @dev Destroys `tokenId`.
* The approval is cleared when the token is burned.
*
* Requirements:
*
* - `tokenId` must exist.
*
* Emits a {Transfer} event.
*/
function _burn(uint256 tokenId) internal virtual {
address owner = ERC721.ownerOf(tokenId);
_beforeTokenTransfer(owner, address(0), tokenId);
// Clear approvals
_approve(address(0), tokenId);
_balances[owner] -= 1;
delete _owners[tokenId];
emit Transfer(owner, address(0), tokenId);
}
/**
* @dev Transfers `tokenId` from `from` to `to`.
* As opposed to {transferFrom}, this imposes no restrictions on msg.sender.
*
* Requirements:
*
* - `to` cannot be the zero address.
* - `tokenId` token must be owned by `from`.
*
* Emits a {Transfer} event.
*/
function _transfer(
address from,
address to,
uint256 tokenId
) internal virtual {
require(ERC721.ownerOf(tokenId) == from, "ERC721: transfer of token that is not own");
require(to != address(0), "ERC721: transfer to the zero address");
_beforeTokenTransfer(from, to, tokenId);
// Clear approvals from the previous owner
_approve(address(0), tokenId);
_balances[from] -= 1;
_balances[to] += 1;
_owners[tokenId] = to;
emit Transfer(from, to, tokenId);
}
/**
* @dev Approve `to` to operate on `tokenId`
*
* Emits a {Approval} event.
*/
function _approve(address to, uint256 tokenId) internal virtual {
_tokenApprovals[tokenId] = to;
emit Approval(ERC721.ownerOf(tokenId), to, tokenId);
}
/**
* @dev Approve `operator` to operate on all of `owner` tokens
*
* Emits a {ApprovalForAll} event.
*/
function _setApprovalForAll(
address owner,
address operator,
bool approved
) internal virtual {
require(owner != operator, "ERC721: approve to caller");
_operatorApprovals[owner][operator] = approved;
emit ApprovalForAll(owner, operator, approved);
}
/**
* @dev Internal function to invoke {IERC721Receiver-onERC721Received} on a target address.
* The call is not executed if the target address is not a contract.
*
* @param from address representing the previous owner of the given token ID
* @param to target address that will receive the tokens
* @param tokenId uint256 ID of the token to be transferred
* @param _data bytes optional data to send along with the call
* @return bool whether the call correctly returned the expected magic value
*/
function _checkOnERC721Received(
address from,
address to,
uint256 tokenId,
bytes memory _data
) private returns (bool) {
if (to.isContract()) {
try IERC721Receiver(to).onERC721Received(_msgSender(), from, tokenId, _data) returns (bytes4 retval) {
return retval == IERC721Receiver.onERC721Received.selector;
} catch (bytes memory reason) {
if (reason.length == 0) {
revert("ERC721: transfer to non ERC721Receiver implementer");
} else {
assembly {
revert(add(32, reason), mload(reason))
}
}
}
} else {
return true;
}
}
/**
* @dev Hook that is called before any token transfer. This includes minting
* and burning.
*
* Calling conditions:
*
* - When `from` and `to` are both non-zero, ``from``'s `tokenId` will be
* transferred to `to`.
* - When `from` is zero, `tokenId` will be minted for `to`.
* - When `to` is zero, ``from``'s `tokenId` will be burned.
* - `from` and `to` are never both zero.
*
* To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks].
*/
function _beforeTokenTransfer(
address from,
address to,
uint256 tokenId
) internal virtual {}
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.0 (token/ERC721/extensions/ERC721Enumerable.sol)
pragma solidity ^0.8.0;
import "../ERC721.sol";
import "./IERC721Enumerable.sol";
/**
* @dev This implements an optional extension of {ERC721} defined in the EIP that adds
* enumerability of all the token ids in the contract as well as all token ids owned by each
* account.
*/
abstract contract ERC721Enumerable is ERC721, IERC721Enumerable {
// Mapping from owner to list of owned token IDs
mapping(address => mapping(uint256 => uint256)) private _ownedTokens;
// Mapping from token ID to index of the owner tokens list
mapping(uint256 => uint256) private _ownedTokensIndex;
// Array with all token ids, used for enumeration
uint256[] private _allTokens;
// Mapping from token id to position in the allTokens array
mapping(uint256 => uint256) private _allTokensIndex;
/**
* @dev See {IERC165-supportsInterface}.
*/
function supportsInterface(bytes4 interfaceId) public view virtual override(IERC165, ERC721) returns (bool) {
return interfaceId == type(IERC721Enumerable).interfaceId || super.supportsInterface(interfaceId);
}
/**
* @dev See {IERC721Enumerable-tokenOfOwnerByIndex}.
*/
function tokenOfOwnerByIndex(address owner, uint256 index) public view virtual override returns (uint256) {
require(index < ERC721.balanceOf(owner), "ERC721Enumerable: owner index out of bounds");
return _ownedTokens[owner][index];
}
/**
* @dev See {IERC721Enumerable-totalSupply}.
*/
function totalSupply() public view virtual override returns (uint256) {
return _allTokens.length;
}
/**
* @dev See {IERC721Enumerable-tokenByIndex}.
*/
function tokenByIndex(uint256 index) public view virtual override returns (uint256) {
require(index < ERC721Enumerable.totalSupply(), "ERC721Enumerable: global index out of bounds");
return _allTokens[index];
}
/**
* @dev Hook that is called before any token transfer. This includes minting
* and burning.
*
* Calling conditions:
*
* - When `from` and `to` are both non-zero, ``from``'s `tokenId` will be
* transferred to `to`.
* - When `from` is zero, `tokenId` will be minted for `to`.
* - When `to` is zero, ``from``'s `tokenId` will be burned.
* - `from` cannot be the zero address.
* - `to` cannot be the zero address.
*
* To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks].
*/
function _beforeTokenTransfer(
address from,
address to,
uint256 tokenId
) internal virtual override {
super._beforeTokenTransfer(from, to, tokenId);
if (from == address(0)) {
_addTokenToAllTokensEnumeration(tokenId);
} else if (from != to) {
_removeTokenFromOwnerEnumeration(from, tokenId);
}
if (to == address(0)) {
_removeTokenFromAllTokensEnumeration(tokenId);
} else if (to != from) {
_addTokenToOwnerEnumeration(to, tokenId);
}
}
/**
* @dev Private function to add a token to this extension's ownership-tracking data structures.
* @param to address representing the new owner of the given token ID
* @param tokenId uint256 ID of the token to be added to the tokens list of the given address
*/
function _addTokenToOwnerEnumeration(address to, uint256 tokenId) private {
uint256 length = ERC721.balanceOf(to);
_ownedTokens[to][length] = tokenId;
_ownedTokensIndex[tokenId] = length;
}
/**
* @dev Private function to add a token to this extension's token tracking data structures.
* @param tokenId uint256 ID of the token to be added to the tokens list
*/
function _addTokenToAllTokensEnumeration(uint256 tokenId) private {
_allTokensIndex[tokenId] = _allTokens.length;
_allTokens.push(tokenId);
}
/**
* @dev Private function to remove a token from this extension's ownership-tracking data structures. Note that
* while the token is not assigned a new owner, the `_ownedTokensIndex` mapping is _not_ updated: this allows for
* gas optimizations e.g. when performing a transfer operation (avoiding double writes).
* This has O(1) time complexity, but alters the order of the _ownedTokens array.
* @param from address representing the previous owner of the given token ID
* @param tokenId uint256 ID of the token to be removed from the tokens list of the given address
*/
function _removeTokenFromOwnerEnumeration(address from, uint256 tokenId) private {
// To prevent a gap in from's tokens array, we store the last token in the index of the token to delete, and
// then delete the last slot (swap and pop).
uint256 lastTokenIndex = ERC721.balanceOf(from) - 1;
uint256 tokenIndex = _ownedTokensIndex[tokenId];
// When the token to delete is the last token, the swap operation is unnecessary
if (tokenIndex != lastTokenIndex) {
uint256 lastTokenId = _ownedTokens[from][lastTokenIndex];
_ownedTokens[from][tokenIndex] = lastTokenId; // Move the last token to the slot of the to-delete token
_ownedTokensIndex[lastTokenId] = tokenIndex; // Update the moved token's index
}
// This also deletes the contents at the last position of the array
delete _ownedTokensIndex[tokenId];
delete _ownedTokens[from][lastTokenIndex];
}
/**
* @dev Private function to remove a token from this extension's token tracking data structures.
* This has O(1) time complexity, but alters the order of the _allTokens array.
* @param tokenId uint256 ID of the token to be removed from the tokens list
*/
function _removeTokenFromAllTokensEnumeration(uint256 tokenId) private {
// To prevent a gap in the tokens array, we store the last token in the index of the token to delete, and
// then delete the last slot (swap and pop).
uint256 lastTokenIndex = _allTokens.length - 1;
uint256 tokenIndex = _allTokensIndex[tokenId];
// When the token to delete is the last token, the swap operation is unnecessary. However, since this occurs so
// rarely (when the last minted token is burnt) that we still do the swap here to avoid the gas cost of adding
// an 'if' statement (like in _removeTokenFromOwnerEnumeration)
uint256 lastTokenId = _allTokens[lastTokenIndex];
_allTokens[tokenIndex] = lastTokenId; // Move the last token to the slot of the to-delete token
_allTokensIndex[lastTokenId] = tokenIndex; // Update the moved token's index
// This also deletes the contents at the last position of the array
delete _allTokensIndex[tokenId];
_allTokens.pop();
}
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.0 (token/ERC721/extensions/ERC721URIStorage.sol)
pragma solidity ^0.8.0;
import "../ERC721.sol";
/**
* @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];
}
}
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.0 (access/Ownable.sol)
pragma solidity ^0.8.0;
import "../utils/Context.sol";
/**
* @dev Contract module which provides a basic access control mechanism, where
* there is an account (an owner) that can be granted exclusive access to
* specific functions.
*
* By default, the owner account will be the one that deploys the contract. This
* can later be changed with {transferOwnership}.
*
* This module is used through inheritance. It will make available the modifier
* `onlyOwner`, which can be applied to your functions to restrict their use to
* the owner.
*/
abstract contract Ownable is Context {
address private _owner;
event OwnershipTransferred(address indexed previousOwner, address indexed newOwner);
/**
* @dev Initializes the contract setting the deployer as the initial owner.
*/
constructor() {
_transferOwnership(_msgSender());
}
/**
* @dev Returns the address of the current owner.
*/
function owner() public view virtual returns (address) {
return _owner;
}
/**
* @dev Throws if called by any account other than the owner.
*/
modifier onlyOwner() {
require(owner() == _msgSender(), "Ownable: caller is not the owner");
_;
}
/**
* @dev Leaves the contract without owner. It will not be possible to call
* `onlyOwner` functions anymore. Can only be called by the current owner.
*
* NOTE: Renouncing ownership will leave the contract without an owner,
* thereby removing any functionality that is only available to the owner.
*/
function renounceOwnership() public virtual onlyOwner {
_transferOwnership(address(0));
}
/**
* @dev Transfers ownership of the contract to a new account (`newOwner`).
* Can only be called by the current owner.
*/
function transferOwnership(address newOwner) public virtual onlyOwner {
require(newOwner != address(0), "Ownable: new owner is the zero address");
_transferOwnership(newOwner);
}
/**
* @dev Transfers ownership of the contract to a new account (`newOwner`).
* Internal function without access restriction.
*/
function _transferOwnership(address newOwner) internal virtual {
address oldOwner = _owner;
_owner = newOwner;
emit OwnershipTransferred(oldOwner, newOwner);
}
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.0 (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.0 (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.0 (token/ERC721/IERC721.sol)
pragma solidity ^0.8.0;
import "../../utils/introspection/IERC165.sol";
/**
* @dev Required interface of an ERC721 compliant contract.
*/
interface IERC721 is IERC165 {
/**
* @dev Emitted when `tokenId` token is transferred from `from` to `to`.
*/
event Transfer(address indexed from, address indexed to, uint256 indexed tokenId);
/**
* @dev Emitted when `owner` enables `approved` to manage the `tokenId` token.
*/
event Approval(address indexed owner, address indexed approved, uint256 indexed tokenId);
/**
* @dev Emitted when `owner` enables or disables (`approved`) `operator` to manage all of its assets.
*/
event ApprovalForAll(address indexed owner, address indexed operator, bool approved);
/**
* @dev Returns the number of tokens in ``owner``'s account.
*/
function balanceOf(address owner) external view returns (uint256 balance);
/**
* @dev Returns the owner of the `tokenId` token.
*
* Requirements:
*
* - `tokenId` must exist.
*/
function ownerOf(uint256 tokenId) external view returns (address owner);
/**
* @dev Safely transfers `tokenId` token from `from` to `to`, checking first that contract recipients
* are aware of the ERC721 protocol to prevent tokens from being forever locked.
*
* Requirements:
*
* - `from` cannot be the zero address.
* - `to` cannot be the zero address.
* - `tokenId` token must exist and be owned by `from`.
* - If the caller is not `from`, it must be have been allowed to move this token by either {approve} or {setApprovalForAll}.
* - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer.
*
* Emits a {Transfer} event.
*/
function safeTransferFrom(
address from,
address to,
uint256 tokenId
) external;
/**
* @dev Transfers `tokenId` token from `from` to `to`.
*
* WARNING: Usage of this method is discouraged, use {safeTransferFrom} whenever possible.
*
* Requirements:
*
* - `from` cannot be the zero address.
* - `to` cannot be the zero address.
* - `tokenId` token must be owned by `from`.
* - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}.
*
* Emits a {Transfer} event.
*/
function transferFrom(
address from,
address to,
uint256 tokenId
) external;
/**
* @dev Gives permission to `to` to transfer `tokenId` token to another account.
* The approval is cleared when the token is transferred.
*
* Only a single account can be approved at a time, so approving the zero address clears previous approvals.
*
* Requirements:
*
* - The caller must own the token or be an approved operator.
* - `tokenId` must exist.
*
* Emits an {Approval} event.
*/
function approve(address to, uint256 tokenId) external;
/**
* @dev Returns the account approved for `tokenId` token.
*
* Requirements:
*
* - `tokenId` must exist.
*/
function getApproved(uint256 tokenId) external view returns (address operator);
/**
* @dev Approve or remove `operator` as an operator for the caller.
* Operators can call {transferFrom} or {safeTransferFrom} for any token owned by the caller.
*
* Requirements:
*
* - The `operator` cannot be the caller.
*
* Emits an {ApprovalForAll} event.
*/
function setApprovalForAll(address operator, bool _approved) external;
/**
* @dev Returns if the `operator` is allowed to manage all of the assets of `owner`.
*
* See {setApprovalForAll}
*/
function isApprovedForAll(address owner, address operator) external view returns (bool);
/**
* @dev Safely transfers `tokenId` token from `from` to `to`.
*
* Requirements:
*
* - `from` cannot be the zero address.
* - `to` cannot be the zero address.
* - `tokenId` token must exist and be owned by `from`.
* - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}.
* - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer.
*
* Emits a {Transfer} event.
*/
function safeTransferFrom(
address from,
address to,
uint256 tokenId,
bytes calldata data
) external;
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.0 (token/ERC721/IERC721Receiver.sol)
pragma solidity ^0.8.0;
/**
* @title ERC721 token receiver interface
* @dev Interface for any contract that wants to support safeTransfers
* from ERC721 asset contracts.
*/
interface IERC721Receiver {
/**
* @dev Whenever an {IERC721} `tokenId` token is transferred to this contract via {IERC721-safeTransferFrom}
* by `operator` from `from`, this function is called.
*
* It must return its Solidity selector to confirm the token transfer.
* If any other value is returned or the interface is not implemented by the recipient, the transfer will be reverted.
*
* The selector can be obtained in Solidity with `IERC721.onERC721Received.selector`.
*/
function onERC721Received(
address operator,
address from,
uint256 tokenId,
bytes calldata data
) external returns (bytes4);
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.0 (token/ERC721/extensions/IERC721Metadata.sol)
pragma solidity ^0.8.0;
import "../IERC721.sol";
/**
* @title ERC-721 Non-Fungible Token Standard, optional metadata extension
* @dev See https://eips.ethereum.org/EIPS/eip-721
*/
interface IERC721Metadata is IERC721 {
/**
* @dev Returns the token collection name.
*/
function name() external view returns (string memory);
/**
* @dev Returns the token collection symbol.
*/
function symbol() external view returns (string memory);
/**
* @dev Returns the Uniform Resource Identifier (URI) for `tokenId` token.
*/
function tokenURI(uint256 tokenId) external view returns (string memory);
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.0 (utils/Address.sol)
pragma solidity ^0.8.0;
/**
* @dev Collection of functions related to the address type
*/
library Address {
/**
* @dev Returns true if `account` is a contract.
*
* [IMPORTANT]
* ====
* It is unsafe to assume that an address for which this function returns
* false is an externally-owned account (EOA) and not a contract.
*
* Among others, `isContract` will return false for the following
* types of addresses:
*
* - an externally-owned account
* - a contract in construction
* - an address where a contract will be created
* - an address where a contract lived, but was destroyed
* ====
*/
function isContract(address account) internal view returns (bool) {
// This method relies on extcodesize, which returns 0 for contracts in
// construction, since the code is only stored at the end of the
// constructor execution.
uint256 size;
assembly {
size := extcodesize(account)
}
return size > 0;
}
/**
* @dev Replacement for Solidity's `transfer`: sends `amount` wei to
* `recipient`, forwarding all available gas and reverting on errors.
*
* https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost
* of certain opcodes, possibly making contracts go over the 2300 gas limit
* imposed by `transfer`, making them unable to receive funds via
* `transfer`. {sendValue} removes this limitation.
*
* https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more].
*
* IMPORTANT: because control is transferred to `recipient`, care must be
* taken to not create reentrancy vulnerabilities. Consider using
* {ReentrancyGuard} or the
* https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern].
*/
function sendValue(address payable recipient, uint256 amount) internal {
require(address(this).balance >= amount, "Address: insufficient balance");
(bool success, ) = recipient.call{value: amount}("");
require(success, "Address: unable to send value, recipient may have reverted");
}
/**
* @dev Performs a Solidity function call using a low level `call`. A
* plain `call` is an unsafe replacement for a function call: use this
* function instead.
*
* If `target` reverts with a revert reason, it is bubbled up by this
* function (like regular Solidity function calls).
*
* Returns the raw returned data. To convert to the expected return value,
* use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`].
*
* Requirements:
*
* - `target` must be a contract.
* - calling `target` with `data` must not revert.
*
* _Available since v3.1._
*/
function functionCall(address target, bytes memory data) internal returns (bytes memory) {
return functionCall(target, data, "Address: low-level call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with
* `errorMessage` as a fallback revert reason when `target` reverts.
*
* _Available since v3.1._
*/
function functionCall(
address target,
bytes memory data,
string memory errorMessage
) internal returns (bytes memory) {
return functionCallWithValue(target, data, 0, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but also transferring `value` wei to `target`.
*
* Requirements:
*
* - the calling contract must have an ETH balance of at least `value`.
* - the called Solidity function must be `payable`.
*
* _Available since v3.1._
*/
function functionCallWithValue(
address target,
bytes memory data,
uint256 value
) internal returns (bytes memory) {
return functionCallWithValue(target, data, value, "Address: low-level call with value failed");
}
/**
* @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but
* with `errorMessage` as a fallback revert reason when `target` reverts.
*
* _Available since v3.1._
*/
function functionCallWithValue(
address target,
bytes memory data,
uint256 value,
string memory errorMessage
) internal returns (bytes memory) {
require(address(this).balance >= value, "Address: insufficient balance for call");
require(isContract(target), "Address: call to non-contract");
(bool success, bytes memory returndata) = target.call{value: value}(data);
return verifyCallResult(success, returndata, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but performing a static call.
*
* _Available since v3.3._
*/
function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) {
return functionStaticCall(target, data, "Address: low-level static call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`],
* but performing a static call.
*
* _Available since v3.3._
*/
function functionStaticCall(
address target,
bytes memory data,
string memory errorMessage
) internal view returns (bytes memory) {
require(isContract(target), "Address: static call to non-contract");
(bool success, bytes memory returndata) = target.staticcall(data);
return verifyCallResult(success, returndata, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but performing a delegate call.
*
* _Available since v3.4._
*/
function functionDelegateCall(address target, bytes memory data) internal returns (bytes memory) {
return functionDelegateCall(target, data, "Address: low-level delegate call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`],
* but performing a delegate call.
*
* _Available since v3.4._
*/
function functionDelegateCall(
address target,
bytes memory data,
string memory errorMessage
) internal returns (bytes memory) {
require(isContract(target), "Address: delegate call to non-contract");
(bool success, bytes memory returndata) = target.delegatecall(data);
return verifyCallResult(success, returndata, errorMessage);
}
/**
* @dev Tool to verifies that a low level call was successful, and revert if it wasn't, either by bubbling the
* revert reason using the provided one.
*
* _Available since v4.3._
*/
function verifyCallResult(
bool success,
bytes memory returndata,
string memory errorMessage
) internal pure returns (bytes memory) {
if (success) {
return returndata;
} else {
// Look for revert reason and bubble it up if present
if (returndata.length > 0) {
// The easiest way to bubble the revert reason is using memory via assembly
assembly {
let returndata_size := mload(returndata)
revert(add(32, returndata), returndata_size)
}
} else {
revert(errorMessage);
}
}
}
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.0 (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.0 (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.0 (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.0 (utils/introspection/IERC165.sol)
pragma solidity ^0.8.0;
/**
* @dev Interface of the ERC165 standard, as defined in the
* https://eips.ethereum.org/EIPS/eip-165[EIP].
*
* Implementers can declare support of contract interfaces, which can then be
* queried by others ({ERC165Checker}).
*
* For an implementation, see {ERC165}.
*/
interface IERC165 {
/**
* @dev Returns true if this contract implements the interface defined by
* `interfaceId`. See the corresponding
* https://eips.ethereum.org/EIPS/eip-165#how-interfaces-are-identified[EIP section]
* to learn more about how these ids are created.
*
* This function call must use less than 30 000 gas.
*/
function supportsInterface(bytes4 interfaceId) external view returns (bool);
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.0 (token/ERC721/extensions/IERC721Enumerable.sol)
pragma solidity ^0.8.0;
import "../IERC721.sol";
/**
* @title ERC-721 Non-Fungible Token Standard, optional enumeration extension
* @dev See https://eips.ethereum.org/EIPS/eip-721
*/
interface IERC721Enumerable is IERC721 {
/**
* @dev Returns the total amount of tokens stored by the contract.
*/
function totalSupply() external view returns (uint256);
/**
* @dev Returns a token ID owned by `owner` at a given `index` of its token list.
* Use along with {balanceOf} to enumerate all of ``owner``'s tokens.
*/
function tokenOfOwnerByIndex(address owner, uint256 index) external view returns (uint256 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 get all quotes in all cubes | function allCubeQuote() public view returns( string[] memory ){
uint cubecount = totalSupply();
string[] memory result = new string[](cubecount);
uint256 index;
for (index = 0; index < cubecount; index++) {
result[index] = cube_Quote[index];
}
return result;
}
| 5,745,139 | [
1,
588,
777,
10681,
316,
777,
276,
23317,
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,
777,
39,
4895,
10257,
1435,
1071,
1476,
1135,
12,
533,
8526,
3778,
262,
95,
203,
3639,
2254,
276,
373,
557,
592,
273,
2078,
3088,
1283,
5621,
203,
3639,
533,
8526,
3778,
563,
273,
394,
533,
8526,
12,
71,
373,
557,
592,
1769,
203,
3639,
2254,
5034,
770,
31,
203,
3639,
364,
261,
1615,
273,
374,
31,
770,
411,
276,
373,
557,
592,
31,
770,
27245,
288,
203,
5411,
563,
63,
1615,
65,
273,
225,
18324,
67,
10257,
63,
1615,
15533,
203,
3639,
289,
203,
3639,
327,
563,
31,
7010,
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
] |
/**
*Submitted for verification at Etherscan.io on 2022-04-14
*/
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.13;
interface ManagerLike {
function cdpCan(
address owner,
uint256 cdpId,
address allowedAddr
) external view returns (uint256);
function vat() external view returns (address);
function ilks(uint256) external view returns (bytes32);
function owns(uint256) external view returns (address);
function urns(uint256) external view returns (address);
function cdpAllow(
uint256 cdp,
address usr,
uint256 ok
) 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;
}
interface ICommand {
function isTriggerDataValid(uint256 _cdpId, bytes memory triggerData)
external
view
returns (bool);
function isExecutionCorrect(uint256 cdpId, bytes memory triggerData)
external
view
returns (bool);
function isExecutionLegal(uint256 cdpId, bytes memory triggerData) external view returns (bool);
function execute(
bytes calldata executionData,
uint256 cdpId,
bytes memory triggerData
) external;
}
interface BotLike {
function addRecord(
uint256 cdpId,
uint256 triggerType,
uint256 replacedTriggerId,
bytes memory triggerData
) external;
function removeRecord(
// This function should be executed allways in a context of AutomationBot address not DsProxy,
//msg.sender should be dsProxy
uint256 cdpId,
uint256 triggerId
) external;
function execute(
bytes calldata executionData,
uint256 cdpId,
bytes calldata triggerData,
address commandAddress,
uint256 triggerId,
uint256 daiCoverage
) external;
}
contract ServiceRegistry {
uint256 public constant MAX_DELAY = 30 days;
mapping(bytes32 => uint256) public lastExecuted;
mapping(bytes32 => address) private namedService;
address public owner;
uint256 public requiredDelay;
modifier validateInput(uint256 len) {
require(msg.data.length == len, "registry/illegal-padding");
_;
}
modifier delayedExecution() {
bytes32 operationHash = keccak256(msg.data);
uint256 reqDelay = requiredDelay;
/* solhint-disable not-rely-on-time */
if (lastExecuted[operationHash] == 0 && reqDelay > 0) {
// not called before, scheduled for execution
lastExecuted[operationHash] = block.timestamp;
emit ChangeScheduled(operationHash, block.timestamp + reqDelay, msg.data);
} else {
require(
block.timestamp - reqDelay > lastExecuted[operationHash],
"registry/delay-too-small"
);
emit ChangeApplied(operationHash, block.timestamp, msg.data);
_;
lastExecuted[operationHash] = 0;
}
/* solhint-enable not-rely-on-time */
}
modifier onlyOwner() {
require(msg.sender == owner, "registry/only-owner");
_;
}
constructor(uint256 initialDelay) {
require(initialDelay <= MAX_DELAY, "registry/invalid-delay");
requiredDelay = initialDelay;
owner = msg.sender;
}
function transferOwnership(address newOwner)
external
onlyOwner
validateInput(36)
delayedExecution
{
owner = newOwner;
}
function changeRequiredDelay(uint256 newDelay)
external
onlyOwner
validateInput(36)
delayedExecution
{
require(newDelay <= MAX_DELAY, "registry/invalid-delay");
requiredDelay = newDelay;
}
function getServiceNameHash(string memory name) external pure returns (bytes32) {
return keccak256(abi.encodePacked(name));
}
function addNamedService(bytes32 serviceNameHash, address serviceAddress)
external
onlyOwner
validateInput(68)
delayedExecution
{
require(namedService[serviceNameHash] == address(0), "registry/service-override");
namedService[serviceNameHash] = serviceAddress;
}
function updateNamedService(bytes32 serviceNameHash, address serviceAddress)
external
onlyOwner
validateInput(68)
delayedExecution
{
require(namedService[serviceNameHash] != address(0), "registry/service-does-not-exist");
namedService[serviceNameHash] = serviceAddress;
}
function removeNamedService(bytes32 serviceNameHash) external onlyOwner validateInput(36) {
require(namedService[serviceNameHash] != address(0), "registry/service-does-not-exist");
namedService[serviceNameHash] = address(0);
emit NamedServiceRemoved(serviceNameHash);
}
function getRegisteredService(string memory serviceName) external view returns (address) {
return namedService[keccak256(abi.encodePacked(serviceName))];
}
function getServiceAddress(bytes32 serviceNameHash) external view returns (address) {
return namedService[serviceNameHash];
}
function clearScheduledExecution(bytes32 scheduledExecution)
external
onlyOwner
validateInput(36)
{
require(lastExecuted[scheduledExecution] > 0, "registry/execution-not-scheduled");
lastExecuted[scheduledExecution] = 0;
emit ChangeCancelled(scheduledExecution);
}
event ChangeScheduled(bytes32 dataHash, uint256 scheduledFor, bytes data);
event ChangeApplied(bytes32 dataHash, uint256 appliedAt, bytes data);
event ChangeCancelled(bytes32 dataHash);
event NamedServiceRemoved(bytes32 nameHash);
}
/**
* @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);
}
contract DSMath {
function add(uint256 x, uint256 y) internal pure returns (uint256 z) {
require((z = x + y) >= x, "");
}
function sub(uint256 x, uint256 y) internal pure returns (uint256 z) {
require((z = x - y) <= x, "");
}
function mul(uint256 x, uint256 y) internal pure returns (uint256 z) {
require(y == 0 || (z = x * y) / y == x, "");
}
function div(uint256 x, uint256 y) internal pure returns (uint256 z) {
return x / y;
}
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(int256 x, int256 y) internal pure returns (int256 z) {
return x <= y ? x : y;
}
function imax(int256 x, int256 y) internal pure returns (int256 z) {
return x >= y ? x : y;
}
uint256 internal constant WAD = 10**18;
uint256 internal 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;
}
// This famous algorithm is called "exponentiation by squaring"
// and calculates x^n with x as fixed-point and n as regular unsigned.
//
// It's O(log n), instead of O(n) for naive repeated multiplication.
//
// These facts are why it works:
//
// If n is even, then x^n = (x^2)^(n/2).
// If n is odd, then x^n = x * x^(n-1),
// and applying the equation for even x gives
// x^n = x * (x^2)^((n-1) / 2).
//
// Also, EVM division is flooring and
// floor[(n-1) / 2] = floor[n / 2].
//
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);
}
}
}
}
abstract contract IVat {
struct Urn {
uint256 ink; // Locked Collateral [wad]
uint256 art; // Normalised Debt [wad]
}
struct Ilk {
uint256 Art; // Total Normalised Debt [wad]
uint256 rate; // Accumulated Rates [ray]
uint256 spot; // Price with Safety Margin [ray]
uint256 line; // Debt Ceiling [rad]
uint256 dust; // Urn Debt Floor [rad]
}
mapping(bytes32 => mapping(address => Urn)) public urns;
mapping(bytes32 => Ilk) public ilks;
mapping(bytes32 => mapping(address => uint256)) public gem; // [wad]
function can(address, address) public view virtual returns (uint256);
function dai(address) public view virtual returns (uint256);
function frob(
bytes32,
address,
address,
address,
int256,
int256
) public virtual;
function hope(address) public virtual;
function move(
address,
address,
uint256
) public virtual;
function fork(
bytes32,
address,
address,
int256,
int256
) public virtual;
}
abstract contract IGem {
function dec() public virtual returns (uint256);
function gem() public virtual returns (IGem);
function join(address, uint256) public payable virtual;
function exit(address, uint256) public virtual;
function approve(address, uint256) public virtual;
function transfer(address, uint256) public virtual returns (bool);
function transferFrom(
address,
address,
uint256
) public virtual returns (bool);
function deposit() public payable virtual;
function withdraw(uint256) public virtual;
function allowance(address, address) public virtual returns (uint256);
}
abstract contract IJoin {
bytes32 public ilk;
function dec() public view virtual returns (uint256);
function gem() public view virtual returns (IGem);
function join(address, uint256) public payable virtual;
function exit(address, uint256) public virtual;
}
abstract contract IDaiJoin {
function vat() public virtual returns (IVat);
function dai() public virtual returns (IGem);
function join(address, uint256) public payable virtual;
function exit(address, uint256) public virtual;
}
abstract contract IJug {
struct Ilk {
uint256 duty;
uint256 rho;
}
mapping(bytes32 => Ilk) public ilks;
function drip(bytes32) public virtual returns (uint256);
}
/// @title Getter contract for Vault info from Maker protocol
contract McdUtils is DSMath {
address public immutable serviceRegistry;
IERC20 private immutable DAI;
address private immutable daiJoin;
address public immutable jug;
constructor(
address _serviceRegistry,
IERC20 _dai,
address _daiJoin,
address _jug
) {
serviceRegistry = _serviceRegistry;
DAI = _dai;
daiJoin = _daiJoin;
jug = _jug;
}
function toInt256(uint256 x) internal pure returns (int256 y) {
y = int256(x);
require(y >= 0, "int256-overflow");
}
function _getDrawDart(
address vat,
address urn,
bytes32 ilk,
uint256 wad
) internal returns (int256 dart) {
// Updates stability fee rate
uint256 rate = IJug(jug).drip(ilk);
// Gets DAI balance of the urn in the vat
uint256 dai = IVat(vat).dai(urn);
// If there was already enough DAI in the vat balance, just exits it without adding more debt
if (dai < mul(wad, RAY)) {
// Calculates the needed dart so together with the existing dai in the vat is enough to exit wad amount of DAI tokens
dart = toInt256(sub(mul(wad, RAY), dai) / rate);
// This is neeeded due lack of precision. It might need to sum an extra dart wei (for the given DAI wad amount)
dart = mul(uint256(dart), rate) < mul(wad, RAY) ? dart + 1 : dart;
}
}
function drawDebt(
uint256 borrowedDai,
uint256 cdpId,
ManagerLike manager,
address sendTo
) external {
address urn = manager.urns(cdpId);
address vat = manager.vat();
manager.frob(cdpId, 0, _getDrawDart(vat, urn, manager.ilks(cdpId), borrowedDai));
manager.move(cdpId, address(this), mul(borrowedDai, RAY));
if (IVat(vat).can(address(this), daiJoin) == 0) {
IVat(vat).hope(daiJoin);
}
IJoin(daiJoin).exit(sendTo, borrowedDai);
}
}
contract AutomationBot {
struct TriggerRecord {
bytes32 triggerHash;
uint256 cdpId;
}
string private constant CDP_MANAGER_KEY = "CDP_MANAGER";
string private constant AUTOMATION_BOT_KEY = "AUTOMATION_BOT";
string private constant AUTOMATION_EXECUTOR_KEY = "AUTOMATION_EXECUTOR";
string private constant MCD_UTILS_KEY = "MCD_UTILS";
mapping(uint256 => TriggerRecord) public activeTriggers;
uint256 public triggersCounter = 0;
ServiceRegistry public immutable serviceRegistry;
address public immutable self;
constructor(ServiceRegistry _serviceRegistry) {
serviceRegistry = _serviceRegistry;
self = address(this);
}
modifier auth(address caller) {
require(
serviceRegistry.getRegisteredService(AUTOMATION_EXECUTOR_KEY) == caller,
"bot/not-executor"
);
_;
}
modifier onlyDelegate() {
require(address(this) != self, "bot/only-delegate");
_;
}
// works correctly in any context
function validatePermissions(
uint256 cdpId,
address operator,
ManagerLike manager
) private view {
require(isCdpOwner(cdpId, operator, manager), "bot/no-permissions");
}
// works correctly in any context
function isCdpAllowed(
uint256 cdpId,
address operator,
ManagerLike manager
) public view returns (bool) {
address cdpOwner = manager.owns(cdpId);
return (manager.cdpCan(cdpOwner, cdpId, operator) == 1) || (operator == cdpOwner);
}
// works correctly in any context
function isCdpOwner(
uint256 cdpId,
address operator,
ManagerLike manager
) private view returns (bool) {
return (operator == manager.owns(cdpId));
}
// works correctly in any context
function getCommandAddress(uint256 triggerType) public view returns (address) {
bytes32 commandHash = keccak256(abi.encode("Command", triggerType));
address commandAddress = serviceRegistry.getServiceAddress(commandHash);
return commandAddress;
}
// works correctly in any context
function getTriggersHash(
uint256 cdpId,
bytes memory triggerData,
address commandAddress
) private view returns (bytes32) {
bytes32 triggersHash = keccak256(
abi.encodePacked(cdpId, triggerData, serviceRegistry, commandAddress)
);
return triggersHash;
}
// works correctly in context of Automation Bot
function checkTriggersExistenceAndCorrectness(
uint256 cdpId,
uint256 triggerId,
address commandAddress,
bytes memory triggerData
) private view {
bytes32 triggersHash = activeTriggers[triggerId].triggerHash;
require(
triggersHash != bytes32(0) &&
triggersHash == getTriggersHash(cdpId, triggerData, commandAddress),
"bot/invalid-trigger"
);
}
function checkTriggersExistenceAndCorrectness(uint256 cdpId, uint256 triggerId) private view {
require(activeTriggers[triggerId].cdpId == cdpId, "bot/invalid-trigger");
}
// works correctly in context of automationBot
function addRecord(
// This function should be executed allways in a context of AutomationBot address not DsProxy,
// msg.sender should be dsProxy
uint256 cdpId,
uint256 triggerType,
uint256 replacedTriggerId,
bytes memory triggerData
) external {
ManagerLike manager = ManagerLike(serviceRegistry.getRegisteredService(CDP_MANAGER_KEY));
address commandAddress = getCommandAddress(triggerType);
require(
ICommand(commandAddress).isTriggerDataValid(cdpId, triggerData),
"bot/invalid-trigger-data"
);
require(isCdpAllowed(cdpId, msg.sender, manager), "bot/no-permissions");
triggersCounter = triggersCounter + 1;
activeTriggers[triggersCounter] = TriggerRecord(
getTriggersHash(cdpId, triggerData, commandAddress),
cdpId
);
if (replacedTriggerId != 0) {
require(
activeTriggers[replacedTriggerId].cdpId == cdpId,
"bot/trigger-removal-illegal"
);
activeTriggers[replacedTriggerId] = TriggerRecord(0, 0);
emit TriggerRemoved(cdpId, replacedTriggerId);
}
emit TriggerAdded(triggersCounter, commandAddress, cdpId, triggerData);
}
// works correctly in context of automationBot
function removeRecord(
// This function should be executed allways in a context of AutomationBot address not DsProxy,
// msg.sender should be dsProxy
uint256 cdpId,
uint256 triggerId
) external {
address managerAddress = serviceRegistry.getRegisteredService(CDP_MANAGER_KEY);
require(isCdpAllowed(cdpId, msg.sender, ManagerLike(managerAddress)), "bot/no-permissions");
// validatePermissions(cdpId, msg.sender, ManagerLike(managerAddress));
checkTriggersExistenceAndCorrectness(cdpId, triggerId);
activeTriggers[triggerId] = TriggerRecord(0, 0);
emit TriggerRemoved(cdpId, triggerId);
}
//works correctly in context of dsProxy
function addTrigger(
uint256 cdpId,
uint256 triggerType,
uint256 replacedTriggerId,
bytes memory triggerData
) external onlyDelegate {
// TODO: consider adding isCdpAllow add flag in tx payload, make sense from extensibility perspective
ManagerLike manager = ManagerLike(serviceRegistry.getRegisteredService(CDP_MANAGER_KEY));
address automationBot = serviceRegistry.getRegisteredService(AUTOMATION_BOT_KEY);
BotLike(automationBot).addRecord(cdpId, triggerType, replacedTriggerId, triggerData);
if (!isCdpAllowed(cdpId, automationBot, manager)) {
manager.cdpAllow(cdpId, automationBot, 1);
emit ApprovalGranted(cdpId, automationBot);
}
}
//works correctly in context of dsProxy
// TODO: removeAllowance parameter of this method moves responsibility to decide on this to frontend.
// In case of a bug on frontend allowance might be revoked by setting this parameter to `true`
// despite there still be some active triggers which will be disables by this call.
// One of the solutions is to add counter of active triggers and revoke allowance only if last trigger is being deleted
function removeTrigger(
uint256 cdpId,
uint256 triggerId,
bool removeAllowance
) external onlyDelegate {
address managerAddress = serviceRegistry.getRegisteredService(CDP_MANAGER_KEY);
ManagerLike manager = ManagerLike(managerAddress);
address automationBot = serviceRegistry.getRegisteredService(AUTOMATION_BOT_KEY);
BotLike(automationBot).removeRecord(cdpId, triggerId);
if (removeAllowance) {
manager.cdpAllow(cdpId, automationBot, 0);
emit ApprovalRemoved(cdpId, automationBot);
}
emit TriggerRemoved(cdpId, triggerId);
}
//works correctly in context of dsProxy
function removeApproval(ServiceRegistry _serviceRegistry, uint256 cdpId) external onlyDelegate {
address approvedEntity = changeApprovalStatus(_serviceRegistry, cdpId, 0);
emit ApprovalRemoved(cdpId, approvedEntity);
}
//works correctly in context of dsProxy
function grantApproval(ServiceRegistry _serviceRegistry, uint256 cdpId) external onlyDelegate {
address approvedEntity = changeApprovalStatus(_serviceRegistry, cdpId, 1);
emit ApprovalGranted(cdpId, approvedEntity);
}
//works correctly in context of dsProxy
function changeApprovalStatus(
ServiceRegistry _serviceRegistry,
uint256 cdpId,
uint256 status
) private returns (address) {
address managerAddress = _serviceRegistry.getRegisteredService(CDP_MANAGER_KEY);
ManagerLike manager = ManagerLike(managerAddress);
address automationBot = _serviceRegistry.getRegisteredService(AUTOMATION_BOT_KEY);
require(
isCdpAllowed(cdpId, automationBot, manager) != (status == 1),
"bot/approval-unchanged"
);
validatePermissions(cdpId, address(this), manager);
manager.cdpAllow(cdpId, automationBot, status);
return automationBot;
}
function drawDaiFromVault(
uint256 cdpId,
ManagerLike manager,
uint256 daiCoverage
) internal {
address utilsAddress = serviceRegistry.getRegisteredService(MCD_UTILS_KEY);
McdUtils utils = McdUtils(utilsAddress);
manager.cdpAllow(cdpId, utilsAddress, 1);
utils.drawDebt(daiCoverage, cdpId, manager, msg.sender);
manager.cdpAllow(cdpId, utilsAddress, 0);
}
//works correctly in context of automationBot
function execute(
bytes calldata executionData,
uint256 cdpId,
bytes calldata triggerData,
address commandAddress,
uint256 triggerId,
uint256 daiCoverage
) external auth(msg.sender) {
checkTriggersExistenceAndCorrectness(cdpId, triggerId, commandAddress, triggerData);
ManagerLike manager = ManagerLike(serviceRegistry.getRegisteredService(CDP_MANAGER_KEY));
drawDaiFromVault(cdpId, manager, daiCoverage);
ICommand command = ICommand(commandAddress);
require(command.isExecutionLegal(cdpId, triggerData), "bot/trigger-execution-illegal");
manager.cdpAllow(cdpId, commandAddress, 1);
command.execute(executionData, cdpId, triggerData);
activeTriggers[triggerId] = TriggerRecord(0, 0);
manager.cdpAllow(cdpId, commandAddress, 0);
require(command.isExecutionCorrect(cdpId, triggerData), "bot/trigger-execution-wrong");
emit TriggerExecuted(triggerId, cdpId, executionData);
}
event ApprovalRemoved(uint256 indexed cdpId, address approvedEntity);
event ApprovalGranted(uint256 indexed cdpId, address approvedEntity);
event TriggerRemoved(uint256 indexed cdpId, uint256 indexed triggerId);
event TriggerAdded(
uint256 indexed triggerId,
address indexed commandAddress,
uint256 indexed cdpId,
bytes triggerData
);
event TriggerExecuted(uint256 indexed triggerId, uint256 indexed cdpId, bytes executionData);
}
/**
* @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);
}
}
}
}
/**
* @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");
}
}
}
interface IWETH {
function withdraw(uint256 wad) external;
}
interface IExchange {
function swapTokenForDai(
address asset,
uint256 amount,
uint256 receiveAtLeast,
address callee,
bytes calldata withData
) external;
function swapDaiForToken(
address asset,
uint256 amount,
uint256 receiveAtLeast,
address callee,
bytes calldata withData
) external;
}
contract AutomationExecutor {
using SafeERC20 for IERC20;
BotLike public immutable bot;
IERC20 public immutable dai;
IWETH public immutable weth;
address public exchange;
address public owner;
mapping(address => bool) public callers;
constructor(
BotLike _bot,
IERC20 _dai,
IWETH _weth,
address _exchange
) {
bot = _bot;
weth = _weth;
dai = _dai;
exchange = _exchange;
owner = msg.sender;
callers[owner] = true;
}
modifier onlyOwner() {
require(msg.sender == owner, "executor/only-owner");
_;
}
modifier auth(address caller) {
require(callers[caller], "executor/not-authorized");
_;
}
function transferOwnership(address newOwner) external onlyOwner {
require(newOwner != address(0), "executor/invalid-new-owner");
owner = newOwner;
}
function setExchange(address newExchange) external onlyOwner {
require(newExchange != address(0), "executor/invalid-new-exchange");
exchange = newExchange;
}
function addCaller(address caller) external onlyOwner {
callers[caller] = true;
}
function removeCaller(address caller) external onlyOwner {
require(caller != msg.sender, "executor/cannot-remove-owner");
callers[caller] = false;
}
function execute(
bytes calldata executionData,
uint256 cdpId,
bytes calldata triggerData,
address commandAddress,
uint256 triggerId,
uint256 daiCoverage,
uint256 minerBribe,
int256 gasRefund
) external auth(msg.sender) {
uint256 initialGasAvailable = gasleft();
bot.execute(executionData, cdpId, triggerData, commandAddress, triggerId, daiCoverage);
if (minerBribe > 0) {
block.coinbase.transfer(minerBribe);
}
uint256 finalGasAvailable = gasleft();
uint256 etherUsed = tx.gasprice *
uint256(int256(initialGasAvailable - finalGasAvailable) - gasRefund);
if (address(this).balance > etherUsed) {
payable(msg.sender).transfer(etherUsed);
} else {
payable(msg.sender).transfer(address(this).balance);
}
}
function swap(
address otherAsset,
bool toDai,
uint256 amount,
uint256 receiveAtLeast,
address callee,
bytes calldata withData
) external auth(msg.sender) {
IERC20 fromToken = toDai ? IERC20(otherAsset) : dai;
require(
amount > 0 && amount <= fromToken.balanceOf(address(this)),
"executor/invalid-amount"
);
uint256 allowance = fromToken.allowance(address(this), exchange);
if (amount > allowance) {
fromToken.safeIncreaseAllowance(exchange, type(uint256).max - allowance);
}
if (toDai) {
IExchange(exchange).swapTokenForDai(
otherAsset,
amount,
receiveAtLeast,
callee,
withData
);
} else {
IExchange(exchange).swapDaiForToken(
otherAsset,
amount,
receiveAtLeast,
callee,
withData
);
}
}
function withdraw(address asset, uint256 amount) external onlyOwner {
if (asset == address(0)) {
require(amount <= address(this).balance, "executor/invalid-amount");
(bool sent, ) = payable(owner).call{ value: amount }("");
require(sent, "executor/withdrawal-failed");
} else {
IERC20(asset).safeTransfer(owner, amount);
}
}
function unwrapWETH(uint256 amount) external onlyOwner {
weth.withdraw(amount);
}
receive() external payable {}
}
interface MPALike {
struct CdpData {
address gemJoin;
address payable fundsReceiver;
uint256 cdpId;
bytes32 ilk;
uint256 requiredDebt;
uint256 borrowCollateral;
uint256 withdrawCollateral;
uint256 withdrawDai;
uint256 depositDai;
uint256 depositCollateral;
bool skipFL;
string methodName;
}
struct AddressRegistry {
address jug;
address manager;
address multiplyProxyActions;
address lender;
address exchange;
}
struct ExchangeData {
address fromTokenAddress;
address toTokenAddress;
uint256 fromTokenAmount;
uint256 toTokenAmount;
uint256 minToTokenAmount;
address exchangeAddress;
bytes _exchangeCalldata;
}
function closeVaultExitCollateral(
ExchangeData calldata exchangeData,
CdpData memory cdpData,
AddressRegistry calldata addressRegistry
) external;
function closeVaultExitDai(
ExchangeData calldata exchangeData,
CdpData memory cdpData,
AddressRegistry calldata addressRegistry
) external;
}
interface IPipInterface {
function read() external returns (bytes32);
}
interface SpotterLike {
function ilks(bytes32) external view returns (IPipInterface pip, uint256 mat);
function par() external view returns (uint256);
}
interface VatLike {
function urns(bytes32, address) external view returns (uint256 ink, uint256 art);
function ilks(bytes32)
external
view
returns (
uint256 art, // Total Normalised Debt [wad]
uint256 rate, // Accumulated Rates [ray]
uint256 spot, // Price with Safety Margin [ray]
uint256 line, // Debt Ceiling [rad]
uint256 dust // Urn Debt Floor [rad]
);
function gem(bytes32, address) external view returns (uint256); // [wad]
function can(address, address) external view returns (uint256);
function dai(address) external view returns (uint256);
function frob(
bytes32,
address,
address,
address,
int256,
int256
) external;
function hope(address) external;
function move(
address,
address,
uint256
) external;
function fork(
bytes32,
address,
address,
int256,
int256
) external;
}
interface OsmMomLike {
function osms(bytes32) external view returns (address);
}
interface OsmLike {
function peep() external view returns (bytes32, bool);
function bud(address) external view returns (uint256);
function kiss(address a) external;
}
/// @title Getter contract for Vault info from Maker protocol
contract McdView is DSMath {
ManagerLike public manager;
VatLike public vat;
SpotterLike public spotter;
OsmMomLike public osmMom;
address public owner;
mapping(address => bool) public whitelisted;
constructor(
address _vat,
address _manager,
address _spotter,
address _mom,
address _owner
) {
manager = ManagerLike(_manager);
vat = VatLike(_vat);
spotter = SpotterLike(_spotter);
osmMom = OsmMomLike(_mom);
owner = _owner;
}
function approve(address _allowedReader, bool isApproved) external {
require(msg.sender == owner, "mcd-view/not-authorised");
whitelisted[_allowedReader] = isApproved;
}
/// @notice Gets Vault info (collateral, debt)
/// @param vaultId Id of the Vault
function getVaultInfo(uint256 vaultId) public view returns (uint256, uint256) {
address urn = manager.urns(vaultId);
bytes32 ilk = manager.ilks(vaultId);
(uint256 collateral, uint256 debt) = vat.urns(ilk, urn);
(, uint256 rate, , , ) = vat.ilks(ilk);
return (collateral, rmul(debt, rate));
}
/// @notice Gets a price of the asset
/// @param ilk Ilk of the Vault
function getPrice(bytes32 ilk) public view returns (uint256) {
(, uint256 mat) = spotter.ilks(ilk);
(, , uint256 spot, , ) = vat.ilks(ilk);
return div(rmul(rmul(spot, spotter.par()), mat), 10**9);
}
/// @notice Gets oracle next price of the asset
/// @param ilk Ilk of the Vault
function getNextPrice(bytes32 ilk) public view returns (uint256) {
require(whitelisted[msg.sender], "mcd-view/not-whitelisted");
OsmLike osm = OsmLike(osmMom.osms(ilk));
(bytes32 val, bool status) = osm.peep();
require(status, "mcd-view/osm-price-error");
return uint256(val);
}
/// @notice Gets Vaults ratio
/// @param vaultId Id of the Vault
function getRatio(uint256 vaultId, bool useNextPrice) public view returns (uint256) {
bytes32 ilk = manager.ilks(vaultId);
uint256 price = useNextPrice ? getNextPrice(ilk) : getPrice(ilk);
(uint256 collateral, uint256 debt) = getVaultInfo(vaultId);
if (debt == 0) return 0;
return wdiv(wmul(collateral, price), debt);
}
}
contract CloseCommand is ICommand {
address public immutable serviceRegistry;
string private constant CDP_MANAGER_KEY = "CDP_MANAGER";
string private constant MCD_VIEW_KEY = "MCD_VIEW";
string private constant MPA_KEY = "MULTIPLY_PROXY_ACTIONS";
constructor(address _serviceRegistry) {
serviceRegistry = _serviceRegistry;
}
function isExecutionCorrect(uint256 cdpId, bytes memory) external view override returns (bool) {
address viewAddress = ServiceRegistry(serviceRegistry).getRegisteredService(MCD_VIEW_KEY);
McdView viewerContract = McdView(viewAddress);
(uint256 collateral, uint256 debt) = viewerContract.getVaultInfo(cdpId);
return !(collateral > 0 || debt > 0);
}
function isExecutionLegal(uint256 _cdpId, bytes memory triggerData)
external
view
override
returns (bool)
{
(, , uint256 slLevel) = abi.decode(triggerData, (uint256, uint16, uint256));
address managerAddress = ServiceRegistry(serviceRegistry).getRegisteredService(
CDP_MANAGER_KEY
);
ManagerLike manager = ManagerLike(managerAddress);
if (manager.owns(_cdpId) == address(0)) {
return false;
}
address viewAddress = ServiceRegistry(serviceRegistry).getRegisteredService(MCD_VIEW_KEY);
uint256 collRatio = McdView(viewAddress).getRatio(_cdpId, true);
bool vaultNotEmpty = collRatio != 0; // MCD_VIEW contract returns 0 (instead of infinity) as a collateralisation ratio of empty vault
return vaultNotEmpty && collRatio <= slLevel * 10**16;
}
function execute(
bytes calldata executionData,
uint256,
bytes memory triggerData
) external override {
(, uint16 triggerType, ) = abi.decode(triggerData, (uint256, uint16, uint256));
address mpaAddress = ServiceRegistry(serviceRegistry).getRegisteredService(MPA_KEY);
bytes4 prefix = abi.decode(executionData, (bytes4));
bytes4 expectedSelector;
if (triggerType == 1) {
expectedSelector = MPALike.closeVaultExitCollateral.selector;
} else if (triggerType == 2) {
expectedSelector = MPALike.closeVaultExitDai.selector;
} else revert("unsupported-triggerType");
require(prefix == expectedSelector, "wrong-payload");
//since all global values in this contract are either const or immutable, this delegate call do not break any storage
//this is simplest approach, most similar to way we currently call dsProxy
// solhint-disable-next-line avoid-low-level-calls
(bool status, ) = mpaAddress.delegatecall(executionData);
require(status, "execution failed");
}
function isTriggerDataValid(uint256 _cdpId, bytes memory triggerData)
external
pure
override
returns (bool)
{
(uint256 cdpId, uint16 triggerType, uint256 slLevel) = abi.decode(
triggerData,
(uint256, uint16, uint256)
);
return slLevel > 100 && _cdpId == cdpId && (triggerType == 1 || triggerType == 2);
}
}
contract DummyCommand is ICommand {
address public serviceRegistry;
bool public initialCheckReturn;
bool public finalCheckReturn;
bool public revertsInExecute;
bool public validTriggerData;
constructor(
address _serviceRegistry,
bool _initialCheckReturn,
bool _finalCheckReturn,
bool _revertsInExecute,
bool _validTriggerData
) {
serviceRegistry = _serviceRegistry;
initialCheckReturn = _initialCheckReturn;
finalCheckReturn = _finalCheckReturn;
revertsInExecute = _revertsInExecute;
validTriggerData = _validTriggerData;
}
function changeValidTriggerDataFlag(bool _validTriggerData) external {
validTriggerData = _validTriggerData;
}
function changeFlags(
bool _initialCheckReturn,
bool _finalCheckReturn,
bool _revertsInExecute
) external {
initialCheckReturn = _initialCheckReturn;
finalCheckReturn = _finalCheckReturn;
revertsInExecute = _revertsInExecute;
}
function isTriggerDataValid(uint256, bytes memory) external view override returns (bool) {
return validTriggerData;
}
function isExecutionCorrect(
uint256, // cdpId
bytes memory // triggerData
) external view override returns (bool) {
return finalCheckReturn;
}
function isExecutionLegal(
uint256, // cdpId
bytes memory // triggerData
) external view override returns (bool) {
return initialCheckReturn;
}
function execute(
bytes calldata,
uint256,
bytes memory
) external view override {
require(!revertsInExecute, "command failed");
}
}
/**
* @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 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 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:
*
* - `to` cannot be the zero address.
* - the caller must have a balance of at least `amount`.
*/
function transfer(address to, uint256 amount) public virtual override returns (bool) {
address owner = _msgSender();
_transfer(owner, to, 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}.
*
* NOTE: If `amount` is the maximum `uint256`, the allowance is not updated on
* `transferFrom`. This is semantically equivalent to an infinite approval.
*
* Requirements:
*
* - `spender` cannot be the zero address.
*/
function approve(address spender, uint256 amount) public virtual override returns (bool) {
address owner = _msgSender();
_approve(owner, 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}.
*
* NOTE: Does not update the allowance if the current allowance
* is the maximum `uint256`.
*
* Requirements:
*
* - `from` and `to` cannot be the zero address.
* - `from` must have a balance of at least `amount`.
* - the caller must have allowance for ``from``'s tokens of at least
* `amount`.
*/
function transferFrom(
address from,
address to,
uint256 amount
) public virtual override returns (bool) {
address spender = _msgSender();
_spendAllowance(from, spender, amount);
_transfer(from, to, 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) {
address owner = _msgSender();
_approve(owner, spender, _allowances[owner][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) {
address owner = _msgSender();
uint256 currentAllowance = _allowances[owner][spender];
require(currentAllowance >= subtractedValue, "ERC20: decreased allowance below zero");
unchecked {
_approve(owner, 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:
*
* - `from` cannot be the zero address.
* - `to` cannot be the zero address.
* - `from` must have a balance of at least `amount`.
*/
function _transfer(
address from,
address to,
uint256 amount
) internal virtual {
require(from != address(0), "ERC20: transfer from the zero address");
require(to != address(0), "ERC20: transfer to the zero address");
_beforeTokenTransfer(from, to, amount);
uint256 fromBalance = _balances[from];
require(fromBalance >= amount, "ERC20: transfer amount exceeds balance");
unchecked {
_balances[from] = fromBalance - amount;
}
_balances[to] += amount;
emit Transfer(from, to, amount);
_afterTokenTransfer(from, to, 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 Spend `amount` form the allowance of `owner` toward `spender`.
*
* Does not update the allowance amount in case of infinite allowance.
* Revert if not enough allowance is available.
*
* Might emit an {Approval} event.
*/
function _spendAllowance(
address owner,
address spender,
uint256 amount
) internal virtual {
uint256 currentAllowance = allowance(owner, spender);
if (currentAllowance != type(uint256).max) {
require(currentAllowance >= amount, "ERC20: insufficient allowance");
unchecked {
_approve(owner, spender, currentAllowance - 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 {}
}
contract TestERC20 is ERC20 {
constructor(
string memory name_,
string memory symbol_,
uint256 amount_
) ERC20(name_, symbol_) {
_mint(msg.sender, amount_);
}
}
contract TestExchange is IExchange {
using SafeERC20 for IERC20;
IERC20 public immutable DAI;
constructor(IERC20 _dai) {
DAI = _dai;
}
function swapTokenForDai(
address asset,
uint256 amount,
uint256 receiveAtLeast,
address,
bytes calldata
) external override {
require(
IERC20(asset).transferFrom(msg.sender, address(this), amount),
"exchange/asset-from-failed"
);
require(DAI.transfer(msg.sender, receiveAtLeast), "exchange/dai-to-failed");
}
function swapDaiForToken(
address asset,
uint256 amount,
uint256 receiveAtLeast,
address,
bytes calldata
) external override {
require(DAI.transferFrom(msg.sender, address(this), amount), "exchange/dai-from-failed");
require(IERC20(asset).transfer(msg.sender, receiveAtLeast), "exchange/asset-to-failed");
}
}
interface DsProxyLike {
function owner() external view returns (address);
function setOwner(address owner_) external;
function execute(address target, bytes memory data) external payable returns (bytes32 response);
}
contract TestWETH {
string public name = "Wrapped Ether";
string public symbol = "WETH";
uint8 public decimals = 18;
event Approval(address indexed src, address indexed guy, uint256 wad);
event Transfer(address indexed src, address indexed dst, uint256 wad);
event Deposit(address indexed dst, uint256 wad);
event Withdrawal(address indexed src, uint256 wad);
mapping(address => uint256) public balanceOf;
mapping(address => mapping(address => uint256)) public allowance;
receive() external payable {
deposit();
}
function deposit() public payable {
balanceOf[msg.sender] += msg.value;
emit Deposit(msg.sender, msg.value);
}
function withdraw(uint256 wad) public {
require(balanceOf[msg.sender] >= wad);
balanceOf[msg.sender] -= wad;
payable(msg.sender).transfer(wad);
emit Withdrawal(msg.sender, wad);
}
function totalSupply() public view returns (uint256) {
return address(this).balance;
}
function approve(address guy, uint256 wad) public returns (bool) {
allowance[msg.sender][guy] = wad;
emit Approval(msg.sender, guy, wad);
return true;
}
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) {
require(balanceOf[src] >= wad);
if (src != msg.sender && allowance[src][msg.sender] != type(uint256).max) {
require(allowance[src][msg.sender] >= wad);
allowance[src][msg.sender] -= wad;
}
balanceOf[src] -= wad;
balanceOf[dst] += wad;
emit Transfer(src, dst, wad);
return true;
}
} | MCD_VIEW contract returns 0 (instead of infinity) as a collateralisation ratio of empty vault
| bool vaultNotEmpty = collRatio != 0; | 10,861,423 | [
1,
49,
10160,
67,
12145,
6835,
1135,
374,
261,
8591,
684,
434,
27272,
13,
487,
279,
4508,
2045,
287,
10742,
7169,
434,
1008,
9229,
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,
3639,
1426,
9229,
18431,
273,
4508,
8541,
480,
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
] |
// SPDX-License-Identifier: MIT
// solhint-disable-next-line compiler-version
pragma solidity ^0.8.0;
import "../../utils/AddressUpgradeable.sol";
/**
* @dev This is a base contract to aid in writing upgradeable contracts, or any kind of contract that will be deployed
* behind a proxy. Since a proxied contract can't have a constructor, it's common to move constructor logic to an
* external initializer function, usually called `initialize`. It then becomes necessary to protect this initializer
* function so it can only be called once. The {initializer} modifier provided by this contract will have this effect.
*
* TIP: To avoid leaving the proxy in an uninitialized state, the initializer function should be called as early as
* possible by providing the encoded function call as the `_data` argument to {UpgradeableProxy-constructor}.
*
* CAUTION: When used with inheritance, manual care must be taken to not invoke a parent initializer twice, or to ensure
* that all initializers are idempotent. This is not verified automatically as constructors are by Solidity.
*/
abstract contract Initializable {
/**
* @dev Indicates that the contract has been initialized.
*/
bool private _initialized;
/**
* @dev Indicates that the contract is in the process of being initialized.
*/
bool private _initializing;
/**
* @dev Modifier to protect an initializer function from being invoked twice.
*/
modifier initializer() {
require(_initializing || !_initialized, "Initializable: contract is already initialized");
bool isTopLevelCall = !_initializing;
if (isTopLevelCall) {
_initializing = true;
_initialized = true;
}
_;
if (isTopLevelCall) {
_initializing = false;
}
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
/**
* @dev Interface of the ERC20 standard as defined in the EIP.
*/
interface IERC20Upgradeable {
/**
* @dev Returns the amount of tokens in existence.
*/
function totalSupply() external view returns (uint256);
/**
* @dev Returns the amount of tokens owned by `account`.
*/
function balanceOf(address account) external view returns (uint256);
/**
* @dev Moves `amount` tokens from the caller's account to `recipient`.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/
function transfer(address recipient, uint256 amount) external returns (bool);
/**
* @dev Returns the remaining number of tokens that `spender` will be
* allowed to spend on behalf of `owner` through {transferFrom}. This is
* zero by default.
*
* This value changes when {approve} or {transferFrom} are called.
*/
function allowance(address owner, address spender) external view returns (uint256);
/**
* @dev Sets `amount` as the allowance of `spender` over the caller's tokens.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* IMPORTANT: Beware that changing an allowance with this method brings the risk
* that someone may use both the old and the new allowance by unfortunate
* transaction ordering. One possible solution to mitigate this race
* condition is to first reduce the spender's allowance to 0 and set the
* desired value afterwards:
* https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729
*
* Emits an {Approval} event.
*/
function approve(address spender, uint256 amount) external returns (bool);
/**
* @dev Moves `amount` tokens from `sender` to `recipient` using the
* allowance mechanism. `amount` is then deducted from the caller's
* allowance.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/
function transferFrom(address sender, address recipient, uint256 amount) external returns (bool);
/**
* @dev Emitted when `value` tokens are moved from one account (`from`) to
* another (`to`).
*
* Note that `value` may be zero.
*/
event Transfer(address indexed from, address indexed to, uint256 value);
/**
* @dev Emitted when the allowance of a `spender` for an `owner` is set by
* a call to {approve}. `value` is the new allowance.
*/
event Approval(address indexed owner, address indexed spender, uint256 value);
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
/**
* @dev Collection of functions related to the address type
*/
library AddressUpgradeable {
/**
* @dev Returns true if `account` is a contract.
*
* [IMPORTANT]
* ====
* It is unsafe to assume that an address for which this function returns
* false is an externally-owned account (EOA) and not a contract.
*
* Among others, `isContract` will return false for the following
* types of addresses:
*
* - an externally-owned account
* - a contract in construction
* - an address where a contract will be created
* - an address where a contract lived, but was destroyed
* ====
*/
function isContract(address account) internal view returns (bool) {
// This method relies on extcodesize, which returns 0 for contracts in
// construction, since the code is only stored at the end of the
// constructor execution.
uint256 size;
// solhint-disable-next-line no-inline-assembly
assembly { size := extcodesize(account) }
return size > 0;
}
/**
* @dev Replacement for Solidity's `transfer`: sends `amount` wei to
* `recipient`, forwarding all available gas and reverting on errors.
*
* https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost
* of certain opcodes, possibly making contracts go over the 2300 gas limit
* imposed by `transfer`, making them unable to receive funds via
* `transfer`. {sendValue} removes this limitation.
*
* https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more].
*
* IMPORTANT: because control is transferred to `recipient`, care must be
* taken to not create reentrancy vulnerabilities. Consider using
* {ReentrancyGuard} or the
* https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern].
*/
function sendValue(address payable recipient, uint256 amount) internal {
require(address(this).balance >= amount, "Address: insufficient balance");
// solhint-disable-next-line avoid-low-level-calls, avoid-call-value
(bool success, ) = recipient.call{ value: amount }("");
require(success, "Address: unable to send value, recipient may have reverted");
}
/**
* @dev Performs a Solidity function call using a low level `call`. A
* plain`call` is an unsafe replacement for a function call: use this
* function instead.
*
* If `target` reverts with a revert reason, it is bubbled up by this
* function (like regular Solidity function calls).
*
* Returns the raw returned data. To convert to the expected return value,
* use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`].
*
* Requirements:
*
* - `target` must be a contract.
* - calling `target` with `data` must not revert.
*
* _Available since v3.1._
*/
function functionCall(address target, bytes memory data) internal returns (bytes memory) {
return functionCall(target, data, "Address: low-level call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with
* `errorMessage` as a fallback revert reason when `target` reverts.
*
* _Available since v3.1._
*/
function functionCall(address target, bytes memory data, string memory errorMessage) internal returns (bytes memory) {
return functionCallWithValue(target, data, 0, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but also transferring `value` wei to `target`.
*
* Requirements:
*
* - the calling contract must have an ETH balance of at least `value`.
* - the called Solidity function must be `payable`.
*
* _Available since v3.1._
*/
function functionCallWithValue(address target, bytes memory data, uint256 value) internal returns (bytes memory) {
return functionCallWithValue(target, data, value, "Address: low-level call with value failed");
}
/**
* @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but
* with `errorMessage` as a fallback revert reason when `target` reverts.
*
* _Available since v3.1._
*/
function functionCallWithValue(address target, bytes memory data, uint256 value, string memory errorMessage) internal returns (bytes memory) {
require(address(this).balance >= value, "Address: insufficient balance for call");
require(isContract(target), "Address: call to non-contract");
// solhint-disable-next-line avoid-low-level-calls
(bool success, bytes memory returndata) = target.call{ value: value }(data);
return _verifyCallResult(success, returndata, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but performing a static call.
*
* _Available since v3.3._
*/
function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) {
return functionStaticCall(target, data, "Address: low-level static call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`],
* but performing a static call.
*
* _Available since v3.3._
*/
function functionStaticCall(address target, bytes memory data, string memory errorMessage) internal view returns (bytes memory) {
require(isContract(target), "Address: static call to non-contract");
// solhint-disable-next-line avoid-low-level-calls
(bool success, bytes memory returndata) = target.staticcall(data);
return _verifyCallResult(success, returndata, errorMessage);
}
function _verifyCallResult(bool success, bytes memory returndata, string memory errorMessage) private pure returns(bytes memory) {
if (success) {
return returndata;
} else {
// Look for revert reason and bubble it up if present
if (returndata.length > 0) {
// The easiest way to bubble the revert reason is using memory via assembly
// solhint-disable-next-line no-inline-assembly
assembly {
let returndata_size := mload(returndata)
revert(add(32, returndata), returndata_size)
}
} else {
revert(errorMessage);
}
}
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import "../utils/Context.sol";
import "../utils/introspection/ERC165.sol";
/**
* @dev External interface of AccessControl declared to support ERC165 detection.
*/
interface IAccessControl {
function hasRole(bytes32 role, address account) external view returns (bool);
function getRoleAdmin(bytes32 role) external view returns (bytes32);
function grantRole(bytes32 role, address account) external;
function revokeRole(bytes32 role, address account) external;
function renounceRole(bytes32 role, address account) external;
}
/**
* @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 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 {_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 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 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 {
require(hasRole(getRoleAdmin(role), _msgSender()), "AccessControl: sender must be an admin to grant");
_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 {
require(hasRole(getRoleAdmin(role), _msgSender()), "AccessControl: sender must be an admin to revoke");
_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 {
emit RoleAdminChanged(role, getRoleAdmin(role), adminRole);
_roles[role].adminRole = 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());
}
}
}
// 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;
/**
* @dev Contract module that helps prevent reentrant calls to a function.
*
* Inheriting from `ReentrancyGuard` will make the {nonReentrant} modifier
* available, which can be applied to functions to make sure there are no nested
* (reentrant) calls to them.
*
* Note that because there is a single `nonReentrant` guard, functions marked as
* `nonReentrant` may not call one another. This can be worked around by making
* those functions `private`, and then adding `external` `nonReentrant` entry
* points to them.
*
* TIP: If you would like to learn more about reentrancy and alternative ways
* to protect against it, check out our blog post
* https://blog.openzeppelin.com/reentrancy-after-istanbul/[Reentrancy After Istanbul].
*/
abstract contract ReentrancyGuard {
// Booleans are more expensive than uint256 or any type that takes up a full
// word because each write operation emits an extra SLOAD to first read the
// slot's contents, replace the bits taken up by the boolean, and then write
// back. This is the compiler's defense against contract upgrades and
// pointer aliasing, and it cannot be disabled.
// The values being non-zero value makes deployment a bit more expensive,
// but in exchange the refund on every call to nonReentrant will be lower in
// amount. Since refunds are capped to a percentage of the total
// transaction's gas, it is best to keep them low in cases like this one, to
// increase the likelihood of the full refund coming into effect.
uint256 private constant _NOT_ENTERED = 1;
uint256 private constant _ENTERED = 2;
uint256 private _status;
constructor () {
_status = _NOT_ENTERED;
}
/**
* @dev Prevents a contract from calling itself, directly or indirectly.
* Calling a `nonReentrant` function from another `nonReentrant`
* function is not supported. It is possible to prevent this from happening
* by making the `nonReentrant` function external, and make it call a
* `private` function that does the actual work.
*/
modifier nonReentrant() {
// On the first call to nonReentrant, _notEntered will be true
require(_status != _ENTERED, "ReentrancyGuard: reentrant call");
// Any calls to nonReentrant after this point will fail
_status = _ENTERED;
_;
// By storing the original value once again, a refund is triggered (see
// https://eips.ethereum.org/EIPS/eip-2200)
_status = _NOT_ENTERED;
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
/**
* @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'
// solhint-disable-next-line max-line-length
require((value == 0) || (token.allowance(address(this), spender) == 0),
"SafeERC20: approve from non-zero to non-zero allowance"
);
_callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, value));
}
function safeIncreaseAllowance(IERC20 token, address spender, uint256 value) internal {
uint256 newAllowance = token.allowance(address(this), spender) + value;
_callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance));
}
function safeDecreaseAllowance(IERC20 token, address spender, uint256 value) internal {
unchecked {
uint256 oldAllowance = token.allowance(address(this), spender);
require(oldAllowance >= value, "SafeERC20: decreased allowance below zero");
uint256 newAllowance = oldAllowance - value;
_callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance));
}
}
/**
* @dev Imitates a Solidity high-level call (i.e. a regular function call to a contract), relaxing the requirement
* on the return value: the return value is optional (but if data is returned, it must not be false).
* @param token The token targeted by the call.
* @param data The call data (encoded using abi.encode or one of its variants).
*/
function _callOptionalReturn(IERC20 token, bytes memory data) private {
// We need to perform a low level call here, to bypass Solidity's return data size checking mechanism, since
// we're implementing it ourselves. We use {Address.functionCall} to perform this call, which verifies that
// the target address contains contract code and also asserts for success in the low-level call.
bytes memory returndata = address(token).functionCall(data, "SafeERC20: low-level call failed");
if (returndata.length > 0) { // Return data is optional
// solhint-disable-next-line max-line-length
require(abi.decode(returndata, (bool)), "SafeERC20: ERC20 operation did not succeed");
}
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
/**
* @dev Collection of functions related to the address type
*/
library Address {
/**
* @dev Returns true if `account` is a contract.
*
* [IMPORTANT]
* ====
* It is unsafe to assume that an address for which this function returns
* false is an externally-owned account (EOA) and not a contract.
*
* Among others, `isContract` will return false for the following
* types of addresses:
*
* - an externally-owned account
* - a contract in construction
* - an address where a contract will be created
* - an address where a contract lived, but was destroyed
* ====
*/
function isContract(address account) internal view returns (bool) {
// This method relies on extcodesize, which returns 0 for contracts in
// construction, since the code is only stored at the end of the
// constructor execution.
uint256 size;
// solhint-disable-next-line no-inline-assembly
assembly { size := extcodesize(account) }
return size > 0;
}
/**
* @dev Replacement for Solidity's `transfer`: sends `amount` wei to
* `recipient`, forwarding all available gas and reverting on errors.
*
* https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost
* of certain opcodes, possibly making contracts go over the 2300 gas limit
* imposed by `transfer`, making them unable to receive funds via
* `transfer`. {sendValue} removes this limitation.
*
* https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more].
*
* IMPORTANT: because control is transferred to `recipient`, care must be
* taken to not create reentrancy vulnerabilities. Consider using
* {ReentrancyGuard} or the
* https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern].
*/
function sendValue(address payable recipient, uint256 amount) internal {
require(address(this).balance >= amount, "Address: insufficient balance");
// solhint-disable-next-line avoid-low-level-calls, avoid-call-value
(bool success, ) = recipient.call{ value: amount }("");
require(success, "Address: unable to send value, recipient may have reverted");
}
/**
* @dev Performs a Solidity function call using a low level `call`. A
* plain`call` is an unsafe replacement for a function call: use this
* function instead.
*
* If `target` reverts with a revert reason, it is bubbled up by this
* function (like regular Solidity function calls).
*
* Returns the raw returned data. To convert to the expected return value,
* use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`].
*
* Requirements:
*
* - `target` must be a contract.
* - calling `target` with `data` must not revert.
*
* _Available since v3.1._
*/
function functionCall(address target, bytes memory data) internal returns (bytes memory) {
return functionCall(target, data, "Address: low-level call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with
* `errorMessage` as a fallback revert reason when `target` reverts.
*
* _Available since v3.1._
*/
function functionCall(address target, bytes memory data, string memory errorMessage) internal returns (bytes memory) {
return functionCallWithValue(target, data, 0, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but also transferring `value` wei to `target`.
*
* Requirements:
*
* - the calling contract must have an ETH balance of at least `value`.
* - the called Solidity function must be `payable`.
*
* _Available since v3.1._
*/
function functionCallWithValue(address target, bytes memory data, uint256 value) internal returns (bytes memory) {
return functionCallWithValue(target, data, value, "Address: low-level call with value failed");
}
/**
* @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but
* with `errorMessage` as a fallback revert reason when `target` reverts.
*
* _Available since v3.1._
*/
function functionCallWithValue(address target, bytes memory data, uint256 value, string memory errorMessage) internal returns (bytes memory) {
require(address(this).balance >= value, "Address: insufficient balance for call");
require(isContract(target), "Address: call to non-contract");
// solhint-disable-next-line avoid-low-level-calls
(bool success, bytes memory returndata) = target.call{ value: value }(data);
return _verifyCallResult(success, returndata, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but performing a static call.
*
* _Available since v3.3._
*/
function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) {
return functionStaticCall(target, data, "Address: low-level static call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`],
* but performing a static call.
*
* _Available since v3.3._
*/
function functionStaticCall(address target, bytes memory data, string memory errorMessage) internal view returns (bytes memory) {
require(isContract(target), "Address: static call to non-contract");
// solhint-disable-next-line avoid-low-level-calls
(bool success, bytes memory returndata) = target.staticcall(data);
return _verifyCallResult(success, returndata, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but performing a delegate call.
*
* _Available since v3.4._
*/
function functionDelegateCall(address target, bytes memory data) internal returns (bytes memory) {
return functionDelegateCall(target, data, "Address: low-level delegate call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`],
* but performing a delegate call.
*
* _Available since v3.4._
*/
function functionDelegateCall(address target, bytes memory data, string memory errorMessage) internal returns (bytes memory) {
require(isContract(target), "Address: delegate call to non-contract");
// solhint-disable-next-line avoid-low-level-calls
(bool success, bytes memory returndata) = target.delegatecall(data);
return _verifyCallResult(success, returndata, errorMessage);
}
function _verifyCallResult(bool success, bytes memory returndata, string memory errorMessage) private pure returns(bytes memory) {
if (success) {
return returndata;
} else {
// Look for revert reason and bubble it up if present
if (returndata.length > 0) {
// The easiest way to bubble the revert reason is using memory via assembly
// solhint-disable-next-line no-inline-assembly
assembly {
let returndata_size := mload(returndata)
revert(add(32, returndata), returndata_size)
}
} else {
revert(errorMessage);
}
}
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import "./math/Math.sol";
/**
* @dev Collection of functions related to array types.
*/
library Arrays {
/**
* @dev Searches a sorted `array` and returns the first index that contains
* a value greater or equal to `element`. If no such index exists (i.e. all
* values in the array are strictly less than `element`), the array length is
* returned. Time complexity O(log n).
*
* `array` is expected to be sorted in ascending order, and to contain no
* repeated elements.
*/
function findUpperBound(uint256[] storage array, uint256 element) internal view returns (uint256) {
if (array.length == 0) {
return 0;
}
uint256 low = 0;
uint256 high = array.length;
while (low < high) {
uint256 mid = Math.average(low, high);
// Note that mid will always be strictly less than high (i.e. it will be a valid array index)
// because Math.average rounds down (it does integer division with truncation).
if (array[mid] > element) {
high = mid;
} else {
low = mid + 1;
}
}
// At this point `low` is the exclusive upper bound. We will return the inclusive upper bound.
if (low > 0 && array[low - 1] == element) {
return low - 1;
} else {
return low;
}
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
/*
* @dev Provides information about the current execution context, including the
* sender of the transaction and its data. While these are generally available
* via msg.sender and msg.data, they should not be accessed in such a direct
* manner, since when dealing with meta-transactions the account sending and
* paying for execution may not be the actual sender (as far as an application
* is concerned).
*
* This contract is only required for intermediate, library-like contracts.
*/
abstract contract Context {
function _msgSender() internal view virtual returns (address) {
return msg.sender;
}
function _msgData() internal view virtual returns (bytes calldata) {
this; // silence state mutability warning without generating bytecode - see https://github.com/ethereum/solidity/issues/2691
return msg.data;
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import "./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;
/**
* @dev Standard math utilities missing in the Solidity language.
*/
library Math {
/**
* @dev Returns the largest of two numbers.
*/
function max(uint256 a, uint256 b) internal pure returns (uint256) {
return a >= b ? a : b;
}
/**
* @dev Returns the smallest of two numbers.
*/
function min(uint256 a, uint256 b) internal pure returns (uint256) {
return a < b ? a : b;
}
/**
* @dev Returns the average of two numbers. The result is rounded towards
* zero.
*/
function average(uint256 a, uint256 b) internal pure returns (uint256) {
// (a + b) / 2 can overflow, so we distribute
return (a / 2) + (b / 2) + ((a % 2 + b % 2) / 2);
}
}
// SPDX-License-Identifier: MIT
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 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. This function uses a `revert`
* opcode (which leaves remaining gas untouched) while Solidity uses an
* invalid opcode to revert (consuming all remaining gas).
*
* 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
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 `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;
// When the value to delete is the last one, the swap operation is unnecessary. However, since this occurs
// so rarely, we still do the swap anyway to avoid the gas cost of adding an 'if' statement.
bytes32 lastvalue = set._values[lastIndex];
// Move the last value to the index where the value to delete is
set._values[toDeleteIndex] = lastvalue;
// Update the index for the moved value
set._indexes[lastvalue] = toDeleteIndex + 1; // All indexes are 1-based
// Delete the slot where the moved value was stored
set._values.pop();
// Delete the index for the deleted slot
delete set._indexes[value];
return true;
} else {
return false;
}
}
/**
* @dev Returns true if the value is in the set. O(1).
*/
function _contains(Set storage set, bytes32 value) private view returns (bool) {
return set._indexes[value] != 0;
}
/**
* @dev Returns the number of values on the set. O(1).
*/
function _length(Set storage set) private view returns (uint256) {
return set._values.length;
}
/**
* @dev Returns the value stored at position `index` in the set. O(1).
*
* Note that there are no guarantees on the ordering of values inside the
* array, and it may change when more values are added or removed.
*
* Requirements:
*
* - `index` must be strictly less than {length}.
*/
function _at(Set storage set, uint256 index) private view returns (bytes32) {
require(set._values.length > index, "EnumerableSet: index out of bounds");
return set._values[index];
}
// 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);
}
// 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))));
}
// 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));
}
}
// SPDX-License-Identifier: GPL-3.0-or-later
pragma solidity >=0.4.0;
// 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);
}
}
pragma solidity >=0.5.0;
interface IUniswapV2Factory {
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;
}
pragma solidity >=0.5.0;
interface IUniswapV2Pair {
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;
}
pragma solidity >=0.6.2;
interface IUniswapV2Router01 {
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);
}
pragma solidity >=0.6.2;
import './IUniswapV2Router01.sol';
interface IUniswapV2Router02 is IUniswapV2Router01 {
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;
}
// SPDX-License-Identifier: AGPL-3.0
pragma solidity 0.8.3;
import "./OndoRegistryClientInitializable.sol";
abstract contract OndoRegistryClient is OndoRegistryClientInitializable {
constructor(address _registry) {
__OndoRegistryClient__initialize(_registry);
}
}
// SPDX-License-Identifier: AGPL-3.0
pragma solidity 0.8.3;
import "@openzeppelin/contracts-upgradeable/proxy/utils/Initializable.sol";
import "@openzeppelin/contracts/security/Pausable.sol";
import "@openzeppelin/contracts/security/ReentrancyGuard.sol";
import "@openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol";
import "contracts/interfaces/IRegistry.sol";
import "contracts/libraries/OndoLibrary.sol";
abstract contract OndoRegistryClientInitializable is
Initializable,
ReentrancyGuard,
Pausable
{
using SafeERC20 for IERC20;
IRegistry public registry;
uint256 public denominator;
function __OndoRegistryClient__initialize(address _registry)
internal
initializer
{
require(_registry != address(0), "Invalid registry address");
registry = IRegistry(_registry);
denominator = registry.denominator();
}
/**
* @notice General ACL checker
* @param _role Role as defined in OndoLibrary
*/
modifier isAuthorized(bytes32 _role) {
require(registry.authorized(_role, msg.sender), "Unauthorized");
_;
}
/*
* @notice Helper to expose a Pausable interface to tools
*/
function paused() public view virtual override returns (bool) {
return registry.paused() || super.paused();
}
function pause() external virtual isAuthorized(OLib.PANIC_ROLE) {
super._pause();
}
function unpause() external virtual isAuthorized(OLib.GUARDIAN_ROLE) {
super._unpause();
}
/**
* @notice Grab tokens and send to caller
* @dev If the _amount[i] is 0, then transfer all the tokens
* @param _tokens List of tokens
* @param _amounts Amount of each token to send
*/
function _rescueTokens(address[] calldata _tokens, uint256[] memory _amounts)
internal
virtual
{
for (uint256 i = 0; i < _tokens.length; i++) {
uint256 amount = _amounts[i];
if (amount == 0) {
amount = IERC20(_tokens[i]).balanceOf(address(this));
}
IERC20(_tokens[i]).safeTransfer(msg.sender, amount);
}
}
function rescueTokens(address[] calldata _tokens, uint256[] memory _amounts)
public
whenPaused
isAuthorized(OLib.GUARDIAN_ROLE)
{
require(_tokens.length == _amounts.length, "Invalid array sizes");
_rescueTokens(_tokens, _amounts);
}
}
// SPDX-License-Identifier: AGPL-3.0
pragma solidity 0.8.3;
import "@openzeppelin/contracts/access/AccessControl.sol";
import "@openzeppelin/contracts/utils/structs/EnumerableSet.sol";
import "contracts/interfaces/ITrancheToken.sol";
import "contracts/interfaces/IRegistry.sol";
import "contracts/libraries/OndoLibrary.sol";
import "contracts/interfaces/IWETH.sol";
/**
* @title Global values used by many contracts
* @notice This is mostly used for access control
*/
contract Registry is IRegistry, AccessControl {
using EnumerableSet for EnumerableSet.AddressSet;
bool private _paused;
mapping(bytes32 => bool) private featureFlags;
uint256 public constant override denominator = 10000;
IWETH public immutable override weth;
address payable public fallbackRecipient;
mapping(address => string) public strategistNames;
modifier onlyRole(bytes32 _role) {
require(hasRole(_role, msg.sender), "Unauthorized: Invalid role");
_;
}
constructor(
address _governance,
address payable _fallbackRecipient,
address _weth
) {
require(
_fallbackRecipient != address(0) && _fallbackRecipient != address(this),
"Invalid address"
);
require(_governance != address(0), "Invalid governance address");
require(_weth != address(0), "Invalid weth address");
_setupRole(DEFAULT_ADMIN_ROLE, _governance);
_setupRole(OLib.GOVERNANCE_ROLE, _governance);
_setRoleAdmin(OLib.VAULT_ROLE, OLib.DEPLOYER_ROLE);
_setRoleAdmin(OLib.ROLLOVER_ROLE, OLib.DEPLOYER_ROLE);
_setRoleAdmin(OLib.STRATEGY_ROLE, OLib.DEPLOYER_ROLE);
fallbackRecipient = _fallbackRecipient;
weth = IWETH(_weth);
}
/**
* @notice General ACL check
* @param _role One of the predefined roles
* @param _account Address to check
* @return Access/Denied
*/
function authorized(bytes32 _role, address _account)
public
view
override
returns (bool)
{
return hasRole(_role, _account);
}
/**
* @notice Add a new official strategist
* @dev grantRole protects this ACL
* @param _strategist Address of new strategist
* @param _name Display name for UI
*/
function addStrategist(address _strategist, string calldata _name) external {
grantRole(OLib.STRATEGIST_ROLE, _strategist);
strategistNames[_strategist] = _name;
}
/**
* Enables a feature flag.
*/
function enableFeatureFlag(bytes32 _featureFlag)
external
override
onlyRole(OLib.GOVERNANCE_ROLE)
{
featureFlags[_featureFlag] = true;
}
/**
* Disables a feature flag.
*/
function disableFeatureFlag(bytes32 _featureFlag)
external
override
onlyRole(OLib.GOVERNANCE_ROLE)
{
featureFlags[_featureFlag] = false;
}
/**
* Returns a feature flag value.
*/
function getFeatureFlag(bytes32 _featureFlag)
external
view
override
returns (bool)
{
return featureFlags[_featureFlag];
}
/**
* Removes a feature flag.
*/
function deleteFeatureFlag(bytes32 _featureFlag)
external
override
onlyRole(OLib.GOVERNANCE_ROLE)
{
delete featureFlags[_featureFlag];
}
/**
* @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);
/*
* @notice Helper to expose a Pausable interface to tools
*/
function paused() public view override returns (bool) {
return _paused;
}
/**
* @notice Turn on paused variable. Everything stops!
*/
function pause() external override onlyRole(OLib.PANIC_ROLE) {
_paused = true;
emit Paused(msg.sender);
}
/**
* @notice Turn off paused variable. Everything resumes.
*/
function unpause() external override onlyRole(OLib.GUARDIAN_ROLE) {
_paused = false;
emit Unpaused(msg.sender);
}
/**
* @notice Who will get any random eth from dead tranchetokens
* @param _target Receipient of ETH
*/
function setFallbackRecipient(address payable _target)
external
onlyRole(OLib.GOVERNANCE_ROLE)
{
fallbackRecipient = _target;
}
}
// SPDX-License-Identifier: AGPL-3.0
pragma solidity 0.8.3;
import "contracts/libraries/OndoLibrary.sol";
import "contracts/interfaces/ITrancheToken.sol";
import "contracts/interfaces/IStrategy.sol";
interface IPairVault {
// Container to return Vault info to caller
struct VaultView {
uint256 id;
Asset[] assets;
IStrategy strategy; // Shared contract that interacts with AMMs
address creator; // Account that calls createVault
address strategist; // Has the right to call invest() and redeem(), and harvest() if strategy supports it
address rollover;
uint256 hurdleRate; // Return offered to senior tranche
OLib.State state; // Current state of Vault
uint256 startAt; // Time when the Vault is unpaused to begin accepting deposits
uint256 investAt; // Time when investors can't move funds, strategist can invest
uint256 redeemAt; // Time when strategist can redeem LP tokens, investors can withdraw
}
// Track the asset type and amount in different stages
struct Asset {
IERC20 token;
ITrancheToken trancheToken;
uint256 trancheCap;
uint256 userCap;
uint256 deposited;
uint256 originalInvested;
uint256 totalInvested; // not literal 1:1, originalInvested + proportional lp from mid-term
uint256 received;
uint256 rolloverDeposited;
}
function getState(uint256 _vaultId) external view returns (OLib.State);
function createVault(OLib.VaultParams calldata _params)
external
returns (uint256 vaultId);
function deposit(
uint256 _vaultId,
OLib.Tranche _tranche,
uint256 _amount
) external;
function depositETH(uint256 _vaultId, OLib.Tranche _tranche) external payable;
function depositLp(uint256 _vaultId, uint256 _amount)
external
returns (uint256 seniorTokensOwed, uint256 juniorTokensOwed);
function invest(
uint256 _vaultId,
uint256 _seniorMinOut,
uint256 _juniorMinOut
) external returns (uint256, uint256);
function redeem(
uint256 _vaultId,
uint256 _seniorMinOut,
uint256 _juniorMinOut
) external returns (uint256, uint256);
function withdraw(uint256 _vaultId, OLib.Tranche _tranche)
external
returns (uint256);
function withdrawETH(uint256 _vaultId, OLib.Tranche _tranche)
external
returns (uint256);
function withdrawLp(uint256 _vaultId, uint256 _amount)
external
returns (uint256, uint256);
function claim(uint256 _vaultId, OLib.Tranche _tranche)
external
returns (uint256, uint256);
function claimETH(uint256 _vaultId, OLib.Tranche _tranche)
external
returns (uint256, uint256);
function depositFromRollover(
uint256 _vaultId,
uint256 _rolloverId,
uint256 _seniorAmount,
uint256 _juniorAmount
) external;
function rolloverClaim(uint256 _vaultId, uint256 _rolloverId)
external
returns (uint256, uint256);
function setRollover(
uint256 _vaultId,
address _rollover,
uint256 _rolloverId
) external;
function canDeposit(uint256 _vaultId) external view returns (bool);
// function canTransition(uint256 _vaultId, OLib.State _state)
// external
// view
// returns (bool);
function getVaultById(uint256 _vaultId)
external
view
returns (VaultView memory);
function vaultInvestor(uint256 _vaultId, OLib.Tranche _tranche)
external
view
returns (
uint256 position,
uint256 claimableBalance,
uint256 withdrawableExcess,
uint256 withdrawableBalance
);
function seniorExpected(uint256 _vaultId) external view returns (uint256);
}
// SPDX-License-Identifier: AGPL-3.0
pragma solidity 0.8.3;
import "@openzeppelin/contracts/access/AccessControl.sol";
import "contracts/interfaces/IWETH.sol";
/**
* @title Global values used by many contracts
* @notice This is mostly used for access control
*/
interface IRegistry is IAccessControl {
function paused() external view returns (bool);
function pause() external;
function unpause() external;
function enableFeatureFlag(bytes32 _featureFlag) external;
function disableFeatureFlag(bytes32 _featureFlag) external;
function getFeatureFlag(bytes32 _featureFlag) external view returns (bool);
function deleteFeatureFlag(bytes32 _featureFlag) external;
function denominator() external view returns (uint256);
function weth() external view returns (IWETH);
function authorized(bytes32 _role, address _account)
external
view
returns (bool);
}
// SPDX-License-Identifier: AGPL-3.0
pragma solidity 0.8.3;
import "@openzeppelin/contracts/token/ERC20/IERC20.sol";
import "contracts/libraries/OndoLibrary.sol";
import "contracts/interfaces/IPairVault.sol";
interface IStrategy {
// Additional info stored for each Vault
struct Vault {
IPairVault origin; // who created this Vault
IERC20 pool; // the DEX pool
IERC20 senior; // senior asset in pool
IERC20 junior; // junior asset in pool
uint256 shares; // number of shares for ETF-style mid-duration entry/exit
uint256 seniorExcess; // unused senior deposits
uint256 juniorExcess; // unused junior deposits
}
function vaults(uint256 vaultId)
external
view
returns (
IPairVault origin,
IERC20 pool,
IERC20 senior,
IERC20 junior,
uint256 shares,
uint256 seniorExcess,
uint256 juniorExcess
);
function addVault(
uint256 _vaultId,
IERC20 _senior,
IERC20 _junior
) external;
function addLp(uint256 _vaultId, uint256 _lpTokens) external;
function removeLp(
uint256 _vaultId,
uint256 _shares,
address to
) external;
function getVaultInfo(uint256 _vaultId)
external
view
returns (IERC20, uint256);
function invest(
uint256 _vaultId,
uint256 _totalSenior,
uint256 _totalJunior,
uint256 _extraSenior,
uint256 _extraJunior,
uint256 _seniorMinOut,
uint256 _juniorMinOut
) external returns (uint256 seniorInvested, uint256 juniorInvested);
function sharesFromLp(uint256 vaultId, uint256 lpTokens)
external
view
returns (
uint256 shares,
uint256 vaultShares,
IERC20 pool
);
function lpFromShares(uint256 vaultId, uint256 shares)
external
view
returns (uint256 lpTokens, uint256 vaultShares);
function redeem(
uint256 _vaultId,
uint256 _seniorExpected,
uint256 _seniorMinOut,
uint256 _juniorMinOut
) external returns (uint256, uint256);
function withdrawExcess(
uint256 _vaultId,
OLib.Tranche tranche,
address to,
uint256 amount
) external;
}
// SPDX-License-Identifier: AGPL-3.0
pragma solidity 0.8.3;
import "@openzeppelin/contracts-upgradeable/token/ERC20/IERC20Upgradeable.sol";
interface ITrancheToken is IERC20Upgradeable {
function mint(address _account, uint256 _amount) external;
function burn(address _account, uint256 _amount) external;
function destroy(address payable _receiver) external;
}
// SPDX-License-Identifier: AGPL-3.0
pragma solidity 0.8.3;
import "@openzeppelin/contracts/token/ERC20/IERC20.sol";
interface IWETH is IERC20 {
function deposit() external payable;
function withdraw(uint256 wad) external;
}
// SPDX-License-Identifier: AGPL-3.0
pragma solidity 0.8.3;
import "@openzeppelin/contracts/utils/Arrays.sol";
import "@openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol";
import "@openzeppelin/contracts/token/ERC20/IERC20.sol";
//import "@openzeppelin/contracts/utils/Address.sol";
/**
* @title Helper functions
*/
library OLib {
using Arrays for uint256[];
// State transition per Vault. Just linear transitions.
enum State {Inactive, Deposit, Live, Withdraw}
// Only supports 2 tranches for now
enum Tranche {Senior, Junior}
struct VaultParams {
address seniorAsset;
address juniorAsset;
address strategist;
address strategy;
uint256 hurdleRate;
uint256 startTime;
uint256 enrollment;
uint256 duration;
string seniorName;
string seniorSym;
string juniorName;
string juniorSym;
uint256 seniorTrancheCap;
uint256 seniorUserCap;
uint256 juniorTrancheCap;
uint256 juniorUserCap;
}
struct RolloverParams {
address strategist;
string seniorName;
string seniorSym;
string juniorName;
string juniorSym;
}
bytes32 public constant GOVERNANCE_ROLE = keccak256("GOVERNANCE_ROLE");
bytes32 public constant PANIC_ROLE = keccak256("PANIC_ROLE");
bytes32 public constant GUARDIAN_ROLE = keccak256("GUARDIAN_ROLE");
bytes32 public constant DEPLOYER_ROLE = keccak256("DEPLOYER_ROLE");
bytes32 public constant CREATOR_ROLE = keccak256("CREATOR_ROLE");
bytes32 public constant STRATEGIST_ROLE = keccak256("STRATEGIST_ROLE");
bytes32 public constant VAULT_ROLE = keccak256("VAULT_ROLE");
bytes32 public constant ROLLOVER_ROLE = keccak256("ROLLOVER_ROLE");
bytes32 public constant STRATEGY_ROLE = keccak256("STRATEGY_ROLE");
// Both sums are running sums. If a user deposits [$1, $5, $3], then
// userSums would be [$1, $6, $9]. You can figure out the deposit
// amount be subtracting userSums[i]-userSum[i-1].
// prefixSums is the total deposited for all investors + this
// investors deposit at the time this deposit is made. So at
// prefixSum[0], it would be $1 + totalDeposits, where totalDeposits
// could be $1000 because other investors have put in money.
struct Investor {
uint256[] userSums;
uint256[] prefixSums;
bool claimed;
bool withdrawn;
}
/**
* @dev Given the total amount invested by the Vault, we want to find
* out how many of this investor's deposits were actually
* used. Use findUpperBound on the prefixSum to find the point
* where total deposits were accepted. For example, if $2000 was
* deposited by all investors and $1000 was invested, then some
* position in the prefixSum splits the array into deposits that
* got in, and deposits that didn't get in. That same position
* maps to userSums. This is the user's deposits that got
* in. Since we are keeping track of the sums, we know at that
* position the total deposits for a user was $15, even if it was
* 15 $1 deposits. And we know the amount that didn't get in is
* the last value in userSum - the amount that got it.
* @param investor A specific investor
* @param invested The total amount invested by this Vault
*/
function getInvestedAndExcess(Investor storage investor, uint256 invested)
internal
view
returns (uint256 userInvested, uint256 excess)
{
uint256[] storage prefixSums_ = investor.prefixSums;
uint256 length = prefixSums_.length;
if (length == 0) {
// There were no deposits. Return 0, 0.
return (userInvested, excess);
}
uint256 leastUpperBound = prefixSums_.findUpperBound(invested);
if (length == leastUpperBound) {
// All deposits got in, no excess. Return total deposits, 0
userInvested = investor.userSums[length - 1];
return (userInvested, excess);
}
uint256 prefixSum = prefixSums_[leastUpperBound];
if (prefixSum == invested) {
// Not all deposits got in, but there are no partial deposits
userInvested = investor.userSums[leastUpperBound];
excess = investor.userSums[length - 1] - userInvested;
} else {
// Let's say some of my deposits got in. The last deposit,
// however, was $100 and only $30 got in. Need to split that
// deposit so $30 got in, $70 is excess.
userInvested = leastUpperBound > 0
? investor.userSums[leastUpperBound - 1]
: 0;
uint256 depositAmount = investor.userSums[leastUpperBound] - userInvested;
if (prefixSum - depositAmount < invested) {
userInvested += (depositAmount + invested - prefixSum);
excess = investor.userSums[length - 1] - userInvested;
} else {
excess = investor.userSums[length - 1] - userInvested;
}
}
}
}
/**
* @title Subset of SafeERC20 from openZeppelin
*
* @dev Some non-standard ERC20 contracts (e.g. Tether) break
* `approve` by forcing it to behave like `safeApprove`. This means
* `safeIncreaseAllowance` will fail when it tries to adjust the
* allowance. The code below simply adds an extra call to
* `approve(spender, 0)`.
*/
library OndoSaferERC20 {
using SafeERC20 for IERC20;
function ondoSafeIncreaseAllowance(
IERC20 token,
address spender,
uint256 value
) internal {
uint256 newAllowance = token.allowance(address(this), spender) + value;
token.safeApprove(spender, 0);
token.safeApprove(spender, newAllowance);
}
}
// SPDX-License-Identifier: AGPL-3.0
pragma solidity 0.8.3;
import "@uniswap/v2-core/contracts/interfaces/IUniswapV2Pair.sol";
import "@uniswap/v2-core/contracts/interfaces/IUniswapV2Factory.sol";
import "@uniswap/v2-periphery/contracts/interfaces/IUniswapV2Router02.sol";
import "@openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol";
import "contracts/strategies/BasePairLPStrategy.sol";
import "contracts/vendor/uniswap/UniswapV2Library.sol";
import "contracts/vendor/uniswap/SushiSwapLibrary.sol";
import "contracts/Registry.sol";
import "@uniswap/lib/contracts/libraries/Babylonian.sol";
/**
* @title Access Uniswap
* @notice Add and remove liquidity to Uniswap
*/
abstract contract AUniswapStrategy is BasePairLPStrategy {
using SafeERC20 for IERC20;
using OndoSaferERC20 for IERC20;
// Pointers to Uniswap contracts
IUniswapV2Router02 public immutable uniRouter02;
uint8 public amm;
address public immutable uniFactory;
struct Call {
address target;
bytes data;
}
/**
* @dev
* @param _registry Ondo global registry
* @param _router Address for UniswapV2Router02
* @param _factory Address for UniswapV2Factory
*/
constructor(
address _registry,
address _router,
address _factory,
uint8 _amm
) BasePairLPStrategy(_registry) {
require(_router != address(0) && _factory != address(0), "Invalid target");
require(_amm == 0 || _amm == 1, "Invalid AMM");
amm = _amm;
uniRouter02 = IUniswapV2Router02(_router);
uniFactory = _factory;
}
/**
* @notice Conversion of LP tokens to shares
* @dev Simpler than Sushiswap strat because there's no compounding investment. Shares don't change.
* @param vaultId Vault
* @param lpTokens Amount of LP tokens
* @return Number of shares for LP tokens
* @return Total shares for this Vault
* @return Uniswap pool
*/
function sharesFromLp(uint256 vaultId, uint256 lpTokens)
external
view
virtual
override
returns (
uint256,
uint256,
IERC20
)
{
Vault storage vault_ = vaults[vaultId];
return (lpTokens, vault_.shares, vault_.pool);
}
/**
* @notice Conversion of shares to LP tokens
* @param vaultId Vault
* @param shares Amount of shares
* @return Number LP tokens
* @return Total shares for this Vault
*/
function lpFromShares(uint256 vaultId, uint256 shares)
external
view
virtual
override
returns (uint256, uint256)
{
Vault storage vault_ = vaults[vaultId];
return (shares, vault_.shares);
}
/**
* @notice Check whether liquidity pool already exists
* @param _senior Asset used for senior tranche
* @param _junior Asset used for junior tranche
*/
function poolExists(IERC20 _senior, IERC20 _junior)
internal
view
returns (bool)
{
return getPair(address(_senior), address(_junior)) != address(0);
}
/**
* @notice AllPairsVault registers Vault here
* @param _vaultId Reference to Vault
* @param _senior Asset used for senior tranche
* @param _junior Asset used for junior tranche
*/
function addVault(
uint256 _vaultId,
IERC20 _senior,
IERC20 _junior
) external override nonReentrant isAuthorized(OLib.VAULT_ROLE) {
require(
address(vaults[_vaultId].origin) == address(0),
"Vault id already registered"
);
require(poolExists(_senior, _junior), "Pool doesn't exist");
Vault storage vault_ = vaults[_vaultId];
vault_.origin = IPairVault(msg.sender);
vault_.pool = IERC20(getPair(address(_senior), address(_junior)));
vault_.senior = IERC20(_senior);
vault_.junior = IERC20(_junior);
}
function getPair(address senior, address junior)
internal
view
virtual
returns (address)
{
if (amm == 0) {
return UniswapV2Library.pairFor(uniFactory, senior, junior);
} else {
return SushiSwapLibrary.pairFor(uniFactory, senior, junior);
}
}
/**
* @notice Simple wrapper around uniswap
* @param amtIn Amount in
* @param minOut Minimum out
* @param path Router path
*/
function swapExactIn(
uint256 amtIn,
uint256 minOut,
address[] memory path
) internal returns (uint256) {
IERC20(path[0]).ondoSafeIncreaseAllowance(address(uniRouter02), amtIn);
return
uniRouter02.swapExactTokensForTokens(
amtIn,
minOut,
path,
address(this),
block.timestamp
)[path.length - 1];
}
/**
* @notice Simple wrapper around uniswap
* @param amtOut Amount out
* @param maxIn Maximum tokens offered as input
* @param path Router path
*/
function swapExactOut(
uint256 amtOut,
uint256 maxIn,
address[] memory path
) internal returns (uint256) {
IERC20(path[0]).ondoSafeIncreaseAllowance(address(uniRouter02), maxIn);
return
uniRouter02.swapTokensForExactTokens(
amtOut,
maxIn,
path,
address(this),
block.timestamp
)[0];
}
/**
* @dev Given the total available amounts of senior and junior asset
* tokens, invest as much as possible and record any excess uninvested
* assets.
* @param _vaultId Reference to specific Vault
* @param _totalSenior Total amount available to invest into senior assets
* @param _totalJunior Total amount available to invest into junior assets
* @param _extraSenior Extra funds due to cap on tranche, must be returned
* @param _extraJunior Extra funds due to cap on tranche, must be returned
* @param _seniorMinIn To ensure you get a decent price
* @param _juniorMinIn Same. Passed to addLiquidity on AMM
*/
function invest(
uint256 _vaultId,
uint256 _totalSenior,
uint256 _totalJunior,
uint256 _extraSenior,
uint256 _extraJunior,
uint256 _seniorMinIn,
uint256 _juniorMinIn
)
external
virtual
override
nonReentrant
whenNotPaused
onlyOrigin(_vaultId)
returns (uint256 seniorInvested, uint256 juniorInvested)
{
(seniorInvested, juniorInvested, ) = _invest(
_vaultId,
_totalSenior,
_totalJunior,
_extraSenior,
_extraJunior,
_seniorMinIn,
_juniorMinIn
);
}
function _invest(
uint256 _vaultId,
uint256 _totalSenior,
uint256 _totalJunior,
uint256 _extraSenior,
uint256 _extraJunior,
uint256 _seniorMinIn,
uint256 _juniorMinIn
)
internal
returns (
uint256 seniorInvested,
uint256 juniorInvested,
uint256 lpTokens
)
{
Vault storage vault_ = vaults[_vaultId];
vault_.senior.ondoSafeIncreaseAllowance(address(uniRouter02), _totalSenior);
vault_.junior.ondoSafeIncreaseAllowance(address(uniRouter02), _totalJunior);
(seniorInvested, juniorInvested, lpTokens) = uniRouter02.addLiquidity(
address(vault_.senior),
address(vault_.junior),
_totalSenior,
_totalJunior,
_seniorMinIn,
_juniorMinIn,
address(this),
block.timestamp
);
vault_.shares += lpTokens;
vault_.seniorExcess = _totalSenior - seniorInvested + _extraSenior;
vault_.juniorExcess = _totalJunior - juniorInvested + _extraJunior;
emit Invest(_vaultId, vault_.shares);
}
// hack to get stack down for redeem
function getPath(address _token0, address _token1)
internal
pure
returns (address[] memory path)
{
path = new address[](2);
path[0] = _token0;
path[1] = _token1;
}
function swapForSr(
address _senior,
address _junior,
uint256 _seniorExpected,
uint256 seniorReceived,
uint256 juniorReceived
) internal returns (uint256, uint256) {
uint256 seniorNeeded = _seniorExpected - seniorReceived;
address[] memory jr2Sr = getPath(_junior, _senior);
if (seniorNeeded > getAmountsOut(juniorReceived, jr2Sr)[1]) {
seniorReceived += swapExactIn(juniorReceived, 0, jr2Sr);
return (seniorReceived, 0);
} else {
juniorReceived -= swapExactOut(seniorNeeded, juniorReceived, jr2Sr);
return (_seniorExpected, juniorReceived);
}
}
function getAmountsOut(uint256 juniorReceived, address[] memory jr2Sr)
internal
view
virtual
returns (uint256[] memory)
{
if (amm == 0) {
return UniswapV2Library.getAmountsOut(uniFactory, juniorReceived, jr2Sr);
} else {
return SushiSwapLibrary.getAmountsOut(uniFactory, juniorReceived, jr2Sr);
}
}
/**
* @dev Convert all LP tokens back into the pair of underlying
* assets. Also convert any Sushi equally into both tranches.
* The senior tranche is expecting to get paid some hurdle
* rate above where they started. Here are the possible outcomes:
* - If the senior tranche doesn't have enough, then sell some or
* all junior tokens to get the senior to the expected
* returns. In the worst case, the senior tranche could suffer
* a loss and the junior tranche will be wiped out.
* - If the senior tranche has more than enough, reduce this tranche
* to the expected payoff. The excess senior tokens should be
* converted to junior tokens.
* @param _vaultId Reference to a specific Vault
* @param _seniorExpected Amount the senior tranche is expecting
* @param _seniorMinReceived Compute total for seniorReceived, factoring in slippage
* @param _juniorMinReceived Same.
* @return seniorReceived Final amount for senior tranche
* @return juniorReceived Final amount for junior tranche
*/
function redeem(
uint256 _vaultId,
uint256 _seniorExpected,
uint256 _seniorMinReceived,
uint256 _juniorMinReceived
)
external
virtual
override
nonReentrant
whenNotPaused
onlyOrigin(_vaultId)
returns (uint256 seniorReceived, uint256 juniorReceived)
{
Vault storage vault_ = vaults[_vaultId];
return
_redeem(
_vaultId,
vault_.shares,
_seniorExpected,
_seniorMinReceived,
_juniorMinReceived
);
}
function _redeem(
uint256 _vaultId,
uint256 _totaLP,
uint256 _seniorExpected,
uint256 _seniorMinReceived,
uint256 _juniorMinReceived
) internal returns (uint256 seniorReceived, uint256 juniorReceived) {
Vault storage vault_ = vaults[_vaultId];
{
IERC20 pool = IERC20(vault_.pool);
IERC20(pool).ondoSafeIncreaseAllowance(address(uniRouter02), _totaLP);
(seniorReceived, juniorReceived) = uniRouter02.removeLiquidity(
address(vault_.senior),
address(vault_.junior),
_totaLP,
0,
0,
address(this),
block.timestamp
);
}
if (seniorReceived < _seniorExpected) {
(seniorReceived, juniorReceived) = swapForSr(
address(vault_.senior),
address(vault_.junior),
_seniorExpected,
seniorReceived,
juniorReceived
);
} else {
if (seniorReceived > _seniorExpected) {
juniorReceived += swapExactIn(
seniorReceived - _seniorExpected,
0,
getPath(address(vault_.senior), address(vault_.junior))
);
}
seniorReceived = _seniorExpected;
}
require(
_seniorMinReceived <= seniorReceived &&
_juniorMinReceived <= juniorReceived,
"Too much slippage"
);
vault_.senior.ondoSafeIncreaseAllowance(
msg.sender,
seniorReceived + vault_.seniorExcess
);
vault_.junior.ondoSafeIncreaseAllowance(
msg.sender,
juniorReceived + vault_.juniorExcess
);
emit Redeem(_vaultId);
return (seniorReceived, juniorReceived);
}
function calculateSwapInAmount(uint256 reserveIn, uint256 userIn)
internal
pure
returns (uint256)
{
return
(Babylonian.sqrt(reserveIn * (userIn * 3988000 + reserveIn * 3988009)) -
reserveIn *
1997) / 1994;
}
function swapBForA(
address a,
address b,
uint256 aAmount,
uint256 bAmount
) internal returns (uint256, uint256) {
(uint256 aReserve, uint256 bReserve) =
amm == 0
? UniswapV2Library.getReserves(uniFactory, address(a), address(b))
: SushiSwapLibrary.getReserves(uniFactory, address(a), address(b));
// fancy math to get the amountToSwap
uint256 amountToSwap = calculateSwapInAmount(bReserve, bAmount);
// subtract bond amount since that amount will be converted to usdc
bAmount -= amountToSwap;
// convert bond to usdc
aAmount += swapExactIn(amountToSwap, 0, getPath(address(b), address(a)));
return (aAmount, bAmount);
}
function sellAForB(
address a,
address b,
uint256 amountA
) internal returns (uint256 bAmount) {
bAmount = swapExactIn(amountA, 0, getPath(a, b));
}
// you have some quantity of a and b and you want to add liquidity so both can be added as much as possible
function investAandB(
address a,
address b,
uint256 amountA,
uint256 amountB
)
internal
returns (
uint256 seniorInvested,
uint256 juniorInvested,
uint256 lpTokens
)
{
(seniorInvested, juniorInvested, lpTokens) = addLiquidity(
address(a),
address(a),
amountA,
amountB,
0,
0
);
// one of the asssets is now zero or close to zero
amountA -= seniorInvested;
amountB -= juniorInvested;
// if we have more weth then eden, then swap weth for eden, 50/50
if (amountA > amountB) {
(amountB, amountA) = swapBForA(b, a, amountB, amountA);
} else if (amountB > 0) {
(amountA, amountB) = swapBForA(a, b, amountA, amountB);
}
// if either of the amounts is greater than zero we can try adding liquidity
if (amountA > 0 || amountB > 0) {
uint256 lpTokens2;
(seniorInvested, juniorInvested, lpTokens2) = addLiquidity(
a,
b,
amountA,
amountB,
0,
0
);
lpTokens += lpTokens2;
}
}
// you have a single asset and you want to split that with b and add liquidity
function investB(
address a,
address b,
uint256 amountA,
uint256 amountB
)
internal
returns (
uint256 seniorInvested,
uint256 juniorInvested,
uint256 lpTokens
)
{
(amountA, amountB) = swapBForA(a, b, amountA, amountB);
(seniorInvested, juniorInvested, lpTokens) = addLiquidity(
a,
b,
amountA,
amountB,
0,
0
);
}
function addLiquidity(
address token0,
address token1,
uint256 amt0,
uint256 amt1,
uint256 minOut0,
uint256 minOut1
)
internal
returns (
uint256 out0,
uint256 out1,
uint256 lp
)
{
IERC20(token0).ondoSafeIncreaseAllowance(address(uniRouter02), amt0);
IERC20(token1).ondoSafeIncreaseAllowance(address(uniRouter02), amt1);
(out0, out1, lp) = uniRouter02.addLiquidity(
token0,
token1,
amt0,
amt1,
minOut0,
minOut1,
address(this),
block.timestamp
);
}
function multiexcall(Call[] calldata calls)
external
isAuthorized(OLib.GUARDIAN_ROLE)
returns (bytes[] memory returnData)
{
returnData = new bytes[](calls.length);
for (uint256 i = 0; i < calls.length; i++) {
(bool success, bytes memory ret) = calls[i].target.call(calls[i].data);
require(success, "Multicall aggregate: call failed");
returnData[i] = ret;
}
}
// function _rescueStuckTokens(address[] calldata _tokens) internal override {
// super._rescueStuckTokens(_tokens);
// }
}
// SPDX-License-Identifier: AGPL-3.0
pragma solidity 0.8.3;
import "@openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol";
import "contracts/interfaces/IStrategy.sol";
import "contracts/Registry.sol";
import "contracts/libraries/OndoLibrary.sol";
import "contracts/OndoRegistryClient.sol";
import "contracts/interfaces/IPairVault.sol";
/**
* @title Basic LP strategy
* @notice All LP strategies should inherit from this
*/
abstract contract BasePairLPStrategy is OndoRegistryClient, IStrategy {
using SafeERC20 for IERC20;
modifier onlyOrigin(uint256 _vaultId) {
require(
msg.sender == address(vaults[_vaultId].origin),
"Unauthorized: Only Vault contract"
);
_;
}
event Invest(uint256 indexed vault, uint256 lpTokens);
event Redeem(uint256 indexed vault);
event Harvest(address indexed pool, uint256 lpTokens);
mapping(uint256 => Vault) public override vaults;
constructor(address _registry) OndoRegistryClient(_registry) {}
/**
* @notice Deposit more LP tokens while Vault is invested
*/
function addLp(uint256 _vaultId, uint256 _amount)
external
virtual
override
whenNotPaused
onlyOrigin(_vaultId)
{
Vault storage vault_ = vaults[_vaultId];
vault_.shares += _amount;
}
/**
* @notice Remove LP tokens while Vault is invested
*/
function removeLp(
uint256 _vaultId,
uint256 _amount,
address to
) external virtual override whenNotPaused onlyOrigin(_vaultId) {
Vault storage vault_ = vaults[_vaultId];
vault_.shares -= _amount;
IERC20(vault_.pool).safeTransfer(to, _amount);
}
/**
* @notice Return the DEX pool and the amount of LP tokens
*/
function getVaultInfo(uint256 _vaultId)
external
view
override
returns (IERC20, uint256)
{
Vault storage c = vaults[_vaultId];
return (c.pool, c.shares);
}
/**
* @notice Send excess tokens to investor
*/
function withdrawExcess(
uint256 _vaultId,
OLib.Tranche tranche,
address to,
uint256 amount
) external override onlyOrigin(_vaultId) {
Vault storage _vault = vaults[_vaultId];
if (tranche == OLib.Tranche.Senior) {
uint256 excess = _vault.seniorExcess;
require(amount <= excess, "Withdrawing too much");
_vault.seniorExcess -= amount;
_vault.senior.safeTransfer(to, amount);
} else {
uint256 excess = _vault.juniorExcess;
require(amount <= excess, "Withdrawing too much");
_vault.juniorExcess -= amount;
_vault.junior.safeTransfer(to, amount);
}
}
}
pragma solidity 0.8.3;
import "contracts/strategies/AUniswapStrategy.sol";
import "contracts/vendor/barnbridge/Staking.sol";
import "contracts/vendor/barnbridge/YieldFarmLP.sol";
import "contracts/libraries/OndoLibrary.sol";
import "@openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol";
contract BondStrategy is AUniswapStrategy {
using SafeERC20 for IERC20;
using OndoSaferERC20 for IERC20;
string public constant name = "Ondo UniswapV2 BOND/USDC Strategy";
uint256 public totalLP;
Staking public immutable stakingContract;
YieldFarmLp public immutable yieldFarm;
IERC20 public immutable bond;
IERC20 public immutable usdc;
IERC20 public immutable usdcBondUniLp;
constructor(
address _registry,
address _router,
address _factory,
address _staking,
address _yieldFarm,
address _usdc,
address _bond,
address _usdcBondUniLp
) AUniswapStrategy(_registry, _router, _factory, 0) {
// AMM 0 stands for uniswap
require(_staking != address(0), "staking address cannot be zero");
require(_yieldFarm != address(0), "yieldfarm cannot be zero");
require(_bond != address(0), "bond cannot be zero");
require(_usdc != address(0), "usdc cannot be zero");
require(_usdcBondUniLp != address(0), "usdcBondUniLp cannot be zero");
stakingContract = Staking(_staking);
yieldFarm = YieldFarmLp(_yieldFarm);
bond = IERC20(_bond);
usdc = IERC20(_usdc);
usdcBondUniLp = IERC20(_usdcBondUniLp);
}
function invest(
uint256 _vaultId,
uint256 _totalSenior,
uint256 _totalJunior,
uint256 _extraSenior,
uint256 _extraJunior,
uint256 _seniorMinIn,
uint256 _juniorMinIn
)
external
override
nonReentrant
whenNotPaused
onlyOrigin(_vaultId)
returns (uint256 seniorInvested, uint256 juniorInvested)
{
uint256 lpTokens;
(seniorInvested, juniorInvested, lpTokens) = _invest(
_vaultId,
_totalSenior,
_totalJunior,
_extraSenior,
_extraJunior,
_seniorMinIn,
_juniorMinIn
);
depositIntoStaking(lpTokens);
}
function redeem(
uint256 _vaultId,
uint256 _seniorExpected,
uint256 _seniorMinReceived,
uint256 _juniorMinReceived
)
external
override
nonReentrant
whenNotPaused
onlyOrigin(_vaultId)
returns (uint256 seniorReceived, uint256 juniorReceived)
{
Vault storage vault_ = vaults[_vaultId];
// withdraw from stakingContract
uint256 totalLPBefore = totalLP;
withdrawFromStaking(totalLP);
(seniorReceived, juniorReceived) = _redeem(
_vaultId,
totalLPBefore,
_seniorExpected,
_seniorMinReceived,
_juniorMinReceived
);
}
function depositIntoStaking(uint256 _amount) internal {
require(_amount > 0, "amount must be greater than 0");
// increase allowance for our lp tokens
usdcBondUniLp.ondoSafeIncreaseAllowance(address(stakingContract), _amount);
// deposit into staking
stakingContract.deposit(address(usdcBondUniLp), _amount);
totalLP += _amount;
}
function withdrawFromStaking(uint256 _amount) internal {
require(_amount > 0, "_amount must be greater than 0");
stakingContract.withdraw(address(usdcBondUniLp), _amount);
totalLP -= _amount;
}
/**
* @notice Deposit more LP tokens while Vault is invested
*/
function addLp(uint256 _vaultId, uint256 _amount)
external
virtual
override
whenNotPaused
onlyOrigin(_vaultId)
{
Vault storage vault_ = vaults[_vaultId];
depositIntoStaking(_amount);
vault_.shares += _amount;
}
/**
* @notice Remove LP tokens while Vault is invested
*/
function removeLp(
uint256 _vaultId,
uint256 _amount,
address to
) external virtual override whenNotPaused onlyOrigin(_vaultId) {
Vault storage vault_ = vaults[_vaultId];
withdrawFromStaking(_amount);
IERC20(vault_.pool).safeTransfer(to, _amount);
vault_.shares -= _amount;
}
function harvest(uint256 _minLp)
external
nonReentrant
whenNotPaused
isAuthorized(OLib.STRATEGIST_ROLE)
returns (uint256)
{
uint256 bondAmountBefore = bond.balanceOf(address(this));
// get harvested tokens for all epochs
yieldFarm.massHarvest();
uint256 bondAmountAfter = bond.balanceOf(address(this));
// technically can just use balanceOf since all bond balance should be provided as LP
uint256 bondAmount = bondAmountAfter - bondAmountBefore;
uint256 usdcAmount = 0;
uint256 lpTokens = 0;
// we know that bond would have increased as part of harvest so now we need to convert the bond to balance with usdc so we can provide more LP
if (bondAmount > 10000) {
// same interface for uniswap and sushiswap
(, , lpTokens) = investB(
address(usdc),
address(bond),
usdcAmount,
bondAmount
);
// we have more LP now so time to invest that in staking contract
// stake new LP tokens in bond
depositIntoStaking(lpTokens);
}
require(lpTokens >= _minLp, "Exceeds maximum slippage");
return lpTokens;
}
}
pragma solidity 0.8.3;
interface Staking {
function balanceOf(address user, address token)
external
view
returns (uint256);
function deposit(address tokenAddress, uint256 amount) external;
function withdraw(address tokenAddress, uint256 amount) external;
}
pragma solidity 0.8.3;
interface YieldFarmLp {
function massHarvest() external returns (uint256);
function harvest(uint128 epochId) external returns (uint256);
}
pragma solidity >=0.8.0;
import "@uniswap/v2-core/contracts/interfaces/IUniswapV2Pair.sol";
import "@openzeppelin/contracts/utils/math/SafeMath.sol";
library SushiSwapLibrary {
using SafeMath for uint256;
// 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(
uint160(
uint256(
keccak256(
abi.encodePacked(
hex"ff",
factory,
keccak256(abi.encodePacked(token0, token1)),
hex"e18a34eb0e04b04f7a0ac29a6e80748dca96319b42c54d679cb821dca90c6303" // init code hash
)
)
)
)
);
}
// fetches and sorts the reserves for a pair
function getReserves(
address factory,
address tokenA,
address tokenB
) internal view returns (uint256 reserveA, uint256 reserveB) {
(address token0, ) = sortTokens(tokenA, tokenB);
(uint256 reserve0, uint256 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(
uint256 amountA,
uint256 reserveA,
uint256 reserveB
) internal pure returns (uint256 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(
uint256 amountIn,
uint256 reserveIn,
uint256 reserveOut
) internal pure returns (uint256 amountOut) {
require(amountIn > 0, "UniswapV2Library: INSUFFICIENT_INPUT_AMOUNT");
require(
reserveIn > 0 && reserveOut > 0,
"UniswapV2Library: INSUFFICIENT_LIQUIDITY"
);
uint256 amountInWithFee = amountIn.mul(997);
uint256 numerator = amountInWithFee.mul(reserveOut);
uint256 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(
uint256 amountOut,
uint256 reserveIn,
uint256 reserveOut
) internal pure returns (uint256 amountIn) {
require(amountOut > 0, "UniswapV2Library: INSUFFICIENT_OUTPUT_AMOUNT");
require(
reserveIn > 0 && reserveOut > 0,
"UniswapV2Library: INSUFFICIENT_LIQUIDITY"
);
uint256 numerator = reserveIn.mul(amountOut).mul(1000);
uint256 denominator = reserveOut.sub(amountOut).mul(997);
amountIn = (numerator / denominator).add(1);
}
// performs chained getAmountOut calculations on any number of pairs
function getAmountsOut(
address factory,
uint256 amountIn,
address[] memory path
) internal view returns (uint256[] memory amounts) {
require(path.length >= 2, "UniswapV2Library: INVALID_PATH");
amounts = new uint256[](path.length);
amounts[0] = amountIn;
for (uint256 i; i < path.length - 1; i++) {
(uint256 reserveIn, uint256 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,
uint256 amountOut,
address[] memory path
) internal view returns (uint256[] memory amounts) {
require(path.length >= 2, "UniswapV2Library: INVALID_PATH");
amounts = new uint256[](path.length);
amounts[amounts.length - 1] = amountOut;
for (uint256 i = path.length - 1; i > 0; i--) {
(uint256 reserveIn, uint256 reserveOut) =
getReserves(factory, path[i - 1], path[i]);
amounts[i - 1] = getAmountIn(amounts[i], reserveIn, reserveOut);
}
}
}
pragma solidity >=0.8.0;
import "@uniswap/v2-core/contracts/interfaces/IUniswapV2Pair.sol";
import "@openzeppelin/contracts/utils/math/SafeMath.sol";
library UniswapV2Library {
using SafeMath for uint256;
// 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(
uint160(
uint256(
keccak256(
abi.encodePacked(
hex"ff",
factory,
keccak256(abi.encodePacked(token0, token1)),
hex"96e8ac4277198ff8b6f785478aa9a39f403cb768dd02cbee326c3e7da348845f" // init code hash
)
)
)
)
);
}
// fetches and sorts the reserves for a pair
function getReserves(
address factory,
address tokenA,
address tokenB
) internal view returns (uint256 reserveA, uint256 reserveB) {
(address token0, ) = sortTokens(tokenA, tokenB);
(uint256 reserve0, uint256 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(
uint256 amountA,
uint256 reserveA,
uint256 reserveB
) internal pure returns (uint256 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(
uint256 amountIn,
uint256 reserveIn,
uint256 reserveOut
) internal pure returns (uint256 amountOut) {
require(amountIn > 0, "UniswapV2Library: INSUFFICIENT_INPUT_AMOUNT");
require(
reserveIn > 0 && reserveOut > 0,
"UniswapV2Library: INSUFFICIENT_LIQUIDITY"
);
uint256 amountInWithFee = amountIn.mul(997);
uint256 numerator = amountInWithFee.mul(reserveOut);
uint256 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(
uint256 amountOut,
uint256 reserveIn,
uint256 reserveOut
) internal pure returns (uint256 amountIn) {
require(amountOut > 0, "UniswapV2Library: INSUFFICIENT_OUTPUT_AMOUNT");
require(
reserveIn > 0 && reserveOut > 0,
"UniswapV2Library: INSUFFICIENT_LIQUIDITY"
);
uint256 numerator = reserveIn.mul(amountOut).mul(1000);
uint256 denominator = reserveOut.sub(amountOut).mul(997);
amountIn = (numerator / denominator).add(1);
}
// performs chained getAmountOut calculations on any number of pairs
function getAmountsOut(
address factory,
uint256 amountIn,
address[] memory path
) internal view returns (uint256[] memory amounts) {
require(path.length >= 2, "UniswapV2Library: INVALID_PATH");
amounts = new uint256[](path.length);
amounts[0] = amountIn;
for (uint256 i; i < path.length - 1; i++) {
(uint256 reserveIn, uint256 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,
uint256 amountOut,
address[] memory path
) internal view returns (uint256[] memory amounts) {
require(path.length >= 2, "UniswapV2Library: INVALID_PATH");
amounts = new uint256[](path.length);
amounts[amounts.length - 1] = amountOut;
for (uint256 i = path.length - 1; i > 0; i--) {
(uint256 reserveIn, uint256 reserveOut) =
getReserves(factory, path[i - 1], path[i]);
amounts[i - 1] = getAmountIn(amounts[i], reserveIn, reserveOut);
}
}
} | * Removes a feature flag./ | function deleteFeatureFlag(bytes32 _featureFlag)
external
override
onlyRole(OLib.GOVERNANCE_ROLE)
{
delete featureFlags[_featureFlag];
}
| 14,555,298 | [
1,
6220,
279,
2572,
2982,
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,
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,
225,
445,
1430,
4595,
4678,
12,
3890,
1578,
389,
7238,
4678,
13,
203,
565,
3903,
203,
565,
3849,
203,
565,
1338,
2996,
12,
1741,
495,
18,
43,
12959,
50,
4722,
67,
16256,
13,
203,
225,
288,
203,
565,
1430,
2572,
5094,
63,
67,
7238,
4678,
15533,
203,
225,
289,
203,
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,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-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/0x356ED178c62a251136D883f01e1B84CF6980AEa8/sources/contracts/GNARDescriptor.sol | Whether or not new Gnar parts can be added Whether or not `tokenURI` should be returned as a data URI (Default: true) Base URI Gnar Color Palettes (Index => Hex Colors) Gnar Backgrounds (Hex Colors) Gnar Bodies (Custom RLE) Gnar Accessories (Custom RLE) Gnar Heads (Custom RLE) Gnar Glasses (Custom RLE) | contract GNARDescriptor is IGnarDescriptor, Ownable {
using Strings for uint256;
bool public override arePartsLocked;
bool public override isDataURIEnabled = true;
string public override baseURI;
mapping(uint8 => string[]) public override palettes;
string[] public override backgrounds;
bytes[] public override bodies;
bytes[] public override accessories;
bytes[] public override heads;
bytes[] public override glasses;
pragma solidity ^0.8.6;
import {Ownable} from "@openzeppelin/contracts/access/Ownable.sol";
import {Base64} from "base64-sol/base64.sol";
import {Strings} from "@openzeppelin/contracts/utils/Strings.sol";
import {IGnarDescriptor} from "../interfaces/IGNARDescriptor.sol";
import {IGnarSeeder} from "../interfaces/IGNARSeeder.sol";
import {MultiPartRLEToSVG} from "./libs/MultiPartRLEToSVG.sol";
modifier whenPartsNotLocked() {
require(!arePartsLocked, "Parts are locked");
_;
}
function backgroundCount() external view override returns (uint256) {
return backgrounds.length;
}
function bodyCount() external view override returns (uint256) {
return bodies.length;
}
function accessoryCount() external view override returns (uint256) {
return accessories.length;
}
function headCount() external view override returns (uint256) {
return heads.length;
}
function glassesCount() external view override returns (uint256) {
return glasses.length;
}
function addManyColorsToPalette(
uint8 paletteIndex,
string[] calldata newColors
) external override onlyOwner {
require(
palettes[paletteIndex].length + newColors.length <= 256,
"Palettes can only hold 256 colors"
);
for (uint256 i = 0; i < newColors.length; i++) {
_addColorToPalette(paletteIndex, newColors[i]);
}
}
function addManyColorsToPalette(
uint8 paletteIndex,
string[] calldata newColors
) external override onlyOwner {
require(
palettes[paletteIndex].length + newColors.length <= 256,
"Palettes can only hold 256 colors"
);
for (uint256 i = 0; i < newColors.length; i++) {
_addColorToPalette(paletteIndex, newColors[i]);
}
}
function addManyBackgrounds(string[] calldata _backgrounds)
external
override
onlyOwner
whenPartsNotLocked
{
for (uint256 i = 0; i < _backgrounds.length; i++) {
_addBackground(_backgrounds[i]);
}
}
function addManyBackgrounds(string[] calldata _backgrounds)
external
override
onlyOwner
whenPartsNotLocked
{
for (uint256 i = 0; i < _backgrounds.length; i++) {
_addBackground(_backgrounds[i]);
}
}
function addManyBodies(bytes[] calldata _bodies)
external
override
onlyOwner
whenPartsNotLocked
{
for (uint256 i = 0; i < _bodies.length; i++) {
_addBody(_bodies[i]);
}
}
function addManyBodies(bytes[] calldata _bodies)
external
override
onlyOwner
whenPartsNotLocked
{
for (uint256 i = 0; i < _bodies.length; i++) {
_addBody(_bodies[i]);
}
}
function addManyAccessories(bytes[] calldata _accessories)
external
override
onlyOwner
whenPartsNotLocked
{
for (uint256 i = 0; i < _accessories.length; i++) {
_addAccessory(_accessories[i]);
}
}
function addManyAccessories(bytes[] calldata _accessories)
external
override
onlyOwner
whenPartsNotLocked
{
for (uint256 i = 0; i < _accessories.length; i++) {
_addAccessory(_accessories[i]);
}
}
function addManyHeads(bytes[] calldata _heads)
external
override
onlyOwner
whenPartsNotLocked
{
for (uint256 i = 0; i < _heads.length; i++) {
_addHead(_heads[i]);
}
}
function addManyHeads(bytes[] calldata _heads)
external
override
onlyOwner
whenPartsNotLocked
{
for (uint256 i = 0; i < _heads.length; i++) {
_addHead(_heads[i]);
}
}
function addManyGlasses(bytes[] calldata _glasses)
external
override
onlyOwner
whenPartsNotLocked
{
for (uint256 i = 0; i < _glasses.length; i++) {
_addGlasses(_glasses[i]);
}
}
function addManyGlasses(bytes[] calldata _glasses)
external
override
onlyOwner
whenPartsNotLocked
{
for (uint256 i = 0; i < _glasses.length; i++) {
_addGlasses(_glasses[i]);
}
}
function addColorToPalette(uint8 _paletteIndex, string calldata _color)
external
override
onlyOwner
{
require(
palettes[_paletteIndex].length <= 255,
"Palettes can only hold 256 colors"
);
_addColorToPalette(_paletteIndex, _color);
}
function addBackground(string calldata _background)
external
override
onlyOwner
whenPartsNotLocked
{
_addBackground(_background);
}
function addBody(bytes calldata _body)
external
override
onlyOwner
whenPartsNotLocked
{
_addBody(_body);
}
function addAccessory(bytes calldata _accessory)
external
override
onlyOwner
whenPartsNotLocked
{
_addAccessory(_accessory);
}
function addHead(bytes calldata _head)
external
override
onlyOwner
whenPartsNotLocked
{
_addHead(_head);
}
function addGlasses(bytes calldata _glasses)
external
override
onlyOwner
whenPartsNotLocked
{
_addGlasses(_glasses);
}
function lockParts() external override onlyOwner whenPartsNotLocked {
arePartsLocked = true;
emit PartsLocked();
}
function toggleDataURIEnabled() external override onlyOwner {
bool enabled = !isDataURIEnabled;
isDataURIEnabled = enabled;
emit DataURIToggled(enabled);
}
function setBaseURI(string calldata _baseURI) external override onlyOwner {
baseURI = _baseURI;
emit BaseURIUpdated(_baseURI);
}
function tokenURI(uint256 tokenId, IGnarSeeder.Seed memory seed)
external
view
override
returns (string memory)
{
if (isDataURIEnabled) {
return dataURI(tokenId, seed);
}
return string(abi.encodePacked(baseURI, tokenId.toString()));
}
function tokenURI(uint256 tokenId, IGnarSeeder.Seed memory seed)
external
view
override
returns (string memory)
{
if (isDataURIEnabled) {
return dataURI(tokenId, seed);
}
return string(abi.encodePacked(baseURI, tokenId.toString()));
}
function dataURI(uint256 tokenId, IGnarSeeder.Seed memory seed)
public
view
override
returns (string memory)
{
string memory gnarId = tokenId.toString();
string memory name = string(abi.encodePacked("Gnar ", gnarId));
string memory description = string(
abi.encodePacked("Gnar ", gnarId, " both skater and terrain")
);
return genericDataURI(name, description, seed);
}
function genericDataURI(
string memory name,
string memory description,
IGnarSeeder.Seed memory seed
) public view override returns (string memory) {
string memory image = _generateSVGImage(
MultiPartRLEToSVG.SVGParams({
parts: _getPartsForSeed(seed),
background: backgrounds[seed.background]
})
);
abi.encodePacked(
'data:application/json;base64,',
Base64.encode(
bytes(
)
)
)
);
}
function genericDataURI(
string memory name,
string memory description,
IGnarSeeder.Seed memory seed
) public view override returns (string memory) {
string memory image = _generateSVGImage(
MultiPartRLEToSVG.SVGParams({
parts: _getPartsForSeed(seed),
background: backgrounds[seed.background]
})
);
abi.encodePacked(
'data:application/json;base64,',
Base64.encode(
bytes(
)
)
)
);
}
return string(
abi.encodePacked('{"name":"', name, '", "description":"', description, '", "image": "', 'data:image/svg+xml;base64,', image, '"}')
function generateSVGImage(IGnarSeeder.Seed memory seed)
external
view
override
returns (string memory)
{
MultiPartRLEToSVG.SVGParams memory params = MultiPartRLEToSVG
.SVGParams({
parts: _getPartsForSeed(seed),
background: backgrounds[seed.background]
});
return _generateSVGImage(params);
}
function generateSVGImage(IGnarSeeder.Seed memory seed)
external
view
override
returns (string memory)
{
MultiPartRLEToSVG.SVGParams memory params = MultiPartRLEToSVG
.SVGParams({
parts: _getPartsForSeed(seed),
background: backgrounds[seed.background]
});
return _generateSVGImage(params);
}
function _generateSVGImage(MultiPartRLEToSVG.SVGParams memory params)
public
view
returns (string memory svg)
{
return
Base64.encode(
bytes(MultiPartRLEToSVG.generateSVG(params, palettes))
);
}
function _addColorToPalette(uint8 _paletteIndex, string calldata _color)
internal
{
palettes[_paletteIndex].push(_color);
}
function _addBackground(string calldata _background) internal {
backgrounds.push(_background);
}
function _addBody(bytes calldata _body) internal {
bodies.push(_body);
}
function _addAccessory(bytes calldata _accessory) internal {
accessories.push(_accessory);
}
function _addHead(bytes calldata _head) internal {
heads.push(_head);
}
function _addGlasses(bytes calldata _glasses) internal {
glasses.push(_glasses);
}
function _getPartsForSeed(IGnarSeeder.Seed memory seed)
internal
view
returns (bytes[] memory)
{
bytes[] memory _parts = new bytes[](4);
_parts[0] = bodies[seed.body];
_parts[1] = accessories[seed.accessory];
_parts[2] = heads[seed.head];
_parts[3] = glasses[seed.glasses];
return _parts;
}
}
| 16,113,250 | [
1,
18247,
578,
486,
394,
611,
82,
297,
2140,
848,
506,
3096,
17403,
578,
486,
1375,
2316,
3098,
68,
1410,
506,
2106,
487,
279,
501,
3699,
261,
1868,
30,
638,
13,
3360,
3699,
611,
82,
297,
5563,
453,
287,
278,
1078,
261,
1016,
516,
15734,
30448,
13,
611,
82,
297,
8977,
87,
261,
7037,
30448,
13,
611,
82,
297,
605,
18134,
261,
3802,
534,
900,
13,
611,
82,
297,
5016,
2401,
261,
3802,
534,
900,
13,
611,
82,
297,
3667,
87,
261,
3802,
534,
900,
13,
611,
82,
297,
611,
459,
281,
261,
3802,
534,
900,
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
] | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
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
] | [
1,
16351,
611,
50,
985,
3187,
353,
13102,
82,
297,
3187,
16,
14223,
6914,
288,
203,
565,
1450,
8139,
364,
2254,
5034,
31,
203,
203,
565,
1426,
1071,
3849,
854,
4305,
8966,
31,
203,
203,
565,
1426,
1071,
3849,
353,
751,
3098,
1526,
273,
638,
31,
203,
203,
565,
533,
1071,
3849,
1026,
3098,
31,
203,
203,
565,
2874,
12,
11890,
28,
516,
533,
63,
5717,
1071,
3849,
25995,
278,
1078,
31,
203,
203,
565,
533,
8526,
1071,
3849,
5412,
87,
31,
203,
203,
565,
1731,
8526,
1071,
3849,
25126,
31,
203,
203,
565,
1731,
8526,
1071,
3849,
2006,
2401,
31,
203,
203,
565,
1731,
8526,
1071,
3849,
22742,
31,
203,
203,
565,
1731,
8526,
1071,
3849,
314,
459,
281,
31,
203,
203,
683,
9454,
18035,
560,
3602,
20,
18,
28,
18,
26,
31,
203,
5666,
288,
5460,
429,
97,
628,
8787,
3190,
94,
881,
84,
292,
267,
19,
16351,
87,
19,
3860,
19,
5460,
429,
18,
18281,
14432,
203,
5666,
288,
2171,
1105,
97,
628,
315,
1969,
1105,
17,
18281,
19,
1969,
1105,
18,
18281,
14432,
203,
5666,
288,
7957,
97,
628,
8787,
3190,
94,
881,
84,
292,
267,
19,
16351,
87,
19,
5471,
19,
7957,
18,
18281,
14432,
203,
5666,
288,
3047,
82,
297,
3187,
97,
628,
315,
6216,
15898,
19,
10452,
985,
3187,
18,
18281,
14432,
203,
5666,
288,
3047,
82,
297,
12702,
264,
97,
628,
315,
6216,
15898,
19,
10452,
985,
12702,
264,
18,
18281,
14432,
203,
5666,
288,
5002,
1988,
54,
900,
774,
26531,
97,
628,
25165,
21571,
19,
5002,
2
] |
pragma solidity ^0.4.24;
import "./LibSubmarineSimple.sol";
import "./CypherpunkCoin.sol";
contract DutchAuction is LibSubmarineSimple {
uint256 public endAuctionTxBlockNumber;
uint256 public endAuctionTxIndex;
bool public canfinalize;
uint256 public constant startCommitBlock;
uint256 public constant endCommitBlock;
CypherpunkCoin public token;
address public owner;
uint256 public clearingPrice;
uint256 public ethRefundLastBidder;
address public lastBidder;
// start the auction with specified commitment period, owner and token
constructor(
Cypherpunk _token,
address _owner,
uint256 _startCommitBlock,
uint256 _endCommitBlock
) public {
token = _token;
owner = _owner;
startCommitBlock = _startCommitBlock;
endCommitBlock = _endCommitBlock;
}
// owner based on the events Revealed and Unlocked emitted by the contract
// to set these attributes
function prepareFinalize(
uint256 _endAuctionTxBlockNumber,
uint256 _endAuctionTxIndex,
uint256 _clearingPrice,
uint256 _ethRefundLastBidder,
address _lastBidder
) public {
require(msg.sender == owner);
// set the transaction that ends the auction
endAuctionTxBlockNumber = _endAuctionTxBlockNumber;
endAuctionTxIndex = _endAuctionTxIndex;
clearingPrice = _clearingPrice;
lastBidder = _lastBidder;
ethRefundLastBidder = _ethRefundLastBidder;
canfinalize = true;
}
// a bidder call this function to take their tokens if their commitment are valid to do so
// or get their ETH back
function finalize(bytes32 _submarineId) {
require(
canfinalize,
"Have to wait for the owner to set the ending block transaction"
);
require(
revealedAndUnlocked(_submarineId),
"The commitment has not been revealed or unlocked"
);
SubmarineSession ss = sessions[_submarineId];
// check whether the commit transaction is in the specified window
if (
ss.commitTxBlockNumber >= startCommitBlock &&
(ss.commitTxBlockNumber < endAuctionTxBlockNumber ||
(ss.commitTxBlockNumber == endAuctionTxBlockNumber &&
ss.commitTxIndex <= endAuctionTxIndex))
) {
// check whether the bidder is the last bidder
if (
bidders[_submarineId] == lastBidder && ethRefundLastBidder != 0
) {
address payable bidderPayable = address(
uint160(address(bidders[_submarineId]))
);
ss.amountRevealed = ss.amountRevealed.sub(ethRefundLastBidder);
bidderPayable.transfer(ethRefundLastBidder);
}
token.transfer(
bidders[_submarineId],
ss.amountRevealed.div(clearingPrice)
);
} else bidders[_submarineId].transfer(ss.amountUnlocked);
}
// function executed on every revealing
function onSubmarineReveal(
bytes32 _submarineId,
bytes _embeddedDAppData,
uint256 _value,
uint32 _commitTxBlockNumber
) {
// require the commit to be in the specified period
require(
_commitTxBlockNumber >= startCommitBlock &&
_commitTxBlockNumber <= endCommitBlock,
"The commitment has to be in the committing window"
);
bidders[_submarineId] = msg.sender;
}
}
| start the auction with specified commitment period, owner and token | contract DutchAuction is LibSubmarineSimple {
uint256 public endAuctionTxBlockNumber;
uint256 public endAuctionTxIndex;
bool public canfinalize;
uint256 public constant startCommitBlock;
uint256 public constant endCommitBlock;
CypherpunkCoin public token;
address public owner;
uint256 public clearingPrice;
uint256 public ethRefundLastBidder;
address public lastBidder;
constructor(
Cypherpunk _token,
address _owner,
uint256 _startCommitBlock,
uint256 _endCommitBlock
) public {
token = _token;
owner = _owner;
startCommitBlock = _startCommitBlock;
endCommitBlock = _endCommitBlock;
}
function prepareFinalize(
uint256 _endAuctionTxBlockNumber,
uint256 _endAuctionTxIndex,
uint256 _clearingPrice,
uint256 _ethRefundLastBidder,
address _lastBidder
) public {
require(msg.sender == owner);
endAuctionTxBlockNumber = _endAuctionTxBlockNumber;
endAuctionTxIndex = _endAuctionTxIndex;
clearingPrice = _clearingPrice;
lastBidder = _lastBidder;
ethRefundLastBidder = _ethRefundLastBidder;
canfinalize = true;
}
function finalize(bytes32 _submarineId) {
require(
canfinalize,
"Have to wait for the owner to set the ending block transaction"
);
require(
revealedAndUnlocked(_submarineId),
"The commitment has not been revealed or unlocked"
);
SubmarineSession ss = sessions[_submarineId];
if (
ss.commitTxBlockNumber >= startCommitBlock &&
(ss.commitTxBlockNumber < endAuctionTxBlockNumber ||
(ss.commitTxBlockNumber == endAuctionTxBlockNumber &&
ss.commitTxIndex <= endAuctionTxIndex))
) {
if (
bidders[_submarineId] == lastBidder && ethRefundLastBidder != 0
) {
address payable bidderPayable = address(
uint160(address(bidders[_submarineId]))
);
ss.amountRevealed = ss.amountRevealed.sub(ethRefundLastBidder);
bidderPayable.transfer(ethRefundLastBidder);
}
token.transfer(
bidders[_submarineId],
ss.amountRevealed.div(clearingPrice)
);
} else bidders[_submarineId].transfer(ss.amountUnlocked);
}
function finalize(bytes32 _submarineId) {
require(
canfinalize,
"Have to wait for the owner to set the ending block transaction"
);
require(
revealedAndUnlocked(_submarineId),
"The commitment has not been revealed or unlocked"
);
SubmarineSession ss = sessions[_submarineId];
if (
ss.commitTxBlockNumber >= startCommitBlock &&
(ss.commitTxBlockNumber < endAuctionTxBlockNumber ||
(ss.commitTxBlockNumber == endAuctionTxBlockNumber &&
ss.commitTxIndex <= endAuctionTxIndex))
) {
if (
bidders[_submarineId] == lastBidder && ethRefundLastBidder != 0
) {
address payable bidderPayable = address(
uint160(address(bidders[_submarineId]))
);
ss.amountRevealed = ss.amountRevealed.sub(ethRefundLastBidder);
bidderPayable.transfer(ethRefundLastBidder);
}
token.transfer(
bidders[_submarineId],
ss.amountRevealed.div(clearingPrice)
);
} else bidders[_submarineId].transfer(ss.amountUnlocked);
}
function finalize(bytes32 _submarineId) {
require(
canfinalize,
"Have to wait for the owner to set the ending block transaction"
);
require(
revealedAndUnlocked(_submarineId),
"The commitment has not been revealed or unlocked"
);
SubmarineSession ss = sessions[_submarineId];
if (
ss.commitTxBlockNumber >= startCommitBlock &&
(ss.commitTxBlockNumber < endAuctionTxBlockNumber ||
(ss.commitTxBlockNumber == endAuctionTxBlockNumber &&
ss.commitTxIndex <= endAuctionTxIndex))
) {
if (
bidders[_submarineId] == lastBidder && ethRefundLastBidder != 0
) {
address payable bidderPayable = address(
uint160(address(bidders[_submarineId]))
);
ss.amountRevealed = ss.amountRevealed.sub(ethRefundLastBidder);
bidderPayable.transfer(ethRefundLastBidder);
}
token.transfer(
bidders[_submarineId],
ss.amountRevealed.div(clearingPrice)
);
} else bidders[_submarineId].transfer(ss.amountUnlocked);
}
function onSubmarineReveal(
bytes32 _submarineId,
bytes _embeddedDAppData,
uint256 _value,
uint32 _commitTxBlockNumber
) {
require(
_commitTxBlockNumber >= startCommitBlock &&
_commitTxBlockNumber <= endCommitBlock,
"The commitment has to be in the committing window"
);
bidders[_submarineId] = msg.sender;
}
}
| 13,007,346 | [
1,
1937,
326,
279,
4062,
598,
1269,
23274,
3879,
16,
3410,
471,
1147,
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,
16351,
463,
322,
343,
37,
4062,
353,
10560,
1676,
3684,
558,
5784,
288,
203,
565,
2254,
5034,
1071,
679,
37,
4062,
4188,
1768,
1854,
31,
203,
565,
2254,
5034,
1071,
679,
37,
4062,
4188,
1016,
31,
203,
565,
1426,
1071,
848,
30343,
31,
203,
565,
2254,
5034,
1071,
5381,
787,
5580,
1768,
31,
203,
565,
2254,
5034,
1071,
5381,
679,
5580,
1768,
31,
203,
565,
22337,
21496,
84,
1683,
27055,
1071,
1147,
31,
203,
565,
1758,
1071,
3410,
31,
203,
565,
2254,
5034,
1071,
29820,
5147,
31,
203,
565,
2254,
5034,
1071,
13750,
21537,
3024,
17763,
765,
31,
203,
565,
1758,
1071,
1142,
17763,
765,
31,
203,
203,
565,
3885,
12,
203,
3639,
22337,
21496,
84,
1683,
389,
2316,
16,
203,
3639,
1758,
389,
8443,
16,
203,
3639,
2254,
5034,
389,
1937,
5580,
1768,
16,
203,
3639,
2254,
5034,
389,
409,
5580,
1768,
203,
565,
262,
1071,
288,
203,
3639,
1147,
273,
389,
2316,
31,
203,
3639,
3410,
273,
389,
8443,
31,
203,
3639,
787,
5580,
1768,
273,
389,
1937,
5580,
1768,
31,
203,
3639,
679,
5580,
1768,
273,
389,
409,
5580,
1768,
31,
203,
565,
289,
203,
203,
565,
445,
2911,
7951,
554,
12,
203,
3639,
2254,
5034,
389,
409,
37,
4062,
4188,
1768,
1854,
16,
203,
3639,
2254,
5034,
389,
409,
37,
4062,
4188,
1016,
16,
203,
3639,
2254,
5034,
389,
2131,
5968,
5147,
16,
203,
3639,
2254,
5034,
389,
546,
21537,
3024,
17763,
765,
16,
203,
3639,
1758,
389,
2722,
17763,
765,
203,
565,
262,
1071,
288,
203,
3639,
2583,
12,
2
] |
pragma solidity >=0.4.22 <0.6.0;
// * Gods Unchained Ticket Sale
//
// * Version 1.0
//
// * A dedicated contract selling tickets for the Gods Unchained tournament.
//
// * https://gu.cards
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 TournamentTicket is ERC20Interface {}
contract TournamentTicketSale {
//////// V A R I A B L E S
//
// Current address of the ticket contract (tickets).
//
address public ticketContract;
//
// Address that owns the tickets.
//
address payable public ticketOwner;
//
// In case the sale is paused.
//
bool public paused;
//
// Price per ticket.
//
uint public pricePerTicket;
//
// Standard contract ownership.
//
address payable public owner;
address payable private nextOwner;
//////// M O D I F I E R S
//
// Invokable only by contract owner.
//
modifier onlyContractOwner {
require(msg.sender == owner, "Function called by non-owner.");
_;
}
//
// Invokable only by owner of the tickets.
//
modifier onlyTicketOwner {
require(msg.sender == ticketOwner, "Function called by non-ticket-owner.");
_;
}
//
// Invokable only if exchange is not paused.
//
modifier onlyUnpaused {
require(paused == false, "Exchange is paused.");
_;
}
//////// C O N S T R U C T O R
//
constructor() public {
owner = msg.sender;
}
//////// F U N C T I O N S
//
// Buy a single ticket.
//
function buyOne() onlyUnpaused payable external {
TournamentTicket ticket = getTicketContract();
require(ticket.balanceOf(msg.sender) == 0, "You already have a ticket, and you only need one to participate!");
require(pricePerTicket > 0, "The price per ticket needs to be more than 0!");
require(msg.value == pricePerTicket, "The amout sent is not corresponding with the ticket price!");
require(
ticket.transferFrom(getTicketOwnerAddress(), msg.sender, 1000000000000000000),
"Ticket transfer failed!"
);
getTicketOwnerAddress().transfer(msg.value);
}
//
// Sets current ticket price.
//
function setTicketPrice(uint price) external onlyTicketOwner {
pricePerTicket = price;
}
//
// Sets current ticket token contract address.
//
function setTicketContract(address value) external onlyContractOwner {
ticketContract = value;
}
//
// Get current ticket token contract instance.
//
function getTicketContract() internal view returns(TournamentTicket) {
return(TournamentTicket(ticketContract));
}
//
// Sets current ticket token contract address.
//
function setTicketOwnerAddress(address payable value) external onlyContractOwner {
ticketOwner = value;
}
//
// Get current ticket token contract instance.
//
function getTicketOwnerAddress() internal view returns(address payable) {
return(ticketOwner);
}
//
// Set paused
//
function setPaused(bool value) external onlyContractOwner {
paused = value;
}
//
// Standard contract ownership transfer.
//
function approveNextOwner(address payable _nextOwner) external onlyContractOwner {
require(_nextOwner != owner, "Cannot approve current owner.");
nextOwner = _nextOwner;
}
//
// Accept the next getGodsTokenContract owner.
//
function acceptNextOwner() external {
require(msg.sender == nextOwner, "The new owner has to accept the previously set new owner.");
owner = nextOwner;
}
//
// Fallback function deliberately left empty. It's primary use case
// is to top up the exchange.
//
function () external payable {}
} | Current address of the ticket contract (tickets). Address that owns the tickets. In case the sale is paused. Price per ticket. Standard contract ownership. Invokable only by contract owner. | contract TournamentTicketSale {
address public ticketContract;
address payable public ticketOwner;
bool public paused;
uint public pricePerTicket;
address payable public owner;
address payable private nextOwner;
contract TournamentTicket is ERC20Interface {}
modifier onlyContractOwner {
require(msg.sender == owner, "Function called by non-owner.");
_;
}
modifier onlyTicketOwner {
require(msg.sender == ticketOwner, "Function called by non-ticket-owner.");
_;
}
modifier onlyUnpaused {
require(paused == false, "Exchange is paused.");
_;
}
constructor() public {
owner = msg.sender;
}
function buyOne() onlyUnpaused payable external {
TournamentTicket ticket = getTicketContract();
require(ticket.balanceOf(msg.sender) == 0, "You already have a ticket, and you only need one to participate!");
require(pricePerTicket > 0, "The price per ticket needs to be more than 0!");
require(msg.value == pricePerTicket, "The amout sent is not corresponding with the ticket price!");
require(
ticket.transferFrom(getTicketOwnerAddress(), msg.sender, 1000000000000000000),
"Ticket transfer failed!"
);
getTicketOwnerAddress().transfer(msg.value);
}
function setTicketPrice(uint price) external onlyTicketOwner {
pricePerTicket = price;
}
function setTicketContract(address value) external onlyContractOwner {
ticketContract = value;
}
function getTicketContract() internal view returns(TournamentTicket) {
return(TournamentTicket(ticketContract));
}
function setTicketOwnerAddress(address payable value) external onlyContractOwner {
ticketOwner = value;
}
function getTicketOwnerAddress() internal view returns(address payable) {
return(ticketOwner);
}
function setPaused(bool value) external onlyContractOwner {
paused = value;
}
function approveNextOwner(address payable _nextOwner) external onlyContractOwner {
require(_nextOwner != owner, "Cannot approve current owner.");
nextOwner = _nextOwner;
}
function acceptNextOwner() external {
require(msg.sender == nextOwner, "The new owner has to accept the previously set new owner.");
owner = nextOwner;
}
function () external payable {}
} | 12,536,578 | [
1,
3935,
1758,
434,
326,
9322,
6835,
261,
6470,
2413,
2934,
5267,
716,
29065,
326,
24475,
18,
657,
648,
326,
272,
5349,
353,
17781,
18,
20137,
1534,
9322,
18,
8263,
6835,
23178,
18,
17602,
429,
1338,
635,
6835,
3410,
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
] | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
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
] | [
1,
16351,
2974,
30751,
13614,
30746,
288,
203,
203,
565,
1758,
1071,
9322,
8924,
31,
203,
565,
1758,
8843,
429,
1071,
9322,
5541,
31,
203,
565,
1426,
1071,
17781,
31,
203,
565,
2254,
1071,
6205,
2173,
13614,
31,
203,
565,
1758,
8843,
429,
1071,
3410,
31,
203,
565,
1758,
8843,
429,
3238,
1024,
5541,
31,
203,
203,
16351,
2974,
30751,
13614,
353,
4232,
39,
3462,
1358,
2618,
203,
565,
9606,
1338,
8924,
5541,
288,
203,
3639,
2583,
12,
3576,
18,
15330,
422,
3410,
16,
315,
2083,
2566,
635,
1661,
17,
8443,
1199,
1769,
203,
3639,
389,
31,
203,
565,
289,
203,
565,
9606,
1338,
13614,
5541,
288,
203,
3639,
2583,
12,
3576,
18,
15330,
422,
9322,
5541,
16,
315,
2083,
2566,
635,
1661,
17,
16282,
17,
8443,
1199,
1769,
203,
3639,
389,
31,
203,
565,
289,
203,
565,
9606,
1338,
984,
8774,
3668,
288,
203,
3639,
2583,
12,
8774,
3668,
422,
629,
16,
315,
11688,
353,
17781,
1199,
1769,
203,
3639,
389,
31,
203,
565,
289,
203,
203,
565,
3885,
1435,
1071,
288,
203,
3639,
3410,
273,
1234,
18,
15330,
31,
203,
565,
289,
203,
203,
565,
445,
30143,
3335,
1435,
1338,
984,
8774,
3668,
8843,
429,
3903,
288,
203,
3639,
2974,
30751,
13614,
9322,
273,
3181,
29378,
8924,
5621,
203,
203,
3639,
2583,
12,
16282,
18,
12296,
951,
12,
3576,
18,
15330,
13,
422,
374,
16,
315,
6225,
1818,
1240,
279,
9322,
16,
471,
1846,
1338,
1608,
1245,
358,
30891,
340,
4442,
1769,
203,
3639,
2583,
12,
8694,
2173,
13614,
405,
374,
16,
315,
2
] |
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.9;
/* Interface Imports */
import { iOVM_L2ToL1MessagePasser } from "./iOVM_L2ToL1MessagePasser.sol";
/**
* @title OVM_L2ToL1MessagePasser
* @dev The L2 to L1 Message Passer is a utility contract which facilitate an L1 proof of the
* of a message on L2. The L1 Cross Domain Messenger performs this proof in its
* _verifyStorageProof function, which verifies the existence of the transaction hash in this
* contract's `sentMessages` mapping.
*/
contract OVM_L2ToL1MessagePasser is iOVM_L2ToL1MessagePasser {
/**********************
* Contract Variables *
**********************/
mapping(bytes32 => bool) public sentMessages;
/********************
* Public Functions *
********************/
/**
* Passes a message to L1.
* @param _message Message to pass to L1.
*/
function passMessageToL1(bytes memory _message) public {
// Note: although this function is public, only messages sent from the
// L2CrossDomainMessenger will be relayed by the L1CrossDomainMessenger.
// This is enforced by a check in L1CrossDomainMessenger._verifyStorageProof().
sentMessages[keccak256(abi.encodePacked(_message, msg.sender))] = true;
}
}
| * @title OVM_L2ToL1MessagePasser @dev The L2 to L1 Message Passer is a utility contract which facilitate an L1 proof of the of a message on L2. The L1 Cross Domain Messenger performs this proof in its _verifyStorageProof function, which verifies the existence of the transaction hash in this contract's `sentMessages` mapping./ | contract OVM_L2ToL1MessagePasser is iOVM_L2ToL1MessagePasser {
mapping(bytes32 => bool) public sentMessages;
pragma solidity ^0.8.9;
import { iOVM_L2ToL1MessagePasser } from "./iOVM_L2ToL1MessagePasser.sol";
function passMessageToL1(bytes memory _message) public {
sentMessages[keccak256(abi.encodePacked(_message, msg.sender))] = true;
}
}
| 6,346,056 | [
1,
51,
7397,
67,
48,
22,
774,
48,
21,
1079,
6433,
264,
225,
1021,
511,
22,
358,
511,
21,
2350,
10311,
264,
353,
279,
12788,
6835,
1492,
5853,
330,
305,
340,
392,
511,
21,
14601,
434,
326,
434,
279,
883,
603,
511,
22,
18,
1021,
511,
21,
19742,
6648,
490,
18912,
11199,
333,
14601,
316,
2097,
389,
8705,
3245,
20439,
445,
16,
1492,
20761,
326,
15782,
434,
326,
2492,
1651,
316,
333,
6835,
1807,
1375,
7569,
5058,
68,
2874,
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
] | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
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
] | [
1,
16351,
531,
7397,
67,
48,
22,
774,
48,
21,
1079,
6433,
264,
353,
277,
51,
7397,
67,
48,
22,
774,
48,
21,
1079,
6433,
264,
288,
203,
203,
565,
2874,
12,
3890,
1578,
516,
1426,
13,
1071,
3271,
5058,
31,
203,
203,
203,
683,
9454,
18035,
560,
3602,
20,
18,
28,
18,
29,
31,
203,
5666,
288,
277,
51,
7397,
67,
48,
22,
774,
48,
21,
1079,
6433,
264,
289,
628,
25165,
77,
51,
7397,
67,
48,
22,
774,
48,
21,
1079,
6433,
264,
18,
18281,
14432,
203,
565,
445,
1342,
1079,
774,
48,
21,
12,
3890,
3778,
389,
2150,
13,
1071,
288,
203,
3639,
3271,
5058,
63,
79,
24410,
581,
5034,
12,
21457,
18,
3015,
4420,
329,
24899,
2150,
16,
1234,
18,
15330,
3719,
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,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-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/0x479bb758024d768e4153031AC3F8Cd1e458Bd6c2/sources/contracts/OracleAggregator.sol | decimals of inToken decimals of outToken | function _getDecimals(address inToken, address _outToken)
private
view
returns (uint256 inTokenDecimals, uint256 outTokenDecimals)
{
if (inToken != ETH && inToken != USD) {
try ERC20(inToken).decimals() returns (uint8 _inputDecimals) {
inTokenDecimals = uint256(_inputDecimals);
revert("OracleAggregator: ERC20.decimals() revert");
}
if (inToken != ETH) {
inTokenDecimals = _nrOfDecimalsUSD[USD];
inTokenDecimals = 18;
}
}
if (_outToken != ETH && _outToken != USD) {
try ERC20(_outToken).decimals() returns (uint8 _outputDecimals) {
outTokenDecimals = uint256(_outputDecimals);
revert("OracleAggregator: ERC20.decimals() revert");
}
if (_outToken != ETH) {
outTokenDecimals = _nrOfDecimalsUSD[USD];
outTokenDecimals = 18;
}
}
}
| 8,436,446 | [
1,
31734,
434,
316,
1345,
15105,
434,
596,
1345,
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,
225,
445,
389,
588,
31809,
12,
2867,
316,
1345,
16,
1758,
389,
659,
1345,
13,
203,
565,
3238,
203,
565,
1476,
203,
565,
1135,
261,
11890,
5034,
316,
1345,
31809,
16,
2254,
5034,
596,
1345,
31809,
13,
203,
225,
288,
203,
565,
309,
261,
267,
1345,
480,
512,
2455,
597,
316,
1345,
480,
587,
9903,
13,
288,
203,
1377,
775,
4232,
39,
3462,
12,
267,
1345,
2934,
31734,
1435,
1135,
261,
11890,
28,
389,
2630,
31809,
13,
288,
203,
3639,
316,
1345,
31809,
273,
2254,
5034,
24899,
2630,
31809,
1769,
203,
3639,
15226,
2932,
23601,
17711,
30,
4232,
39,
3462,
18,
31734,
1435,
15226,
8863,
203,
1377,
289,
203,
1377,
309,
261,
267,
1345,
480,
512,
2455,
13,
288,
203,
3639,
316,
1345,
31809,
273,
389,
11611,
951,
31809,
3378,
40,
63,
3378,
40,
15533,
203,
3639,
316,
1345,
31809,
273,
6549,
31,
203,
1377,
289,
203,
565,
289,
203,
203,
565,
309,
261,
67,
659,
1345,
480,
512,
2455,
597,
389,
659,
1345,
480,
587,
9903,
13,
288,
203,
1377,
775,
4232,
39,
3462,
24899,
659,
1345,
2934,
31734,
1435,
1135,
261,
11890,
28,
389,
2844,
31809,
13,
288,
203,
3639,
596,
1345,
31809,
273,
2254,
5034,
24899,
2844,
31809,
1769,
203,
3639,
15226,
2932,
23601,
17711,
30,
4232,
39,
3462,
18,
31734,
1435,
15226,
8863,
203,
1377,
289,
203,
1377,
309,
261,
67,
659,
1345,
480,
512,
2455,
13,
288,
203,
3639,
596,
1345,
31809,
273,
389,
11611,
951,
31809,
3378,
40,
63,
3378,
40,
15533,
203,
3639,
596,
1345,
31809,
273,
2
] |
// Sources flattened with hardhat v2.1.2 https://hardhat.org
// File @openzeppelin/contracts/math/[email protected]
// SPDX-License-Identifier: MIT
pragma solidity >=0.6.0 <0.8.0;
/**
* @dev Wrappers over Solidity's arithmetic operations with added overflow
* checks.
*
* Arithmetic operations in Solidity wrap on overflow. This can easily result
* in bugs, because programmers usually assume that an overflow raises an
* error, which is the standard behavior in high level programming languages.
* `SafeMath` restores this intuition by reverting the transaction when an
* operation overflows.
*
* Using this library instead of the unchecked operations eliminates an entire
* class of bugs, so it's recommended to use it always.
*/
library SafeMath {
/**
* @dev Returns the addition of two unsigned integers, 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;
}
}
// File @openzeppelin/contracts/utils/[email protected]
// SPDX-License-Identifier: MIT
pragma solidity >=0.6.0 <0.8.0;
/*
* @dev Provides information about the current execution context, including the
* sender of the transaction and its data. While these are generally available
* via msg.sender and msg.data, they should not be accessed in such a direct
* manner, since when dealing with GSN meta-transactions the account sending and
* paying for execution may not be the actual sender (as far as an application
* is concerned).
*
* This contract is only required for intermediate, library-like contracts.
*/
abstract contract Context {
function _msgSender() internal view virtual returns (address payable) {
return msg.sender;
}
function _msgData() internal view virtual returns (bytes memory) {
this; // silence state mutability warning without generating bytecode - see https://github.com/ethereum/solidity/issues/2691
return msg.data;
}
}
// File @openzeppelin/contracts/access/[email protected]
// SPDX-License-Identifier: MIT
pragma solidity >=0.6.0 <0.8.0;
/**
* @dev Contract module which provides a basic access control mechanism, where
* there is an account (an owner) that can be granted exclusive access to
* specific functions.
*
* By default, the owner account will be the one that deploys the contract. This
* can later be changed with {transferOwnership}.
*
* This module is used through inheritance. It will make available the modifier
* `onlyOwner`, which can be applied to your functions to restrict their use to
* the owner.
*/
abstract contract Ownable is Context {
address private _owner;
event OwnershipTransferred(address indexed previousOwner, address indexed newOwner);
/**
* @dev Initializes the contract setting the deployer as the initial owner.
*/
constructor () internal {
address msgSender = _msgSender();
_owner = msgSender;
emit OwnershipTransferred(address(0), msgSender);
}
/**
* @dev Returns the address of the current owner.
*/
function owner() public view 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;
}
}
// File @openzeppelin/contracts/utils/[email protected]
// SPDX-License-Identifier: MIT
pragma solidity >=0.6.0 <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 `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;
// When the value to delete is the last one, the swap operation is unnecessary. However, since this occurs
// so rarely, we still do the swap anyway to avoid the gas cost of adding an 'if' statement.
bytes32 lastvalue = set._values[lastIndex];
// Move the last value to the index where the value to delete is
set._values[toDeleteIndex] = lastvalue;
// Update the index for the moved value
set._indexes[lastvalue] = toDeleteIndex + 1; // All indexes are 1-based
// Delete the slot where the moved value was stored
set._values.pop();
// Delete the index for the deleted slot
delete set._indexes[value];
return true;
} else {
return false;
}
}
/**
* @dev Returns true if the value is in the set. O(1).
*/
function _contains(Set storage set, bytes32 value) private view returns (bool) {
return set._indexes[value] != 0;
}
/**
* @dev Returns the number of values on the set. O(1).
*/
function _length(Set storage set) private view returns (uint256) {
return set._values.length;
}
/**
* @dev Returns the value stored at position `index` in the set. O(1).
*
* Note that there are no guarantees on the ordering of values inside the
* array, and it may change when more values are added or removed.
*
* Requirements:
*
* - `index` must be strictly less than {length}.
*/
function _at(Set storage set, uint256 index) private view returns (bytes32) {
require(set._values.length > index, "EnumerableSet: index out of bounds");
return set._values[index];
}
// 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);
}
// 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))));
}
// UintSet
struct UintSet {
Set _inner;
}
/**
* @dev Add a value to a set. O(1).
*
* Returns true if the value was added to the set, that is if it was not
* already present.
*/
function add(UintSet storage set, uint256 value) internal returns (bool) {
return _add(set._inner, bytes32(value));
}
/**
* @dev Removes a value from a set. O(1).
*
* Returns true if the value was removed from the set, that is if it was
* present.
*/
function remove(UintSet storage set, uint256 value) internal returns (bool) {
return _remove(set._inner, bytes32(value));
}
/**
* @dev Returns true if the value is in the set. O(1).
*/
function contains(UintSet storage set, uint256 value) internal view returns (bool) {
return _contains(set._inner, bytes32(value));
}
/**
* @dev Returns the number of values on the set. O(1).
*/
function length(UintSet storage set) internal view returns (uint256) {
return _length(set._inner);
}
/**
* @dev Returns the value stored at position `index` in the set. O(1).
*
* Note that there are no guarantees on the ordering of values inside the
* array, and it may change when more values are added or removed.
*
* Requirements:
*
* - `index` must be strictly less than {length}.
*/
function at(UintSet storage set, uint256 index) internal view returns (uint256) {
return uint256(_at(set._inner, index));
}
}
// File @openzeppelin/contracts/utils/[email protected]
// SPDX-License-Identifier: MIT
pragma solidity >=0.6.2 <0.8.0;
/**
* @dev Collection of functions related to the address type
*/
library Address {
/**
* @dev Returns true if `account` is a contract.
*
* [IMPORTANT]
* ====
* It is unsafe to assume that an address for which this function returns
* false is an externally-owned account (EOA) and not a contract.
*
* Among others, `isContract` will return false for the following
* types of addresses:
*
* - an externally-owned account
* - a contract in construction
* - an address where a contract will be created
* - an address where a contract lived, but was destroyed
* ====
*/
function isContract(address account) internal view returns (bool) {
// This method relies on extcodesize, which returns 0 for contracts in
// construction, since the code is only stored at the end of the
// constructor execution.
uint256 size;
// solhint-disable-next-line no-inline-assembly
assembly { size := extcodesize(account) }
return size > 0;
}
/**
* @dev Replacement for Solidity's `transfer`: sends `amount` wei to
* `recipient`, forwarding all available gas and reverting on errors.
*
* https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost
* of certain opcodes, possibly making contracts go over the 2300 gas limit
* imposed by `transfer`, making them unable to receive funds via
* `transfer`. {sendValue} removes this limitation.
*
* https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more].
*
* IMPORTANT: because control is transferred to `recipient`, care must be
* taken to not create reentrancy vulnerabilities. Consider using
* {ReentrancyGuard} or the
* https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern].
*/
function sendValue(address payable recipient, uint256 amount) internal {
require(address(this).balance >= amount, "Address: insufficient balance");
// solhint-disable-next-line avoid-low-level-calls, avoid-call-value
(bool success, ) = recipient.call{ value: amount }("");
require(success, "Address: unable to send value, recipient may have reverted");
}
/**
* @dev Performs a Solidity function call using a low level `call`. A
* plain`call` is an unsafe replacement for a function call: use this
* function instead.
*
* If `target` reverts with a revert reason, it is bubbled up by this
* function (like regular Solidity function calls).
*
* Returns the raw returned data. To convert to the expected return value,
* use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`].
*
* Requirements:
*
* - `target` must be a contract.
* - calling `target` with `data` must not revert.
*
* _Available since v3.1._
*/
function functionCall(address target, bytes memory data) internal returns (bytes memory) {
return functionCall(target, data, "Address: low-level call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with
* `errorMessage` as a fallback revert reason when `target` reverts.
*
* _Available since v3.1._
*/
function functionCall(address target, bytes memory data, string memory errorMessage) internal returns (bytes memory) {
return functionCallWithValue(target, data, 0, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but also transferring `value` wei to `target`.
*
* Requirements:
*
* - the calling contract must have an ETH balance of at least `value`.
* - the called Solidity function must be `payable`.
*
* _Available since v3.1._
*/
function functionCallWithValue(address target, bytes memory data, uint256 value) internal returns (bytes memory) {
return functionCallWithValue(target, data, value, "Address: low-level call with value failed");
}
/**
* @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but
* with `errorMessage` as a fallback revert reason when `target` reverts.
*
* _Available since v3.1._
*/
function functionCallWithValue(address target, bytes memory data, uint256 value, string memory errorMessage) internal returns (bytes memory) {
require(address(this).balance >= value, "Address: insufficient balance for call");
require(isContract(target), "Address: call to non-contract");
// solhint-disable-next-line avoid-low-level-calls
(bool success, bytes memory returndata) = target.call{ value: value }(data);
return _verifyCallResult(success, returndata, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but performing a static call.
*
* _Available since v3.3._
*/
function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) {
return functionStaticCall(target, data, "Address: low-level static call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`],
* but performing a static call.
*
* _Available since v3.3._
*/
function functionStaticCall(address target, bytes memory data, string memory errorMessage) internal view returns (bytes memory) {
require(isContract(target), "Address: static call to non-contract");
// solhint-disable-next-line avoid-low-level-calls
(bool success, bytes memory returndata) = target.staticcall(data);
return _verifyCallResult(success, returndata, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but performing a delegate call.
*
* _Available since v3.4._
*/
function functionDelegateCall(address target, bytes memory data) internal returns (bytes memory) {
return functionDelegateCall(target, data, "Address: low-level delegate call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`],
* but performing a delegate call.
*
* _Available since v3.4._
*/
function functionDelegateCall(address target, bytes memory data, string memory errorMessage) internal returns (bytes memory) {
require(isContract(target), "Address: delegate call to non-contract");
// solhint-disable-next-line avoid-low-level-calls
(bool success, bytes memory returndata) = target.delegatecall(data);
return _verifyCallResult(success, returndata, errorMessage);
}
function _verifyCallResult(bool success, bytes memory returndata, string memory errorMessage) private pure returns(bytes memory) {
if (success) {
return returndata;
} else {
// Look for revert reason and bubble it up if present
if (returndata.length > 0) {
// The easiest way to bubble the revert reason is using memory via assembly
// solhint-disable-next-line no-inline-assembly
assembly {
let returndata_size := mload(returndata)
revert(add(32, returndata), returndata_size)
}
} else {
revert(errorMessage);
}
}
}
}
// File @openzeppelin/contracts/access/[email protected]
// SPDX-License-Identifier: MIT
pragma solidity >=0.6.0 <0.8.0;
/**
* @dev Contract module that allows children to implement role-based access
* control mechanisms.
*
* 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 {
using EnumerableSet for EnumerableSet.AddressSet;
using Address for address;
struct RoleData {
EnumerableSet.AddressSet members;
bytes32 adminRole;
}
mapping (bytes32 => RoleData) private _roles;
bytes32 public constant DEFAULT_ADMIN_ROLE = 0x00;
/**
* @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 {_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) public view returns (bool) {
return _roles[role].members.contains(account);
}
/**
* @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 returns (uint256) {
return _roles[role].members.length();
}
/**
* @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 returns (address) {
return _roles[role].members.at(index);
}
/**
* @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 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 {
require(hasRole(_roles[role].adminRole, _msgSender()), "AccessControl: sender must be an admin to grant");
_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 {
require(hasRole(_roles[role].adminRole, _msgSender()), "AccessControl: sender must be an admin to revoke");
_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 {
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 {
emit RoleAdminChanged(role, _roles[role].adminRole, adminRole);
_roles[role].adminRole = adminRole;
}
function _grantRole(bytes32 role, address account) private {
if (_roles[role].members.add(account)) {
emit RoleGranted(role, account, _msgSender());
}
}
function _revokeRole(bytes32 role, address account) private {
if (_roles[role].members.remove(account)) {
emit RoleRevoked(role, account, _msgSender());
}
}
}
// File @openzeppelin/contracts/token/ERC20/[email protected]
// SPDX-License-Identifier: MIT
pragma solidity >=0.6.0 <0.8.0;
/**
* @dev Interface of the ERC20 standard as defined in the EIP.
*/
interface IERC20 {
/**
* @dev Returns the amount of tokens in existence.
*/
function totalSupply() external view returns (uint256);
/**
* @dev Returns the amount of tokens owned by `account`.
*/
function balanceOf(address account) external view returns (uint256);
/**
* @dev Moves `amount` tokens from the caller's account to `recipient`.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/
function transfer(address recipient, uint256 amount) external returns (bool);
/**
* @dev Returns the remaining number of tokens that `spender` will be
* allowed to spend on behalf of `owner` through {transferFrom}. This is
* zero by default.
*
* This value changes when {approve} or {transferFrom} are called.
*/
function allowance(address owner, address spender) external view returns (uint256);
/**
* @dev Sets `amount` as the allowance of `spender` over the caller's tokens.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* IMPORTANT: Beware that changing an allowance with this method brings the risk
* that someone may use both the old and the new allowance by unfortunate
* transaction ordering. One possible solution to mitigate this race
* condition is to first reduce the spender's allowance to 0 and set the
* desired value afterwards:
* https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729
*
* Emits an {Approval} event.
*/
function approve(address spender, uint256 amount) external returns (bool);
/**
* @dev Moves `amount` tokens from `sender` to `recipient` using the
* allowance mechanism. `amount` is then deducted from the caller's
* allowance.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/
function transferFrom(address sender, address recipient, uint256 amount) external returns (bool);
/**
* @dev Emitted when `value` tokens are moved from one account (`from`) to
* another (`to`).
*
* Note that `value` may be zero.
*/
event Transfer(address indexed from, address indexed to, uint256 value);
/**
* @dev Emitted when the allowance of a `spender` for an `owner` is set by
* a call to {approve}. `value` is the new allowance.
*/
event Approval(address indexed owner, address indexed spender, uint256 value);
}
// File @openzeppelin/contracts/token/ERC20/[email protected]
// SPDX-License-Identifier: MIT
pragma solidity >=0.6.0 <0.8.0;
/**
* @title SafeERC20
* @dev Wrappers around ERC20 operations that throw on failure (when the token
* contract returns false). Tokens that return no value (and instead revert or
* throw on failure) are also supported, non-reverting calls are assumed to be
* successful.
* To use this library you can add a `using SafeERC20 for IERC20;` statement to your contract,
* which allows you to call the safe operations as `token.safeTransfer(...)`, etc.
*/
library SafeERC20 {
using SafeMath for uint256;
using Address for address;
function safeTransfer(IERC20 token, address to, uint256 value) internal {
_callOptionalReturn(token, abi.encodeWithSelector(token.transfer.selector, to, value));
}
function safeTransferFrom(IERC20 token, address from, address to, uint256 value) internal {
_callOptionalReturn(token, abi.encodeWithSelector(token.transferFrom.selector, from, to, value));
}
/**
* @dev Deprecated. This function has issues similar to the ones found in
* {IERC20-approve}, and its usage is discouraged.
*
* Whenever possible, use {safeIncreaseAllowance} and
* {safeDecreaseAllowance} instead.
*/
function safeApprove(IERC20 token, address spender, uint256 value) internal {
// safeApprove should only be called when setting an initial allowance,
// or when resetting it to zero. To increase and decrease it, use
// 'safeIncreaseAllowance' and 'safeDecreaseAllowance'
// solhint-disable-next-line max-line-length
require((value == 0) || (token.allowance(address(this), spender) == 0),
"SafeERC20: approve from non-zero to non-zero allowance"
);
_callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, value));
}
function safeIncreaseAllowance(IERC20 token, address spender, uint256 value) internal {
uint256 newAllowance = token.allowance(address(this), spender).add(value);
_callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance));
}
function safeDecreaseAllowance(IERC20 token, address spender, uint256 value) internal {
uint256 newAllowance = token.allowance(address(this), spender).sub(value, "SafeERC20: decreased allowance below zero");
_callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance));
}
/**
* @dev Imitates a Solidity high-level call (i.e. a regular function call to a contract), relaxing the requirement
* on the return value: the return value is optional (but if data is returned, it must not be false).
* @param token The token targeted by the call.
* @param data The call data (encoded using abi.encode or one of its variants).
*/
function _callOptionalReturn(IERC20 token, bytes memory data) private {
// We need to perform a low level call here, to bypass Solidity's return data size checking mechanism, since
// we're implementing it ourselves. We use {Address.functionCall} to perform this call, which verifies that
// the target address contains contract code and also asserts for success in the low-level call.
bytes memory returndata = address(token).functionCall(data, "SafeERC20: low-level call failed");
if (returndata.length > 0) { // Return data is optional
// solhint-disable-next-line max-line-length
require(abi.decode(returndata, (bool)), "SafeERC20: ERC20 operation did not succeed");
}
}
}
// File @uniswap/v2-core/contracts/interfaces/[email protected]
pragma solidity >=0.5.0;
interface IUniswapV2Pair {
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;
}
// File contracts/oracle/IOracle.sol
/*
Copyright 2020 Cook Finance Devs, based on the works of the Cook Finance Squad
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
pragma solidity ^0.6.2;
pragma experimental ABIEncoderV2;
abstract contract IOracle {
function update() external virtual returns (uint256);
function pairAddress() external view virtual returns (address);
}
// File contracts/oracle/IWETH.sol
pragma solidity ^0.6.2;
abstract contract IWETH {
function deposit() public payable virtual;
}
// File contracts/oracle/IPriceConsumerV3.sol
pragma solidity ^0.6.2;
abstract contract IPriceConsumerV3 {
function getLatestPrice() public view virtual returns (int256);
}
// File contracts/core/IPool.sol
/*
Copyright 2020 Cook Finance Devs, based on the works of the Cook Finance Squad
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
pragma solidity ^0.6.2;
abstract contract IPool {
function stake(uint256 value) external virtual;
function unstake(uint256 value) external virtual;
function harvest(uint256 value) public virtual;
function claim(uint256 value) public virtual;
function zapStake(uint256 value, address userAddress) external virtual;
}
// File contracts/external/UniswapV2Library.sol
pragma solidity >=0.5.0;
library UniswapV2Library {
using SafeMath for uint256;
// 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(
uint256(
keccak256(
abi.encodePacked(
hex"ff",
factory,
keccak256(abi.encodePacked(token0, token1)),
hex"96e8ac4277198ff8b6f785478aa9a39f403cb768dd02cbee326c3e7da348845f" // init code hash
)
)
)
);
}
// fetches and sorts the reserves for a pair
function getReserves(
address factory,
address tokenA,
address tokenB
) internal view returns (uint256 reserveA, uint256 reserveB) {
(address token0, ) = sortTokens(tokenA, tokenB);
(uint256 reserve0, uint256 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(
uint256 amountA,
uint256 reserveA,
uint256 reserveB
) internal pure returns (uint256 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(
uint256 amountIn,
uint256 reserveIn,
uint256 reserveOut
) internal pure returns (uint256 amountOut) {
require(amountIn > 0, "UniswapV2Library: INSUFFICIENT_INPUT_AMOUNT");
require(
reserveIn > 0 && reserveOut > 0,
"UniswapV2Library: INSUFFICIENT_LIQUIDITY"
);
uint256 amountInWithFee = amountIn.mul(997);
uint256 numerator = amountInWithFee.mul(reserveOut);
uint256 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(
uint256 amountOut,
uint256 reserveIn,
uint256 reserveOut
) internal pure returns (uint256 amountIn) {
require(amountOut > 0, "UniswapV2Library: INSUFFICIENT_OUTPUT_AMOUNT");
require(
reserveIn > 0 && reserveOut > 0,
"UniswapV2Library: INSUFFICIENT_LIQUIDITY"
);
uint256 numerator = reserveIn.mul(amountOut).mul(1000);
uint256 denominator = reserveOut.sub(amountOut).mul(997);
amountIn = (numerator / denominator).add(1);
}
// performs chained getAmountOut calculations on any number of pairs
function getAmountsOut(
address factory,
uint256 amountIn,
address[] memory path
) internal view returns (uint256[] memory amounts) {
require(path.length >= 2, "UniswapV2Library: INVALID_PATH");
amounts = new uint256[](path.length);
amounts[0] = amountIn;
for (uint256 i; i < path.length - 1; i++) {
(uint256 reserveIn, uint256 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,
uint256 amountOut,
address[] memory path
) internal view returns (uint256[] memory amounts) {
require(path.length >= 2, "UniswapV2Library: INVALID_PATH");
amounts = new uint256[](path.length);
amounts[amounts.length - 1] = amountOut;
for (uint256 i = path.length - 1; i > 0; i--) {
(uint256 reserveIn, uint256 reserveOut) =
getReserves(factory, path[i - 1], path[i]);
amounts[i - 1] = getAmountIn(amounts[i], reserveIn, reserveOut);
}
}
}
// File contracts/core/CookDistribution.sol
pragma solidity ^0.6.2;
/**
* @title TokenVesting
* @dev A token holder contract that can release its token balance gradually like a
* typical vesting scheme, with a cliff and vesting period.
*/
contract CookDistribution is Ownable, AccessControl {
using SafeMath for uint256;
using SafeERC20 for IERC20;
event AllocationRegistered(address indexed beneficiary, uint256 amount);
event TokensWithdrawal(address userAddress, uint256 amount);
struct Allocation {
uint256 amount;
uint256 released;
bool blackListed;
bool isRegistered;
}
// beneficiary of tokens after they are released
mapping(address => Allocation) private _beneficiaryAllocations;
// oracle price data (dayNumber => price)
mapping(uint256 => uint256) private _oraclePriceFeed;
// all beneficiary address1
address[] private _allBeneficiary;
// vesting start time unix
uint256 public _start;
// vesting duration in day
uint256 public _duration;
// vesting interval
uint32 public _interval;
// released percentage triggered by price, should divided by 100
uint256 public _advancePercentage;
// last released percentage triggered date in dayNumber
uint256 public _lastPriceUnlockDay;
// next step to unlock
uint32 public _nextPriceUnlockStep;
// Max step can be moved
uint32 public _maxPriceUnlockMoveStep;
IERC20 private _token;
IOracle private _oracle;
IPriceConsumerV3 private _priceConsumer;
// Date-related constants for sanity-checking dates to reject obvious erroneous inputs
// SECONDS_PER_DAY = 30 for test only
uint32 private constant SECONDS_PER_DAY = 86400; /* 86400 seconds in a day */
uint256[] private _priceKey;
uint256[] private _percentageValue;
mapping(uint256 => uint256) private _pricePercentageMapping;
// Fields for Admin
// stop everyone from claiming/zapping cook token due to emgergency
bool public _pauseClaim;
bytes32 public constant MANAGER_ROLE = keccak256("MANAGER");
bytes32 public constant ADMIN_ROLE = keccak256("ADMIN");
constructor(
IERC20 token_,
address[] memory beneficiaries_,
uint256[] memory amounts_,
uint256 start, // in unix
uint256 duration, // in day
uint32 interval, // in day
address oracle_,
address priceConsumer_
) public {
// init beneficiaries
for (uint256 i = 0; i < beneficiaries_.length; i++) {
// store all beneficiaries address
_allBeneficiary.push(beneficiaries_[i]);
// Add new allocation to beneficiaryAllocations
_beneficiaryAllocations[beneficiaries_[i]] = Allocation(amounts_[i], 0, false, true);
emit AllocationRegistered(beneficiaries_[i], amounts_[i]);
}
_token = token_;
_duration = duration;
_start = start;
_interval = interval;
// init release percentage is 1%
_advancePercentage = 1;
_oracle = IOracle(oracle_);
_priceConsumer = IPriceConsumerV3(priceConsumer_);
_lastPriceUnlockDay = 0;
_nextPriceUnlockStep = 0;
_maxPriceUnlockMoveStep = 1;
_pauseClaim = false;
// init price percentage
_priceKey = [500000, 800000, 1100000, 1400000, 1700000, 2000000, 2300000, 2600000, 2900000, 3200000, 3500000, 3800000, 4100000,
4400000, 4700000, 5000000, 5300000, 5600000, 5900000, 6200000, 6500000];
_percentageValue = [1, 5, 10, 15, 20, 25, 30, 35, 40, 45, 50, 55, 60, 65, 70, 75, 80, 85, 90, 95, 100];
for (uint256 i = 0; i < _priceKey.length; i++) {
_pricePercentageMapping[_priceKey[i]] = _percentageValue[i];
}
// Make the deployer defaul admin role and manager role
_setupRole(MANAGER_ROLE, msg.sender);
_setupRole(ADMIN_ROLE, msg.sender);
_setRoleAdmin(MANAGER_ROLE, ADMIN_ROLE);
}
fallback() external payable {
revert();
}
function setStart(uint256 start) public {
require(hasRole(MANAGER_ROLE, msg.sender), "only manager");
_start = start;
}
function setDuration(uint256 duration) public {
require(hasRole(MANAGER_ROLE, msg.sender), "only manager");
_duration = duration;
}
function setInvertal(uint32 interval) public {
require(hasRole(MANAGER_ROLE, msg.sender), "only manager");
_interval = interval;
}
function setAdvancePercentage(uint256 advancePercentage) public {
require(hasRole(MANAGER_ROLE, msg.sender), "only manager");
_advancePercentage = advancePercentage;
}
function getRegisteredStatus(address userAddress) public view returns (bool) {
return _beneficiaryAllocations[userAddress].isRegistered;
}
function getUserVestingAmount(address userAddress) public view returns (uint256) {
return _beneficiaryAllocations[userAddress].amount;
}
function getUserAvailableAmount(address userAddress, uint256 onDayOrToday) public view returns (uint256) {
uint256 avalible = _getVestedAmount(userAddress, onDayOrToday).sub(_beneficiaryAllocations[userAddress].released);
return avalible;
}
function getUserVestedAmount(address userAddress, uint256 onDayOrToday)
public
view
returns (uint256 amountVested)
{
return _getVestedAmount(userAddress, onDayOrToday);
}
/**
* @dev returns the day number of the current day, in days since the UNIX epoch.
*/
function today() public view virtual returns (uint256 dayNumber) {
return uint256(block.timestamp / SECONDS_PER_DAY);
}
function startDay() public view returns (uint256) {
return uint256(_start / SECONDS_PER_DAY);
}
function _effectiveDay(uint256 onDayOrToday) public view returns (uint256) {
return onDayOrToday == 0 ? today() : onDayOrToday;
}
function _getVestedAmount(address userAddress, uint256 onDayOrToday) internal view returns (uint256) {
uint256 onDay = _effectiveDay(onDayOrToday); // day
// If after end of vesting, then the vested amount is total amount.
if (onDay >= (startDay() + _duration)) {
return _beneficiaryAllocations[userAddress].amount;
}
// If it's before the vesting then the vested amount is zero.
else if (onDay < startDay()) {
// All are vested (none are not vested)
return 0;
}
// Otherwise a fractional amount is vested.
else {
// Compute the exact number of days vested.
uint256 daysVested = onDay - startDay();
// Adjust result rounding down to take into consideration the interval.
uint256 effectiveDaysVested = (daysVested / _interval) * _interval;
uint256 vested = 0;
if (
_beneficiaryAllocations[userAddress]
.amount
.mul(effectiveDaysVested)
.div(_duration) >
_beneficiaryAllocations[userAddress]
.amount
.mul(_advancePercentage)
.div(100)
) {
// no price based percentage > date based percentage
vested = _beneficiaryAllocations[userAddress]
.amount
.mul(effectiveDaysVested)
.div(_duration);
} else {
// price based percentage > date based percentage
vested = _beneficiaryAllocations[userAddress]
.amount
.mul(_advancePercentage)
.div(100);
}
return vested;
}
}
/**
withdraw function
*/
function withdraw(uint256 withdrawAmount) public {
address userAddress = msg.sender;
require(_beneficiaryAllocations[userAddress].blackListed == false, "You're blacklisted.");
require(_pauseClaim == false, "Not claimable due to emgergency");
require(getUserAvailableAmount(userAddress, today()) >= withdrawAmount, "insufficient avalible cook balance");
_beneficiaryAllocations[userAddress].released = _beneficiaryAllocations[userAddress].released.add(withdrawAmount);
_token.safeTransfer(userAddress, withdrawAmount);
emit TokensWithdrawal(userAddress, withdrawAmount);
}
function _calWethAmountToPairCook(uint256 cookAmount) internal returns (uint256, address) {
// get pair address
IUniswapV2Pair lpPair = IUniswapV2Pair(_oracle.pairAddress());
uint256 reserve0;
uint256 reserve1;
address weth;
if (lpPair.token0() == address(_token)) {
(reserve0, reserve1, ) = lpPair.getReserves();
weth = lpPair.token1();
} else {
(reserve1, reserve0, ) = lpPair.getReserves();
weth = lpPair.token0();
}
uint256 wethAmount =
(reserve0 == 0 && reserve1 == 0)
? cookAmount
: UniswapV2Library.quote(cookAmount, reserve0, reserve1);
return (wethAmount, weth);
}
function zapLP(uint256 cookAmount, address poolAddress) external {
_zapLP(cookAmount, poolAddress, false);
}
function _zapLP(uint256 cookAmount, address poolAddress, bool isWithEth) internal {
address userAddress = msg.sender;
_checkValidZap(userAddress, cookAmount);
uint256 newUniv2 = 0;
(, newUniv2) = addLiquidity(cookAmount);
IERC20(_oracle.pairAddress()).approve(poolAddress, newUniv2);
IPool(poolAddress).zapStake(newUniv2, userAddress);
}
function _checkValidZap(address userAddress, uint256 cookAmount) internal {
require(_beneficiaryAllocations[userAddress].isRegistered == true, "Only registered address.");
require(_beneficiaryAllocations[userAddress].blackListed == false, "You're blacklisted.");
require(_pauseClaim == false, "Cook token can not be zap.");
require(cookAmount > 0, "zero zap amount");
require(getUserAvailableAmount(userAddress, today()) >= cookAmount, "insufficient avalible cook balance");
_beneficiaryAllocations[userAddress].released = _beneficiaryAllocations[userAddress].released.add(cookAmount);
}
function addLiquidity(uint256 cookAmount) internal returns (uint256, uint256) {
// get pair address
(uint256 wethAmount, ) = _calWethAmountToPairCook(cookAmount);
_token.safeTransfer(_oracle.pairAddress(), cookAmount);
IUniswapV2Pair lpPair = IUniswapV2Pair(_oracle.pairAddress());
if (lpPair.token0() == address(_token)) {
// token0 == cook, token1 == weth
require(IERC20(lpPair.token1()).balanceOf(msg.sender) >= wethAmount, "insufficient weth balance");
require(IERC20(lpPair.token1()).allowance(msg.sender, address(this)) >= wethAmount, "insufficient weth allowance");
IERC20(lpPair.token1()).safeTransferFrom(
msg.sender,
_oracle.pairAddress(),
wethAmount
);
} else if (lpPair.token1() == address(_token)) {
// token0 == weth, token1 == cook
require(IERC20(lpPair.token0()).balanceOf(msg.sender) >= wethAmount, "insufficient weth balance");
require(IERC20(lpPair.token0()).allowance(msg.sender, address(this)) >= wethAmount, "insufficient weth allowance");
IERC20(lpPair.token0()).safeTransferFrom(msg.sender, _oracle.pairAddress(), wethAmount);
}
return (wethAmount, lpPair.mint(address(this)));
}
// Zap into Cook staking pool functions
function zapCook(uint256 cookAmount, address cookPoolAddress) external {
address userAddress = msg.sender;
_checkValidZap(userAddress, cookAmount);
IERC20(address(_token)).approve(cookPoolAddress, cookAmount);
IPool(cookPoolAddress).zapStake(cookAmount, userAddress);
}
// Admin Functions
function setPriceBasedMaxStep(uint32 newMaxPriceBasedStep) public {
require(hasRole(MANAGER_ROLE, msg.sender), "only manager");
_maxPriceUnlockMoveStep = newMaxPriceBasedStep;
}
/**
* add adddress with allocation
*/
function addAddressWithAllocation(address beneficiaryAddress, uint256 amount, uint256 release) public {
require(hasRole(MANAGER_ROLE, msg.sender), "only manager");
require(_beneficiaryAllocations[beneficiaryAddress].isRegistered == false, "The address exisits.");
_beneficiaryAllocations[beneficiaryAddress].isRegistered = true;
_beneficiaryAllocations[beneficiaryAddress] = Allocation( amount, release, false, true
);
emit AllocationRegistered(beneficiaryAddress, amount);
}
/**
* Add multiple address with multiple allocations
*/
function addMultipleAddressWithAllocations(address[] memory beneficiaryAddresses, uint256[] memory amounts, uint256[] memory releases) public {
require(hasRole(MANAGER_ROLE, msg.sender), "only manager");
require(beneficiaryAddresses.length > 0 && amounts.length > 0 && beneficiaryAddresses.length == amounts.length, "Inconsistent length input");
for (uint256 i = 0; i < beneficiaryAddresses.length; i++) {
require(_beneficiaryAllocations[beneficiaryAddresses[i]].isRegistered == false, "The address exisits.");
_beneficiaryAllocations[beneficiaryAddresses[i]].isRegistered = true;
_beneficiaryAllocations[beneficiaryAddresses[i]] = Allocation(amounts[i], releases[i], false, true);
emit AllocationRegistered(beneficiaryAddresses[i], amounts[i]);
}
}
function getTotalAvailable() public view returns (uint256) {uint256 totalAvailable = 0;
require(hasRole(MANAGER_ROLE, msg.sender), "only manager");
for (uint256 i = 0; i < _allBeneficiary.length; ++i) {
totalAvailable += getUserAvailableAmount(_allBeneficiary[i], today());
}
return totalAvailable;
}
function getLatestSevenSMA() public view returns (uint256) {
// 7 day sma
uint256 priceSum = uint256(0);
uint256 priceCount = uint256(0);
for (uint32 i = 0; i < 7; ++i) {
if (_oraclePriceFeed[today() - i] != 0) {
priceSum = priceSum + _oraclePriceFeed[today() - i];
priceCount += 1;
}
}
uint256 sevenSMA = 0;
if (priceCount == 7) {
sevenSMA = priceSum.div(priceCount);
}
return sevenSMA;
}
function updatePriceFeed() public {
require(hasRole(MANAGER_ROLE, msg.sender), "only manager");
// oracle capture -> 900000000000000000 -> 1 cook = 0.9 ETH
uint256 cookPrice = _oracle.update();
// ETH/USD capture -> 127164849196 -> 1ETH = 1271.64USD
uint256 ethPrice = uint256(_priceConsumer.getLatestPrice());
uint256 price = cookPrice.mul(ethPrice).div(10**18);
// update price to _oraclePriceFeed
_oraclePriceFeed[today()] = price;
if (today() >= _lastPriceUnlockDay.add(7)) {
// 7 day sma
uint256 sevenSMA = getLatestSevenSMA();
uint256 priceRef = 0;
for (uint32 i = 0; i < _priceKey.length; ++i) {
if (sevenSMA >= _priceKey[i]) {
priceRef = _pricePercentageMapping[_priceKey[i]];
}
}
// no lower action if the price drop after price-based unlock
if (priceRef > _advancePercentage) {
// guard _nextPriceUnlockStep exceed
if (_nextPriceUnlockStep >= _percentageValue.length) {
_nextPriceUnlockStep = uint32(_percentageValue.length - 1);
}
// update _advancePercentage to nextStep percentage
_advancePercentage = _pricePercentageMapping[
_priceKey[_nextPriceUnlockStep]
];
// update nextStep value
_nextPriceUnlockStep =
_nextPriceUnlockStep +
_maxPriceUnlockMoveStep;
// update lastUnlcokDay
_lastPriceUnlockDay = today();
}
}
}
// Put an evil address into blacklist
function blacklistAddress(address userAddress) public {
require(hasRole(MANAGER_ROLE, msg.sender), "only manager");
_beneficiaryAllocations[userAddress].blackListed = true;
}
//Remove an address from blacklist
function removeAddressFromBlacklist(address userAddress) public {
require(hasRole(MANAGER_ROLE, msg.sender), "only manager");
_beneficiaryAllocations[userAddress].blackListed = false;
}
// Pause all claim due to emergency
function pauseClaim() public {
require(hasRole(MANAGER_ROLE, msg.sender), "only manager");
_pauseClaim = true;
}
// resume cliamable
function resumeCliam() public {
require(hasRole(MANAGER_ROLE, msg.sender), "only manager");
_pauseClaim = false;
}
// admin emergency to transfer token to owner
function emergencyWithdraw(uint256 amount) public onlyOwner {
_token.safeTransfer(msg.sender, amount);
}
function getManagerRole() public returns (bytes32) {
return MANAGER_ROLE;
}
} | admin emergency to transfer token to owner | function emergencyWithdraw(uint256 amount) public onlyOwner {
_token.safeTransfer(msg.sender, amount);
}
| 438,707 | [
1,
3666,
801,
24530,
358,
7412,
1147,
358,
3410,
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,
801,
24530,
1190,
9446,
12,
11890,
5034,
3844,
13,
1071,
1338,
5541,
288,
203,
3639,
389,
2316,
18,
4626,
5912,
12,
3576,
18,
15330,
16,
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,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
] |
// File: contracts/vendor/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) {
require(b <= a, "SafeMath: subtraction overflow");
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-solidity/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) {
// Solidity only automatically asserts when dividing by 0
require(b > 0, "SafeMath: division by zero");
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) {
require(b != 0, "SafeMath: modulo by zero");
return a % b;
}
}
// File: contracts/interfaces/LinkTokenInterface.sol
pragma solidity ^0.6.0;
interface LinkTokenInterface {
function allowance(address owner, address spender) external view returns (uint256 remaining);
function approve(address spender, uint256 value) external returns (bool success);
function balanceOf(address owner) external view returns (uint256 balance);
function decimals() external view returns (uint8 decimalPlaces);
function decreaseApproval(address spender, uint256 addedValue) external returns (bool success);
function increaseApproval(address spender, uint256 subtractedValue) external;
function name() external view returns (string memory tokenName);
function symbol() external view returns (string memory tokenSymbol);
function totalSupply() external view returns (uint256 totalTokensIssued);
function transfer(address to, uint256 value) external returns (bool success);
function transferAndCall(address to, uint256 value, bytes calldata data) external returns (bool success);
function transferFrom(address from, address to, uint256 value) external returns (bool success);
}
// File: contracts/interfaces/BlockHashStoreInterface.sol
pragma solidity 0.6.6;
interface BlockHashStoreInterface {
function getBlockhash(uint256 number) external view returns (bytes32);
}
// File: contracts/VRF.sol
pragma solidity 0.6.6;
/** ****************************************************************************
* @notice Verification of verifiable-random-function (VRF) proofs, following
* @notice https://datatracker.ietf.org/doc/html/draft-irtf-cfrg-vrf-05#section-5.3
* @notice See https://eprint.iacr.org/2017/099.pdf for security proofs.
* @dev Bibliographic references:
* @dev Goldberg, et al., "Verifiable Random Functions (VRFs)", Internet Draft
* @dev draft-irtf-cfrg-vrf-05, IETF, Aug 11 2019,
* @dev https://datatracker.ietf.org/doc/html/draft-irtf-cfrg-vrf-05
* @dev Papadopoulos, et al., "Making NSEC5 Practical for DNSSEC", Cryptology
* @dev ePrint Archive, Report 2017/099, https://eprint.iacr.org/2017/099.pdf
* ****************************************************************************
* @dev USAGE
* @dev The main entry point is randomValueFromVRFProof. See its docstring.
* ****************************************************************************
* @dev PURPOSE
* @dev Reggie the Random Oracle (not his real job) wants to provide randomness
* @dev to Vera the verifier in such a way that Vera can be sure he's not
* @dev making his output up to suit himself. Reggie provides Vera a public key
* @dev to which he knows the secret key. Each time Vera provides a seed to
* @dev Reggie, he gives back a value which is computed completely
* @dev deterministically from the seed and the secret key.
* @dev Reggie provides a proof by which Vera can verify that the output was
* @dev correctly computed once Reggie tells it to her, but without that proof,
* @dev the output is computationally indistinguishable to her from a uniform
* @dev random sample from the output space.
* @dev The purpose of this contract is to perform that verification.
* ****************************************************************************
* @dev DESIGN NOTES
* @dev The VRF algorithm verified here satisfies the full unqiqueness, full
* @dev collision resistance, and full pseudorandomness security properties.
* @dev See "SECURITY PROPERTIES" below, and
* @dev https://datatracker.ietf.org/doc/html/draft-irtf-cfrg-vrf-05#section-3
* @dev An elliptic curve point is generally represented in the solidity code
* @dev as a uint256[2], corresponding to its affine coordinates in
* @dev GF(FIELD_SIZE).
* @dev For the sake of efficiency, this implementation deviates from the spec
* @dev in some minor ways:
* @dev - Keccak hash rather than the SHA256 hash recommended in
* @dev https://datatracker.ietf.org/doc/html/draft-irtf-cfrg-vrf-05#section-5.5
* @dev Keccak costs much less gas on the EVM, and provides similar security.
* @dev - Secp256k1 curve instead of the P-256 or ED25519 curves recommended in
* @dev https://datatracker.ietf.org/doc/html/draft-irtf-cfrg-vrf-05#section-5.5
* @dev For curve-point multiplication, it's much cheaper to abuse ECRECOVER
* @dev - hashToCurve recursively hashes until it finds a curve x-ordinate. On
* @dev the EVM, this is slightly more efficient than the recommendation in
* @dev https://datatracker.ietf.org/doc/html/draft-irtf-cfrg-vrf-05#section-5.4.1.1
* @dev step 5, to concatenate with a nonce then hash, and rehash with the
* @dev nonce updated until a valid x-ordinate is found.
* @dev - hashToCurve does not include a cipher version string or the byte 0x1
* @dev in the hash message, as recommended in step 5.B of the draft
* @dev standard. They are unnecessary here because no variation in the
* @dev cipher suite is allowed.
* @dev - Similarly, the hash input in scalarFromCurvePoints does not include a
* @dev commitment to the cipher suite, either, which differs from step 2 of
* @dev https://datatracker.ietf.org/doc/html/draft-irtf-cfrg-vrf-05#section-5.4.3
* @dev . Also, the hash input is the concatenation of the uncompressed
* @dev points, not the compressed points as recommended in step 3.
* @dev - In the calculation of the challenge value "c", the "u" value (i.e.
* @dev the value computed by Reggie as the nonce times the secp256k1
* @dev generator point, see steps 5 and 7 of
* @dev https://datatracker.ietf.org/doc/html/draft-irtf-cfrg-vrf-05#section-5.3
* @dev ) is replaced by its ethereum address, i.e. the lower 160 bits of the
* @dev keccak hash of the original u. This is because we only verify the
* @dev calculation of u up to its address, by abusing ECRECOVER.
* ****************************************************************************
* @dev SECURITY PROPERTIES
* @dev Here are the security properties for this VRF:
* @dev Full uniqueness: For any seed and valid VRF public key, there is
* @dev exactly one VRF output which can be proved to come from that seed, in
* @dev the sense that the proof will pass verifyVRFProof.
* @dev Full collision resistance: It's cryptographically infeasible to find
* @dev two seeds with same VRF output from a fixed, valid VRF key
* @dev Full pseudorandomness: Absent the proofs that the VRF outputs are
* @dev derived from a given seed, the outputs are computationally
* @dev indistinguishable from randomness.
* @dev https://eprint.iacr.org/2017/099.pdf, Appendix B contains the proofs
* @dev for these properties.
* @dev For secp256k1, the key validation described in section
* @dev https://datatracker.ietf.org/doc/html/draft-irtf-cfrg-vrf-05#section-5.6
* @dev is unnecessary, because secp256k1 has cofactor 1, and the
* @dev representation of the public key used here (affine x- and y-ordinates
* @dev of the secp256k1 point on the standard y^2=x^3+7 curve) cannot refer to
* @dev the point at infinity.
* ****************************************************************************
* @dev OTHER SECURITY CONSIDERATIONS
*
* @dev The seed input to the VRF could in principle force an arbitrary amount
* @dev of work in hashToCurve, by requiring extra rounds of hashing and
* @dev checking whether that's yielded the x ordinate of a secp256k1 point.
* @dev However, under the Random Oracle Model the probability of choosing a
* @dev point which forces n extra rounds in hashToCurve is 2⁻ⁿ. The base cost
* @dev for calling hashToCurve is about 25,000 gas, and each round of checking
* @dev for a valid x ordinate costs about 15,555 gas, so to find a seed for
* @dev which hashToCurve would cost more than 2,017,000 gas, one would have to
* @dev try, in expectation, about 2¹²⁸ seeds, which is infeasible for any
* @dev foreseeable computational resources. (25,000 + 128 * 15,555 < 2,017,000.)
* @dev Since the gas block limit for the Ethereum main net is 10,000,000 gas,
* @dev this means it is infeasible for an adversary to prevent correct
* @dev operation of this contract by choosing an adverse seed.
* @dev (See TestMeasureHashToCurveGasCost for verification of the gas cost for
* @dev hashToCurve.)
* @dev It may be possible to make a secure constant-time hashToCurve function.
* @dev See notes in hashToCurve docstring.
*/
contract VRF {
// See https://www.secg.org/sec2-v2.pdf, section 2.4.1, for these constants.
uint256 constant private GROUP_ORDER = // Number of points in Secp256k1
// solium-disable-next-line indentation
0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFEBAAEDCE6AF48A03BBFD25E8CD0364141;
// Prime characteristic of the galois field over which Secp256k1 is defined
uint256 constant private FIELD_SIZE =
// solium-disable-next-line indentation
0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFEFFFFFC2F;
uint256 constant private WORD_LENGTH_BYTES = 0x20;
// (base^exponent) % FIELD_SIZE
// Cribbed from https://medium.com/@rbkhmrcr/precompiles-solidity-e5d29bd428c4
function bigModExp(uint256 base, uint256 exponent)
internal view returns (uint256 exponentiation) {
uint256 callResult;
uint256[6] memory bigModExpContractInputs;
bigModExpContractInputs[0] = WORD_LENGTH_BYTES; // Length of base
bigModExpContractInputs[1] = WORD_LENGTH_BYTES; // Length of exponent
bigModExpContractInputs[2] = WORD_LENGTH_BYTES; // Length of modulus
bigModExpContractInputs[3] = base;
bigModExpContractInputs[4] = exponent;
bigModExpContractInputs[5] = FIELD_SIZE;
uint256[1] memory output;
assembly { // solhint-disable-line no-inline-assembly
callResult := staticcall(
not(0), // Gas cost: no limit
0x05, // Bigmodexp contract address
bigModExpContractInputs,
0xc0, // Length of input segment: 6*0x20-bytes
output,
0x20 // Length of output segment
)
}
if (callResult == 0) {revert("bigModExp failure!");}
return output[0];
}
// Let q=FIELD_SIZE. q % 4 = 3, ∴ x≡r^2 mod q ⇒ x^SQRT_POWER≡±r mod q. See
// https://en.wikipedia.org/wiki/Modular_square_root#Prime_or_prime_power_modulus
uint256 constant private SQRT_POWER = (FIELD_SIZE + 1) >> 2;
// Computes a s.t. a^2 = x in the field. Assumes a exists
function squareRoot(uint256 x) internal view returns (uint256) {
return bigModExp(x, SQRT_POWER);
}
// The value of y^2 given that (x,y) is on secp256k1.
function ySquared(uint256 x) internal pure returns (uint256) {
// Curve is y^2=x^3+7. See section 2.4.1 of https://www.secg.org/sec2-v2.pdf
uint256 xCubed = mulmod(x, mulmod(x, x, FIELD_SIZE), FIELD_SIZE);
return addmod(xCubed, 7, FIELD_SIZE);
}
// True iff p is on secp256k1
function isOnCurve(uint256[2] memory p) internal pure returns (bool) {
return ySquared(p[0]) == mulmod(p[1], p[1], FIELD_SIZE);
}
// Hash x uniformly into {0, ..., FIELD_SIZE-1}.
function fieldHash(bytes memory b) internal pure returns (uint256 x_) {
x_ = uint256(keccak256(b));
// Rejecting if x >= FIELD_SIZE corresponds to step 2.1 in section 2.3.4 of
// http://www.secg.org/sec1-v2.pdf , which is part of the definition of
// string_to_point in the IETF draft
while (x_ >= FIELD_SIZE) {
x_ = uint256(keccak256(abi.encodePacked(x_)));
}
}
// Hash b to a random point which hopefully lies on secp256k1. The y ordinate
// is always even, due to
// https://datatracker.ietf.org/doc/html/draft-irtf-cfrg-vrf-05#section-5.4.1.1
// step 5.C, which references arbitrary_string_to_point, defined in
// https://datatracker.ietf.org/doc/html/draft-irtf-cfrg-vrf-05#section-5.5 as
// returning the point with given x ordinate, and even y ordinate.
function newCandidateSecp256k1Point(bytes memory b)
internal view returns (uint256[2] memory p) {
p[0] = fieldHash(b);
p[1] = squareRoot(ySquared(p[0]));
if (p[1] % 2 == 1) {
p[1] = FIELD_SIZE - p[1];
}
}
// Domain-separation tag for initial hash in hashToCurve. Corresponds to
// vrf.go/hashToCurveHashPrefix
uint256 constant HASH_TO_CURVE_HASH_PREFIX = 1;
// Cryptographic hash function onto the curve.
//
// Corresponds to algorithm in section 5.4.1.1 of the draft standard. (But see
// DESIGN NOTES above for slight differences.)
//
// TODO(alx): Implement a bounded-computation hash-to-curve, as described in
// "Construction of Rational Points on Elliptic Curves over Finite Fields"
// http://citeseerx.ist.psu.edu/viewdoc/download?doi=10.1.1.831.5299&rep=rep1&type=pdf
// and suggested by
// https://datatracker.ietf.org/doc/html/draft-irtf-cfrg-hash-to-curve-01#section-5.2.2
// (Though we can't used exactly that because secp256k1's j-invariant is 0.)
//
// This would greatly simplify the analysis in "OTHER SECURITY CONSIDERATIONS"
// https://www.pivotaltracker.com/story/show/171120900
function hashToCurve(uint256[2] memory pk, uint256 input)
internal view returns (uint256[2] memory rv) {
rv = newCandidateSecp256k1Point(abi.encodePacked(HASH_TO_CURVE_HASH_PREFIX,
pk, input));
while (!isOnCurve(rv)) {
rv = newCandidateSecp256k1Point(abi.encodePacked(rv[0]));
}
}
/** *********************************************************************
* @notice Check that product==scalar*multiplicand
*
* @dev Based on Vitalik Buterin's idea in ethresear.ch post cited below.
*
* @param multiplicand: secp256k1 point
* @param scalar: non-zero GF(GROUP_ORDER) scalar
* @param product: secp256k1 expected to be multiplier * multiplicand
* @return verifies true iff product==scalar*multiplicand, with cryptographically high probability
*/
function ecmulVerify(uint256[2] memory multiplicand, uint256 scalar,
uint256[2] memory product) internal pure returns(bool verifies)
{
require(scalar != 0); // Rules out an ecrecover failure case
uint256 x = multiplicand[0]; // x ordinate of multiplicand
uint8 v = multiplicand[1] % 2 == 0 ? 27 : 28; // parity of y ordinate
// https://ethresear.ch/t/you-can-kinda-abuse-ecrecover-to-do-ecmul-in-secp256k1-today/2384/9
// Point corresponding to address ecrecover(0, v, x, s=scalar*x) is
// (x⁻¹ mod GROUP_ORDER) * (scalar * x * multiplicand - 0 * g), i.e.
// scalar*multiplicand. See https://crypto.stackexchange.com/a/18106
bytes32 scalarTimesX = bytes32(mulmod(scalar, x, GROUP_ORDER));
address actual = ecrecover(bytes32(0), v, bytes32(x), scalarTimesX);
// Explicit conversion to address takes bottom 160 bits
address expected = address(uint256(keccak256(abi.encodePacked(product))));
return (actual == expected);
}
// Returns x1/z1-x2/z2=(x1z2-x2z1)/(z1z2) in projective coordinates on P¹(𝔽ₙ)
function projectiveSub(uint256 x1, uint256 z1, uint256 x2, uint256 z2)
internal pure returns(uint256 x3, uint256 z3) {
uint256 num1 = mulmod(z2, x1, FIELD_SIZE);
uint256 num2 = mulmod(FIELD_SIZE - x2, z1, FIELD_SIZE);
(x3, z3) = (addmod(num1, num2, FIELD_SIZE), mulmod(z1, z2, FIELD_SIZE));
}
// Returns x1/z1*x2/z2=(x1x2)/(z1z2), in projective coordinates on P¹(𝔽ₙ)
function projectiveMul(uint256 x1, uint256 z1, uint256 x2, uint256 z2)
internal pure returns(uint256 x3, uint256 z3) {
(x3, z3) = (mulmod(x1, x2, FIELD_SIZE), mulmod(z1, z2, FIELD_SIZE));
}
/** **************************************************************************
@notice Computes elliptic-curve sum, in projective co-ordinates
@dev Using projective coordinates avoids costly divisions
@dev To use this with p and q in affine coordinates, call
@dev projectiveECAdd(px, py, qx, qy). This will return
@dev the addition of (px, py, 1) and (qx, qy, 1), in the
@dev secp256k1 group.
@dev This can be used to calculate the z which is the inverse to zInv
@dev in isValidVRFOutput. But consider using a faster
@dev re-implementation such as ProjectiveECAdd in the golang vrf package.
@dev This function assumes [px,py,1],[qx,qy,1] are valid projective
coordinates of secp256k1 points. That is safe in this contract,
because this method is only used by linearCombination, which checks
points are on the curve via ecrecover.
**************************************************************************
@param px The first affine coordinate of the first summand
@param py The second affine coordinate of the first summand
@param qx The first affine coordinate of the second summand
@param qy The second affine coordinate of the second summand
(px,py) and (qx,qy) must be distinct, valid secp256k1 points.
**************************************************************************
Return values are projective coordinates of [px,py,1]+[qx,qy,1] as points
on secp256k1, in P²(𝔽ₙ)
@return sx
@return sy
@return sz
*/
function projectiveECAdd(uint256 px, uint256 py, uint256 qx, uint256 qy)
internal pure returns(uint256 sx, uint256 sy, uint256 sz) {
// See "Group law for E/K : y^2 = x^3 + ax + b", in section 3.1.2, p. 80,
// "Guide to Elliptic Curve Cryptography" by Hankerson, Menezes and Vanstone
// We take the equations there for (sx,sy), and homogenize them to
// projective coordinates. That way, no inverses are required, here, and we
// only need the one inverse in affineECAdd.
// We only need the "point addition" equations from Hankerson et al. Can
// skip the "point doubling" equations because p1 == p2 is cryptographically
// impossible, and require'd not to be the case in linearCombination.
// Add extra "projective coordinate" to the two points
(uint256 z1, uint256 z2) = (1, 1);
// (lx, lz) = (qy-py)/(qx-px), i.e., gradient of secant line.
uint256 lx = addmod(qy, FIELD_SIZE - py, FIELD_SIZE);
uint256 lz = addmod(qx, FIELD_SIZE - px, FIELD_SIZE);
uint256 dx; // Accumulates denominator from sx calculation
// sx=((qy-py)/(qx-px))^2-px-qx
(sx, dx) = projectiveMul(lx, lz, lx, lz); // ((qy-py)/(qx-px))^2
(sx, dx) = projectiveSub(sx, dx, px, z1); // ((qy-py)/(qx-px))^2-px
(sx, dx) = projectiveSub(sx, dx, qx, z2); // ((qy-py)/(qx-px))^2-px-qx
uint256 dy; // Accumulates denominator from sy calculation
// sy=((qy-py)/(qx-px))(px-sx)-py
(sy, dy) = projectiveSub(px, z1, sx, dx); // px-sx
(sy, dy) = projectiveMul(sy, dy, lx, lz); // ((qy-py)/(qx-px))(px-sx)
(sy, dy) = projectiveSub(sy, dy, py, z1); // ((qy-py)/(qx-px))(px-sx)-py
if (dx != dy) { // Cross-multiply to put everything over a common denominator
sx = mulmod(sx, dy, FIELD_SIZE);
sy = mulmod(sy, dx, FIELD_SIZE);
sz = mulmod(dx, dy, FIELD_SIZE);
} else { // Already over a common denominator, use that for z ordinate
sz = dx;
}
}
// p1+p2, as affine points on secp256k1.
//
// invZ must be the inverse of the z returned by projectiveECAdd(p1, p2).
// It is computed off-chain to save gas.
//
// p1 and p2 must be distinct, because projectiveECAdd doesn't handle
// point doubling.
function affineECAdd(
uint256[2] memory p1, uint256[2] memory p2,
uint256 invZ) internal pure returns (uint256[2] memory) {
uint256 x;
uint256 y;
uint256 z;
(x, y, z) = projectiveECAdd(p1[0], p1[1], p2[0], p2[1]);
require(mulmod(z, invZ, FIELD_SIZE) == 1, "invZ must be inverse of z");
// Clear the z ordinate of the projective representation by dividing through
// by it, to obtain the affine representation
return [mulmod(x, invZ, FIELD_SIZE), mulmod(y, invZ, FIELD_SIZE)];
}
// True iff address(c*p+s*g) == lcWitness, where g is generator. (With
// cryptographically high probability.)
function verifyLinearCombinationWithGenerator(
uint256 c, uint256[2] memory p, uint256 s, address lcWitness)
internal pure returns (bool) {
// Rule out ecrecover failure modes which return address 0.
require(lcWitness != address(0), "bad witness");
uint8 v = (p[1] % 2 == 0) ? 27 : 28; // parity of y-ordinate of p
bytes32 pseudoHash = bytes32(GROUP_ORDER - mulmod(p[0], s, GROUP_ORDER)); // -s*p[0]
bytes32 pseudoSignature = bytes32(mulmod(c, p[0], GROUP_ORDER)); // c*p[0]
// https://ethresear.ch/t/you-can-kinda-abuse-ecrecover-to-do-ecmul-in-secp256k1-today/2384/9
// The point corresponding to the address returned by
// ecrecover(-s*p[0],v,p[0],c*p[0]) is
// (p[0]⁻¹ mod GROUP_ORDER)*(c*p[0]-(-s)*p[0]*g)=c*p+s*g.
// See https://crypto.stackexchange.com/a/18106
// https://bitcoin.stackexchange.com/questions/38351/ecdsa-v-r-s-what-is-v
address computed = ecrecover(pseudoHash, v, bytes32(p[0]), pseudoSignature);
return computed == lcWitness;
}
// c*p1 + s*p2. Requires cp1Witness=c*p1 and sp2Witness=s*p2. Also
// requires cp1Witness != sp2Witness (which is fine for this application,
// since it is cryptographically impossible for them to be equal. In the
// (cryptographically impossible) case that a prover accidentally derives
// a proof with equal c*p1 and s*p2, they should retry with a different
// proof nonce.) Assumes that all points are on secp256k1
// (which is checked in verifyVRFProof below.)
function linearCombination(
uint256 c, uint256[2] memory p1, uint256[2] memory cp1Witness,
uint256 s, uint256[2] memory p2, uint256[2] memory sp2Witness,
uint256 zInv)
internal pure returns (uint256[2] memory) {
require((cp1Witness[0] - sp2Witness[0]) % FIELD_SIZE != 0,
"points in sum must be distinct");
require(ecmulVerify(p1, c, cp1Witness), "First multiplication check failed");
require(ecmulVerify(p2, s, sp2Witness), "Second multiplication check failed");
return affineECAdd(cp1Witness, sp2Witness, zInv);
}
// Domain-separation tag for the hash taken in scalarFromCurvePoints.
// Corresponds to scalarFromCurveHashPrefix in vrf.go
uint256 constant SCALAR_FROM_CURVE_POINTS_HASH_PREFIX = 2;
// Pseudo-random number from inputs. Matches vrf.go/scalarFromCurvePoints, and
// https://datatracker.ietf.org/doc/html/draft-irtf-cfrg-vrf-05#section-5.4.3
// The draft calls (in step 7, via the definition of string_to_int, in
// https://datatracker.ietf.org/doc/html/rfc8017#section-4.2 ) for taking the
// first hash without checking that it corresponds to a number less than the
// group order, which will lead to a slight bias in the sample.
//
// TODO(alx): We could save a bit of gas by following the standard here and
// using the compressed representation of the points, if we collated the y
// parities into a single bytes32.
// https://www.pivotaltracker.com/story/show/171120588
function scalarFromCurvePoints(
uint256[2] memory hash, uint256[2] memory pk, uint256[2] memory gamma,
address uWitness, uint256[2] memory v)
internal pure returns (uint256 s) {
return uint256(
keccak256(abi.encodePacked(SCALAR_FROM_CURVE_POINTS_HASH_PREFIX,
hash, pk, gamma, v, uWitness)));
}
// True if (gamma, c, s) is a correctly constructed randomness proof from pk
// and seed. zInv must be the inverse of the third ordinate from
// projectiveECAdd applied to cGammaWitness and sHashWitness. Corresponds to
// section 5.3 of the IETF draft.
//
// TODO(alx): Since I'm only using pk in the ecrecover call, I could only pass
// the x ordinate, and the parity of the y ordinate in the top bit of uWitness
// (which I could make a uint256 without using any extra space.) Would save
// about 2000 gas. https://www.pivotaltracker.com/story/show/170828567
function verifyVRFProof(
uint256[2] memory pk, uint256[2] memory gamma, uint256 c, uint256 s,
uint256 seed, address uWitness, uint256[2] memory cGammaWitness,
uint256[2] memory sHashWitness, uint256 zInv)
internal view {
require(isOnCurve(pk), "public key is not on curve");
require(isOnCurve(gamma), "gamma is not on curve");
require(isOnCurve(cGammaWitness), "cGammaWitness is not on curve");
require(isOnCurve(sHashWitness), "sHashWitness is not on curve");
// Step 5. of IETF draft section 5.3 (pk corresponds to 5.3's Y, and here
// we use the address of u instead of u itself. Also, here we add the
// terms instead of taking the difference, and in the proof consruction in
// vrf.GenerateProof, we correspondingly take the difference instead of
// taking the sum as they do in step 7 of section 5.1.)
require(
verifyLinearCombinationWithGenerator(c, pk, s, uWitness),
"addr(c*pk+s*g)≠_uWitness"
);
// Step 4. of IETF draft section 5.3 (pk corresponds to Y, seed to alpha_string)
uint256[2] memory hash = hashToCurve(pk, seed);
// Step 6. of IETF draft section 5.3, but see note for step 5 about +/- terms
uint256[2] memory v = linearCombination(
c, gamma, cGammaWitness, s, hash, sHashWitness, zInv);
// Steps 7. and 8. of IETF draft section 5.3
uint256 derivedC = scalarFromCurvePoints(hash, pk, gamma, uWitness, v);
require(c == derivedC, "invalid proof");
}
// Domain-separation tag for the hash used as the final VRF output.
// Corresponds to vrfRandomOutputHashPrefix in vrf.go
uint256 constant VRF_RANDOM_OUTPUT_HASH_PREFIX = 3;
// Length of proof marshaled to bytes array. Shows layout of proof
uint public constant PROOF_LENGTH = 64 + // PublicKey (uncompressed format.)
64 + // Gamma
32 + // C
32 + // S
32 + // Seed
0 + // Dummy entry: The following elements are included for gas efficiency:
32 + // uWitness (gets padded to 256 bits, even though it's only 160)
64 + // cGammaWitness
64 + // sHashWitness
32; // zInv (Leave Output out, because that can be efficiently calculated)
/* ***************************************************************************
* @notice Returns proof's output, if proof is valid. Otherwise reverts
* @param proof A binary-encoded proof, as output by vrf.Proof.MarshalForSolidityVerifier
*
* Throws if proof is invalid, otherwise:
* @return output i.e., the random output implied by the proof
* ***************************************************************************
* @dev See the calculation of PROOF_LENGTH for the binary layout of proof.
*/
function randomValueFromVRFProof(bytes memory proof)
internal view returns (uint256 output) {
require(proof.length == PROOF_LENGTH, "wrong proof length");
uint256[2] memory pk; // parse proof contents into these variables
uint256[2] memory gamma;
// c, s and seed combined (prevents "stack too deep" compilation error)
uint256[3] memory cSSeed;
address uWitness;
uint256[2] memory cGammaWitness;
uint256[2] memory sHashWitness;
uint256 zInv;
(pk, gamma, cSSeed, uWitness, cGammaWitness, sHashWitness, zInv) = abi.decode(
proof, (uint256[2], uint256[2], uint256[3], address, uint256[2],
uint256[2], uint256));
verifyVRFProof(
pk,
gamma,
cSSeed[0], // c
cSSeed[1], // s
cSSeed[2], // seed
uWitness,
cGammaWitness,
sHashWitness,
zInv
);
output = uint256(keccak256(abi.encode(VRF_RANDOM_OUTPUT_HASH_PREFIX, gamma)));
}
}
// File: contracts/VRFRequestIDBase.sol
pragma solidity ^0.6.0;
contract VRFRequestIDBase {
/**
* @notice returns the seed which is actually input to the VRF coordinator
*
* @dev To prevent repetition of VRF output due to repetition of the
* @dev user-supplied seed, that seed is combined in a hash with the
* @dev user-specific nonce, and the address of the consuming contract. The
* @dev risk of repetition is mostly mitigated by inclusion of a blockhash in
* @dev the final seed, but the nonce does protect against repetition in
* @dev requests which are included in a single block.
*
* @param _userSeed VRF seed input provided by user
* @param _requester Address of the requesting contract
* @param _nonce User-specific nonce at the time of the request
*/
function makeVRFInputSeed(bytes32 _keyHash, uint256 _userSeed,
address _requester, uint256 _nonce)
internal pure returns (uint256)
{
return uint256(keccak256(abi.encode(_keyHash, _userSeed, _requester, _nonce)));
}
/**
* @notice Returns the id for this request
* @param _keyHash The serviceAgreement ID to be used for this request
* @param _vRFInputSeed The seed to be passed directly to the VRF
* @return The id for this request
*
* @dev Note that _vRFInputSeed is not the seed passed by the consuming
* @dev contract, but the one generated by makeVRFInputSeed
*/
function makeRequestId(
bytes32 _keyHash, uint256 _vRFInputSeed) internal pure returns (bytes32) {
return keccak256(abi.encodePacked(_keyHash, _vRFInputSeed));
}
}
// File: contracts/VRFConsumerBase.sol
pragma solidity ^0.6.0;
/** ****************************************************************************
* @notice Interface for contracts using VRF randomness
* *****************************************************************************
* @dev PURPOSE
*
* @dev Reggie the Random Oracle (not his real job) wants to provide randomness
* @dev to Vera the verifier in such a way that Vera can be sure he's not
* @dev making his output up to suit himself. Reggie provides Vera a public key
* @dev to which he knows the secret key. Each time Vera provides a seed to
* @dev Reggie, he gives back a value which is computed completely
* @dev deterministically from the seed and the secret key.
*
* @dev Reggie provides a proof by which Vera can verify that the output was
* @dev correctly computed once Reggie tells it to her, but without that proof,
* @dev the output is indistinguishable to her from a uniform random sample
* @dev from the output space.
*
* @dev The purpose of this contract is to make it easy for unrelated contracts
* @dev to talk to Vera the verifier about the work Reggie is doing, to provide
* @dev simple access to a verifiable source of randomness.
* *****************************************************************************
* @dev USAGE
*
* @dev Calling contracts must inherit from VRFConsumerInterface, and can
* @dev initialize VRFConsumerInterface's attributes in their constructor as
* @dev shown:
*
* @dev contract VRFConsumer {
* @dev constuctor(<other arguments>, address _vrfCoordinator, address _link)
* @dev VRFConsumerBase(_vrfCoordinator, _link) public {
* @dev <initialization with other arguments goes here>
* @dev }
* @dev }
*
* @dev The oracle will have given you an ID for the VRF keypair they have
* @dev committed to (let's call it keyHash), and have told you the minimum LINK
* @dev price for VRF service. Make sure your contract has sufficient LINK, and
* @dev call requestRandomness(keyHash, fee, seed), where seed is the input you
* @dev want to generate randomness from.
*
* @dev Once the VRFCoordinator has received and validated the oracle's response
* @dev to your request, it will call your contract's fulfillRandomness method.
*
* @dev The randomness argument to fulfillRandomness is the actual random value
* @dev generated from your seed.
*
* @dev The requestId argument is generated from the keyHash and the seed by
* @dev makeRequestId(keyHash, seed). If your contract could have concurrent
* @dev requests open, you can use the requestId to track which seed is
* @dev associated with which randomness. See VRFRequestIDBase.sol for more
* @dev details.
*
* @dev Colliding `requestId`s are cryptographically impossible as long as seeds
* @dev differ. (Which is critical to making unpredictable randomness! See the
* @dev next section.)
*
* *****************************************************************************
* @dev SECURITY CONSIDERATIONS
*
* @dev Since the ultimate input to the VRF is mixed with the block hash of the
* @dev block in which the request is made, user-provided seeds have no impact
* @dev on its economic security properties. They are only included for API
* @dev compatability with previous versions of this contract.
*
* @dev Since the block hash of the block which contains the requestRandomness()
* @dev call is mixed into the input to the VRF *last*, a sufficiently powerful
* @dev miner could, in principle, fork the blockchain to evict the block
* @dev containing the request, forcing the request to be included in a
* @dev different block with a different hash, and therefore a different input
* @dev to the VRF. However, such an attack would incur a substantial economic
* @dev cost. This cost scales with the number of blocks the VRF oracle waits
* @dev until it calls fulfillRandomness().
*/
abstract contract VRFConsumerBase is VRFRequestIDBase {
using SafeMath for uint256;
/**
* @notice fulfillRandomness handles the VRF response. Your contract must
* @notice implement it.
*
* @dev The VRFCoordinator expects a calling contract to have a method with
* @dev this signature, and will trigger it once it has verified the proof
* @dev associated with the randomness (It is triggered via a call to
* @dev rawFulfillRandomness, below.)
*
* @param requestId The Id initially returned by requestRandomness
* @param randomness the VRF output
*/
function fulfillRandomness(bytes32 requestId, uint256 randomness)
internal virtual;
/**
* @notice requestRandomness initiates a request for VRF output given _seed
*
* @dev See "SECURITY CONSIDERATIONS" above for more information on _seed.
*
* @dev The fulfillRandomness method receives the output, once it's provided
* @dev by the Oracle, and verified by the vrfCoordinator.
*
* @dev The _keyHash must already be registered with the VRFCoordinator, and
* @dev the _fee must exceed the fee specified during registration of the
* @dev _keyHash.
*
* @param _keyHash ID of public key against which randomness is generated
* @param _fee The amount of LINK to send with the request
* @param _seed seed mixed into the input of the VRF
*
* @return requestId unique ID for this request
*
* @dev The returned requestId can be used to distinguish responses to *
* @dev concurrent requests. It is passed as the first argument to
* @dev fulfillRandomness.
*/
function requestRandomness(bytes32 _keyHash, uint256 _fee, uint256 _seed)
public returns (bytes32 requestId)
{
LINK.transferAndCall(vrfCoordinator, _fee, abi.encode(_keyHash, _seed));
// This is the seed passed to VRFCoordinator. The oracle will mix this with
// the hash of the block containing this request to obtain the seed/input
// which is finally passed to the VRF cryptographic machinery.
uint256 vRFSeed = makeVRFInputSeed(_keyHash, _seed, address(this), nonces[_keyHash]);
// nonces[_keyHash] must stay in sync with
// VRFCoordinator.nonces[_keyHash][this], which was incremented by the above
// successful LINK.transferAndCall (in VRFCoordinator.randomnessRequest).
// This provides protection against the user repeating their input
// seed, which would result in a predictable/duplicate output.
nonces[_keyHash] = nonces[_keyHash].add(1);
return makeRequestId(_keyHash, vRFSeed);
}
LinkTokenInterface immutable internal LINK;
address immutable private vrfCoordinator;
// Nonces for each VRF key from which randomness has been requested.
//
// Must stay in sync with VRFCoordinator[_keyHash][this]
mapping(bytes32 /* keyHash */ => uint256 /* nonce */) public nonces;
constructor(address _vrfCoordinator, address _link) public {
vrfCoordinator = _vrfCoordinator;
LINK = LinkTokenInterface(_link);
}
// rawFulfillRandomness is called by VRFCoordinator when it receives a valid VRF
// proof. rawFulfillRandomness then calls fulfillRandomness, after validating
// the origin of the call
function rawFulfillRandomness(bytes32 requestId, uint256 randomness) external {
require(msg.sender == vrfCoordinator, "Only VRFCoordinator can fulfill");
fulfillRandomness(requestId, randomness);
}
}
// File: contracts/VRFCoordinator.sol
pragma solidity 0.6.6;
/**
* @title VRFCoordinator coordinates on-chain verifiable-randomness requests
* @title with off-chain responses
*/
contract VRFCoordinator is VRF, VRFRequestIDBase {
using SafeMath for uint256;
LinkTokenInterface internal LINK;
BlockHashStoreInterface internal blockHashStore;
constructor(address _link, address _blockHashStore) public {
LINK = LinkTokenInterface(_link);
blockHashStore = BlockHashStoreInterface(_blockHashStore);
}
struct Callback { // Tracks an ongoing request
address callbackContract; // Requesting contract, which will receive response
// Amount of LINK paid at request time. Total LINK = 1e9 * 1e18 < 2^96, so
// this representation is adequate, and saves a word of storage when this
// field follows the 160-bit callbackContract address.
uint96 randomnessFee;
// Commitment to seed passed to oracle by this contract, and the number of
// the block in which the request appeared. This is the keccak256 of the
// concatenation of those values. Storing this commitment saves a word of
// storage.
bytes32 seedAndBlockNum;
}
struct ServiceAgreement { // Tracks oracle commitments to VRF service
address vRFOracle; // Oracle committing to respond with VRF service
uint96 fee; // Minimum payment for oracle response. Total LINK=1e9*1e18<2^96
bytes32 jobID; // ID of corresponding chainlink job in oracle's DB
}
mapping(bytes32 /* (provingKey, seed) */ => Callback) public callbacks;
mapping(bytes32 /* provingKey */ => ServiceAgreement)
public serviceAgreements;
mapping(address /* oracle */ => uint256 /* LINK balance */)
public withdrawableTokens;
mapping(bytes32 /* provingKey */ => mapping(address /* consumer */ => uint256))
private nonces;
// The oracle only needs the jobID to look up the VRF, but specifying public
// key as well prevents a malicious oracle from inducing VRF outputs from
// another oracle by reusing the jobID.
event RandomnessRequest(
bytes32 keyHash,
uint256 seed,
bytes32 indexed jobID,
address sender,
uint256 fee,
bytes32 requestID);
event NewServiceAgreement(bytes32 keyHash, uint256 fee);
event RandomnessRequestFulfilled(bytes32 requestId, uint256 output);
/**
* @notice Commits calling address to serve randomness
* @param _fee minimum LINK payment required to serve randomness
* @param _oracle the address of the Chainlink node with the proving key and job
* @param _publicProvingKey public key used to prove randomness
* @param _jobID ID of the corresponding chainlink job in the oracle's db
*/
function registerProvingKey(
uint256 _fee, address _oracle, uint256[2] calldata _publicProvingKey, bytes32 _jobID
)
external
{
bytes32 keyHash = hashOfKey(_publicProvingKey);
address oldVRFOracle = serviceAgreements[keyHash].vRFOracle;
require(oldVRFOracle == address(0), "please register a new key");
require(_oracle != address(0), "_oracle must not be 0x0");
serviceAgreements[keyHash].vRFOracle = _oracle;
serviceAgreements[keyHash].jobID = _jobID;
// Yes, this revert message doesn't fit in a word
require(_fee <= 1e9 ether,
"you can't charge more than all the LINK in the world, greedy");
serviceAgreements[keyHash].fee = uint96(_fee);
emit NewServiceAgreement(keyHash, _fee);
}
/**
* @notice Called by LINK.transferAndCall, on successful LINK transfer
*
* @dev To invoke this, use the requestRandomness method in VRFConsumerBase.
*
* @dev The VRFCoordinator will call back to the calling contract when the
* @dev oracle responds, on the method fulfillRandomness. See
* @dev VRFConsumerBase.fulfilRandomness for its signature. Your consuming
* @dev contract should inherit from VRFConsumerBase, and implement
* @dev fulfilRandomness.
*
* @param _sender address: who sent the LINK (must be a contract)
* @param _fee amount of LINK sent
* @param _data abi-encoded call to randomnessRequest
*/
function onTokenTransfer(address _sender, uint256 _fee, bytes memory _data)
public
onlyLINK
{
(bytes32 keyHash, uint256 seed) = abi.decode(_data, (bytes32, uint256));
randomnessRequest(keyHash, seed, _fee, _sender);
}
/**
* @notice creates the chainlink request for randomness
*
* @param _keyHash ID of the VRF public key against which to generate output
* @param _consumerSeed Input to the VRF, from which randomness is generated
* @param _feePaid Amount of LINK sent with request. Must exceed fee for key
* @param _sender Requesting contract; to be called back with VRF output
*
* @dev _consumerSeed is mixed with key hash, sender address and nonce to
* @dev obtain preSeed, which is passed to VRF oracle, which mixes it with the
* @dev hash of the block containing this request, to compute the final seed.
*
* @dev The requestId used to store the request data is constructed from the
* @dev preSeed and keyHash.
*/
function randomnessRequest(
bytes32 _keyHash,
uint256 _consumerSeed,
uint256 _feePaid,
address _sender
)
internal
sufficientLINK(_feePaid, _keyHash)
{
uint256 nonce = nonces[_keyHash][_sender];
uint256 preSeed = makeVRFInputSeed(_keyHash, _consumerSeed, _sender, nonce);
bytes32 requestId = makeRequestId(_keyHash, preSeed);
// Cryptographically guaranteed by preSeed including an increasing nonce
assert(callbacks[requestId].callbackContract == address(0));
callbacks[requestId].callbackContract = _sender;
assert(_feePaid < 1e27); // Total LINK fits in uint96
callbacks[requestId].randomnessFee = uint96(_feePaid);
callbacks[requestId].seedAndBlockNum = keccak256(abi.encodePacked(
preSeed, block.number));
emit RandomnessRequest(_keyHash, preSeed, serviceAgreements[_keyHash].jobID,
_sender, _feePaid, requestId);
nonces[_keyHash][_sender] = nonces[_keyHash][_sender].add(1);
}
// Offsets into fulfillRandomnessRequest's _proof of various values
//
// Public key. Skips byte array's length prefix.
uint256 public constant PUBLIC_KEY_OFFSET = 0x20;
// Seed is 7th word in proof, plus word for length, (6+1)*0x20=0xe0
uint256 public constant PRESEED_OFFSET = 0xe0;
/**
* @notice Called by the chainlink node to fulfill requests
*
* @param _proof the proof of randomness. Actual random output built from this
*
* @dev The structure of _proof corresponds to vrf.MarshaledOnChainResponse,
* @dev in the node source code. I.e., it is a vrf.MarshaledProof with the
* @dev seed replaced by the preSeed, followed by the hash of the requesting
* @dev block.
*/
function fulfillRandomnessRequest(bytes memory _proof) public {
(bytes32 currentKeyHash, Callback memory callback, bytes32 requestId,
uint256 randomness) = getRandomnessFromProof(_proof);
// Pay oracle
address oadd = serviceAgreements[currentKeyHash].vRFOracle;
withdrawableTokens[oadd] = withdrawableTokens[oadd].add(
callback.randomnessFee);
// Forget request. Must precede callback (prevents reentrancy)
delete callbacks[requestId];
callBackWithRandomness(requestId, randomness, callback.callbackContract);
emit RandomnessRequestFulfilled(requestId, randomness);
}
function callBackWithRandomness(bytes32 requestId, uint256 randomness,
address consumerContract) internal {
// Dummy variable; allows access to method selector in next line. See
// https://github.com/ethereum/solidity/issues/3506#issuecomment-553727797
VRFConsumerBase v;
bytes memory resp = abi.encodeWithSelector(
v.rawFulfillRandomness.selector, requestId, randomness);
// The bound b here comes from https://eips.ethereum.org/EIPS/eip-150. The
// actual gas available to the consuming contract will be b-floor(b/64).
// This is chosen to leave the consuming contract ~200k gas, after the cost
// of the call itself.
uint256 b = 206000;
require(gasleft() >= b, "not enough gas for consumer");
// A low-level call is necessary, here, because we don't want the consuming
// contract to be able to revert this execution, and thus deny the oracle
// payment for a valid randomness response. This also necessitates the above
// check on the gasleft, as otherwise there would be no indication if the
// callback method ran out of gas.
//
// solhint-disable-next-line avoid-low-level-calls
(bool success,) = consumerContract.call(resp);
// Avoid unused-local-variable warning. (success is only present to prevent
// a warning that the return value of consumerContract.call is unused.)
(success);
}
function getRandomnessFromProof(bytes memory _proof)
internal view returns (bytes32 currentKeyHash, Callback memory callback,
bytes32 requestId, uint256 randomness) {
// blockNum follows proof, which follows length word (only direct-number
// constants are allowed in assembly, so have to compute this in code)
uint256 BLOCKNUM_OFFSET = 0x20 + PROOF_LENGTH;
// _proof.length skips the initial length word, so not including the
// blocknum in this length check balances out.
require(_proof.length == BLOCKNUM_OFFSET, "wrong proof length");
uint256[2] memory publicKey;
uint256 preSeed;
uint256 blockNum;
assembly { // solhint-disable-line no-inline-assembly
publicKey := add(_proof, PUBLIC_KEY_OFFSET)
preSeed := mload(add(_proof, PRESEED_OFFSET))
blockNum := mload(add(_proof, BLOCKNUM_OFFSET))
}
currentKeyHash = hashOfKey(publicKey);
requestId = makeRequestId(currentKeyHash, preSeed);
callback = callbacks[requestId];
require(callback.callbackContract != address(0), "no corresponding request");
require(callback.seedAndBlockNum == keccak256(abi.encodePacked(preSeed,
blockNum)), "wrong preSeed or block num");
bytes32 blockHash = blockhash(blockNum);
if (blockHash == bytes32(0)) {
blockHash = blockHashStore.getBlockhash(blockNum);
require(blockHash != bytes32(0), "please prove blockhash");
}
// The seed actually used by the VRF machinery, mixing in the blockhash
uint256 actualSeed = uint256(keccak256(abi.encodePacked(preSeed, blockHash)));
// solhint-disable-next-line no-inline-assembly
assembly { // Construct the actual proof from the remains of _proof
mstore(add(_proof, PRESEED_OFFSET), actualSeed)
mstore(_proof, PROOF_LENGTH)
}
randomness = VRF.randomValueFromVRFProof(_proof); // Reverts on failure
}
/**
* @dev Allows the oracle operator to withdraw their LINK
* @param _recipient is the address the funds will be sent to
* @param _amount is the amount of LINK transferred from the Coordinator contract
*/
function withdraw(address _recipient, uint256 _amount)
external
hasAvailableFunds(_amount)
{
withdrawableTokens[msg.sender] = withdrawableTokens[msg.sender].sub(_amount);
assert(LINK.transfer(_recipient, _amount));
}
/**
* @notice Returns the serviceAgreements key associated with this public key
* @param _publicKey the key to return the address for
*/
function hashOfKey(uint256[2] memory _publicKey) public pure returns (bytes32) {
return keccak256(abi.encodePacked(_publicKey));
}
/**
* @dev Reverts if amount is not at least what was agreed upon in the service agreement
* @param _feePaid The payment for the request
* @param _keyHash The key which the request is for
*/
modifier sufficientLINK(uint256 _feePaid, bytes32 _keyHash) {
require(_feePaid >= serviceAgreements[_keyHash].fee, "Below agreed payment");
_;
}
/**
* @dev Reverts if not sent from the LINK token
*/
modifier onlyLINK() {
require(msg.sender == address(LINK), "Must use LINK token");
_;
}
/**
* @dev Reverts if amount requested is greater than withdrawable balance
* @param _amount The given amount to compare to `withdrawableTokens`
*/
modifier hasAvailableFunds(uint256 _amount) {
require(withdrawableTokens[msg.sender] >= _amount, "can't withdraw more than balance");
_;
}
} | Hash b to a random point which hopefully lies on secp256k1. The y ordinate is always even, due to https:datatracker.ietf.org/doc/html/draft-irtf-cfrg-vrf-05#section-5.4.1.1 step 5.C, which references arbitrary_string_to_point, defined in https:datatracker.ietf.org/doc/html/draft-irtf-cfrg-vrf-05#section-5.5 as returning the point with given x ordinate, and even y ordinate. | internal view returns (uint256[2] memory p) {
p[0] = fieldHash(b);
p[1] = squareRoot(ySquared(p[0]));
function newCandidateSecp256k1Point(bytes memory b)
if (p[1] % 2 == 1) {
p[1] = FIELD_SIZE - p[1];
}
}
| 1,168,906 | [
1,
2310,
324,
358,
279,
2744,
1634,
1492,
27370,
4095,
328,
606,
603,
1428,
84,
5034,
79,
21,
18,
1021,
677,
4642,
3322,
353,
3712,
5456,
16,
6541,
358,
2333,
30,
3404,
270,
21580,
264,
18,
18508,
18,
3341,
19,
2434,
19,
2620,
19,
17153,
17,
2714,
74,
17,
71,
4840,
75,
17,
16825,
17,
6260,
3464,
17,
25,
18,
24,
18,
21,
18,
21,
2235,
1381,
18,
39,
16,
1492,
5351,
11078,
67,
1080,
67,
869,
67,
1153,
16,
2553,
316,
2333,
30,
3404,
270,
21580,
264,
18,
18508,
18,
3341,
19,
2434,
19,
2620,
19,
17153,
17,
2714,
74,
17,
71,
4840,
75,
17,
16825,
17,
6260,
3464,
17,
25,
18,
25,
487,
5785,
326,
1634,
598,
864,
619,
4642,
3322,
16,
471,
5456,
677,
4642,
3322,
18,
2,
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,
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
] | [
1,
565,
2713,
1476,
1135,
261,
11890,
5034,
63,
22,
65,
3778,
293,
13,
288,
203,
1377,
293,
63,
20,
65,
273,
652,
2310,
12,
70,
1769,
203,
1377,
293,
63,
21,
65,
273,
8576,
2375,
12,
93,
20888,
12,
84,
63,
20,
5717,
1769,
203,
225,
445,
394,
11910,
2194,
84,
5034,
79,
21,
2148,
12,
3890,
3778,
324,
13,
203,
1377,
309,
261,
84,
63,
21,
65,
738,
576,
422,
404,
13,
288,
203,
3639,
293,
63,
21,
65,
273,
9921,
67,
4574,
300,
293,
63,
21,
15533,
203,
1377,
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,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-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.6.5;
import "./Assert.sol";
import "./CallForwarder.sol";
import "../contracts/BNS.sol";
import "../contracts/DriveFactory.sol";
import "../contracts/Drive.sol";
contract TestDrive is Drive {
BNS bns_addr;
constructor(BNS _bns) Drive() public { bns_addr = _bns; }
function bns() internal override view returns (IBNS) { return bns_addr; }
}
contract TestDrive2 is TestDrive {
constructor(BNS _bns) TestDrive(_bns) public {}
function Version() external override pure returns (int256) { return 200; }
}
contract Dummy {
}
contract DriveFactoryTest {
BNS bns;
TestDrive version1;
TestDrive version2;
address number1;
DriveFactory factory;
constructor() public {
version1 = new TestDrive(bns);
version2 = new TestDrive2(bns);
factory = new DriveFactory();
number1 = address(new Dummy());
}
function checkCreate2() public {
bytes32 salt = hex"0011001100110011001100110011001100110011001100110011001100110011";
address should = factory.Create2Address(salt);
address raw = factory.Create(payable(address(this)), salt, address(version1));
Assert.notEqual(raw, address(0), "Create2() should not return 0");
Assert.equal(raw, should, "Create2() and Create2Address() should return the same address");
Drive drive = Drive(raw);
drive.AddMember(number1, RoleType.Admin);
// Factory created contract should work normally
Assert.equal(drive.Version(), 133, "Version() should be equal 133");
acceptanceTest(drive);
// Upgrade
factory.Upgrade(salt, address(version2));
// and test again
Assert.equal(drive.Version(), 200, "Version() should be equal 200");
acceptanceTest(drive);
}
function acceptanceTest(Drive drive) internal {
Assert.equal(address(this), drive.owner(), "address(this) should be owner");
Assert.ok(drive.Role(address(this)) == RoleType.Owner, "address(this) should be RoleType.Owner");
drive.AddMember(number1, RoleType.Admin);
address[] memory members = drive.Members();
Assert.equal(members.length, 1, "Members() should return one member");
Assert.equal(members[0], number1, "Members() should return [number1]");
}
}
| Factory created contract should work normally Upgrade and test again | function checkCreate2() public {
bytes32 salt = hex"0011001100110011001100110011001100110011001100110011001100110011";
address should = factory.Create2Address(salt);
address raw = factory.Create(payable(address(this)), salt, address(version1));
Assert.notEqual(raw, address(0), "Create2() should not return 0");
Assert.equal(raw, should, "Create2() and Create2Address() should return the same address");
Drive drive = Drive(raw);
drive.AddMember(number1, RoleType.Admin);
Assert.equal(drive.Version(), 133, "Version() should be equal 133");
acceptanceTest(drive);
factory.Upgrade(salt, address(version2));
Assert.equal(drive.Version(), 200, "Version() should be equal 200");
acceptanceTest(drive);
}
| 15,858,203 | [
1,
1733,
2522,
6835,
1410,
1440,
15849,
17699,
471,
1842,
3382,
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,
866,
1684,
22,
1435,
1071,
288,
203,
3639,
1731,
1578,
4286,
273,
3827,
6,
713,
2499,
713,
2499,
713,
2499,
713,
2499,
713,
2499,
713,
2499,
713,
2499,
713,
2499,
713,
2499,
713,
2499,
713,
2499,
713,
2499,
713,
2499,
713,
2499,
713,
2499,
713,
2499,
14432,
203,
3639,
1758,
1410,
273,
3272,
18,
1684,
22,
1887,
12,
5759,
1769,
203,
3639,
1758,
1831,
273,
3272,
18,
1684,
12,
10239,
429,
12,
2867,
12,
2211,
13,
3631,
4286,
16,
1758,
12,
1589,
21,
10019,
203,
203,
3639,
5452,
18,
902,
5812,
12,
1899,
16,
1758,
12,
20,
3631,
315,
1684,
22,
1435,
1410,
486,
327,
374,
8863,
203,
3639,
5452,
18,
9729,
12,
1899,
16,
1410,
16,
315,
1684,
22,
1435,
471,
1788,
22,
1887,
1435,
1410,
327,
326,
1967,
1758,
8863,
203,
203,
3639,
11473,
688,
14316,
273,
11473,
688,
12,
1899,
1769,
203,
203,
3639,
14316,
18,
986,
4419,
12,
2696,
21,
16,
6204,
559,
18,
4446,
1769,
203,
203,
3639,
5452,
18,
9729,
12,
25431,
18,
1444,
9334,
30537,
16,
315,
1444,
1435,
1410,
506,
3959,
30537,
8863,
203,
3639,
21656,
4709,
12,
25431,
1769,
203,
203,
3639,
3272,
18,
10784,
12,
5759,
16,
1758,
12,
1589,
22,
10019,
203,
540,
203,
3639,
5452,
18,
9729,
12,
25431,
18,
1444,
9334,
4044,
16,
315,
1444,
1435,
1410,
506,
3959,
4044,
8863,
203,
3639,
21656,
4709,
12,
25431,
1769,
203,
565,
289,
203,
203,
2,
-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;
// Implementation of a Constant Product Automated Market Maker
// Other liquidiuty pool contracts: https://github.com/search?p=2&q=liquidity+pool+contract&type=Repositories
// https://github.com/OCTIONOFFICIAL/liquiditypoolV2
contract LiquidityPool {
uint private k = 2500000000;
uint public equityToken501c = 500000;
uint public investorCash = 500000;
uint public parValue = 10;
address private owner;
uint constant private fee_pct = 1;
uint private total_fees = 0;
struct Transaction {
uint256 time;
address sender;
uint amount;
uint fee;
}
mapping(uint => Transaction[]) private transactions;
struct Investor {
address addr;
uint256 time;
uint amount;
}
mapping(address => Investor[]) private investors;
constructor(uint tokens, uint cash, uint _parValue) public {
owner = msg.sender;
parValue = _parValue;
equityToken501c = tokens;
investorCash = cash;
k = tokens * cash;
Investor memory investor = Investor(owner, now, cash);
investors[owner].push(investor);
}
modifier onlyOwner() {
require(msg.sender == owner, "access denied");
_;
}
/**
* Owner can add investor cash and tokens to the liquidity pool
*/
function add(uint tokens, uint cash) public payable onlyOwner {
require((equityToken501c + tokens) * (investorCash + cash) == k,"liquidity pool is out of balance");
equityToken501c += tokens;
investorCash += cash;
}
function invest(address invaddr, uint cash) public payable onlyOwner {
investorCash += cash;
Investor memory investor = Investor(invaddr, now, cash);
investors[invaddr].push(investor);
k = equityToken501c * investorCash;
}
function getTransactions() public view onlyOwner returns(string memory) {
string memory output = "";
for( uint i = 0; i < transactions[0].length; i++) {
output = string(
abi.encodePacked(output, "'", transactions[0][i].time, "','", transactions[0][i].sender, "',", transactions[0][i].amount, ",", transactions[0][i].fee)
);
}
return output;
}
function totalFees() public view onlyOwner returns(uint) {
return total_fees;
}
function buy501CToken(uint _501cToBuy) public returns (uint cost) {
equityToken501c -= _501cToBuy;
uint newCashAmount = k / equityToken501c;
uint fee = 1 / (fee_pct * 100);
newCashAmount -= fee;
require(newCashAmount >= parValue, "price must be at least par value");
cost = newCashAmount - investorCash;
total_fees += fee;
investorCash += cost;
Transaction memory transaction = Transaction(now, msg.sender, _501cToBuy, fee);
transactions[0].push(transaction);
return cost;
}
function sell501CTokens(uint _501cToSell) public returns (uint bought) {
equityToken501c += _501cToSell;
uint newCashAmount = k / equityToken501c;
uint fee = 1 / (fee_pct * 100);
newCashAmount -= fee;
require(newCashAmount >= parValue, "price must be at least par value");
bought = investorCash - newCashAmount;
total_fees += fee;
investorCash = newCashAmount;
Transaction memory transaction = Transaction(now, msg.sender, _501cToSell, fee);
transactions[0].push(transaction);
return bought;
}
}
| * Owner can add investor cash and tokens to the liquidity pool/ | function add(uint tokens, uint cash) public payable onlyOwner {
require((equityToken501c + tokens) * (investorCash + cash) == k,"liquidity pool is out of balance");
equityToken501c += tokens;
investorCash += cash;
}
| 12,580,626 | [
1,
5541,
848,
527,
2198,
395,
280,
276,
961,
471,
2430,
358,
326,
4501,
372,
24237,
2845,
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
] | [
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,
0,
0,
0
] | [
1,
225,
445,
527,
12,
11890,
2430,
16,
2254,
276,
961,
13,
1071,
8843,
429,
1338,
5541,
288,
203,
565,
2583,
12443,
14298,
560,
1345,
9172,
71,
397,
2430,
13,
380,
261,
5768,
395,
280,
39,
961,
397,
276,
961,
13,
422,
417,
10837,
549,
372,
24237,
2845,
353,
596,
434,
11013,
8863,
203,
565,
1298,
560,
1345,
9172,
71,
1011,
2430,
31,
203,
565,
2198,
395,
280,
39,
961,
1011,
276,
961,
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
] |
./full_match/1/0x6f9140097Ab6278B41Cf9597a597030207b8D75d/sources/lib/seaport-core/src/lib/ConsiderationDecoder.sol | * @dev Converts a function taking ReceivedItem, address, bytes32, and bytes types (e.g. the _transfer function) into a function taking ConsiderationItem, address, bytes32, and bytes types. @param inFn The input function, taking ReceivedItem, address, bytes32, and bytes types (e.g. the _transfer function). @return outFn The output function, taking ConsiderationItem, address, bytes32, and bytes types./ | {
function _toConsiderationItemInput(
function(ReceivedItem memory, address, bytes32, bytes memory)
internal inFn
)
internal
pure
returns (
function(ConsiderationItem memory, address, bytes32, bytes memory)
internal outFn
)
assembly {
outFn := inFn
}
}
| 9,676,151 | [
1,
5692,
279,
445,
13763,
21066,
1180,
16,
1758,
16,
1731,
1578,
16,
471,
1731,
1377,
1953,
261,
73,
18,
75,
18,
326,
389,
13866,
445,
13,
1368,
279,
445,
13763,
1377,
23047,
367,
1180,
16,
1758,
16,
1731,
1578,
16,
471,
1731,
1953,
18,
225,
316,
5372,
1021,
810,
445,
16,
13763,
21066,
1180,
16,
1758,
16,
1731,
1578,
16,
2398,
471,
1731,
1953,
261,
73,
18,
75,
18,
326,
389,
13866,
445,
2934,
327,
596,
5372,
1021,
876,
445,
16,
13763,
23047,
367,
1180,
16,
1758,
16,
9079,
1731,
1578,
16,
471,
1731,
1953,
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
] | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
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
] | [
1,
565,
288,
203,
565,
445,
389,
869,
9054,
3585,
367,
1180,
1210,
12,
203,
3639,
445,
12,
8872,
1180,
3778,
16,
1758,
16,
1731,
1578,
16,
1731,
3778,
13,
203,
5411,
2713,
316,
5372,
203,
565,
262,
203,
3639,
2713,
203,
3639,
16618,
203,
3639,
1135,
261,
203,
5411,
445,
12,
9054,
3585,
367,
1180,
3778,
16,
1758,
16,
1731,
1578,
16,
1731,
3778,
13,
203,
4766,
7734,
2713,
596,
5372,
203,
3639,
262,
203,
3639,
19931,
288,
203,
5411,
596,
5372,
519,
316,
5372,
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,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-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/80001/0xe78D2f06d7Ad0cDC884D7DDB65e4BCEdbD212298/sources/_solidstate/contracts/token/ERC20/base/ERC20BaseInternal.sol | * @notice transfer tokens to given recipient on behalf of given holder @param holder holder of tokens prior to transfer @param recipient beneficiary of token transfer @param amount quantity of tokens to transfer @return success status (always true; otherwise function should revert)/ | function _transferFrom(
address holder,
address recipient,
uint256 amount
) internal virtual returns (bool) {
_decreaseAllowance(holder, msg.sender, amount);
_transfer(holder, recipient, amount);
return true;
}
| 9,525,867 | [
1,
13866,
2430,
358,
864,
8027,
603,
12433,
6186,
434,
864,
10438,
225,
10438,
10438,
434,
2430,
6432,
358,
7412,
225,
8027,
27641,
74,
14463,
814,
434,
1147,
7412,
225,
3844,
10457,
434,
2430,
358,
7412,
327,
2216,
1267,
261,
17737,
638,
31,
3541,
445,
1410,
15226,
13176,
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
] | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
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
] | [
1,
565,
445,
389,
13866,
1265,
12,
203,
3639,
1758,
10438,
16,
203,
3639,
1758,
8027,
16,
203,
3639,
2254,
5034,
3844,
203,
565,
262,
2713,
5024,
1135,
261,
6430,
13,
288,
203,
3639,
389,
323,
11908,
7009,
1359,
12,
4505,
16,
1234,
18,
15330,
16,
3844,
1769,
203,
203,
3639,
389,
13866,
12,
4505,
16,
8027,
16,
3844,
1769,
203,
203,
3639,
327,
638,
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
] |
pragma solidity 0.5;
import "../AddressLib.sol";
/**
* @title AddressLibMock
* @author Igor Dulger
* @dev Mock contract to test Address library. All docs are into origin library.
*/
contract AddressLibMock {
using AddressLib for address;
using AddressLib for address payable;
function addressToString(address _code) external pure returns(string memory) {
return _code.addressToString();
}
}
| * @title AddressLibMock @author Igor Dulger @dev Mock contract to test Address library. All docs are into origin library./ | contract AddressLibMock {
using AddressLib for address;
using AddressLib for address payable;
function addressToString(address _code) external pure returns(string memory) {
return _code.addressToString();
}
}
| 12,659,863 | [
1,
1887,
5664,
9865,
225,
467,
3022,
463,
332,
693,
225,
7867,
6835,
358,
1842,
5267,
5313,
18,
4826,
3270,
854,
1368,
4026,
5313,
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
] | [
1,
1,
1,
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,
16351,
5267,
5664,
9865,
288,
203,
203,
565,
1450,
5267,
5664,
364,
1758,
31,
203,
565,
1450,
5267,
5664,
364,
1758,
8843,
429,
31,
203,
203,
565,
445,
1758,
5808,
12,
2867,
389,
710,
13,
3903,
16618,
1135,
12,
1080,
3778,
13,
288,
203,
3639,
327,
389,
710,
18,
2867,
5808,
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
] |
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import "@openzeppelin/contracts/token/ERC721/IERC721.sol";
import '@openzeppelin/contracts/token/ERC721/extensions/ERC721Enumerable.sol';
import "@openzeppelin/contracts/token/ERC721/extensions/ERC721URIStorage.sol";
import "@openzeppelin/contracts/access/Ownable.sol";
import "@openzeppelin/contracts/token/ERC20/IERC20.sol";//Imported for balanceOf function to check tokenBalance of msg.sender
contract Island is ERC721Enumerable, ERC721URIStorage, Ownable {
event Claim (address indexed buyer, uint256 tokenID);
event Paid (address indexed influencer, uint _amount);
uint256 public burnCount;
uint256 constant public TOTALCOUNT = 10000;
uint256 constant public MAXBATCH = 10;
string public baseURI = "https://islandboys.wtf/";
bool private _started = false;
string constant _NAME = "ISLAND BOYS";
string constant _SYMBOL = "BOY";
address constant _RUGS = 0x6C94954D0b265F657A4A1B35dfAA8B73D1A3f199;
address constant _DRAPES = 0x9aF0e1748fF32f698847CfAB5013469a37dCdb17;
address constant _BLAZED = 0x8584e7A1817C795f74Ce985a1d13b962758FE3CA;
address constant _HEADS = 0xC6904FB685b4DFbDb98a5B70E40863Cd9AEF33DC;
address constant _DOJI = 0x5e9dC633830Af18AA43dDB7B042646AADEDCCe81;
address constant _RECORDS = 0x153C5091580cB9c3f12F7C1e170743a9af7B774a;
address constant _INFLUENZAS = 0xaf76c7B002a3b7F062E1a19248B0579C52EeBE4A;
address constant _ZINGOT = 0x8dEeFeBd24EF87e3F7aEf2057a002a8E91837801;
constructor()
ERC721(_NAME, _SYMBOL) {
setStart(true);
safeMint(0x86a8A293fB94048189F76552eba5EC47bc272223, 1);
transferOwnership(0x86a8A293fB94048189F76552eba5EC47bc272223);
}
receive() external payable {
}
function setBaseURI(string memory _newURI) public onlyOwner {
baseURI = _newURI;
}
function setTokenURI(uint256 _tokenId, string memory _tokenURI) public onlyOwner {
_setTokenURI(_tokenId, _tokenURI);
}
function setStart(bool _start) public onlyOwner {
_started = _start;
}
function claimIsland(uint256 _batchCount) public {
require(_started);
require(_batchCount > 0 && _batchCount <= MAXBATCH);
require(totalSupply() + _batchCount + burnCount <= TOTALCOUNT);
require(hasRugToken(), "You must own at least one Rug project to mint.");
for(uint256 i = 0; i < _batchCount; i++) {
uint mintID = totalSupply() + 1;
emit Claim(_msgSender(), mintID);
_mint(_msgSender(), mintID);
}
}
function walletInventory(address _owner) external view returns (uint256[] memory) {
uint256 tokenCount = balanceOf(_owner);
uint256[] memory tokensId = new uint256[](tokenCount);
for (uint256 i = 0; i < tokenCount; i++) {
tokensId[i] = tokenOfOwnerByIndex(_owner, i);
}
return tokensId;
}
function hasRugToken() public view returns (bool) {
address sender = _msgSender();
if(
IERC721(_RUGS).balanceOf(sender) > 0 ||
IERC721(_DRAPES).balanceOf(sender) > 0 ||
IERC721(_BLAZED).balanceOf(sender) > 0 ||
IERC721(_HEADS).balanceOf(sender) > 0 ||
IERC721(_DOJI).balanceOf(sender) > 0 ||
IERC721(_RECORDS).balanceOf(sender) > 0 ||
IERC721(_ZINGOT).balanceOf(sender) > 0 ||
IERC721(_INFLUENZAS).balanceOf(sender) > 0
) {
return true;
}
return false;
}
/**
* Override isApprovedForAll to auto-approve OS's proxy contract
*/
function isApprovedForAll(
address _owner,
address _operator
) public override view returns (bool isOperator) {
// if OpenSea's ERC721 Proxy Address is detected, auto-return true
if (_operator == address(0xa5409ec958C83C3f309868babACA7c86DCB077c1)) { // OpenSea approval
return true;
}
// otherwise, use the default ERC721.isApprovedForAll()
return ERC721.isApprovedForAll(_owner, _operator);
}
function safeMint(address to, uint256 tokenId) public onlyOwner {
require((totalSupply() + burnCount) < TOTALCOUNT);
require(tokenId >= 1);
_safeMint(to, tokenId);
}
function _beforeTokenTransfer(address from, address to, uint256 tokenId)
internal
override(ERC721, ERC721Enumerable)
{
super._beforeTokenTransfer(from, to, tokenId);
}
function burn(uint256 tokenId) public {
//solhint-disable-next-line max-line-length
require(_isApprovedOrOwner(_msgSender(), tokenId));
burnCount++;
_burn(tokenId);
}
function _burn(uint256 tokenId) internal override(ERC721, ERC721URIStorage) {
super._burn(tokenId);
}
function tokenURI(uint256 tokenId) public view override(ERC721, ERC721URIStorage) returns (string memory){
return super.tokenURI(tokenId);
}
//THIS IS MANDATORY or REMOVE DO NOT FORGET
function _baseURI() internal view virtual override returns (string memory){
return baseURI;
}
function supportsInterface(bytes4 interfaceId)
public
view
override(ERC721, ERC721Enumerable)
returns (bool)
{
return super.supportsInterface(interfaceId);
}
}
// 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 "../ERC721.sol";
import "./IERC721Enumerable.sol";
/**
* @dev This implements an optional extension of {ERC721} defined in the EIP that adds
* enumerability of all the token ids in the contract as well as all token ids owned by each
* account.
*/
abstract contract ERC721Enumerable is ERC721, IERC721Enumerable {
// Mapping from owner to list of owned token IDs
mapping(address => mapping(uint256 => uint256)) private _ownedTokens;
// Mapping from token ID to index of the owner tokens list
mapping(uint256 => uint256) private _ownedTokensIndex;
// Array with all token ids, used for enumeration
uint256[] private _allTokens;
// Mapping from token id to position in the allTokens array
mapping(uint256 => uint256) private _allTokensIndex;
/**
* @dev See {IERC165-supportsInterface}.
*/
function supportsInterface(bytes4 interfaceId) public view virtual override(IERC165, ERC721) returns (bool) {
return interfaceId == type(IERC721Enumerable).interfaceId || super.supportsInterface(interfaceId);
}
/**
* @dev See {IERC721Enumerable-tokenOfOwnerByIndex}.
*/
function tokenOfOwnerByIndex(address owner, uint256 index) public view virtual override returns (uint256) {
require(index < ERC721.balanceOf(owner), "ERC721Enumerable: owner index out of bounds");
return _ownedTokens[owner][index];
}
/**
* @dev See {IERC721Enumerable-totalSupply}.
*/
function totalSupply() public view virtual override returns (uint256) {
return _allTokens.length;
}
/**
* @dev See {IERC721Enumerable-tokenByIndex}.
*/
function tokenByIndex(uint256 index) public view virtual override returns (uint256) {
require(index < ERC721Enumerable.totalSupply(), "ERC721Enumerable: global index out of bounds");
return _allTokens[index];
}
/**
* @dev Hook that is called before any token transfer. This includes minting
* and burning.
*
* Calling conditions:
*
* - When `from` and `to` are both non-zero, ``from``'s `tokenId` will be
* transferred to `to`.
* - When `from` is zero, `tokenId` will be minted for `to`.
* - When `to` is zero, ``from``'s `tokenId` will be burned.
* - `from` cannot be the zero address.
* - `to` cannot be the zero address.
*
* To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks].
*/
function _beforeTokenTransfer(
address from,
address to,
uint256 tokenId
) internal virtual override {
super._beforeTokenTransfer(from, to, tokenId);
if (from == address(0)) {
_addTokenToAllTokensEnumeration(tokenId);
} else if (from != to) {
_removeTokenFromOwnerEnumeration(from, tokenId);
}
if (to == address(0)) {
_removeTokenFromAllTokensEnumeration(tokenId);
} else if (to != from) {
_addTokenToOwnerEnumeration(to, tokenId);
}
}
/**
* @dev Private function to add a token to this extension's ownership-tracking data structures.
* @param to address representing the new owner of the given token ID
* @param tokenId uint256 ID of the token to be added to the tokens list of the given address
*/
function _addTokenToOwnerEnumeration(address to, uint256 tokenId) private {
uint256 length = ERC721.balanceOf(to);
_ownedTokens[to][length] = tokenId;
_ownedTokensIndex[tokenId] = length;
}
/**
* @dev Private function to add a token to this extension's token tracking data structures.
* @param tokenId uint256 ID of the token to be added to the tokens list
*/
function _addTokenToAllTokensEnumeration(uint256 tokenId) private {
_allTokensIndex[tokenId] = _allTokens.length;
_allTokens.push(tokenId);
}
/**
* @dev Private function to remove a token from this extension's ownership-tracking data structures. Note that
* while the token is not assigned a new owner, the `_ownedTokensIndex` mapping is _not_ updated: this allows for
* gas optimizations e.g. when performing a transfer operation (avoiding double writes).
* This has O(1) time complexity, but alters the order of the _ownedTokens array.
* @param from address representing the previous owner of the given token ID
* @param tokenId uint256 ID of the token to be removed from the tokens list of the given address
*/
function _removeTokenFromOwnerEnumeration(address from, uint256 tokenId) private {
// To prevent a gap in from's tokens array, we store the last token in the index of the token to delete, and
// then delete the last slot (swap and pop).
uint256 lastTokenIndex = ERC721.balanceOf(from) - 1;
uint256 tokenIndex = _ownedTokensIndex[tokenId];
// When the token to delete is the last token, the swap operation is unnecessary
if (tokenIndex != lastTokenIndex) {
uint256 lastTokenId = _ownedTokens[from][lastTokenIndex];
_ownedTokens[from][tokenIndex] = lastTokenId; // Move the last token to the slot of the to-delete token
_ownedTokensIndex[lastTokenId] = tokenIndex; // Update the moved token's index
}
// This also deletes the contents at the last position of the array
delete _ownedTokensIndex[tokenId];
delete _ownedTokens[from][lastTokenIndex];
}
/**
* @dev Private function to remove a token from this extension's token tracking data structures.
* This has O(1) time complexity, but alters the order of the _allTokens array.
* @param tokenId uint256 ID of the token to be removed from the tokens list
*/
function _removeTokenFromAllTokensEnumeration(uint256 tokenId) private {
// To prevent a gap in the tokens array, we store the last token in the index of the token to delete, and
// then delete the last slot (swap and pop).
uint256 lastTokenIndex = _allTokens.length - 1;
uint256 tokenIndex = _allTokensIndex[tokenId];
// When the token to delete is the last token, the swap operation is unnecessary. However, since this occurs so
// rarely (when the last minted token is burnt) that we still do the swap here to avoid the gas cost of adding
// an 'if' statement (like in _removeTokenFromOwnerEnumeration)
uint256 lastTokenId = _allTokens[lastTokenIndex];
_allTokens[tokenIndex] = lastTokenId; // Move the last token to the slot of the to-delete token
_allTokensIndex[lastTokenId] = tokenIndex; // Update the moved token's index
// This also deletes the contents at the last position of the array
delete _allTokensIndex[tokenId];
_allTokens.pop();
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import "../ERC721.sol";
/**
* @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];
}
}
}
// 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);
}
}
// 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;
/**
* @dev Interface of the ERC165 standard, as defined in the
* https://eips.ethereum.org/EIPS/eip-165[EIP].
*
* Implementers can declare support of contract interfaces, which can then be
* queried by others ({ERC165Checker}).
*
* For an implementation, see {ERC165}.
*/
interface IERC165 {
/**
* @dev Returns true if this contract implements the interface defined by
* `interfaceId`. See the corresponding
* https://eips.ethereum.org/EIPS/eip-165#how-interfaces-are-identified[EIP section]
* to learn more about how these ids are created.
*
* This function call must use less than 30 000 gas.
*/
function supportsInterface(bytes4 interfaceId) external view returns (bool);
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import "./IERC721.sol";
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 "../IERC721.sol";
/**
* @title ERC-721 Non-Fungible Token Standard, optional enumeration extension
* @dev See https://eips.ethereum.org/EIPS/eip-721
*/
interface IERC721Enumerable is IERC721 {
/**
* @dev Returns the total amount of tokens stored by the contract.
*/
function totalSupply() external view returns (uint256);
/**
* @dev Returns a token ID owned by `owner` at a given `index` of its token list.
* Use along with {balanceOf} to enumerate all of ``owner``'s tokens.
*/
function tokenOfOwnerByIndex(address owner, uint256 index) external view returns (uint256 tokenId);
/**
* @dev Returns a token ID at a given `index` of all the tokens stored by the contract.
* Use along with {totalSupply} to enumerate all tokens.
*/
function tokenByIndex(uint256 index) external view returns (uint256);
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
/**
* @title ERC721 token receiver interface
* @dev Interface for any contract that wants to support safeTransfers
* from ERC721 asset contracts.
*/
interface IERC721Receiver {
/**
* @dev Whenever an {IERC721} `tokenId` token is transferred to this contract via {IERC721-safeTransferFrom}
* by `operator` from `from`, this function is called.
*
* It must return its Solidity selector to confirm the token transfer.
* If any other value is returned or the interface is not implemented by the recipient, the transfer will be reverted.
*
* The selector can be obtained in Solidity with `IERC721.onERC721Received.selector`.
*/
function onERC721Received(
address operator,
address from,
uint256 tokenId,
bytes calldata data
) external returns (bytes4);
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import "../IERC721.sol";
/**
* @title ERC-721 Non-Fungible Token Standard, optional metadata extension
* @dev See https://eips.ethereum.org/EIPS/eip-721
*/
interface IERC721Metadata is IERC721 {
/**
* @dev Returns the token collection name.
*/
function name() external view returns (string memory);
/**
* @dev Returns the token collection symbol.
*/
function symbol() external view returns (string memory);
/**
* @dev Returns the Uniform Resource Identifier (URI) for `tokenId` token.
*/
function tokenURI(uint256 tokenId) external view returns (string memory);
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
/**
* @dev Collection of functions related to the address type
*/
library Address {
/**
* @dev Returns true if `account` is a contract.
*
* [IMPORTANT]
* ====
* It is unsafe to assume that an address for which this function returns
* false is an externally-owned account (EOA) and not a contract.
*
* Among others, `isContract` will return false for the following
* types of addresses:
*
* - an externally-owned account
* - a contract in construction
* - an address where a contract will be created
* - an address where a contract lived, but was destroyed
* ====
*/
function isContract(address account) internal view returns (bool) {
// This method relies on extcodesize, which returns 0 for contracts in
// construction, since the code is only stored at the end of the
// constructor execution.
uint256 size;
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 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 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;
}
} | Imported for balanceOf function to check tokenBalance of msg.sender
| import "@openzeppelin/contracts/token/ERC20/IERC20.sol"; | 13,412,058 | [
1,
24934,
364,
11013,
951,
445,
358,
866,
1147,
13937,
434,
1234,
18,
15330,
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,
5666,
8787,
3190,
94,
881,
84,
292,
267,
19,
16351,
87,
19,
2316,
19,
654,
39,
3462,
19,
45,
654,
39,
3462,
18,
18281,
14432,
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
] |
pragma solidity ^0.4.19;
contract Ownable {
/**
* @dev set `owner` of the contract to the sender
*/
address 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));
owner = newOwner;
}
}
library SafeMath {
function sub(uint256 a, uint256 b) internal pure returns (uint256) {
require(b <= a);
return a - b;
}
}
/**
* @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) public view returns (uint256);
function transfer(address to, uint256 value) public returns (bool);
event Transfer(address indexed from, address indexed to, uint256 value);
}
/**
* @title ERC20 interface
* @dev see https://github.com/ethereum/EIPs/issues/20
*/
contract ERC20 is ERC20Basic {
function allowance(address owner, address spender) public view returns (uint256);
function transferFrom(address from, address to, uint256 value) public returns (bool);
function approve(address spender, uint256 value) public returns (bool);
event Approval(address indexed owner, address indexed spender, uint256 value);
}
/**
* @title Basic token
* @dev Basic version of StandardToken, with no allowances.
*/
contract BasicToken is ERC20Basic {
using SafeMath for uint256;
mapping(address => uint256) balances;
/**
* @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] += _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] += _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];
}
}
/**
* @title Mintable token
* @dev Simple ERC20 Token example, with mintable token creation
* @dev Issue: * https://github.com/OpenZeppelin/zeppelin-solidity/issues/120
* Based on code by TokenMarketNet: https://github.com/TokenMarketNet/ico/blob/master/contracts/MintableToken.sol
*/
contract MintableToken is StandardToken, Ownable {
event Mint(address indexed to, uint256 amount);
event Burn(address indexed burner, uint value);
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 += _amount;
balances[_to] += _amount;
Mint(_to, _amount);
Transfer(address(0), _to, _amount);
return true;
}
/**
* @dev Function to burn tokens
* @param _addr The address that will have _amount of tokens burned.
* @param _amount The amount of tokens to burn.
*/
function burn(address _addr, uint _amount) onlyOwner public {
require(_amount > 0 && balances[_addr] >= _amount && totalSupply >= _amount);
balances[_addr] -= _amount;
totalSupply -= _amount;
Burn(_addr, _amount);
Transfer(_addr, address(0), _amount);
}
/**
* @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 WealthBuilderToken is MintableToken {
string public name = "Wealth Builder Token";
string public symbol = "WBT";
uint32 public decimals = 18;
/**
* how many {tokens*10^(-18)} get per 1wei
*/
uint public rate = 10**7;
/**
* multiplicator for rate
*/
uint public mrate = 10**7;
function setRate(uint _rate) onlyOwner public {
rate = _rate;
}
}
contract Data is Ownable {
// node => its parent
mapping (address => address) private parent;
// node => its status
mapping (address => uint8) public statuses;
// node => sum of all his child deposits in USD cents
mapping (address => uint) public referralDeposits;
// client => balance in wei*10^(-6) available for withdrawal
mapping(address => uint256) private balances;
// investor => balance in wei*10^(-6) available for withdrawal
mapping(address => uint256) private investorBalances;
function parentOf(address _addr) public constant returns (address) {
return parent[_addr];
}
function balanceOf(address _addr) public constant returns (uint256) {
return balances[_addr] / 1000000;
}
function investorBalanceOf(address _addr) public constant returns (uint256) {
return investorBalances[_addr] / 1000000;
}
/**
* @dev The Data constructor to set up the first depositer
*/
function Data() public {
// DirectorOfRegion - 7
statuses[msg.sender] = 7;
}
function addBalance(address _addr, uint256 amount) onlyOwner public {
balances[_addr] += amount;
}
function subtrBalance(address _addr, uint256 amount) onlyOwner public {
require(balances[_addr] >= amount);
balances[_addr] -= amount;
}
function addInvestorBalance(address _addr, uint256 amount) onlyOwner public {
investorBalances[_addr] += amount;
}
function subtrInvestorBalance(address _addr, uint256 amount) onlyOwner public {
require(investorBalances[_addr] >= amount);
investorBalances[_addr] -= amount;
}
function addReferralDeposit(address _addr, uint256 amount) onlyOwner public {
referralDeposits[_addr] += amount;
}
function setStatus(address _addr, uint8 _status) onlyOwner public {
statuses[_addr] = _status;
}
function setParent(address _addr, address _parent) onlyOwner public {
parent[_addr] = _parent;
}
}
contract Declaration {
// threshold in USD => status
mapping (uint => uint8) statusThreshold;
// status => (depositsNumber => percentage)
mapping (uint8 => mapping (uint8 => uint)) feeDistribution;
// status thresholds in USD
uint[8] thresholds = [
0, 5000, 35000, 150000, 500000, 2500000, 5000000, 10000000
];
uint[5] referralFees = [50, 30, 20, 10, 5];
uint[5] serviceFees = [25, 20, 15, 10, 5];
/**
* @dev The Declaration constructor to define some constants
*/
function Declaration() public {
setFeeDistributionsAndStatusThresholds();
}
/**
* @dev Set up fee distribution & status thresholds
*/
function setFeeDistributionsAndStatusThresholds() private {
// Agent - 0
setFeeDistributionAndStatusThreshold(0, [12, 8, 5, 2, 1], thresholds[0]);
// SilverAgent - 1
setFeeDistributionAndStatusThreshold(1, [16, 10, 6, 3, 2], thresholds[1]);
// Manager - 2
setFeeDistributionAndStatusThreshold(2, [20, 12, 8, 4, 2], thresholds[2]);
// ManagerOfGroup - 3
setFeeDistributionAndStatusThreshold(3, [25, 15, 10, 5, 3], thresholds[3]);
// ManagerOfRegion - 4
setFeeDistributionAndStatusThreshold(4, [30, 18, 12, 6, 3], thresholds[4]);
// Director - 5
setFeeDistributionAndStatusThreshold(5, [35, 21, 14, 7, 4], thresholds[5]);
// DirectorOfGroup - 6
setFeeDistributionAndStatusThreshold(6, [40, 24, 16, 8, 4], thresholds[6]);
// DirectorOfRegion - 7
setFeeDistributionAndStatusThreshold(7, [50, 30, 20, 10, 5], thresholds[7]);
}
/**
* @dev Set up specific fee and status threshold
* @param _st The status to set up for
* @param _percentages Array of pecentages, which should go to member
* @param _threshold The minimum amount of sum of children deposits to get
* the status _st
*/
function setFeeDistributionAndStatusThreshold(
uint8 _st,
uint8[5] _percentages,
uint _threshold
)
private
{
statusThreshold[_threshold] = _st;
for (uint8 i = 0; i < _percentages.length; i++) {
feeDistribution[_st][i] = _percentages[i];
}
}
}
contract Investors is Ownable {
// investors
/*
"0x418155b19d7350f5a843b826474aa2f7623e99a6","0xbeb7a29a008d69069fd10154966870ff1dda44a0","0xa9cb1b8ba1c8facb92172e459389f80d304595a3","0xf3f2bf9be0ccc8f27a15ccf18d820c0722e8996a","0xa0f36ac9f68c1a4594ef5cec29dc9b1cc67f822c","0xc319278cca404e3a479b088922e4117feb4cec9d","0xe633c933529d6fd7c6147d2b0dc51bfbe3304e56","0x5bd2c1f2f06b16e427a4ec3a6beef6263fd506da","0x52c4f101d0367c3f9933d0c14ea389e74ad00352","0xf7a0d2149f324a0b607ebf23df671acc4e9da6d2","0x0418df662bb2994262bb720d477e558a59e19490","0xf0de6520e0726ba3d84611f84867aa9987391402","0x1e895274a9570f150f11ae0ed86dd42a53208b81","0x95a247bef71f6b234e9805d1493366a302a498e4","0x9daaeaf355f69f7176a0145df6d1769d7f14553b","0x029136181d87c6f0979431255424b5fad78e8491","0x7e1f5669d9e1c593a495c5cec384ca32ad4a09fc","0x46c7e04fdaaa1a9298e63ca2fd47b0004cb236bf","0x5933fa485863da06584057494f0f6660d3c1477c","0x4290231804dd59947aff9fcef925287e44906e7b","0x2feaf2101b3f9943a81567badb56e3780946ce3f","0x5b602c34ba643913908f69a4cd5846a07ed3915b","0x146308896955030ce3bcc6030bab142afddaa1e6","0x9fc61b75451fabf5b5b78e03bacaf8bb592541fc","0x87f7636f7856466b6c6bce999574a784387e2b78","0x024db1f560327ab5174f1a737caf446b5644c709","0x715c248e621cbdb6f091bf653bb4bc331d2f9b1e","0xfe92a23b497140ba055a91ade89d91f95f8e5153","0xc3426e0e0634725a628a7a21bfd49274e1f24733","0xb12a79b9dba8bbb9ed5e329466a9c2703da38dbd","0x44d8336749ebf584a4bcd636cefe83e6e0b33e7d","0x89c91460c3bdc164250e5a27351c743c070c226a","0xe0798a1b847f450b5d4819043d27a380a4715af8","0xeac5e75252d902cb7f8473e45fff9ceb391c536b","0xea53e88876a6da2579d837a559b31b08d6750681","0x5df22fac00c45ef7b5c285c54a006798f42bbc6e","0x09899f20064b5e67d02f6a97ef412564977ee193","0xc572f18d0a4a65f6e612e6de484dbc15b8839df3","0x397b9719e720c0d33fe7dcc004958e56636cbf82","0x577de83b60299df60cc7fce7ac78d3a5d880aa95","0x9a716298949b16c4610b40ba1d19e96d3286c35c","0x60ef523f3845e38a20b63344a4e9ec689773ead6","0xe34252e3efe0514c5fb76c9fb39ff31f554d6659","0xbabfbdf4f422d36c00e448cc562ce0f5dbe47d64","0x2608cca4aff4cc3008ac6bd22e0664348ecee088","0x0dd1d3102f89d4ee7c260048cbe01933f17debde","0xdbb28fafc4ecd7736247aca7dc8e20782ca86a7a","0x6201fc413bb9292527956a70e7575436d5135ce1","0xa836f4cfb8fd3e5bccc9c7a6a678f2a5928b7c79","0x85dce799fd059d86c420eb4e3c1bd89e323b7b12","0xdef2086c6bbdc8b0f6e130907f05345b44af8cc3","0xc1004695ce07ef5efb1d218672e5cfcb659c5900","0x227a5b4bb4cffc2b907d9f586dd100989efeee56","0xd372b3d43ba8ea406f64dbc68f70ec812e54fbc8","0xdf6c417cdb27bc0c877a0e121a2c58ad884e85c6","0x090f4d53b5d7ebcb8e348709cdb708d80cd199f0","0x2499b302b6f5e57f54c1c7a326813e3dffddcd1a","0x3114024a034443e972707522d911fc709f62dd3e","0x30b864f49cef510b1173a5bfc31e77b0b59daf9e","0x9a9680f5ddee6cef96ef36ab506f4b6d3198c35e","0x08018337b9b138b631cd325168c3d5014df6e18b","0x2ac345a4ec1615c3a236099ebbed4911673bbfa5","0x2b9fd54828cd443b7c411419b058b44bd02fdc49","0x208713a63460d44e5a83ae8e8f7333496a05065e","0xe4052eb7ba8891ee7ccd7551faaa5f4c421904e7","0x74bc9db1ac813db06f771bcff359e9237b01c906","0x033dd047a042ea873ca27af36b64ca566a006e97","0xb4721808a3f2830a1708967302443b53f5943429","0xc91fbb815c2f4944d8c6846be6ac0e30f5a037df","0x19ef947c276436ac11a8be15567909a37d824e73","0x079eefd69c5a4c5e4c9ee3fa08c2a2964da3e11a","0x11fb64be296590f948d56daab6c2d102c9842b08","0x06ec97feaeb0f4b9a75f9671d6b62bfadaf18ddd","0xaeda3cff45032695fb2cf4f584cda822bd5d8b7e","0x9f377085d3da85107cd68bd08bdd9a1b862d44e0","0xb46b8d1c313c52fd422fe189dde1b4d0800a5e0f","0x99039fa34510c7321f4d19ea337c80cc14cc885d","0x378aba0f47c7790ed0e5ca61749b0025d1208a5d","0x4395e1db93d4e2f4583a4f87494eb0aea057b8fd","0xa4035578750564e48abfb5ba1d6eec1da1bf366f","0xb611b39eb6c16dae3754e514ddd5f02fcadd765f","0x67d41491ddc004e899a3faf109f526cd717fe6d8","0x58e2c10865f9a1668e800c91b6a3d7b3416fb26c","0x04e34355ced9d532c9bc01d5e569f31b6d46cd50","0xf80358cabdc9b9b79570b6f073a861cf5567bb57","0xbdacb079fc17a00d945f01f4f9bd5d03cfcd5b6c","0x387a723060bc42a7796c76197d2d3b41b4c43d19","0xa04cc8fc56c34ab8104f63c11bf211de4bb7b0aa","0x3bf8b5ede7501519d41792715215735d8f40af10","0x6c3a13bac5cf61b1927562a927e89ca6b5d034d6","0x9899aecef15de43eec04859be649ac4c50330886","0xa4d25bac971ca08b47a908a070b6362102206c12"
"0xf88d963dc3f58fe6e71879543e57734e8152f70d","0x7b30a000f7ae56ee6206cbd9fb20c934b4bbb5d1","0xb2f0e5330e90559a738eda0df156635e18a145fd","0x5b2c07b6cce506f2293f1b32dc33d9928b8c9ada","0x5a967c0e38cb3bfad90df288ce238699cc47b5e3","0x0e686d6f3c897cae3984b80b5f6a7c785c708718","0xa8ea0b6bc70502644c0644fb4c0810540a1fa261","0xc70e278819ef5aec6b3ededc21e2981557e14443","0x477b5ae32ffcd34eb25f0c52866d4f602982dc6f","0x3e72a45fbc6a0858b506a0c7bedff79af75ae37c","0x1430e272a50703ef46d8ed5aa01e1ced71245341","0xc87d0bb90a6105a66fd5105c6746218d381b8207","0x0ed7f98b6177d0c15e27704f2bae4d068b8594d5","0x09a627b57879eb625cd8b7c59ffa363222553c23","0x0fdbc41046590ef7ee2a73b9808fd5bd7e189ac4","0x6a4b68af67a3b4a98fe1a59210dd3d775e567729","0x442a3daf774329fee3e904e86ddec1191f4be3ce","0x9efa8fe7fa51c8b36ab902046f879b035520f556","0x510e8e58b8ce4acaa6866e59dfc0fa339ea358e5","0x374831251283aa63aee6506ac6580479aaf3c22b","0xf758c498d020c0b92f2116d09d7ef6509c2c71bd","0xd83e8281ffcfb0ff96236e99ba66aabb8dcc7920","0x3670c3a5e65b757db8c82b12dd92057ac19d41fa","0xfd28eb7e3e5e3406ce6b82045d487c2be294cd38","0x2d23cd492096b903e4595ccdac74e49692a6ea8e","0x94d3a0a19ed5448052c549fd1f69f54c5f1fd8c5","0x8e5354ac59cee09d252e379a3534053306022ebe","0xa66f3700dda0147c56c2970202768c956c644ffd","0xf11d32baef6221f36916c58844cd8e9813c0af47","0x384a9bc1de23b36c2a23b963e57c8cd85b0d592c","0xbd00dfbaaa1abaa7948c7b2a6bed6e644293cc1c","0xa99a28afcbd4ab09a2ef2c0932becd0368225ee6","0xe554084d77bc6e510eed7276cb6033865375b669","0xe7582fa53531915a2fef5a81b98969d0091d8d44","0x5f15db1d209fa6fd3c667fb086d3d89e3793511f","0x7e9ff5348d57d3427e24b7e104ad5acf039edaf2","0xb4fb1a01483454d75a0cdfa983b99236c4c91111","0x4a7cc5eebfe019efab06c1fa9ae8453dc63ba84e","0xb6fc08d5043b51ac05cdbd88afaab0e4422762d0","0xb18365f4f1e95287a5f85c8a67cebee9e6164c31","0xaf575cfb94d65eaeaace749868282d0e26e4608a","0x3d07e5ff3a2d29ee17584dff60cc99bb4cd79c3d","0x08f0afc93fbc8188150f4bcab004e259cd4785aa","0x65ac3ed81f101e5651c72c4cc2d74650378b5b0c","0x58aef4fc6b54cb53683a6481655021109b8d4dce","0x6aa43e24604577574a0632524a1f4c21d70a61e2","0xbee55aa5ad9953294ecac83a6b62f10c8155444b","0x99dc885ac6ec9873e2409d5a31e7f525c1897e09","0x53a0622034680d64bd0f139df5e989d70b194a4d","0xa6ba4966f1fdd0e8560516e53490b25cf0c4fbd1","0xbd1b95ee4621ecda41961da61277e17e52f37dbf","0xf6481b881eea526ae36cbe11d58d641f96f04a77","0xd158d53d75eac0dda9d2dedf3418d071a2fd44ee","0xb22697e3f33544da7782c8197d07704e1906a3bf","0xa3237e67df409dca45930c1f5f671251adc202be","0x72b26f2dded753a01f391322b00f9a85a77c7fda","0x203fbf3a77bdf35f7aca220b363272896db91d57","0xb1be2f4d72eb87dfcf7ed93c8ec16e4040e52560","0xc60d8a0313ede22194ebe6285471f72f9bcdcda0","0x9888e7423ea48413a4c90a10c76ca5f90d065e1f","0x0be856768ad0ec5b45464ce5202e2c337224cebf","0x3b54ea00a74b116510c4f73a3fc19a62991aaf64","0xe72aa06ffe7058f73622f219af164369c03e3a41","0x7e71fada017d9af455f38db4957d527f51fe1bc5","0x78430e58934220f37ca6b9dbe622f076ad0eb3f5","0x0c765e201bb43d49ab5b44d40d3cf1d219424821","0x4739d251b40028761bbd8034a21919d926f23b45","0x00a7c7bc71022032f6ef3f699b212c9450875740","0x0d4f50b0d43d34a163b8dd7c33fbcc92a19cfa59","0x9284fbc0cc35d9b835de2b00b6b7093075527f6b","0x3564e101b32fe5f3c99e8da823ac003373c26d33","0xf5a358f228dc964fa7c703cb6ad9f6002ce77b17","0x8297a09b5dac9e60896c787f0995ac06441ab14f","0xed8c9b4fd60a6e4ae66c38f5819cffb360af5dd5","0x23009de4ec4a666ba719656d844e42e264e14c6b","0x63227f4492c6bbd9e1015f2c864a31eef1465cd3","0xf3e0ec409386ea202b15d97bb8dd2d131917e3b1","0x981154fafb3a5aeee43d984ee255e5121ce79790","0x49a4598cdf112b5848c11c465d39989fcb5cb6c1","0x575ca03f00f9e5566d85dc095165998953ab0753","0x09d87f2979c4ac6c9d4077d1f5d94cb9aadf43ca","0x0b4575867757b3982379f4d05c92fd2d019247a0","0x8c666d40e2ac961885d675e58e3115b859dac6c1","0x34a3401ebe8431d44efee9948c4b641142407aa8","0x1683512dbcce189ea6042862a2ba4abd4886623b","0x72d45f733336f6f03ef20c1ad4f51ff6b7f90186","0x569fe010fe2d40037c029537eef78aa9b0e018f9","0x061def9fab3aee4161711d4c040d138a273893b5","0xe77e2ae67e1152425c75ff56291d03d92f5d3cad","0x93ebdeb0b0c967f5cc1a10f481569e1871b7d7cd","0x6d7910f900fc3e3f2e2b6d5d8aad43bc6a232685","0xb16e28be300f579a81f2b80fdd5a95cf168bf3a4"
"0xd69835daeee01601ea991efe9fd0309c64c07d42","0x30b45ed69250a160ee91dadab2986d21626d7f4b","0xd28075489da5f9ef51bcc61668c114296a8e8603","0xb63c5cb479034bacc04266536e32aeeb9f958059","0x5f81fe78b5c238afd97a32c572aa04d87b730147","0xb98c8d7d64ef60cc76410f31c19570da0c4d9f12","0x031eb1c3a9909ea26d07f194abe5ad7f6945a482","0x83691573a4fdb5ff2cdbe2df155da09810a3c2bc","0x6722a482e1f3b797e69f98a3324b6660b9c6baa5","0xbda61db5824240280ed000a57ed5e6f70d552dd6","0x58605742105060e5c3070b88b0f51eca7f022d06","0xb4754815ccfc9c98a80f71a0a2c97471188bd556","0x50503144f253e6f05103b643c082ebf215436d95","0xd0dbef9f712ee0ca05fe48b6a40f5b774a109feb"
*/
address[] public investors;
// investor address => percentage * 10^(-2)
/*
3026,1500,510,462,453,302,250,250,226,220,150,129,100,100,60,50,50,50,50,50,50,50,50,50,50,40,40,30,27,26,25,25,25,25,25,25,25,25,23,20,19,15,15,15,15,15,14,14,13,13,13,13,12,12,11,11,11,11,11,11,10,10,10,10,10,10,10,10,12,9,9,8,8,8,8,7,6,6,6,6,6,6,6,6,6,6,6,6,6,5,5,5
5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,4,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,2,1,6
6,125,50,5,8,50,23,3,115,14,10,50,5,5
*/
mapping (address => uint) public investorPercentages;
/**
* @dev Add investors
*/
function addInvestors(address[] _investors, uint[] _investorPercentages) onlyOwner public {
for (uint i = 0; i < _investors.length; i++) {
investors.push(_investors[i]);
investorPercentages[_investors[i]] = _investorPercentages[i];
}
}
/**
* @dev Get investors count
* @return uint count
*/
function getInvestorsCount() public constant returns (uint) {
return investors.length;
}
/**
* @dev Get investors' fee depending on the current year
* @return uint8 The fee percentage, which investors get
*/
function getInvestorsFee() public constant returns (uint8) {
//01/01/2020
if (now >= 1577836800) {
return 1;
}
//01/01/2019
if (now >= 1546300800) {
return 5;
}
return 10;
}
}
contract Referral is Declaration, Ownable {
using SafeMath for uint;
// reference to token contract
WealthBuilderToken private token;
// reference to data contract
Data private data;
// reference to investors contract
Investors private investors;
// investors balance to be distributed in wei*10^(2)
uint public investorsBalance;
/**
* how many USD cents get per ETH
*/
uint public ethUsdRate;
/**
* @dev The Referral constructor to set up the first depositer,
* reference to system token, data & investors and set ethUsdRate
*/
function Referral(uint _ethUsdRate, address _token, address _data, address _investors) public {
ethUsdRate = _ethUsdRate;
// instantiate token & data contracts
token = WealthBuilderToken(_token);
data = Data(_data);
investors = Investors(_investors);
investorsBalance = 0;
}
/**
* @dev Callback function
*/
function() payable public {
}
function invest(address client, uint8 depositsCount) payable public {
uint amount = msg.value;
// if less then 5 deposits
if (depositsCount < 5) {
uint serviceFee;
uint investorsFee = 0;
if (depositsCount == 0) {
uint8 investorsFeePercentage = investors.getInvestorsFee();
serviceFee = amount * (serviceFees[depositsCount].sub(investorsFeePercentage));
investorsFee = amount * investorsFeePercentage;
investorsBalance += investorsFee;
} else {
serviceFee = amount * serviceFees[depositsCount];
}
uint referralFee = amount * referralFees[depositsCount];
// distribute deposit fee among users above on the branch & update users' statuses
distribute(data.parentOf(client), 0, depositsCount, amount);
// update balance & number of deposits of user
uint active = (amount * 100)
.sub(referralFee)
.sub(serviceFee)
.sub(investorsFee);
token.mint(client, active / 100 * token.rate() / token.mrate());
// update owner`s balance
data.addBalance(owner, serviceFee * 10000);
} else {
token.mint(client, amount * token.rate() / token.mrate());
}
}
/**
* @dev Recursively distribute deposit fee between parents
* @param _node Parent address
* @param _prevPercentage The percentage for previous parent
* @param _depositsCount Count of depositer deposits
* @param _amount The amount of deposit
*/
function distribute(
address _node,
uint _prevPercentage,
uint8 _depositsCount,
uint _amount
)
private
{
address node = _node;
uint prevPercentage = _prevPercentage;
// distribute deposit fee among users above on the branch & update users' statuses
while(node != address(0)) {
uint8 status = data.statuses(node);
// count fee percentage of current node
uint nodePercentage = feeDistribution[status][_depositsCount];
uint percentage = nodePercentage.sub(prevPercentage);
data.addBalance(node, _amount * percentage * 10000);
//update refferals sum amount
data.addReferralDeposit(node, _amount * ethUsdRate / 10**18);
//update status
updateStatus(node, status);
node = data.parentOf(node);
prevPercentage = nodePercentage;
}
}
/**
* @dev Update node status if children sum amount is enough
* @param _node Node address
* @param _status Node current status
*/
function updateStatus(address _node, uint8 _status) private {
uint refDep = data.referralDeposits(_node);
for (uint i = thresholds.length - 1; i > _status; i--) {
uint threshold = thresholds[i] * 100;
if (refDep >= threshold) {
data.setStatus(_node, statusThreshold[threshold]);
break;
}
}
}
/**
* @dev Distribute fee between investors
*/
function distributeInvestorsFee(uint start, uint end) onlyOwner public {
for (uint i = start; i < end; i++) {
address investor = investors.investors(i);
uint investorPercentage = investors.investorPercentages(investor);
data.addInvestorBalance(investor, investorsBalance * investorPercentage);
}
if (end == investors.getInvestorsCount()) {
investorsBalance = 0;
}
}
/**
* @dev Set token exchange rate
* @param _rate wbt/eth rate
*/
function setRate(uint _rate) onlyOwner public {
token.setRate(_rate);
}
/**
* @dev Set ETH exchange rate
* @param _ethUsdRate eth/usd rate
*/
function setEthUsdRate(uint _ethUsdRate) onlyOwner public {
ethUsdRate = _ethUsdRate;
}
/**
* @dev Add new child
* @param _inviter parent
* @param _invitee child
*/
function invite(
address _inviter,
address _invitee
)
public onlyOwner
{
data.setParent(_invitee, _inviter);
// Agent - 0
data.setStatus(_invitee, 0);
}
/**
* @dev Set _status for _addr
* @param _addr address
* @param _status ref. status
*/
function setStatus(address _addr, uint8 _status) public onlyOwner {
data.setStatus(_addr, _status);
}
/**
* @dev Set investors contract address
* @param _addr address
*/
function setInvestors(address _addr) public onlyOwner {
investors = Investors(_addr);
}
/**
* @dev Withdraw _amount for _addr
* @param _addr withdrawal address
* @param _amount withdrawal amount
*/
function withdraw(address _addr, uint256 _amount, bool investor) public onlyOwner {
uint amount = investor ? data.investorBalanceOf(_addr)
: data.balanceOf(_addr);
require(amount >= _amount && this.balance >= _amount);
if (investor) {
data.subtrInvestorBalance(_addr, _amount * 1000000);
} else {
data.subtrBalance(_addr, _amount * 1000000);
}
_addr.transfer(_amount);
}
/**
* @dev Withdraw contract balance to _addr
* @param _addr withdrawal address
*/
function withdrawOwner(address _addr, uint256 _amount) public onlyOwner {
require(this.balance >= _amount);
_addr.transfer(_amount);
}
/**
* @dev Withdraw corresponding amount of ETH to _addr and burn _value tokens
* @param _addr withdrawal address
* @param _amount amount of tokens to sell
*/
function withdrawToken(address _addr, uint256 _amount) onlyOwner public {
token.burn(_addr, _amount);
uint256 etherValue = _amount * token.mrate() / token.rate();
_addr.transfer(etherValue);
}
/**
* @dev Transfer ownership of token contract to _addr
* @param _addr address
*/
function transferTokenOwnership(address _addr) onlyOwner public {
token.transferOwnership(_addr);
}
/**
* @dev Transfer ownership of data contract to _addr
* @param _addr address
*/
function transferDataOwnership(address _addr) onlyOwner public {
data.transferOwnership(_addr);
}
}
contract PChannel is Ownable {
Referral private refProgram;
// fixed deposit amount in USD cents
uint private depositAmount = 100000;
// max deposit amount in USD cents
uint private maxDepositAmount = 125000;
// investor => number of deposits
mapping (address => uint8) private deposits;
function PChannel(address _refProgram) public {
refProgram = Referral(_refProgram);
}
function() payable public {
uint8 depositsCount = deposits[msg.sender];
// check if user has already exceeded 15 deposits limit
require(depositsCount < 15);
uint amount = msg.value;
uint usdAmount = amount * refProgram.ethUsdRate() / 10**18;
// check if deposit amount is valid
require(usdAmount >= depositAmount && usdAmount <= maxDepositAmount);
refProgram.invest.value(amount)(msg.sender, depositsCount);
deposits[msg.sender]++;
}
/**
* @dev Set investors contract address
* @param _addr address
*/
function setRefProgram(address _addr) public onlyOwner {
refProgram = Referral(_addr);
}
} | * @dev Transfer ownership of token contract to _addr @param _addr address/ | function transferTokenOwnership(address _addr) onlyOwner public {
token.transferOwnership(_addr);
}
| 626,893 | [
1,
5912,
23178,
434,
1147,
6835,
358,
389,
4793,
225,
389,
4793,
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
] | [
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,
7412,
1345,
5460,
12565,
12,
2867,
389,
4793,
13,
1338,
5541,
1071,
288,
203,
3639,
1147,
18,
13866,
5460,
12565,
24899,
4793,
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,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-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 "openzeppelin-solidity/contracts/token/ERC721/ERC721Full.sol";
import "./GrantRole.sol";
import "./OperatorRole.sol";
import "./StringUtils.sol";
import "./mocks/EcoCoin.sol";
import "./mocks/Finance.sol";
/**
* @title EcoCert token contract
*
* @dev The EcoCert is a ERC721 non-fungible token. It represents tree ownership and
* interacts with the EcoCoin contract to mint coins according to the implemented harvesting scheme.
* It is designed to interact with aragon's finance app, too.
*/
contract EcoCert is ERC721Full, GrantRole, OperatorRole {
event GrantCertificate(uint256 id, address indexed receiver, address indexed beneficiary, string uri, uint256 value);
event CertificateHarvest(uint256 id, uint256 amount);
using Counters for Counters.Counter;
Counters.Counter private _tokenId;
uint256 private _payoutRate; /// The percentage rate (0-100) of harvested coins that is paid to the EcoCert holder. The other part goes to the DAO's finance app.
/// Essential data about each granted EcoCert token
struct EcoCertData {
uint256 value; /// Amount of coins to be harvested during one year
address beneficiary; /// Address to send the harvested coins for the owner
uint256 harvestTime; /// Last harvesting time
}
mapping(uint256 => EcoCertData) private _data;
EcoCoin public _ecoCoin; /// Link to EcoCoin contract
Finance public _finance; /// Link to DAO's finance app, e.g. from aragon
constructor()
ERC721Full(
"ECO tree certificate",
"ETC"
)
public
{
_payoutRate = 10; /// Standard payout rate is 10% for cert owner, 90% for DAO
}
/**
* @dev Set the address of the EcoCoin contract. In case we have to update the EcoCoin contract,
* this method can be used to keep all certificates valid and work with another contract.
* @param ecoCoin The address of the EcoCoin contract
*/
function setEcoCoinContract(EcoCoin ecoCoin) external onlyOperator {
_ecoCoin = ecoCoin;
}
/**
* @dev Set the address of the finance contract. This should be set to the finance app of the
* DAO so that harvested coins can be sent to the DAO. The interface of the finance app is
* interoperable with aragon's finance app, but it should be easy to adapt it to other interfaces.
* @param finance The address of the finance app.
*/
function setFinanceContract(Finance finance) external onlyOperator {
_finance = finance;
}
/**
* @dev Set the payout rate, that determines how much of the harvested coins are paid to
* the certificate owner. The other part of harvested coins is sent to the DAO (finance).
* @param payoutRate Percentage to be paid to certificate owners, range 0-100
*/
function setPayoutRate(uint256 payoutRate) external onlyGranter {
require(payoutRate <= 100, "EcoCert: set payout rate with invalid parameter");
_payoutRate = payoutRate;
}
/**
* @dev Get the current payout rate. Range 0-100.
* @return payout rate.
*/
function payoutRate() external view returns (uint256) {
return _payoutRate;
}
/**
* @dev Grant a new eco certificate to receiver address.
* @param value The amount of coins that can be harvested per year.
* @param tokenURI URI with additional data about the certificate.
* @param receiver Address to be the owner of the granted certificate.
* @param beneficiary Target address for harvested coins of the owner.
*/
function grant(uint256 value, string calldata tokenURI, address receiver, address beneficiary) external onlyGranter {
_tokenId.increment();
uint256 grantedTokenId = _tokenId.current();
_mint(receiver, grantedTokenId);
_data[grantedTokenId] = EcoCertData(value, beneficiary, now);
_setTokenURI(grantedTokenId, tokenURI);
emit GrantCertificate(grantedTokenId, receiver, beneficiary, tokenURI, value);
}
/**
* @dev Burn an eco certificate.
* @param tokenId ID of the token to be burnt.
*/
function burn(uint256 tokenId) external onlyGranter {
_burn(tokenId);
}
/**
* @dev Set the value of an eco certificate.
* @param tokenId ID of the token to be changed.
* @param value The amount of coins that can be harvested per year.
*/
function setTokenValue(uint256 tokenId, uint256 value) onlyGranter external {
_setTokenValue(tokenId, value);
}
/**
* @dev Set the beneficiary address of an eco certificate.
* @param tokenId ID of the token to be changed.
* @param beneficiary Target address for harvested coins of the owner.
*/
function setTokenBeneficiary(uint256 tokenId, address beneficiary) external {
require(ownerOf(tokenId) == msg.sender, "EcoCert: set token beneficiary called from non-owner");
_setTokenBeneficiary(tokenId, beneficiary);
}
/**
* @dev Returns the value for a given eco certificate ID.
* @param tokenId ID of the token to query.
* @return The amount of coins that can be harvested per year.
*/
function tokenValue(uint256 tokenId) external view returns (uint256) {
require(_exists(tokenId), "EcoCert: value query for nonexistent token");
return _data[tokenId].value;
}
/**
* @dev Returns the beneficiary address for a given eco certificate ID.
* @param tokenId Id of the token to query.
* @return Target address for harvested coins of the owner.
*/
function tokenBeneficiary(uint256 tokenId) external view returns (address) {
require(_exists(tokenId), "EcoCert: beneficiary query for nonexistent token");
return _data[tokenId].beneficiary;
}
/**
* @dev Returns the last time, coins were harvested for a given eco certificate ID.
* @param tokenId Id of the token to query.
* @return Last time (in secs since the epoch) that harvest was called.
*/
function tokenHarvestTime(uint256 tokenId) external view returns (uint256) {
require(_exists(tokenId), "EcoCert: harvest time query for nonexistent token");
return _data[tokenId].harvestTime;
}
/**
* @dev Harvest ECO coins from certificate.
* First, it calculates the amount of coins that are ready for harvesting. This value depends on
* the value of the certificate and the time since the last harvest.
* Then, new coins are minted and distributed to the beneficiary address and the DAO.
* @param tokenId Id of the token to query.
*/
function harvest(uint256 tokenId) external {
require(_exists(tokenId), "EcoCert: harvest for nonexistent token");
// Determine value since last harvest
uint256 value = _data[tokenId].value * (now-_data[tokenId].harvestTime) / (60*60*24*30*12);
// Update harvest time
_data[tokenId].harvestTime = now;
// Send coins to certificate beneficiary
_ecoCoin.mint(_data[tokenId].beneficiary, value * _payoutRate / 100);
// Send coins to DAC finance app
uint256 valueForDao = value * (100 - _payoutRate) / 100;
_ecoCoin.mint(address(this), valueForDao);
_ecoCoin.approve(address(_finance), valueForDao);
_finance.deposit(address(_ecoCoin), valueForDao, StringUtils.strConcat("Harvest certificate #", StringUtils.uint2str(tokenId)));
emit CertificateHarvest(tokenId, value);
}
/**
* @dev Internal function to set the value for a given certificate token.
* Reverts if the token ID does not exist.
* @param tokenId uint256 ID of the token to set its value.
* @param value Value to assign.
*/
function _setTokenValue(uint256 tokenId, uint256 value) internal {
require(_exists(tokenId), "EcoCert: value set of nonexistent token");
_data[tokenId].value = value;
}
/**
* @dev Internal function to set the beneficiary for a given certificate token.
* Reverts if the token ID does not exist.
* @param tokenId uint256 ID of the token to set its beneficiary.
* @param beneficiary Beneficiary address to assign.
*/
function _setTokenBeneficiary(uint256 tokenId, address beneficiary) internal {
require(_exists(tokenId), "EcoCert: beneficiary set of nonexistent token");
_data[tokenId].beneficiary = beneficiary;
}
}
| * @dev Returns the last time, coins were harvested for a given eco certificate ID. @param tokenId Id of the token to query. @return Last time (in secs since the epoch) that harvest was called./ | function tokenHarvestTime(uint256 tokenId) external view returns (uint256) {
require(_exists(tokenId), "EcoCert: harvest time query for nonexistent token");
return _data[tokenId].harvestTime;
}
| 981,931 | [
1,
1356,
326,
1142,
813,
16,
276,
9896,
4591,
17895,
90,
3149,
364,
279,
864,
425,
2894,
4944,
1599,
18,
225,
1147,
548,
3124,
434,
326,
1147,
358,
843,
18,
327,
6825,
813,
261,
267,
18043,
3241,
326,
7632,
13,
716,
17895,
26923,
1703,
2566,
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,
1147,
44,
297,
26923,
950,
12,
11890,
5034,
1147,
548,
13,
3903,
1476,
1135,
261,
11890,
5034,
13,
288,
203,
3639,
2583,
24899,
1808,
12,
2316,
548,
3631,
315,
41,
2894,
5461,
30,
17895,
26923,
813,
843,
364,
1661,
19041,
1147,
8863,
203,
3639,
327,
389,
892,
63,
2316,
548,
8009,
30250,
26923,
950,
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
] |
import './Whitelist.sol';
pragma solidity ^0.4.2;
contract MultiAccessPrecise {
/**
* Codes:
* 1 - tx execution on destination contract has thrown an error
*/
event Error(uint8 errorCode);
/**
* Confirmation event.
* event
* @param owner - The owner address.
* @param operation - The operation name.
* @param completed - If teh operation is completed or not.
*/
event Confirmation(address indexed owner, bytes32 indexed operation, bool completed);
/**
* Revoke event.
* event
* @param owner - The owner address.
* @param operation - The operation name.
*/
event Revoke(address owner, bytes32 operation);
/**
* Owner change event.
* event
* @param oldOwner - The old owner address.
* @param newOwner - The new owner address.
*/
event OwnerChanged(address oldOwner, address newOwner);
/**
* Owner addedd event.
* event
* @param newOwner - The new owner address.
*/
event OwnerAdded(address newOwner);
/**
* Owner removed event.
* event
* @param oldOwner - The old owner address.
*/
event OwnerRemoved(address oldOwner);
/**
* Requirement change event.
* event
* @param newRequirement - The uint of the new requirement.
*/
event RequirementChanged(uint newRequirement);
/**
* Recipient contract requirement change event.
* event
* @param newRecipientRequirement - The uint of the new recipient requirement.
*/
event RecipientRequirementChanged(uint newRecipientRequirement);
/**
* Recipient contract's method requirement change event.
* event
* @param methodSignature - Target method signature
* @param newRecipientMethodRequirement - The uint of the recipient method requirement.
*/
event RecipientMethodRequirementChanged(string methodSignature, uint newRecipientMethodRequirement);
/**
* Recipient contract's method requirement revoked event.
* event
* @param methodSignature - Target method signature
*/
event RecipientMethodRequirementRevoked(string methodSignature);
struct PendingState {
bool[] ownersDone;
uint yetNeeded;
bytes32 op;
}
mapping(bytes32 => uint) pendingIndex;
PendingState[] pending;
address public multiAccessRecipient;
uint public multiAccessRequired;
uint public multiAccessRecipientRequired;
mapping(bytes4 => uint) public multiAccessRecipientMethodRequired;
mapping(address => uint) ownerIndex;
address[] public multiAccessOwners;
Whitelist public whitelist;
/**
* Allow only the owner on msg.sender to exec the function.
* modifier
*/
modifier onlyowner {
if (multiAccessIsOwner(msg.sender)) {
_;
}
}
/**
* Allow only if many owners has agreed to exec the function.
* modifier
*/
modifier ownersThreshold(address _to, bytes _data) {
if (_confirmAndCheck(_to, _data)) {
_;
}
}
modifier ownersThresholdInternal() {
if (_confirmAndCheck(address(this), msg.data)) {
_;
}
}
/**
* Only allow if requirement is in valid range
* modifier
*/
modifier requirementIsValid(uint _newRequirement) {
if (_newRequirement > 0 && _newRequirement < multiAccessOwners.length) {
_;
}
}
/**
* Construct of MultiAccess with the msg.sender and only multiAccessOwner and multiAccessRequired as one.
* constructor
*/
/*function MultiAccessPrecise() {
multiAccessOwners.length = 2;
multiAccessOwners[1] = msg.sender;
ownerIndex[msg.sender] = 1;
multiAccessRequired = 1;
multiAccessRecipientRequired = 1;
pending.length = 1;
whitelist = new Whitelist(new address[](0));
}*/
// Not yet supported for this compiler version
function assert(bool _assertion) {
if (!_assertion) {
throw;
}
}
// Default: new MultiAccessPrecise([msg.sender], 1, 0x0, new address[](0), 1)
function MultiAccessPrecise(
address[] _owners,
uint _internalRequirement,
address _defaultDestination,
address[] _whitelistedDestinations,
uint _destinationRequirement
) {
uint _i; // Reusing
assert(_owners.length != 0);
assert(_internalRequirement > 0);
assert(_destinationRequirement > 0);
assert(_internalRequirement <= _owners.length);
assert(_destinationRequirement <= _owners.length);
// Owners
multiAccessOwners.length = _owners.length + 1; // Cheaper to set full length once
for (_i = 0; _i < _owners.length; _i++) {
assert(ownerIndex[_owners[_i]] == 0); // No duplicates
multiAccessOwners[_i + 1] = _owners[_i];
ownerIndex[_owners[_i]] = _i + 1;
}
// Requirements
multiAccessRequired = _internalRequirement;
multiAccessRecipientRequired = _destinationRequirement;
// Destinations
multiAccessRecipient = _defaultDestination;
whitelist = new Whitelist(_whitelistedDestinations);
pending.length = 1;
}
/**
* Know if an owner has confirmed an operation.
* public_function
* @param _owner - The caller of the function.
* @param _operation - The data array.
*/
function multiAccessHasConfirmed(bytes32 _operation, address _owner) constant returns (bool) {
uint pos = pendingIndex[_operation];
if (pos == 0) {
return false;
}
uint index = ownerIndex[_owner];
var pendingOp = pending[pos];
if (index >= pendingOp.ownersDone.length) {
return false;
}
return pendingOp.ownersDone[index];
}
/**
* Confirm an operation.
* internalfunction
* @param _to - tx destination address
* @param _data - raw data to be sent for execution onto destination contract
*/
function _confirmAndCheck(address _to, bytes _data) onlyowner() internal returns (bool) {
bytes32 operation = sha3(_to, _data);
uint index = ownerIndex[msg.sender];
if (multiAccessHasConfirmed(operation, msg.sender)) {
return false;
}
var pos = pendingIndex[operation];
if (pos == 0) {
bytes4 _methodId = bytes4(uint8(_data[0]) * 2**24 + uint8(_data[1]) * 2**16 + uint8(_data[2]) * 2**8 + uint8(_data[3]));
pos = pending.length++;
pending[pos].yetNeeded = _getRequirement(_to, _methodId);
pending[pos].op = operation;
pendingIndex[operation] = pos;
}
var pendingOp = pending[pos];
if (pendingOp.yetNeeded <= 1) {
Confirmation(msg.sender, operation, true);
if (pos < pending.length-1) {
PendingState last = pending[pending.length-1];
pending[pos] = last;
pendingIndex[last.op] = pos;
}
pending.length--;
delete pendingIndex[operation];
return true;
} else {
Confirmation(msg.sender, operation, false);
pendingOp.yetNeeded--;
if (index >= pendingOp.ownersDone.length) {
pendingOp.ownersDone.length = index+1;
}
pendingOp.ownersDone[index] = true;
}
return false;
}
/**
* Calculate number of signatures required for the provided execution
* internalfunction
*/
function _getRequirement(address _to, bytes4 _methodId) internal returns (uint) {
if (_to == address(this)) { // Internal call
return multiAccessRequired;
}
else if (_to != multiAccessRecipient && !whitelist.isWhitelisted(_to)) { // To unknown contract, max requirement
return multiAccessRequired;
}
// Whitelisted destinations
else if (multiAccessRecipientMethodRequired[_methodId] > 0) { // Method requirement configured
return multiAccessRecipientMethodRequired[_methodId];
}
else { // Generic call to any destination method
return multiAccessRecipientRequired;
}
}
/**
* Remove all the pending operations.
* internalfunction
*/
function _clearPending() internal {
uint length = pending.length;
// uint 0 - 1 == MAX_VAL
// This check is cheaper than to convert to int
if (length == 0) {
return;
}
for (uint i = length - 1; i > 0; --i) {
delete pendingIndex[pending[i].op];
pending.length--;
}
}
// Arbitrary whitelisted destination tx can be executed with custom requirement
function whitelistDestination(address _destination)
ownersThresholdInternal
external {
whitelist.add(_destination);
}
function revokeWhitelistedDestination(address _destination)
ownersThresholdInternal
external {
whitelist.remove(_destination);
}
/**
* Know if an address is an multiAccessOwner.
* public_function
* @param _addr - The operation name.
*/
function multiAccessIsOwner(address _addr) constant returns (bool) {
return ownerIndex[_addr] > 0;
}
/**
* Revoke a vote from an operation.
* public_function
* @param _operation -The operation name.
*/
function multiAccessRevoke(bytes32 _operation) onlyowner() external {
uint index = ownerIndex[msg.sender];
if (!multiAccessHasConfirmed(_operation, msg.sender)) {
return;
}
var pendingOp = pending[pendingIndex[_operation]];
pendingOp.ownersDone[index] = false;
pendingOp.yetNeeded++;
Revoke(msg.sender, _operation);
}
/**
* Change the address of one owner.
* external_function
* @param _from - The old address.
* @param _to - The new address.
*/
function multiAccessChangeOwner(address _from, address _to) ownersThresholdInternal external {
if (multiAccessIsOwner(_to)) {
return;
}
uint index = ownerIndex[_from];
if (index == 0) {
return;
}
_clearPending();
multiAccessOwners[index] = _to;
delete ownerIndex[_from];
ownerIndex[_to] = index;
OwnerChanged(_from, _to);
}
/**
* Add a owner.
* external_function
* @param _owner - The address to add.
*/
function multiAccessAddOwner(address _owner) ownersThresholdInternal external {
if (multiAccessIsOwner(_owner)) {
return;
}
uint pos = multiAccessOwners.length++;
multiAccessOwners[pos] = _owner;
ownerIndex[_owner] = pos;
OwnerAdded(_owner);
}
/**
* Remove a owner.
* external_function
* @param _owner - The address to remove.
*/
function multiAccessRemoveOwner(address _owner) ownersThresholdInternal external {
uint index = ownerIndex[_owner];
if (index == 0) {
return;
}
if (multiAccessRequired >= multiAccessOwners.length-1) {
return;
}
if (index < multiAccessOwners.length-1) {
address last = multiAccessOwners[multiAccessOwners.length-1];
multiAccessOwners[index] = last;
ownerIndex[last] = index;
}
multiAccessOwners.length--;
delete ownerIndex[_owner];
_clearPending();
OwnerRemoved(_owner);
}
/**
* Change the requirement.
* external_function
* @param _newRequired - The new amount of required signatures.
*/
function multiAccessChangeRequirement(uint _newRequired)
ownersThresholdInternal
requirementIsValid(_newRequired)
external
{
multiAccessRequired = _newRequired;
_clearPending();
RequirementChanged(_newRequired);
}
/**
* Change the recipient requirement.
* external_function
* @param _newRecipientRequired - The new amount of recipient required signatures.
*/
function multiAccessChangeRecipientRequirement(uint _newRecipientRequired)
ownersThresholdInternal
requirementIsValid(_newRecipientRequired)
external
{
multiAccessRecipientRequired = _newRecipientRequired;
_clearPending();
RecipientRequirementChanged(_newRecipientRequired);
}
/**
* Change the recipient method requirement.
* external_function
* @param _methodSignature - Signature of the target method. E.g.: doSomething(bytes4,uint32)
* Use explicit data types. For ex. instead of uint use uint256
* @param _newRecipientMethodRequired - The new amount of recipient method required signatures.
*/
function multiAccessChangeRecipientMethodRequirement(string _methodSignature, uint _newRecipientMethodRequired)
ownersThresholdInternal
requirementIsValid(_newRecipientMethodRequired)
external
{
var _methodId = bytes4(sha3(_methodSignature));
multiAccessRecipientMethodRequired[_methodId] = _newRecipientMethodRequired;
_clearPending();
RecipientMethodRequirementChanged(_methodSignature, _newRecipientMethodRequired);
}
/**
* Revoke the recipient method requirement.
* external_function
* @param _methodSignature - Signature of the target method. E.g.: doSomething(bytes4,uint32)
* Use explicit data types. For ex. instead of uint use uint256
*/
function multiAccessRevokeRecipientMethodRequirement(string _methodSignature)
ownersThresholdInternal
external
{
var _methodId = bytes4(sha3(_methodSignature));
// Requirement not exists
if (multiAccessRecipientMethodRequired[_methodId] == 0) {
throw;
}
delete multiAccessRecipientMethodRequired[_methodId];
_clearPending();
RecipientMethodRequirementRevoked(_methodSignature);
}
/**
* Set the recipient.
* public_function
* @param _address - The multiAccessRecipient address.
*/
function multiAccessSetRecipient(address _address) ownersThresholdInternal returns (bool _success) {
if (multiAccessRecipient == _address) {
return true;
}
multiAccessRecipient = _address;
_clearPending();
return true;
}
/*
* Call arbitrary address.
* public_function
* @param _to - The address to call.
* @param _value - The value of wei to send with the call.
* @param _data - Message data to send with the call.
*/
/*function multiAccessCall(address _to, uint _value, bytes _data) onlymanyowners(true) returns(bool _success) {
return _to.call.value(_value)(_data);
}*/
// To any address
function execute(address _to, bytes _data) ownersThreshold(_to, _data) returns(bool _success) {
if (_data.length > 0 ) {
return _to.call(_data);
}
}
function() ownersThreshold(multiAccessRecipient, msg.data) {
if (msg.data.length > 0) {
if (!multiAccessRecipient.call(msg.data)) {
Error(1);
}
}
}
}
| Call arbitrary address. public_function @param _to - The address to call. @param _value - The value of wei to send with the call. @param _data - Message data to send with the call./function multiAccessCall(address _to, uint _value, bytes _data) onlymanyowners(true) returns(bool _success) { | return _to.call.value(_value)(_data);
| 13,010,535 | [
1,
1477,
11078,
1758,
18,
1071,
67,
915,
225,
389,
869,
300,
1021,
1758,
358,
745,
18,
225,
389,
1132,
300,
1021,
460,
434,
732,
77,
358,
1366,
598,
326,
745,
18,
225,
389,
892,
300,
2350,
501,
358,
1366,
598,
326,
745,
18,
19,
915,
3309,
1862,
1477,
12,
2867,
389,
869,
16,
2254,
389,
1132,
16,
1731,
389,
892,
13,
1338,
9353,
995,
414,
12,
3767,
13,
1135,
12,
6430,
389,
4768,
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,
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,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
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,
389,
869,
18,
1991,
18,
1132,
24899,
1132,
21433,
67,
892,
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,
-100,
-100
] |
// SPDX-License-Identifier: UNLICENSED
pragma solidity 0.8.7;
/*
██████╗ ███████╗ █████╗ ██╗ ██╗████████╗██╗ ██╗ ██████╗ █████╗ ██████╗ ██████╗ ███████╗
██╔══██╗██╔════╝██╔══██╗██║ ██║╚══██╔══╝╚██╗ ██╔╝██╔════╝██╔══██╗██╔══██╗██╔══██╗██╔════╝
██████╔╝█████╗ ███████║██║ ██║ ██║ ╚████╔╝ ██║ ███████║██████╔╝██║ ██║███████╗
██╔══██╗██╔══╝ ██╔══██║██║ ██║ ██║ ╚██╔╝ ██║ ██╔══██║██╔══██╗██║ ██║╚════██║
██║ ██║███████╗██║ ██║███████╗██║ ██║ ██║ ╚██████╗██║ ██║██║ ██║██████╔╝███████║
╚═╝ ╚═╝╚══════╝╚═╝ ╚═╝╚══════╝╚═╝ ╚═╝ ╚═╝ ╚═════╝╚═╝ ╚═╝╚═╝ ╚═╝╚═════╝ ╚══════╝
*/
import "@openzeppelin/contracts/access/AccessControl.sol";
import "@openzeppelin/contracts/utils/math/SafeCast.sol";
import "@openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol";
import "hardhat/console.sol";
import "./lib/NativeMetaTransaction.sol";
import "./interfaces/IRCTreasury.sol";
import "./interfaces/IRCMarket.sol";
import "./interfaces/IRCOrderbook.sol";
import "./interfaces/IRCNftHubL2.sol";
import "./interfaces/IRCFactory.sol";
import "./interfaces/IRCBridge.sol";
/// @title Reality Cards Treasury
/// @author Andrew Stanger & Daniel Chilvers
/// @notice If you have found a bug, please contact [email protected] no hack pls!!
contract RCTreasury is AccessControl, NativeMetaTransaction, IRCTreasury {
using SafeERC20 for IERC20;
/*╔═════════════════════════════════╗
║ VARIABLES ║
╚═════════════════════════════════╝*/
/// @dev orderbook instance, to remove users bids on foreclosure
IRCOrderbook public override orderbook;
/// @dev leaderboard instance
IRCLeaderboard public override leaderboard;
/// @dev token contract
IERC20 public override erc20;
/// @dev the Factory so only the Factory can add new markets
IRCFactory public override factory;
/// @dev address of (as yet non existent) Bridge for withdrawals to mainnet
address public override bridgeAddress;
/// @dev sum of all deposits
uint256 public override totalDeposits;
/// @dev the rental payments made in each market
mapping(address => uint256) public override marketPot;
/// @dev sum of all market pots
uint256 public override totalMarketPots;
/// @dev rent taken and allocated to a particular market
uint256 public override marketBalance;
/// @dev a quick check if a user is foreclosed
mapping(address => bool) public override isForeclosed;
/// @dev to keep track of the size of the rounding issue between rent collections
uint256 public override marketBalanceTopup;
/// @param deposit the users current deposit in wei
/// @param rentalRate the daily cost of the cards the user current owns
/// @param bidRate the sum total of all placed bids
/// @param lastRentCalc The timestamp of the users last rent calculation
/// @param lastRentalTime The timestamp the user last made a rental
struct User {
uint128 deposit;
uint128 rentalRate;
uint128 bidRate;
uint64 lastRentCalc;
uint64 lastRentalTime;
}
mapping(address => User) public user;
/*╔═════════════════════════════════╗
║ GOVERNANCE VARIABLES ║
╚═════════════════════════════════╝*/
/// @dev only parameters that need to be are here, the rest are in the Factory
/// @dev minimum rental duration (1 day divisor: i.e. 24 = 1 hour, 48 = 30 mins)
uint256 public override minRentalDayDivisor;
/// @dev max deposit balance, to minimise funds at risk
uint256 public override maxContractBalance;
/// @dev whitelist to only allow certain addresses to deposit
/// @dev intended for beta use only, will be disabled after launch
mapping(address => bool) public isAllowed;
bool public whitelistEnabled;
/// @dev allow markets to be restricted to a certain role
mapping(address => bytes32) public marketWhitelist;
/// @dev to test if the uberOwner multisig all still have access they
/// @dev .. will periodically be asked to update this variable.
uint256 public override uberOwnerCheckTime;
/*╔═════════════════════════════════╗
║ SAFETY ║
╚═════════════════════════════════╝*/
/// @dev if true, cannot deposit, withdraw or rent any cards across all events
bool public override globalPause;
/// @dev if true, cannot rent, claim or upgrade any cards for specific market
mapping(address => bool) public override marketPaused;
/// @dev if true, owner has locked the market pause (Governors are locked out)
mapping(address => bool) public override lockMarketPaused;
/*╔═════════════════════════════════╗
║ Access Control ║
╚═════════════════════════════════╝*/
bytes32 public constant UBER_OWNER = keccak256("UBER_OWNER");
bytes32 public constant OWNER = keccak256("OWNER");
bytes32 public constant GOVERNOR = keccak256("GOVERNOR");
bytes32 public constant FACTORY = keccak256("FACTORY");
bytes32 public constant MARKET = keccak256("MARKET");
bytes32 public constant TREASURY = keccak256("TREASURY");
bytes32 public constant ORDERBOOK = keccak256("ORDERBOOK");
bytes32 public constant WHITELIST = keccak256("WHITELIST");
bytes32 public constant ARTIST = keccak256("ARTIST");
bytes32 public constant AFFILIATE = keccak256("AFFILIATE");
bytes32 public constant CARD_AFFILIATE = keccak256("CARD_AFFILIATE");
/*╔═════════════════════════════════╗
║ EVENTS ║
╚═════════════════════════════════╝*/
event LogUserForeclosed(address indexed user, bool indexed foreclosed);
event LogAdjustDeposit(
address indexed user,
uint256 indexed amount,
bool increase
);
event LogMarketPaused(address market, bool paused);
event LogGlobalPause(bool paused);
event LogMarketWhitelist(address _market, bytes32 role);
/*╔═════════════════════════════════╗
║ CONSTRUCTOR ║
╚═════════════════════════════════╝*/
constructor(address _tokenAddress) {
// initialise MetaTransactions
_initializeEIP712("RealityCardsTreasury", "1");
/* setup AccessControl
UBER_OWNER
┌───────────┬────┴─────┬────────────┐
│ │ │ │
OWNER FACTORY ORDERBOOK TREASURY
│ │
GOVERNOR MARKET
│
WHITELIST | ARTIST | AFFILIATE | CARD_AFFILIATE
*/
_setupRole(DEFAULT_ADMIN_ROLE, msgSender());
_setupRole(UBER_OWNER, msgSender());
_setupRole(OWNER, msgSender());
_setupRole(GOVERNOR, msgSender());
_setupRole(WHITELIST, msgSender());
_setupRole(TREASURY, address(this));
_setRoleAdmin(UBER_OWNER, UBER_OWNER);
_setRoleAdmin(OWNER, UBER_OWNER);
_setRoleAdmin(FACTORY, UBER_OWNER);
_setRoleAdmin(ORDERBOOK, UBER_OWNER);
_setRoleAdmin(TREASURY, UBER_OWNER);
_setRoleAdmin(GOVERNOR, OWNER);
_setRoleAdmin(WHITELIST, GOVERNOR);
_setRoleAdmin(ARTIST, GOVERNOR);
_setRoleAdmin(AFFILIATE, GOVERNOR);
_setRoleAdmin(CARD_AFFILIATE, GOVERNOR);
_setRoleAdmin(MARKET, FACTORY);
// initialise adjustable parameters
setMinRental(24 * 6); // MinRental is a divisor of 1 day(86400 seconds), 24*6 will set to 10 minutes
setMaxContractBalance(1_000_000 ether); // 1m
setTokenAddress(_tokenAddress);
whitelistEnabled = true;
}
/*╔═════════════════════════════════╗
║ MODIFIERS ║
╚═════════════════════════════════╝*/
/// @notice check that funds haven't gone missing during this function call
modifier balancedBooks() {
_;
/// @dev using >= not == in case anyone sends tokens direct to contract
require(
erc20.balanceOf(address(this)) >=
totalDeposits + marketBalance + totalMarketPots,
"Books are unbalanced!"
);
}
/*╔═════════════════════════════════╗
║ GOVERNANCE - OWNER ║
╚═════════════════════════════════╝*/
/// @dev all functions should be onlyRole(OWNER)
// min rental event emitted by market. Nothing else need be emitted.
/*┌────────────────────────────────────┐
│ CALLED WITHIN CONSTRUCTOR - PUBLIC │
└────────────────────────────────────┘*/
/// @notice minimum rental duration (1 day divisor: i.e. 24 = 1 hour, 48 = 30 mins)
/// @param _newDivisor the divisor to set
function setMinRental(uint256 _newDivisor) public override onlyRole(OWNER) {
minRentalDayDivisor = _newDivisor;
}
/// @notice set max deposit balance, to minimise funds at risk
/// @dev this is only a soft check, it is possible to exceed this limit
/// @param _newBalanceLimit the max balance to set in wei
function setMaxContractBalance(uint256 _newBalanceLimit)
public
override
onlyRole(OWNER)
{
maxContractBalance = _newBalanceLimit;
}
/*┌──────────────────────────────────────────┐
│ NOT CALLED WITHIN CONSTRUCTOR - EXTERNAL │
└──────────────────────────────────────────┘*/
/// @notice if true, cannot deposit, withdraw or rent any cards
function changeGlobalPause() external override onlyRole(OWNER) {
globalPause = !globalPause;
emit LogGlobalPause(globalPause);
}
/// @notice if true, cannot make a new rental, or claim the NFT for a specific market
/// @param _market The
function changePauseMarket(address _market, bool _paused)
external
override
onlyRole(OWNER)
{
require(hasRole(MARKET, _market), "This isn't a market");
marketPaused[_market] = _paused;
lockMarketPaused[_market] = marketPaused[_market];
emit LogMarketPaused(_market, marketPaused[_market]);
}
/// @notice allow governance (via the factory) to approve and un pause the market if the owner hasn't paused it
function unPauseMarket(address _market)
external
override
onlyRole(FACTORY)
{
require(hasRole(MARKET, _market), "This isn't a market");
require(!lockMarketPaused[_market], "Owner has paused market");
marketPaused[_market] = false;
emit LogMarketPaused(_market, marketPaused[_market]);
}
/*╔═════════════════════════════════╗
║ WHITELIST FUNCTIONS ║
╚═════════════════════════════════╝*/
// There are 2 whitelist functionalities here,
// 1. a whitelist for users to enter the system, restrict deposits.
// 2. a market specific whitelist, restrict rentals on certain markets to certain users.
/// @notice if true, users must be on the whitelist to deposit
function toggleWhitelist() external override onlyRole(OWNER) {
whitelistEnabled = !whitelistEnabled;
}
/// @notice Add/Remove multiple users to the whitelist
/// @param _users an array of users to add or remove
/// @param add true to add the users
function batchWhitelist(address[] calldata _users, bool add)
external
override
onlyRole(GOVERNOR)
{
if (add) {
for (uint256 index = 0; index < _users.length; index++) {
RCTreasury.grantRole(WHITELIST, _users[index]);
}
} else {
for (uint256 index = 0; index < _users.length; index++) {
RCTreasury.revokeRole(WHITELIST, _users[index]);
}
}
}
/// @notice to implement (or remove) a market specific whitelist
/// @param _market the market to affect
/// @param _role the role required for this market
/// @dev it'd be nice to pass the role as a string but then we couldn't reset this
function updateMarketWhitelist(address _market, bytes32 _role)
external
onlyRole(GOVERNOR)
{
marketWhitelist[_market] = _role;
emit LogMarketWhitelist(_market, _role);
}
/// @notice Some markets may be restricted to certain roles,
/// @notice This function checks if the user has the role required for a given market
/// @dev Used for the markets to check themselves
/// @param _user The user to check
function marketWhitelistCheck(address _user)
external
view
override
returns (bool)
{
bytes32 requiredRole = marketWhitelist[msgSender()];
if (requiredRole == bytes32(0)) {
return true;
} else {
return hasRole(requiredRole, _user);
}
}
/*╔═════════════════════════════════╗
║ GOVERNANCE - UBER OWNER ║
╠═════════════════════════════════╣
║ ******** DANGER ZONE ******** ║
╚═════════════════════════════════╝*/
/// @dev uber owner required for upgrades
/// @dev deploying and setting a new factory is effectively an upgrade
/// @dev this is separate so owner so can be set to multisig, or burn address to relinquish upgrade ability
/// @dev ... while maintaining governance over other governance functions
/// @notice Simply updates a variable with the current block.timestamp used
/// @notice .. to check the uberOwner multisig controllers all still have access.
function uberOwnerTest() external override onlyRole(UBER_OWNER) {
uberOwnerCheckTime = block.timestamp;
}
function setFactoryAddress(address _newFactory)
external
override
onlyRole(UBER_OWNER)
{
require(_newFactory != address(0), "Must set an address");
// factory is also an OWNER and GOVERNOR to use the proxy functions
revokeRole(FACTORY, address(factory));
revokeRole(OWNER, address(factory));
revokeRole(GOVERNOR, address(factory));
factory = IRCFactory(_newFactory);
grantRole(FACTORY, address(factory));
grantRole(OWNER, address(factory));
grantRole(GOVERNOR, address(factory));
}
/// @notice To set the orderbook address
/// @dev changing this while markets are active could prove disastrous
function setOrderbookAddress(address _newOrderbook)
external
override
onlyRole(UBER_OWNER)
{
require(_newOrderbook != address(0), "Must set an address");
revokeRole(ORDERBOOK, address(orderbook));
orderbook = IRCOrderbook(_newOrderbook);
grantRole(ORDERBOOK, address(orderbook));
factory.setOrderbookAddress(orderbook);
}
/// @notice To set the leaderboard address
/// @dev The treasury doesn't need the leaderboard, just setting
/// @dev .. here to keep the setters in the same place.
function setLeaderboardAddress(address _newLeaderboard)
external
override
onlyRole(UBER_OWNER)
{
require(_newLeaderboard != address(0), "Must set an address");
leaderboard = IRCLeaderboard(_newLeaderboard);
factory.setLeaderboardAddress(leaderboard);
}
/// @notice To change the ERC20 token.
/// @dev changing this while tokens have been deposited could prove disastrous
function setTokenAddress(address _newToken)
public
override
onlyRole(UBER_OWNER)
{
require(_newToken != address(0), "Must set an address");
erc20 = IERC20(_newToken);
}
/// @notice To set the bridge address and approve token transfers
function setBridgeAddress(address _newBridge)
external
override
onlyRole(UBER_OWNER)
{
require(_newBridge != address(0), "Must set an address");
bridgeAddress = _newBridge;
erc20.approve(_newBridge, type(uint256).max);
}
/// @notice Disaster recovery, pulls all funds from the Treasury to the UberOwner
function globalExit() external onlyRole(UBER_OWNER) {
uint256 _balance = erc20.balanceOf(address(this));
/// @dev using msg.sender instead of msgSender as a precaution should Meta-Tx be compromised
erc20.safeTransfer(msg.sender, _balance);
}
/*╔═════════════════════════════════╗
║ DEPOSIT AND WITHDRAW FUNCTIONS ║
╚═════════════════════════════════╝*/
/// @notice deposit tokens into RealityCards
/// @dev it is passed the user instead of using msg.sender because might be called
/// @dev ... via contract or Layer1->Layer2 bot
/// @param _user the user to credit the deposit to
/// @param _amount the amount to deposit, must be approved
function deposit(uint256 _amount, address _user)
external
override
balancedBooks
returns (bool)
{
require(!globalPause, "Deposits are disabled");
require(
erc20.allowance(msgSender(), address(this)) >= _amount,
"User not approved to send this amount"
);
require(
(erc20.balanceOf(address(this)) + _amount) <= maxContractBalance,
"Limit hit"
);
require(_amount > 0, "Must deposit something");
if (whitelistEnabled) {
require(hasRole(WHITELIST, _user), "Not in whitelist");
}
// do some cleaning up, it might help cancel their foreclosure
orderbook.removeOldBids(_user);
user[_user].deposit += SafeCast.toUint128(_amount);
totalDeposits += _amount;
erc20.safeTransferFrom(msgSender(), address(this), _amount);
emit LogAdjustDeposit(_user, _amount, true);
// this deposit could cancel the users foreclosure
assessForeclosure(_user);
return true;
}
/// @notice withdraw a users deposit either directly or over the bridge to the mainnet
/// @dev this is the only function where funds leave the contract
/// @param _amount the amount to withdraw
/// @param _localWithdrawal if true then withdraw to the users address, otherwise to the bridge
function withdrawDeposit(uint256 _amount, bool _localWithdrawal)
external
override
balancedBooks
{
require(!globalPause, "Withdrawals are disabled");
address _msgSender = msgSender();
require(user[_msgSender].deposit > 0, "Nothing to withdraw");
// only allow withdraw if they have no bids,
// OR they've had their cards for at least the minimum rental period
require(
user[_msgSender].bidRate == 0 ||
block.timestamp - (user[_msgSender].lastRentalTime) >
uint256(1 days) / minRentalDayDivisor,
"Too soon"
);
// step 1: collect rent on owned cards
collectRentUser(_msgSender, block.timestamp);
// step 2: process withdrawal
if (_amount > user[_msgSender].deposit) {
_amount = user[_msgSender].deposit;
}
emit LogAdjustDeposit(_msgSender, _amount, false);
user[_msgSender].deposit -= SafeCast.toUint128(_amount);
totalDeposits -= _amount;
if (_localWithdrawal) {
erc20.safeTransfer(_msgSender, _amount);
} else {
IRCBridge bridge = IRCBridge(bridgeAddress);
bridge.withdrawToMainnet(_msgSender, _amount);
}
// step 3: remove bids if insufficient deposit
// do some cleaning up first, it might help avoid their foreclosure
orderbook.removeOldBids(_msgSender);
if (
user[_msgSender].bidRate != 0 &&
user[_msgSender].bidRate / (minRentalDayDivisor) >
user[_msgSender].deposit
) {
// foreclose user, this is requred to remove them from the orderbook
isForeclosed[_msgSender] = true;
// remove them from the orderbook
orderbook.removeUserFromOrderbook(_msgSender);
}
}
/// @notice to increase the market balance
/// @dev not strictly required but prevents markets being short-changed due to rounding issues
function topupMarketBalance(uint256 _amount)
external
override
balancedBooks
{
marketBalanceTopup += _amount;
marketBalance += _amount;
erc20.safeTransferFrom(msgSender(), address(this), _amount);
}
/*╔═════════════════════════════════╗
║ ERC20 helpers ║
╚═════════════════════════════════╝*/
/// @notice allow and balance check
/// @dev used for the Factory to check before spending too much gas
function checkSponsorship(address sender, uint256 _amount)
external
view
override
{
require(
erc20.allowance(sender, address(this)) >= _amount,
"Insufficient Allowance"
);
require(erc20.balanceOf(sender) >= _amount, "Insufficient Balance");
}
/*╔═════════════════════════════════╗
║ MARKET CALLABLE ║
╚═════════════════════════════════╝*/
// only markets can call these functions
/// @notice a rental payment is equivalent to moving from user's deposit to market pot,
/// @notice ..called by _collectRent in the market
/// @param _amount amount of rent to pay in wei
function payRent(uint256 _amount)
external
override
balancedBooks
onlyRole(MARKET)
returns (uint256)
{
require(!globalPause, "Rentals are disabled");
if (marketBalance < _amount) {
uint256 discrepancy = _amount - marketBalance;
if (discrepancy > marketBalanceTopup) {
marketBalanceTopup = 0;
} else {
marketBalanceTopup -= discrepancy;
}
_amount = marketBalance;
}
address _market = msgSender();
marketBalance -= _amount;
marketPot[_market] += _amount;
totalMarketPots += _amount;
/// @dev return the amount just in case it was adjusted
return _amount;
}
/// @notice a payout is equivalent to moving from market pot to user's deposit (the opposite of payRent)
/// @param _user the user to query
/// @param _amount amount to payout in wei
function payout(address _user, uint256 _amount)
external
override
balancedBooks
onlyRole(MARKET)
returns (bool)
{
require(!globalPause, "Payouts are disabled");
user[_user].deposit += SafeCast.toUint128(_amount);
marketPot[msgSender()] -= _amount;
totalMarketPots -= _amount;
totalDeposits += _amount;
assessForeclosure(_user);
emit LogAdjustDeposit(_user, _amount, true);
return true;
}
/// @dev called by _collectRentAction() in the market in situations where collectRentUser() collected too much rent
function refundUser(address _user, uint256 _refund)
external
override
balancedBooks
onlyRole(MARKET)
{
marketBalance -= _refund;
user[_user].deposit += SafeCast.toUint128(_refund);
totalDeposits += _refund;
emit LogAdjustDeposit(_user, _refund, true);
assessForeclosure(_user);
}
/// @notice ability to add liquidity to the pot without being able to win (called by market sponsor function).
function sponsor(address _sponsor, uint256 _amount)
external
override
balancedBooks
onlyRole(MARKET)
{
require(!globalPause, "Global Pause is Enabled");
address _market = msgSender();
require(!lockMarketPaused[_market], "Market is paused");
require(
erc20.allowance(_sponsor, address(this)) >= _amount,
"Not approved to send this amount"
);
marketPot[_market] += _amount;
totalMarketPots += _amount;
erc20.safeTransferFrom(_sponsor, address(this), _amount);
}
/// @notice tracks when the user last rented- so they cannot rent and immediately withdraw,
/// @notice ..thus bypassing minimum rental duration
/// @param _user the user to query
function updateLastRentalTime(address _user)
external
override
onlyRole(MARKET)
{
// update the last rental time
user[_user].lastRentalTime = SafeCast.toUint64(block.timestamp);
// check if this is their first rental (no previous rental calculation)
if (user[_user].lastRentCalc == 0) {
// we need to start their clock ticking, update their last rental calculation time
user[_user].lastRentCalc = SafeCast.toUint64(block.timestamp);
}
}
/*╔═════════════════════════════════╗
║ MARKET HELPERS ║
╚═════════════════════════════════╝*/
/// @notice Allows the factory to add a new market to AccessControl
/// @dev Also controls the default paused state
/// @param _market The market address to add
/// @param _paused If the market should be paused or not
function addMarket(address _market, bool _paused) external override {
require(hasRole(FACTORY, msgSender()), "Not Authorised");
marketPaused[_market] = _paused;
AccessControl.grantRole(MARKET, _market);
emit LogMarketPaused(_market, marketPaused[_market]);
}
/// @notice provides the sum total of a users bids across all markets (whether active or not)
/// @param _user the user address to query
function userTotalBids(address _user)
external
view
override
returns (uint256)
{
return user[_user].bidRate;
}
/// @notice provide the users remaining deposit
/// @param _user the user address to query
function userDeposit(address _user)
external
view
override
returns (uint256)
{
return uint256(user[_user].deposit);
}
/*╔═════════════════════════════════╗
║ ORDERBOOK CALLABLE ║
╚═════════════════════════════════╝*/
/// @notice updates users rental rates when ownership changes
/// @dev rentalRate = sum of all active bids
/// @param _oldOwner the address of the user losing ownership
/// @param _newOwner the address of the user gaining ownership
/// @param _oldPrice the price the old owner was paying
/// @param _newPrice the price the new owner will be paying
/// @param _timeOwnershipChanged the timestamp of this event
function updateRentalRate(
address _oldOwner,
address _newOwner,
uint256 _oldPrice,
uint256 _newPrice,
uint256 _timeOwnershipChanged
) external override onlyRole(ORDERBOOK) {
if (
_timeOwnershipChanged != user[_newOwner].lastRentCalc &&
!hasRole(MARKET, _newOwner)
) {
// The new owners rent must be collected before adjusting their rentalRate
// See if the new owner has had a rent collection before or after this ownership change
if (_timeOwnershipChanged < user[_newOwner].lastRentCalc) {
// the new owner has a more recent rent collection
uint256 _additionalRentOwed = rentOwedBetweenTimestamps(
user[_newOwner].lastRentCalc,
_timeOwnershipChanged,
_newPrice
);
// they have enough funds, just collect the extra
// we can be sure of this because it was checked they can cover the minimum rental
_increaseMarketBalance(_additionalRentOwed, _newOwner);
emit LogAdjustDeposit(_newOwner, _additionalRentOwed, false);
} else {
// the new owner has an old rent collection, do they own anything else?
if (user[_newOwner].rentalRate != 0) {
// rent collect up-to ownership change time
collectRentUser(_newOwner, _timeOwnershipChanged);
} else {
// first card owned, set start time
user[_newOwner].lastRentCalc = SafeCast.toUint64(
_timeOwnershipChanged
);
// send an event for the UI to have a timestamp
emit LogAdjustDeposit(_newOwner, 0, false);
}
}
}
// Must add before subtract, to avoid underflow in the case a user is only updating their price.
user[_newOwner].rentalRate += SafeCast.toUint128(_newPrice);
user[_oldOwner].rentalRate -= SafeCast.toUint128(_oldPrice);
}
/// @dev increase bidRate when new bid entered
function increaseBidRate(address _user, uint256 _price)
external
override
onlyRole(ORDERBOOK)
{
user[_user].bidRate += SafeCast.toUint128(_price);
}
/// @dev decrease bidRate when bid removed
function decreaseBidRate(address _user, uint256 _price)
external
override
onlyRole(ORDERBOOK)
{
user[_user].bidRate -= SafeCast.toUint128(_price);
}
/*╔═════════════════════════════════╗
║ RENT CALC HELPERS ║
╚═════════════════════════════════╝*/
/// @notice returns the rent due between the users last rent calculation and
/// @notice ..the current block.timestamp for all cards a user owns
/// @param _user the user to query
/// @param _timeOfCollection calculate up to a given time
function rentOwedUser(address _user, uint256 _timeOfCollection)
internal
view
returns (uint256 rentDue)
{
return
(user[_user].rentalRate *
(_timeOfCollection - user[_user].lastRentCalc)) / (1 days);
}
/// @notice calculates the rent owed between the given timestamps
/// @param _time1 one of the timestamps
/// @param _time2 the second timestamp
/// @param _price the rental rate for this time period
/// @return _rent the rent due for this time period
/// @dev the timestamps can be given in any order
function rentOwedBetweenTimestamps(
uint256 _time1,
uint256 _time2,
uint256 _price
) internal pure returns (uint256 _rent) {
if (_time1 < _time2) {
(_time1, _time2) = (_time2, _time1);
}
_rent = (_price * (_time1 - _time2)) / (1 days);
}
/// @notice returns the current estimate of the users foreclosure time
/// @param _user the user to query
/// @param _newBid calculate foreclosure including a new card
/// @param _timeOfNewBid timestamp of when a new card was gained
function foreclosureTimeUser(
address _user,
uint256 _newBid,
uint256 _timeOfNewBid
) external view override returns (uint256) {
uint256 totalUserDailyRent = user[_user].rentalRate;
if (totalUserDailyRent > 0) {
uint256 timeLeftOfDeposit = (user[_user].deposit * 1 days) /
totalUserDailyRent;
uint256 foreclosureTimeWithoutNewCard = user[_user].lastRentCalc +
timeLeftOfDeposit;
if (
foreclosureTimeWithoutNewCard > _timeOfNewBid &&
_timeOfNewBid != 0
) {
// calculate how long they can own the new card for
uint256 _rentDifference = rentOwedBetweenTimestamps(
user[_user].lastRentCalc,
_timeOfNewBid,
totalUserDailyRent
);
uint256 _depositAtTimeOfNewBid = 0;
if (user[_user].lastRentCalc < _timeOfNewBid) {
// new bid is after user rent calculation
_depositAtTimeOfNewBid =
user[_user].deposit -
_rentDifference;
} else {
// new bid is before user rent calculation
_depositAtTimeOfNewBid =
user[_user].deposit +
_rentDifference;
}
uint256 _timeLeftOfDepositWithNewBid = (_depositAtTimeOfNewBid *
1 days) / (totalUserDailyRent + _newBid);
uint256 _foreclosureTimeWithNewCard = _timeOfNewBid +
_timeLeftOfDepositWithNewBid;
if (_foreclosureTimeWithNewCard > user[_user].lastRentCalc) {
return _foreclosureTimeWithNewCard;
} else {
// The user couldn't afford to own the new card up to their last
// .. rent calculation, we can't rewind their rent calculation because
// .. of gas limits (there could be many markets having taken rent).
// Therefore unfortunately we can't give any ownership to this user as
// .. this could mean getting caught in a loop we may not be able to
// .. exit because of gas limits (there could be many users in this
// .. situation and we can't leave any unaccounted for).
// This means we return 0 to signify that the user can't afford this
// .. new ownership.
return 0;
}
} else {
return user[_user].lastRentCalc + timeLeftOfDeposit;
}
} else {
if (_newBid == 0) {
// if no rentals they'll foreclose after the heat death of the universe
return type(uint256).max;
} else {
return
_timeOfNewBid + ((user[_user].deposit * 1 days) / _newBid);
}
}
}
/// @notice call for a rent collection on the given user
/// @notice IF the user doesn't have enough deposit, returns foreclosure time
/// @notice ..otherwise returns zero
/// @param _user the user to query
/// @param _timeToCollectTo the timestamp to collect rent up-to
/// @return newTimeLastCollectedOnForeclosure the time the user foreclosed if they foreclosed in this calculation
function collectRentUser(address _user, uint256 _timeToCollectTo)
public
override
returns (uint256 newTimeLastCollectedOnForeclosure)
{
require(!globalPause, "Global pause is enabled");
require(_timeToCollectTo != 0, "Must set collection time");
require(
_timeToCollectTo <= block.timestamp,
"Can't collect future rent"
);
if (user[_user].lastRentCalc < _timeToCollectTo) {
uint256 rentOwedByUser = rentOwedUser(_user, _timeToCollectTo);
if (rentOwedByUser > 0 && rentOwedByUser > user[_user].deposit) {
// The User has run out of deposit already.
uint256 previousCollectionTime = user[_user].lastRentCalc;
/*
timeTheirDepositLasted = timeSinceLastUpdate * (usersDeposit/rentOwed)
= (now - previousCollectionTime) * (usersDeposit/rentOwed)
*/
uint256 timeUsersDepositLasts = ((_timeToCollectTo -
previousCollectionTime) * uint256(user[_user].deposit)) /
rentOwedByUser;
/*
Users last collection time = previousCollectionTime + timeTheirDepositLasted
*/
rentOwedByUser = uint256(user[_user].deposit);
newTimeLastCollectedOnForeclosure =
previousCollectionTime +
timeUsersDepositLasts;
_increaseMarketBalance(rentOwedByUser, _user);
user[_user].lastRentCalc = SafeCast.toUint64(
newTimeLastCollectedOnForeclosure
);
assert(user[_user].deposit == 0);
isForeclosed[_user] = true;
emit LogUserForeclosed(_user, true);
} else {
// User has enough deposit to pay rent.
_increaseMarketBalance(rentOwedByUser, _user);
user[_user].lastRentCalc = SafeCast.toUint64(_timeToCollectTo);
}
emit LogAdjustDeposit(_user, rentOwedByUser, false);
}
}
/// moving from the user deposit to the markets available balance
function _increaseMarketBalance(uint256 rentCollected, address _user)
internal
{
marketBalance += rentCollected;
user[_user].deposit -= SafeCast.toUint128(rentCollected);
totalDeposits -= rentCollected;
}
/// @notice checks if the user should still be foreclosed
function assessForeclosure(address _user) public override {
if (user[_user].deposit > (user[_user].bidRate / minRentalDayDivisor)) {
isForeclosed[_user] = false;
emit LogUserForeclosed(_user, false);
} else {
isForeclosed[_user] = true;
emit LogUserForeclosed(_user, true);
}
}
/// @dev can't be called hasRole also because AccessControl.hasRole isn't virtual
function checkPermission(bytes32 role, address account)
external
view
override
returns (bool)
{
return AccessControl.hasRole(role, account);
}
/// @notice To grant a role (string) to an address
/// @param role the role to grant, this is a string and will be converted to bytes32
/// @param account the account to grant the role to
/// @dev Not necessary but makes granting roles easier
/// @dev not called grantRole as overloading a string and bytes32 causes issues with tools like remix
function grantRoleString(string memory role, address account)
external
override
{
bytes32 _role = keccak256(abi.encodePacked(role));
RCTreasury.grantRole(_role, account);
}
/// @notice To grant a role (bytes32) to an address
/// @param role the role to grant
/// @param account the account to grant the role to
function grantRole(bytes32 role, address account)
public
override(AccessControl, IRCTreasury)
{
AccessControl.grantRole(role, account);
}
/// @notice To check is a particular account has a certain role
/// @param role The role (string) to query about
/// @param account the address which may have this role
/// @return Bool, True if the account has role
/// @dev needed because we can't override hasRole (it's not virtual) and
/// @dev .. without this the contract wouldn't fully implement the interface
/// @dev Similar to checkPermissions except using string instead of bytes32
function checkRole(string memory role, address account)
external
view
override
returns (bool)
{
bytes32 _role = keccak256(abi.encodePacked(role));
return hasRole(_role, account);
}
/// @notice To revoke a role (string) from an address
/// @param role the role to revoke, this is a string and will be converted to bytes32
/// @param account the account to revoke the role from
/// @dev Not necessary but makes revoking roles easier
/// @dev not called revokeRole as overloading a string and bytes32 causes issues with tools like remix
function revokeRoleString(string memory role, address account)
external
override
{
bytes32 _role = keccak256(abi.encodePacked(role));
RCTreasury.revokeRole(_role, account);
}
/// @notice To revoke a role (bytes32) from an address
/// @param role the role to revoke
/// @param account the account to revoke the role from
function revokeRole(bytes32 role, address account)
public
override(AccessControl, IRCTreasury)
{
AccessControl.revokeRole(role, account);
}
/*
▲
▲ ▲
*/
}
| @notice To change the ERC20 token. @dev changing this while tokens have been deposited could prove disastrous | function setTokenAddress(address _newToken)
public
override
onlyRole(UBER_OWNER)
{
require(_newToken != address(0), "Must set an address");
erc20 = IERC20(_newToken);
}
| 979,367 | [
1,
774,
2549,
326,
4232,
39,
3462,
1147,
18,
225,
12770,
333,
1323,
2430,
1240,
2118,
443,
1724,
329,
3377,
450,
537,
1015,
689,
303,
407,
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,
445,
22629,
1887,
12,
2867,
389,
2704,
1345,
13,
203,
3639,
1071,
203,
3639,
3849,
203,
3639,
1338,
2996,
12,
3457,
654,
67,
29602,
13,
203,
565,
288,
203,
3639,
2583,
24899,
2704,
1345,
480,
1758,
12,
20,
3631,
315,
10136,
444,
392,
1758,
8863,
203,
3639,
6445,
71,
3462,
273,
467,
654,
39,
3462,
24899,
2704,
1345,
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
] |
// SPDX-License-Identifier: MIT
pragma solidity 0.6.12;
import "../libraries/math/SafeMath.sol";
import "../libraries/token/IERC20.sol";
import "../libraries/token/SafeERC20.sol";
import "../libraries/utils/ReentrancyGuard.sol";
import "../libraries/utils/Address.sol";
import "./interfaces/IRewardTracker.sol";
import "./interfaces/IVester.sol";
import "../tokens/interfaces/IMintable.sol";
import "../tokens/interfaces/IWETH.sol";
import "../core/interfaces/IGlpManager.sol";
import "../access/Governable.sol";
contract RewardRouterV2 is ReentrancyGuard, Governable {
using SafeMath for uint256;
using SafeERC20 for IERC20;
using Address for address payable;
bool public isInitialized;
address public weth;
address public gmx;
address public esGmx;
address public bnGmx;
address public glp; // GMX Liquidity Provider token
address public stakedGmxTracker;
address public bonusGmxTracker;
address public feeGmxTracker;
address public stakedGlpTracker;
address public feeGlpTracker;
address public glpManager;
address public gmxVester;
address public glpVester;
mapping (address => address) public pendingReceivers;
event StakeGmx(address account, address token, uint256 amount);
event UnstakeGmx(address account, address token, uint256 amount);
event StakeGlp(address account, uint256 amount);
event UnstakeGlp(address account, uint256 amount);
receive() external payable {
require(msg.sender == weth, "Router: invalid sender");
}
function initialize(
address _weth,
address _gmx,
address _esGmx,
address _bnGmx,
address _glp,
address _stakedGmxTracker,
address _bonusGmxTracker,
address _feeGmxTracker,
address _feeGlpTracker,
address _stakedGlpTracker,
address _glpManager,
address _gmxVester,
address _glpVester
) external onlyGov {
require(!isInitialized, "RewardRouter: already initialized");
isInitialized = true;
weth = _weth;
gmx = _gmx;
esGmx = _esGmx;
bnGmx = _bnGmx;
glp = _glp;
stakedGmxTracker = _stakedGmxTracker;
bonusGmxTracker = _bonusGmxTracker;
feeGmxTracker = _feeGmxTracker;
feeGlpTracker = _feeGlpTracker;
stakedGlpTracker = _stakedGlpTracker;
glpManager = _glpManager;
gmxVester = _gmxVester;
glpVester = _glpVester;
}
// to help users who accidentally send their tokens to this contract
function withdrawToken(address _token, address _account, uint256 _amount) external onlyGov {
IERC20(_token).safeTransfer(_account, _amount);
}
function batchStakeGmxForAccount(address[] memory _accounts, uint256[] memory _amounts) external nonReentrant onlyGov {
address _gmx = gmx;
for (uint256 i = 0; i < _accounts.length; i++) {
_stakeGmx(msg.sender, _accounts[i], _gmx, _amounts[i]);
}
}
function stakeGmxForAccount(address _account, uint256 _amount) external nonReentrant onlyGov {
_stakeGmx(msg.sender, _account, gmx, _amount);
}
function stakeGmx(uint256 _amount) external nonReentrant {
_stakeGmx(msg.sender, msg.sender, gmx, _amount);
}
function stakeEsGmx(uint256 _amount) external nonReentrant {
_stakeGmx(msg.sender, msg.sender, esGmx, _amount);
}
function unstakeGmx(uint256 _amount) external nonReentrant {
_unstakeGmx(msg.sender, gmx, _amount, true);
}
function unstakeEsGmx(uint256 _amount) external nonReentrant {
_unstakeGmx(msg.sender, esGmx, _amount, true);
}
function mintAndStakeGlp(address _token, uint256 _amount, uint256 _minUsdg, uint256 _minGlp) external nonReentrant returns (uint256) {
require(_amount > 0, "RewardRouter: invalid _amount");
address account = msg.sender;
uint256 glpAmount = IGlpManager(glpManager).addLiquidityForAccount(account, account, _token, _amount, _minUsdg, _minGlp);
IRewardTracker(feeGlpTracker).stakeForAccount(account, account, glp, glpAmount);
IRewardTracker(stakedGlpTracker).stakeForAccount(account, account, feeGlpTracker, glpAmount);
emit StakeGlp(account, glpAmount);
return glpAmount;
}
function mintAndStakeGlpETH(uint256 _minUsdg, uint256 _minGlp) external payable nonReentrant returns (uint256) {
require(msg.value > 0, "RewardRouter: invalid msg.value");
IWETH(weth).deposit{value: msg.value}();
IERC20(weth).approve(glpManager, msg.value);
address account = msg.sender;
uint256 glpAmount = IGlpManager(glpManager).addLiquidityForAccount(address(this), account, weth, msg.value, _minUsdg, _minGlp);
IRewardTracker(feeGlpTracker).stakeForAccount(account, account, glp, glpAmount);
IRewardTracker(stakedGlpTracker).stakeForAccount(account, account, feeGlpTracker, glpAmount);
emit StakeGlp(account, glpAmount);
return glpAmount;
}
function unstakeAndRedeemGlp(address _tokenOut, uint256 _glpAmount, uint256 _minOut, address _receiver) external nonReentrant returns (uint256) {
require(_glpAmount > 0, "RewardRouter: invalid _glpAmount");
address account = msg.sender;
IRewardTracker(stakedGlpTracker).unstakeForAccount(account, feeGlpTracker, _glpAmount, account);
IRewardTracker(feeGlpTracker).unstakeForAccount(account, glp, _glpAmount, account);
uint256 amountOut = IGlpManager(glpManager).removeLiquidityForAccount(account, _tokenOut, _glpAmount, _minOut, _receiver);
emit UnstakeGlp(account, _glpAmount);
return amountOut;
}
function unstakeAndRedeemGlpETH(uint256 _glpAmount, uint256 _minOut, address payable _receiver) external nonReentrant returns (uint256) {
require(_glpAmount > 0, "RewardRouter: invalid _glpAmount");
address account = msg.sender;
IRewardTracker(stakedGlpTracker).unstakeForAccount(account, feeGlpTracker, _glpAmount, account);
IRewardTracker(feeGlpTracker).unstakeForAccount(account, glp, _glpAmount, account);
uint256 amountOut = IGlpManager(glpManager).removeLiquidityForAccount(account, weth, _glpAmount, _minOut, address(this));
IWETH(weth).withdraw(amountOut);
_receiver.sendValue(amountOut);
emit UnstakeGlp(account, _glpAmount);
return amountOut;
}
function claim() external nonReentrant {
address account = msg.sender;
IRewardTracker(feeGmxTracker).claimForAccount(account, account);
IRewardTracker(feeGlpTracker).claimForAccount(account, account);
IRewardTracker(stakedGmxTracker).claimForAccount(account, account);
IRewardTracker(stakedGlpTracker).claimForAccount(account, account);
}
function claimEsGmx() external nonReentrant {
address account = msg.sender;
IRewardTracker(stakedGmxTracker).claimForAccount(account, account);
IRewardTracker(stakedGlpTracker).claimForAccount(account, account);
}
function claimFees() external nonReentrant {
address account = msg.sender;
IRewardTracker(feeGmxTracker).claimForAccount(account, account);
IRewardTracker(feeGlpTracker).claimForAccount(account, account);
}
function compound() external nonReentrant {
_compound(msg.sender);
}
function compoundForAccount(address _account) external nonReentrant onlyGov {
_compound(_account);
}
function handleRewards(
bool _shouldClaimGmx,
bool _shouldStakeGmx,
bool _shouldClaimEsGmx,
bool _shouldStakeEsGmx,
bool _shouldStakeMultiplierPoints,
bool _shouldClaimWeth,
bool _shouldConvertWethToEth
) external nonReentrant {
address account = msg.sender;
uint256 gmxAmount = 0;
if (_shouldClaimGmx) {
uint256 gmxAmount0 = IVester(gmxVester).claimForAccount(account, account);
uint256 gmxAmount1 = IVester(glpVester).claimForAccount(account, account);
gmxAmount = gmxAmount0.add(gmxAmount1);
}
if (_shouldStakeGmx && gmxAmount > 0) {
_stakeGmx(account, account, gmx, gmxAmount);
}
uint256 esGmxAmount = 0;
if (_shouldClaimEsGmx) {
uint256 esGmxAmount0 = IRewardTracker(stakedGmxTracker).claimForAccount(account, account);
uint256 esGmxAmount1 = IRewardTracker(stakedGlpTracker).claimForAccount(account, account);
esGmxAmount = esGmxAmount0.add(esGmxAmount1);
}
if (_shouldStakeEsGmx && esGmxAmount > 0) {
_stakeGmx(account, account, esGmx, esGmxAmount);
}
if (_shouldStakeMultiplierPoints) {
uint256 bnGmxAmount = IRewardTracker(bonusGmxTracker).claimForAccount(account, account);
if (bnGmxAmount > 0) {
IRewardTracker(feeGmxTracker).stakeForAccount(account, account, bnGmx, bnGmxAmount);
}
}
if (_shouldClaimWeth) {
if (_shouldConvertWethToEth) {
uint256 weth0 = IRewardTracker(feeGmxTracker).claimForAccount(account, address(this));
uint256 weth1 = IRewardTracker(feeGlpTracker).claimForAccount(account, address(this));
uint256 wethAmount = weth0.add(weth1);
IWETH(weth).withdraw(wethAmount);
payable(account).sendValue(wethAmount);
} else {
IRewardTracker(feeGmxTracker).claimForAccount(account, account);
IRewardTracker(feeGlpTracker).claimForAccount(account, account);
}
}
}
function batchCompoundForAccounts(address[] memory _accounts) external nonReentrant onlyGov {
for (uint256 i = 0; i < _accounts.length; i++) {
_compound(_accounts[i]);
}
}
function signalTransfer(address _receiver) external nonReentrant {
require(IERC20(gmxVester).balanceOf(msg.sender) == 0, "RewardRouter: sender has vested tokens");
require(IERC20(glpVester).balanceOf(msg.sender) == 0, "RewardRouter: sender has vested tokens");
_validateReceiver(_receiver);
pendingReceivers[msg.sender] = _receiver;
}
function acceptTransfer(address _sender) external nonReentrant {
require(IERC20(gmxVester).balanceOf(_sender) == 0, "RewardRouter: sender has vested tokens");
require(IERC20(glpVester).balanceOf(_sender) == 0, "RewardRouter: sender has vested tokens");
address receiver = msg.sender;
require(pendingReceivers[_sender] == receiver, "RewardRouter: transfer not signalled");
delete pendingReceivers[_sender];
_validateReceiver(receiver);
_compound(_sender);
uint256 stakedGmx = IRewardTracker(stakedGmxTracker).depositBalances(_sender, gmx);
if (stakedGmx > 0) {
_unstakeGmx(_sender, gmx, stakedGmx, false);
_stakeGmx(_sender, receiver, gmx, stakedGmx);
}
uint256 stakedEsGmx = IRewardTracker(stakedGmxTracker).depositBalances(_sender, esGmx);
if (stakedEsGmx > 0) {
_unstakeGmx(_sender, esGmx, stakedEsGmx, false);
_stakeGmx(_sender, receiver, esGmx, stakedEsGmx);
}
uint256 stakedBnGmx = IRewardTracker(feeGmxTracker).depositBalances(_sender, bnGmx);
if (stakedBnGmx > 0) {
IRewardTracker(feeGmxTracker).unstakeForAccount(_sender, bnGmx, stakedBnGmx, _sender);
IRewardTracker(feeGmxTracker).stakeForAccount(_sender, receiver, bnGmx, stakedBnGmx);
}
uint256 esGmxBalance = IERC20(esGmx).balanceOf(_sender);
if (esGmxBalance > 0) {
IERC20(esGmx).transferFrom(_sender, receiver, esGmxBalance);
}
uint256 glpAmount = IRewardTracker(feeGlpTracker).depositBalances(_sender, glp);
if (glpAmount > 0) {
IRewardTracker(stakedGlpTracker).unstakeForAccount(_sender, feeGlpTracker, glpAmount, _sender);
IRewardTracker(feeGlpTracker).unstakeForAccount(_sender, glp, glpAmount, _sender);
IRewardTracker(feeGlpTracker).stakeForAccount(_sender, receiver, glp, glpAmount);
IRewardTracker(stakedGlpTracker).stakeForAccount(receiver, receiver, feeGlpTracker, glpAmount);
}
IVester(gmxVester).transferStakeValues(_sender, receiver);
IVester(glpVester).transferStakeValues(_sender, receiver);
}
function _validateReceiver(address _receiver) private view {
require(IRewardTracker(stakedGmxTracker).averageStakedAmounts(_receiver) == 0, "RewardRouter: stakedGmxTracker.averageStakedAmounts > 0");
require(IRewardTracker(stakedGmxTracker).cumulativeRewards(_receiver) == 0, "RewardRouter: stakedGmxTracker.cumulativeRewards > 0");
require(IRewardTracker(bonusGmxTracker).averageStakedAmounts(_receiver) == 0, "RewardRouter: bonusGmxTracker.averageStakedAmounts > 0");
require(IRewardTracker(bonusGmxTracker).cumulativeRewards(_receiver) == 0, "RewardRouter: bonusGmxTracker.cumulativeRewards > 0");
require(IRewardTracker(feeGmxTracker).averageStakedAmounts(_receiver) == 0, "RewardRouter: feeGmxTracker.averageStakedAmounts > 0");
require(IRewardTracker(feeGmxTracker).cumulativeRewards(_receiver) == 0, "RewardRouter: feeGmxTracker.cumulativeRewards > 0");
require(IVester(gmxVester).transferredAverageStakedAmounts(_receiver) == 0, "RewardRouter: gmxVester.transferredAverageStakedAmounts > 0");
require(IVester(gmxVester).transferredCumulativeRewards(_receiver) == 0, "RewardRouter: gmxVester.transferredCumulativeRewards > 0");
require(IRewardTracker(stakedGlpTracker).averageStakedAmounts(_receiver) == 0, "RewardRouter: stakedGlpTracker.averageStakedAmounts > 0");
require(IRewardTracker(stakedGlpTracker).cumulativeRewards(_receiver) == 0, "RewardRouter: stakedGlpTracker.cumulativeRewards > 0");
require(IRewardTracker(feeGlpTracker).averageStakedAmounts(_receiver) == 0, "RewardRouter: feeGlpTracker.averageStakedAmounts > 0");
require(IRewardTracker(feeGlpTracker).cumulativeRewards(_receiver) == 0, "RewardRouter: feeGlpTracker.cumulativeRewards > 0");
require(IVester(glpVester).transferredAverageStakedAmounts(_receiver) == 0, "RewardRouter: gmxVester.transferredAverageStakedAmounts > 0");
require(IVester(glpVester).transferredCumulativeRewards(_receiver) == 0, "RewardRouter: gmxVester.transferredCumulativeRewards > 0");
require(IERC20(gmxVester).balanceOf(_receiver) == 0, "RewardRouter: gmxVester.balance > 0");
require(IERC20(glpVester).balanceOf(_receiver) == 0, "RewardRouter: glpVester.balance > 0");
}
function _compound(address _account) private {
_compoundGmx(_account);
_compoundGlp(_account);
}
function _compoundGmx(address _account) private {
uint256 esGmxAmount = IRewardTracker(stakedGmxTracker).claimForAccount(_account, _account);
if (esGmxAmount > 0) {
_stakeGmx(_account, _account, esGmx, esGmxAmount);
}
uint256 bnGmxAmount = IRewardTracker(bonusGmxTracker).claimForAccount(_account, _account);
if (bnGmxAmount > 0) {
IRewardTracker(feeGmxTracker).stakeForAccount(_account, _account, bnGmx, bnGmxAmount);
}
}
function _compoundGlp(address _account) private {
uint256 esGmxAmount = IRewardTracker(stakedGlpTracker).claimForAccount(_account, _account);
if (esGmxAmount > 0) {
_stakeGmx(_account, _account, esGmx, esGmxAmount);
}
}
function _stakeGmx(address _fundingAccount, address _account, address _token, uint256 _amount) private {
require(_amount > 0, "RewardRouter: invalid _amount");
IRewardTracker(stakedGmxTracker).stakeForAccount(_fundingAccount, _account, _token, _amount);
IRewardTracker(bonusGmxTracker).stakeForAccount(_account, _account, stakedGmxTracker, _amount);
IRewardTracker(feeGmxTracker).stakeForAccount(_account, _account, bonusGmxTracker, _amount);
emit StakeGmx(_account, _token, _amount);
}
function _unstakeGmx(address _account, address _token, uint256 _amount, bool _shouldReduceBnGmx) private {
require(_amount > 0, "RewardRouter: invalid _amount");
uint256 balance = IRewardTracker(stakedGmxTracker).stakedAmounts(_account);
IRewardTracker(feeGmxTracker).unstakeForAccount(_account, bonusGmxTracker, _amount, _account);
IRewardTracker(bonusGmxTracker).unstakeForAccount(_account, stakedGmxTracker, _amount, _account);
IRewardTracker(stakedGmxTracker).unstakeForAccount(_account, _token, _amount, _account);
if (_shouldReduceBnGmx) {
uint256 bnGmxAmount = IRewardTracker(bonusGmxTracker).claimForAccount(_account, _account);
if (bnGmxAmount > 0) {
IRewardTracker(feeGmxTracker).stakeForAccount(_account, _account, bnGmx, bnGmxAmount);
}
uint256 stakedBnGmx = IRewardTracker(feeGmxTracker).depositBalances(_account, bnGmx);
if (stakedBnGmx > 0) {
uint256 reductionAmount = stakedBnGmx.mul(_amount).div(balance);
IRewardTracker(feeGmxTracker).unstakeForAccount(_account, bnGmx, reductionAmount, _account);
IMintable(bnGmx).burn(_account, reductionAmount);
}
}
emit UnstakeGmx(_account, _token, _amount);
}
}
| GMX Liquidity Provider token
| address public glp; | 1,846,327 | [
1,
43,
13874,
511,
18988,
24237,
7561,
1147,
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,
1758,
1071,
5118,
84,
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
] |
./full_match/1/0x113dE669181708f8b497329654606e6134673c8c/sources/contracts/Reindeer.sol | Smart contract for Reindeer NFTs Last edited : 27 OCT 2021, 4:44 PM Last updated at 18 Dec, 2021 8:30 PM | contract ReindeerNFT is ERC721Enumerable, Ownable {
using Strings for uint256;
string public baseURI;
string public baseExtension = ".json";
uint256 public cost = 0.07 ether;
uint256 public maxSupply = 777;
uint256 public maxMintAmount = 20;
bool public paused = true;
bytes32 private seedPhrase = 0x6abe10cdef935bbc20e799c9ecc3ed3f94f70081687588d1fc0e81319936e6d8;
address payable private contractOwner;
constructor(
string memory _name,
string memory _symbol,
string memory _initBaseURI
pragma solidity >=0.7.0 <0.9.0;
) ERC721(_name, _symbol) {
setBaseURI(_initBaseURI);
contractOwner = payable(msg.sender);
}
function _baseURI() internal view virtual override returns (string memory) {
return baseURI;
}
function mint(string memory phrase, uint256 _mintAmount)
public
payable
returns (string memory)
{
require(msg.sender != address(0));
bytes32 hashedWord = sha256(abi.encodePacked(phrase));
require(hashedWord == seedPhrase, "Password doesn't match");
uint256 supply = totalSupply();
require(_mintAmount > 0, "need to mint at least 1 NFT");
require(
_mintAmount <= maxMintAmount,
"max mint amount per session exceeded"
);
require(supply + _mintAmount <= maxSupply, "max NFT limit exceeded");
if (msg.sender != owner()) {
require(!paused, "the contract is paused");
require(msg.value >= cost * _mintAmount, "insufficient funds");
}
for (uint256 i = 0; i < _mintAmount; i++) {
_safeMint(msg.sender, supply + i);
}
contractOwner.transfer(address(this).balance);
}
function mint(string memory phrase, uint256 _mintAmount)
public
payable
returns (string memory)
{
require(msg.sender != address(0));
bytes32 hashedWord = sha256(abi.encodePacked(phrase));
require(hashedWord == seedPhrase, "Password doesn't match");
uint256 supply = totalSupply();
require(_mintAmount > 0, "need to mint at least 1 NFT");
require(
_mintAmount <= maxMintAmount,
"max mint amount per session exceeded"
);
require(supply + _mintAmount <= maxSupply, "max NFT limit exceeded");
if (msg.sender != owner()) {
require(!paused, "the contract is paused");
require(msg.value >= cost * _mintAmount, "insufficient funds");
}
for (uint256 i = 0; i < _mintAmount; i++) {
_safeMint(msg.sender, supply + i);
}
contractOwner.transfer(address(this).balance);
}
function mint(string memory phrase, uint256 _mintAmount)
public
payable
returns (string memory)
{
require(msg.sender != address(0));
bytes32 hashedWord = sha256(abi.encodePacked(phrase));
require(hashedWord == seedPhrase, "Password doesn't match");
uint256 supply = totalSupply();
require(_mintAmount > 0, "need to mint at least 1 NFT");
require(
_mintAmount <= maxMintAmount,
"max mint amount per session exceeded"
);
require(supply + _mintAmount <= maxSupply, "max NFT limit exceeded");
if (msg.sender != owner()) {
require(!paused, "the contract is paused");
require(msg.value >= cost * _mintAmount, "insufficient funds");
}
for (uint256 i = 0; i < _mintAmount; i++) {
_safeMint(msg.sender, supply + i);
}
contractOwner.transfer(address(this).balance);
}
function walletOfOwner(address _owner)
public
view
returns (uint256[] memory)
{
uint256 ownerTokenCount = balanceOf(_owner);
uint256[] memory tokenIds = new uint256[](ownerTokenCount);
for (uint256 i; i < ownerTokenCount; i++) {
tokenIds[i] = tokenOfOwnerByIndex(_owner, i);
}
return tokenIds;
}
function walletOfOwner(address _owner)
public
view
returns (uint256[] memory)
{
uint256 ownerTokenCount = balanceOf(_owner);
uint256[] memory tokenIds = new uint256[](ownerTokenCount);
for (uint256 i; i < ownerTokenCount; i++) {
tokenIds[i] = tokenOfOwnerByIndex(_owner, i);
}
return tokenIds;
}
function tokenURI(uint256 tokenId)
public
view
virtual
override
returns (string memory)
{
require(
_exists(tokenId),
"ERC721Metadata: URI query for nonexistent token"
);
string memory currentBaseURI = _baseURI();
return
bytes(currentBaseURI).length > 0
? string(
abi.encodePacked(
currentBaseURI,
tokenId.toString(),
baseExtension
)
)
: "";
}
function getContractBalance() public view returns (uint256) {
return address(this).balance;
}
function setCost(uint256 _newCost) public onlyOwner {
cost = _newCost;
}
function setmaxMintAmount(uint256 _newmaxMintAmount) public onlyOwner {
maxMintAmount = _newmaxMintAmount;
}
function setBaseURI(string memory _newBaseURI) public onlyOwner {
baseURI = _newBaseURI;
}
function pause(bool _state) public onlyOwner {
paused = _state;
}
function setSecret(bytes32 _secret) public onlyOwner {
seedPhrase = _secret;
}
function withdraw() public payable onlyOwner {
(bool success, ) = payable(msg.sender).call{
value: address(this).balance
}("");
require(success);
}
function withdraw() public payable onlyOwner {
(bool success, ) = payable(msg.sender).call{
value: address(this).balance
}("");
require(success);
}
function withdrawBalance() public onlyOwner {
contractOwner.transfer(address(this).balance);
}
}
| 9,775,371 | [
1,
23824,
6835,
364,
868,
267,
323,
264,
423,
4464,
87,
6825,
18532,
294,
12732,
531,
1268,
26599,
21,
16,
1059,
30,
6334,
23544,
6825,
3526,
622,
6549,
3416,
16,
26599,
21,
1725,
30,
5082,
23544,
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,
16351,
868,
267,
323,
264,
50,
4464,
353,
4232,
39,
27,
5340,
3572,
25121,
16,
14223,
6914,
288,
203,
565,
1450,
8139,
364,
2254,
5034,
31,
203,
565,
533,
1071,
1026,
3098,
31,
203,
565,
533,
1071,
1026,
3625,
273,
3552,
1977,
14432,
203,
565,
2254,
5034,
1071,
6991,
273,
374,
18,
8642,
225,
2437,
31,
203,
565,
2254,
5034,
1071,
943,
3088,
1283,
273,
2371,
4700,
31,
203,
565,
2254,
5034,
1071,
943,
49,
474,
6275,
273,
4200,
31,
203,
565,
1426,
1071,
17781,
273,
638,
31,
203,
565,
1731,
1578,
3238,
5009,
12812,
273,
374,
92,
26,
378,
73,
2163,
71,
536,
29,
4763,
9897,
71,
3462,
73,
27,
2733,
71,
29,
24410,
23,
329,
23,
74,
11290,
74,
26874,
28,
23329,
5877,
5482,
72,
21,
7142,
20,
73,
28,
3437,
19818,
5718,
73,
26,
72,
28,
31,
203,
565,
1758,
8843,
429,
3238,
6835,
5541,
31,
203,
565,
3885,
12,
203,
3639,
533,
3778,
389,
529,
16,
203,
3639,
533,
3778,
389,
7175,
16,
203,
3639,
533,
3778,
389,
2738,
2171,
3098,
203,
683,
9454,
18035,
560,
1545,
20,
18,
27,
18,
20,
411,
20,
18,
29,
18,
20,
31,
203,
565,
262,
4232,
39,
27,
5340,
24899,
529,
16,
389,
7175,
13,
288,
203,
3639,
26435,
3098,
24899,
2738,
2171,
3098,
1769,
203,
3639,
6835,
5541,
273,
8843,
429,
12,
3576,
18,
15330,
1769,
203,
565,
289,
203,
565,
445,
389,
1969,
3098,
1435,
2713,
1476,
5024,
3849,
1135,
261,
1080,
3778,
13,
288,
203,
3639,
327,
1026,
3098,
31,
2
] |
/**
*Submitted for verification at Etherscan.io on 2019-12-03
*/
pragma solidity 0.5.13;
/*
* @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;
}
}
/**
* @dev Interface of the ERC20 standard as defined in the EIP. Does not include
* the optional functions; to access them see {ERC20Detailed}.
*/
interface IERC20 {
/**
* @dev Returns the amount of tokens in existence.
*/
function totalSupply() external view returns (uint256);
/**
* @dev Returns the amount of tokens owned by `account`.
*/
function balanceOf(address account) external view returns (uint256);
/**
* @dev Moves `amount` tokens from the caller's account to `recipient`.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/
function transfer(address recipient, uint256 amount) external returns (bool);
/**
* @dev Returns the remaining number of tokens that `spender` will be
* allowed to spend on behalf of `owner` through {transferFrom}. This is
* zero by default.
*
* This value changes when {approve} or {transferFrom} are called.
*/
function allowance(address owner, address spender) external view returns (uint256);
/**
* @dev Sets `amount` as the allowance of `spender` over the caller's tokens.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* IMPORTANT: Beware that changing an allowance with this method brings the risk
* that someone may use both the old and the new allowance by unfortunate
* transaction ordering. One possible solution to mitigate this race
* condition is to first reduce the spender's allowance to 0 and set the
* desired value afterwards:
* https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729
*
* Emits an {Approval} event.
*/
function approve(address spender, uint256 amount) external returns (bool);
/**
* @dev Moves `amount` tokens from `sender` to `recipient` using the
* allowance mechanism. `amount` is then deducted from the caller's
* allowance.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/
function transferFrom(address sender, address recipient, uint256 amount) external returns (bool);
/**
* @dev Emitted when `value` tokens are moved from one account (`from`) to
* another (`to`).
*
* Note that `value` may be zero.
*/
event Transfer(address indexed from, address indexed to, uint256 value);
/**
* @dev Emitted when the allowance of a `spender` for an `owner` is set by
* a call to {approve}. `value` is the new allowance.
*/
event Approval(address indexed owner, address indexed spender, uint256 value);
}
/**
* @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 ; //inject UNINIT LOCAL/STATE VAR
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 ; //inject UNINIT LOCAL/STATE VAR
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 ; //inject UNINIT LOCAL/STATE VAR
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 ; //inject UNINIT LOCAL/STATE VAR
// 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;
}
}
/**
* @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}.
*
* TIP: For a detailed writeup see our guide
* https://forum.zeppelin.solutions/t/how-to-implement-erc20-supply-mechanisms/226[How
* to implement supply mechanisms].
*
* We have followed general OpenZeppelin guidelines: functions revert instead
* of returning `false` on failure. This behavior is nonetheless conventional
* and does not conflict with the expectations of ERC20 applications.
*
* Additionally, an {Approval} event is emitted on calls to {transferFrom}.
* This allows applications to reconstruct the allowance for all accounts just
* by listening to said events. Other implementations of the EIP may not emit
* these events, as it isn't required by the specification.
*
* Finally, the non-standard {decreaseAllowance} and {increaseAllowance}
* functions have been added to mitigate the well-known issues around setting
* allowances. See {IERC20-approve}.
*/
contract ERC20 is Context, IERC20 {
using SafeMath for uint256;
mapping (address => uint256) private _balances;
mapping (address => mapping (address => uint256)) private _allowances;
uint256 private _totalSupply;
/**
* @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(_msgSender(), 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 amount) public 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 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 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, "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");
_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");
_balances[account] = _balances[account].sub(amount, "ERC20: burn amount exceeds balance");
_totalSupply = _totalSupply.sub(amount);
emit Transfer(account, address(0), amount);
}
/**
* @dev Sets `amount` as the allowance of `spender` over the `owner`s tokens.
*
* This is internal function is equivalent to `approve`, and can be used to
* e.g. set automatic allowances for certain subsystems, etc.
*
* Emits an {Approval} event.
*
* Requirements:
*
* - `owner` cannot be the zero address.
* - `spender` cannot be the zero address.
*/
function _approve(address owner, address spender, uint256 amount) internal {
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 Destroys `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, _msgSender(), _allowances[account][_msgSender()].sub(amount, "ERC20: burn amount exceeds allowance"));
}
}
contract GlobalsAndUtility is ERC20 {
/* XfLobbyEnter (auto-generated event)
uint40 timestamp --> data0 [ 39: 0]
address indexed memberAddr
uint256 indexed entryId
uint96 rawAmount --> data0 [135: 40]
address indexed referrerAddr
*/
event XfLobbyEnter(
uint256 data0,
address indexed memberAddr,
uint256 indexed entryId,
address indexed referrerAddr
);
/* XfLobbyExit (auto-generated event)
uint40 timestamp --> data0 [ 39: 0]
address indexed memberAddr
uint256 indexed entryId
uint72 xfAmount --> data0 [111: 40]
address indexed referrerAddr
*/
event XfLobbyExit(
uint256 data0,
address indexed memberAddr,
uint256 indexed entryId,
address indexed referrerAddr
);
/* DailyDataUpdate (auto-generated event)
uint40 timestamp --> data0 [ 39: 0]
uint16 beginDay --> data0 [ 55: 40]
uint16 endDay --> data0 [ 71: 56]
bool isAutoUpdate --> data0 [ 79: 72]
address indexed updaterAddr
*/
event DailyDataUpdate(
uint256 data0,
address indexed updaterAddr
);
/* Claim (auto-generated event)
uint40 timestamp --> data0 [ 39: 0]
bytes20 indexed btcAddr
uint56 rawSatoshis --> data0 [ 95: 40]
uint56 adjSatoshis --> data0 [151: 96]
address indexed claimToAddr
uint8 claimFlags --> data0 [159:152]
uint72 claimedHearts --> data0 [231:160]
address indexed referrerAddr
address senderAddr --> data1 [159: 0]
*/
event Claim(
uint256 data0,
uint256 data1,
bytes20 indexed btcAddr,
address indexed claimToAddr,
address indexed referrerAddr
);
/* ClaimAssist (auto-generated event)
uint40 timestamp --> data0 [ 39: 0]
bytes20 btcAddr --> data0 [199: 40]
uint56 rawSatoshis --> data0 [255:200]
uint56 adjSatoshis --> data1 [ 55: 0]
address claimToAddr --> data1 [215: 56]
uint8 claimFlags --> data1 [223:216]
uint72 claimedHearts --> data2 [ 71: 0]
address referrerAddr --> data2 [231: 72]
address indexed senderAddr
*/
event ClaimAssist(
uint256 data0,
uint256 data1,
uint256 data2,
address indexed senderAddr
);
/* StakeStart (auto-generated event)
uint40 timestamp --> data0 [ 39: 0]
address indexed stakerAddr
uint40 indexed stakeId
uint72 stakedHearts --> data0 [111: 40]
uint72 stakeShares --> data0 [183:112]
uint16 stakedDays --> data0 [199:184]
bool isAutoStake --> data0 [207:200]
*/
event StakeStart(
uint256 data0,
address indexed stakerAddr,
uint40 indexed stakeId
);
/* StakeGoodAccounting(auto-generated event)
uint40 timestamp --> data0 [ 39: 0]
address indexed stakerAddr
uint40 indexed stakeId
uint72 stakedHearts --> data0 [111: 40]
uint72 stakeShares --> data0 [183:112]
uint72 payout --> data0 [255:184]
uint72 penalty --> data1 [ 71: 0]
address indexed senderAddr
*/
event StakeGoodAccounting(
uint256 data0,
uint256 data1,
address indexed stakerAddr,
uint40 indexed stakeId,
address indexed senderAddr
);
/* StakeEnd (auto-generated event)
uint40 timestamp --> data0 [ 39: 0]
address indexed stakerAddr
uint40 indexed stakeId
uint72 stakedHearts --> data0 [111: 40]
uint72 stakeShares --> data0 [183:112]
uint72 payout --> data0 [255:184]
uint72 penalty --> data1 [ 71: 0]
uint16 servedDays --> data1 [ 87: 72]
bool prevUnlocked --> data1 [ 95: 88]
*/
event StakeEnd(
uint256 data0,
uint256 data1,
address indexed stakerAddr,
uint40 indexed stakeId
);
/* ShareRateChange (auto-generated event)
uint40 timestamp --> data0 [ 39: 0]
uint40 shareRate --> data0 [ 79: 40]
uint40 indexed stakeId
*/
event ShareRateChange(
uint256 data0,
uint40 indexed stakeId
);
/* Origin address */
address internal constant ORIGIN_ADDR = 0x9A6a414D6F3497c05E3b1De90520765fA1E07c03;
/* Flush address */
address payable internal constant FLUSH_ADDR = 0x1028132da0B246F5FdDE135fB8B27166766f9c30;
/* ERC20 constants */
string public constant name = "HEX TOKEN";
string public constant symbol = "HEXTKN";
uint8 public constant decimals = 8;
/* Hearts per Satoshi = 10,000 * 1e8 / 1e8 = 1e4 */
uint256 private constant HEARTS_PER_HEX = 10 ** uint256(decimals); // 1e8
uint256 private constant HEX_PER_BTC = 1e4;
uint256 private constant SATOSHIS_PER_BTC = 1e8;
uint256 internal constant HEARTS_PER_SATOSHI = HEARTS_PER_HEX / SATOSHIS_PER_BTC * HEX_PER_BTC;
/* Time of contract launch (2019-12-03T00:00:00Z) */
uint256 internal constant LAUNCH_TIME = 1575331200;
/* Size of a Hearts or Shares uint */
uint256 internal constant HEART_UINT_SIZE = 72;
/* Size of a transform lobby entry index uint */
uint256 internal constant XF_LOBBY_ENTRY_INDEX_SIZE = 40;
uint256 internal constant XF_LOBBY_ENTRY_INDEX_MASK = (1 << XF_LOBBY_ENTRY_INDEX_SIZE) - 1;
/* Seed for WAAS Lobby */
uint256 internal constant WAAS_LOBBY_SEED_HEX = 1e9;
uint256 internal constant WAAS_LOBBY_SEED_HEARTS = WAAS_LOBBY_SEED_HEX * HEARTS_PER_HEX;
/* Start of claim phase */
uint256 internal constant PRE_CLAIM_DAYS = 1;
uint256 internal constant CLAIM_PHASE_START_DAY = PRE_CLAIM_DAYS;
/* Length of claim phase */
uint256 private constant CLAIM_PHASE_WEEKS = 50;
uint256 internal constant CLAIM_PHASE_DAYS = CLAIM_PHASE_WEEKS * 7;
/* End of claim phase */
uint256 internal constant CLAIM_PHASE_END_DAY = CLAIM_PHASE_START_DAY + CLAIM_PHASE_DAYS;
/* Number of words to hold 1 bit for each transform lobby day */
uint256 internal constant XF_LOBBY_DAY_WORDS = (CLAIM_PHASE_END_DAY + 255) >> 8;
/* BigPayDay */
uint256 internal constant BIG_PAY_DAY = CLAIM_PHASE_END_DAY + 1;
/* Root hash of the UTXO Merkle tree */
bytes32 internal constant MERKLE_TREE_ROOT = 0x4e831acb4223b66de3b3d2e54a2edeefb0de3d7916e2886a4b134d9764d41bec;
/* Size of a Satoshi claim uint in a Merkle leaf */
uint256 internal constant MERKLE_LEAF_SATOSHI_SIZE = 45;
/* Zero-fill between BTC address and Satoshis in a Merkle leaf */
uint256 internal constant MERKLE_LEAF_FILL_SIZE = 256 - 160 - MERKLE_LEAF_SATOSHI_SIZE;
uint256 internal constant MERKLE_LEAF_FILL_BASE = (1 << MERKLE_LEAF_FILL_SIZE) - 1;
uint256 internal constant MERKLE_LEAF_FILL_MASK = MERKLE_LEAF_FILL_BASE << MERKLE_LEAF_SATOSHI_SIZE;
/* Size of a Satoshi total uint */
uint256 internal constant SATOSHI_UINT_SIZE = 51;
uint256 internal constant SATOSHI_UINT_MASK = (1 << SATOSHI_UINT_SIZE) - 1;
/* Total Satoshis from all BTC addresses in UTXO snapshot */
uint256 internal constant FULL_SATOSHIS_TOTAL = 1807766732160668;
/* Total Satoshis from supported BTC addresses in UTXO snapshot after applying Silly Whale */
uint256 internal constant CLAIMABLE_SATOSHIS_TOTAL = 910087996911001;
/* Number of claimable BTC addresses in UTXO snapshot */
uint256 internal constant CLAIMABLE_BTC_ADDR_COUNT = 27997742;
/* Largest BTC address Satoshis balance in UTXO snapshot (sanity check) */
uint256 internal constant MAX_BTC_ADDR_BALANCE_SATOSHIS = 25550214098481;
/* Percentage of total claimed Hearts that will be auto-staked from a claim */
uint256 internal constant AUTO_STAKE_CLAIM_PERCENT = 90;
/* Stake timing parameters */
uint256 internal constant MIN_STAKE_DAYS = 1;
uint256 internal constant MIN_AUTO_STAKE_DAYS = 350;
uint256 internal constant MAX_STAKE_DAYS = 5555; // Approx 15 years
uint256 internal constant EARLY_PENALTY_MIN_DAYS = 90;
uint256 private constant LATE_PENALTY_GRACE_WEEKS = 2;
uint256 internal constant LATE_PENALTY_GRACE_DAYS = LATE_PENALTY_GRACE_WEEKS * 7;
uint256 private constant LATE_PENALTY_SCALE_WEEKS = 100;
uint256 internal constant LATE_PENALTY_SCALE_DAYS = LATE_PENALTY_SCALE_WEEKS * 7;
/* Stake shares Longer Pays Better bonus constants used by _stakeStartBonusHearts() */
uint256 private constant LPB_BONUS_PERCENT = 20;
uint256 private constant LPB_BONUS_MAX_PERCENT = 200;
uint256 internal constant LPB = 364 * 100 / LPB_BONUS_PERCENT;
uint256 internal constant LPB_MAX_DAYS = LPB * LPB_BONUS_MAX_PERCENT / 100;
/* Stake shares Bigger Pays Better bonus constants used by _stakeStartBonusHearts() */
uint256 private constant BPB_BONUS_PERCENT = 10;
uint256 private constant BPB_MAX_HEX = 150 * 1e6;
uint256 internal constant BPB_MAX_HEARTS = BPB_MAX_HEX * HEARTS_PER_HEX;
uint256 internal constant BPB = BPB_MAX_HEARTS * 100 / BPB_BONUS_PERCENT;
/* Share rate is scaled to increase precision */
uint256 internal constant SHARE_RATE_SCALE = 1e5;
/* Share rate max (after scaling) */
uint256 internal constant SHARE_RATE_UINT_SIZE = 40;
uint256 internal constant SHARE_RATE_MAX = (1 << SHARE_RATE_UINT_SIZE) - 1;
/* Constants for preparing the claim message text */
uint8 internal constant ETH_ADDRESS_BYTE_LEN = 20;
uint8 internal constant ETH_ADDRESS_HEX_LEN = ETH_ADDRESS_BYTE_LEN * 2;
uint8 internal constant CLAIM_PARAM_HASH_BYTE_LEN = 12;
uint8 internal constant CLAIM_PARAM_HASH_HEX_LEN = CLAIM_PARAM_HASH_BYTE_LEN * 2;
uint8 internal constant BITCOIN_SIG_PREFIX_LEN = 24;
bytes24 internal constant BITCOIN_SIG_PREFIX_STR = "Bitcoin Signed Message:\n";
bytes internal constant STD_CLAIM_PREFIX_STR = "Claim_HEX_to_0x";
bytes internal constant OLD_CLAIM_PREFIX_STR = "Claim_BitcoinHEX_to_0x";
bytes16 internal constant HEX_DIGITS = "0123456789abcdef";
/* Claim flags passed to btcAddressClaim() */
uint8 internal constant CLAIM_FLAG_MSG_PREFIX_OLD = 1 << 0;
uint8 internal constant CLAIM_FLAG_BTC_ADDR_COMPRESSED = 1 << 1;
uint8 internal constant CLAIM_FLAG_BTC_ADDR_P2WPKH_IN_P2SH = 1 << 2;
uint8 internal constant CLAIM_FLAG_BTC_ADDR_BECH32 = 1 << 3;
uint8 internal constant CLAIM_FLAG_ETH_ADDR_LOWERCASE = 1 << 4;
/* Globals expanded for memory (except _latestStakeId) and compact for storage */
struct GlobalsCache {
// 1
uint256 _lockedHeartsTotal;
uint256 _nextStakeSharesTotal;
uint256 _shareRate;
uint256 _stakePenaltyTotal;
// 2
uint256 _dailyDataCount;
uint256 _stakeSharesTotal;
uint40 _latestStakeId;
uint256 _unclaimedSatoshisTotal;
uint256 _claimedSatoshisTotal;
uint256 _claimedBtcAddrCount;
//
uint256 _currentDay;
}
struct GlobalsStore {
// 1
uint72 lockedHeartsTotal;
uint72 nextStakeSharesTotal;
uint40 shareRate;
uint72 stakePenaltyTotal;
// 2
uint16 dailyDataCount;
uint72 stakeSharesTotal;
uint40 latestStakeId;
uint128 claimStats;
}
GlobalsStore public globals;
/* Claimed BTC addresses */
mapping(bytes20 => bool) public btcAddressClaims;
/* Daily data */
struct DailyDataStore {
uint72 dayPayoutTotal;
uint72 dayStakeSharesTotal;
uint56 dayUnclaimedSatoshisTotal;
}
mapping(uint256 => DailyDataStore) public dailyData;
/* Stake expanded for memory (except _stakeId) and compact for storage */
struct StakeCache {
uint40 _stakeId;
uint256 _stakedHearts;
uint256 _stakeShares;
uint256 _lockedDay;
uint256 _stakedDays;
uint256 _unlockedDay;
bool _isAutoStake;
}
struct StakeStore {
uint40 stakeId;
uint72 stakedHearts;
uint72 stakeShares;
uint16 lockedDay;
uint16 stakedDays;
uint16 unlockedDay;
bool isAutoStake;
}
mapping(address => StakeStore[]) public stakeLists;
/* Temporary state for calculating daily rounds */
struct DailyRoundState {
uint256 _allocSupplyCached;
uint256 _mintOriginBatch;
uint256 _payoutTotal;
}
struct XfLobbyEntryStore {
uint96 rawAmount;
address referrerAddr;
}
struct XfLobbyQueueStore {
uint40 headIndex;
uint40 tailIndex;
mapping(uint256 => XfLobbyEntryStore) entries;
}
mapping(uint256 => uint256) public xfLobby;
mapping(uint256 => mapping(address => XfLobbyQueueStore)) public xfLobbyMembers;
/**
* @dev PUBLIC FACING: Optionally update daily data for a smaller
* range to reduce gas cost for a subsequent operation
* @param beforeDay Only update days before this day number (optional; 0 for current day)
*/
function dailyDataUpdate(uint256 beforeDay)
external
{
GlobalsCache memory g;
GlobalsCache memory gSnapshot;
_globalsLoad(g, gSnapshot);
/* Skip pre-claim period */
require(g._currentDay > CLAIM_PHASE_START_DAY, "HEX: Too early");
if (beforeDay != 0) {
require(beforeDay <= g._currentDay, "HEX: beforeDay cannot be in the future");
_dailyDataUpdate(g, beforeDay, false);
} else {
/* Default to updating before current day */
_dailyDataUpdate(g, g._currentDay, false);
}
_globalsSync(g, gSnapshot);
}
/**
* @dev PUBLIC FACING: External helper to return multiple values of daily data with
* a single call. Ugly implementation due to limitations of the standard ABI encoder.
* @param beginDay First day of data range
* @param endDay Last day (non-inclusive) of data range
* @return Fixed array of packed values
*/
function dailyDataRange(uint256 beginDay, uint256 endDay)
external
view
returns (uint256[] memory list)
{
require(beginDay < endDay && endDay <= globals.dailyDataCount, "HEX: range invalid");
list = new uint256[](endDay - beginDay);
uint256 src ; //inject UNINIT LOCAL/STATE VAR
uint256 dst ; //inject UNINIT LOCAL/STATE VAR
uint256 v;
do {
v = uint256(dailyData[src].dayUnclaimedSatoshisTotal) << (HEART_UINT_SIZE * 2);
v |= uint256(dailyData[src].dayStakeSharesTotal) << HEART_UINT_SIZE;
v |= uint256(dailyData[src].dayPayoutTotal);
list[dst++] = v;
} while (++src < endDay);
return list;
}
/**
* @dev PUBLIC FACING: External helper to return most global info with a single call.
* Ugly implementation due to limitations of the standard ABI encoder.
* @return Fixed array of values
*/
function globalInfo()
external
view
returns (uint256[13] memory)
{
uint256 _claimedBtcAddrCount;
uint256 _claimedSatoshisTotal;
uint256 _unclaimedSatoshisTotal;
(_claimedBtcAddrCount, _claimedSatoshisTotal, _unclaimedSatoshisTotal) = _claimStatsDecode(
globals.claimStats
);
return [
// 1
globals.lockedHeartsTotal,
globals.nextStakeSharesTotal,
globals.shareRate,
globals.stakePenaltyTotal,
// 2
globals.dailyDataCount,
globals.stakeSharesTotal,
globals.latestStakeId,
_unclaimedSatoshisTotal,
_claimedSatoshisTotal,
_claimedBtcAddrCount,
//
block.timestamp,
totalSupply(),
xfLobby[_currentDay()]
];
}
/**
* @dev PUBLIC FACING: ERC20 totalSupply() is the circulating supply and does not include any
* staked Hearts. allocatedSupply() includes both.
* @return Allocated Supply in Hearts
*/
function allocatedSupply()
external
view
returns (uint256)
{
return totalSupply() + globals.lockedHeartsTotal;
}
/**
* @dev PUBLIC FACING: External helper for the current day number since launch time
* @return Current day number (zero-based)
*/
function currentDay()
external
view
returns (uint256)
{
return _currentDay();
}
function _currentDay()
internal
view
returns (uint256)
{
return (block.timestamp - LAUNCH_TIME) / 1 days;
}
function _dailyDataUpdateAuto(GlobalsCache memory g)
internal
{
_dailyDataUpdate(g, g._currentDay, true);
}
function _globalsLoad(GlobalsCache memory g, GlobalsCache memory gSnapshot)
internal
view
{
// 1
g._lockedHeartsTotal = globals.lockedHeartsTotal;
g._nextStakeSharesTotal = globals.nextStakeSharesTotal;
g._shareRate = globals.shareRate;
g._stakePenaltyTotal = globals.stakePenaltyTotal;
// 2
g._dailyDataCount = globals.dailyDataCount;
g._stakeSharesTotal = globals.stakeSharesTotal;
g._latestStakeId = globals.latestStakeId;
(g._claimedBtcAddrCount, g._claimedSatoshisTotal, g._unclaimedSatoshisTotal) = _claimStatsDecode(
globals.claimStats
);
//
g._currentDay = _currentDay();
_globalsCacheSnapshot(g, gSnapshot);
}
function _globalsCacheSnapshot(GlobalsCache memory g, GlobalsCache memory gSnapshot)
internal
pure
{
// 1
gSnapshot._lockedHeartsTotal = g._lockedHeartsTotal;
gSnapshot._nextStakeSharesTotal = g._nextStakeSharesTotal;
gSnapshot._shareRate = g._shareRate;
gSnapshot._stakePenaltyTotal = g._stakePenaltyTotal;
// 2
gSnapshot._dailyDataCount = g._dailyDataCount;
gSnapshot._stakeSharesTotal = g._stakeSharesTotal;
gSnapshot._latestStakeId = g._latestStakeId;
gSnapshot._unclaimedSatoshisTotal = g._unclaimedSatoshisTotal;
gSnapshot._claimedSatoshisTotal = g._claimedSatoshisTotal;
gSnapshot._claimedBtcAddrCount = g._claimedBtcAddrCount;
}
function _globalsSync(GlobalsCache memory g, GlobalsCache memory gSnapshot)
internal
{
if (g._lockedHeartsTotal != gSnapshot._lockedHeartsTotal
|| g._nextStakeSharesTotal != gSnapshot._nextStakeSharesTotal
|| g._shareRate != gSnapshot._shareRate
|| g._stakePenaltyTotal != gSnapshot._stakePenaltyTotal) {
// 1
globals.lockedHeartsTotal = uint72(g._lockedHeartsTotal);
globals.nextStakeSharesTotal = uint72(g._nextStakeSharesTotal);
globals.shareRate = uint40(g._shareRate);
globals.stakePenaltyTotal = uint72(g._stakePenaltyTotal);
}
if (g._dailyDataCount != gSnapshot._dailyDataCount
|| g._stakeSharesTotal != gSnapshot._stakeSharesTotal
|| g._latestStakeId != gSnapshot._latestStakeId
|| g._unclaimedSatoshisTotal != gSnapshot._unclaimedSatoshisTotal
|| g._claimedSatoshisTotal != gSnapshot._claimedSatoshisTotal
|| g._claimedBtcAddrCount != gSnapshot._claimedBtcAddrCount) {
// 2
globals.dailyDataCount = uint16(g._dailyDataCount);
globals.stakeSharesTotal = uint72(g._stakeSharesTotal);
globals.latestStakeId = g._latestStakeId;
globals.claimStats = _claimStatsEncode(
g._claimedBtcAddrCount,
g._claimedSatoshisTotal,
g._unclaimedSatoshisTotal
);
}
}
function _stakeLoad(StakeStore storage stRef, uint40 stakeIdParam, StakeCache memory st)
internal
view
{
/* Ensure caller's stakeIndex is still current */
require(stakeIdParam == stRef.stakeId, "HEX: stakeIdParam not in stake");
st._stakeId = stRef.stakeId;
st._stakedHearts = stRef.stakedHearts;
st._stakeShares = stRef.stakeShares;
st._lockedDay = stRef.lockedDay;
st._stakedDays = stRef.stakedDays;
st._unlockedDay = stRef.unlockedDay;
st._isAutoStake = stRef.isAutoStake;
}
function _stakeUpdate(StakeStore storage stRef, StakeCache memory st)
internal
{
stRef.stakeId = st._stakeId;
stRef.stakedHearts = uint72(st._stakedHearts);
stRef.stakeShares = uint72(st._stakeShares);
stRef.lockedDay = uint16(st._lockedDay);
stRef.stakedDays = uint16(st._stakedDays);
stRef.unlockedDay = uint16(st._unlockedDay);
stRef.isAutoStake = st._isAutoStake;
}
function _stakeAdd(
StakeStore[] storage stakeListRef,
uint40 newStakeId,
uint256 newStakedHearts,
uint256 newStakeShares,
uint256 newLockedDay,
uint256 newStakedDays,
bool newAutoStake
)
internal
{
stakeListRef.push(
StakeStore(
newStakeId,
uint72(newStakedHearts),
uint72(newStakeShares),
uint16(newLockedDay),
uint16(newStakedDays),
uint16(0), // unlockedDay
newAutoStake
)
);
}
/**
* @dev Efficiently delete from an unordered array by moving the last element
* to the "hole" and reducing the array length. Can change the order of the list
* and invalidate previously held indexes.
* @notice stakeListRef length and stakeIndex are already ensured valid in stakeEnd()
* @param stakeListRef Reference to stakeLists[stakerAddr] array in storage
* @param stakeIndex Index of the element to delete
*/
function _stakeRemove(StakeStore[] storage stakeListRef, uint256 stakeIndex)
internal
{
uint256 lastIndex ; //inject UNINIT LOCAL/STATE VAR
/* Skip the copy if element to be removed is already the last element */
if (stakeIndex != lastIndex) {
/* Copy last element to the requested element's "hole" */
stakeListRef[stakeIndex] = stakeListRef[lastIndex];
}
/*
Reduce the array length now that the array is contiguous.
Surprisingly, 'pop()' uses less gas than 'stakeListRef.length = lastIndex'
*/
stakeListRef.pop();
}
function _claimStatsEncode(
uint256 _claimedBtcAddrCount,
uint256 _claimedSatoshisTotal,
uint256 _unclaimedSatoshisTotal
)
internal
pure
returns (uint128)
{
uint256 v ; //inject UNINIT LOCAL/STATE VAR
v |= _claimedSatoshisTotal << SATOSHI_UINT_SIZE;
v |= _unclaimedSatoshisTotal;
return uint128(v);
}
function _claimStatsDecode(uint128 v)
internal
pure
returns (uint256 _claimedBtcAddrCount, uint256 _claimedSatoshisTotal, uint256 _unclaimedSatoshisTotal)
{
_claimedBtcAddrCount = v >> (SATOSHI_UINT_SIZE * 2);
_claimedSatoshisTotal = (v >> SATOSHI_UINT_SIZE) & SATOSHI_UINT_MASK;
_unclaimedSatoshisTotal = v & SATOSHI_UINT_MASK;
return (_claimedBtcAddrCount, _claimedSatoshisTotal, _unclaimedSatoshisTotal);
}
/**
* @dev Estimate the stake payout for an incomplete day
* @param g Cache of stored globals
* @param stakeSharesParam Param from stake to calculate bonuses for
* @param day Day to calculate bonuses for
* @return Payout in Hearts
*/
function _estimatePayoutRewardsDay(GlobalsCache memory g, uint256 stakeSharesParam, uint256 day)
internal
view
returns (uint256 payout)
{
/* Prevent updating state for this estimation */
GlobalsCache memory gTmp;
_globalsCacheSnapshot(g, gTmp);
DailyRoundState memory rs;
rs._allocSupplyCached = totalSupply() + g._lockedHeartsTotal;
_dailyRoundCalc(gTmp, rs, day);
/* Stake is no longer locked so it must be added to total as if it were */
gTmp._stakeSharesTotal += stakeSharesParam;
payout = rs._payoutTotal * stakeSharesParam / gTmp._stakeSharesTotal;
if (day == BIG_PAY_DAY) {
uint256 bigPaySlice ; //inject UNINIT LOCAL/STATE VAR
payout += bigPaySlice + _calcAdoptionBonus(gTmp, bigPaySlice);
}
return payout;
}
function _calcAdoptionBonus(GlobalsCache memory g, uint256 payout)
internal
pure
returns (uint256)
{
/*
VIRAL REWARDS: Add adoption percentage bonus to payout
viral = payout * (claimedBtcAddrCount / CLAIMABLE_BTC_ADDR_COUNT)
*/
uint256 viral ; //inject UNINIT LOCAL/STATE VAR
/*
CRIT MASS REWARDS: Add adoption percentage bonus to payout
crit = payout * (claimedSatoshisTotal / CLAIMABLE_SATOSHIS_TOTAL)
*/
uint256 crit ; //inject UNINIT LOCAL/STATE VAR
return viral + crit;
}
function _dailyRoundCalc(GlobalsCache memory g, DailyRoundState memory rs, uint256 day)
private
pure
{
/*
Calculate payout round
Inflation of 3.69% inflation per 364 days (approx 1 year)
dailyInterestRate = exp(log(1 + 3.69%) / 364) - 1
= exp(log(1 + 0.0369) / 364) - 1
= exp(log(1.0369) / 364) - 1
= 0.000099553011616349 (approx)
payout = allocSupply * dailyInterestRate
= allocSupply / (1 / dailyInterestRate)
= allocSupply / (1 / 0.000099553011616349)
= allocSupply / 10044.899534066692 (approx)
= allocSupply * 10000 / 100448995 (* 10000/10000 for int precision)
*/
rs._payoutTotal = rs._allocSupplyCached * 10000 / 100448995;
if (day < CLAIM_PHASE_END_DAY) {
uint256 bigPaySlice ; //inject UNINIT LOCAL/STATE VAR
uint256 originBonus ; //inject UNINIT LOCAL/STATE VAR
rs._mintOriginBatch += originBonus;
rs._allocSupplyCached += originBonus;
rs._payoutTotal += _calcAdoptionBonus(g, rs._payoutTotal);
}
if (g._stakePenaltyTotal != 0) {
rs._payoutTotal += g._stakePenaltyTotal;
g._stakePenaltyTotal = 0;
}
}
function _dailyRoundCalcAndStore(GlobalsCache memory g, DailyRoundState memory rs, uint256 day)
private
{
_dailyRoundCalc(g, rs, day);
dailyData[day].dayPayoutTotal = uint72(rs._payoutTotal);
dailyData[day].dayStakeSharesTotal = uint72(g._stakeSharesTotal);
dailyData[day].dayUnclaimedSatoshisTotal = uint56(g._unclaimedSatoshisTotal);
}
function _dailyDataUpdate(GlobalsCache memory g, uint256 beforeDay, bool isAutoUpdate)
private
{
if (g._dailyDataCount >= beforeDay) {
/* Already up-to-date */
return;
}
DailyRoundState memory rs;
rs._allocSupplyCached = totalSupply() + g._lockedHeartsTotal;
uint256 day ; //inject UNINIT LOCAL/STATE VAR
_dailyRoundCalcAndStore(g, rs, day);
/* Stakes started during this day are added to the total the next day */
if (g._nextStakeSharesTotal != 0) {
g._stakeSharesTotal += g._nextStakeSharesTotal;
g._nextStakeSharesTotal = 0;
}
while (++day < beforeDay) {
_dailyRoundCalcAndStore(g, rs, day);
}
_emitDailyDataUpdate(g._dailyDataCount, day, isAutoUpdate);
g._dailyDataCount = day;
if (rs._mintOriginBatch != 0) {
_mint(ORIGIN_ADDR, rs._mintOriginBatch);
}
}
function _emitDailyDataUpdate(uint256 beginDay, uint256 endDay, bool isAutoUpdate)
private
{
emit DailyDataUpdate( // (auto-generated event)
uint256(uint40(block.timestamp))
| (uint256(uint16(beginDay)) << 40)
| (uint256(uint16(endDay)) << 56)
| (isAutoUpdate ? (1 << 72) : 0),
msg.sender
);
}
}
contract StakeableToken is GlobalsAndUtility {
/**
* @dev PUBLIC FACING: Open a stake.
* @param newStakedHearts Number of Hearts to stake
* @param newStakedDays Number of days to stake
*/
function stakeStart(uint256 newStakedHearts, uint256 newStakedDays)
external
{
GlobalsCache memory g;
GlobalsCache memory gSnapshot;
_globalsLoad(g, gSnapshot);
/* Enforce the minimum stake time */
require(newStakedDays >= MIN_STAKE_DAYS, "HEX: newStakedDays lower than minimum");
/* Check if log data needs to be updated */
_dailyDataUpdateAuto(g);
_stakeStart(g, newStakedHearts, newStakedDays, false);
/* Remove staked Hearts from balance of staker */
_burn(msg.sender, newStakedHearts);
_globalsSync(g, gSnapshot);
}
/**
* @dev PUBLIC FACING: Unlocks a completed stake, distributing the proceeds of any penalty
* immediately. The staker must still call stakeEnd() to retrieve their stake return (if any).
* @param stakerAddr Address of staker
* @param stakeIndex Index of stake within stake list
* @param stakeIdParam The stake's id
*/
function stakeGoodAccounting(address stakerAddr, uint256 stakeIndex, uint40 stakeIdParam)
external
{
GlobalsCache memory g;
GlobalsCache memory gSnapshot;
_globalsLoad(g, gSnapshot);
/* require() is more informative than the default assert() */
require(stakeLists[stakerAddr].length != 0, "HEX: Empty stake list");
require(stakeIndex < stakeLists[stakerAddr].length, "HEX: stakeIndex invalid");
StakeStore storage stRef = stakeLists[stakerAddr][stakeIndex];
/* Get stake copy */
StakeCache memory st;
_stakeLoad(stRef, stakeIdParam, st);
/* Stake must have served full term */
require(g._currentDay >= st._lockedDay + st._stakedDays, "HEX: Stake not fully served");
/* Stake must still be locked */
require(st._unlockedDay == 0, "HEX: Stake already unlocked");
/* Check if log data needs to be updated */
_dailyDataUpdateAuto(g);
/* Unlock the completed stake */
_stakeUnlock(g, st);
/* stakeReturn value is unused here */
(, uint256 payout, uint256 penalty, uint256 cappedPenalty) = _stakePerformance(
g,
st,
st._stakedDays
);
_emitStakeGoodAccounting(
stakerAddr,
stakeIdParam,
st._stakedHearts,
st._stakeShares,
payout,
penalty
);
if (cappedPenalty != 0) {
_splitPenaltyProceeds(g, cappedPenalty);
}
/* st._unlockedDay has changed */
_stakeUpdate(stRef, st);
_globalsSync(g, gSnapshot);
}
/**
* @dev PUBLIC FACING: Closes a stake. The order of the stake list can change so
* a stake id is used to reject stale indexes.
* @param stakeIndex Index of stake within stake list
* @param stakeIdParam The stake's id
*/
function stakeEnd(uint256 stakeIndex, uint40 stakeIdParam)
external
{
GlobalsCache memory g;
GlobalsCache memory gSnapshot;
_globalsLoad(g, gSnapshot);
StakeStore[] storage stakeListRef = stakeLists[msg.sender];
/* require() is more informative than the default assert() */
require(stakeListRef.length != 0, "HEX: Empty stake list");
require(stakeIndex < stakeListRef.length, "HEX: stakeIndex invalid");
/* Get stake copy */
StakeCache memory st;
_stakeLoad(stakeListRef[stakeIndex], stakeIdParam, st);
/* Check if log data needs to be updated */
_dailyDataUpdateAuto(g);
uint256 servedDays ; //inject UNINIT LOCAL/STATE VAR
bool prevUnlocked ; //inject UNINIT LOCAL/STATE VAR
uint256 stakeReturn;
uint256 payout ; //inject UNINIT LOCAL/STATE VAR
uint256 penalty ; //inject UNINIT LOCAL/STATE VAR
uint256 cappedPenalty ; //inject UNINIT LOCAL/STATE VAR
if (g._currentDay >= st._lockedDay) {
if (prevUnlocked) {
/* Previously unlocked in stakeGoodAccounting(), so must have served full term */
servedDays = st._stakedDays;
} else {
_stakeUnlock(g, st);
servedDays = g._currentDay - st._lockedDay;
if (servedDays > st._stakedDays) {
servedDays = st._stakedDays;
} else {
/* Deny early-unstake before an auto-stake minimum has been served */
if (servedDays < MIN_AUTO_STAKE_DAYS) {
require(!st._isAutoStake, "HEX: Auto-stake still locked");
}
}
}
(stakeReturn, payout, penalty, cappedPenalty) = _stakePerformance(g, st, servedDays);
} else {
/* Deny early-unstake before an auto-stake minimum has been served */
require(!st._isAutoStake, "HEX: Auto-stake still locked");
/* Stake hasn't been added to the total yet, so no penalties or rewards apply */
g._nextStakeSharesTotal -= st._stakeShares;
stakeReturn = st._stakedHearts;
}
_emitStakeEnd(
stakeIdParam,
st._stakedHearts,
st._stakeShares,
payout,
penalty,
servedDays,
prevUnlocked
);
if (cappedPenalty != 0 && !prevUnlocked) {
/* Split penalty proceeds only if not previously unlocked by stakeGoodAccounting() */
_splitPenaltyProceeds(g, cappedPenalty);
}
/* Pay the stake return, if any, to the staker */
if (stakeReturn != 0) {
_mint(msg.sender, stakeReturn);
/* Update the share rate if necessary */
_shareRateUpdate(g, st, stakeReturn);
}
g._lockedHeartsTotal -= st._stakedHearts;
_stakeRemove(stakeListRef, stakeIndex);
_globalsSync(g, gSnapshot);
}
/**
* @dev PUBLIC FACING: Return the current stake count for a staker address
* @param stakerAddr Address of staker
*/
function stakeCount(address stakerAddr)
external
view
returns (uint256)
{
return stakeLists[stakerAddr].length;
}
/**
* @dev Open a stake.
* @param g Cache of stored globals
* @param newStakedHearts Number of Hearts to stake
* @param newStakedDays Number of days to stake
* @param newAutoStake Stake is automatic directly from a new claim
*/
function _stakeStart(
GlobalsCache memory g,
uint256 newStakedHearts,
uint256 newStakedDays,
bool newAutoStake
)
internal
{
/* Enforce the maximum stake time */
require(newStakedDays <= MAX_STAKE_DAYS, "HEX: newStakedDays higher than maximum");
uint256 bonusHearts ; //inject UNINIT LOCAL/STATE VAR
uint256 newStakeShares ; //inject UNINIT LOCAL/STATE VAR
/* Ensure newStakedHearts is enough for at least one stake share */
require(newStakeShares != 0, "HEX: newStakedHearts must be at least minimum shareRate");
/*
The stakeStart timestamp will always be part-way through the current
day, so it needs to be rounded-up to the next day to ensure all
stakes align with the same fixed calendar days. The current day is
already rounded-down, so rounded-up is current day + 1.
*/
uint256 newLockedDay ; //inject UNINIT LOCAL/STATE VAR
/* Create Stake */
uint40 newStakeId ; //inject UNINIT LOCAL/STATE VAR
_stakeAdd(
stakeLists[msg.sender],
newStakeId,
newStakedHearts,
newStakeShares,
newLockedDay,
newStakedDays,
newAutoStake
);
_emitStakeStart(newStakeId, newStakedHearts, newStakeShares, newStakedDays, newAutoStake);
/* Stake is added to total in the next round, not the current round */
g._nextStakeSharesTotal += newStakeShares;
/* Track total staked Hearts for inflation calculations */
g._lockedHeartsTotal += newStakedHearts;
}
/**
* @dev Calculates total stake payout including rewards for a multi-day range
* @param g Cache of stored globals
* @param stakeSharesParam Param from stake to calculate bonuses for
* @param beginDay First day to calculate bonuses for
* @param endDay Last day (non-inclusive) of range to calculate bonuses for
* @return Payout in Hearts
*/
function _calcPayoutRewards(
GlobalsCache memory g,
uint256 stakeSharesParam,
uint256 beginDay,
uint256 endDay
)
private
view
returns (uint256 payout)
{
for (uint256 day ; day < endDay; day++) { //inject UNINIT LOCAL/STATE VAR
payout += dailyData[day].dayPayoutTotal * stakeSharesParam
/ dailyData[day].dayStakeSharesTotal;
}
/* Less expensive to re-read storage than to have the condition inside the loop */
if (beginDay <= BIG_PAY_DAY && endDay > BIG_PAY_DAY) {
uint256 bigPaySlice ; //inject UNINIT LOCAL/STATE VAR
payout += bigPaySlice + _calcAdoptionBonus(g, bigPaySlice);
}
return payout;
}
/**
* @dev Calculate bonus Hearts for a new stake, if any
* @param newStakedHearts Number of Hearts to stake
* @param newStakedDays Number of days to stake
*/
function _stakeStartBonusHearts(uint256 newStakedHearts, uint256 newStakedDays)
private
pure
returns (uint256 bonusHearts)
{
/*
LONGER PAYS BETTER:
If longer than 1 day stake is committed to, each extra day
gives bonus shares of approximately 0.0548%, which is approximately 20%
extra per year of increased stake length committed to, but capped to a
maximum of 200% extra.
extraDays = stakedDays - 1
longerBonus% = (extraDays / 364) * 20%
= (extraDays / 364) / 5
= extraDays / 1820
= extraDays / LPB
extraDays = longerBonus% * 1820
extraDaysMax = longerBonusMax% * 1820
= 200% * 1820
= 3640
= LPB_MAX_DAYS
BIGGER PAYS BETTER:
Bonus percentage scaled 0% to 10% for the first 150M HEX of stake.
biggerBonus% = (cappedHearts / BPB_MAX_HEARTS) * 10%
= (cappedHearts / BPB_MAX_HEARTS) / 10
= cappedHearts / (BPB_MAX_HEARTS * 10)
= cappedHearts / BPB
COMBINED:
combinedBonus% = longerBonus% + biggerBonus%
cappedExtraDays cappedHearts
= --------------- + ------------
LPB BPB
cappedExtraDays * BPB cappedHearts * LPB
= --------------------- + ------------------
LPB * BPB LPB * BPB
cappedExtraDays * BPB + cappedHearts * LPB
= --------------------------------------------
LPB * BPB
bonusHearts = hearts * combinedBonus%
= hearts * (cappedExtraDays * BPB + cappedHearts * LPB) / (LPB * BPB)
*/
uint256 cappedExtraDays ; //inject UNINIT LOCAL/STATE VAR
/* Must be more than 1 day for Longer-Pays-Better */
if (newStakedDays > 1) {
cappedExtraDays = newStakedDays <= LPB_MAX_DAYS ? newStakedDays - 1 : LPB_MAX_DAYS;
}
uint256 cappedStakedHearts ; //inject UNINIT LOCAL/STATE VAR
bonusHearts = cappedExtraDays * BPB + cappedStakedHearts * LPB;
bonusHearts = newStakedHearts * bonusHearts / (LPB * BPB);
return bonusHearts;
}
function _stakeUnlock(GlobalsCache memory g, StakeCache memory st)
private
pure
{
g._stakeSharesTotal -= st._stakeShares;
st._unlockedDay = g._currentDay;
}
function _stakePerformance(GlobalsCache memory g, StakeCache memory st, uint256 servedDays)
private
view
returns (uint256 stakeReturn, uint256 payout, uint256 penalty, uint256 cappedPenalty)
{
if (servedDays < st._stakedDays) {
(payout, penalty) = _calcPayoutAndEarlyPenalty(
g,
st._lockedDay,
st._stakedDays,
servedDays,
st._stakeShares
);
stakeReturn = st._stakedHearts + payout;
} else {
// servedDays must == stakedDays here
payout = _calcPayoutRewards(
g,
st._stakeShares,
st._lockedDay,
st._lockedDay + servedDays
);
stakeReturn = st._stakedHearts + payout;
penalty = _calcLatePenalty(st._lockedDay, st._stakedDays, st._unlockedDay, stakeReturn);
}
if (penalty != 0) {
if (penalty > stakeReturn) {
/* Cannot have a negative stake return */
cappedPenalty = stakeReturn;
stakeReturn = 0;
} else {
/* Remove penalty from the stake return */
cappedPenalty = penalty;
stakeReturn -= cappedPenalty;
}
}
return (stakeReturn, payout, penalty, cappedPenalty);
}
function _calcPayoutAndEarlyPenalty(
GlobalsCache memory g,
uint256 lockedDayParam,
uint256 stakedDaysParam,
uint256 servedDays,
uint256 stakeSharesParam
)
private
view
returns (uint256 payout, uint256 penalty)
{
uint256 servedEndDay ; //inject UNINIT LOCAL/STATE VAR
/* 50% of stakedDays (rounded up) with a minimum applied */
uint256 penaltyDays ; //inject UNINIT LOCAL/STATE VAR
if (penaltyDays < EARLY_PENALTY_MIN_DAYS) {
penaltyDays = EARLY_PENALTY_MIN_DAYS;
}
if (servedDays == 0) {
/* Fill penalty days with the estimated average payout */
uint256 expected ; //inject UNINIT LOCAL/STATE VAR
penalty = expected * penaltyDays;
return (payout, penalty); // Actual payout was 0
}
if (penaltyDays < servedDays) {
/*
Simplified explanation of intervals where end-day is non-inclusive:
penalty: [lockedDay ... penaltyEndDay)
delta: [penaltyEndDay ... servedEndDay)
payout: [lockedDay ....................... servedEndDay)
*/
uint256 penaltyEndDay ; //inject UNINIT LOCAL/STATE VAR
penalty = _calcPayoutRewards(g, stakeSharesParam, lockedDayParam, penaltyEndDay);
uint256 delta ; //inject UNINIT LOCAL/STATE VAR
payout = penalty + delta;
return (payout, penalty);
}
/* penaltyDays >= servedDays */
payout = _calcPayoutRewards(g, stakeSharesParam, lockedDayParam, servedEndDay);
if (penaltyDays == servedDays) {
penalty = payout;
} else {
/*
(penaltyDays > servedDays) means not enough days served, so fill the
penalty days with the average payout from only the days that were served.
*/
penalty = payout * penaltyDays / servedDays;
}
return (payout, penalty);
}
function _calcLatePenalty(
uint256 lockedDayParam,
uint256 stakedDaysParam,
uint256 unlockedDayParam,
uint256 rawStakeReturn
)
private
pure
returns (uint256)
{
/* Allow grace time before penalties accrue */
uint256 maxUnlockedDay ; //inject UNINIT LOCAL/STATE VAR
if (unlockedDayParam <= maxUnlockedDay) {
return 0;
}
/* Calculate penalty as a percentage of stake return based on time */
return rawStakeReturn * (unlockedDayParam - maxUnlockedDay) / LATE_PENALTY_SCALE_DAYS;
}
function _splitPenaltyProceeds(GlobalsCache memory g, uint256 penalty)
private
{
/* Split a penalty 50:50 between Origin and stakePenaltyTotal */
uint256 splitPenalty ; //inject UNINIT LOCAL/STATE VAR
if (splitPenalty != 0) {
_mint(ORIGIN_ADDR, splitPenalty);
}
/* Use the other half of the penalty to account for an odd-numbered penalty */
splitPenalty = penalty - splitPenalty;
g._stakePenaltyTotal += splitPenalty;
}
function _shareRateUpdate(GlobalsCache memory g, StakeCache memory st, uint256 stakeReturn)
private
{
if (stakeReturn > st._stakedHearts) {
/*
Calculate the new shareRate that would yield the same number of shares if
the user re-staked this stakeReturn, factoring in any bonuses they would
receive in stakeStart().
*/
uint256 bonusHearts ; //inject UNINIT LOCAL/STATE VAR
uint256 newShareRate ; //inject UNINIT LOCAL/STATE VAR
if (newShareRate > SHARE_RATE_MAX) {
/*
Realistically this can't happen, but there are contrived theoretical
scenarios that can lead to extreme values of newShareRate, so it is
capped to prevent them anyway.
*/
newShareRate = SHARE_RATE_MAX;
}
if (newShareRate > g._shareRate) {
g._shareRate = newShareRate;
_emitShareRateChange(newShareRate, st._stakeId);
}
}
}
function _emitStakeStart(
uint40 stakeId,
uint256 stakedHearts,
uint256 stakeShares,
uint256 stakedDays,
bool isAutoStake
)
private
{
emit StakeStart( // (auto-generated event)
uint256(uint40(block.timestamp))
| (uint256(uint72(stakedHearts)) << 40)
| (uint256(uint72(stakeShares)) << 112)
| (uint256(uint16(stakedDays)) << 184)
| (isAutoStake ? (1 << 200) : 0),
msg.sender,
stakeId
);
}
function _emitStakeGoodAccounting(
address stakerAddr,
uint40 stakeId,
uint256 stakedHearts,
uint256 stakeShares,
uint256 payout,
uint256 penalty
)
private
{
emit StakeGoodAccounting( // (auto-generated event)
uint256(uint40(block.timestamp))
| (uint256(uint72(stakedHearts)) << 40)
| (uint256(uint72(stakeShares)) << 112)
| (uint256(uint72(payout)) << 184),
uint256(uint72(penalty)),
stakerAddr,
stakeId,
msg.sender
);
}
function _emitStakeEnd(
uint40 stakeId,
uint256 stakedHearts,
uint256 stakeShares,
uint256 payout,
uint256 penalty,
uint256 servedDays,
bool prevUnlocked
)
private
{
emit StakeEnd( // (auto-generated event)
uint256(uint40(block.timestamp))
| (uint256(uint72(stakedHearts)) << 40)
| (uint256(uint72(stakeShares)) << 112)
| (uint256(uint72(payout)) << 184),
uint256(uint72(penalty))
| (uint256(uint16(servedDays)) << 72)
| (prevUnlocked ? (1 << 88) : 0),
msg.sender,
stakeId
);
}
function _emitShareRateChange(uint256 shareRate, uint40 stakeId)
private
{
emit ShareRateChange( // (auto-generated event)
uint256(uint40(block.timestamp))
| (uint256(uint40(shareRate)) << 40),
stakeId
);
}
}
/**
* @dev These functions deal with verification of Merkle trees (hash trees),
*/
library MerkleProof {
/**
* @dev Returns true if a `leaf` can be proved to be a part of a Merkle tree
* defined by `root`. For this, a `proof` must be provided, containing
* sibling hashes on the branch from the leaf to the root of the tree. Each
* pair of leaves and each pair of pre-images are assumed to be sorted.
*/
function verify(bytes32[] memory proof, bytes32 root, bytes32 leaf) internal pure returns (bool) {
bytes32 computedHash ; //inject UNINIT LOCAL/STATE VAR
for (uint256 i ; i < proof.length; i++) { //inject UNINIT LOCAL/STATE VAR
bytes32 proofElement ; //inject UNINIT LOCAL/STATE VAR
if (computedHash < proofElement) {
// Hash(current computed hash + current element of the proof)
computedHash = keccak256(abi.encodePacked(computedHash, proofElement));
} else {
// Hash(current element of the proof + current computed hash)
computedHash = keccak256(abi.encodePacked(proofElement, computedHash));
}
}
// Check if the computed hash (root) is equal to the provided root
return computedHash == root;
}
}
contract UTXOClaimValidation is StakeableToken {
/**
* @dev PUBLIC FACING: Verify a BTC address and balance are unclaimed and part of the Merkle tree
* @param btcAddr Bitcoin address (binary; no base58-check encoding)
* @param rawSatoshis Raw BTC address balance in Satoshis
* @param proof Merkle tree proof
* @return True if can be claimed
*/
function btcAddressIsClaimable(bytes20 btcAddr, uint256 rawSatoshis, bytes32[] calldata proof)
external
view
returns (bool)
{
uint256 day ; //inject UNINIT LOCAL/STATE VAR
require(day >= CLAIM_PHASE_START_DAY, "HEX: Claim phase has not yet started");
require(day < CLAIM_PHASE_END_DAY, "HEX: Claim phase has ended");
/* Don't need to check Merkle proof if UTXO BTC address has already been claimed */
if (btcAddressClaims[btcAddr]) {
return false;
}
/* Verify the Merkle tree proof */
return _btcAddressIsValid(btcAddr, rawSatoshis, proof);
}
/**
* @dev PUBLIC FACING: Verify a BTC address and balance are part of the Merkle tree
* @param btcAddr Bitcoin address (binary; no base58-check encoding)
* @param rawSatoshis Raw BTC address balance in Satoshis
* @param proof Merkle tree proof
* @return True if valid
*/
function btcAddressIsValid(bytes20 btcAddr, uint256 rawSatoshis, bytes32[] calldata proof)
external
pure
returns (bool)
{
return _btcAddressIsValid(btcAddr, rawSatoshis, proof);
}
/**
* @dev PUBLIC FACING: Verify a Merkle proof using the UTXO Merkle tree
* @param merkleLeaf Leaf asserted to be present in the Merkle tree
* @param proof Generated Merkle tree proof
* @return True if valid
*/
function merkleProofIsValid(bytes32 merkleLeaf, bytes32[] calldata proof)
external
pure
returns (bool)
{
return _merkleProofIsValid(merkleLeaf, proof);
}
/**
* @dev PUBLIC FACING: Verify that a Bitcoin signature matches the claim message containing
* the Ethereum address and claim param hash
* @param claimToAddr Eth address within the signed claim message
* @param claimParamHash Param hash within the signed claim message
* @param pubKeyX First half of uncompressed ECDSA public key
* @param pubKeyY Second half of uncompressed ECDSA public key
* @param claimFlags Claim flags specifying address and message formats
* @param v v parameter of ECDSA signature
* @param r r parameter of ECDSA signature
* @param s s parameter of ECDSA signature
* @return True if matching
*/
function claimMessageMatchesSignature(
address claimToAddr,
bytes32 claimParamHash,
bytes32 pubKeyX,
bytes32 pubKeyY,
uint8 claimFlags,
uint8 v,
bytes32 r,
bytes32 s
)
public
pure
returns (bool)
{
require(v >= 27 && v <= 30, "HEX: v invalid");
/*
ecrecover() returns an Eth address rather than a public key, so
we must do the same to compare.
*/
address pubKeyEthAddr ; //inject UNINIT LOCAL/STATE VAR
/* Create and hash the claim message text */
bytes32 messageHash ; //inject UNINIT LOCAL/STATE VAR
/* Verify the public key */
return ecrecover(messageHash, v, r, s) == pubKeyEthAddr;
}
/**
* @dev PUBLIC FACING: Derive an Ethereum address from an ECDSA public key
* @param pubKeyX First half of uncompressed ECDSA public key
* @param pubKeyY Second half of uncompressed ECDSA public key
* @return Derived Eth address
*/
function pubKeyToEthAddress(bytes32 pubKeyX, bytes32 pubKeyY)
public
pure
returns (address)
{
return address(uint160(uint256(keccak256(abi.encodePacked(pubKeyX, pubKeyY)))));
}
/**
* @dev PUBLIC FACING: Derive a Bitcoin address from an ECDSA public key
* @param pubKeyX First half of uncompressed ECDSA public key
* @param pubKeyY Second half of uncompressed ECDSA public key
* @param claimFlags Claim flags specifying address and message formats
* @return Derived Bitcoin address (binary; no base58-check encoding)
*/
function pubKeyToBtcAddress(bytes32 pubKeyX, bytes32 pubKeyY, uint8 claimFlags)
public
pure
returns (bytes20)
{
/*
Helpful references:
- https://en.bitcoin.it/wiki/Technical_background_of_version_1_Bitcoin_addresses
- https://github.com/cryptocoinjs/ecurve/blob/master/lib/point.js
*/
uint8 startingByte;
bytes memory pubKey;
bool compressed ; //inject UNINIT LOCAL/STATE VAR
bool nested ; //inject UNINIT LOCAL/STATE VAR
bool bech32 ; //inject UNINIT LOCAL/STATE VAR
if (compressed) {
/* Compressed public key format */
require(!(nested && bech32), "HEX: claimFlags invalid");
startingByte = (pubKeyY[31] & 0x01) == 0 ? 0x02 : 0x03;
pubKey = abi.encodePacked(startingByte, pubKeyX);
} else {
/* Uncompressed public key format */
require(!nested && !bech32, "HEX: claimFlags invalid");
startingByte = 0x04;
pubKey = abi.encodePacked(startingByte, pubKeyX, pubKeyY);
}
bytes20 pubKeyHash ; //inject UNINIT LOCAL/STATE VAR
if (nested) {
return _hash160(abi.encodePacked(hex"0014", pubKeyHash));
}
return pubKeyHash;
}
/**
* @dev Verify a BTC address and balance are part of the Merkle tree
* @param btcAddr Bitcoin address (binary; no base58-check encoding)
* @param rawSatoshis Raw BTC address balance in Satoshis
* @param proof Merkle tree proof
* @return True if valid
*/
function _btcAddressIsValid(bytes20 btcAddr, uint256 rawSatoshis, bytes32[] memory proof)
internal
pure
returns (bool)
{
/*
Ensure the proof does not attempt to treat a Merkle leaf as if it were an
internal Merkle tree node. A leaf will always have the zero-fill. An
internal node will never have the zero-fill, as guaranteed by HEX's Merkle
tree construction.
The first element, proof[0], will always be a leaf because it is the pair
of the leaf being validated. The rest of the elements, proof[1..length-1],
must be internal nodes.
The number of leaves (CLAIMABLE_BTC_ADDR_COUNT) is even, as guaranteed by
HEX's Merkle tree construction, which eliminates the only edge-case where
this validation would not apply.
*/
require((uint256(proof[0]) & MERKLE_LEAF_FILL_MASK) == 0, "HEX: proof invalid");
for (uint256 i ; i < proof.length; i++) { //inject UNINIT LOCAL/STATE VAR
require((uint256(proof[i]) & MERKLE_LEAF_FILL_MASK) != 0, "HEX: proof invalid");
}
/*
Calculate the 32 byte Merkle leaf associated with this BTC address and balance
160 bits: BTC address
52 bits: Zero-fill
45 bits: Satoshis (limited by MAX_BTC_ADDR_BALANCE_SATOSHIS)
*/
bytes32 merkleLeaf ; //inject UNINIT LOCAL/STATE VAR
/* Verify the Merkle tree proof */
return _merkleProofIsValid(merkleLeaf, proof);
}
/**
* @dev Verify a Merkle proof using the UTXO Merkle tree
* @param merkleLeaf Leaf asserted to be present in the Merkle tree
* @param proof Generated Merkle tree proof
* @return True if valid
*/
function _merkleProofIsValid(bytes32 merkleLeaf, bytes32[] memory proof)
private
pure
returns (bool)
{
return MerkleProof.verify(proof, MERKLE_TREE_ROOT, merkleLeaf);
}
function _claimMessageCreate(address claimToAddr, bytes32 claimParamHash, uint8 claimFlags)
private
pure
returns (bytes memory)
{
bytes memory prefixStr = (claimFlags & CLAIM_FLAG_MSG_PREFIX_OLD) != 0
? OLD_CLAIM_PREFIX_STR
: STD_CLAIM_PREFIX_STR;
bool includeAddrChecksum ; //inject UNINIT LOCAL/STATE VAR
bytes memory addrStr = _addressStringCreate(claimToAddr, includeAddrChecksum);
if (claimParamHash == 0) {
return abi.encodePacked(
BITCOIN_SIG_PREFIX_LEN,
BITCOIN_SIG_PREFIX_STR,
uint8(prefixStr.length) + ETH_ADDRESS_HEX_LEN,
prefixStr,
addrStr
);
}
bytes memory claimParamHashStr = new bytes(CLAIM_PARAM_HASH_HEX_LEN);
_hexStringFromData(claimParamHashStr, claimParamHash, CLAIM_PARAM_HASH_BYTE_LEN);
return abi.encodePacked(
BITCOIN_SIG_PREFIX_LEN,
BITCOIN_SIG_PREFIX_STR,
uint8(prefixStr.length) + ETH_ADDRESS_HEX_LEN + 1 + CLAIM_PARAM_HASH_HEX_LEN,
prefixStr,
addrStr,
"_",
claimParamHashStr
);
}
function _addressStringCreate(address addr, bool includeAddrChecksum)
private
pure
returns (bytes memory addrStr)
{
addrStr = new bytes(ETH_ADDRESS_HEX_LEN);
_hexStringFromData(addrStr, bytes32(bytes20(addr)), ETH_ADDRESS_BYTE_LEN);
if (includeAddrChecksum) {
bytes32 addrStrHash ; //inject UNINIT LOCAL/STATE VAR
uint256 offset ; //inject UNINIT LOCAL/STATE VAR
for (uint256 i ; i < ETH_ADDRESS_BYTE_LEN; i++) { //inject UNINIT LOCAL/STATE VAR
uint8 b ; //inject UNINIT LOCAL/STATE VAR
_addressStringChecksumChar(addrStr, offset++, b >> 4);
_addressStringChecksumChar(addrStr, offset++, b & 0x0f);
}
}
return addrStr;
}
function _addressStringChecksumChar(bytes memory addrStr, uint256 offset, uint8 hashNybble)
private
pure
{
bytes1 ch ; //inject UNINIT LOCAL/STATE VAR
if (ch >= "a" && hashNybble >= 8) {
addrStr[offset] = ch ^ 0x20;
}
}
function _hexStringFromData(bytes memory hexStr, bytes32 data, uint256 dataLen)
private
pure
{
uint256 offset ; //inject UNINIT LOCAL/STATE VAR
for (uint256 i ; i < dataLen; i++) { //inject UNINIT LOCAL/STATE VAR
uint8 b ; //inject UNINIT LOCAL/STATE VAR
hexStr[offset++] = HEX_DIGITS[b >> 4];
hexStr[offset++] = HEX_DIGITS[b & 0x0f];
}
}
/**
* @dev sha256(sha256(data))
* @param data Data to be hashed
* @return 32-byte hash
*/
function _hash256(bytes memory data)
private
pure
returns (bytes32)
{
return sha256(abi.encodePacked(sha256(data)));
}
/**
* @dev ripemd160(sha256(data))
* @param data Data to be hashed
* @return 20-byte hash
*/
function _hash160(bytes memory data)
private
pure
returns (bytes20)
{
return ripemd160(abi.encodePacked(sha256(data)));
}
}
contract UTXORedeemableToken is UTXOClaimValidation {
/**
* @dev PUBLIC FACING: Claim a BTC address and its Satoshi balance in Hearts
* crediting the appropriate amount to a specified Eth address. Bitcoin ECDSA
* signature must be from that BTC address and must match the claim message
* for the Eth address.
* @param rawSatoshis Raw BTC address balance in Satoshis
* @param proof Merkle tree proof
* @param claimToAddr Destination Eth address to credit Hearts to
* @param pubKeyX First half of uncompressed ECDSA public key for the BTC address
* @param pubKeyY Second half of uncompressed ECDSA public key for the BTC address
* @param claimFlags Claim flags specifying address and message formats
* @param v v parameter of ECDSA signature
* @param r r parameter of ECDSA signature
* @param s s parameter of ECDSA signature
* @param autoStakeDays Number of days to auto-stake, subject to minimum auto-stake days
* @param referrerAddr Eth address of referring user (optional; 0x0 for no referrer)
* @return Total number of Hearts credited, if successful
*/
function btcAddressClaim(
uint256 rawSatoshis,
bytes32[] calldata proof,
address claimToAddr,
bytes32 pubKeyX,
bytes32 pubKeyY,
uint8 claimFlags,
uint8 v,
bytes32 r,
bytes32 s,
uint256 autoStakeDays,
address referrerAddr
)
external
returns (uint256)
{
/* Sanity check */
require(rawSatoshis <= MAX_BTC_ADDR_BALANCE_SATOSHIS, "HEX: CHK: rawSatoshis");
/* Enforce the minimum stake time for the auto-stake from this claim */
require(autoStakeDays >= MIN_AUTO_STAKE_DAYS, "HEX: autoStakeDays lower than minimum");
/* Ensure signature matches the claim message containing the Eth address and claimParamHash */
{
bytes32 claimParamHash ; //inject UNINIT LOCAL/STATE VAR
if (claimToAddr != msg.sender) {
/* Claimer did not send this, so claim params must be signed */
claimParamHash = keccak256(
abi.encodePacked(MERKLE_TREE_ROOT, autoStakeDays, referrerAddr)
);
}
require(
claimMessageMatchesSignature(
claimToAddr,
claimParamHash,
pubKeyX,
pubKeyY,
claimFlags,
v,
r,
s
),
"HEX: Signature mismatch"
);
}
/* Derive BTC address from public key */
bytes20 btcAddr ; //inject UNINIT LOCAL/STATE VAR
/* Ensure BTC address has not yet been claimed */
require(!btcAddressClaims[btcAddr], "HEX: BTC address balance already claimed");
/* Ensure BTC address is part of the Merkle tree */
require(
_btcAddressIsValid(btcAddr, rawSatoshis, proof),
"HEX: BTC address or balance unknown"
);
/* Mark BTC address as claimed */
btcAddressClaims[btcAddr] = true;
return _satoshisClaimSync(
rawSatoshis,
claimToAddr,
btcAddr,
claimFlags,
autoStakeDays,
referrerAddr
);
}
function _satoshisClaimSync(
uint256 rawSatoshis,
address claimToAddr,
bytes20 btcAddr,
uint8 claimFlags,
uint256 autoStakeDays,
address referrerAddr
)
private
returns (uint256 totalClaimedHearts)
{
GlobalsCache memory g;
GlobalsCache memory gSnapshot;
_globalsLoad(g, gSnapshot);
totalClaimedHearts = _satoshisClaim(
g,
rawSatoshis,
claimToAddr,
btcAddr,
claimFlags,
autoStakeDays,
referrerAddr
);
_globalsSync(g, gSnapshot);
return totalClaimedHearts;
}
/**
* @dev Credit an Eth address with the Hearts value of a raw Satoshis balance
* @param g Cache of stored globals
* @param rawSatoshis Raw BTC address balance in Satoshis
* @param claimToAddr Destination Eth address for the claimed Hearts to be sent
* @param btcAddr Bitcoin address (binary; no base58-check encoding)
* @param autoStakeDays Number of days to auto-stake, subject to minimum auto-stake days
* @param referrerAddr Eth address of referring user (optional; 0x0 for no referrer)
* @return Total number of Hearts credited, if successful
*/
function _satoshisClaim(
GlobalsCache memory g,
uint256 rawSatoshis,
address claimToAddr,
bytes20 btcAddr,
uint8 claimFlags,
uint256 autoStakeDays,
address referrerAddr
)
private
returns (uint256 totalClaimedHearts)
{
/* Allowed only during the claim phase */
require(g._currentDay >= CLAIM_PHASE_START_DAY, "HEX: Claim phase has not yet started");
require(g._currentDay < CLAIM_PHASE_END_DAY, "HEX: Claim phase has ended");
/* Check if log data needs to be updated */
_dailyDataUpdateAuto(g);
/* Sanity check */
require(
g._claimedBtcAddrCount < CLAIMABLE_BTC_ADDR_COUNT,
"HEX: CHK: _claimedBtcAddrCount"
);
(uint256 adjSatoshis, uint256 claimedHearts, uint256 claimBonusHearts) = _calcClaimValues(
g,
rawSatoshis
);
/* Increment claim count to track viral rewards */
g._claimedBtcAddrCount++;
totalClaimedHearts = _remitBonuses(
claimToAddr,
btcAddr,
claimFlags,
rawSatoshis,
adjSatoshis,
claimedHearts,
claimBonusHearts,
referrerAddr
);
/* Auto-stake a percentage of the successful claim */
uint256 autoStakeHearts ; //inject UNINIT LOCAL/STATE VAR
_stakeStart(g, autoStakeHearts, autoStakeDays, true);
/* Mint remaining claimed Hearts to claim address */
_mint(claimToAddr, totalClaimedHearts - autoStakeHearts);
return totalClaimedHearts;
}
function _remitBonuses(
address claimToAddr,
bytes20 btcAddr,
uint8 claimFlags,
uint256 rawSatoshis,
uint256 adjSatoshis,
uint256 claimedHearts,
uint256 claimBonusHearts,
address referrerAddr
)
private
returns (uint256 totalClaimedHearts)
{
totalClaimedHearts = claimedHearts + claimBonusHearts;
uint256 originBonusHearts ; //inject UNINIT LOCAL/STATE VAR
if (referrerAddr == address(0)) {
/* No referrer */
_emitClaim(
claimToAddr,
btcAddr,
claimFlags,
rawSatoshis,
adjSatoshis,
totalClaimedHearts,
referrerAddr
);
} else {
/* Referral bonus of 10% of total claimed Hearts to claimer */
uint256 referralBonusHearts ; //inject UNINIT LOCAL/STATE VAR
totalClaimedHearts += referralBonusHearts;
/* Then a cumulative referrer bonus of 20% to referrer */
uint256 referrerBonusHearts ; //inject UNINIT LOCAL/STATE VAR
originBonusHearts += referralBonusHearts + referrerBonusHearts;
if (referrerAddr == claimToAddr) {
/* Self-referred */
totalClaimedHearts += referrerBonusHearts;
_emitClaim(
claimToAddr,
btcAddr,
claimFlags,
rawSatoshis,
adjSatoshis,
totalClaimedHearts,
referrerAddr
);
} else {
/* Referred by different address */
_emitClaim(
claimToAddr,
btcAddr,
claimFlags,
rawSatoshis,
adjSatoshis,
totalClaimedHearts,
referrerAddr
);
_mint(referrerAddr, referrerBonusHearts);
}
}
_mint(ORIGIN_ADDR, originBonusHearts);
return totalClaimedHearts;
}
function _emitClaim(
address claimToAddr,
bytes20 btcAddr,
uint8 claimFlags,
uint256 rawSatoshis,
uint256 adjSatoshis,
uint256 claimedHearts,
address referrerAddr
)
private
{
emit Claim( // (auto-generated event)
uint256(uint40(block.timestamp))
| (uint256(uint56(rawSatoshis)) << 40)
| (uint256(uint56(adjSatoshis)) << 96)
| (uint256(claimFlags) << 152)
| (uint256(uint72(claimedHearts)) << 160),
uint256(uint160(msg.sender)),
btcAddr,
claimToAddr,
referrerAddr
);
if (claimToAddr == msg.sender) {
return;
}
emit ClaimAssist( // (auto-generated event)
uint256(uint40(block.timestamp))
| (uint256(uint160(btcAddr)) << 40)
| (uint256(uint56(rawSatoshis)) << 200),
uint256(uint56(adjSatoshis))
| (uint256(uint160(claimToAddr)) << 56)
| (uint256(claimFlags) << 216),
uint256(uint72(claimedHearts))
| (uint256(uint160(referrerAddr)) << 72),
msg.sender
);
}
function _calcClaimValues(GlobalsCache memory g, uint256 rawSatoshis)
private
pure
returns (uint256 adjSatoshis, uint256 claimedHearts, uint256 claimBonusHearts)
{
/* Apply Silly Whale reduction */
adjSatoshis = _adjustSillyWhale(rawSatoshis);
require(
g._claimedSatoshisTotal + adjSatoshis <= CLAIMABLE_SATOSHIS_TOTAL,
"HEX: CHK: _claimedSatoshisTotal"
);
g._claimedSatoshisTotal += adjSatoshis;
uint256 daysRemaining ; //inject UNINIT LOCAL/STATE VAR
/* Apply late-claim reduction */
adjSatoshis = _adjustLateClaim(adjSatoshis, daysRemaining);
g._unclaimedSatoshisTotal -= adjSatoshis;
/* Convert to Hearts and calculate speed bonus */
claimedHearts = adjSatoshis * HEARTS_PER_SATOSHI;
claimBonusHearts = _calcSpeedBonus(claimedHearts, daysRemaining);
return (adjSatoshis, claimedHearts, claimBonusHearts);
}
/**
* @dev Apply Silly Whale adjustment
* @param rawSatoshis Raw BTC address balance in Satoshis
* @return Adjusted BTC address balance in Satoshis
*/
function _adjustSillyWhale(uint256 rawSatoshis)
private
pure
returns (uint256)
{
if (rawSatoshis < 1000e8) {
/* For < 1,000 BTC: no penalty */
return rawSatoshis;
}
if (rawSatoshis >= 10000e8) {
/* For >= 10,000 BTC: penalty is 75%, leaving 25% */
return rawSatoshis / 4;
}
/*
For 1,000 <= BTC < 10,000: penalty scales linearly from 50% to 75%
penaltyPercent = (btc - 1000) / (10000 - 1000) * (75 - 50) + 50
= (btc - 1000) / 9000 * 25 + 50
= (btc - 1000) / 360 + 50
appliedPercent = 100 - penaltyPercent
= 100 - ((btc - 1000) / 360 + 50)
= 100 - (btc - 1000) / 360 - 50
= 50 - (btc - 1000) / 360
= (18000 - (btc - 1000)) / 360
= (18000 - btc + 1000) / 360
= (19000 - btc) / 360
adjustedBtc = btc * appliedPercent / 100
= btc * ((19000 - btc) / 360) / 100
= btc * (19000 - btc) / 36000
adjustedSat = 1e8 * adjustedBtc
= 1e8 * (btc * (19000 - btc) / 36000)
= 1e8 * ((sat / 1e8) * (19000 - (sat / 1e8)) / 36000)
= 1e8 * (sat / 1e8) * (19000 - (sat / 1e8)) / 36000
= (sat / 1e8) * 1e8 * (19000 - (sat / 1e8)) / 36000
= (sat / 1e8) * (19000e8 - sat) / 36000
= sat * (19000e8 - sat) / 36000e8
*/
return rawSatoshis * (19000e8 - rawSatoshis) / 36000e8;
}
/**
* @dev Apply late-claim adjustment to scale claim to zero by end of claim phase
* @param adjSatoshis Adjusted BTC address balance in Satoshis (after Silly Whale)
* @param daysRemaining Number of reward days remaining in claim phase
* @return Adjusted BTC address balance in Satoshis (after Silly Whale and Late-Claim)
*/
function _adjustLateClaim(uint256 adjSatoshis, uint256 daysRemaining)
private
pure
returns (uint256)
{
/*
Only valid from CLAIM_PHASE_DAYS to 1, and only used during that time.
adjustedSat = sat * (daysRemaining / CLAIM_PHASE_DAYS) * 100%
= sat * daysRemaining / CLAIM_PHASE_DAYS
*/
return adjSatoshis * daysRemaining / CLAIM_PHASE_DAYS;
}
/**
* @dev Calculates speed bonus for claiming earlier in the claim phase
* @param claimedHearts Hearts claimed from adjusted BTC address balance Satoshis
* @param daysRemaining Number of claim days remaining in claim phase
* @return Speed bonus in Hearts
*/
function _calcSpeedBonus(uint256 claimedHearts, uint256 daysRemaining)
private
pure
returns (uint256)
{
/*
Only valid from CLAIM_PHASE_DAYS to 1, and only used during that time.
Speed bonus is 20% ... 0% inclusive.
bonusHearts = claimedHearts * ((daysRemaining - 1) / (CLAIM_PHASE_DAYS - 1)) * 20%
= claimedHearts * ((daysRemaining - 1) / (CLAIM_PHASE_DAYS - 1)) * 20/100
= claimedHearts * ((daysRemaining - 1) / (CLAIM_PHASE_DAYS - 1)) / 5
= claimedHearts * (daysRemaining - 1) / ((CLAIM_PHASE_DAYS - 1) * 5)
*/
return claimedHearts * (daysRemaining - 1) / ((CLAIM_PHASE_DAYS - 1) * 5);
}
}
contract TransformableToken is UTXORedeemableToken {
/**
* @dev PUBLIC FACING: Enter the tranform lobby for the current round
* @param referrerAddr Eth address of referring user (optional; 0x0 for no referrer)
*/
function xfLobbyEnter(address referrerAddr)
external
payable
{
uint256 enterDay ; //inject UNINIT LOCAL/STATE VAR
require(enterDay < CLAIM_PHASE_END_DAY, "HEX: Lobbies have ended");
uint256 rawAmount ; //inject UNINIT LOCAL/STATE VAR
require(rawAmount != 0, "HEX: Amount required");
XfLobbyQueueStore storage qRef = xfLobbyMembers[enterDay][msg.sender];
uint256 entryIndex ; //inject UNINIT LOCAL/STATE VAR
qRef.entries[entryIndex] = XfLobbyEntryStore(uint96(rawAmount), referrerAddr);
xfLobby[enterDay] += rawAmount;
_emitXfLobbyEnter(enterDay, entryIndex, rawAmount, referrerAddr);
}
/**
* @dev PUBLIC FACING: Leave the transform lobby after the round is complete
* @param enterDay Day number when the member entered
* @param count Number of queued-enters to exit (optional; 0 for all)
*/
function xfLobbyExit(uint256 enterDay, uint256 count)
external
{
require(enterDay < _currentDay(), "HEX: Round is not complete");
XfLobbyQueueStore storage qRef = xfLobbyMembers[enterDay][msg.sender];
uint256 headIndex ; //inject UNINIT LOCAL/STATE VAR
uint256 endIndex;
if (count != 0) {
require(count <= qRef.tailIndex - headIndex, "HEX: count invalid");
endIndex = headIndex + count;
} else {
endIndex = qRef.tailIndex;
require(headIndex < endIndex, "HEX: count invalid");
}
uint256 waasLobby ; //inject UNINIT LOCAL/STATE VAR
uint256 _xfLobby ; //inject UNINIT LOCAL/STATE VAR
uint256 totalXfAmount ; //inject UNINIT LOCAL/STATE VAR
uint256 originBonusHearts ; //inject UNINIT LOCAL/STATE VAR
do {
uint256 rawAmount ; //inject UNINIT LOCAL/STATE VAR
address referrerAddr ; //inject UNINIT LOCAL/STATE VAR
delete qRef.entries[headIndex];
uint256 xfAmount ; //inject UNINIT LOCAL/STATE VAR
if (referrerAddr == address(0)) {
/* No referrer */
_emitXfLobbyExit(enterDay, headIndex, xfAmount, referrerAddr);
} else {
/* Referral bonus of 10% of xfAmount to member */
uint256 referralBonusHearts ; //inject UNINIT LOCAL/STATE VAR
xfAmount += referralBonusHearts;
/* Then a cumulative referrer bonus of 20% to referrer */
uint256 referrerBonusHearts ; //inject UNINIT LOCAL/STATE VAR
if (referrerAddr == msg.sender) {
/* Self-referred */
xfAmount += referrerBonusHearts;
_emitXfLobbyExit(enterDay, headIndex, xfAmount, referrerAddr);
} else {
/* Referred by different address */
_emitXfLobbyExit(enterDay, headIndex, xfAmount, referrerAddr);
_mint(referrerAddr, referrerBonusHearts);
}
originBonusHearts += referralBonusHearts + referrerBonusHearts;
}
totalXfAmount += xfAmount;
} while (++headIndex < endIndex);
qRef.headIndex = uint40(headIndex);
if (originBonusHearts != 0) {
_mint(ORIGIN_ADDR, originBonusHearts);
}
if (totalXfAmount != 0) {
_mint(msg.sender, totalXfAmount);
}
}
/**
* @dev PUBLIC FACING: Release any value that has been sent to the contract
*/
function xfLobbyFlush()
external
{
require(address(this).balance != 0, "HEX: No value");
FLUSH_ADDR.transfer(address(this).balance);
}
/**
* @dev PUBLIC FACING: External helper to return multiple values of xfLobby[] with
* a single call
* @param beginDay First day of data range
* @param endDay Last day (non-inclusive) of data range
* @return Fixed array of values
*/
function xfLobbyRange(uint256 beginDay, uint256 endDay)
external
view
returns (uint256[] memory list)
{
require(
beginDay < endDay && endDay <= CLAIM_PHASE_END_DAY && endDay <= _currentDay(),
"HEX: invalid range"
);
list = new uint256[](endDay - beginDay);
uint256 src ; //inject UNINIT LOCAL/STATE VAR
uint256 dst ; //inject UNINIT LOCAL/STATE VAR
do {
list[dst++] = uint256(xfLobby[src++]);
} while (src < endDay);
return list;
}
/**
* @dev PUBLIC FACING: Return a current lobby member queue entry.
* Only needed due to limitations of the standard ABI encoder.
* @param memberAddr Eth address of the lobby member
* @param entryId 49 bit compound value. Top 9 bits: enterDay, Bottom 40 bits: entryIndex
* @return 1: Raw amount that was entered with; 2: Referring Eth addr (optional; 0x0 for no referrer)
*/
function xfLobbyEntry(address memberAddr, uint256 entryId)
external
view
returns (uint256 rawAmount, address referrerAddr)
{
uint256 enterDay ; //inject UNINIT LOCAL/STATE VAR
uint256 entryIndex ; //inject UNINIT LOCAL/STATE VAR
XfLobbyEntryStore storage entry = xfLobbyMembers[enterDay][memberAddr].entries[entryIndex];
require(entry.rawAmount != 0, "HEX: Param invalid");
return (entry.rawAmount, entry.referrerAddr);
}
/**
* @dev PUBLIC FACING: Return the lobby days that a user is in with a single call
* @param memberAddr Eth address of the user
* @return Bit vector of lobby day numbers
*/
function xfLobbyPendingDays(address memberAddr)
external
view
returns (uint256[XF_LOBBY_DAY_WORDS] memory words)
{
uint256 day ; //inject UNINIT LOCAL/STATE VAR
if (day > CLAIM_PHASE_END_DAY) {
day = CLAIM_PHASE_END_DAY;
}
while (day-- != 0) {
if (xfLobbyMembers[day][memberAddr].tailIndex > xfLobbyMembers[day][memberAddr].headIndex) {
words[day >> 8] |= 1 << (day & 255);
}
}
return words;
}
function _waasLobby(uint256 enterDay)
private
returns (uint256 waasLobby)
{
if (enterDay >= CLAIM_PHASE_START_DAY) {
GlobalsCache memory g;
GlobalsCache memory gSnapshot;
_globalsLoad(g, gSnapshot);
_dailyDataUpdateAuto(g);
uint256 unclaimed ; //inject UNINIT LOCAL/STATE VAR
waasLobby = unclaimed * HEARTS_PER_SATOSHI / CLAIM_PHASE_DAYS;
_globalsSync(g, gSnapshot);
} else {
waasLobby = WAAS_LOBBY_SEED_HEARTS;
}
return waasLobby;
}
function _emitXfLobbyEnter(
uint256 enterDay,
uint256 entryIndex,
uint256 rawAmount,
address referrerAddr
)
private
{
emit XfLobbyEnter( // (auto-generated event)
uint256(uint40(block.timestamp))
| (uint256(uint96(rawAmount)) << 40),
msg.sender,
(enterDay << XF_LOBBY_ENTRY_INDEX_SIZE) | entryIndex,
referrerAddr
);
}
function _emitXfLobbyExit(
uint256 enterDay,
uint256 entryIndex,
uint256 xfAmount,
address referrerAddr
)
private
{
emit XfLobbyExit( // (auto-generated event)
uint256(uint40(block.timestamp))
| (uint256(uint72(xfAmount)) << 40),
msg.sender,
(enterDay << XF_LOBBY_ENTRY_INDEX_SIZE) | entryIndex,
referrerAddr
);
}
}
contract HEX_TOKEN is TransformableToken {
constructor()
public
{
/* Initialize global shareRate to 1 */
globals.shareRate = uint40(1 * SHARE_RATE_SCALE);
/* Initialize dailyDataCount to skip pre-claim period */
globals.dailyDataCount = uint16(PRE_CLAIM_DAYS);
/* Add all Satoshis from UTXO snapshot to contract */
globals.claimStats = _claimStatsEncode(
0, // _claimedBtcAddrCount
0, // _claimedSatoshisTotal
FULL_SATOSHIS_TOTAL // _unclaimedSatoshisTotal
);
}
function() external payable {}
} | inject UNINIT LOCAL/STATE VAR
| address referrerAddr ; | 1,819,175 | [
1,
22170,
5019,
12919,
15234,
19,
7998,
8350,
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,
5411,
1758,
14502,
3178,
274,
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
] |
// SPDX-License-Identifier: MIT
pragma solidity 0.8.3;
import "./utils/Ownable.sol";
/**
* @notice Allows each token to be associated with a creator.
*/
contract Participants is Ownable {
mapping(address => uint256) public seed;
mapping(address => uint256) public private1;
mapping(address => uint256) public private2;
constructor() {
// ****** For tests only - Should be comment in deploy ******
// seed[
// 0x70997970C51812dc3A010C7d01b50e0d17dc79C8
// ] = 625000000000000000000000; // 625000 DDAO | $ 100000
// private1[
// 0x3C44CdDdB6a900fa2b585dd299e03d12FA4293BC
// ] = 31250000000000000000000; // 31250 DDAO | $ 10000
// private2[
// 0x90F79bf6EB2c4f870365E785982E1f101E93b906
// ] = 2170212765957400000000; // 2170.2127659574 DDAO | $ 1020
// ****** For tests only ^^^ ******
seed[
0xECCFbC5B04Da35D611EF8b51099fA5Bc6639d73b
] = 625000000000000000000000; // 625000 DDAO | $ 100000
seed[
0x7777420DD0E5f0E13D51C831f77495a057aaBBBB
] = 332500000000000000000000; // 332500 DDAO | $ 53200
seed[
0xEB2d2F1b8c558a40207669291Fda468E50c8A0bB
] = 312500000000000000000000; // 312500 DDAO | $ 50000
seed[
0x8595f8141E90fcf6Ee17C85142Fd03d3138A6198
] = 312500000000000000000000; // 312500 DDAO | $ 50000
seed[
0xCf57A3b1C076838116731FDe404492D9d168747A
] = 312500000000000000000000; // 312500 DDAO | $ 50000
seed[
0x07587c046d4d4BD97C2d64EDBfAB1c1fE28A10E5
] = 312500000000000000000000; // 312500 DDAO | $ 50000
seed[
0x5555DADcb41fB48934b02A0DBF793b97541F7777
] = 312500000000000000000000; // 312500 DDAO | $ 50000
private1[
0x0026Ec57900Be57503Efda250328507156dAC982
] = 93750000000000000000000; // 93750 DDAO | $ 30000
private1[
0xd53b873683Df491553eea6a069770144Ad30F3A9
] = 93750000000000000000000; // 93750 DDAO | $ 30000
private1[
0x7701E5Bf2D8aE221f23F460FE73420eeE86d2872
] = 78125000000000000000000; // 78125 DDAO | $ 25000
private1[
0x1A72CCE42499361FFF103855F845B8cFc1c25b67
] = 62500000000000000000000; // 62500 DDAO | $ 20000
private1[
0x1b9E791f3259dcEF7D1e366b33F644841c2461a5
] = 62500000000000000000000; // 62500 DDAO | $ 20000
private1[
0x4E560A3ecfe9E5386E727c76f6e2690aE7a1Bc82
] = 58437500000000000000000; // 58437.5 DDAO | $ 18700
private1[
0xCeeA2d354c6357ed7e10e629bd2734119A5B3c21
] = 48351171684062000000000; // 48351.171684063 DDAO | $ 15472.3749389
private1[
0x98BCE99aa50CB33eca0dDcb2a04404B80dEd3F3E
] = 46875000000000000000000; // 46875 DDAO | $ 15000
private1[
0xeE74a1e81B6C55e3D02D05D7CaE9FD6BCee0E651
] = 39062500000000000000000; // 39062.5 DDAO | $ 12500
private1[
0x9f8eF2849133286860A8216cA11359381706Fa4a
] = 37500000000000000000000; // 37500 DDAO | $ 12000
private1[
0x8D88F01D183DDfD30782E565fdBcD85c14413cAF
] = 34375000000000000000000; // 34375 DDAO | $ 11000
private1[
0xB862D5e30DE97368801bDC24A53aD90F56a9C068
] = 33021339193750000000000; // 33021.33919375 DDAO | $ 10566.828542
private1[
0x4F9ef189F387e0a91d46812cFB2ecE0d558a471C
] = 31562500000000000000000; // 31562.5 DDAO | $ 10100
private1[
0x79e5c907b9d4Af5840C687e6975a1C530895454a
] = 31318750000000000000000; // 31318.75 DDAO | $ 10022
private1[
0xFB81414570E338E28C98417c38A3A5c9C6503516
] = 31253125000000000000000; // 31253.125 DDAO | $ 10001
private1[
0x35e55F287EFA64dAb88A289a32F9e5942Ab28b18
] = 31250000000000000000000; // 31250 DDAO | $ 10000
private1[
0xda7B5C50874a82C0262b4eA6e6001E2b002829E9
] = 31250000000000000000000; // 31250 DDAO | $ 10000
private1[
0x7Ed273A361D6bb16833f0E563C313e205738112f
] = 31250000000000000000000; // 31250 DDAO | $ 10000
private1[
0x3cB704A5FB4428796b728DF7e4CbC67BCA1497Ae
] = 31250000000000000000000; // 31250 DDAO | $ 10000
private1[
0xEc8c50223E785C3Ff21fd9F9ABafAcfB1e2215FC
] = 31250000000000000000000; // 31250 DDAO | $ 10000
private1[
0x871cAEF9d39e05f76A3F6A3Bb7690168f0188925
] = 31250000000000000000000; // 31250 DDAO | $ 10000
private1[
0xbE20DFb456b7E81f691A8445d073e56602E3cefa
] = 31250000000000000000000; // 31250 DDAO | $ 10000
private1[
0x710A169B822Bf51b8F8E6538c63deD200932BB29
] = 31250000000000000000000; // 31250 DDAO | $ 10000
private1[
0x6Fa98A4254c7E9Ec681cCeb3Cb8D64a70Dbea256
] = 31250000000000000000000; // 31250 DDAO | $ 10000
private1[
0x524b7c9B4cA33ba72445DFd2d6404C81d8D1F2E3
] = 31250000000000000000000; // 31250 DDAO | $ 10000
private1[
0x92fc7C69AD976e188b004Cd60Cbd0C8448c770bA
] = 31250000000000000000000; // 31250 DDAO | $ 10000
private1[
0x32f8E5d3F4039d1DF89B6A1e544288289A500Fd1
] = 31250000000000000000000; // 31250 DDAO | $ 10000
private1[
0x256b09f7Ae7d5fec8C8ac77184CA09F867BbBf4c
] = 31250000000000000000000; // 31250 DDAO | $ 10000
private1[
0xC9D15F4E6f1b37CbF0E8068Ff84B5282edEF9707
] = 31250000000000000000000; // 31250 DDAO | $ 10000
private1[
0x8ad686fB89b2944B083C900ec5dDCd2bB02af1D0
] = 31250000000000000000000; // 31250 DDAO | $ 10000
private1[
0xe1C69F432f2Ba9eEb33ab4bDd23BD417cb89886a
] = 31250000000000000000000; // 31250 DDAO | $ 10000
private1[
0x355e03d40211cc6b6D18ce52278e91566fF29839
] = 31250000000000000000000; // 31250 DDAO | $ 10000
private2[
0x4F80d10339CdA1EDc936e15E7066C1DBbd8Eb01F
] = 15782000000000000000000; // 15782 DDAO | $ 7417.54
private2[
0x4959769500C751f32FEa39012b5244C722c643Dd
] = 10667532039798000000000; // 10667.532039798 DDAO | $ 5013.7400587051
private2[
0x89BFc312583bE9a9E518928F24eBdc03270C7375
] = 10648936170213000000000; // 10648.936170213 DDAO | $ 5005
private2[
0x4d35B59A3C1F59D5fF94dD7B2b3A1198378c4678
] = 10639598053191000000000; // 10639.598053191 DDAO | $ 5000.611085
private2[
0xa73eAf66656270Cc2b27304a170a3ACbd666B54B
] = 10638297872340000000000; // 10638.29787234 DDAO | $ 5000
private2[
0xb647f84d4DC1C9bD9Bf42BfFe0FEA69C9F2bb843
] = 10638297872340000000000; // 10638.29787234 DDAO | $ 5000
private2[
0x33Ad49856da25b8E2E2D762c411AEda0D1727918
] = 10638297872340000000000; // 10638.29787234 DDAO | $ 5000
private2[
0x420ACe7D85821A887891A43CC8a2aFE0D84433a9
] = 10638297872340000000000; // 10638.29787234 DDAO | $ 5000
private2[
0x3A484fc4E7873Bd79D0B9B05ED6067A549eC9f49
] = 10638297872340000000000; // 10638.29787234 DDAO | $ 5000
private2[
0x7AE29F334D7cb67b58df5aE2A19F360F1Fd3bE75
] = 10638297872340000000000; // 10638.29787234 DDAO | $ 5000
private2[
0xd09153823Cf2f29ed6B7E959739bca97C1D273B8
] = 10638297872340000000000; // 10638.29787234 DDAO | $ 5000
private2[
0xDE92728804683EC03EFAF6C293e428fc72C2ec95
] = 10638297872340000000000; // 10638.29787234 DDAO | $ 5000
private2[
0x3A79caC51e770a84E8Cb5155AAafAA9CaC83F429
] = 10638297872340000000000; // 10638.29787234 DDAO | $ 5000
private2[
0x5A20ab4F35Dba889D1f6244c0D53A153DCd28766
] = 9444461942553200000000; // 9444.4619425532 DDAO | $ 4438.897113
private2[
0x79440849d5BA6Df5fb1F45Ff36BE3979F4271fa4
] = 7518148665957400000000; // 7518.1486659574 DDAO | $ 3533.529873
private2[
0xbD0Ad704f38AfebbCb4BA891389938D4177A8A92
] = 7446808510638300000000; // 7446.8085106383 DDAO | $ 3500
private2[
0x21130c9b9D00BcB6cDAF24d0E85809cf96251F35
] = 6489361702127700000000; // 6489.3617021277 DDAO | $ 3050
private2[
0x42A6396437eBA7bFD6B5195B7134BE64443521ed
] = 6412765957446800000000; // 6412.7659574468 DDAO | $ 3014
private2[
0xC3aB2C2Eb604F159C842D9cAdaBBa2d6254c43d5
] = 6389361702127700000000; // 6389.3617021277 DDAO | $ 3003
private2[
0x5D10100d130467cf8DBE2B904100141F1a63318F
] = 6382978723404300000000; // 6382.9787234043 DDAO | $ 3000
private2[
0x585a003aA0b446C0F9baD7b3b0BAc5A809988588
] = 6382978723404300000000; // 6382.9787234043 DDAO | $ 3000
private2[
0x125EaE40D9898610C926bb5fcEE9529D9ac885aF
] = 6382978723404300000000; // 6382.9787234043 DDAO | $ 3000
private2[
0x24f39151D6d8A9574D1DAC49a44F1263999D0dda
] = 5319148936170200000000; // 5319.1489361702 DDAO | $ 2500
private2[
0xe6BB1bEBF6829ca5240A80F7076E4CFD6Ee540ae
] = 5276595744680900000000; // 5276.5957446809 DDAO | $ 2480
private2[
0xf3143D244F33eb40252464d3b692FA519847B7a9
] = 4851063829787200000000; // 4851.0638297872 DDAO | $ 2280
private2[
0x764108BAcf10e30F6f249d17E7612fB9008923F0
] = 4851063829787200000000; // 4851.0638297872 DDAO | $ 2280
private2[
0xF6d670C5C0B206f44E93dE811054F8C0b6e15905
] = 4289361702127700000000; // 4289.3617021277 DDAO | $ 2016
private2[
0x73073A915f8a582B061091368486fECA640552BA
] = 4274680851063800000000; // 4274.6808510638 DDAO | $ 2009.1
private2[
0xa66a4b8461e4786C265B7AbD1F5dfdb6e487f809
] = 4256595744680900000000; // 4256.5957446809 DDAO | $ 2000.6
private2[
0x07b449319D200b1189406c58967348c5bA0D4083
] = 4256457456721200000000; // 4256.4574567212 DDAO | $ 2000.5350046589
private2[
0x15c5F3a14d4492b1a26f4c6557251a6F247a2Dd5
] = 4255319148936200000000; // 4255.3191489362 DDAO | $ 2000
private2[
0x7eE33a8939C6e08cfE207519e220456CB770b982
] = 4255319148936200000000; // 4255.3191489362 DDAO | $ 2000
private2[
0x2aE024C5EE8dA720b9A51F50D53a291aca37dEb1
] = 4255319148936200000000; // 4255.3191489362 DDAO | $ 2000
private2[
0x0f5A11bEc9B124e73F51186042f4516F924353e0
] = 4255319148936200000000; // 4255.3191489362 DDAO | $ 2000
private2[
0x2230A3fa220B0234E468a52389272d239CEB809d
] = 4255319148936200000000; // 4255.3191489362 DDAO | $ 2000
private2[
0x65028EEE0F81E76A8Ffc39721eD4c18643cB9A4C
] = 4255319148936200000000; // 4255.3191489362 DDAO | $ 2000
private2[
0x931ddC55Ea7074a190ded7429E82dfAdFeDC0269
] = 4255319148936200000000; // 4255.3191489362 DDAO | $ 2000
private2[
0xB6a95916221Abef28339594161cd154Bc650c515
] = 3765957446808500000000; // 3765.9574468085 DDAO | $ 1770
private2[
0x093E088901909dEecC1b4a1479fBcCE1FBEd31E7
] = 3617021276595700000000; // 3617.0212765957 DDAO | $ 1700
private2[
0xb521154e8f8978f64567FE0FA7359Ab47f7363fA
] = 3287234042553200000000; // 3287.2340425532 DDAO | $ 1545
private2[
0x9867EBde73BD54d2D7e55E28057A5Fe3bd2027b6
] = 3272787242553200000000; // 3272.7872425532 DDAO | $ 1538.210004
private2[
0x4D3c3E7F5EBae3aCBac78EfF2457a842Ab86577e
] = 3251063829787200000000; // 3251.0638297872 DDAO | $ 1528
private2[
0x522b76c8f7764009178B3Fd89bBB0134ADEC44a8
] = 3202645110425500000000; // 3202.6451104255 DDAO | $ 1505.2432019
private2[
0x882bBB07991c5c2f65988fd077CdDF405FE5b56f
] = 3192340425531900000000; // 3192.3404255319 DDAO | $ 1500.4
private2[
0x0c2262b636d91Ec5582f4F95b40988a56496B8f1
] = 3191489361702100000000; // 3191.4893617021 DDAO | $ 1500
private2[
0x57dA448673AfB7a06150Ab7a92c7572e7c75D2E5
] = 3191489361702100000000; // 3191.4893617021 DDAO | $ 1500
private2[
0x68cf193fFE134aD92C1DB0267d2062D01FEFDD06
] = 3191489361702100000000; // 3191.4893617021 DDAO | $ 1500
private2[
0x35205135F0883e6a59aF9cb64310c53003433122
] = 3191489361702100000000; // 3191.4893617021 DDAO | $ 1500
private2[
0xA368bae3df1107cF22Daf0a79761EF94656D789A
] = 3159574468085100000000; // 3159.5744680851 DDAO | $ 1485
private2[
0xA31B0BE89D0bcDF35B39682b652bEb8390A8F2Dc
] = 2913791265957400000000; // 2913.7912659574 DDAO | $ 1369.481895
private2[
0x9F74e07D01c8eE7D1b4B0e9739c8c75E8c23Ef4b
] = 2872340425531900000000; // 2872.3404255319 DDAO | $ 1350
private2[
0xA7a9544D86066BF583be602195536918497b1fFf
] = 2765957446808500000000; // 2765.9574468085 DDAO | $ 1300
private2[
0x64F8eF34aC5Dc26410f2A1A0e2b4641189040231
] = 2600000000000000000000; // 2600 DDAO | $ 1222
private2[
0xE088efbff6aA52f679F76F33924C61F2D79FF8E2
] = 2553191489361700000000; // 2553.1914893617 DDAO | $ 1200
private2[
0xD0929C7f44AB8cda86502baaf9961527fC856DDC
] = 2515989780989700000000; // 2515.9897809897 DDAO | $ 1182.5151970652
private2[
0x6592aB22faD2d91c01cCB4429F11022E2595C401
] = 2511826170212800000000; // 2511.8261702128 DDAO | $ 1180.5583
private2[
0x07E8cd40Be6DD430a8B70E990D6aF7Cd2c5fD52c
] = 2476687060085100000000; // 2476.6870600851 DDAO | $ 1164.04291824
private2[
0x875Bf94C16000710f721Cf453B948f23B7394ec2
] = 2345194139228500000000; // 2345.1941392285 DDAO | $ 1102.2412454374
private2[
0x1bdaA24527F033ABBe9Bc51b63C0F2a3e913485b
] = 2340425531914900000000; // 2340.4255319149 DDAO | $ 1100
private2[
0x687922176D1BbcBcdC295E121BcCaA45A1f40fCd
] = 2340425531914900000000; // 2340.4255319149 DDAO | $ 1100
private2[
0x2CE83785eD44961959bf5251e85af897Ba9ddAC7
] = 2319702504255300000000; // 2319.7025042553 DDAO | $ 1090.260177
private2[
0xCDCaDF2195c1376f59808028eA21630B361Ba9b8
] = 2310638297872300000000; // 2310.6382978723 DDAO | $ 1086
private2[
0x7Ff698e124d1D14E6d836aF4dA0Ae448c8FfFa6F
] = 2302934836170200000000; // 2302.9348361702 DDAO | $ 1082.379373
private2[
0x11f53fdAb3054a5cA63778659263aF0838b642b1
] = 2234042553191500000000; // 2234.0425531915 DDAO | $ 1050
private2[
0x9f8eF2849133286860A8216cA11359381706Fa4a
] = 2234042553191500000000; // 2234.0425531915 DDAO | $ 1050
private2[
0x826121D2a47c9D6e71Fd4FED082CECCc8A5381b1
] = 2202127659574500000000; // 2202.1276595745 DDAO | $ 1035
private2[
0x674901AdeB413C126a069402E751ba80F2e2152e
] = 2201778444129100000000; // 2201.7784441291 DDAO | $ 1034.8358687407
private2[
0x228Bb6C83e8d0767eD342dd333DDbD55Ad217a3D
] = 2191489361702100000000; // 2191.4893617021 DDAO | $ 1030
private2[
0xB248B3309e31Ca924449fd2dbe21862E9f1accf5
] = 2172669850608700000000; // 2172.6698506087 DDAO | $ 1021.1548297861
private2[
0xb14ae50038abBd0F5B38b93F4384e4aFE83b9350
] = 2170212765957400000000; // 2170.2127659574 DDAO | $ 1020
private2[
0x795e43E9e2423620dA9107F2a5088e039F9A0112
] = 2167234042553200000000; // 2167.2340425532 DDAO | $ 1018.6
private2[
0x86649d0a9cAf37b51E33b04d89d4BF63dd696fE6
] = 2159574468085100000000; // 2159.5744680851 DDAO | $ 1015
private2[
0x8a382bb6BF2008492268DEdC549B6Cf189a067B5
] = 2143092963829800000000; // 2143.0929638298 DDAO | $ 1007.253693
private2[
0x687cEE1e9B4E2a33A63C5319fe6D5DbBaa8d5E91
] = 2142553191489400000000; // 2142.5531914894 DDAO | $ 1007
private2[
0x390b07DC402DcFD54D5113C8f85d90329A0141ef
] = 2129787234042600000000; // 2129.7872340426 DDAO | $ 1001
private2[
0x0aa05378529F2D1707a0B196B846d7963d677d37
] = 2129787234042600000000; // 2129.7872340426 DDAO | $ 1001
private2[
0x8c1203dfC78068b0Fa5d7a2dD2a2fF9cFA89fFcE
] = 2127659574468100000000; // 2127.6595744681 DDAO | $ 1000
private2[
0xee86f2BAFC7e33EFDD5cf3970e33C361Cb7aDeD9
] = 2127659574468100000000; // 2127.6595744681 DDAO | $ 1000
private2[
0x0be82Fe1422d6D5cA74fd73A37a6C89636235B25
] = 2127659574468100000000; // 2127.6595744681 DDAO | $ 1000
private2[
0xF33782f1384a931A3e66650c3741FCC279a838fC
] = 2127659574468100000000; // 2127.6595744681 DDAO | $ 1000
private2[
0xD878a0a545dCC7751Caf6d796c0267C202A957Db
] = 2127659574468100000000; // 2127.6595744681 DDAO | $ 1000
private2[
0x7A4Ad79C4EACe6db85a86a9Fa71EEBD9bbA17Af2
] = 2127659574468100000000; // 2127.6595744681 DDAO | $ 1000
private2[
0x32527CA6ec2B85AbaCA0fb2dd3878e5b7Bb5b370
] = 2127659574468100000000; // 2127.6595744681 DDAO | $ 1000
private2[
0x35E3c412286d59Af71ba5836cE6017E416ACf8BC
] = 2127659574468100000000; // 2127.6595744681 DDAO | $ 1000
private2[
0xDc6c3d081691f7ef4ae25f488098aD0350052D43
] = 2127659574468100000000; // 2127.6595744681 DDAO | $ 1000
private2[
0xfA79F7c2601a4C2A40C80eC10cE0667988B0FC36
] = 2127659574468100000000; // 2127.6595744681 DDAO | $ 1000
private2[
0xD24596a11337129A939ba11034912B7D55262b46
] = 2127659574468100000000; // 2127.6595744681 DDAO | $ 1000
private2[
0x5748c8EE8F7Fe23D14096E51Ca0fb3Cb63223643
] = 2127659574468100000000; // 2127.6595744681 DDAO | $ 1000
private2[
0xe2D18861c892f4eFbaB6b2749e2eDe16aF458A94
] = 2127659574468100000000; // 2127.6595744681 DDAO | $ 1000
private2[
0x7F052861bf21f5208e7C0e30C9056a79E8314bA9
] = 2127659574468100000000; // 2127.6595744681 DDAO | $ 1000
private2[
0xA9786dA5d3ABb6C404b79DF28b7f402E58eF7c5B
] = 2127659574468100000000; // 2127.6595744681 DDAO | $ 1000
private2[
0xaF997affb94c5Ca556b28b024E162AA3164f4A43
] = 2127659574468100000000; // 2127.6595744681 DDAO | $ 1000
private2[
0x55fb5D5ae4A4F8369209fEf691587d40227166F6
] = 2127659574468100000000; // 2127.6595744681 DDAO | $ 1000
private2[
0xf98de1A22d715A88C2A33821917e8ce2e5583D5A
] = 2127659574468100000000; // 2127.6595744681 DDAO | $ 1000
private2[
0x6F15FA9582FdCF84f9F12D32F1C850775fD033eE
] = 2127659574468100000000; // 2127.6595744681 DDAO | $ 1000
private2[
0x6F255406306D6D78e97a29F7f249f6d2d85d9801
] = 2127659574468100000000; // 2127.6595744681 DDAO | $ 1000
private2[
0x2fb0d4F09e5F7E399354D8DbF602c871b84c081F
] = 2127659574468100000000; // 2127.6595744681 DDAO | $ 1000
private2[
0x6B745dEfEE931Ee790DFe5333446eF454c45D8Cf
] = 2127659574468100000000; // 2127.6595744681 DDAO | $ 1000
private2[
0x94d3B13745c23fB57a9634Db0b6e4f0d8b5a1053
] = 2127659574468100000000; // 2127.6595744681 DDAO | $ 1000
private2[
0x498E96c727700a6B7aC2c4EfBd3E9a5DA4F0d137
] = 2127659574468100000000; // 2127.6595744681 DDAO | $ 1000
private2[
0xB7c3A0928c06A80DC4A4CDc9dC0aec33E047A4c8
] = 1063829787234000000000; // 1063.829787234 DDAO | $ 500
}
}
| 39062.5 DDAO | $ 12500
| ] = 39062500000000000000000; | 5,536,126 | [
1,
5520,
7677,
22,
18,
25,
463,
18485,
571,
271,
2593,
12483,
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,
3639,
308,
273,
16977,
7677,
2947,
12648,
2787,
11706,
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
] |
// Contracts by dYdX Foundation. Individual files are released under different licenses.
//
// https://dydx.community
// https://github.com/dydxfoundation/governance-contracts
//
// SPDX-License-Identifier: AGPL-3.0
pragma solidity 0.7.5;
pragma abicoder v2;
import { IERC20 } from '../../interfaces/IERC20.sol';
import { ILiquidityStakingV1 } from '../../interfaces/ILiquidityStakingV1.sol';
import { IMerkleDistributorV1 } from '../../interfaces/IMerkleDistributorV1.sol';
import { IStarkPerpetual } from '../../interfaces/IStarkPerpetual.sol';
import { SafeERC20 } from '../../dependencies/open-zeppelin/SafeERC20.sol';
import { SP2Withdrawals } from './impl/SP2Withdrawals.sol';
import { SP1Getters } from '../v1/impl/SP1Getters.sol';
import { SP2Guardian } from './impl/SP2Guardian.sol';
import { SP2Owner } from './impl/SP2Owner.sol';
/**
* @title StarkProxyV2
* @author dYdX
*
* @notice Proxy contract allowing a LiquidityStaking borrower to use borrowed funds (as well as
* their own funds, if desired) on the dYdX L2 exchange. Restrictions are put in place to
* prevent borrowed funds being used outside the exchange. Furthermore, a guardian address is
* specified which has the ability to restrict borrows and make repayments.
*
* Owner actions may be delegated to various roles as defined in SP1Roles. Other actions are
* available to guardian roles, to be nominated by dYdX governance.
*/
contract StarkProxyV2 is
SP2Guardian,
SP2Owner,
SP2Withdrawals,
SP1Getters
{
using SafeERC20 for IERC20;
// ============ Constructor ============
constructor(
ILiquidityStakingV1 liquidityStaking,
IStarkPerpetual starkPerpetual,
IERC20 token,
IMerkleDistributorV1 merkleDistributor
)
SP2Guardian(liquidityStaking, starkPerpetual, token)
SP2Withdrawals(merkleDistributor)
{}
// ============ External Functions ============
function initialize()
external
initializer
{}
// ============ Internal Functions ============
/**
* @dev Returns the revision of the implementation contract.
*
* @return The revision number.
*/
function getRevision()
internal
pure
override
returns (uint256)
{
return 2;
}
}
// SPDX-License-Identifier: MIT
pragma solidity 0.7.5;
/**
* @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: Apache-2.0
pragma solidity 0.7.5;
pragma abicoder v2;
/**
* @title ILiquidityStakingV1
* @author dYdX
*
* @notice Partial interface for LiquidityStakingV1.
*/
interface ILiquidityStakingV1 {
function getToken() external view virtual returns (address);
function getBorrowedBalance(address borrower) external view virtual returns (uint256);
function getBorrowerDebtBalance(address borrower) external view virtual returns (uint256);
function isBorrowingRestrictedForBorrower(address borrower) external view virtual returns (bool);
function getTimeRemainingInEpoch() external view virtual returns (uint256);
function inBlackoutWindow() external view virtual returns (bool);
// LS1Borrowing
function borrow(uint256 amount) external virtual;
function repayBorrow(address borrower, uint256 amount) external virtual;
function getAllocatedBalanceCurrentEpoch(address borrower)
external
view
virtual
returns (uint256);
function getAllocatedBalanceNextEpoch(address borrower) external view virtual returns (uint256);
function getBorrowableAmount(address borrower) external view virtual returns (uint256);
// LS1DebtAccounting
function repayDebt(address borrower, uint256 amount) external virtual;
}
// SPDX-License-Identifier: Apache-2.0
pragma solidity 0.7.5;
pragma abicoder v2;
/**
* @title IMerkleDistributorV1
* @author dYdX
*
* @notice Partial interface for the MerkleDistributorV1 contract.
*/
interface IMerkleDistributorV1 {
function getIpnsName()
external
virtual
view
returns (string memory);
function getRewardsParameters()
external
virtual
view
returns (uint256, uint256, uint256);
function getActiveRoot()
external
virtual
view
returns (bytes32 merkleRoot, uint256 epoch, bytes memory ipfsCid);
function getNextRootEpoch()
external
virtual
view
returns (uint256);
function claimRewards(
uint256 cumulativeAmount,
bytes32[] calldata merkleProof
)
external
returns (uint256);
}
// SPDX-License-Identifier: Apache-2.0
pragma solidity 0.7.5;
pragma abicoder v2;
/**
* @title IStarkPerpetual
* @author dYdX
*
* @notice Partial interface for the StarkPerpetual contract, for accessing the dYdX L2 exchange.
* @dev See https://github.com/starkware-libs/starkex-contracts
*/
interface IStarkPerpetual {
function registerUser(
address ethKey,
uint256 starkKey,
bytes calldata signature
) external;
function deposit(
uint256 starkKey,
uint256 assetType,
uint256 vaultId,
uint256 quantizedAmount
) external;
function withdraw(uint256 starkKey, uint256 assetType) external;
function forcedWithdrawalRequest(
uint256 starkKey,
uint256 vaultId,
uint256 quantizedAmount,
bool premiumCost
) external;
function forcedTradeRequest(
uint256 starkKeyA,
uint256 starkKeyB,
uint256 vaultIdA,
uint256 vaultIdB,
uint256 collateralAssetId,
uint256 syntheticAssetId,
uint256 amountCollateral,
uint256 amountSynthetic,
bool aIsBuyingSynthetic,
uint256 submissionExpirationTime,
uint256 nonce,
bytes calldata signature,
bool premiumCost
) external;
function mainAcceptGovernance() external;
function proxyAcceptGovernance() external;
function mainRemoveGovernor(address governorForRemoval) external;
function proxyRemoveGovernor(address governorForRemoval) external;
function registerAssetConfigurationChange(uint256 assetId, bytes32 configHash) external;
function applyAssetConfigurationChange(uint256 assetId, bytes32 configHash) external;
function registerGlobalConfigurationChange(bytes32 configHash) external;
function applyGlobalConfigurationChange(bytes32 configHash) external;
function getEthKey(uint256 starkKey) external view returns (address);
function depositCancel(
uint256 starkKey,
uint256 assetType,
uint256 vaultId
) external;
function depositReclaim(
uint256 starkKey,
uint256 assetType,
uint256 vaultId
) external;
}
// SPDX-License-Identifier: MIT
pragma solidity 0.7.5;
import { IERC20 } from '../../interfaces/IERC20.sol';
import { SafeMath } from './SafeMath.sol';
import { Address } from './Address.sol';
/**
* @title SafeERC20
* @dev From https://github.com/OpenZeppelin/openzeppelin-contracts
* 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));
}
function safeApprove(
IERC20 token,
address spender,
uint256 value
) internal {
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 callOptionalReturn(IERC20 token, bytes memory data) private {
require(address(token).isContract(), 'SafeERC20: call to non-contract');
// solhint-disable-next-line avoid-low-level-calls
(bool success, bytes memory returndata) = address(token).call(data);
require(success, 'SafeERC20: low-level call failed');
if (returndata.length > 0) {
// Return data is optional
// solhint-disable-next-line max-line-length
require(abi.decode(returndata, (bool)), 'SafeERC20: ERC20 operation did not succeed');
}
}
}
// SPDX-License-Identifier: AGPL-3.0
pragma solidity 0.7.5;
pragma abicoder v2;
import { SafeERC20 } from '../../../dependencies/open-zeppelin/SafeERC20.sol';
import { SafeMath } from '../../../dependencies/open-zeppelin/SafeMath.sol';
import { IERC20 } from '../../../interfaces/IERC20.sol';
import { IMerkleDistributorV1 } from '../../../interfaces/IMerkleDistributorV1.sol';
import { IStarkPerpetual } from '../../../interfaces/IStarkPerpetual.sol';
import { SP2Exchange } from './SP2Exchange.sol';
/**
* @title SP2Withdrawals
* @author dYdX
*
* @dev Actions which may be called only by WITHDRAWAL_OPERATOR_ROLE. Allows for withdrawing
* funds from the contract to external addresses that were approved by OWNER_ROLE.
*/
abstract contract SP2Withdrawals is
SP2Exchange
{
using SafeERC20 for IERC20;
using SafeMath for uint256;
// ============ Constants ============
IMerkleDistributorV1 public immutable MERKLE_DISTRIBUTOR;
// ============ Events ============
event ExternalWithdrewToken(
address recipient,
uint256 amount
);
event ExternalWithdrewOtherToken(
address token,
address recipient,
uint256 amount
);
event ExternalWithdrewEther(
address recipient,
uint256 amount
);
// ============ Constructor ============
constructor(
IMerkleDistributorV1 merkleDistributor
) {
MERKLE_DISTRIBUTOR = merkleDistributor;
}
// ============ External Functions ============
/**
* @notice Claim rewards from the Merkle distributor. They will be held in this contract until
* withdrawn by the WITHDRAWAL_OPERATOR_ROLE.
*
* @param cumulativeAmount The total all-time rewards this contract has earned.
* @param merkleProof The Merkle proof for this contract address and cumulative amount.
*
* @return The amount of new reward received.
*/
function claimRewardsFromMerkleDistributor(
uint256 cumulativeAmount,
bytes32[] calldata merkleProof
)
external
nonReentrant
onlyRole(WITHDRAWAL_OPERATOR_ROLE)
returns (uint256)
{
return MERKLE_DISTRIBUTOR.claimRewards(cumulativeAmount, merkleProof);
}
/**
* @notice Withdraw a token amount in excess of the borrowed balance, or an amount approved by
* the GUARDIAN_ROLE.
*
* The contract may hold an excess balance if, for example, additional funds were added by the
* contract owner for use with the same exchange account, or if profits were earned from
* activity on the exchange.
*
* @param recipient The recipient to receive tokens. Must be authorized by OWNER_ROLE.
*/
function externalWithdrawToken(
address recipient,
uint256 amount
)
external
nonReentrant
onlyRole(WITHDRAWAL_OPERATOR_ROLE)
onlyAllowedRecipient(recipient)
{
// If we are approved for the full amount, then skip the borrowed balance check.
uint256 approvedAmount = _APPROVED_AMOUNT_FOR_EXTERNAL_WITHDRAWAL_;
if (approvedAmount >= amount) {
_APPROVED_AMOUNT_FOR_EXTERNAL_WITHDRAWAL_ = approvedAmount.sub(amount);
} else {
uint256 owedBalance = getBorrowedAndDebtBalance();
uint256 tokenBalance = getTokenBalance();
require(tokenBalance > owedBalance, 'SP2Withdrawals: No withdrawable balance');
uint256 availableBalance = tokenBalance.sub(owedBalance);
require(amount <= availableBalance, 'SP2Withdrawals: Amount exceeds withdrawable balance');
// Always decrease the approval amount.
_APPROVED_AMOUNT_FOR_EXTERNAL_WITHDRAWAL_ = 0;
}
TOKEN.safeTransfer(recipient, amount);
emit ExternalWithdrewToken(recipient, amount);
}
/**
* @notice Withdraw any ERC20 token balance other than the token used for borrowing.
*
* @param recipient The recipient to receive tokens. Must be authorized by OWNER_ROLE.
*/
function externalWithdrawOtherToken(
address token,
address recipient,
uint256 amount
)
external
nonReentrant
onlyRole(WITHDRAWAL_OPERATOR_ROLE)
onlyAllowedRecipient(recipient)
{
require(
token != address(TOKEN),
'SP2Withdrawals: Cannot use this function to withdraw borrowed token'
);
IERC20(token).safeTransfer(recipient, amount);
emit ExternalWithdrewOtherToken(token, recipient, amount);
}
/**
* @notice Withdraw any ether.
*
* Note: The contract is not expected to hold Ether so this is not normally needed.
*
* @param recipient The recipient to receive Ether. Must be authorized by OWNER_ROLE.
*/
function externalWithdrawEther(
address recipient,
uint256 amount
)
external
nonReentrant
onlyRole(WITHDRAWAL_OPERATOR_ROLE)
onlyAllowedRecipient(recipient)
{
payable(recipient).transfer(amount);
emit ExternalWithdrewEther(recipient, amount);
}
}
// SPDX-License-Identifier: AGPL-3.0
pragma solidity 0.7.5;
pragma abicoder v2;
import { SafeMath } from '../../../dependencies/open-zeppelin/SafeMath.sol';
import { Math } from '../../../utils/Math.sol';
import { SP1Storage } from './SP1Storage.sol';
/**
* @title SP1Getters
* @author dYdX
*
* @dev Simple external getter functions.
*/
abstract contract SP1Getters is
SP1Storage
{
using SafeMath for uint256;
// ============ External Functions ============
/**
* @notice Check whether a STARK key is on the allowlist for exchange operations.
*
* @param starkKey The STARK key to check.
*
* @return Boolean `true` if the STARK key is allowed, otherwise `false`.
*/
function isStarkKeyAllowed(
uint256 starkKey
)
external
view
returns (bool)
{
return _ALLOWED_STARK_KEYS_[starkKey];
}
/**
* @notice Check whether a recipient is on the allowlist to receive withdrawals.
*
* @param recipient The recipient to check.
*
* @return Boolean `true` if the recipient is allowed, otherwise `false`.
*/
function isRecipientAllowed(
address recipient
)
external
view
returns (bool)
{
return _ALLOWED_RECIPIENTS_[recipient];
}
/**
* @notice Get the amount approved by the guardian for external withdrawals.
* Note that withdrawals are always permitted if the amount is in excess of the borrowed amount.
*
* @return The amount approved for external withdrawals.
*/
function getApprovedAmountForExternalWithdrawal()
external
view
returns (uint256)
{
return _APPROVED_AMOUNT_FOR_EXTERNAL_WITHDRAWAL_;
}
/**
* @notice Check whether this borrower contract is restricted from new borrowing, as well as
* restricted from depositing borrowed funds to the exchange.
*
* @return Boolean `true` if the borrower is restricted, otherwise `false`.
*/
function isBorrowingRestricted()
external
view
returns (bool)
{
return _IS_BORROWING_RESTRICTED_;
}
/**
* @notice Get the timestamp at which a forced trade request was queued.
*
* @param argsHash The hash of the forced trade request args.
*
* @return Timestamp at which the forced trade was queued, or zero, if it was not queued or was
* vetoed by the VETO_GUARDIAN_ROLE.
*/
function getQueuedForcedTradeTimestamp(
bytes32 argsHash
)
external
view
returns (uint256)
{
return _QUEUED_FORCED_TRADE_TIMESTAMPS_[argsHash];
}
}
// SPDX-License-Identifier: AGPL-3.0
pragma solidity 0.7.5;
pragma abicoder v2;
import { SafeMath } from '../../../dependencies/open-zeppelin/SafeMath.sol';
import { IERC20 } from '../../../interfaces/IERC20.sol';
import { ILiquidityStakingV1 } from '../../../interfaces/ILiquidityStakingV1.sol';
import { IStarkPerpetual } from '../../../interfaces/IStarkPerpetual.sol';
import { SP1Borrowing } from '../../v1/impl/SP1Borrowing.sol';
import { SP2Exchange } from './SP2Exchange.sol';
/**
* @title SP2Guardian
* @author dYdX
*
* @dev Defines guardian powers, to be owned or delegated by dYdX governance.
*/
abstract contract SP2Guardian is
SP1Borrowing,
SP2Exchange
{
using SafeMath for uint256;
// ============ Events ============
event BorrowingRestrictionChanged(
bool isBorrowingRestricted
);
event GuardianVetoedForcedTradeRequest(
bytes32 argsHash
);
event GuardianUpdateApprovedAmountForExternalWithdrawal(
uint256 amount
);
// ============ Constructor ============
constructor(
ILiquidityStakingV1 liquidityStaking,
IStarkPerpetual starkPerpetual,
IERC20 token
)
SP1Borrowing(liquidityStaking, token)
SP2Exchange(starkPerpetual)
{}
// ============ External Functions ============
/**
* @notice Approve an additional amount for external withdrawal by WITHDRAWAL_OPERATOR_ROLE.
*
* @param amount The additional amount to approve for external withdrawal.
*
* @return The new amount approved for external withdrawal.
*/
function increaseApprovedAmountForExternalWithdrawal(
uint256 amount
)
external
nonReentrant
onlyRole(GUARDIAN_ROLE)
returns (uint256)
{
uint256 newApprovedAmount = _APPROVED_AMOUNT_FOR_EXTERNAL_WITHDRAWAL_.add(
amount
);
_APPROVED_AMOUNT_FOR_EXTERNAL_WITHDRAWAL_ = newApprovedAmount;
emit GuardianUpdateApprovedAmountForExternalWithdrawal(newApprovedAmount);
return newApprovedAmount;
}
/**
* @notice Set the approved amount for external withdrawal to zero.
*
* @return The amount that was previously approved for external withdrawal.
*/
function resetApprovedAmountForExternalWithdrawal()
external
nonReentrant
onlyRole(GUARDIAN_ROLE)
returns (uint256)
{
uint256 previousApprovedAmount = _APPROVED_AMOUNT_FOR_EXTERNAL_WITHDRAWAL_;
_APPROVED_AMOUNT_FOR_EXTERNAL_WITHDRAWAL_ = 0;
emit GuardianUpdateApprovedAmountForExternalWithdrawal(0);
return previousApprovedAmount;
}
/**
* @notice Guardian method to restrict borrowing or depositing borrowed funds to the exchange.
*/
function guardianSetBorrowingRestriction(
bool isBorrowingRestricted
)
external
nonReentrant
onlyRole(GUARDIAN_ROLE)
{
_IS_BORROWING_RESTRICTED_ = isBorrowingRestricted;
emit BorrowingRestrictionChanged(isBorrowingRestricted);
}
/**
* @notice Guardian method to repay this contract's borrowed balance, using this contract's funds.
*
* @param amount Amount to repay.
*/
function guardianRepayBorrow(
uint256 amount
)
external
nonReentrant
onlyRole(GUARDIAN_ROLE)
{
_repayBorrow(amount, true);
}
/**
* @notice Guardian method to repay a debt balance owed by the borrower.
*
* @param amount Amount to repay.
*/
function guardianRepayDebt(
uint256 amount
)
external
nonReentrant
onlyRole(GUARDIAN_ROLE)
{
_repayDebt(amount, true);
}
/**
* @notice Guardian method to trigger a withdrawal. This will transfer funds from StarkPerpetual
* to this contract. This requires a (slow) withdrawal from L2 to have been previously processed.
*
* Note: This function is intentionally not protected by the onlyAllowedKey modifier.
*
* @return The ERC20 token amount received by this contract.
*/
function guardianWithdrawFromExchange(
uint256 starkKey,
uint256 assetType
)
external
nonReentrant
onlyRole(GUARDIAN_ROLE)
returns (uint256)
{
return _withdrawFromExchange(starkKey, assetType, true);
}
/**
* @notice Guardian method to trigger a forced withdrawal request.
* Reverts if the borrower has no overdue debt.
*
* Note: This function is intentionally not protected by the onlyAllowedKey modifier.
*/
function guardianForcedWithdrawalRequest(
uint256 starkKey,
uint256 vaultId,
uint256 quantizedAmount,
bool premiumCost
)
external
nonReentrant
onlyRole(GUARDIAN_ROLE)
{
require(
getDebtBalance() > 0,
'SP2Guardian: Cannot call forced action if borrower has no overdue debt'
);
_forcedWithdrawalRequest(
starkKey,
vaultId,
quantizedAmount,
premiumCost,
true // isGuardianAction
);
}
/**
* @notice Guardian method to trigger a forced trade request.
* Reverts if the borrower has no overdue debt.
*
* Note: This function is intentionally not protected by the onlyAllowedKey modifier.
*/
function guardianForcedTradeRequest(
uint256[12] calldata args,
bytes calldata signature
)
external
nonReentrant
onlyRole(GUARDIAN_ROLE)
{
require(
getDebtBalance() > 0,
'SP2Guardian: Cannot call forced action if borrower has no overdue debt'
);
_forcedTradeRequest(args, signature, true);
}
/**
* @notice Guardian method to prevent queued forced trade requests from being executed.
*
* May only be called by VETO_GUARDIAN_ROLE.
*
* @param argsHashes An array of hashes for each forced trade request to veto.
*/
function guardianVetoForcedTradeRequests(
bytes32[] calldata argsHashes
)
external
nonReentrant
onlyRole(VETO_GUARDIAN_ROLE)
{
for (uint256 i = 0; i < argsHashes.length; i++) {
bytes32 argsHash = argsHashes[i];
_QUEUED_FORCED_TRADE_TIMESTAMPS_[argsHash] = 0;
emit GuardianVetoedForcedTradeRequest(argsHash);
}
}
/**
* @notice Guardian method to request to cancel a pending deposit to the exchange.
*
* @param starkKey The STARK key of the account.
* @param assetType The exchange asset ID for the deposit.
* @param vaultId The exchange position ID for the deposit.
*
* Note: This function is intentionally not protected by the onlyAllowedKey modifier.
*/
function guardianDepositCancel(
uint256 starkKey,
uint256 assetType,
uint256 vaultId
)
external
nonReentrant
onlyRole(GUARDIAN_ROLE)
{
_depositCancel(starkKey, assetType, vaultId, true);
}
/**
* @notice Guardian method to reclaim a canceled pending deposit to the exchange. Requires
* that `depositCancel` was previously called.
*
* @param starkKey The STARK key of the account.
* @param assetType The exchange asset ID for the deposit.
* @param vaultId The exchange position ID for the deposit.
*
* Note: This function is intentionally not protected by the onlyAllowedKey modifier.
*/
function guardianDepositReclaim(
uint256 starkKey,
uint256 assetType,
uint256 vaultId
)
external
nonReentrant
onlyRole(GUARDIAN_ROLE)
{
_depositReclaim(starkKey, assetType, vaultId, true);
}
}
// SPDX-License-Identifier: AGPL-3.0
pragma solidity 0.7.5;
pragma abicoder v2;
import { SafeERC20 } from '../../../dependencies/open-zeppelin/SafeERC20.sol';
import { SafeMath } from '../../../dependencies/open-zeppelin/SafeMath.sol';
import { IERC20 } from '../../../interfaces/IERC20.sol';
import { IStarkPerpetual } from '../../../interfaces/IStarkPerpetual.sol';
import { SP1Borrowing } from '../../v1/impl/SP1Borrowing.sol';
import { SP2Exchange } from './SP2Exchange.sol';
/**
* @title SP2Owner
* @author dYdX
*
* @dev Actions which may be called only by OWNER_ROLE. These include actions with a larger amount
* of control over the funds held by the contract.
*/
abstract contract SP2Owner is
SP1Borrowing,
SP2Exchange
{
using SafeERC20 for IERC20;
using SafeMath for uint256;
// ============ Constants ============
/// @notice Time that must elapse before a queued forced trade request can be submitted.
uint256 public constant FORCED_TRADE_WAITING_PERIOD = 7 days;
/// @notice Max time that may elapse after the waiting period before a queued forced trade
/// request expires.
uint256 public constant FORCED_TRADE_GRACE_PERIOD = 7 days;
// ============ Events ============
event UpdatedStarkKey(
uint256 starkKey,
bool isAllowed
);
event UpdatedExternalRecipient(
address recipient,
bool isAllowed
);
event QueuedForcedTradeRequest(
uint256[12] args,
bytes32 argsHash
);
// ============ External Functions ============
/**
* @notice Allow exchange functions to be called for a particular STARK key.
*
* Will revert if the STARK key is not registered to this contract's address on the
* StarkPerpetual contract.
*
* @param starkKey The STARK key to allow.
*/
function allowStarkKey(
uint256 starkKey
)
external
nonReentrant
onlyRole(OWNER_ROLE)
{
// This will revert with 'USER_UNREGISTERED' if the STARK key was not registered.
address ethKey = STARK_PERPETUAL.getEthKey(starkKey);
// Require the STARK key to be registered to this contract before we allow it to be used.
require(ethKey == address(this), 'SP2Owner: STARK key not registered to this contract');
require(!_ALLOWED_STARK_KEYS_[starkKey], 'SP2Owner: STARK key already allowed');
_ALLOWED_STARK_KEYS_[starkKey] = true;
emit UpdatedStarkKey(starkKey, true);
}
/**
* @notice Remove a STARK key from the allowed list.
*
* @param starkKey The STARK key to disallow.
*/
function disallowStarkKey(
uint256 starkKey
)
external
nonReentrant
onlyRole(OWNER_ROLE)
{
require(_ALLOWED_STARK_KEYS_[starkKey], 'SP2Owner: STARK key already disallowed');
_ALLOWED_STARK_KEYS_[starkKey] = false;
emit UpdatedStarkKey(starkKey, false);
}
/**
* @notice Allow withdrawals of excess funds to be made to a particular recipient.
*
* @param recipient The recipient to allow.
*/
function allowExternalRecipient(
address recipient
)
external
nonReentrant
onlyRole(OWNER_ROLE)
{
require(!_ALLOWED_RECIPIENTS_[recipient], 'SP2Owner: Recipient already allowed');
_ALLOWED_RECIPIENTS_[recipient] = true;
emit UpdatedExternalRecipient(recipient, true);
}
/**
* @notice Remove a recipient from the allowed list.
*
* @param recipient The recipient to disallow.
*/
function disallowExternalRecipient(
address recipient
)
external
nonReentrant
onlyRole(OWNER_ROLE)
{
require(_ALLOWED_RECIPIENTS_[recipient], 'SP2Owner: Recipient already disallowed');
_ALLOWED_RECIPIENTS_[recipient] = false;
emit UpdatedExternalRecipient(recipient, false);
}
/**
* @notice Set ERC20 token allowance for the exchange contract.
*
* @param token The ERC20 token to set the allowance for.
* @param amount The new allowance amount.
*/
function setExchangeContractAllowance(
address token,
uint256 amount
)
external
nonReentrant
onlyRole(OWNER_ROLE)
{
// SafeERC20 safeApprove requires setting to zero first.
IERC20(token).safeApprove(address(STARK_PERPETUAL), 0);
IERC20(token).safeApprove(address(STARK_PERPETUAL), amount);
}
/**
* @notice Set ERC20 token allowance for the staking contract.
*
* @param token The ERC20 token to set the allowance for.
* @param amount The new allowance amount.
*/
function setStakingContractAllowance(
address token,
uint256 amount
)
external
nonReentrant
onlyRole(OWNER_ROLE)
{
// SafeERC20 safeApprove requires setting to zero first.
IERC20(token).safeApprove(address(LIQUIDITY_STAKING), 0);
IERC20(token).safeApprove(address(LIQUIDITY_STAKING), amount);
}
/**
* @notice Request a forced withdrawal from the exchange.
*
* @param starkKey The STARK key of the account. Must be authorized by OWNER_ROLE.
* @param vaultId The exchange position ID for the account to deposit to.
* @param quantizedAmount The withdrawal amount denominated in the exchange base units.
* @param premiumCost Whether to pay a higher fee for faster inclusion in certain scenarios.
*/
function forcedWithdrawalRequest(
uint256 starkKey,
uint256 vaultId,
uint256 quantizedAmount,
bool premiumCost
)
external
nonReentrant
onlyRole(OWNER_ROLE)
onlyAllowedKey(starkKey)
{
_forcedWithdrawalRequest(starkKey, vaultId, quantizedAmount, premiumCost, false);
}
/**
* @notice Queue a forced trade request to be submitted after the waiting period.
*
* @param args Arguments for the forced trade request.
*/
function queueForcedTradeRequest(
uint256[12] calldata args
)
external
nonReentrant
onlyRole(OWNER_ROLE)
{
bytes32 argsHash = keccak256(abi.encodePacked(args));
_QUEUED_FORCED_TRADE_TIMESTAMPS_[argsHash] = block.timestamp;
emit QueuedForcedTradeRequest(args, argsHash);
}
/**
* @notice Submit a forced trade request that was previously queued.
*
* @param args Arguments for the forced trade request.
* @param signature The signature of the counterparty to the trade.
*/
function forcedTradeRequest(
uint256[12] calldata args,
bytes calldata signature
)
external
nonReentrant
onlyRole(OWNER_ROLE)
onlyAllowedKey(args[0]) // starkKeyA
{
bytes32 argsHash = keccak256(abi.encodePacked(args));
uint256 timestamp = _QUEUED_FORCED_TRADE_TIMESTAMPS_[argsHash];
require(
timestamp != 0,
'SP2Owner: Forced trade not queued or was vetoed'
);
uint256 elapsed = block.timestamp.sub(timestamp);
require(
elapsed >= FORCED_TRADE_WAITING_PERIOD,
'SP2Owner: Waiting period has not elapsed for forced trade'
);
require(
elapsed <= FORCED_TRADE_WAITING_PERIOD.add(FORCED_TRADE_GRACE_PERIOD),
'SP2Owner: Grace period has elapsed for forced trade'
);
_QUEUED_FORCED_TRADE_TIMESTAMPS_[argsHash] = 0;
_forcedTradeRequest(args, signature, false);
}
/**
* @notice Request to cancel a pending deposit to the exchange.
*
* @param starkKey The STARK key of the account. Must be authorized by OWNER_ROLE.
* @param assetType The exchange asset ID for the deposit.
* @param vaultId The exchange position ID for the deposit.
*/
function depositCancel(
uint256 starkKey,
uint256 assetType,
uint256 vaultId
)
external
nonReentrant
onlyRole(OWNER_ROLE)
onlyAllowedKey(starkKey)
{
_depositCancel(starkKey, assetType, vaultId, false);
}
/**
* @notice Reclaim a canceled pending deposit to the exchange. Requires that `depositCancel`
* was previously called.
*
* @param starkKey The STARK key of the account. Must be authorized by OWNER_ROLE.
* @param assetType The exchange asset ID for the deposit.
* @param vaultId The exchange position ID for the deposit.
*/
function depositReclaim(
uint256 starkKey,
uint256 assetType,
uint256 vaultId
)
external
nonReentrant
onlyRole(OWNER_ROLE)
onlyAllowedKey(starkKey)
{
_depositReclaim(starkKey, assetType, vaultId, false);
}
}
// SPDX-License-Identifier: MIT
pragma solidity 0.7.5;
/**
* @dev Wrappers over Solidity's arithmetic operations with added overflow
* checks.
*
* Arithmetic operations in Solidity wrap on overflow. This can easily result
* in bugs, because programmers usually assume that an overflow raises an
* error, which is the standard behavior in high level programming languages.
* `SafeMath` restores this intuition by reverting the transaction when an
* operation overflows.
*
* Using this library instead of the unchecked operations eliminates an entire
* class of bugs, so it's recommended to use it always.
*/
library SafeMath {
/**
* @dev Returns the addition of two unsigned integers, reverting on
* overflow.
*
* Counterpart to Solidity's `+` operator.
*
* Requirements:
* - Addition cannot overflow.
*/
function add(uint256 a, uint256 b) internal pure returns (uint256) {
uint256 c = a + b;
require(c >= a, 'SafeMath: addition overflow');
return c;
}
/**
* @dev Returns the subtraction of two unsigned integers, reverting on
* overflow (when the result is negative).
*
* Counterpart to Solidity's `-` operator.
*
* Requirements:
* - Subtraction cannot overflow.
*/
function sub(uint256 a, uint256 b) internal pure returns (uint256) {
return sub(a, b, 'SafeMath: subtraction overflow');
}
/**
* @dev Returns the subtraction of two unsigned integers, reverting with custom message on
* overflow (when the result is negative).
*
* Counterpart to Solidity's `-` operator.
*
* Requirements:
* - Subtraction cannot overflow.
*/
function sub(
uint256 a,
uint256 b,
string memory errorMessage
) internal pure returns (uint256) {
require(b <= a, errorMessage);
uint256 c = a - b;
return c;
}
/**
* @dev Returns the multiplication of two unsigned integers, reverting on
* overflow.
*
* Counterpart to Solidity's `*` operator.
*
* Requirements:
* - Multiplication cannot overflow.
*/
function mul(uint256 a, uint256 b) internal pure returns (uint256) {
// Gas optimization: this is cheaper than requiring 'a' not being zero, but the
// benefit is lost if 'b' is also tested.
// See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522
if (a == 0) {
return 0;
}
uint256 c = a * b;
require(c / a == b, 'SafeMath: multiplication overflow');
return c;
}
/**
* @dev Returns the integer division of two unsigned integers. Reverts on
* division by zero. The result is rounded towards zero.
*
* Counterpart to Solidity's `/` operator. Note: this function uses a
* `revert` opcode (which leaves remaining gas untouched) while Solidity
* uses an invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
* - The divisor cannot be zero.
*/
function div(uint256 a, uint256 b) internal pure returns (uint256) {
return div(a, b, 'SafeMath: division by zero');
}
/**
* @dev Returns the integer division of two unsigned integers. Reverts with custom message on
* division by zero. The result is rounded towards zero.
*
* Counterpart to Solidity's `/` operator. Note: this function uses a
* `revert` opcode (which leaves remaining gas untouched) while Solidity
* uses an invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
* - The divisor cannot be zero.
*/
function div(
uint256 a,
uint256 b,
string memory errorMessage
) internal pure returns (uint256) {
// Solidity only automatically asserts when dividing by 0
require(b > 0, errorMessage);
uint256 c = a / b;
// assert(a == b * c + a % b); // There is no case in which this doesn't hold
return c;
}
/**
* @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo),
* Reverts when dividing by zero.
*
* Counterpart to Solidity's `%` operator. This function uses a `revert`
* opcode (which leaves remaining gas untouched) while Solidity uses an
* invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
* - The divisor cannot be zero.
*/
function mod(uint256 a, uint256 b) internal pure returns (uint256) {
return mod(a, b, 'SafeMath: modulo by zero');
}
/**
* @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo),
* Reverts with custom message when dividing by zero.
*
* Counterpart to Solidity's `%` operator. This function uses a `revert`
* opcode (which leaves remaining gas untouched) while Solidity uses an
* invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
* - The divisor cannot be zero.
*/
function mod(
uint256 a,
uint256 b,
string memory errorMessage
) internal pure returns (uint256) {
require(b != 0, errorMessage);
return a % b;
}
}
// SPDX-License-Identifier: MIT
pragma solidity 0.7.5;
/**
* @dev Collection of functions related to the address type
*/
library Address {
/**
* @dev Returns true if `account` is a contract.
*
* [IMPORTANT]
* ====
* It is unsafe to assume that an address for which this function returns
* false is an externally-owned account (EOA) and not a contract.
*
* Among others, `isContract` will return false for the following
* types of addresses:
*
* - an externally-owned account
* - a contract in construction
* - an address where a contract will be created
* - an address where a contract lived, but was destroyed
* ====
*/
function isContract(address account) internal view returns (bool) {
// According to EIP-1052, 0x0 is the value returned for not-yet created accounts
// and 0xc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470 is returned
// for accounts without code, i.e. `keccak256('')`
bytes32 codehash;
bytes32 accountHash = 0xc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470;
// solhint-disable-next-line no-inline-assembly
assembly {
codehash := extcodehash(account)
}
return (codehash != accountHash && codehash != 0x0);
}
/**
* @dev Replacement for Solidity's `transfer`: sends `amount` wei to
* `recipient`, forwarding all available gas and reverting on errors.
*
* https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost
* of certain opcodes, possibly making contracts go over the 2300 gas limit
* imposed by `transfer`, making them unable to receive funds via
* `transfer`. {sendValue} removes this limitation.
*
* https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more].
*
* IMPORTANT: because control is transferred to `recipient`, care must be
* taken to not create reentrancy vulnerabilities. Consider using
* {ReentrancyGuard} or the
* https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern].
*/
function sendValue(address payable recipient, uint256 amount) internal {
require(address(this).balance >= amount, 'Address: insufficient balance');
// solhint-disable-next-line avoid-low-level-calls, avoid-call-value
(bool success, ) = recipient.call{value: amount}('');
require(success, 'Address: unable to send value, recipient may have reverted');
}
}
// SPDX-License-Identifier: AGPL-3.0
pragma solidity 0.7.5;
pragma abicoder v2;
import { SafeMath } from '../../../dependencies/open-zeppelin/SafeMath.sol';
import { IERC20 } from '../../../interfaces/IERC20.sol';
import { IStarkPerpetual } from '../../../interfaces/IStarkPerpetual.sol';
import { SP1Balances } from '../../v1/impl/SP1Balances.sol';
/**
* @title SP2Exchange
* @author dYdX
*
* @dev Handles calls to the StarkPerpetual contract, for interacting with the dYdX L2 exchange.
*
* Standard exchange operation is handled by EXCHANGE_OPERATOR_ROLE. The “forced” actions can only
* be called by the OWNER_ROLE or GUARDIAN_ROLE. Some other functions are also callable by
* the GUARDIAN_ROLE.
*
* See SP1Roles, SP2Guardian, SP2Owner, and SP2Withdrawals.
*/
abstract contract SP2Exchange is
SP1Balances
{
using SafeMath for uint256;
// ============ Constants ============
IStarkPerpetual public immutable STARK_PERPETUAL;
// ============ Events ============
event DepositedToExchange(
uint256 starkKey,
uint256 starkAssetType,
uint256 starkVaultId,
uint256 tokenAmount
);
event WithdrewFromExchange(
uint256 starkKey,
uint256 starkAssetType,
uint256 tokenAmount,
bool isGuardianAction
);
/// @dev Limited fields included. Details can be retrieved from Starkware logs if needed.
event RequestedForcedWithdrawal(
uint256 starkKey,
uint256 vaultId,
bool isGuardianAction
);
/// @dev Limited fields included. Details can be retrieved from Starkware logs if needed.
event RequestedForcedTrade(
uint256 starkKey,
uint256 vaultId,
bool isGuardianAction
);
event DepositCanceled(
uint256 starkKey,
uint256 starkAssetType,
uint256 vaultId,
bool isGuardianAction
);
event DepositReclaimed(
uint256 starkKey,
uint256 starkAssetType,
uint256 vaultId,
uint256 fundsReclaimed,
bool isGuardianAction
);
// ============ Constructor ============
constructor(
IStarkPerpetual starkPerpetual
) {
STARK_PERPETUAL = starkPerpetual;
}
// ============ External Functions ============
/**
* @notice Deposit funds to the exchange.
*
* IMPORTANT: The caller is responsible for providing `quantizedAmount` in the right units.
* Currently, the exchange collateral is USDC, denominated in ERC20 token units, but
* this could change.
*
* @param starkKey The STARK key of the account. Must be authorized by OWNER_ROLE.
* @param assetType The exchange asset ID for the asset to deposit.
* @param vaultId The exchange position ID for the account to deposit to.
* @param quantizedAmount The deposit amount denominated in the exchange base units.
*
* @return The ERC20 token amount spent.
*/
function depositToExchange(
uint256 starkKey,
uint256 assetType,
uint256 vaultId,
uint256 quantizedAmount
)
external
nonReentrant
onlyRole(EXCHANGE_OPERATOR_ROLE)
onlyAllowedKey(starkKey)
returns (uint256)
{
// Deposit and get the deposited token amount.
uint256 startingBalance = getTokenBalance();
STARK_PERPETUAL.deposit(starkKey, assetType, vaultId, quantizedAmount);
uint256 endingBalance = getTokenBalance();
uint256 tokenAmount = startingBalance.sub(endingBalance);
// Disallow depositing borrowed funds to the exchange if the guardian has restricted borrowing.
if (_IS_BORROWING_RESTRICTED_) {
require(
endingBalance >= getBorrowedAndDebtBalance(),
'SP2Exchange: Cannot deposit borrowed funds to the exchange while Restricted'
);
}
emit DepositedToExchange(starkKey, assetType, vaultId, tokenAmount);
return tokenAmount;
}
/**
* @notice Trigger a withdrawal of account funds held in the exchange contract. This can be
* called after a (slow) withdrawal has already been processed by the L2 exchange.
*
* @param starkKey The STARK key of the account. Must be authorized by OWNER_ROLE.
* @param assetType The exchange asset ID for the asset to withdraw.
*
* @return The ERC20 token amount received by this contract.
*/
function withdrawFromExchange(
uint256 starkKey,
uint256 assetType
)
external
nonReentrant
onlyRole(EXCHANGE_OPERATOR_ROLE)
onlyAllowedKey(starkKey)
returns (uint256)
{
return _withdrawFromExchange(starkKey, assetType, false);
}
// ============ Internal Functions ============
function _withdrawFromExchange(
uint256 starkKey,
uint256 assetType,
bool isGuardianAction
)
internal
returns (uint256)
{
uint256 startingBalance = getTokenBalance();
STARK_PERPETUAL.withdraw(starkKey, assetType);
uint256 endingBalance = getTokenBalance();
uint256 tokenAmount = endingBalance.sub(startingBalance);
emit WithdrewFromExchange(starkKey, assetType, tokenAmount, isGuardianAction);
return tokenAmount;
}
function _forcedWithdrawalRequest(
uint256 starkKey,
uint256 vaultId,
uint256 quantizedAmount,
bool premiumCost,
bool isGuardianAction
)
internal
{
STARK_PERPETUAL.forcedWithdrawalRequest(starkKey, vaultId, quantizedAmount, premiumCost);
emit RequestedForcedWithdrawal(starkKey, vaultId, isGuardianAction);
}
function _forcedTradeRequest(
uint256[12] calldata args,
bytes calldata signature,
bool isGuardianAction
)
internal
{
// Split into two functions to avoid error 'call stack too deep'.
if (args[11] != 0) {
_forcedTradeRequestPremiumCostTrue(args, signature);
} else {
_forcedTradeRequestPremiumCostFalse(args, signature);
}
emit RequestedForcedTrade(
args[0], // starkKeyA
args[2], // vaultIdA
isGuardianAction
);
}
function _depositCancel(
uint256 starkKey,
uint256 assetType,
uint256 vaultId,
bool isGuardianAction
)
internal
{
STARK_PERPETUAL.depositCancel(starkKey, assetType, vaultId);
emit DepositCanceled(starkKey, assetType, vaultId, isGuardianAction);
}
function _depositReclaim(
uint256 starkKey,
uint256 assetType,
uint256 vaultId,
bool isGuardianAction
)
internal
{
uint256 startingBalance = getTokenBalance();
STARK_PERPETUAL.depositReclaim(starkKey, assetType, vaultId);
uint256 endingBalance = getTokenBalance();
uint256 tokenAmount = endingBalance.sub(startingBalance);
emit DepositReclaimed(
starkKey,
assetType,
vaultId,
tokenAmount,
isGuardianAction
);
}
// ============ Private Functions ============
// Split into two functions to avoid error 'call stack too deep'.
function _forcedTradeRequestPremiumCostTrue(
uint256[12] calldata args,
bytes calldata signature
)
private
{
STARK_PERPETUAL.forcedTradeRequest(
args[0], // starkKeyA
args[1], // starkKeyB
args[2], // vaultIdA
args[3], // vaultIdB
args[4], // collateralAssetId
args[5], // syntheticAssetId
args[6], // amountCollateral
args[7], // amountSynthetic
args[8] != 0, // aIsBuyingSynthetic
args[9], // submissionExpirationTime
args[10], // nonce
signature,
true // premiumCost
);
}
// Split into two functions to avoid error 'call stack too deep'.
function _forcedTradeRequestPremiumCostFalse(
uint256[12] calldata args,
bytes calldata signature
)
private
{
STARK_PERPETUAL.forcedTradeRequest(
args[0], // starkKeyA
args[1], // starkKeyB
args[2], // vaultIdA
args[3], // vaultIdB
args[4], // collateralAssetId
args[5], // syntheticAssetId
args[6], // amountCollateral
args[7], // amountSynthetic
args[8] != 0, // aIsBuyingSynthetic
args[9], // submissionExpirationTime
args[10], // nonce
signature,
false // premiumCost
);
}
}
// SPDX-License-Identifier: AGPL-3.0
pragma solidity 0.7.5;
pragma abicoder v2;
import { SafeMath } from '../../../dependencies/open-zeppelin/SafeMath.sol';
import { IERC20 } from '../../../interfaces/IERC20.sol';
import { ILiquidityStakingV1 } from '../../../interfaces/ILiquidityStakingV1.sol';
import { Math } from '../../../utils/Math.sol';
import { SP1Roles } from './SP1Roles.sol';
/**
* @title SP1Balances
* @author dYdX
*
* @dev Contains common constants and functions related to token balances.
*/
abstract contract SP1Balances is
SP1Roles
{
using SafeMath for uint256;
// ============ Constants ============
IERC20 public immutable TOKEN;
ILiquidityStakingV1 public immutable LIQUIDITY_STAKING;
// ============ Constructor ============
constructor(
ILiquidityStakingV1 liquidityStaking,
IERC20 token
) {
LIQUIDITY_STAKING = liquidityStaking;
TOKEN = token;
}
// ============ Public Functions ============
function getAllocatedBalanceCurrentEpoch()
public
view
returns (uint256)
{
return LIQUIDITY_STAKING.getAllocatedBalanceCurrentEpoch(address(this));
}
function getAllocatedBalanceNextEpoch()
public
view
returns (uint256)
{
return LIQUIDITY_STAKING.getAllocatedBalanceNextEpoch(address(this));
}
function getBorrowableAmount()
public
view
returns (uint256)
{
if (_IS_BORROWING_RESTRICTED_) {
return 0;
}
return LIQUIDITY_STAKING.getBorrowableAmount(address(this));
}
function getBorrowedBalance()
public
view
returns (uint256)
{
return LIQUIDITY_STAKING.getBorrowedBalance(address(this));
}
function getDebtBalance()
public
view
returns (uint256)
{
return LIQUIDITY_STAKING.getBorrowerDebtBalance(address(this));
}
function getBorrowedAndDebtBalance()
public
view
returns (uint256)
{
return getBorrowedBalance().add(getDebtBalance());
}
function getTokenBalance()
public
view
returns (uint256)
{
return TOKEN.balanceOf(address(this));
}
}
// SPDX-License-Identifier: Apache-2.0
pragma solidity 0.7.5;
pragma abicoder v2;
import { SafeMath } from '../dependencies/open-zeppelin/SafeMath.sol';
/**
* @title Math
* @author dYdX
*
* @dev Library for non-standard Math functions.
*/
library Math {
using SafeMath for uint256;
// ============ Library Functions ============
/**
* @dev Return `ceil(numerator / denominator)`.
*/
function divRoundUp(
uint256 numerator,
uint256 denominator
)
internal
pure
returns (uint256)
{
if (numerator == 0) {
// SafeMath will check for zero denominator
return SafeMath.div(0, denominator);
}
return numerator.sub(1).div(denominator).add(1);
}
/**
* @dev Returns the minimum between a and b.
*/
function min(
uint256 a,
uint256 b
)
internal
pure
returns (uint256)
{
return a < b ? a : b;
}
/**
* @dev Returns the maximum between a and b.
*/
function max(
uint256 a,
uint256 b
)
internal
pure
returns (uint256)
{
return a > b ? a : b;
}
}
// SPDX-License-Identifier: AGPL-3.0
pragma solidity 0.7.5;
pragma abicoder v2;
import { SP1Storage } from './SP1Storage.sol';
/**
* @title SP1Roles
* @author dYdX
*
* @dev Defines roles used in the StarkProxyV1 contract. The hierarchy and powers of each role
* are described below. Not all roles need to be used.
*
* Overview:
*
* During operation of this contract, funds will flow between the following three
* contracts:
*
* LiquidityStaking <> StarkProxy <> StarkPerpetual
*
* Actions which move fund from left to right are called “open” actions, whereas actions which
* move funds from right to left are called “close” actions.
*
* Also note that the “forced” actions (forced trade and forced withdrawal) require special care
* since they directly impact the financial risk of positions held on the exchange.
*
* Roles:
*
* GUARDIAN_ROLE
* | -> May perform “close” actions as defined above, but “forced” actions can only be taken
* | if the borrower has an outstanding debt balance.
* | -> May restrict “open” actions as defined above, except w.r.t. funds in excess of the
* | borrowed balance.
* | -> May approve a token amount to be withdrawn externally by the WITHDRAWAL_OPERATOR_ROLE
* | to an allowed address.
* |
* +-- VETO_GUARDIAN_ROLE
* -> May veto forced trade requests initiated by the owner, during the waiting period.
*
* OWNER_ROLE
* | -> May add or remove allowed recipients who may receive excess funds.
* | -> May add or remove allowed STARK keys for use on the exchange.
* | -> May set ERC20 allowances on the LiquidityStakingV1 and StarkPerpetual contracts.
* | -> May call the “forced” actions: forcedWithdrawalRequest and forcedTradeRequest.
* |
* +-- DELEGATION_ADMIN_ROLE
* |
* +-- BORROWER_ROLE
* | -> May call functions on LiquidityStakingV1: autoPayOrBorrow, borrow, repay,
* | and repayDebt.
* |
* +-- EXCHANGE_OPERATOR_ROLE
* | -> May call functions on StarkPerpetual: depositToExchange and
* | withdrawFromExchange.
* |
* +-- WITHDRAWAL_OPERATOR_ROLE
* -> May withdraw funds in excess of the borrowed balance to an allowed recipient.
*/
abstract contract SP1Roles is
SP1Storage
{
bytes32 public constant GUARDIAN_ROLE = keccak256('GUARDIAN_ROLE');
bytes32 public constant VETO_GUARDIAN_ROLE = keccak256('VETO_GUARDIAN_ROLE');
bytes32 public constant OWNER_ROLE = keccak256('OWNER_ROLE');
bytes32 public constant DELEGATION_ADMIN_ROLE = keccak256('DELEGATION_ADMIN_ROLE');
bytes32 public constant BORROWER_ROLE = keccak256('BORROWER_ROLE');
bytes32 public constant EXCHANGE_OPERATOR_ROLE = keccak256('EXCHANGE_OPERATOR_ROLE');
bytes32 public constant WITHDRAWAL_OPERATOR_ROLE = keccak256('WITHDRAWAL_OPERATOR_ROLE');
function __SP1Roles_init(
address guardian
)
internal
{
// Assign GUARDIAN_ROLE.
_setupRole(GUARDIAN_ROLE, guardian);
// Assign OWNER_ROLE and DELEGATION_ADMIN_ROLE to the sender.
_setupRole(OWNER_ROLE, msg.sender);
_setupRole(DELEGATION_ADMIN_ROLE, msg.sender);
// Set admins for all roles. (Don't use the default admin role.)
_setRoleAdmin(GUARDIAN_ROLE, GUARDIAN_ROLE);
_setRoleAdmin(VETO_GUARDIAN_ROLE, GUARDIAN_ROLE);
_setRoleAdmin(OWNER_ROLE, OWNER_ROLE);
_setRoleAdmin(DELEGATION_ADMIN_ROLE, OWNER_ROLE);
_setRoleAdmin(BORROWER_ROLE, DELEGATION_ADMIN_ROLE);
_setRoleAdmin(EXCHANGE_OPERATOR_ROLE, DELEGATION_ADMIN_ROLE);
_setRoleAdmin(WITHDRAWAL_OPERATOR_ROLE, DELEGATION_ADMIN_ROLE);
}
}
// SPDX-License-Identifier: AGPL-3.0
pragma solidity 0.7.5;
pragma abicoder v2;
import {
AccessControlUpgradeable
} from '../../../dependencies/open-zeppelin/AccessControlUpgradeable.sol';
import { ReentrancyGuard } from '../../../utils/ReentrancyGuard.sol';
import { VersionedInitializable } from '../../../utils/VersionedInitializable.sol';
/**
* @title SP1Storage
* @author dYdX
*
* @dev Storage contract. Contains or inherits from all contracts with storage.
*/
abstract contract SP1Storage is
AccessControlUpgradeable,
ReentrancyGuard,
VersionedInitializable
{
// ============ Modifiers ============
/**
* @dev Modifier to ensure the STARK key is allowed.
*/
modifier onlyAllowedKey(
uint256 starkKey
) {
require(_ALLOWED_STARK_KEYS_[starkKey], 'SP1Storage: STARK key is not on the allowlist');
_;
}
/**
* @dev Modifier to ensure the recipient is allowed.
*/
modifier onlyAllowedRecipient(
address recipient
) {
require(_ALLOWED_RECIPIENTS_[recipient], 'SP1Storage: Recipient is not on the allowlist');
_;
}
// ============ Storage ============
mapping(uint256 => bool) internal _ALLOWED_STARK_KEYS_;
mapping(address => bool) internal _ALLOWED_RECIPIENTS_;
/// @dev Note that withdrawals are always permitted if the amount is in excess of the borrowed
/// amount. Also, this approval only applies to the primary ERC20 token, `TOKEN`.
uint256 internal _APPROVED_AMOUNT_FOR_EXTERNAL_WITHDRAWAL_;
/// @dev Note that this is different from _IS_BORROWING_RESTRICTED_ in LiquidityStakingV1.
bool internal _IS_BORROWING_RESTRICTED_;
/// @dev Mapping from args hash to timestamp.
mapping(bytes32 => uint256) internal _QUEUED_FORCED_TRADE_TIMESTAMPS_;
}
// SPDX-License-Identifier: MIT
pragma solidity 0.7.5;
import './Context.sol';
import './Strings.sol';
import './ERC165.sol';
/**
* @dev External interface of AccessControl declared to support ERC165 detection.
*/
interface IAccessControlUpgradeable {
function hasRole(bytes32 role, address account) external view returns (bool);
function getRoleAdmin(bytes32 role) external view returns (bytes32);
function grantRole(bytes32 role, address account) external;
function revokeRole(bytes32 role, address account) external;
function renounceRole(bytes32 role, address account) external;
}
/**
* @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 AccessControlUpgradeable is Context, IAccessControlUpgradeable, ERC165 {
struct RoleData {
mapping(address => bool) members;
bytes32 adminRole;
}
mapping(bytes32 => RoleData) private _roles;
bytes32 public constant DEFAULT_ADMIN_ROLE = 0x00;
/**
* @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 {_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 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]{20}) is missing role (0x[0-9a-f]{32})$/
*
* _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(IAccessControlUpgradeable).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]{20}) is missing role (0x[0-9a-f]{32})$/
*/
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 {
emit RoleAdminChanged(role, getRoleAdmin(role), adminRole);
_roles[role].adminRole = 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());
}
}
uint256[49] private __gap;
}
// SPDX-License-Identifier: Apache-2.0
pragma solidity 0.7.5;
pragma abicoder v2;
/**
* @title ReentrancyGuard
* @author dYdX
*
* @dev Updated ReentrancyGuard library designed to be used with Proxy Contracts.
*/
abstract contract ReentrancyGuard {
uint256 private constant NOT_ENTERED = 1;
uint256 private constant ENTERED = uint256(int256(-1));
uint256 private _STATUS_;
constructor()
internal
{
_STATUS_ = NOT_ENTERED;
}
modifier nonReentrant() {
require(_STATUS_ != ENTERED, 'ReentrancyGuard: reentrant call');
_STATUS_ = ENTERED;
_;
_STATUS_ = NOT_ENTERED;
}
}
// SPDX-License-Identifier: AGPL-3.0
pragma solidity 0.7.5;
/**
* @title VersionedInitializable
* @author Aave, inspired by the OpenZeppelin Initializable contract
*
* @dev Helper contract to support initializer functions. To use it, replace
* the constructor with a function that has the `initializer` modifier.
* WARNING: Unlike constructors, initializer functions must be manually
* invoked. This applies both to deploying an Initializable contract, as well
* as extending an Initializable contract via inheritance.
* WARNING: When used with inheritance, manual care must be taken to not invoke
* a parent initializer twice, or ensure that all initializers are idempotent,
* because this is not dealt with automatically as with constructors.
*
*/
abstract contract VersionedInitializable {
/**
* @dev Indicates that the contract has been initialized.
*/
uint256 internal lastInitializedRevision = 0;
/**
* @dev Modifier to use in the initializer function of a contract.
*/
modifier initializer() {
uint256 revision = getRevision();
require(revision > lastInitializedRevision, "Contract instance has already been initialized");
lastInitializedRevision = revision;
_;
}
/// @dev returns the revision number of the contract.
/// Needs to be defined in the inherited class as a constant.
function getRevision() internal pure virtual returns(uint256);
// Reserved storage space to allow for layout changes in the future.
uint256[50] private ______gap;
}
// SPDX-License-Identifier: MIT
pragma solidity 0.7.5;
/*
* @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;
}
}
// SPDX-License-Identifier: MIT
pragma solidity 0.7.5;
/**
* @dev String operations.
*/
library Strings {
bytes16 private constant alphabet = '0123456789abcdef';
/**
* @dev Converts a `uint256` to its ASCII `string` decimal representation.
*/
function toString(uint256 value) internal pure returns (string memory) {
// Inspired by OraclizeAPI's implementation - MIT licence
// https://github.com/oraclize/ethereum-api/blob/b42146b063c7d6ee1358846c198246239e9360e8/oraclizeAPI_0.4.25.sol
if (value == 0) {
return '0';
}
uint256 temp = value;
uint256 digits;
while (temp != 0) {
digits++;
temp /= 10;
}
bytes memory buffer = new bytes(digits);
while (value != 0) {
digits -= 1;
buffer[digits] = bytes1(uint8(48 + uint256(value % 10)));
value /= 10;
}
return string(buffer);
}
/**
* @dev Converts a `uint256` to its ASCII `string` hexadecimal representation.
*/
function toHexString(uint256 value) internal pure returns (string memory) {
if (value == 0) {
return '0x00';
}
uint256 temp = value;
uint256 length = 0;
while (temp != 0) {
length++;
temp >>= 8;
}
return toHexString(value, length);
}
/**
* @dev Converts a `uint256` to its ASCII `string` hexadecimal representation with fixed length.
*/
function toHexString(uint256 value, uint256 length) internal pure returns (string memory) {
bytes memory buffer = new bytes(2 * length + 2);
buffer[0] = '0';
buffer[1] = 'x';
for (uint256 i = 2 * length + 1; i > 1; --i) {
buffer[i] = alphabet[value & 0xf];
value >>= 4;
}
require(value == 0, 'Strings: hex length insufficient');
return string(buffer);
}
}
// SPDX-License-Identifier: MIT
pragma solidity 0.7.5;
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.7.5;
/**
* @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: AGPL-3.0
pragma solidity 0.7.5;
pragma abicoder v2;
import { SafeMath } from '../../../dependencies/open-zeppelin/SafeMath.sol';
import { IERC20 } from '../../../interfaces/IERC20.sol';
import { ILiquidityStakingV1 } from '../../../interfaces/ILiquidityStakingV1.sol';
import { Math } from '../../../utils/Math.sol';
import { SP1Balances } from './SP1Balances.sol';
/**
* @title SP1Borrowing
* @author dYdX
*
* @dev Handles calls to the LiquidityStaking contract to borrow and repay funds.
*/
abstract contract SP1Borrowing is
SP1Balances
{
using SafeMath for uint256;
// ============ Events ============
event Borrowed(
uint256 amount,
uint256 newBorrowedBalance
);
event RepaidBorrow(
uint256 amount,
uint256 newBorrowedBalance,
bool isGuardianAction
);
event RepaidDebt(
uint256 amount,
uint256 newDebtBalance,
bool isGuardianAction
);
// ============ Constructor ============
constructor(
ILiquidityStakingV1 liquidityStaking,
IERC20 token
)
SP1Balances(liquidityStaking, token)
{}
// ============ External Functions ============
/**
* @notice Automatically repay or borrow to bring borrowed balance to the next allocated balance.
* Must be called during the blackout window, to ensure allocated balance will not change before
* the start of the next epoch. Reverts if there are insufficient funds to prevent a shortfall.
*
* Can be called with eth_call to view amounts that will be borrowed or repaid.
*
* @return The newly borrowed amount.
* @return The borrow amount repaid.
* @return The debt amount repaid.
*/
function autoPayOrBorrow()
external
nonReentrant
onlyRole(BORROWER_ROLE)
returns (
uint256,
uint256,
uint256
)
{
// Ensure we are in the blackout window.
require(
LIQUIDITY_STAKING.inBlackoutWindow(),
'SP1Borrowing: Auto-pay may only be used during the blackout window'
);
// Get the borrowed balance, next allocated balance, and token balance.
uint256 borrowedBalance = getBorrowedBalance();
uint256 nextAllocatedBalance = getAllocatedBalanceNextEpoch();
uint256 tokenBalance = getTokenBalance();
// Return values.
uint256 borrowAmount = 0;
uint256 repayBorrowAmount = 0;
uint256 repayDebtAmount = 0;
if (borrowedBalance > nextAllocatedBalance) {
// Make the necessary repayment due by the end of the current epoch.
repayBorrowAmount = borrowedBalance.sub(nextAllocatedBalance);
require(
tokenBalance >= repayBorrowAmount,
'SP1Borrowing: Insufficient funds to avoid falling short on repayment'
);
_repayBorrow(repayBorrowAmount, false);
} else {
// Borrow the max borrowable amount.
borrowAmount = getBorrowableAmount();
if (borrowAmount != 0) {
_borrow(borrowAmount);
}
}
// Finally, use remaining funds to pay any overdue debt.
uint256 debtBalance = getDebtBalance();
repayDebtAmount = Math.min(debtBalance, tokenBalance);
if (repayDebtAmount != 0) {
_repayDebt(repayDebtAmount, false);
}
return (borrowAmount, repayBorrowAmount, repayDebtAmount);
}
function borrow(
uint256 amount
)
external
nonReentrant
onlyRole(BORROWER_ROLE)
{
// Disallow if the guardian has restricted borrowing.
require(
!_IS_BORROWING_RESTRICTED_,
'SP1Borrowing: Cannot borrow while Restricted'
);
_borrow(amount);
}
function repayBorrow(
uint256 amount
)
external
nonReentrant
onlyRole(BORROWER_ROLE)
{
_repayBorrow(amount, false);
}
function repayDebt(
uint256 amount
)
external
nonReentrant
onlyRole(BORROWER_ROLE)
{
_repayDebt(amount, false);
}
// ============ Internal Functions ============
function _borrow(
uint256 amount
)
internal
{
LIQUIDITY_STAKING.borrow(amount);
emit Borrowed(amount, getBorrowedBalance());
}
function _repayBorrow(
uint256 amount,
bool isGovernanceAction
)
internal
{
LIQUIDITY_STAKING.repayBorrow(address(this), amount);
emit RepaidBorrow(amount, getBorrowedBalance(), isGovernanceAction);
}
function _repayDebt(
uint256 amount,
bool isGovernanceAction
)
internal
{
LIQUIDITY_STAKING.repayDebt(address(this), amount);
emit RepaidDebt(amount, getDebtBalance(), isGovernanceAction);
}
} | * @notice Guardian method to prevent queued forced trade requests from being executed. May only be called by VETO_GUARDIAN_ROLE. @param argsHashes An array of hashes for each forced trade request to veto./ | function guardianVetoForcedTradeRequests(
bytes32[] calldata argsHashes
)
external
nonReentrant
onlyRole(VETO_GUARDIAN_ROLE)
{
for (uint256 i = 0; i < argsHashes.length; i++) {
bytes32 argsHash = argsHashes[i];
_QUEUED_FORCED_TRADE_TIMESTAMPS_[argsHash] = 0;
emit GuardianVetoedForcedTradeRequest(argsHash);
}
}
| 6,189,875 | [
1,
16709,
2779,
707,
358,
5309,
12234,
13852,
18542,
3285,
628,
3832,
7120,
18,
225,
16734,
1338,
506,
2566,
635,
776,
1584,
51,
67,
30673,
985,
2565,
1258,
67,
16256,
18,
282,
833,
14455,
225,
1922,
526,
434,
9869,
364,
1517,
13852,
18542,
590,
358,
331,
11453,
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
] | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
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,
225,
445,
11026,
2779,
58,
11453,
1290,
3263,
22583,
6421,
12,
203,
565,
1731,
1578,
8526,
745,
892,
833,
14455,
203,
225,
262,
203,
565,
3903,
203,
565,
1661,
426,
8230,
970,
203,
565,
1338,
2996,
12,
58,
1584,
51,
67,
30673,
985,
2565,
1258,
67,
16256,
13,
203,
225,
288,
203,
565,
364,
261,
11890,
5034,
277,
273,
374,
31,
277,
411,
833,
14455,
18,
2469,
31,
277,
27245,
288,
203,
1377,
1731,
1578,
833,
2310,
273,
833,
14455,
63,
77,
15533,
203,
1377,
389,
19533,
40,
67,
7473,
23552,
67,
20060,
1639,
67,
4684,
882,
2192,
5857,
67,
63,
1968,
2310,
65,
273,
374,
31,
203,
1377,
3626,
22809,
2779,
58,
11453,
329,
1290,
3263,
22583,
691,
12,
1968,
2310,
1769,
203,
565,
289,
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
] |
//Address: 0x81481c47639c8e1BbF07E7b1b868B48EE8bBcd23
//Contract name: WisePlatSale
//Balance: 0 Ether
//Verification Date: 10/21/2017
//Transacion Count: 13
// CODE STARTS HERE
pragma solidity ^0.4.16;
/**
* @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 {
if (newOwner != address(0)) {
owner = newOwner;
}
}
}
/**
* @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 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 Basic token
* @dev Basic version of StandardToken, with no allowances.
*/
contract BasicToken is ERC20Basic {
using SafeMath for uint256;
mapping(address => uint256) balances;
/**
* @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) returns (bool) {
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) constant returns (uint256 balance) {
return balances[_owner];
}
}
/**
* @title ERC20 interface
* @dev see https://github.com/ethereum/EIPs/issues/20
*/
contract ERC20 is ERC20Basic {
function allowance(address owner, address spender) 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);
}
contract StandardToken is ERC20, BasicToken {
mapping (address => mapping (address => uint256)) 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 amout of tokens to be transfered
*/
function transferFrom(address _from, address _to, uint256 _value) returns (bool) {
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[_to] = balances[_to].add(_value);
balances[_from] = balances[_from].sub(_value);
allowed[_from][msg.sender] = _allowance.sub(_value);
Transfer(_from, _to, _value);
return true;
}
/**
* @dev Aprove the passed address to spend the specified amount of tokens on behalf of msg.sender.
* @param _spender The address which will spend the funds.
* @param _value The amount of tokens to be spent.
*/
function approve(address _spender, uint256 _value) returns (bool) {
// 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;
}
/**
* @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 specifing the amount of tokens still avaible for the spender.
*/
function allowance(address _owner, address _spender) constant returns (uint256 remaining) {
return allowed[_owner][_spender];
}
}
contract MintableToken is StandardToken, Ownable {
event MintFinished();
bool public mintingFinished = false;
modifier canMint() {
require(!mintingFinished);
_;
}
/**
* @dev Function to mint tokens
* @param _to The address that will recieve 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 returns (bool) {
totalSupply = totalSupply.add(_amount);
balances[_to] = balances[_to].add(_amount);
Transfer(0X0, _to, _amount);
return true;
}
/**
* @dev Function to stop minting new tokens.
* @return True if the operation was successful.
*/
function finishMinting() onlyOwner returns (bool) {
mintingFinished = true;
MintFinished();
return true;
}
}
contract WisePlat is MintableToken {
string public name = "WisePlat Token";
string public symbol = "WISE";
uint256 public decimals = 18;
address public bountyWallet = 0x0;
bool public transferStatus = false;
/**
* @dev modifier that throws if trading has not started yet
*/
modifier hasStartedTransfer() {
require(transferStatus || msg.sender == bountyWallet);
_;
}
/**
* @dev Allows the owner to enable transfer.
*/
function startTransfer() public onlyOwner {
transferStatus = true;
}
/**
* @dev Allows the owner to stop transfer.
*/
function stopTransfer() public onlyOwner {
transferStatus = false;
}
function setbountyWallet(address _bountyWallet) public onlyOwner {
bountyWallet = _bountyWallet;
}
/**
* @dev Allows anyone to transfer the WISE tokens once transfer has started
* @param _to the recipient address of the tokens.
* @param _value number of tokens to be transfered.
*/
function transfer(address _to, uint _value) hasStartedTransfer returns (bool){
return super.transfer(_to, _value);
}
/**
* @dev Allows anyone to transfer the WISE tokens once transfer has started
* @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 uint the amout of tokens to be transfered
*/
function transferFrom(address _from, address _to, uint _value) hasStartedTransfer returns (bool){
return super.transferFrom(_from, _to, _value);
}
}
contract WisePlatSale is Ownable {
using SafeMath for uint256;
// The token being offered
WisePlat public token;
// start and end block where investments are allowed (both inclusive)
uint256 public constant startTimestamp = 1509274800; //Pre-ICO start 2017/10/29 @ 11:00:00 (UTC)
uint256 public constant middleTimestamp = 1511607601; //Pre-ICO finish and ICO start 2017/11/25 @ 11:00:01 (UTC)
uint256 public constant endTimestamp = 1514764799; //ICO finish 2017/12/31 @ 23:59:59 (UTC)
// address where funds are collected
address public constant devWallet = 0x00d6F1eA4238e8d9f1C33B7500CB89EF3e91190c;
address public constant proWallet = 0x6501BDA688e8AC6C9cD96dc2DFBd6bDF3e886C05;
address public constant bountyWallet = 0x354FFa86F138883b880C282000B5005E867E8eE4;
address public constant remainderWallet = 0x656C64D5C8BADe2a56A564B12706eE89bbe486EA;
address public constant fundsWallet = 0x06D49e8aA90b1413A641D69c6B8AC154f5c9FE92;
// how many token units a buyer gets per wei
uint256 public rate = 10;
uint256 public constant ratePreICO = 20; //on Pre-ICO it is 20 WISE for 1 ETH
uint256 public constant rateICO = 15; //on ICO it is 15 WISE for 1 ETH
// amount of raised money in wei
uint256 public weiRaised;
// minimum contribution to participate in token offer
uint256 public constant minContribution = 0.1 ether;
uint256 public constant minContribution_mBTC = 10;
uint256 public rateBTCxETH = 17;
// WISE tokens
uint256 public constant tokensTotal = 10000000 * 1e18; //WISE Total tokens 10,000,000.00
uint256 public constant tokensCrowdsale = 7000000 * 1e18; //WISE tokens for Crowdsale 7,000,000.00
uint256 public constant tokensDevelopers = 1900000 * 1e18; //WISE tokens for Developers 1,900,000.00
uint256 public constant tokensPromotion = 1000000 * 1e18; //WISE tokens for Promotion 1,000,000.00
uint256 public constant tokensBounty = 100000 * 1e18; //WISE tokens for Bounty 100,000.00
uint256 public tokensRemainder;
event TokenPurchase(address indexed purchaser, address indexed beneficiary, uint256 value, uint256 amount);
event TokenClaim4BTC(address indexed purchaser_evt, address indexed beneficiary_evt, uint256 value_evt, uint256 amount_evt, uint256 btc_evt, uint256 rateBTCxETH_evt);
event SaleClosed();
function WisePlatSale() {
token = new WisePlat();
token.mint(devWallet, tokensDevelopers);
token.mint(proWallet, tokensPromotion);
token.mint(bountyWallet, tokensBounty);
token.setbountyWallet(bountyWallet); //allow transfer for bountyWallet
require(startTimestamp >= now);
require(endTimestamp >= startTimestamp);
}
// check if valid purchase
modifier validPurchase {
require(now >= startTimestamp);
require(now <= endTimestamp);
require(msg.value >= minContribution);
require(tokensTotal > token.totalSupply());
_;
}
// check if valid claim for BTC
modifier validPurchase4BTC {
require(now >= startTimestamp);
require(now <= endTimestamp);
require(tokensTotal > token.totalSupply());
_;
}
// @return true if crowdsale event has ended
function hasEnded() public constant returns (bool) {
bool timeLimitReached = now > endTimestamp;
bool allOffered = tokensTotal <= token.totalSupply();
return timeLimitReached || allOffered;
}
// low level token purchase function
function buyTokens(address beneficiary) payable validPurchase {
require(beneficiary != 0x0);
uint256 weiAmount = msg.value;
// calculate token amount to be created
if (now < middleTimestamp) {rate = ratePreICO;} else {rate = rateICO;}
uint256 tokens = weiAmount.mul(rate);
require(token.totalSupply().add(tokens) <= tokensTotal);
// update state
weiRaised = weiRaised.add(weiAmount);
token.mint(beneficiary, tokens);
TokenPurchase(msg.sender, beneficiary, weiAmount, tokens);
fundsWallet.transfer(msg.value); //transfer funds to fundsWallet
}
//claim tokens buyed for mBTC
function claimTokens4mBTC(address beneficiary, uint256 mBTC) validPurchase4BTC public onlyOwner {
require(beneficiary != 0x0);
require(mBTC >= minContribution_mBTC);
//uint256 _BTC = mBTC.div(1000); //convert mBTC to BTC
//uint256 _ETH = _BTC.mul(rateBTCxETH); //convert BTC to ETH
//uint256 weiAmount = _ETH * 1e18; //convert ETH to wei
uint256 weiAmount = mBTC.mul(rateBTCxETH) * 1e15; //all convert in one line mBTC->BTC->ETH->wei
// calculate token amount to be created
if (now < middleTimestamp) {rate = ratePreICO;} else {rate = rateICO;}
uint256 tokens = weiAmount.mul(rate);
require(token.totalSupply().add(tokens) <= tokensTotal);
// update state
weiRaised = weiRaised.add(weiAmount);
token.mint(beneficiary, tokens);
TokenClaim4BTC(msg.sender, beneficiary, weiAmount, tokens, mBTC, rateBTCxETH);
//fundsWallet.transfer(msg.value); //transfer funds to fundsWallet - already should be transfered to BTC wallet
}
// to enable transfer
function startTransfers() public onlyOwner {
token.startTransfer();
}
// to stop transfer
function stopTransfers() public onlyOwner {
token.stopTransfer();
}
// to correct exchange rate ETH for BTC
function correctExchangeRateBTCxETH(uint256 _rateBTCxETH) public onlyOwner {
require(_rateBTCxETH != 0);
rateBTCxETH = _rateBTCxETH;
}
// finish mining coins and transfer ownership of WISE token to owner
function finishMinting() public onlyOwner {
require(hasEnded());
uint issuedTokenSupply = token.totalSupply();
tokensRemainder = tokensTotal.sub(issuedTokenSupply);
if (tokensRemainder > 0) {token.mint(remainderWallet, tokensRemainder);}
token.finishMinting();
token.transferOwnership(owner);
SaleClosed();
}
// fallback function can be used to buy tokens
function () payable {
buyTokens(msg.sender);
}
/**
* @dev Reclaim all ERC20Basic compatible tokens
* @param tokenAddr address The address of the token contract
*/
function reclaimToken(address tokenAddr) external onlyOwner {
require(!isTokenOfferedToken(tokenAddr));
ERC20Basic tokenInst = ERC20Basic(tokenAddr);
uint256 balance = tokenInst.balanceOf(this);
tokenInst.transfer(msg.sender, balance);
}
function isTokenOfferedToken(address tokenAddr) returns(bool) {
return token == tokenAddr;
}
}
| * @dev modifier that throws if trading has not started yet/ | modifier hasStartedTransfer() {
require(transferStatus || msg.sender == bountyWallet);
_;
}
| 14,067,261 | [
1,
20597,
716,
1216,
309,
1284,
7459,
711,
486,
5746,
4671,
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
] | [
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,
225,
9606,
711,
9217,
5912,
1435,
288,
203,
565,
2583,
12,
13866,
1482,
747,
1234,
18,
15330,
422,
324,
592,
93,
16936,
1769,
203,
565,
389,
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
] |
./full_match/42/0x4Efb8892f6f20aDB6C3da1786CFB1A6aFd198bd7/sources/Users/dror/IdeaProjects/gsn-release/contracts/Migrations.sol | solhint-disable-next-line var-name-mixedcase | contract Migrations {
address public owner;
uint public last_completed_migration;
pragma solidity ^0.7.5;
constructor() {
owner = msg.sender;
}
modifier restricted() {
if (msg.sender == owner) _;
}
function setCompleted(uint completed) public restricted {
last_completed_migration = completed;
}
function upgrade(address newAddress) public restricted {
Migrations upgraded = Migrations(newAddress);
upgraded.setCompleted(last_completed_migration);
}
}
| 16,204,355 | [
1,
18281,
11317,
17,
8394,
17,
4285,
17,
1369,
569,
17,
529,
17,
19562,
3593,
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,
490,
10475,
288,
203,
565,
1758,
1071,
3410,
31,
203,
565,
2254,
1071,
1142,
67,
13615,
67,
15746,
31,
203,
203,
683,
9454,
18035,
560,
3602,
20,
18,
27,
18,
25,
31,
203,
565,
3885,
1435,
288,
203,
3639,
3410,
273,
1234,
18,
15330,
31,
203,
565,
289,
203,
203,
565,
9606,
15693,
1435,
288,
203,
3639,
309,
261,
3576,
18,
15330,
422,
3410,
13,
389,
31,
203,
565,
289,
203,
203,
565,
445,
444,
9556,
12,
11890,
5951,
13,
1071,
15693,
288,
203,
3639,
1142,
67,
13615,
67,
15746,
273,
5951,
31,
203,
565,
289,
203,
203,
565,
445,
8400,
12,
2867,
394,
1887,
13,
1071,
15693,
288,
203,
3639,
490,
10475,
31049,
273,
490,
10475,
12,
2704,
1887,
1769,
203,
3639,
31049,
18,
542,
9556,
12,
2722,
67,
13615,
67,
15746,
1769,
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
] |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.