contract_name
stringlengths 1
238
| contract_address
stringlengths 42
42
| language
stringclasses 2
values | source_code
stringlengths 197
770k
| abi
stringlengths 2
43.6k
| compiler_version
stringclasses 198
values | optimization_used
bool 2
classes | runs
int64 0
100M
| constructor_arguments
stringlengths 0
85.2k
| evm_version
stringclasses 10
values | library
stringclasses 172
values | license_type
stringclasses 16
values | proxy
bool 2
classes | implementation
stringlengths 0
42
| swarm_source
stringlengths 0
71
|
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
Forwarder
|
0x7fdeb3669c31bdd2450e7147e0aef71a9ec80569
|
Solidity
|
pragma solidity ^0.4.14;
/**
* Contract that exposes the needed erc20 token functions
*/
contract ERC20Interface {
// Send _value amount of tokens to address _to
function transfer(address _to, uint256 _value) returns (bool success);
// Get the account balance of another account with address _owner
function balanceOf(address _owner) constant returns (uint256 balance);
}
/**
* Contract that will forward any incoming Ether to its creator
*/
contract Forwarder {
// Address to which any funds sent to this contract will be forwarded
address public parentAddress;
event ForwarderDeposited(address from, uint value, bytes data);
event TokensFlushed(
address tokenContractAddress, // The contract address of the token
uint value // Amount of token sent
);
/**
* Create the contract, and set the destination address to that of the creator
*/
function Forwarder() {
parentAddress = msg.sender;
}
/**
* Modifier that will execute internal code block only if the sender is a parent of the forwarder contract
*/
modifier onlyParent {
if (msg.sender != parentAddress) {
throw;
}
_;
}
/**
* Default function; Gets called when Ether is deposited, and forwards it to the destination address
*/
function() payable {
if (!parentAddress.call.value(msg.value)(msg.data))
throw;
// Fire off the deposited event if we can forward it
ForwarderDeposited(msg.sender, msg.value, msg.data);
}
/**
* Execute a token transfer of the full balance from the forwarder token to the main wallet contract
* @param tokenContractAddress the address of the erc20 token contract
*/
function flushTokens(address tokenContractAddress) onlyParent {
ERC20Interface instance = ERC20Interface(tokenContractAddress);
var forwarderAddress = address(this);
var forwarderBalance = instance.balanceOf(forwarderAddress);
if (forwarderBalance == 0) {
return;
}
if (!instance.transfer(parentAddress, forwarderBalance)) {
throw;
}
TokensFlushed(tokenContractAddress, forwarderBalance);
}
/**
* It is possible that funds were sent to this address before the contract was deployed.
* We can flush those funds to the destination address.
*/
function flush() {
if (!parentAddress.call.value(this.balance)())
throw;
}
}
/**
* Basic multi-signer wallet designed for use in a co-signing environment where 2 signatures are required to move funds.
* Typically used in a 2-of-3 signing configuration. Uses ecrecover to allow for 2 signatures in a single transaction.
*/
contract WalletSimple {
// Events
event Deposited(address from, uint value, bytes data);
event SafeModeActivated(address msgSender);
event Transacted(
address msgSender, // Address of the sender of the message initiating the transaction
address otherSigner, // Address of the signer (second signature) used to initiate the transaction
bytes32 operation, // Operation hash (sha3 of toAddress, value, data, expireTime, sequenceId)
address toAddress, // The address the transaction was sent to
uint value, // Amount of Wei sent to the address
bytes data // Data sent when invoking the transaction
);
event TokenTransacted(
address msgSender, // Address of the sender of the message initiating the transaction
address otherSigner, // Address of the signer (second signature) used to initiate the transaction
bytes32 operation, // Operation hash (sha3 of toAddress, value, tokenContractAddress, expireTime, sequenceId)
address toAddress, // The address the transaction was sent to
uint value, // Amount of token sent
address tokenContractAddress // The contract address of the token
);
// Public fields
address[] public signers; // The addresses that can co-sign transactions on the wallet
bool public safeMode = false; // When active, wallet may only send to signer addresses
// Internal fields
uint constant SEQUENCE_ID_WINDOW_SIZE = 10;
uint[10] recentSequenceIds;
/**
* Modifier that will execute internal code block only if the sender is an authorized signer on this wallet
*/
modifier onlysigner {
if (!isSigner(msg.sender)) {
throw;
}
_;
}
/**
* Set up a simple multi-sig wallet by specifying the signers allowed to be used on this wallet.
* 2 signers will be required to send a transaction from this wallet.
* Note: The sender is NOT automatically added to the list of signers.
* Signers CANNOT be changed once they are set
*
* @param allowedSigners An array of signers on the wallet
*/
function WalletSimple(address[] allowedSigners) {
if (allowedSigners.length != 3) {
// Invalid number of signers
throw;
}
signers = allowedSigners;
}
/**
* Gets called when a transaction is received without calling a method
*/
function() payable {
if (msg.value > 0) {
// Fire deposited event if we are receiving funds
Deposited(msg.sender, msg.value, msg.data);
}
}
/**
* Create a new contract (and also address) that forwards funds to this contract
* returns address of newly created forwarder address
*/
function createForwarder() onlysigner returns (address) {
return new Forwarder();
}
/**
* Execute a multi-signature transaction from this wallet using 2 signers: one from msg.sender and the other from ecrecover.
* The signature is a signed form (using eth.sign) of tightly packed toAddress, value, data, expireTime and sequenceId
* Sequence IDs are numbers starting from 1. They are used to prevent replay attacks and may not be repeated.
*
* @param toAddress the destination address to send an outgoing transaction
* @param value the amount in Wei to be sent
* @param data the data to send to the toAddress when invoking the transaction
* @param expireTime the number of seconds since 1970 for which this transaction is valid
* @param sequenceId the unique sequence id obtainable from getNextSequenceId
* @param signature the result of eth.sign on the operationHash sha3(toAddress, value, data, expireTime, sequenceId)
*/
function sendMultiSig(address toAddress, uint value, bytes data, uint expireTime, uint sequenceId, bytes signature) onlysigner {
// Verify the other signer
var operationHash = sha3("ETHER", toAddress, value, data, expireTime, sequenceId);
var otherSigner = verifyMultiSig(toAddress, operationHash, signature, expireTime, sequenceId);
// Success, send the transaction
if (!(toAddress.call.value(value)(data))) {
// Failed executing transaction
throw;
}
Transacted(msg.sender, otherSigner, operationHash, toAddress, value, data);
}
/**
* Execute a multi-signature token transfer from this wallet using 2 signers: one from msg.sender and the other from ecrecover.
* The signature is a signed form (using eth.sign) of tightly packed toAddress, value, tokenContractAddress, expireTime and sequenceId
* Sequence IDs are numbers starting from 1. They are used to prevent replay attacks and may not be repeated.
*
* @param toAddress the destination address to send an outgoing transaction
* @param value the amount in tokens to be sent
* @param tokenContractAddress the address of the erc20 token contract
* @param expireTime the number of seconds since 1970 for which this transaction is valid
* @param sequenceId the unique sequence id obtainable from getNextSequenceId
* @param signature the result of eth.sign on the operationHash sha3(toAddress, value, tokenContractAddress, expireTime, sequenceId)
*/
function sendMultiSigToken(address toAddress, uint value, address tokenContractAddress, uint expireTime, uint sequenceId, bytes signature) onlysigner {
// Verify the other signer
var operationHash = sha3("ERC20", toAddress, value, tokenContractAddress, expireTime, sequenceId);
var otherSigner = verifyMultiSig(toAddress, operationHash, signature, expireTime, sequenceId);
ERC20Interface instance = ERC20Interface(tokenContractAddress);
if (!instance.transfer(toAddress, value)) {
throw;
}
TokenTransacted(msg.sender, otherSigner, operationHash, toAddress, value, tokenContractAddress);
}
/**
* Execute a token flush from one of the forwarder addresses. This transfer needs only a single signature and can be done by any signer
*
* @param forwarderAddress the address of the forwarder address to flush the tokens from
* @param tokenContractAddress the address of the erc20 token contract
*/
function flushForwarderTokens(address forwarderAddress, address tokenContractAddress) onlysigner {
Forwarder forwarder = Forwarder(forwarderAddress);
forwarder.flushTokens(tokenContractAddress);
}
/**
* Do common multisig verification for both eth sends and erc20token transfers
*
* @param toAddress the destination address to send an outgoing transaction
* @param operationHash the sha3 of the toAddress, value, data/tokenContractAddress and expireTime
* @param signature the tightly packed signature of r, s, and v as an array of 65 bytes (returned by eth.sign)
* @param expireTime the number of seconds since 1970 for which this transaction is valid
* @param sequenceId the unique sequence id obtainable from getNextSequenceId
* returns address of the address to send tokens or eth to
*/
function verifyMultiSig(address toAddress, bytes32 operationHash, bytes signature, uint expireTime, uint sequenceId) private returns (address) {
var otherSigner = recoverAddressFromSignature(operationHash, signature);
// Verify if we are in safe mode. In safe mode, the wallet can only send to signers
if (safeMode && !isSigner(toAddress)) {
// We are in safe mode and the toAddress is not a signer. Disallow!
throw;
}
// Verify that the transaction has not expired
if (expireTime < block.timestamp) {
// Transaction expired
throw;
}
// Try to insert the sequence ID. Will throw if the sequence id was invalid
tryInsertSequenceId(sequenceId);
if (!isSigner(otherSigner)) {
// Other signer not on this wallet or operation does not match arguments
throw;
}
if (otherSigner == msg.sender) {
// Cannot approve own transaction
throw;
}
return otherSigner;
}
/**
* Irrevocably puts contract into safe mode. When in this mode, transactions may only be sent to signing addresses.
*/
function activateSafeMode() onlysigner {
safeMode = true;
SafeModeActivated(msg.sender);
}
/**
* Determine if an address is a signer on this wallet
* @param signer address to check
* returns boolean indicating whether address is signer or not
*/
function isSigner(address signer) returns (bool) {
// Iterate through all signers on the wallet and
for (uint i = 0; i < signers.length; i++) {
if (signers[i] == signer) {
return true;
}
}
return false;
}
/**
* Gets the second signer's address using ecrecover
* @param operationHash the sha3 of the toAddress, value, data/tokenContractAddress and expireTime
* @param signature the tightly packed signature of r, s, and v as an array of 65 bytes (returned by eth.sign)
* returns address recovered from the signature
*/
function recoverAddressFromSignature(bytes32 operationHash, bytes signature) private returns (address) {
if (signature.length != 65) {
throw;
}
// We need to unpack the signature, which is given as an array of 65 bytes (from eth.sign)
bytes32 r;
bytes32 s;
uint8 v;
assembly {
r := mload(add(signature, 32))
s := mload(add(signature, 64))
v := and(mload(add(signature, 65)), 255)
}
if (v < 27) {
v += 27; // Ethereum versions are 27 or 28 as opposed to 0 or 1 which is submitted by some signing libs
}
return ecrecover(operationHash, v, r, s);
}
/**
* Verify that the sequence id has not been used before and inserts it. Throws if the sequence ID was not accepted.
* We collect a window of up to 10 recent sequence ids, and allow any sequence id that is not in the window and
* greater than the minimum element in the window.
* @param sequenceId to insert into array of stored ids
*/
function tryInsertSequenceId(uint sequenceId) onlysigner private {
// Keep a pointer to the lowest value element in the window
uint lowestValueIndex = 0;
for (uint i = 0; i < SEQUENCE_ID_WINDOW_SIZE; i++) {
if (recentSequenceIds[i] == sequenceId) {
// This sequence ID has been used before. Disallow!
throw;
}
if (recentSequenceIds[i] < recentSequenceIds[lowestValueIndex]) {
lowestValueIndex = i;
}
}
if (sequenceId < recentSequenceIds[lowestValueIndex]) {
// The sequence ID being used is lower than the lowest value in the window
// so we cannot accept it as it may have been used before
throw;
}
if (sequenceId > (recentSequenceIds[lowestValueIndex] + 10000)) {
// Block sequence IDs which are much higher than the lowest value
// This prevents people blocking the contract by using very large sequence IDs quickly
throw;
}
recentSequenceIds[lowestValueIndex] = sequenceId;
}
/**
* Gets the next available sequence ID for signing when using executeAndConfirm
* returns the sequenceId one higher than the highest currently stored
*/
function getNextSequenceId() returns (uint) {
uint highestSequenceId = 0;
for (uint i = 0; i < SEQUENCE_ID_WINDOW_SIZE; i++) {
if (recentSequenceIds[i] > highestSequenceId) {
highestSequenceId = recentSequenceIds[i];
}
}
return highestSequenceId + 1;
}
}
|
[{"constant":true,"inputs":[],"name":"parentAddress","outputs":[{"name":"","type":"address"}],"payable":false,"type":"function"},{"constant":false,"inputs":[{"name":"tokenContractAddress","type":"address"}],"name":"flushTokens","outputs":[],"payable":false,"type":"function"},{"constant":false,"inputs":[],"name":"flush","outputs":[],"payable":false,"type":"function"},{"inputs":[],"payable":false,"type":"constructor"},{"payable":true,"type":"fallback"},{"anonymous":false,"inputs":[{"indexed":false,"name":"from","type":"address"},{"indexed":false,"name":"value","type":"uint256"},{"indexed":false,"name":"data","type":"bytes"}],"name":"ForwarderDeposited","type":"event"},{"anonymous":false,"inputs":[{"indexed":false,"name":"tokenContractAddress","type":"address"},{"indexed":false,"name":"value","type":"uint256"}],"name":"TokensFlushed","type":"event"}]
|
v0.4.16-nightly.2017.8.11+commit.c84de7fa
| true
| 200
|
Default
| false
|
bzzr://d0f8838ba17108a895d34ae8ef3bff4e0dc9d639c3c51921fee1d17eaa803721
|
||||
UserWallet
|
0x01028e48006959f28c08a039d65d1c6f80abcf9f
|
Solidity
|
pragma solidity ^0.4.10;
// Copyright 2017 Bittrex
contract AbstractSweeper {
function sweep(address token, uint amount) returns (bool);
function () { throw; }
Controller controller;
function AbstractSweeper(address _controller) {
controller = Controller(_controller);
}
modifier canSweep() {
if (msg.sender != controller.authorizedCaller() && msg.sender != controller.owner()) throw;
if (controller.halted()) throw;
_;
}
}
contract Token {
function balanceOf(address a) returns (uint) {
(a);
return 0;
}
function transfer(address a, uint val) returns (bool) {
(a);
(val);
return false;
}
}
contract DefaultSweeper is AbstractSweeper {
function DefaultSweeper(address controller)
AbstractSweeper(controller) {}
function sweep(address _token, uint _amount)
canSweep
returns (bool) {
bool success = false;
address destination = controller.destination();
if (_token != address(0)) {
Token token = Token(_token);
uint amount = _amount;
if (amount > token.balanceOf(this)) {
return false;
}
success = token.transfer(destination, amount);
}
else {
uint amountInWei = _amount;
if (amountInWei > this.balance) {
return false;
}
success = destination.send(amountInWei);
}
if (success) {
controller.logSweep(this, destination, _token, _amount);
}
return success;
}
}
contract UserWallet {
AbstractSweeperList sweeperList;
function UserWallet(address _sweeperlist) {
sweeperList = AbstractSweeperList(_sweeperlist);
}
function () public payable { }
function tokenFallback(address _from, uint _value, bytes _data) {
(_from);
(_value);
(_data);
}
function sweep(address _token, uint _amount)
returns (bool) {
(_amount);
return sweeperList.sweeperOf(_token).delegatecall(msg.data);
}
}
contract AbstractSweeperList {
function sweeperOf(address _token) returns (address);
}
contract Controller is AbstractSweeperList {
address public owner;
address public authorizedCaller;
address public destination;
bool public halted;
event LogNewWallet(address receiver);
event LogSweep(address indexed from, address indexed to, address indexed token, uint amount);
modifier onlyOwner() {
if (msg.sender != owner) throw;
_;
}
modifier onlyAuthorizedCaller() {
if (msg.sender != authorizedCaller) throw;
_;
}
modifier onlyAdmins() {
if (msg.sender != authorizedCaller && msg.sender != owner) throw;
_;
}
function Controller()
{
owner = msg.sender;
destination = msg.sender;
authorizedCaller = msg.sender;
}
function changeAuthorizedCaller(address _newCaller) onlyOwner {
authorizedCaller = _newCaller;
}
function changeDestination(address _dest) onlyOwner {
destination = _dest;
}
function changeOwner(address _owner) onlyOwner {
owner = _owner;
}
function makeWallet() onlyAdmins returns (address wallet) {
wallet = address(new UserWallet(this));
LogNewWallet(wallet);
}
function halt() onlyAdmins {
halted = true;
}
function start() onlyOwner {
halted = false;
}
address public defaultSweeper = address(new DefaultSweeper(this));
mapping (address => address) sweepers;
function addSweeper(address _token, address _sweeper) onlyOwner {
sweepers[_token] = _sweeper;
}
function sweeperOf(address _token) returns (address) {
address sweeper = sweepers[_token];
if (sweeper == 0) sweeper = defaultSweeper;
return sweeper;
}
function logSweep(address from, address to, address token, uint amount) {
LogSweep(from, to, token, amount);
}
}
|
[{"constant":false,"inputs":[{"name":"_token","type":"address"},{"name":"_amount","type":"uint256"}],"name":"sweep","outputs":[{"name":"","type":"bool"}],"payable":false,"type":"function"},{"constant":false,"inputs":[{"name":"_from","type":"address"},{"name":"_value","type":"uint256"},{"name":"_data","type":"bytes"}],"name":"tokenFallback","outputs":[],"payable":false,"type":"function"},{"inputs":[{"name":"_sweeperlist","type":"address"}],"payable":false,"type":"constructor"},{"payable":true,"type":"fallback"}]
|
v0.4.11+commit.68ef5810
| true
| 200
|
000000000000000000000000a3C1E324CA1ce40db73eD6026c4A177F099B5770
|
Default
| false
|
bzzr://4cdd69fdcf3cf6cbee9677fe380fa5f044048aa9e060ec5619a21ca5a5bd4cd1
|
|||
BondedECDSAKeep
|
0x61935dc4ffc5c5f1d141ac060c0eef04a792d8ee
|
Solidity
|
// File: solidity/contracts/BondedECDSAKeep.sol
/**
▓▓▌ ▓▓ ▐▓▓ ▓▓▓▓▓▓▓▓▓▓▌▐▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓ ▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓ ▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▄
▓▓▓▓▓▓▓▓▓▓ ▓▓▓▓▓▓▓▓▓▓▌▐▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓ ▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓ ▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓
▓▓▓▓▓▓ ▓▓▓▓▓▓▓▀ ▐▓▓▓▓▓▓ ▐▓▓▓▓▓ ▓▓▓▓▓▓ ▓▓▓▓▓ ▐▓▓▓▓▓▌ ▐▓▓▓▓▓▓
▓▓▓▓▓▓▄▄▓▓▓▓▓▓▓▀ ▐▓▓▓▓▓▓▄▄▄▄ ▓▓▓▓▓▓▄▄▄▄ ▐▓▓▓▓▓▌ ▐▓▓▓▓▓▓
▓▓▓▓▓▓▓▓▓▓▓▓▓▀ ▐▓▓▓▓▓▓▓▓▓▓ ▓▓▓▓▓▓▓▓▓▓▌ ▐▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓
▓▓▓▓▓▓▀▀▓▓▓▓▓▓▄ ▐▓▓▓▓▓▓▀▀▀▀ ▓▓▓▓▓▓▀▀▀▀ ▐▓▓▓▓▓▓▓▓▓▓▓▓▓▓▀
▓▓▓▓▓▓ ▀▓▓▓▓▓▓▄ ▐▓▓▓▓▓▓ ▓▓▓▓▓ ▓▓▓▓▓▓ ▓▓▓▓▓ ▐▓▓▓▓▓▌
▓▓▓▓▓▓▓▓▓▓ █▓▓▓▓▓▓▓▓▓ ▐▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓ ▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓ ▓▓▓▓▓▓▓▓▓▓
▓▓▓▓▓▓▓▓▓▓ ▓▓▓▓▓▓▓▓▓▓ ▐▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓ ▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓ ▓▓▓▓▓▓▓▓▓▓
Trust math, not hardware.
*/
pragma solidity 0.5.17;
import "./AbstractBondedECDSAKeep.sol";
import "./BondedECDSAKeepFactory.sol";
import "@keep-network/keep-core/contracts/TokenStaking.sol";
/// @title Bonded ECDSA Keep
/// @notice ECDSA keep with additional signer bond requirement.
/// @dev This contract is used as a master contract for clone factory in
/// BondedECDSAKeepFactory as per EIP-1167. It should never be removed after
/// initial deployment as this will break functionality for all created clones.
contract BondedECDSAKeep is AbstractBondedECDSAKeep {
// Stake that was required from each keep member on keep creation.
// The value is used for keep members slashing.
uint256 public memberStake;
// Emitted when KEEP token slashing failed when submitting signature
// fraud proof. In practice, this situation should never happen but we want
// to be very explicit in this contract and protect the owner that even if
// it happens, the transaction submitting fraud proof is not going to fail
// and keep owner can seize and liquidate bonds in the same transaction.
event SlashingFailed();
TokenStaking tokenStaking;
/// @notice Initialization function.
/// @dev We use clone factory to create new keep. That is why this contract
/// doesn't have a constructor. We provide keep parameters for each instance
/// function after cloning instances from the master contract.
/// @param _owner Address of the keep owner.
/// @param _members Addresses of the keep members.
/// @param _honestThreshold Minimum number of honest keep members.
/// @param _memberStake Stake required from each keep member.
/// @param _stakeLockDuration Stake lock duration in seconds.
/// @param _tokenStaking Address of the TokenStaking contract.
/// @param _keepBonding Address of the KeepBonding contract.
/// @param _keepFactory Address of the BondedECDSAKeepFactory that created
/// this keep.
function initialize(
address _owner,
address[] memory _members,
uint256 _honestThreshold,
uint256 _memberStake,
uint256 _stakeLockDuration,
address _tokenStaking,
address _keepBonding,
address payable _keepFactory
) public {
super.initialize(_owner, _members, _honestThreshold, _keepBonding);
memberStake = _memberStake;
tokenStaking = TokenStaking(_tokenStaking);
tokenStaking.claimDelegatedAuthority(_keepFactory);
lockMemberStakes(_stakeLockDuration);
}
/// @notice Closes keep when owner decides that they no longer need it.
/// Releases bonds to the keep members. Keep can be closed only when
/// there is no signing in progress or requested signing process has timed out.
/// @dev The function can be called only by the owner of the keep and only
/// if the keep has not been already closed.
function closeKeep() public onlyOwner onlyWhenActive {
super.closeKeep();
unlockMemberStakes();
}
/// @notice Terminates the keep.
function terminateKeep() internal {
super.terminateKeep();
unlockMemberStakes();
}
function slashForSignatureFraud() internal {
/* solium-disable-next-line */
(bool success, ) = address(tokenStaking).call(
abi.encodeWithSignature(
"slash(uint256,address[])",
memberStake,
members
)
);
// Should never happen but we want to protect the owner and make sure the
// fraud submission transaction does not fail so that the owner can
// seize and liquidate bonds in the same transaction.
if (!success) {
emit SlashingFailed();
}
}
/// @notice Creates locks on members' token stakes.
/// @param _stakeLockDuration Stake lock duration in seconds.
function lockMemberStakes(uint256 _stakeLockDuration) internal {
for (uint256 i = 0; i < members.length; i++) {
tokenStaking.lockStake(members[i], _stakeLockDuration);
}
}
/// @notice Releases locks the keep had previously placed on the members'
/// token stakes.
function unlockMemberStakes() internal {
for (uint256 i = 0; i < members.length; i++) {
tokenStaking.unlockStake(members[i]);
}
}
/// @notice Gets the beneficiary for the specified member address.
/// @param _member Member address.
/// @return Beneficiary address.
function beneficiaryOf(address _member)
internal
view
returns (address payable)
{
return tokenStaking.beneficiaryOf(_member);
}
}
// File: solidity/contracts/api/IBondedECDSAKeep.sol
/**
▓▓▌ ▓▓ ▐▓▓ ▓▓▓▓▓▓▓▓▓▓▌▐▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓ ▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓ ▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▄
▓▓▓▓▓▓▓▓▓▓ ▓▓▓▓▓▓▓▓▓▓▌▐▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓ ▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓ ▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓
▓▓▓▓▓▓ ▓▓▓▓▓▓▓▀ ▐▓▓▓▓▓▓ ▐▓▓▓▓▓ ▓▓▓▓▓▓ ▓▓▓▓▓ ▐▓▓▓▓▓▌ ▐▓▓▓▓▓▓
▓▓▓▓▓▓▄▄▓▓▓▓▓▓▓▀ ▐▓▓▓▓▓▓▄▄▄▄ ▓▓▓▓▓▓▄▄▄▄ ▐▓▓▓▓▓▌ ▐▓▓▓▓▓▓
▓▓▓▓▓▓▓▓▓▓▓▓▓▀ ▐▓▓▓▓▓▓▓▓▓▓ ▓▓▓▓▓▓▓▓▓▓▌ ▐▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓
▓▓▓▓▓▓▀▀▓▓▓▓▓▓▄ ▐▓▓▓▓▓▓▀▀▀▀ ▓▓▓▓▓▓▀▀▀▀ ▐▓▓▓▓▓▓▓▓▓▓▓▓▓▓▀
▓▓▓▓▓▓ ▀▓▓▓▓▓▓▄ ▐▓▓▓▓▓▓ ▓▓▓▓▓ ▓▓▓▓▓▓ ▓▓▓▓▓ ▐▓▓▓▓▓▌
▓▓▓▓▓▓▓▓▓▓ █▓▓▓▓▓▓▓▓▓ ▐▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓ ▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓ ▓▓▓▓▓▓▓▓▓▓
▓▓▓▓▓▓▓▓▓▓ ▓▓▓▓▓▓▓▓▓▓ ▐▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓ ▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓ ▓▓▓▓▓▓▓▓▓▓
Trust math, not hardware.
*/
pragma solidity 0.5.17;
/// @title ECDSA Keep
/// @notice Contract reflecting an ECDSA keep.
contract IBondedECDSAKeep {
/// @notice Returns public key of this keep.
/// @return Keeps's public key.
function getPublicKey() external view returns (bytes memory);
/// @notice Returns the amount of the keep's ETH bond in wei.
/// @return The amount of the keep's ETH bond in wei.
function checkBondAmount() external view returns (uint256);
/// @notice Calculates a signature over provided digest by the keep. Note that
/// signatures from the keep not explicitly requested by calling `sign`
/// will be provable as fraud via `submitSignatureFraud`.
/// @param _digest Digest to be signed.
function sign(bytes32 _digest) external;
/// @notice Distributes ETH reward evenly across keep signer beneficiaries.
/// @dev Only the value passed to this function is distributed.
function distributeETHReward() external payable;
/// @notice Distributes ERC20 reward evenly across keep signer beneficiaries.
/// @dev This works with any ERC20 token that implements a transferFrom
/// function.
/// This function only has authority over pre-approved
/// token amount. We don't explicitly check for allowance, SafeMath
/// subtraction overflow is enough protection.
/// @param _tokenAddress Address of the ERC20 token to distribute.
/// @param _value Amount of ERC20 token to distribute.
function distributeERC20Reward(address _tokenAddress, uint256 _value)
external;
/// @notice Seizes the signers' ETH bonds. After seizing bonds keep is
/// terminated so it will no longer respond to signing requests. Bonds can
/// be seized only when there is no signing in progress or requested signing
/// process has timed out. This function seizes all of signers' bonds.
/// The application may decide to return part of bonds later after they are
/// processed using returnPartialSignerBonds function.
function seizeSignerBonds() external;
/// @notice Returns partial signer's ETH bonds to the pool as an unbounded
/// value. This function is called after bonds have been seized and processed
/// by the privileged application after calling seizeSignerBonds function.
/// It is entirely up to the application if a part of signers' bonds is
/// returned. The application may decide for that but may also decide to
/// seize bonds and do not return anything.
function returnPartialSignerBonds() external payable;
/// @notice Submits a fraud proof for a valid signature from this keep that was
/// not first approved via a call to sign.
/// @dev The function expects the signed digest to be calculated as a sha256
/// hash of the preimage: `sha256(_preimage)`.
/// @param _v Signature's header byte: `27 + recoveryID`.
/// @param _r R part of ECDSA signature.
/// @param _s S part of ECDSA signature.
/// @param _signedDigest Digest for the provided signature. Result of hashing
/// the preimage.
/// @param _preimage Preimage of the hashed message.
/// @return True if fraud, error otherwise.
function submitSignatureFraud(
uint8 _v,
bytes32 _r,
bytes32 _s,
bytes32 _signedDigest,
bytes calldata _preimage
)
external returns (bool _isFraud);
/// @notice Closes keep when no longer needed. Releases bonds to the keep
/// members. Keep can be closed only when there is no signing in progress or
/// requested signing process has timed out.
/// @dev The function can be called only by the owner of the keep and only
/// if the keep has not been already closed.
function closeKeep() external;
}
// File: solidity/contracts/AbstractBondedECDSAKeep.sol
/**
▓▓▌ ▓▓ ▐▓▓ ▓▓▓▓▓▓▓▓▓▓▌▐▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓ ▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓ ▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▄
▓▓▓▓▓▓▓▓▓▓ ▓▓▓▓▓▓▓▓▓▓▌▐▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓ ▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓ ▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓
▓▓▓▓▓▓ ▓▓▓▓▓▓▓▀ ▐▓▓▓▓▓▓ ▐▓▓▓▓▓ ▓▓▓▓▓▓ ▓▓▓▓▓ ▐▓▓▓▓▓▌ ▐▓▓▓▓▓▓
▓▓▓▓▓▓▄▄▓▓▓▓▓▓▓▀ ▐▓▓▓▓▓▓▄▄▄▄ ▓▓▓▓▓▓▄▄▄▄ ▐▓▓▓▓▓▌ ▐▓▓▓▓▓▓
▓▓▓▓▓▓▓▓▓▓▓▓▓▀ ▐▓▓▓▓▓▓▓▓▓▓ ▓▓▓▓▓▓▓▓▓▓▌ ▐▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓
▓▓▓▓▓▓▀▀▓▓▓▓▓▓▄ ▐▓▓▓▓▓▓▀▀▀▀ ▓▓▓▓▓▓▀▀▀▀ ▐▓▓▓▓▓▓▓▓▓▓▓▓▓▓▀
▓▓▓▓▓▓ ▀▓▓▓▓▓▓▄ ▐▓▓▓▓▓▓ ▓▓▓▓▓ ▓▓▓▓▓▓ ▓▓▓▓▓ ▐▓▓▓▓▓▌
▓▓▓▓▓▓▓▓▓▓ █▓▓▓▓▓▓▓▓▓ ▐▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓ ▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓ ▓▓▓▓▓▓▓▓▓▓
▓▓▓▓▓▓▓▓▓▓ ▓▓▓▓▓▓▓▓▓▓ ▐▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓ ▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓ ▓▓▓▓▓▓▓▓▓▓
Trust math, not hardware.
*/
pragma solidity 0.5.17;
import "./api/IBondedECDSAKeep.sol";
import "./api/IBondingManagement.sol";
import "@keep-network/keep-core/contracts/utils/AddressArrayUtils.sol";
import "openzeppelin-solidity/contracts/math/SafeMath.sol";
import "openzeppelin-solidity/contracts/token/ERC20/IERC20.sol";
import "openzeppelin-solidity/contracts/token/ERC20/SafeERC20.sol";
contract AbstractBondedECDSAKeep is IBondedECDSAKeep {
using AddressArrayUtils for address[];
using SafeMath for uint256;
using SafeERC20 for IERC20;
// Status of the keep.
// Active means the keep is active.
// Closed means the keep was closed happily.
// Terminated means the keep was closed due to misbehavior.
enum Status {Active, Closed, Terminated}
// Address of the keep's owner.
address public owner;
// List of keep members' addresses.
address[] public members;
// Minimum number of honest keep members required to produce a signature.
uint256 public honestThreshold;
// Keep's ECDSA public key serialized to 64-bytes, where X and Y coordinates
// are padded with zeros to 32-byte each.
bytes public publicKey;
// Latest digest requested to be signed. Used to validate submitted signature.
bytes32 public digest;
// Map of all digests requested to be signed. Used to validate submitted
// signature. Holds the block number at which the signature over the given
// digest was requested
mapping(bytes32 => uint256) public digests;
// The timestamp at which keep has been created and key generation process
// started.
uint256 internal keyGenerationStartTimestamp;
// The timestamp at which signing process started. Used also to track if
// signing is in progress. When set to `0` indicates there is no
// signing process in progress.
uint256 internal signingStartTimestamp;
// Map stores public key by member addresses. All members should submit the
// same public key.
mapping(address => bytes) internal submittedPublicKeys;
// Map stores amount of wei stored in the contract for each member address.
mapping(address => uint256) internal memberETHBalances;
// Map stores preimages that have been proven to be fraudulent. This is needed
// to prevent from slashing members multiple times for the same fraudulent
// preimage.
mapping(bytes => bool) internal fraudulentPreimages;
// The current status of the keep.
// If the keep is Active members monitor it and support requests from the
// keep owner.
// If the owner decides to close the keep the flag is set to Closed.
// If the owner seizes member bonds the flag is set to Terminated.
Status internal status;
IBondingManagement internal bonding;
// Flags execution of contract initialization.
bool internal isInitialized;
// Notification that the keep was requested to sign a digest.
event SignatureRequested(bytes32 indexed digest);
// Notification that the submitted public key does not match a key submitted
// by other member. The event contains address of the member who tried to
// submit a public key and a conflicting public key submitted already by other
// member.
event ConflictingPublicKeySubmitted(
address indexed submittingMember,
bytes conflictingPublicKey
);
// Notification that keep's ECDSA public key has been successfully established.
event PublicKeyPublished(bytes publicKey);
// Notification that ETH reward has been distributed to keep members.
event ETHRewardDistributed(uint256 amount);
// Notification that ERC20 reward has been distributed to keep members.
event ERC20RewardDistributed(address indexed token, uint256 amount);
// Notification that the keep was closed by the owner.
// Members no longer need to support this keep.
event KeepClosed();
// Notification that the keep has been terminated by the owner.
// Members no longer need to support this keep.
event KeepTerminated();
// Notification that the signature has been calculated. Contains a digest which
// was used for signature calculation and a signature in a form of r, s and
// recovery ID values.
// The signature is chain-agnostic. Some chains (e.g. Ethereum and BTC) requires
// `v` to be calculated by increasing recovery id by 27. Please consult the
// documentation about what the particular chain expects.
event SignatureSubmitted(
bytes32 indexed digest,
bytes32 r,
bytes32 s,
uint8 recoveryID
);
/// @notice Returns keep's ECDSA public key.
/// @return Keep's ECDSA public key.
function getPublicKey() external view returns (bytes memory) {
return publicKey;
}
/// @notice Submits a public key to the keep.
/// @dev Public key is published successfully if all members submit the same
/// value. In case of conflicts with others members submissions it will emit
/// `ConflictingPublicKeySubmitted` event. When all submitted keys match
/// it will store the key as keep's public key and emit a `PublicKeyPublished`
/// event.
/// @param _publicKey Signer's public key.
function submitPublicKey(bytes calldata _publicKey) external onlyMember {
require(
!hasMemberSubmittedPublicKey(msg.sender),
"Member already submitted a public key"
);
require(_publicKey.length == 64, "Public key must be 64 bytes long");
submittedPublicKeys[msg.sender] = _publicKey;
// Check if public keys submitted by all keep members are the same as
// the currently submitted one.
uint256 matchingPublicKeysCount = 0;
for (uint256 i = 0; i < members.length; i++) {
if (
keccak256(submittedPublicKeys[members[i]]) !=
keccak256(_publicKey)
) {
// Emit an event only if compared member already submitted a value.
if (hasMemberSubmittedPublicKey(members[i])) {
emit ConflictingPublicKeySubmitted(
msg.sender,
submittedPublicKeys[members[i]]
);
}
} else {
matchingPublicKeysCount++;
}
}
if (matchingPublicKeysCount != members.length) {
return;
}
// All submitted signatures match.
publicKey = _publicKey;
emit PublicKeyPublished(_publicKey);
}
/// @notice Calculates a signature over provided digest by the keep.
/// @dev Only one signing process can be in progress at a time.
/// @param _digest Digest to be signed.
function sign(bytes32 _digest) external onlyOwner onlyWhenActive {
require(publicKey.length != 0, "Public key was not set yet");
require(!isSigningInProgress(), "Signer is busy");
/* solium-disable-next-line */
signingStartTimestamp = block.timestamp;
digests[_digest] = block.number;
digest = _digest;
emit SignatureRequested(_digest);
}
/// @notice Checks if keep is currently awaiting a signature for the given digest.
/// @dev Validates if the signing is currently in progress and compares provided
/// digest with the one for which the latest signature was requested.
/// @param _digest Digest for which to check if signature is being awaited.
/// @return True if the digest is currently expected to be signed, else false.
function isAwaitingSignature(bytes32 _digest) external view returns (bool) {
return isSigningInProgress() && digest == _digest;
}
/// @notice Submits a signature calculated for the given digest.
/// @dev Fails if signature has not been requested or a signature has already
/// been submitted.
/// Validates s value to ensure it's in the lower half of the secp256k1 curve's
/// order.
/// @param _r Calculated signature's R value.
/// @param _s Calculated signature's S value.
/// @param _recoveryID Calculated signature's recovery ID (one of {0, 1, 2, 3}).
function submitSignature(
bytes32 _r,
bytes32 _s,
uint8 _recoveryID
) external onlyMember {
require(isSigningInProgress(), "Not awaiting a signature");
require(_recoveryID < 4, "Recovery ID must be one of {0, 1, 2, 3}");
// Validate `s` value for a malleability concern described in EIP-2.
// Only signatures with `s` value in the lower half of the secp256k1
// curve's order are considered valid.
require(
uint256(_s) <=
0x7FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF5D576E7357A4501DDFE92F46681B20A0,
"Malleable signature - s should be in the low half of secp256k1 curve's order"
);
// We add 27 to the recovery ID to align it with ethereum and bitcoin
// protocols where 27 is added to recovery ID to indicate usage of
// uncompressed public keys.
uint8 _v = 27 + _recoveryID;
// Validate signature.
require(
publicKeyToAddress(publicKey) == ecrecover(digest, _v, _r, _s),
"Invalid signature"
);
signingStartTimestamp = 0;
emit SignatureSubmitted(digest, _r, _s, _recoveryID);
}
/// @notice Distributes ETH reward evenly across all keep signer beneficiaries.
/// If the value cannot be divided evenly across all signers, it sends the
/// remainder to the last keep signer.
/// @dev Only the value passed to this function is distributed. This
/// function does not transfer the value to beneficiaries accounts; instead
/// it holds the value in the contract until withdraw function is called for
/// the specific signer.
function distributeETHReward() external payable {
uint256 memberCount = members.length;
uint256 dividend = msg.value.div(memberCount);
require(dividend > 0, "Dividend value must be non-zero");
for (uint16 i = 0; i < memberCount - 1; i++) {
memberETHBalances[members[i]] += dividend;
}
// Give the dividend to the last signer. Remainder might be equal to
// zero in case of even distribution or some small number.
uint256 remainder = msg.value.mod(memberCount);
memberETHBalances[members[memberCount - 1]] += dividend.add(remainder);
emit ETHRewardDistributed(msg.value);
}
/// @notice Distributes ERC20 reward evenly across all keep signer beneficiaries.
/// @dev This works with any ERC20 token that implements a transferFrom
/// function similar to the interface imported here from
/// OpenZeppelin. This function only has authority over pre-approved
/// token amount. We don't explicitly check for allowance, SafeMath
/// subtraction overflow is enough protection. If the value cannot be
/// divided evenly across the signers, it submits the remainder to the last
/// keep signer.
/// @param _tokenAddress Address of the ERC20 token to distribute.
/// @param _value Amount of ERC20 token to distribute.
function distributeERC20Reward(address _tokenAddress, uint256 _value)
external
{
IERC20 token = IERC20(_tokenAddress);
uint256 memberCount = members.length;
uint256 dividend = _value.div(memberCount);
require(dividend > 0, "Dividend value must be non-zero");
for (uint16 i = 0; i < memberCount - 1; i++) {
token.safeTransferFrom(
msg.sender,
beneficiaryOf(members[i]),
dividend
);
}
// Transfer of dividend for the last member. Remainder might be equal to
// zero in case of even distribution or some small number.
uint256 remainder = _value.mod(memberCount);
token.safeTransferFrom(
msg.sender,
beneficiaryOf(members[memberCount - 1]),
dividend.add(remainder)
);
emit ERC20RewardDistributed(_tokenAddress, _value);
}
/// @notice Gets current amount of ETH hold in the keep for the member.
/// @param _member Keep member address.
/// @return Current balance in wei.
function getMemberETHBalance(address _member)
external
view
returns (uint256)
{
return memberETHBalances[_member];
}
/// @notice Withdraws amount of ether hold in the keep for the member.
/// The value is sent to the beneficiary of the specific member.
/// @param _member Keep member address.
function withdraw(address _member) external {
uint256 value = memberETHBalances[_member];
require(value > 0, "No funds to withdraw");
memberETHBalances[_member] = 0;
/* solium-disable-next-line security/no-call-value */
(bool success, ) = beneficiaryOf(_member).call.value(value)("");
require(success, "Transfer failed");
}
/// @notice Submits a fraud proof for a valid signature from this keep that was
/// not first approved via a call to sign. If fraud is detected it tries to
/// slash members' KEEP tokens. For each keep member tries slashing amount
/// equal to the member stake set by the factory when keep was created.
/// @dev The function expects the signed digest to be calculated as a sha256
/// hash of the preimage: `sha256(_preimage))`. The function reverts if the
/// signature is not fraudulent. The function does not revert if KEEP slashing
/// failed but emits an event instead. In practice, KEEP slashing should
/// never fail.
/// @param _v Signature's header byte: `27 + recoveryID`.
/// @param _r R part of ECDSA signature.
/// @param _s S part of ECDSA signature.
/// @param _signedDigest Digest for the provided signature. Result of hashing
/// the preimage with sha256.
/// @param _preimage Preimage of the hashed message.
/// @return True if fraud, error otherwise.
function submitSignatureFraud(
uint8 _v,
bytes32 _r,
bytes32 _s,
bytes32 _signedDigest,
bytes calldata _preimage
) external onlyWhenActive returns (bool _isFraud) {
bool isFraud = checkSignatureFraud(
_v,
_r,
_s,
_signedDigest,
_preimage
);
require(isFraud, "Signature is not fraudulent");
if (!fraudulentPreimages[_preimage]) {
slashForSignatureFraud();
fraudulentPreimages[_preimage] = true;
}
return isFraud;
}
/// @notice Gets the owner of the keep.
/// @return Address of the keep owner.
function getOwner() external view returns (address) {
return owner;
}
/// @notice Gets the timestamp the keep was opened at.
/// @return Timestamp the keep was opened at.
function getOpenedTimestamp() external view returns (uint256) {
return keyGenerationStartTimestamp;
}
/// @notice Returns the amount of the keep's ETH bond in wei.
/// @return The amount of the keep's ETH bond in wei.
function checkBondAmount() external view returns (uint256) {
uint256 sumBondAmount = 0;
for (uint256 i = 0; i < members.length; i++) {
sumBondAmount += bonding.bondAmount(
members[i],
address(this),
uint256(address(this))
);
}
return sumBondAmount;
}
/// @notice Seizes the signers' ETH bonds. After seizing bonds keep is
/// closed so it will no longer respond to signing requests. Bonds can be
/// seized only when there is no signing in progress or requested signing
/// process has timed out. This function seizes all of signers' bonds.
/// The application may decide to return part of bonds later after they are
/// processed using returnPartialSignerBonds function.
function seizeSignerBonds() external onlyOwner onlyWhenActive {
terminateKeep();
for (uint256 i = 0; i < members.length; i++) {
uint256 amount = bonding.bondAmount(
members[i],
address(this),
uint256(address(this))
);
bonding.seizeBond(
members[i],
uint256(address(this)),
amount,
address(uint160(owner))
);
}
}
/// @notice Returns partial signer's ETH bonds to the pool as an unbounded
/// value. This function is called after bonds have been seized and processed
/// by the privileged application after calling seizeSignerBonds function.
/// It is entirely up to the application if a part of signers' bonds is
/// returned. The application may decide for that but may also decide to
/// seize bonds and do not return anything.
function returnPartialSignerBonds() external payable {
uint256 memberCount = members.length;
uint256 bondPerMember = msg.value.div(memberCount);
require(bondPerMember > 0, "Partial signer bond must be non-zero");
for (uint16 i = 0; i < memberCount - 1; i++) {
bonding.deposit.value(bondPerMember)(members[i]);
}
// Transfer of dividend for the last member. Remainder might be equal to
// zero in case of even distribution or some small number.
uint256 remainder = msg.value.mod(memberCount);
bonding.deposit.value(bondPerMember.add(remainder))(
members[memberCount - 1]
);
}
/// @notice Closes keep when owner decides that they no longer need it.
/// Releases bonds to the keep members.
/// @dev The function can be called only by the owner of the keep and only
/// if the keep has not been already closed.
function closeKeep() public onlyOwner onlyWhenActive {
markAsClosed();
freeMembersBonds();
}
/// @notice Returns true if the keep is active.
/// @return true if the keep is active, false otherwise.
function isActive() public view returns (bool) {
return status == Status.Active;
}
/// @notice Returns true if the keep is closed and members no longer support
/// this keep.
/// @return true if the keep is closed, false otherwise.
function isClosed() public view returns (bool) {
return status == Status.Closed;
}
/// @notice Returns true if the keep has been terminated.
/// Keep is terminated when bonds are seized and members no longer support
/// this keep.
/// @return true if the keep has been terminated, false otherwise.
function isTerminated() public view returns (bool) {
return status == Status.Terminated;
}
/// @notice Returns members of the keep.
/// @return List of the keep members' addresses.
function getMembers() public view returns (address[] memory) {
return members;
}
/// @notice Checks a fraud proof for a valid signature from this keep that was
/// not first approved via a call to sign.
/// @dev The function expects the signed digest to be calculated as a sha256 hash
/// of the preimage: `sha256(_preimage))`. The digest is verified against the
/// preimage to ensure the security of the ECDSA protocol. Verifying just the
/// signature and the digest is not enough and leaves the possibility of the
/// the existential forgery. If digest and preimage verification fails the
/// function reverts.
/// Reverts if a public key has not been set for the keep yet.
/// @param _v Signature's header byte: `27 + recoveryID`.
/// @param _r R part of ECDSA signature.
/// @param _s S part of ECDSA signature.
/// @param _signedDigest Digest for the provided signature. Result of hashing
/// the preimage with sha256.
/// @param _preimage Preimage of the hashed message.
/// @return True if fraud, false otherwise.
function checkSignatureFraud(
uint8 _v,
bytes32 _r,
bytes32 _s,
bytes32 _signedDigest,
bytes memory _preimage
) public view returns (bool _isFraud) {
require(publicKey.length != 0, "Public key was not set yet");
bytes32 calculatedDigest = sha256(_preimage);
require(
_signedDigest == calculatedDigest,
"Signed digest does not match sha256 hash of the preimage"
);
bool isSignatureValid = publicKeyToAddress(publicKey) ==
ecrecover(_signedDigest, _v, _r, _s);
// Check if the signature is valid but was not requested.
return isSignatureValid && digests[_signedDigest] == 0;
}
/// @notice Initialization function.
/// @dev We use clone factory to create new keep. That is why this contract
/// doesn't have a constructor. We provide keep parameters for each instance
/// function after cloning instances from the master contract.
/// Initialization must happen in the same transaction in which the clone is
/// created.
/// @param _owner Address of the keep owner.
/// @param _members Addresses of the keep members.
/// @param _honestThreshold Minimum number of honest keep members.
function initialize(
address _owner,
address[] memory _members,
uint256 _honestThreshold,
address _bonding
) internal {
require(!isInitialized, "Contract already initialized");
owner = _owner;
members = _members;
honestThreshold = _honestThreshold;
status = Status.Active;
isInitialized = true;
/* solium-disable-next-line security/no-block-members*/
keyGenerationStartTimestamp = block.timestamp;
bonding = IBondingManagement(_bonding);
}
/// @notice Checks if the member already submitted a public key.
/// @param _member Address of the member.
/// @return True if member already submitted a public key, else false.
function hasMemberSubmittedPublicKey(address _member)
internal
view
returns (bool)
{
return submittedPublicKeys[_member].length != 0;
}
/// @notice Returns true if signing of a digest is currently in progress.
function isSigningInProgress() internal view returns (bool) {
return signingStartTimestamp != 0;
}
/// @notice Marks the keep as closed.
/// Keep can be marked as closed only when there is no signing in progress
/// or the requested signing process has timed out.
function markAsClosed() internal {
status = Status.Closed;
emit KeepClosed();
}
/// @notice Marks the keep as terminated.
/// Keep can be marked as terminated only when there is no signing in progress
/// or the requested signing process has timed out.
function markAsTerminated() internal {
status = Status.Terminated;
emit KeepTerminated();
}
/// @notice Coverts a public key to an ethereum address.
/// @param _publicKey Public key provided as 64-bytes concatenation of
/// X and Y coordinates (32-bytes each).
/// @return Ethereum address.
function publicKeyToAddress(bytes memory _publicKey)
internal
pure
returns (address)
{
// We hash the public key and then truncate last 20 bytes of the digest
// which is the ethereum address.
return address(uint160(uint256(keccak256(_publicKey))));
}
/// @notice Returns bonds to the keep members.
function freeMembersBonds() internal {
for (uint256 i = 0; i < members.length; i++) {
bonding.freeBond(members[i], uint256(address(this)));
}
}
/// @notice Terminates the keep.
function terminateKeep() internal {
markAsTerminated();
}
/// @notice Punishes keep members after proving a signature fraud.
function slashForSignatureFraud() internal;
/// @notice Gets the beneficiary for the specified member address.
/// @param _member Member address.
/// @return Beneficiary address.
function beneficiaryOf(address _member)
internal
view
returns (address payable);
/// @notice Checks if the caller is the keep's owner.
/// @dev Throws an error if called by any account other than owner.
modifier onlyOwner() {
require(owner == msg.sender, "Caller is not the keep owner");
_;
}
/// @notice Checks if the caller is a keep member.
/// @dev Throws an error if called by any account other than one of the members.
modifier onlyMember() {
require(members.contains(msg.sender), "Caller is not the keep member");
_;
}
/// @notice Checks if the keep is currently active.
/// @dev Throws an error if called when the keep has been already closed.
modifier onlyWhenActive() {
require(isActive(), "Keep is not active");
_;
}
}
// File: solidity/contracts/api/IBondingManagement.sol
/**
▓▓▌ ▓▓ ▐▓▓ ▓▓▓▓▓▓▓▓▓▓▌▐▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓ ▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓ ▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▄
▓▓▓▓▓▓▓▓▓▓ ▓▓▓▓▓▓▓▓▓▓▌▐▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓ ▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓ ▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓
▓▓▓▓▓▓ ▓▓▓▓▓▓▓▀ ▐▓▓▓▓▓▓ ▐▓▓▓▓▓ ▓▓▓▓▓▓ ▓▓▓▓▓ ▐▓▓▓▓▓▌ ▐▓▓▓▓▓▓
▓▓▓▓▓▓▄▄▓▓▓▓▓▓▓▀ ▐▓▓▓▓▓▓▄▄▄▄ ▓▓▓▓▓▓▄▄▄▄ ▐▓▓▓▓▓▌ ▐▓▓▓▓▓▓
▓▓▓▓▓▓▓▓▓▓▓▓▓▀ ▐▓▓▓▓▓▓▓▓▓▓ ▓▓▓▓▓▓▓▓▓▓▌ ▐▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓
▓▓▓▓▓▓▀▀▓▓▓▓▓▓▄ ▐▓▓▓▓▓▓▀▀▀▀ ▓▓▓▓▓▓▀▀▀▀ ▐▓▓▓▓▓▓▓▓▓▓▓▓▓▓▀
▓▓▓▓▓▓ ▀▓▓▓▓▓▓▄ ▐▓▓▓▓▓▓ ▓▓▓▓▓ ▓▓▓▓▓▓ ▓▓▓▓▓ ▐▓▓▓▓▓▌
▓▓▓▓▓▓▓▓▓▓ █▓▓▓▓▓▓▓▓▓ ▐▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓ ▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓ ▓▓▓▓▓▓▓▓▓▓
▓▓▓▓▓▓▓▓▓▓ ▓▓▓▓▓▓▓▓▓▓ ▐▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓ ▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓ ▓▓▓▓▓▓▓▓▓▓
Trust math, not hardware.
*/
pragma solidity 0.5.17;
import "@keep-network/sortition-pools/contracts/api/IBonding.sol";
contract IBondingManagement is IBonding {
/// @notice Add the provided value to operator's pool available for bonding.
/// @param operator Address of the operator.
function deposit(address operator) public payable;
/// @notice Withdraws amount from operator's value available for bonding.
/// @param amount Value to withdraw in wei.
/// @param operator Address of the operator.
function withdraw(uint256 amount, address operator) public;
/// @notice Create bond for the given operator, holder, reference and amount.
/// @param operator Address of the operator to bond.
/// @param holder Address of the holder of the bond.
/// @param referenceID Reference ID used to track the bond by holder.
/// @param amount Value to bond in wei.
/// @param authorizedSortitionPool Address of authorized sortition pool.
function createBond(
address operator,
address holder,
uint256 referenceID,
uint256 amount,
address authorizedSortitionPool
) public;
/// @notice Returns value of wei bonded for the operator.
/// @param operator Address of the operator.
/// @param holder Address of the holder of the bond.
/// @param referenceID Reference ID of the bond.
/// @return Amount of wei in the selected bond.
function bondAmount(
address operator,
address holder,
uint256 referenceID
) public view returns (uint256);
/// @notice Reassigns a bond to a new holder under a new reference.
/// @param operator Address of the bonded operator.
/// @param referenceID Reference ID of the bond.
/// @param newHolder Address of the new holder of the bond.
/// @param newReferenceID New reference ID to register the bond.
function reassignBond(
address operator,
uint256 referenceID,
address newHolder,
uint256 newReferenceID
) public;
/// @notice Releases the bond and moves the bond value to the operator's
/// unbounded value pool.
/// @param operator Address of the bonded operator.
/// @param referenceID Reference ID of the bond.
function freeBond(address operator, uint256 referenceID) public;
/// @notice Seizes the bond by moving some or all of the locked bond to the
/// provided destination address.
/// @param operator Address of the bonded operator.
/// @param referenceID Reference ID of the bond.
/// @param amount Amount to be seized.
/// @param destination Address to send the amount to.
function seizeBond(
address operator,
uint256 referenceID,
uint256 amount,
address payable destination
) public;
}
// File: solidity/contracts/BondedECDSAKeepFactory.sol
/**
▓▓▌ ▓▓ ▐▓▓ ▓▓▓▓▓▓▓▓▓▓▌▐▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓ ▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓ ▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▄
▓▓▓▓▓▓▓▓▓▓ ▓▓▓▓▓▓▓▓▓▓▌▐▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓ ▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓ ▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓
▓▓▓▓▓▓ ▓▓▓▓▓▓▓▀ ▐▓▓▓▓▓▓ ▐▓▓▓▓▓ ▓▓▓▓▓▓ ▓▓▓▓▓ ▐▓▓▓▓▓▌ ▐▓▓▓▓▓▓
▓▓▓▓▓▓▄▄▓▓▓▓▓▓▓▀ ▐▓▓▓▓▓▓▄▄▄▄ ▓▓▓▓▓▓▄▄▄▄ ▐▓▓▓▓▓▌ ▐▓▓▓▓▓▓
▓▓▓▓▓▓▓▓▓▓▓▓▓▀ ▐▓▓▓▓▓▓▓▓▓▓ ▓▓▓▓▓▓▓▓▓▓▌ ▐▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓
▓▓▓▓▓▓▀▀▓▓▓▓▓▓▄ ▐▓▓▓▓▓▓▀▀▀▀ ▓▓▓▓▓▓▀▀▀▀ ▐▓▓▓▓▓▓▓▓▓▓▓▓▓▓▀
▓▓▓▓▓▓ ▀▓▓▓▓▓▓▄ ▐▓▓▓▓▓▓ ▓▓▓▓▓ ▓▓▓▓▓▓ ▓▓▓▓▓ ▐▓▓▓▓▓▌
▓▓▓▓▓▓▓▓▓▓ █▓▓▓▓▓▓▓▓▓ ▐▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓ ▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓ ▓▓▓▓▓▓▓▓▓▓
▓▓▓▓▓▓▓▓▓▓ ▓▓▓▓▓▓▓▓▓▓ ▐▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓ ▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓ ▓▓▓▓▓▓▓▓▓▓
Trust math, not hardware.
*/
pragma solidity 0.5.17;
import "./BondedECDSAKeep.sol";
import "./KeepBonding.sol";
import "./api/IBondedECDSAKeepFactory.sol";
import "./KeepCreator.sol";
import "./GroupSelectionSeed.sol";
import "./CandidatesPools.sol";
import "@keep-network/sortition-pools/contracts/api/IStaking.sol";
import "@keep-network/sortition-pools/contracts/api/IBonding.sol";
import "@keep-network/sortition-pools/contracts/BondedSortitionPool.sol";
import "@keep-network/sortition-pools/contracts/BondedSortitionPoolFactory.sol";
import {
AuthorityDelegator,
TokenStaking
} from "@keep-network/keep-core/contracts/TokenStaking.sol";
import "@keep-network/keep-core/contracts/utils/AddressArrayUtils.sol";
import "openzeppelin-solidity/contracts/math/SafeMath.sol";
/// @title Bonded ECDSA Keep Factory
/// @notice Contract creating bonded ECDSA keeps.
/// @dev We avoid redeployment of bonded ECDSA keep contract by using the clone factory.
/// Proxy delegates calls to sortition pool and therefore does not affect contract's
/// state. This means that we only need to deploy the bonded ECDSA keep contract
/// once. The factory provides clean state for every new bonded ECDSA keep clone.
contract BondedECDSAKeepFactory is
IBondedECDSAKeepFactory,
KeepCreator,
AuthorityDelegator,
GroupSelectionSeed,
CandidatesPools
{
using AddressArrayUtils for address[];
using SafeMath for uint256;
// Notification that a new keep has been created.
event BondedECDSAKeepCreated(
address indexed keepAddress,
address[] members,
address indexed owner,
address indexed application,
uint256 honestThreshold
);
BondedSortitionPoolFactory sortitionPoolFactory;
TokenStaking tokenStaking;
KeepBonding keepBonding;
// Sortition pool is created with a minimum bond of 20 ETH to avoid
// small operators joining and griefing future selections before the
// minimum bond is set to the right value by the application.
//
// Anyone can create a sortition pool for an application with the default
// minimum bond value but the application can change this value later, at
// any point.
uint256 public constant minimumBond = 20e18; // 20 ETH
// Signer candidates in bonded sortition pool are weighted by their eligible
// stake divided by a constant divisor. The divisor is set to 1 KEEP so that
// all KEEPs in eligible stake matter when calculating operator's eligible
// weight for signer selection.
uint256 public constant poolStakeWeightDivisor = 1e18;
constructor(
address _masterBondedECDSAKeepAddress,
address _sortitionPoolFactory,
address _tokenStaking,
address _keepBonding,
address _randomBeacon
)
public
KeepCreator(_masterBondedECDSAKeepAddress)
GroupSelectionSeed(_randomBeacon)
{
sortitionPoolFactory = BondedSortitionPoolFactory(
_sortitionPoolFactory
);
tokenStaking = TokenStaking(_tokenStaking);
keepBonding = KeepBonding(_keepBonding);
}
/// @notice Sets the minimum bondable value required from the operator to
/// join the sortition pool of the given application. It is up to the
/// application to specify a reasonable minimum bond for operators trying to
/// join the pool to prevent griefing by operators joining without enough
/// bondable value.
/// @param _minimumBondableValue The minimum bond value the application
/// requires from a single keep.
/// @param _groupSize Number of signers in the keep.
/// @param _honestThreshold Minimum number of honest keep signers.
function setMinimumBondableValue(
uint256 _minimumBondableValue,
uint256 _groupSize,
uint256 _honestThreshold
) external {
uint256 memberBond = bondPerMember(_minimumBondableValue, _groupSize);
BondedSortitionPool(getSortitionPool(msg.sender))
.setMinimumBondableValue(memberBond);
}
/// @notice Opens a new ECDSA keep.
/// @dev Selects a list of signers for the keep based on provided parameters.
/// A caller of this function is expected to be an application for which
/// member candidates were registered in a pool.
/// @param _groupSize Number of signers in the keep.
/// @param _honestThreshold Minimum number of honest keep signers.
/// @param _owner Address of the keep owner.
/// @param _bond Value of ETH bond required from the keep in wei.
/// @param _stakeLockDuration Stake lock duration in seconds.
/// @return Created keep address.
function openKeep(
uint256 _groupSize,
uint256 _honestThreshold,
address _owner,
uint256 _bond,
uint256 _stakeLockDuration
) external payable nonReentrant returns (address keepAddress) {
require(_groupSize > 0, "Minimum signing group size is 1");
require(_groupSize <= 16, "Maximum signing group size is 16");
require(
_honestThreshold > 0,
"Honest threshold must be greater than 0"
);
require(
_honestThreshold <= _groupSize,
"Honest threshold must be less or equal the group size"
);
address application = msg.sender;
address pool = getSortitionPool(application);
uint256 memberBond = bondPerMember(_bond, _groupSize);
require(memberBond > 0, "Bond per member must be greater than zero");
require(
msg.value >= openKeepFeeEstimate(),
"Insufficient payment for opening a new keep"
);
uint256 minimumStake = tokenStaking.minimumStake();
address[] memory members = BondedSortitionPool(pool).selectSetGroup(
_groupSize,
bytes32(groupSelectionSeed),
minimumStake,
memberBond
);
newGroupSelectionSeed();
// createKeep sets keepOpenedTimestamp value for newly created keep which
// is required to be set before calling `keep.initialize` function as it
// is used to determine token staking delegation authority recognition
// in `__isRecognized` function.
keepAddress = createKeep();
BondedECDSAKeep(keepAddress).initialize(
_owner,
members,
_honestThreshold,
minimumStake,
_stakeLockDuration,
address(tokenStaking),
address(keepBonding),
address(this)
);
for (uint256 i = 0; i < _groupSize; i++) {
keepBonding.createBond(
members[i],
keepAddress,
uint256(keepAddress),
memberBond,
pool
);
}
emit BondedECDSAKeepCreated(
keepAddress,
members,
_owner,
application,
_honestThreshold
);
}
/// @notice Verifies if delegates authority recipient is valid address recognized
/// by the factory for token staking authority delegation.
/// @param _delegatedAuthorityRecipient Address of the delegated authority
/// recipient.
/// @return True if provided address is recognized delegated token staking
/// authority for this factory contract.
function __isRecognized(address _delegatedAuthorityRecipient)
external
returns (bool)
{
return keepOpenedTimestamp[_delegatedAuthorityRecipient] > 0;
}
/// @notice Gets a fee estimate for opening a new keep.
/// @return Uint256 estimate.
function openKeepFeeEstimate() public view returns (uint256) {
return newEntryFeeEstimate();
}
/// @notice Checks if the specified account has enough active stake to become
/// network operator and that this contract has been authorized for potential
/// slashing.
///
/// Having the required minimum of active stake makes the operator eligible
/// to join the network. If the active stake is not currently undelegating,
/// operator is also eligible for work selection.
///
/// @param _operator operator's address
/// @return True if has enough active stake to participate in the network,
/// false otherwise.
function hasMinimumStake(address _operator) public view returns (bool) {
return tokenStaking.hasMinimumStake(_operator, address(this));
}
/// @notice Checks if the factory has the authorization to operate on stake
/// represented by the provided operator.
///
/// @param _operator operator's address
/// @return True if the factory has access to the staked token balance of
/// the provided operator and can slash that stake. False otherwise.
function isOperatorAuthorized(address _operator)
public
view
returns (bool)
{
return tokenStaking.isAuthorizedForOperator(_operator, address(this));
}
/// @notice Gets the stake balance of the specified operator.
/// @param _operator The operator to query the balance of.
/// @return An uint256 representing the amount staked by the passed operator.
function balanceOf(address _operator) public view returns (uint256) {
return tokenStaking.balanceOf(_operator);
}
function newSortitionPool(address _application) internal returns (address) {
return
sortitionPoolFactory.createSortitionPool(
IStaking(address(tokenStaking)),
IBonding(address(keepBonding)),
tokenStaking.minimumStake(),
minimumBond,
poolStakeWeightDivisor
);
}
/// @notice Calculates bond requirement per member performing the necessary
/// rounding.
/// @param _keepBond The bond required from a keep.
/// @param _groupSize Number of signers in the keep.
/// @return Bond value required from each keep member.
function bondPerMember(uint256 _keepBond, uint256 _groupSize)
internal
pure
returns (uint256)
{
// In Solidity, division rounds towards zero (down) and dividing
// '_bond' by '_groupSize' can leave a remainder. Even though, a remainder
// is very small, we want to avoid this from happening and memberBond is
// rounded up by: `(bond + groupSize - 1 ) / groupSize`
// Ex. (100 + 3 - 1) / 3 = 34
return (_keepBond.add(_groupSize).sub(1)).div(_groupSize);
}
}
// File: solidity/contracts/api/IBondedECDSAKeepFactory.sol
/**
▓▓▌ ▓▓ ▐▓▓ ▓▓▓▓▓▓▓▓▓▓▌▐▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓ ▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓ ▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▄
▓▓▓▓▓▓▓▓▓▓ ▓▓▓▓▓▓▓▓▓▓▌▐▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓ ▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓ ▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓
▓▓▓▓▓▓ ▓▓▓▓▓▓▓▀ ▐▓▓▓▓▓▓ ▐▓▓▓▓▓ ▓▓▓▓▓▓ ▓▓▓▓▓ ▐▓▓▓▓▓▌ ▐▓▓▓▓▓▓
▓▓▓▓▓▓▄▄▓▓▓▓▓▓▓▀ ▐▓▓▓▓▓▓▄▄▄▄ ▓▓▓▓▓▓▄▄▄▄ ▐▓▓▓▓▓▌ ▐▓▓▓▓▓▓
▓▓▓▓▓▓▓▓▓▓▓▓▓▀ ▐▓▓▓▓▓▓▓▓▓▓ ▓▓▓▓▓▓▓▓▓▓▌ ▐▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓
▓▓▓▓▓▓▀▀▓▓▓▓▓▓▄ ▐▓▓▓▓▓▓▀▀▀▀ ▓▓▓▓▓▓▀▀▀▀ ▐▓▓▓▓▓▓▓▓▓▓▓▓▓▓▀
▓▓▓▓▓▓ ▀▓▓▓▓▓▓▄ ▐▓▓▓▓▓▓ ▓▓▓▓▓ ▓▓▓▓▓▓ ▓▓▓▓▓ ▐▓▓▓▓▓▌
▓▓▓▓▓▓▓▓▓▓ █▓▓▓▓▓▓▓▓▓ ▐▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓ ▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓ ▓▓▓▓▓▓▓▓▓▓
▓▓▓▓▓▓▓▓▓▓ ▓▓▓▓▓▓▓▓▓▓ ▐▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓ ▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓ ▓▓▓▓▓▓▓▓▓▓
Trust math, not hardware.
*/
pragma solidity 0.5.17;
/// @title Bonded ECDSA Keep Factory
/// @notice Factory for Bonded ECDSA Keeps.
interface IBondedECDSAKeepFactory {
/// @notice Open a new ECDSA Keep.
/// @param _groupSize Number of members in the keep.
/// @param _honestThreshold Minimum number of honest keep members.
/// @param _owner Address of the keep owner.
/// @param _bond Value of ETH bond required from the keep.
/// @param _stakeLockDuration Stake lock duration in seconds.
/// @return Address of the opened keep.
function openKeep(
uint256 _groupSize,
uint256 _honestThreshold,
address _owner,
uint256 _bond,
uint256 _stakeLockDuration
) external payable returns (address keepAddress);
/// @notice Gets a fee estimate for opening a new keep.
/// @return Uint256 estimate.
function openKeepFeeEstimate() external view returns (uint256);
/// @notice Gets the total weight of operators
/// in the sortition pool for the given application.
/// @param _application Address of the application.
/// @return The sum of all registered operators' weights in the pool.
/// Reverts if sortition pool for the application does not exist.
function getSortitionPoolWeight(
address _application
) external view returns (uint256);
/// @notice Sets the minimum bondable value required from the operator to
/// join the sortition pool of the given application. It is up to the
/// application to specify a reasonable minimum bond for operators trying to
/// join the pool to prevent griefing by operators joining without enough
/// bondable value.
/// @dev The default minimum bond value for each sortition pool created
/// is 20 ETH.
/// @param _minimumBondableValue The minimum unbonded value the application
/// requires from a single keep.
/// @param _groupSize Number of signers in the keep.
/// @param _honestThreshold Minimum number of honest keep signers.
function setMinimumBondableValue(
uint256 _minimumBondableValue,
uint256 _groupSize,
uint256 _honestThreshold
) external;
}
// File: solidity/contracts/KeepCreator.sol
/**
▓▓▌ ▓▓ ▐▓▓ ▓▓▓▓▓▓▓▓▓▓▌▐▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓ ▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓ ▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▄
▓▓▓▓▓▓▓▓▓▓ ▓▓▓▓▓▓▓▓▓▓▌▐▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓ ▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓ ▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓
▓▓▓▓▓▓ ▓▓▓▓▓▓▓▀ ▐▓▓▓▓▓▓ ▐▓▓▓▓▓ ▓▓▓▓▓▓ ▓▓▓▓▓ ▐▓▓▓▓▓▌ ▐▓▓▓▓▓▓
▓▓▓▓▓▓▄▄▓▓▓▓▓▓▓▀ ▐▓▓▓▓▓▓▄▄▄▄ ▓▓▓▓▓▓▄▄▄▄ ▐▓▓▓▓▓▌ ▐▓▓▓▓▓▓
▓▓▓▓▓▓▓▓▓▓▓▓▓▀ ▐▓▓▓▓▓▓▓▓▓▓ ▓▓▓▓▓▓▓▓▓▓▌ ▐▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓
▓▓▓▓▓▓▀▀▓▓▓▓▓▓▄ ▐▓▓▓▓▓▓▀▀▀▀ ▓▓▓▓▓▓▀▀▀▀ ▐▓▓▓▓▓▓▓▓▓▓▓▓▓▓▀
▓▓▓▓▓▓ ▀▓▓▓▓▓▓▄ ▐▓▓▓▓▓▓ ▓▓▓▓▓ ▓▓▓▓▓▓ ▓▓▓▓▓ ▐▓▓▓▓▓▌
▓▓▓▓▓▓▓▓▓▓ █▓▓▓▓▓▓▓▓▓ ▐▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓ ▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓ ▓▓▓▓▓▓▓▓▓▓
▓▓▓▓▓▓▓▓▓▓ ▓▓▓▓▓▓▓▓▓▓ ▐▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓ ▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓ ▓▓▓▓▓▓▓▓▓▓
Trust math, not hardware.
*/
pragma solidity 0.5.17;
import "./CloneFactory.sol";
contract KeepCreator is CloneFactory {
// Holds the address of the keep contract that will be used as a master
// contract for cloning.
address public masterKeepAddress;
// Keeps created by this factory.
address[] public keeps;
// Maps keep opened timestamp to each keep address
mapping(address => uint256) keepOpenedTimestamp;
constructor(address _masterKeepAddress) public {
masterKeepAddress = _masterKeepAddress;
}
/// @notice Gets how many keeps have been opened by this contract.
/// @dev Checks the size of the keeps array.
/// @return The number of keeps opened so far.
function getKeepCount() external view returns (uint256) {
return keeps.length;
}
/// @notice Gets a specific keep address at a given index.
/// @return The address of the keep at the given index.
function getKeepAtIndex(uint256 index) external view returns (address) {
require(index < keeps.length, "Out of bounds.");
return keeps[index];
}
/// @notice Gets the opened timestamp of the given keep.
/// @return Timestamp the given keep was opened at or 0 if this keep
/// was not created by this factory.
function getKeepOpenedTimestamp(address _keep)
external
view
returns (uint256)
{
return keepOpenedTimestamp[_keep];
}
/// @notice Creates a new keep instance with a clone factory.
/// @dev It has to be called by a function implementing a keep opening mechanism.
function createKeep() internal returns (address keepAddress) {
keepAddress = createClone(masterKeepAddress);
keeps.push(keepAddress);
/* solium-disable-next-line security/no-block-members*/
keepOpenedTimestamp[keepAddress] = block.timestamp;
}
}
// File: solidity/contracts/CloneFactory.sol
pragma solidity 0.5.17;
/*
The MIT License (MIT)
Copyright (c) 2018 Murray Software, LLC.
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.
*/
//solhint-disable max-line-length
//solhint-disable no-inline-assembly
// Implementation of [EIP-1167] based on [clone-factory]
// source code.
//
// EIP 1167: https://eips.ethereum.org/EIPS/eip-1167
// clone-factory: https://github.com/optionality/clone-factory
// Modified to use ^0.5.10; instead of ^0.4.23 solidity version
//
// TODO: This code is copied from tbtc repo. We should consider pulling the code
// and tests to a common repo.
/* solium-disable */
contract CloneFactory {
function createClone(address target) internal returns (address result) {
bytes20 targetBytes = bytes20(target);
assembly {
let clone := mload(0x40)
mstore(
clone,
0x3d602d80600a3d3981f3363d3d373d3d3d363d73000000000000000000000000
)
mstore(add(clone, 0x14), targetBytes)
mstore(
add(clone, 0x28),
0x5af43d82803e903d91602b57fd5bf30000000000000000000000000000000000
)
result := create(0, clone, 0x37)
}
}
function isClone(address target, address query)
internal
view
returns (bool result)
{
bytes20 targetBytes = bytes20(target);
assembly {
let clone := mload(0x40)
mstore(
clone,
0x363d3d373d3d3d363d7300000000000000000000000000000000000000000000
)
mstore(add(clone, 0xa), targetBytes)
mstore(
add(clone, 0x1e),
0x5af43d82803e903d91602b57fd5bf30000000000000000000000000000000000
)
let other := add(clone, 0x40)
extcodecopy(query, other, 0, 0x2d)
result := and(
eq(mload(clone), mload(other)),
eq(mload(add(clone, 0xd)), mload(add(other, 0xd)))
)
}
}
}
// File: solidity/contracts/CandidatesPools.sol
pragma solidity 0.5.17;
import "@keep-network/sortition-pools/contracts/AbstractSortitionPool.sol";
contract CandidatesPools {
// Notification that a new sortition pool has been created.
event SortitionPoolCreated(
address indexed application,
address sortitionPool
);
// Mapping of pools with registered member candidates for each application.
mapping(address => address) candidatesPools; // application -> candidates pool
/// @notice Creates new sortition pool for the application.
/// @dev Emits an event after sortition pool creation.
/// @param _application Address of the application.
/// @return Address of the created sortition pool contract.
function createSortitionPool(address _application)
external
returns (address)
{
require(
candidatesPools[_application] == address(0),
"Sortition pool already exists"
);
address sortitionPoolAddress = newSortitionPool(_application);
candidatesPools[_application] = sortitionPoolAddress;
emit SortitionPoolCreated(_application, sortitionPoolAddress);
return candidatesPools[_application];
}
/// @notice Register caller as a candidate to be selected as keep member
/// for the provided customer application.
/// @dev If caller is already registered it returns without any changes.
/// @param _application Address of the application.
function registerMemberCandidate(address _application) external {
AbstractSortitionPool candidatesPool = AbstractSortitionPool(
getSortitionPool(_application)
);
address operator = msg.sender;
if (!candidatesPool.isOperatorInPool(operator)) {
candidatesPool.joinPool(operator);
}
}
/// @notice Checks if operator's details in the member candidates pool are
/// up to date for the given application. If not update operator status
/// function should be called by the one who is monitoring the status.
/// @param _operator Operator's address.
/// @param _application Customer application address.
function isOperatorUpToDate(address _operator, address _application)
external
view
returns (bool)
{
return
getSortitionPoolForOperator(_operator, _application)
.isOperatorUpToDate(_operator);
}
/// @notice Invokes update of operator's details in the member candidates pool
/// for the given application
/// @param _operator Operator's address.
/// @param _application Customer application address.
function updateOperatorStatus(address _operator, address _application)
external
{
getSortitionPoolForOperator(_operator, _application)
.updateOperatorStatus(_operator);
}
/// @notice Gets the sortition pool address for the given application.
/// @dev Reverts if sortition does not exist for the application.
/// @param _application Address of the application.
/// @return Address of the sortition pool contract.
function getSortitionPool(address _application)
public
view
returns (address)
{
require(
candidatesPools[_application] != address(0),
"No pool found for the application"
);
return candidatesPools[_application];
}
/// @notice Checks if operator is registered as a candidate for the given
/// customer application.
/// @param _operator Operator's address.
/// @param _application Customer application address.
/// @return True if operator is already registered in the candidates pool,
/// false otherwise.
function isOperatorRegistered(address _operator, address _application)
public
view
returns (bool)
{
if (candidatesPools[_application] == address(0)) {
return false;
}
AbstractSortitionPool candidatesPool = AbstractSortitionPool(
candidatesPools[_application]
);
return candidatesPool.isOperatorRegistered(_operator);
}
/// @notice Checks if given operator is eligible for the given application.
/// @param _operator Operator's address.
/// @param _application Customer application address.
function isOperatorEligible(address _operator, address _application)
public
view
returns (bool)
{
if (candidatesPools[_application] == address(0)) {
return false;
}
AbstractSortitionPool candidatesPool = AbstractSortitionPool(
candidatesPools[_application]
);
return candidatesPool.isOperatorEligible(_operator);
}
/// @notice Gets the total weight of operators
/// in the sortition pool for the given application.
/// @dev Reverts if sortition does not exits for the application.
/// @param _application Address of the application.
/// @return The sum of all registered operators' weights in the pool.
/// Reverts if sortition pool for the application does not exist.
function getSortitionPoolWeight(address _application)
public
view
returns (uint256)
{
return
AbstractSortitionPool(getSortitionPool(_application)).totalWeight();
}
/// @notice Creates new sortition pool for the application.
/// @dev Have to be implemented by keep factory to call desired sortition
/// pool factory.
/// @param _application Address of the application.
/// @return Address of the created sortition pool contract.
function newSortitionPool(address _application) internal returns (address);
/// @notice Gets bonded sortition pool of specific application for the
/// operator.
/// @dev Reverts if the operator is not registered for the application.
/// @param _operator Operator's address.
/// @param _application Customer application address.
/// @return Bonded sortition pool.
function getSortitionPoolForOperator(
address _operator,
address _application
) internal view returns (AbstractSortitionPool) {
require(
isOperatorRegistered(_operator, _application),
"Operator not registered for the application"
);
return AbstractSortitionPool(candidatesPools[_application]);
}
}
// File: solidity/contracts/GroupSelectionSeed.sol
/**
▓▓▌ ▓▓ ▐▓▓ ▓▓▓▓▓▓▓▓▓▓▌▐▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓ ▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓ ▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▄
▓▓▓▓▓▓▓▓▓▓ ▓▓▓▓▓▓▓▓▓▓▌▐▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓ ▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓ ▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓
▓▓▓▓▓▓ ▓▓▓▓▓▓▓▀ ▐▓▓▓▓▓▓ ▐▓▓▓▓▓ ▓▓▓▓▓▓ ▓▓▓▓▓ ▐▓▓▓▓▓▌ ▐▓▓▓▓▓▓
▓▓▓▓▓▓▄▄▓▓▓▓▓▓▓▀ ▐▓▓▓▓▓▓▄▄▄▄ ▓▓▓▓▓▓▄▄▄▄ ▐▓▓▓▓▓▌ ▐▓▓▓▓▓▓
▓▓▓▓▓▓▓▓▓▓▓▓▓▀ ▐▓▓▓▓▓▓▓▓▓▓ ▓▓▓▓▓▓▓▓▓▓▌ ▐▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓
▓▓▓▓▓▓▀▀▓▓▓▓▓▓▄ ▐▓▓▓▓▓▓▀▀▀▀ ▓▓▓▓▓▓▀▀▀▀ ▐▓▓▓▓▓▓▓▓▓▓▓▓▓▓▀
▓▓▓▓▓▓ ▀▓▓▓▓▓▓▄ ▐▓▓▓▓▓▓ ▓▓▓▓▓ ▓▓▓▓▓▓ ▓▓▓▓▓ ▐▓▓▓▓▓▌
▓▓▓▓▓▓▓▓▓▓ █▓▓▓▓▓▓▓▓▓ ▐▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓ ▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓ ▓▓▓▓▓▓▓▓▓▓
▓▓▓▓▓▓▓▓▓▓ ▓▓▓▓▓▓▓▓▓▓ ▐▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓ ▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓ ▓▓▓▓▓▓▓▓▓▓
Trust math, not hardware.
*/
pragma solidity 0.5.17;
import "@keep-network/keep-core/contracts/IRandomBeacon.sol";
import "openzeppelin-solidity/contracts/math/SafeMath.sol";
import "openzeppelin-solidity/contracts/utils/ReentrancyGuard.sol";
contract GroupSelectionSeed is IRandomBeaconConsumer, ReentrancyGuard {
using SafeMath for uint256;
IRandomBeacon randomBeacon;
// Gas required for a callback from the random beacon. The value specifies
// gas required to call `__beaconCallback` function in the worst-case
// scenario with all the checks and maximum allowed uint256 relay entry as
// a callback parameter.
uint256 public constant callbackGas = 30000;
// Random beacon sends back callback surplus to the requestor. It may also
// decide to send additional request subsidy fee. What's more, it may happen
// that the beacon is busy and we will not refresh group selection seed from
// the beacon. We accumulate all funds received from the beacon in the
// reseed pool and later use this pool to reseed using a public reseed
// function on a manual request at any moment.
uint256 public reseedPool;
uint256 public groupSelectionSeed;
constructor(address _randomBeacon) public {
randomBeacon = IRandomBeacon(_randomBeacon);
// Initial value before the random beacon updates the seed.
// https://www.wolframalpha.com/input/?i=pi+to+78+digits
groupSelectionSeed = 31415926535897932384626433832795028841971693993751058209749445923078164062862;
}
/// @notice Adds any received funds to the reseed pool.
function() external payable {
reseedPool += msg.value;
}
/// @notice Sets a new group selection seed value.
/// @dev The function is expected to be called in a callback by the random
/// beacon.
/// @param _relayEntry Beacon output.
function __beaconCallback(uint256 _relayEntry) external onlyRandomBeacon {
groupSelectionSeed = _relayEntry;
}
/// @notice Gets a fee estimate for a new random entry.
/// @return Uint256 estimate.
function newEntryFeeEstimate() public view returns (uint256) {
return randomBeacon.entryFeeEstimate(callbackGas);
}
/// @notice Calculates the fee requestor has to pay to reseed the factory
/// for signer selection. Depending on how much value is stored in the
/// reseed pool and the price of a new relay entry, returned value may vary.
function newGroupSelectionSeedFee() public view returns (uint256) {
uint256 beaconFee = randomBeacon.entryFeeEstimate(callbackGas);
return beaconFee <= reseedPool ? 0 : beaconFee.sub(reseedPool);
}
/// @notice Reseeds the value used for a signer selection. Requires enough
/// payment to be passed. The required payment can be calculated using
/// reseedFee function. Factory is automatically triggering reseeding after
/// opening a new keep but the reseed can be also triggered at any moment
/// using this function.
function requestNewGroupSelectionSeed() public payable nonReentrant {
reseedPool = reseedPool.add(msg.value);
uint256 beaconFee = randomBeacon.entryFeeEstimate(callbackGas);
require(reseedPool >= beaconFee, "Not enough funds to trigger reseed");
reseedPool = reseedPool.sub(beaconFee);
(bool success, bytes memory returnData) = requestRelayEntry(beaconFee);
if (!success) {
revert(string(returnData));
}
}
/// @notice Updates group selection seed.
/// @dev The main goal of this function is to request the random beacon to
/// generate a new random number. The beacon generates the number asynchronously
/// and will call a callback function when the number is ready. In the meantime
/// we update current group selection seed to a new value using a hash function.
/// In case of the random beacon request failure this function won't revert
/// but add beacon payment to factory's reseed pool.
function newGroupSelectionSeed() internal {
// Calculate new group selection seed based on the current seed.
// We added address of the factory as a key to calculate value different
// than sortition pool RNG will, so we don't end up selecting almost
// identical group.
groupSelectionSeed = uint256(
keccak256(abi.encodePacked(groupSelectionSeed, address(this)))
);
// Call the random beacon to get a random group selection seed.
(bool success, ) = requestRelayEntry(msg.value);
if (!success) {
reseedPool += msg.value;
}
}
/// @notice Requests for a relay entry using the beacon payment provided as
/// the parameter.
function requestRelayEntry(uint256 payment)
internal
returns (bool, bytes memory)
{
return
address(randomBeacon).call.value(payment)(
abi.encodeWithSignature(
"requestRelayEntry(address,uint256)",
address(this),
callbackGas
)
);
}
/// @notice Checks if the caller is the random beacon.
/// @dev Throws an error if called by any account other than the random beacon.
modifier onlyRandomBeacon() {
require(
address(randomBeacon) == msg.sender,
"Caller is not the random beacon"
);
_;
}
}
// File: @keep-network/keep-core/contracts/IRandomBeacon.sol
/**
▓▓▌ ▓▓ ▐▓▓ ▓▓▓▓▓▓▓▓▓▓▌▐▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓ ▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓ ▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▄
▓▓▓▓▓▓▓▓▓▓ ▓▓▓▓▓▓▓▓▓▓▌▐▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓ ▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓ ▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓
▓▓▓▓▓▓ ▓▓▓▓▓▓▓▀ ▐▓▓▓▓▓▓ ▐▓▓▓▓▓ ▓▓▓▓▓▓ ▓▓▓▓▓ ▐▓▓▓▓▓▌ ▐▓▓▓▓▓▓
▓▓▓▓▓▓▄▄▓▓▓▓▓▓▓▀ ▐▓▓▓▓▓▓▄▄▄▄ ▓▓▓▓▓▓▄▄▄▄ ▐▓▓▓▓▓▌ ▐▓▓▓▓▓▓
▓▓▓▓▓▓▓▓▓▓▓▓▓▀ ▐▓▓▓▓▓▓▓▓▓▓ ▓▓▓▓▓▓▓▓▓▓▌ ▐▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓
▓▓▓▓▓▓▀▀▓▓▓▓▓▓▄ ▐▓▓▓▓▓▓▀▀▀▀ ▓▓▓▓▓▓▀▀▀▀ ▐▓▓▓▓▓▓▓▓▓▓▓▓▓▓▀
▓▓▓▓▓▓ ▀▓▓▓▓▓▓▄ ▐▓▓▓▓▓▓ ▓▓▓▓▓ ▓▓▓▓▓▓ ▓▓▓▓▓ ▐▓▓▓▓▓▌
▓▓▓▓▓▓▓▓▓▓ █▓▓▓▓▓▓▓▓▓ ▐▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓ ▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓ ▓▓▓▓▓▓▓▓▓▓
▓▓▓▓▓▓▓▓▓▓ ▓▓▓▓▓▓▓▓▓▓ ▐▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓ ▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓ ▓▓▓▓▓▓▓▓▓▓
Trust math, not hardware.
*/
pragma solidity 0.5.17;
/// @title Keep Random Beacon
///
/// @notice Keep Random Beacon generates verifiable randomness that is resistant
/// to bad actors both in the relay network and on the anchoring blockchain.
interface IRandomBeacon {
/// @notice Event emitted for each new relay entry generated. It contains
/// request ID allowing to associate the generated relay entry with relay
/// request created previously with `requestRelayEntry` function. Event is
/// emitted no matter if callback was executed or not.
///
/// @param requestId Relay request ID for which entry was generated.
/// @param entry Generated relay entry.
event RelayEntryGenerated(uint256 requestId, uint256 entry);
/// @notice Provides the customer with an estimated entry fee in wei to use
/// in the request. The fee estimate is only valid for the transaction it is
/// called in, so the customer must make the request immediately after
/// obtaining the estimate. Insufficient payment will lead to the request
/// being rejected and the transaction reverted.
///
/// The customer may decide to provide more ether for an entry fee than
/// estimated by this function. This is especially helpful when callback gas
/// cost fluctuates. Any surplus between the passed fee and the actual cost
/// of producing an entry and executing a callback is returned back to the
/// customer.
/// @param callbackGas Gas required for the callback.
function entryFeeEstimate(uint256 callbackGas)
external
view
returns (uint256);
/// @notice Submits a request to generate a new relay entry. Executes
/// callback on the provided callback contract with the generated entry and
/// emits `RelayEntryGenerated(uint256 requestId, uint256 entry)` event.
/// Callback contract has to declare public `__beaconCallback(uint256)`
/// function that is going to be executed with the result, once ready.
/// It is recommended to implement `IRandomBeaconConsumer` interface to
/// ensure the correct callback function signature.
///
/// @dev Beacon does not support concurrent relay requests. No new requests
/// should be made while the beacon is already processing another request.
/// Requests made while the beacon is busy will be rejected and the
/// transaction reverted.
///
/// @param callbackContract Callback contract address. Callback is called
/// once a new relay entry has been generated. Must declare public
/// `__beaconCallback(uint256)` function. It is recommended to implement
/// `IRandomBeaconConsumer` interface to ensure the correct callback function
/// signature.
/// @param callbackGas Gas required for the callback.
/// The customer needs to ensure they provide a sufficient callback gas
/// to cover the gas fee of executing the callback. Any surplus is returned
/// to the customer. If the callback gas amount turns to be not enough to
/// execute the callback, callback execution is skipped.
/// @return An uint256 representing uniquely generated relay request ID
function requestRelayEntry(address callbackContract, uint256 callbackGas)
external
payable
returns (uint256);
/// @notice Submits a request to generate a new relay entry. Emits
/// `RelayEntryGenerated(uint256 requestId, uint256 entry)` event for the
/// generated entry.
///
/// @dev Beacon does not support concurrent relay requests. No new requests
/// should be made while the beacon is already processing another request.
/// Requests made while the beacon is busy will be rejected and the
/// transaction reverted.
///
/// @return An uint256 representing uniquely generated relay request ID
function requestRelayEntry() external payable returns (uint256);
}
/// @title Keep Random Beacon Consumer
///
/// @notice Receives Keep Random Beacon relay entries with `__beaconCallback`
/// function. Contract implementing this interface does not have to be the one
/// requesting relay entry but it is the one receiving the requested relay entry
/// once it is produced.
///
/// @dev Use this interface to indicate the contract receives relay entries from
/// the beacon and to ensure the correctness of callback function signature.
interface IRandomBeaconConsumer {
/// @notice Receives relay entry produced by Keep Random Beacon. This function
/// should be called only by Keep Random Beacon.
///
/// @param relayEntry Relay entry (random number) produced by Keep Random
/// Beacon.
function __beaconCallback(uint256 relayEntry) external;
}
// File: openzeppelin-solidity/contracts/utils/ReentrancyGuard.sol
pragma solidity ^0.5.0;
/**
* @dev Contract module that helps prevent reentrant calls to a function.
*
* Inheriting from `ReentrancyGuard` will make the `nonReentrant` modifier
* available, which can be aplied 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.
*/
contract ReentrancyGuard {
/// @dev counter to allow mutex lock with only one SSTORE operation
uint256 private _guardCounter;
constructor () internal {
// The counter starts at one to prevent changing it from zero to a non-zero
// value, which is a more expensive operation.
_guardCounter = 1;
}
/**
* @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() {
_guardCounter += 1;
uint256 localCounter = _guardCounter;
_;
require(localCounter == _guardCounter, "ReentrancyGuard: reentrant call");
}
}
// File: @keep-network/sortition-pools/contracts/BondedSortitionPoolFactory.sol
pragma solidity 0.5.17;
import "./BondedSortitionPool.sol";
import "./api/IBonding.sol";
import "./api/IStaking.sol";
/// @title Bonded Sortition Pool Factory
/// @notice Factory for the creation of new bonded sortition pools.
contract BondedSortitionPoolFactory {
/// @notice Creates a new bonded sortition pool instance.
/// @return Address of the new bonded sortition pool contract instance.
function createSortitionPool(
IStaking stakingContract,
IBonding bondingContract,
uint256 minimumStake,
uint256 initialMinimumBond,
uint256 poolWeightDivisor
) public returns (address) {
return
address(
new BondedSortitionPool(
stakingContract,
bondingContract,
minimumStake,
initialMinimumBond,
poolWeightDivisor,
msg.sender
)
);
}
}
// File: @keep-network/sortition-pools/contracts/BondedSortitionPool.sol
pragma solidity 0.5.17;
import "./AbstractSortitionPool.sol";
import "./RNG.sol";
import "./api/IStaking.sol";
import "./api/IBonding.sol";
import "./DynamicArray.sol";
/// @title Bonded Sortition Pool
/// @notice A logarithmic data structure used to store the pool of eligible
/// operators weighted by their stakes. It allows to select a group of operators
/// based on the provided pseudo-random seed and bonding requirements.
/// @dev Keeping pool up to date cannot be done eagerly as proliferation of
/// privileged customers could be used to perform DOS attacks by increasing the
/// cost of such updates. When a sortition pool prospectively selects an
/// operator, the selected operator’s eligibility status and weight needs to be
/// checked and, if necessary, updated in the sortition pool. If the changes
/// would be detrimental to the operator, the operator selection is performed
/// again with the updated input to ensure correctness.
/// The pool should specify a reasonable minimum bondable value for operators
/// trying to join the pool, to prevent griefing the selection.
contract BondedSortitionPool is AbstractSortitionPool {
using DynamicArray for DynamicArray.UintArray;
using DynamicArray for DynamicArray.AddressArray;
using RNG for RNG.State;
struct PoolParams {
IStaking stakingContract;
uint256 minimumStake;
IBonding bondingContract;
// Defines the minimum unbounded value the operator needs to have to be
// eligible to join and stay in the sortition pool. Operators not
// satisfying minimum bondable value are removed from the pool.
uint256 minimumBondableValue;
// Bond required from each operator for the currently pending group
// selection. If operator does not have at least this unbounded value,
// it is skipped during the selection.
uint256 requestedBond;
// The weight divisor in the pool can differ from the minimum stake
uint256 poolWeightDivisor;
address owner;
}
PoolParams poolParams;
constructor(
IStaking _stakingContract,
IBonding _bondingContract,
uint256 _minimumStake,
uint256 _minimumBondableValue,
uint256 _poolWeightDivisor,
address _poolOwner
) public {
require(_minimumStake > 0, "Minimum stake cannot be zero");
poolParams = PoolParams(
_stakingContract,
_minimumStake,
_bondingContract,
_minimumBondableValue,
0,
_poolWeightDivisor,
_poolOwner
);
}
/// @notice Selects a new group of operators of the provided size based on
/// the provided pseudo-random seed and bonding requirements. All operators
/// in the group are unique.
///
/// If there are not enough operators in a pool to form a group or not
/// enough operators are eligible for work selection given the bonding
/// requirements, the function fails.
/// @param groupSize Size of the requested group
/// @param seed Pseudo-random number used to select operators to group
/// @param minimumStake The current minimum stake value
/// @param bondValue Size of the requested bond per operator
function selectSetGroup(
uint256 groupSize,
bytes32 seed,
uint256 minimumStake,
uint256 bondValue
) public returns (address[] memory) {
PoolParams memory params = initializeSelectionParams(
minimumStake,
bondValue
);
require(msg.sender == params.owner, "Only owner may select groups");
uint256 paramsPtr;
// solium-disable-next-line security/no-inline-assembly
assembly {
paramsPtr := params
}
return generalizedSelectGroup(groupSize, seed, paramsPtr, true);
}
/// @notice Sets the minimum bondable value required from the operator
/// so that it is eligible to be in the pool. The pool should specify
/// a reasonable minimum requirement for operators trying to join the pool
/// to prevent griefing group selection.
/// @param minimumBondableValue The minimum bondable value required from the
/// operator.
function setMinimumBondableValue(uint256 minimumBondableValue) public {
require(
msg.sender == poolParams.owner,
"Only owner may update minimum bond value"
);
poolParams.minimumBondableValue = minimumBondableValue;
}
/// @notice Returns the minimum bondable value required from the operator
/// so that it is eligible to be in the pool.
function getMinimumBondableValue() public view returns (uint256) {
return poolParams.minimumBondableValue;
}
function initializeSelectionParams(uint256 minimumStake, uint256 bondValue)
internal
returns (PoolParams memory params)
{
params = poolParams;
if (params.requestedBond != bondValue) {
params.requestedBond = bondValue;
}
if (params.minimumStake != minimumStake) {
params.minimumStake = minimumStake;
poolParams.minimumStake = minimumStake;
}
return params;
}
// Return the eligible weight of the operator,
// which may differ from the weight in the pool.
// Return 0 if ineligible.
function getEligibleWeight(address operator) internal view returns (uint256) {
address ownerAddress = poolParams.owner;
// Get the amount of bondable value available for this pool.
// We only care that this covers one single bond
// regardless of the weight of the operator in the pool.
uint256 bondableValue = poolParams.bondingContract.availableUnbondedValue(
operator,
ownerAddress,
address(this)
);
// Don't query stake if bond is insufficient.
if (bondableValue < poolParams.minimumBondableValue) {
return 0;
}
uint256 eligibleStake = poolParams.stakingContract.eligibleStake(
operator,
ownerAddress
);
// Weight = floor(eligibleStake / poolWeightDivisor)
// but only if eligibleStake >= minimumStake.
// Ethereum uint256 division performs implicit floor
// If eligibleStake < poolWeightDivisor, return 0 = ineligible.
if (eligibleStake < poolParams.minimumStake) {
return 0;
}
return (eligibleStake / poolParams.poolWeightDivisor);
}
function decideFate(
uint256 leaf,
DynamicArray.AddressArray memory, // `selected`, for future use
uint256 paramsPtr
) internal view returns (Fate memory) {
PoolParams memory params;
// solium-disable-next-line security/no-inline-assembly
assembly {
params := paramsPtr
}
address operator = leaf.operator();
uint256 leafWeight = leaf.weight();
if (!isLeafInitialized(leaf)) {
return Fate(Decision.Skip, 0);
}
address ownerAddress = params.owner;
// Get the amount of bondable value available for this pool.
// We only care that this covers one single bond
// regardless of the weight of the operator in the pool.
uint256 bondableValue = params.bondingContract.availableUnbondedValue(
operator,
ownerAddress,
address(this)
);
// If unbonded value is insufficient for the operator to be in the pool,
// delete the operator.
if (bondableValue < params.minimumBondableValue) {
return Fate(Decision.Delete, 0);
}
// If unbonded value is sufficient for the operator to be in the pool
// but it is not sufficient for the current selection, skip the operator.
if (bondableValue < params.requestedBond) {
return Fate(Decision.Skip, 0);
}
uint256 eligibleStake = params.stakingContract.eligibleStake(
operator,
ownerAddress
);
// Weight = floor(eligibleStake / poolWeightDivisor)
// Ethereum uint256 division performs implicit floor
uint256 eligibleWeight = eligibleStake / params.poolWeightDivisor;
if (eligibleWeight < leafWeight || eligibleStake < params.minimumStake) {
return Fate(Decision.Delete, 0);
}
return Fate(Decision.Select, 0);
}
}
// File: @keep-network/sortition-pools/contracts/api/IBonding.sol
pragma solidity 0.5.17;
interface IBonding {
// Gives the amount of ETH
// the `operator` has made available for bonding by the `bondCreator`.
// If the operator doesn't exist,
// or the bond creator isn't authorized,
// returns 0.
function availableUnbondedValue(
address operator,
address bondCreator,
address authorizedSortitionPool
) external view returns (uint256);
}
// File: @keep-network/sortition-pools/contracts/api/IStaking.sol
pragma solidity 0.5.17;
interface IStaking {
// Gives the amount of KEEP tokens staked by the `operator`
// eligible for work selection in the specified `operatorContract`.
//
// If the operator doesn't exist or hasn't finished initializing,
// or the operator contract hasn't been authorized for the operator,
// returns 0.
function eligibleStake(
address operator,
address operatorContract
) external view returns (uint256);
}
// File: @keep-network/sortition-pools/contracts/AbstractSortitionPool.sol
pragma solidity 0.5.17;
import "./GasStation.sol";
import "./RNG.sol";
import "./SortitionTree.sol";
import "./DynamicArray.sol";
import "./api/IStaking.sol";
/// @title Abstract Sortition Pool
/// @notice Abstract contract encapsulating common logic of all sortition pools.
/// @dev Inheriting implementations are expected to implement getEligibleWeight
/// function.
contract AbstractSortitionPool is SortitionTree, GasStation {
using Leaf for uint256;
using Position for uint256;
using DynamicArray for DynamicArray.UintArray;
using DynamicArray for DynamicArray.AddressArray;
using RNG for RNG.State;
enum Decision {
Select, // Add to the group, and use new seed
Skip, // Retry with same seed, skip this leaf
Delete, // Retry with same seed, delete this leaf
UpdateRetry, // Retry with same seed, update this leaf
UpdateSelect // Select and reseed, but also update this leaf
}
struct Fate {
Decision decision;
// The new weight of the leaf if Decision is Update*, otherwise 0
uint256 maybeWeight;
}
// Require 10 blocks after joining before the operator can be selected for
// a group. This reduces the degrees of freedom miners and other
// front-runners have in conducting pool-bumping attacks.
//
// We don't use the stack of empty leaves until we run out of space on the
// rightmost leaf (i.e. after 2 million operators have joined the pool).
// It means all insertions are at the right end, so one can't reorder
// operators already in the pool until the pool has been filled once.
// Because the index is calculated by taking the minimum number of required
// random bits, and seeing if it falls in the range of the total pool weight,
// the only scenarios where insertions on the right matter are if it crosses
// a power of two threshold for the total weight and unlocks another random
// bit, or if a random number that would otherwise be discarded happens to
// fall within that space.
uint256 constant INIT_BLOCKS = 10;
uint256 constant GAS_DEPOSIT_SIZE = 1;
/// @notice The number of blocks that must be mined before the operator who
// joined the pool is eligible for work selection.
function operatorInitBlocks() public pure returns (uint256) {
return INIT_BLOCKS;
}
// Return whether the operator is eligible for the pool.
function isOperatorEligible(address operator) public view returns (bool) {
return getEligibleWeight(operator) > 0;
}
// Return whether the operator is present in the pool.
function isOperatorInPool(address operator) public view returns (bool) {
return getFlaggedLeafPosition(operator) != 0;
}
// Return whether the operator's weight in the pool
// matches their eligible weight.
function isOperatorUpToDate(address operator) public view returns (bool) {
return getEligibleWeight(operator) == getPoolWeight(operator);
}
// Returns whether the operator has passed the initialization blocks period
// to be eligible for the work selection. Reverts if the operator is not in
// the pool.
function isOperatorInitialized(address operator) public view returns (bool) {
require(isOperatorInPool(operator), "Operator is not in the pool");
uint256 flaggedPosition = getFlaggedLeafPosition(operator);
uint256 leafPosition = flaggedPosition.unsetFlag();
uint256 leaf = leaves[leafPosition];
return isLeafInitialized(leaf);
}
// Return the weight of the operator in the pool,
// which may or may not be out of date.
function getPoolWeight(address operator) public view returns (uint256) {
uint256 flaggedPosition = getFlaggedLeafPosition(operator);
if (flaggedPosition == 0) {
return 0;
} else {
uint256 leafPosition = flaggedPosition.unsetFlag();
uint256 leafWeight = leaves[leafPosition].weight();
return leafWeight;
}
}
// Add an operator to the pool,
// reverting if the operator is already present.
function joinPool(address operator) public {
uint256 eligibleWeight = getEligibleWeight(operator);
require(eligibleWeight > 0, "Operator not eligible");
depositGas(operator);
insertOperator(operator, eligibleWeight);
}
// Update the operator's weight if present and eligible,
// or remove from the pool if present and ineligible.
function updateOperatorStatus(address operator) public {
uint256 eligibleWeight = getEligibleWeight(operator);
uint256 inPoolWeight = getPoolWeight(operator);
require(eligibleWeight != inPoolWeight, "Operator already up to date");
if (eligibleWeight == 0) {
removeOperator(operator);
releaseGas(operator);
} else {
updateOperator(operator, eligibleWeight);
}
}
function generalizedSelectGroup(
uint256 groupSize,
bytes32 seed,
// This uint256 is actually a void pointer.
// We can't pass a SelectionParams,
// because the implementation of the SelectionParams struct
// can vary between different concrete sortition pool implementations.
//
// Whatever SelectionParams struct is used by the concrete contract
// should be created in the `selectGroup`/`selectSetGroup` function,
// then coerced into a uint256 to be passed into this function.
// The paramsPtr is then passed to the `decideFate` implementation
// which can coerce it back into the concrete SelectionParams.
// This allows `generalizedSelectGroup`
// to work with any desired eligibility logic.
uint256 paramsPtr,
bool noDuplicates
) internal returns (address[] memory) {
uint256 _root = root;
bool rootChanged = false;
DynamicArray.AddressArray memory selected;
selected = DynamicArray.addressArray(groupSize);
RNG.State memory rng;
rng = RNG.initialize(seed, _root.sumWeight(), groupSize);
while (selected.array.length < groupSize) {
rng.generateNewIndex();
(uint256 leafPosition, uint256 startingIndex) = pickWeightedLeaf(
rng.currentMappedIndex,
_root
);
uint256 leaf = leaves[leafPosition];
address operator = leaf.operator();
uint256 leafWeight = leaf.weight();
Fate memory fate = decideFate(leaf, selected, paramsPtr);
if (fate.decision == Decision.Select) {
selected.arrayPush(operator);
if (noDuplicates) {
rng.addSkippedInterval(startingIndex, leafWeight);
}
rng.reseed(seed, selected.array.length);
continue;
}
if (fate.decision == Decision.Skip) {
rng.addSkippedInterval(startingIndex, leafWeight);
continue;
}
if (fate.decision == Decision.Delete) {
// Update the RNG
rng.updateInterval(startingIndex, leafWeight, 0);
// Remove the leaf and update root
_root = removeLeaf(leafPosition, _root);
rootChanged = true;
// Remove the record of the operator's leaf and release gas
removeLeafPositionRecord(operator);
releaseGas(operator);
continue;
}
if (fate.decision == Decision.UpdateRetry) {
_root = setLeaf(leafPosition, leaf.setWeight(fate.maybeWeight), _root);
rootChanged = true;
rng.updateInterval(startingIndex, leafWeight, fate.maybeWeight);
continue;
}
if (fate.decision == Decision.UpdateSelect) {
_root = setLeaf(leafPosition, leaf.setWeight(fate.maybeWeight), _root);
rootChanged = true;
selected.arrayPush(operator);
rng.updateInterval(startingIndex, leafWeight, fate.maybeWeight);
if (noDuplicates) {
rng.addSkippedInterval(startingIndex, fate.maybeWeight);
}
rng.reseed(seed, selected.array.length);
continue;
}
}
if (rootChanged) {
root = _root;
}
return selected.array;
}
function isLeafInitialized(uint256 leaf) internal view returns (bool) {
uint256 createdAt = leaf.creationBlock();
return block.number > (createdAt + operatorInitBlocks());
}
// Return the eligible weight of the operator,
// which may differ from the weight in the pool.
// Return 0 if ineligible.
function getEligibleWeight(address operator) internal view returns (uint256);
function decideFate(
uint256 leaf,
DynamicArray.AddressArray memory selected,
uint256 paramsPtr
) internal view returns (Fate memory);
function gasDepositSize() internal pure returns (uint256) {
return GAS_DEPOSIT_SIZE;
}
}
// File: @keep-network/sortition-pools/contracts/RNG.sol
pragma solidity 0.5.17;
import "./Leaf.sol";
import "./Interval.sol";
import "./DynamicArray.sol";
library RNG {
using DynamicArray for DynamicArray.UintArray;
////////////////////////////////////////////////////////////////////////////
// Parameters for configuration
// How many bits a position uses per level of the tree;
// each branch of the tree contains 2**SLOT_BITS slots.
uint256 constant SLOT_BITS = 3;
////////////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////////
// Derived constants, do not touch
uint256 constant SLOT_COUNT = 2**SLOT_BITS;
uint256 constant WEIGHT_WIDTH = 256 / SLOT_COUNT;
////////////////////////////////////////////////////////////////////////////
struct State {
// RNG output
uint256 currentMappedIndex;
uint256 currentTruncatedIndex;
// The random bytes used to derive indices
bytes32 currentSeed;
// The full range of indices;
// generated random numbers are in [0, fullRange).
uint256 fullRange;
// The truncated range of indices;
// how many non-skipped indices are left to consider.
// Random indices are generated within this range,
// and mapped to the full range by skipping the specified intervals.
uint256 truncatedRange;
DynamicArray.UintArray skippedIntervals;
}
function initialize(
bytes32 seed,
uint256 range,
uint256 expectedSkippedCount
) internal view returns (State memory self) {
self = State(
0,
0,
seed,
range,
range,
DynamicArray.uintArray(expectedSkippedCount)
);
reseed(self, seed, 0);
return self;
}
function reseed(
State memory self,
bytes32 seed,
uint256 nonce
) internal view {
self.currentSeed = keccak256(
abi.encodePacked(seed, nonce, address(this), "reseed")
);
}
function retryIndex(State memory self) internal view {
uint256 truncatedIndex = self.currentTruncatedIndex;
if (self.currentTruncatedIndex < self.truncatedRange) {
self.currentMappedIndex = Interval.skip(
truncatedIndex,
self.skippedIntervals
);
} else {
generateNewIndex(self);
}
}
function updateInterval(
State memory self,
uint256 startIndex,
uint256 oldWeight,
uint256 newWeight
) internal pure {
int256 weightDiff = int256(newWeight) - int256(oldWeight);
uint256 effectiveStartIndex = startIndex + newWeight;
self.truncatedRange = uint256(int256(self.truncatedRange) + weightDiff);
self.fullRange = uint256(int256(self.fullRange) + weightDiff);
Interval.remapIndices(
effectiveStartIndex,
weightDiff,
self.skippedIntervals
);
}
function addSkippedInterval(
State memory self,
uint256 startIndex,
uint256 weight
) internal pure {
self.truncatedRange -= weight;
Interval.insert(self.skippedIntervals, Interval.make(startIndex, weight));
}
/// @notice Generate a new index based on the current seed,
/// without reseeding first.
/// This will result in the same truncated index as before
/// if it still fits in the current truncated range.
function generateNewIndex(State memory self) internal view {
uint256 _truncatedRange = self.truncatedRange;
require(_truncatedRange > 0, "Not enough operators in pool");
uint256 bits = bitsRequired(_truncatedRange);
uint256 truncatedIndex = truncate(bits, uint256(self.currentSeed));
while (truncatedIndex >= _truncatedRange) {
self.currentSeed = keccak256(
abi.encodePacked(self.currentSeed, address(this), "generate")
);
truncatedIndex = truncate(bits, uint256(self.currentSeed));
}
self.currentTruncatedIndex = truncatedIndex;
self.currentMappedIndex = Interval.skip(
truncatedIndex,
self.skippedIntervals
);
}
/// @notice Calculate how many bits are required
/// for an index in the range `[0 .. range-1]`.
///
/// @param range The upper bound of the desired range, exclusive.
///
/// @return uint The smallest number of bits
/// that can contain the number `range-1`.
function bitsRequired(uint256 range) internal pure returns (uint256) {
uint256 bits = WEIGHT_WIDTH - 1;
// Left shift by `bits`,
// so we have a 1 in the (bits + 1)th least significant bit
// and 0 in other bits.
// If this number is equal or greater than `range`,
// the range [0, range-1] fits in `bits` bits.
//
// Because we loop from high bits to low bits,
// we find the highest number of bits that doesn't fit the range,
// and return that number + 1.
while (1 << bits >= range) {
bits--;
}
return bits + 1;
}
/// @notice Truncate `input` to the `bits` least significant bits.
function truncate(uint256 bits, uint256 input)
internal
pure
returns (uint256)
{
return input & ((1 << bits) - 1);
}
/// @notice Get an index in the range `[0 .. range-1]`
/// and the new state of the RNG,
/// using the provided `state` of the RNG.
///
/// @param range The upper bound of the index, exclusive.
///
/// @param state The previous state of the RNG.
/// The initial state needs to be obtained
/// from a trusted randomness oracle (the random beacon),
/// or from a chain of earlier calls to `RNG.getIndex()`
/// on an originally trusted seed.
///
/// @dev Calculates the number of bits required for the desired range,
/// takes the least significant bits of `state`
/// and checks if the obtained index is within the desired range.
/// The original state is hashed with `keccak256` to get a new state.
/// If the index is outside the range,
/// the function retries until it gets a suitable index.
///
/// @return index A random integer between `0` and `range - 1`, inclusive.
///
/// @return newState The new state of the RNG.
/// When `getIndex()` is called one or more times,
/// care must be taken to always use the output `state`
/// of the most recent call as the input `state` of a subsequent call.
/// At the end of a transaction calling `RNG.getIndex()`,
/// the previous stored state must be overwritten with the latest output.
function getIndex(uint256 range, bytes32 state)
internal
view
returns (uint256, bytes32)
{
uint256 bits = bitsRequired(range);
bool found = false;
uint256 index = 0;
bytes32 newState = state;
while (!found) {
index = truncate(bits, uint256(newState));
newState = keccak256(abi.encodePacked(newState, address(this)));
if (index < range) {
found = true;
}
}
return (index, newState);
}
/// @notice Return an index corresponding to a new, unique leaf.
///
/// @dev Gets a new index in a truncated range
/// with the weights of all previously selected leaves subtracted.
/// This index is then mapped to the full range of possible indices,
/// skipping the ranges covered by previous leaves.
///
/// @param range The full range in which the unique index should be.
///
/// @param state The RNG state.
///
/// @param previousLeaves List of indices and weights
/// corresponding to the _first_ index of each previously selected leaf,
/// and the weight of the same leaf.
/// An index number `i` is a starting index of leaf `o`
/// if querying for index `i` in the sortition pool returns `o`,
/// but querying for `i-1` returns a different leaf.
/// This list REALLY needs to be sorted from smallest to largest.
///
/// @param sumPreviousWeights The sum of the weights of previous leaves.
/// Could be calculated from `previousLeafWeights`
/// but providing it explicitly makes the function a bit simpler.
///
/// @return uniqueIndex An index in [0, range) that does not overlap
/// any of the previousLeaves,
/// as determined by the range [index, index + weight).
function getUniqueIndex(
uint256 range,
bytes32 state,
uint256[] memory previousLeaves,
uint256 sumPreviousWeights
) internal view returns (uint256 uniqueIndex, bytes32 newState) {
// Get an index in the truncated range.
// The truncated range covers only new leaves,
// but has to be mapped to the actual range of indices.
uint256 truncatedRange = range - sumPreviousWeights;
uint256 truncatedIndex;
(truncatedIndex, newState) = getIndex(truncatedRange, state);
// Map the truncated index to the available unique indices.
uniqueIndex = Interval.skip(
truncatedIndex,
DynamicArray.convert(previousLeaves)
);
return (uniqueIndex, newState);
}
}
// File: @keep-network/sortition-pools/contracts/DynamicArray.sol
pragma solidity 0.5.17;
library DynamicArray {
// The in-memory dynamic Array is implemented
// by recording the amount of allocated memory
// separately from the length of the array.
// This gives us a perfectly normal in-memory array
// with all the behavior we're used to,
// but also makes O(1) `push` operations possible
// by expanding into the preallocated memory.
//
// When we run out of preallocated memory when trying to `push`,
// we allocate twice as much and copy the array over.
// With linear allocation costs this would amortize to O(1)
// but with EVM allocations being actually quadratic
// the real performance is a very technical O(N).
// Nonetheless, this is reasonably performant in practice.
//
// A dynamic array can be useful
// even when you aren't dealing with an unknown number of items.
// Because the array tracks the allocated space
// separately from the number of stored items,
// you can push items into the dynamic array
// and iterate over the currently present items
// without tracking their number yourself,
// or using a special null value for empty elements.
//
// Because Solidity doesn't really have useful safety features,
// only enough superficial inconveniences
// to lull yourself into a false sense of security,
// dynamic arrays require a bit of care to handle appropriately.
//
// First of all,
// dynamic arrays must not be created or modified manually.
// Use `uintArray(length)`, or `convert(existingArray)`
// which will perform a safe and efficient conversion for you.
// This also applies to storage;
// in-memory dynamic arrays are for efficient in-memory operations only,
// and it is unnecessary to store dynamic arrays.
// Use a regular `uint256[]` instead.
// The contents of `array` may be written like `dynamicArray.array[i] = x`
// but never reassign the `array` pointer itself
// nor mess with `allocatedMemory` in any way whatsoever.
// If you fail to follow these precautions,
// dragons inhabiting the no-man's-land
// between the array as it's seen by Solidity
// and the next thing allocated after it
// will be unleashed to wreak havoc upon your memory buffers.
//
// Second,
// because the `array` may be reassigned when pushing,
// the following pattern is unsafe:
// ```
// UintArray dynamicArray;
// uint256 len = dynamicArray.array.length;
// uint256[] danglingPointer = dynamicArray.array;
// danglingPointer[0] = x;
// dynamicArray.push(y);
// danglingPointer[0] = z;
// uint256 surprise = danglingPointer[len];
// ```
// After the above code block,
// `dynamicArray.array[0]` may be either `x` or `z`,
// and `surprise` may be `y` or out of bounds.
// This will not share your address space with a malevolent agent of chaos,
// but it will cause entirely avoidable scratchings of the head.
//
// Dynamic arrays should be safe to use like ordinary arrays
// if you always refer to the array field of the dynamic array
// when reading or writing values:
// ```
// UintArray dynamicArray;
// uint256 len = dynamicArray.array.length;
// dynamicArray.array[0] = x;
// dynamicArray.push(y);
// dynamicArray.array[0] = z;
// uint256 notSurprise = dynamicArray.array[len];
// ```
// After this code `notSurprise` is reliably `y`,
// and `dynamicArray.array[0]` is `z`.
struct UintArray {
// XXX: Do not modify this value.
// In fact, do not even read it.
// There is never a legitimate reason to do anything with this value.
// She is quiet and wishes to be left alone.
// The silent vigil of `allocatedMemory`
// is the only thing standing between your contract
// and complete chaos in its memory.
// Respect her wish or face the monstrosities she is keeping at bay.
uint256 allocatedMemory;
// Unlike her sharp and vengeful sister,
// `array` is safe to use normally
// for anything you might do with a normal `uint256[]`.
// Reads and loops will check bounds,
// and writing in individual indices like `myArray.array[i] = x`
// is perfectly fine.
// No curse will befall you as long as you obey this rule:
//
// XXX: Never try to replace her or separate her from her sister
// by writing down the accursed words
// `myArray.array = anotherArray` or `lonelyArray = myArray.array`.
//
// If you do, your cattle will be diseased,
// your children will be led astray in the woods,
// and your memory will be silently overwritten.
// Instead, give her a friend with
// `mySecondArray = convert(anotherArray)`,
// and call her by her family name first.
// She will recognize your respect
// and ward your memory against corruption.
uint256[] array;
}
struct AddressArray {
uint256 allocatedMemory;
address[] array;
}
/// @notice Create an empty dynamic array,
/// with preallocated memory for up to `length` elements.
/// @dev Knowing or estimating the preallocated length in advance
/// helps avoid frequent early allocations when filling the array.
/// @param length The number of items to preallocate space for.
/// @return A new dynamic array.
function uintArray(uint256 length) internal pure returns (UintArray memory) {
uint256[] memory array = _allocateUints(length);
return UintArray(length, array);
}
function addressArray(uint256 length)
internal
pure
returns (AddressArray memory)
{
address[] memory array = _allocateAddresses(length);
return AddressArray(length, array);
}
/// @notice Convert an existing non-dynamic array into a dynamic array.
/// @dev The dynamic array is created
/// with allocated memory equal to the length of the array.
/// @param array The array to convert.
/// @return A new dynamic array,
/// containing the contents of the argument `array`.
function convert(uint256[] memory array)
internal
pure
returns (UintArray memory)
{
return UintArray(array.length, array);
}
function convert(address[] memory array)
internal
pure
returns (AddressArray memory)
{
return AddressArray(array.length, array);
}
/// @notice Push `item` into the dynamic array.
/// @dev This function will be safe
/// as long as you haven't scorned either of the sisters.
/// If you have, the dragons will be released
/// to wreak havoc upon your memory.
/// A spell to dispel the curse exists,
/// but a sacred vow prohibits it from being shared
/// with those who do not know how to discover it on their own.
/// @param self The dynamic array to push into;
/// after the call it will be mutated in place to contain the item,
/// allocating more memory behind the scenes if necessary.
/// @param item The item you wish to push into the array.
function arrayPush(UintArray memory self, uint256 item) internal pure {
uint256 length = self.array.length;
uint256 allocLength = self.allocatedMemory;
// The dynamic array is full so we need to allocate more first.
// We check for >= instead of ==
// so that we can put the require inside the conditional,
// reducing the gas costs of `push` slightly.
if (length >= allocLength) {
// This should never happen if `allocatedMemory` isn't messed with.
require(length == allocLength, "Array length exceeds allocation");
// Allocate twice the original array length,
// then copy the contents over.
uint256 newMemory = length * 2;
uint256[] memory newArray = _allocateUints(newMemory);
_copy(newArray, self.array);
self.array = newArray;
self.allocatedMemory = newMemory;
}
// We have enough free memory so we can push into the array.
_push(self.array, item);
}
function arrayPush(AddressArray memory self, address item) internal pure {
uint256 length = self.array.length;
uint256 allocLength = self.allocatedMemory;
if (length >= allocLength) {
require(length == allocLength, "Array length exceeds allocation");
uint256 newMemory = length * 2;
address[] memory newArray = _allocateAddresses(newMemory);
_copy(newArray, self.array);
self.array = newArray;
self.allocatedMemory = newMemory;
}
_push(self.array, item);
}
/// @notice Pop the last item from the dynamic array,
/// removing it and decrementing the array length in place.
/// @dev This makes the dragons happy
/// as they have more space to roam.
/// Thus they have no desire to escape and ravage your buffers.
/// @param self The array to pop from.
/// @return item The previously last element in the array.
function arrayPop(UintArray memory self)
internal
pure
returns (uint256 item)
{
uint256[] memory array = self.array;
uint256 length = array.length;
require(length > 0, "Can't pop from empty array");
return _pop(array);
}
function arrayPop(AddressArray memory self)
internal
pure
returns (address item)
{
address[] memory array = self.array;
uint256 length = array.length;
require(length > 0, "Can't pop from empty array");
return _pop(array);
}
/// @notice Allocate an empty array,
/// reserving enough memory to safely store `length` items.
/// @dev The array starts with zero length,
/// but the allocated buffer has space for `length` words.
/// "What be beyond the bounds of `array`?" you may ask.
/// The answer is: dragons.
/// But do not worry,
/// for `Array.allocatedMemory` protects your EVM from them.
function _allocateUints(uint256 length)
private
pure
returns (uint256[] memory array)
{
// Calculate the size of the allocated block.
// Solidity arrays without a specified constant length
// (i.e. `uint256[]` instead of `uint256[8]`)
// store the length at the first memory position
// and the contents of the array after it,
// so we add 1 to the length to account for this.
uint256 inMemorySize = (length + 1) * 0x20;
// solium-disable-next-line security/no-inline-assembly
assembly {
// Get some free memory
array := mload(0x40)
// Write a zero in the length field;
// we set the length elsewhere
// if we store anything in the array immediately.
// When we allocate we only know how many words we reserve,
// not how many actually get written.
mstore(array, 0)
// Move the free memory pointer
// to the end of the allocated block.
mstore(0x40, add(array, inMemorySize))
}
return array;
}
function _allocateAddresses(uint256 length)
private
pure
returns (address[] memory array)
{
uint256 inMemorySize = (length + 1) * 0x20;
// solium-disable-next-line security/no-inline-assembly
assembly {
array := mload(0x40)
mstore(array, 0)
mstore(0x40, add(array, inMemorySize))
}
return array;
}
/// @notice Unsafe function to copy the contents of one array
/// into an empty initialized array
/// with sufficient free memory available.
function _copy(uint256[] memory dest, uint256[] memory src) private pure {
// solium-disable-next-line security/no-inline-assembly
assembly {
let length := mload(src)
let byteLength := mul(length, 0x20)
// Store the resulting length of the array.
mstore(dest, length)
// Maintain a write pointer
// for the current write location in the destination array
// by adding the 32 bytes for the array length
// to the starting location.
let writePtr := add(dest, 0x20)
// Stop copying when the write pointer reaches
// the length of the source array.
// We can track the endpoint either from the write or read pointer.
// This uses the write pointer
// because that's the way it was done
// in the (public domain) code I stole this from.
let end := add(writePtr, byteLength)
for {
// Initialize a read pointer to the start of the source array,
// 32 bytes into its memory.
let readPtr := add(src, 0x20)
} lt(writePtr, end) {
// Increase both pointers by 32 bytes each iteration.
writePtr := add(writePtr, 0x20)
readPtr := add(readPtr, 0x20)
} {
// Write the source array into the dest memory
// 32 bytes at a time.
mstore(writePtr, mload(readPtr))
}
}
}
function _copy(address[] memory dest, address[] memory src) private pure {
// solium-disable-next-line security/no-inline-assembly
assembly {
let length := mload(src)
let byteLength := mul(length, 0x20)
mstore(dest, length)
let writePtr := add(dest, 0x20)
let end := add(writePtr, byteLength)
for {
let readPtr := add(src, 0x20)
} lt(writePtr, end) {
writePtr := add(writePtr, 0x20)
readPtr := add(readPtr, 0x20)
} {
mstore(writePtr, mload(readPtr))
}
}
}
/// @notice Unsafe function to push past the limit of an array.
/// Only use with preallocated free memory.
function _push(uint256[] memory array, uint256 item) private pure {
// solium-disable-next-line security/no-inline-assembly
assembly {
// Get array length
let length := mload(array)
let newLength := add(length, 1)
// Calculate how many bytes the array takes in memory,
// including the length field.
// This is equal to 32 * the incremented length.
let arraySize := mul(0x20, newLength)
// Calculate the first memory position after the array
let nextPosition := add(array, arraySize)
// Store the item in the available position
mstore(nextPosition, item)
// Increment array length
mstore(array, newLength)
}
}
function _push(address[] memory array, address item) private pure {
// solium-disable-next-line security/no-inline-assembly
assembly {
let length := mload(array)
let newLength := add(length, 1)
let arraySize := mul(0x20, newLength)
let nextPosition := add(array, arraySize)
mstore(nextPosition, item)
mstore(array, newLength)
}
}
function _pop(uint256[] memory array) private pure returns (uint256 item) {
uint256 length = array.length;
// solium-disable-next-line security/no-inline-assembly
assembly {
// Calculate the memory position of the last element
let lastPosition := add(array, mul(length, 0x20))
// Retrieve the last item
item := mload(lastPosition)
// Decrement array length
mstore(array, sub(length, 1))
}
return item;
}
function _pop(address[] memory array) private pure returns (address item) {
uint256 length = array.length;
// solium-disable-next-line security/no-inline-assembly
assembly {
let lastPosition := add(array, mul(length, 0x20))
item := mload(lastPosition)
mstore(array, sub(length, 1))
}
return item;
}
}
// File: @keep-network/sortition-pools/contracts/GasStation.sol
pragma solidity 0.5.17;
contract GasStation {
mapping(address => mapping(uint256 => uint256)) gasDeposits;
function depositGas(address addr) internal {
setDeposit(addr, 1);
}
function releaseGas(address addr) internal {
setDeposit(addr, 0);
}
function setDeposit(address addr, uint256 val) internal {
for (uint256 i = 0; i < gasDepositSize(); i++) {
gasDeposits[addr][i] = val;
}
}
function gasDepositSize() internal pure returns (uint256);
}
// File: @keep-network/sortition-pools/contracts/SortitionTree.sol
pragma solidity 0.5.17;
import "./StackLib.sol";
import "./Branch.sol";
import "./Position.sol";
import "./Leaf.sol";
contract SortitionTree {
using StackLib for uint256[];
using Branch for uint256;
using Position for uint256;
using Leaf for uint256;
////////////////////////////////////////////////////////////////////////////
// Parameters for configuration
// How many bits a position uses per level of the tree;
// each branch of the tree contains 2**SLOT_BITS slots.
uint256 constant SLOT_BITS = 3;
uint256 constant LEVELS = 7;
////////////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////////
// Derived constants, do not touch
uint256 constant SLOT_COUNT = 2**SLOT_BITS;
uint256 constant SLOT_WIDTH = 256 / SLOT_COUNT;
uint256 constant SLOT_MAX = (2**SLOT_WIDTH) - 1;
uint256 constant POOL_CAPACITY = SLOT_COUNT**LEVELS;
////////////////////////////////////////////////////////////////////////////
// implicit tree
// root 8
// level2 64
// level3 512
// level4 4k
// level5 32k
// level6 256k
// level7 2M
uint256 root;
mapping(uint256 => mapping(uint256 => uint256)) branches;
mapping(uint256 => uint256) leaves;
// the flagged (see setFlag() and unsetFlag() in Position.sol) positions
// of all operators present in the pool
mapping(address => uint256) flaggedLeafPosition;
// the leaf after the rightmost occupied leaf of each stack
uint256 rightmostLeaf;
// the empty leaves in each stack
// between 0 and the rightmost occupied leaf
uint256[] emptyLeaves;
constructor() public {
root = 0;
rightmostLeaf = 0;
}
// checks if operator is already registered in the pool
function isOperatorRegistered(address operator) public view returns (bool) {
return getFlaggedLeafPosition(operator) != 0;
}
// Sum the number of operators in each trunk
function operatorsInPool() public view returns (uint256) {
// Get the number of leaves that might be occupied;
// if `rightmostLeaf` equals `firstLeaf()` the tree must be empty,
// otherwise the difference between these numbers
// gives the number of leaves that may be occupied.
uint256 nPossiblyUsedLeaves = rightmostLeaf;
// Get the number of empty leaves
// not accounted for by the `rightmostLeaf`
uint256 nEmptyLeaves = emptyLeaves.getSize();
return (nPossiblyUsedLeaves - nEmptyLeaves);
}
function totalWeight() public view returns (uint256) {
return root.sumWeight();
}
function insertOperator(address operator, uint256 weight) internal {
require(
!isOperatorRegistered(operator),
"Operator is already registered in the pool"
);
uint256 position = getEmptyLeafPosition();
// Record the block the operator was inserted in
uint256 theLeaf = Leaf.make(operator, block.number, weight);
root = setLeaf(position, theLeaf, root);
// Without position flags,
// the position 0x000000 would be treated as empty
flaggedLeafPosition[operator] = position.setFlag();
}
function removeOperator(address operator) internal {
uint256 flaggedPosition = getFlaggedLeafPosition(operator);
require(flaggedPosition != 0, "Operator is not registered in the pool");
uint256 unflaggedPosition = flaggedPosition.unsetFlag();
root = removeLeaf(unflaggedPosition, root);
removeLeafPositionRecord(operator);
}
function updateOperator(address operator, uint256 weight) internal {
require(
isOperatorRegistered(operator),
"Operator is not registered in the pool"
);
uint256 flaggedPosition = getFlaggedLeafPosition(operator);
uint256 unflaggedPosition = flaggedPosition.unsetFlag();
updateLeaf(unflaggedPosition, weight);
}
function removeLeafPositionRecord(address operator) internal {
flaggedLeafPosition[operator] = 0;
}
function getFlaggedLeafPosition(address operator)
internal
view
returns (uint256)
{
return flaggedLeafPosition[operator];
}
function removeLeaf(uint256 position, uint256 _root)
internal
returns (uint256)
{
uint256 rightmostSubOne = rightmostLeaf - 1;
bool isRightmost = position == rightmostSubOne;
uint256 newRoot = setLeaf(position, 0, _root);
if (isRightmost) {
rightmostLeaf = rightmostSubOne;
} else {
emptyLeaves.stackPush(position);
}
return newRoot;
}
function updateLeaf(uint256 position, uint256 weight) internal {
uint256 oldLeaf = leaves[position];
if (oldLeaf.weight() != weight) {
uint256 newLeaf = oldLeaf.setWeight(weight);
root = setLeaf(position, newLeaf, root);
}
}
function setLeaf(
uint256 position,
uint256 theLeaf,
uint256 _root
) internal returns (uint256) {
uint256 childSlot;
uint256 treeNode;
uint256 newNode;
uint256 nodeWeight = theLeaf.weight();
// set leaf
leaves[position] = theLeaf;
uint256 parent = position;
// set levels 7 to 2
for (uint256 level = LEVELS; level >= 2; level--) {
childSlot = parent.slot();
parent = parent.parent();
treeNode = branches[level][parent];
newNode = treeNode.setSlot(childSlot, nodeWeight);
branches[level][parent] = newNode;
nodeWeight = newNode.sumWeight();
}
// set level Root
childSlot = parent.slot();
return _root.setSlot(childSlot, nodeWeight);
}
function pickWeightedLeaf(uint256 index, uint256 _root)
internal
view
returns (uint256 leafPosition, uint256 leafFirstIndex)
{
uint256 currentIndex = index;
uint256 currentNode = _root;
uint256 currentPosition = 0;
uint256 currentSlot;
require(index < currentNode.sumWeight(), "Index exceeds weight");
// get root slot
(currentSlot, currentIndex) = currentNode.pickWeightedSlot(currentIndex);
// get slots from levels 2 to 7
for (uint256 level = 2; level <= LEVELS; level++) {
currentPosition = currentPosition.child(currentSlot);
currentNode = branches[level][currentPosition];
(currentSlot, currentIndex) = currentNode.pickWeightedSlot(currentIndex);
}
// get leaf position
leafPosition = currentPosition.child(currentSlot);
// get the first index of the leaf
// This works because the last weight returned from `pickWeightedSlot()`
// equals the "overflow" from getting the current slot.
leafFirstIndex = index - currentIndex;
}
function getEmptyLeafPosition() internal returns (uint256) {
uint256 rLeaf = rightmostLeaf;
bool spaceOnRight = (rLeaf + 1) < POOL_CAPACITY;
if (spaceOnRight) {
rightmostLeaf = rLeaf + 1;
return rLeaf;
} else {
bool emptyLeavesInStack = leavesInStack();
require(emptyLeavesInStack, "Pool is full");
return emptyLeaves.stackPop();
}
}
function leavesInStack() internal view returns (bool) {
return emptyLeaves.getSize() > 0;
}
}
// File: @keep-network/sortition-pools/contracts/StackLib.sol
pragma solidity 0.5.17;
library StackLib {
function stackPeek(uint256[] storage _array) internal view returns (uint256) {
require(_array.length > 0, "No value to peek, array is empty");
return (_array[_array.length - 1]);
}
function stackPush(uint256[] storage _array, uint256 _element) public {
_array.push(_element);
}
function stackPop(uint256[] storage _array) internal returns (uint256) {
require(_array.length > 0, "No value to pop, array is empty");
uint256 value = _array[_array.length - 1];
_array.length -= 1;
return value;
}
function getSize(uint256[] storage _array) internal view returns (uint256) {
return _array.length;
}
}
// File: @keep-network/sortition-pools/contracts/Branch.sol
pragma solidity 0.5.17;
/// @notice The implicit 8-ary trees of the sortition pool
/// rely on packing 8 "slots" of 32-bit values into each uint256.
/// The Branch library permits efficient calculations on these slots.
library Branch {
////////////////////////////////////////////////////////////////////////////
// Parameters for configuration
// How many bits a position uses per level of the tree;
// each branch of the tree contains 2**SLOT_BITS slots.
uint256 constant SLOT_BITS = 3;
////////////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////////
// Derived constants, do not touch
uint256 constant SLOT_COUNT = 2**SLOT_BITS;
uint256 constant SLOT_WIDTH = 256 / SLOT_COUNT;
uint256 constant LAST_SLOT = SLOT_COUNT - 1;
uint256 constant SLOT_MAX = (2**SLOT_WIDTH) - 1;
////////////////////////////////////////////////////////////////////////////
/// @notice Calculate the right shift required
/// to make the 32 least significant bits of an uint256
/// be the bits of the `position`th slot
/// when treating the uint256 as a uint32[8].
///
/// @dev Not used for efficiency reasons,
/// but left to illustrate the meaning of a common pattern.
/// I wish solidity had macros, even C macros.
function slotShift(uint256 position) internal pure returns (uint256) {
return position * SLOT_WIDTH;
}
/// @notice Return the `position`th slot of the `node`,
/// treating `node` as a uint32[32].
function getSlot(uint256 node, uint256 position)
internal
pure
returns (uint256)
{
uint256 shiftBits = position * SLOT_WIDTH;
// Doing a bitwise AND with `SLOT_MAX`
// clears all but the 32 least significant bits.
// Because of the right shift by `slotShift(position)` bits,
// those 32 bits contain the 32 bits in the `position`th slot of `node`.
return (node >> shiftBits) & SLOT_MAX;
}
/// @notice Return `node` with the `position`th slot set to zero.
function clearSlot(uint256 node, uint256 position)
internal
pure
returns (uint256)
{
uint256 shiftBits = position * SLOT_WIDTH;
// Shifting `SLOT_MAX` left by `slotShift(position)` bits
// gives us a number where all bits of the `position`th slot are set,
// and all other bits are unset.
//
// Using a bitwise NOT on this number,
// we get a uint256 where all bits are set
// except for those of the `position`th slot.
//
// Bitwise ANDing the original `node` with this number
// sets the bits of `position`th slot to zero,
// leaving all other bits unchanged.
return node & ~(SLOT_MAX << shiftBits);
}
/// @notice Return `node` with the `position`th slot set to `weight`.
///
/// @param weight The weight of of the node.
/// Safely truncated to a 32-bit number,
/// but this should never be called with an overflowing weight regardless.
function setSlot(
uint256 node,
uint256 position,
uint256 weight
) internal pure returns (uint256) {
uint256 shiftBits = position * SLOT_WIDTH;
// Clear the `position`th slot like in `clearSlot()`.
uint256 clearedNode = node & ~(SLOT_MAX << shiftBits);
// Bitwise AND `weight` with `SLOT_MAX`
// to clear all but the 32 least significant bits.
//
// Shift this left by `slotShift(position)` bits
// to obtain a uint256 with all bits unset
// except in the `position`th slot
// which contains the 32-bit value of `weight`.
uint256 shiftedWeight = (weight & SLOT_MAX) << shiftBits;
// When we bitwise OR these together,
// all other slots except the `position`th one come from the left argument,
// and the `position`th gets filled with `weight` from the right argument.
return clearedNode | shiftedWeight;
}
/// @notice Calculate the summed weight of all slots in the `node`.
function sumWeight(uint256 node) internal pure returns (uint256 sum) {
sum = node & SLOT_MAX;
// Iterate through each slot
// by shifting `node` right in increments of 32 bits,
// and adding the 32 least significant bits to the `sum`.
uint256 newNode = node >> SLOT_WIDTH;
while (newNode > 0) {
sum += (newNode & SLOT_MAX);
newNode = newNode >> SLOT_WIDTH;
}
return sum;
}
/// @notice Pick a slot in `node` that corresponds to `index`.
/// Treats the node like an array of virtual stakers,
/// the number of virtual stakers in each slot corresponding to its weight,
/// and picks which slot contains the `index`th virtual staker.
///
/// @dev Requires that `index` be lower than `sumWeight(node)`.
/// However, this is not enforced for performance reasons.
/// If `index` exceeds the permitted range,
/// `pickWeightedSlot()` returns the rightmost slot
/// and an excessively high `newIndex`.
///
/// @return slot The slot of `node` containing the `index`th virtual staker.
///
/// @return newIndex The index of the `index`th virtual staker of `node`
/// within the returned slot.
function pickWeightedSlot(uint256 node, uint256 index)
internal
pure
returns (uint256 slot, uint256 newIndex)
{
newIndex = index;
uint256 newNode = node;
uint256 currentSlotWeight = newNode & SLOT_MAX;
while (newIndex >= currentSlotWeight) {
newIndex -= currentSlotWeight;
slot++;
newNode = newNode >> SLOT_WIDTH;
currentSlotWeight = newNode & SLOT_MAX;
}
return (slot, newIndex);
}
}
// File: @keep-network/sortition-pools/contracts/Position.sol
pragma solidity 0.5.17;
library Position {
////////////////////////////////////////////////////////////////////////////
// Parameters for configuration
// How many bits a position uses per level of the tree;
// each branch of the tree contains 2**SLOT_BITS slots.
uint256 constant SLOT_BITS = 3;
////////////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////////
// Derived constants, do not touch
uint256 constant SLOT_POINTER_MAX = (2**SLOT_BITS) - 1;
uint256 constant LEAF_FLAG = 1 << 255;
////////////////////////////////////////////////////////////////////////////
// Return the last 3 bits of a position number,
// corresponding to its slot in its parent
function slot(uint256 a) internal pure returns (uint256) {
return a & SLOT_POINTER_MAX;
}
// Return the parent of a position number
function parent(uint256 a) internal pure returns (uint256) {
return a >> SLOT_BITS;
}
// Return the location of the child of a at the given slot
function child(uint256 a, uint256 s) internal pure returns (uint256) {
return (a << SLOT_BITS) | (s & SLOT_POINTER_MAX); // slot(s)
}
// Return the uint p as a flagged position uint:
// the least significant 21 bits contain the position
// and the 22nd bit is set as a flag
// to distinguish the position 0x000000 from an empty field.
function setFlag(uint256 p) internal pure returns (uint256) {
return p | LEAF_FLAG;
}
// Turn a flagged position into an unflagged position
// by removing the flag at the 22nd least significant bit.
//
// We shouldn't _actually_ need this
// as all position-manipulating code should ignore non-position bits anyway
// but it's cheap to call so might as well do it.
function unsetFlag(uint256 p) internal pure returns (uint256) {
return p & (~LEAF_FLAG);
}
}
// File: @keep-network/sortition-pools/contracts/Leaf.sol
pragma solidity 0.5.17;
library Leaf {
////////////////////////////////////////////////////////////////////////////
// Parameters for configuration
// How many bits a position uses per level of the tree;
// each branch of the tree contains 2**SLOT_BITS slots.
uint256 constant SLOT_BITS = 3;
////////////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////////
// Derived constants, do not touch
uint256 constant SLOT_COUNT = 2**SLOT_BITS;
uint256 constant SLOT_WIDTH = 256 / SLOT_COUNT;
uint256 constant SLOT_MAX = (2**SLOT_WIDTH) - 1;
uint256 constant WEIGHT_WIDTH = SLOT_WIDTH;
uint256 constant WEIGHT_MAX = SLOT_MAX;
uint256 constant BLOCKHEIGHT_WIDTH = 96 - WEIGHT_WIDTH;
uint256 constant BLOCKHEIGHT_MAX = (2**BLOCKHEIGHT_WIDTH) - 1;
////////////////////////////////////////////////////////////////////////////
function make(
address _operator,
uint256 _creationBlock,
uint256 _weight
) internal pure returns (uint256) {
// Converting a bytesX type into a larger type
// adds zero bytes on the right.
uint256 op = uint256(bytes32(bytes20(_operator)));
// Bitwise AND the weight to erase
// all but the 32 least significant bits
uint256 wt = _weight & WEIGHT_MAX;
// Erase all but the 64 least significant bits,
// then shift left by 32 bits to make room for the weight
uint256 cb = (_creationBlock & BLOCKHEIGHT_MAX) << WEIGHT_WIDTH;
// Bitwise OR them all together to get
// [address operator || uint64 creationBlock || uint32 weight]
return (op | cb | wt);
}
function operator(uint256 leaf) internal pure returns (address) {
// Converting a bytesX type into a smaller type
// truncates it on the right.
return address(bytes20(bytes32(leaf)));
}
/// @notice Return the block number the leaf was created in.
function creationBlock(uint256 leaf) internal pure returns (uint256) {
return ((leaf >> WEIGHT_WIDTH) & BLOCKHEIGHT_MAX);
}
function weight(uint256 leaf) internal pure returns (uint256) {
// Weight is stored in the 32 least significant bits.
// Bitwise AND ensures that we only get the contents of those bits.
return (leaf & WEIGHT_MAX);
}
function setWeight(uint256 leaf, uint256 newWeight)
internal
pure
returns (uint256)
{
return ((leaf & ~WEIGHT_MAX) | (newWeight & WEIGHT_MAX));
}
}
// File: @keep-network/sortition-pools/contracts/Interval.sol
pragma solidity 0.5.17;
import "./Leaf.sol";
import "./DynamicArray.sol";
library Interval {
using DynamicArray for DynamicArray.UintArray;
////////////////////////////////////////////////////////////////////////////
// Parameters for configuration
// How many bits a position uses per level of the tree;
// each branch of the tree contains 2**SLOT_BITS slots.
uint256 constant SLOT_BITS = 3;
////////////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////////
// Derived constants, do not touch
uint256 constant SLOT_COUNT = 2**SLOT_BITS;
uint256 constant SLOT_WIDTH = 256 / SLOT_COUNT;
uint256 constant SLOT_MAX = (2**SLOT_WIDTH) - 1;
uint256 constant WEIGHT_WIDTH = SLOT_WIDTH;
uint256 constant WEIGHT_MAX = SLOT_MAX;
uint256 constant START_INDEX_WIDTH = WEIGHT_WIDTH;
uint256 constant START_INDEX_MAX = WEIGHT_MAX;
uint256 constant START_INDEX_SHIFT = WEIGHT_WIDTH;
////////////////////////////////////////////////////////////////////////////
// Interval stores information about a selected interval
// inside a single uint256 in a manner similar to Leaf
// but optimized for use within group selection
//
// The information stored consists of:
// - weight
// - starting index
function make(uint256 startingIndex, uint256 weight)
internal
pure
returns (uint256)
{
uint256 idx = (startingIndex & START_INDEX_MAX) << START_INDEX_SHIFT;
uint256 wt = weight & WEIGHT_MAX;
return (idx | wt);
}
function opWeight(uint256 op) internal pure returns (uint256) {
return (op & WEIGHT_MAX);
}
// Return the starting index of the interval
function index(uint256 a) internal pure returns (uint256) {
return ((a >> WEIGHT_WIDTH) & START_INDEX_MAX);
}
function setIndex(uint256 op, uint256 i) internal pure returns (uint256) {
uint256 shiftedIndex = ((i & START_INDEX_MAX) << WEIGHT_WIDTH);
return (op & (~(START_INDEX_MAX << WEIGHT_WIDTH))) | shiftedIndex;
}
function insert(DynamicArray.UintArray memory intervals, uint256 interval)
internal
pure
{
uint256 tempInterval = interval;
for (uint256 i = 0; i < intervals.array.length; i++) {
uint256 thisInterval = intervals.array[i];
// We can compare the raw underlying uint256 values
// because the starting index is stored
// in the most significant nonzero bits.
if (tempInterval < thisInterval) {
intervals.array[i] = tempInterval;
tempInterval = thisInterval;
}
}
intervals.arrayPush(tempInterval);
}
function skip(uint256 truncatedIndex, DynamicArray.UintArray memory intervals)
internal
pure
returns (uint256 mappedIndex)
{
mappedIndex = truncatedIndex;
for (uint256 i = 0; i < intervals.array.length; i++) {
uint256 interval = intervals.array[i];
// If the index is greater than the starting index of the `i`th leaf,
// we need to skip that leaf.
if (mappedIndex >= index(interval)) {
// Add the weight of this previous leaf to the index,
// ensuring that we skip the leaf.
mappedIndex += Leaf.weight(interval);
} else {
break;
}
}
return mappedIndex;
}
/// @notice Recalculate the starting indices of the previousLeaves
/// when an interval is removed or added at the specified index.
/// @dev Applies weightDiff to each starting index in previousLeaves
/// that exceeds affectedStartingIndex.
/// @param affectedStartingIndex The starting index of the interval.
/// @param weightDiff The difference in weight;
/// negative for a deleted interval,
/// positive for an added interval.
/// @param previousLeaves The starting indices and weights
/// of the previously selected leaves.
/// @return The starting indices of the previous leaves
/// in a tree with the affected interval updated.
function remapIndices(
uint256 affectedStartingIndex,
int256 weightDiff,
DynamicArray.UintArray memory previousLeaves
) internal pure {
uint256 nPreviousLeaves = previousLeaves.array.length;
for (uint256 i = 0; i < nPreviousLeaves; i++) {
uint256 interval = previousLeaves.array[i];
uint256 startingIndex = index(interval);
// If index is greater than the index of the affected interval,
// update the starting index by the weight change.
if (startingIndex > affectedStartingIndex) {
uint256 newIndex = uint256(int256(startingIndex) + weightDiff);
previousLeaves.array[i] = setIndex(interval, newIndex);
}
}
}
}
// File: @keep-network/keep-core/contracts/KeepRegistry.sol
pragma solidity 0.5.17;
/// @title KeepRegistry
/// @notice Governance owned registry of approved contracts and roles.
contract KeepRegistry {
enum ContractStatus {New, Approved, Disabled}
// Governance role is to enable recovery from key compromise by rekeying
// other roles. Also, it can disable operator contract panic buttons
// permanently.
address public governance;
// Registry Keeper maintains approved operator contracts. Each operator
// contract must be approved before it can be authorized by a staker or
// used by a service contract.
address public registryKeeper;
// Each operator contract has a Panic Button which can disable malicious
// or malfunctioning contract that have been previously approved by the
// Registry Keeper.
//
// New operator contract added to the registry has a default panic button
// value assigned (defaultPanicButton). Panic button for each operator
// contract can be later updated by Governance to individual value.
//
// It is possible to disable panic button for individual contract by
// setting the panic button to zero address. In such case, operator contract
// can not be disabled and is permanently approved in the registry.
mapping(address => address) public panicButtons;
// Default panic button for each new operator contract added to the
// registry. Can be later updated for each contract.
address public defaultPanicButton;
// Each service contract has a Operator Contract Upgrader whose purpose
// is to manage operator contracts for that specific service contract.
// The Operator Contract Upgrader can add new operator contracts to the
// service contract’s operator contract list, and deprecate old ones.
mapping(address => address) public operatorContractUpgraders;
// Operator contract may have a Service Contract Upgrader whose purpose is
// to manage service contracts for that specific operator contract.
// Service Contract Upgrader can add and remove service contracts
// from the list of service contracts approved to work with the operator
// contract. List of service contracts is maintained in the operator
// contract and is optional - not every operator contract needs to have
// a list of service contracts it wants to cooperate with.
mapping(address => address) public serviceContractUpgraders;
// The registry of operator contracts
mapping(address => ContractStatus) public operatorContracts;
event OperatorContractApproved(address operatorContract);
event OperatorContractDisabled(address operatorContract);
event GovernanceUpdated(address governance);
event RegistryKeeperUpdated(address registryKeeper);
event DefaultPanicButtonUpdated(address defaultPanicButton);
event OperatorContractPanicButtonDisabled(address operatorContract);
event OperatorContractPanicButtonUpdated(
address operatorContract,
address panicButton
);
event OperatorContractUpgraderUpdated(
address serviceContract,
address upgrader
);
event ServiceContractUpgraderUpdated(
address operatorContract,
address keeper
);
modifier onlyGovernance() {
require(governance == msg.sender, "Not authorized");
_;
}
modifier onlyRegistryKeeper() {
require(registryKeeper == msg.sender, "Not authorized");
_;
}
modifier onlyPanicButton(address _operatorContract) {
address panicButton = panicButtons[_operatorContract];
require(panicButton != address(0), "Panic button disabled");
require(panicButton == msg.sender, "Not authorized");
_;
}
modifier onlyForNewContract(address _operatorContract) {
require(
isNewOperatorContract(_operatorContract),
"Not a new operator contract"
);
_;
}
modifier onlyForApprovedContract(address _operatorContract) {
require(
isApprovedOperatorContract(_operatorContract),
"Not an approved operator contract"
);
_;
}
constructor() public {
governance = msg.sender;
registryKeeper = msg.sender;
defaultPanicButton = msg.sender;
}
function setGovernance(address _governance) public onlyGovernance {
governance = _governance;
emit GovernanceUpdated(governance);
}
function setRegistryKeeper(address _registryKeeper) public onlyGovernance {
registryKeeper = _registryKeeper;
emit RegistryKeeperUpdated(registryKeeper);
}
function setDefaultPanicButton(address _panicButton) public onlyGovernance {
defaultPanicButton = _panicButton;
emit DefaultPanicButtonUpdated(defaultPanicButton);
}
function setOperatorContractPanicButton(
address _operatorContract,
address _panicButton
) public onlyForApprovedContract(_operatorContract) onlyGovernance {
require(
panicButtons[_operatorContract] != address(0),
"Disabled panic button cannot be updated"
);
require(
_panicButton != address(0),
"Panic button must be non-zero address"
);
panicButtons[_operatorContract] = _panicButton;
emit OperatorContractPanicButtonUpdated(
_operatorContract,
_panicButton
);
}
function disableOperatorContractPanicButton(address _operatorContract)
public
onlyForApprovedContract(_operatorContract)
onlyGovernance
{
require(
panicButtons[_operatorContract] != address(0),
"Panic button already disabled"
);
panicButtons[_operatorContract] = address(0);
emit OperatorContractPanicButtonDisabled(_operatorContract);
}
function setOperatorContractUpgrader(
address _serviceContract,
address _operatorContractUpgrader
) public onlyGovernance {
operatorContractUpgraders[_serviceContract] = _operatorContractUpgrader;
emit OperatorContractUpgraderUpdated(
_serviceContract,
_operatorContractUpgrader
);
}
function setServiceContractUpgrader(
address _operatorContract,
address _serviceContractUpgrader
) public onlyGovernance {
serviceContractUpgraders[_operatorContract] = _serviceContractUpgrader;
emit ServiceContractUpgraderUpdated(
_operatorContract,
_serviceContractUpgrader
);
}
function approveOperatorContract(address operatorContract)
public
onlyForNewContract(operatorContract)
onlyRegistryKeeper
{
operatorContracts[operatorContract] = ContractStatus.Approved;
panicButtons[operatorContract] = defaultPanicButton;
emit OperatorContractApproved(operatorContract);
}
function disableOperatorContract(address operatorContract)
public
onlyForApprovedContract(operatorContract)
onlyPanicButton(operatorContract)
{
operatorContracts[operatorContract] = ContractStatus.Disabled;
emit OperatorContractDisabled(operatorContract);
}
function isNewOperatorContract(address operatorContract)
public
view
returns (bool)
{
return operatorContracts[operatorContract] == ContractStatus.New;
}
function isApprovedOperatorContract(address operatorContract)
public
view
returns (bool)
{
return operatorContracts[operatorContract] == ContractStatus.Approved;
}
function operatorContractUpgraderFor(address _serviceContract)
public
view
returns (address)
{
return operatorContractUpgraders[_serviceContract];
}
function serviceContractUpgraderFor(address _operatorContract)
public
view
returns (address)
{
return serviceContractUpgraders[_operatorContract];
}
}
// File: @keep-network/keep-core/contracts/TokenStaking.sol
/**
▓▓▌ ▓▓ ▐▓▓ ▓▓▓▓▓▓▓▓▓▓▌▐▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓ ▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓ ▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▄
▓▓▓▓▓▓▓▓▓▓ ▓▓▓▓▓▓▓▓▓▓▌▐▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓ ▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓ ▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓
▓▓▓▓▓▓ ▓▓▓▓▓▓▓▀ ▐▓▓▓▓▓▓ ▐▓▓▓▓▓ ▓▓▓▓▓▓ ▓▓▓▓▓ ▐▓▓▓▓▓▌ ▐▓▓▓▓▓▓
▓▓▓▓▓▓▄▄▓▓▓▓▓▓▓▀ ▐▓▓▓▓▓▓▄▄▄▄ ▓▓▓▓▓▓▄▄▄▄ ▐▓▓▓▓▓▌ ▐▓▓▓▓▓▓
▓▓▓▓▓▓▓▓▓▓▓▓▓▀ ▐▓▓▓▓▓▓▓▓▓▓ ▓▓▓▓▓▓▓▓▓▓▌ ▐▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓
▓▓▓▓▓▓▀▀▓▓▓▓▓▓▄ ▐▓▓▓▓▓▓▀▀▀▀ ▓▓▓▓▓▓▀▀▀▀ ▐▓▓▓▓▓▓▓▓▓▓▓▓▓▓▀
▓▓▓▓▓▓ ▀▓▓▓▓▓▓▄ ▐▓▓▓▓▓▓ ▓▓▓▓▓ ▓▓▓▓▓▓ ▓▓▓▓▓ ▐▓▓▓▓▓▌
▓▓▓▓▓▓▓▓▓▓ █▓▓▓▓▓▓▓▓▓ ▐▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓ ▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓ ▓▓▓▓▓▓▓▓▓▓
▓▓▓▓▓▓▓▓▓▓ ▓▓▓▓▓▓▓▓▓▓ ▐▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓ ▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓ ▓▓▓▓▓▓▓▓▓▓
Trust math, not hardware.
*/
pragma solidity 0.5.17;
import "openzeppelin-solidity/contracts/token/ERC20/ERC20Burnable.sol";
import "openzeppelin-solidity/contracts/token/ERC20/SafeERC20.sol";
import "openzeppelin-solidity/contracts/math/SafeMath.sol";
import "./StakeDelegatable.sol";
import "./libraries/staking/MinimumStakeSchedule.sol";
import "./libraries/staking/GrantStaking.sol";
import "./libraries/staking/Locks.sol";
import "./libraries/staking/TopUps.sol";
import "./utils/PercentUtils.sol";
import "./utils/BytesLib.sol";
import "./Authorizations.sol";
import "./TokenStakingEscrow.sol";
import "./TokenSender.sol";
/// @title TokenStaking
/// @notice A token staking contract for a specified standard ERC20Burnable token.
/// A holder of the specified token can stake delegate its tokens to this contract
/// and recover the stake after undelegation period is over.
contract TokenStaking is Authorizations, StakeDelegatable {
using BytesLib for bytes;
using SafeMath for uint256;
using PercentUtils for uint256;
using SafeERC20 for ERC20Burnable;
using GrantStaking for GrantStaking.Storage;
using Locks for Locks.Storage;
using TopUps for TopUps.Storage;
event StakeDelegated(
address indexed owner,
address indexed operator
);
event OperatorStaked(
address indexed operator,
address indexed beneficiary,
address indexed authorizer,
uint256 value
);
event StakeOwnershipTransferred(
address indexed operator,
address indexed newOwner
);
event TopUpInitiated(address indexed operator, uint256 topUp);
event TopUpCompleted(address indexed operator, uint256 newAmount);
event Undelegated(address indexed operator, uint256 undelegatedAt);
event RecoveredStake(address operator);
event TokensSlashed(address indexed operator, uint256 amount);
event TokensSeized(address indexed operator, uint256 amount);
event StakeLocked(address indexed operator, address lockCreator, uint256 until);
event LockReleased(address indexed operator, address lockCreator);
event ExpiredLockReleased(address indexed operator, address lockCreator);
uint256 public deployedAt;
uint256 public initializationPeriod; // varies between mainnet and testnet
ERC20Burnable internal token;
TokenGrant internal tokenGrant;
TokenStakingEscrow internal escrow;
GrantStaking.Storage internal grantStaking;
Locks.Storage internal locks;
TopUps.Storage internal topUps;
uint256 internal constant twoWeeks = 1209600; // [sec]
uint256 internal constant twoMonths = 5184000; // [sec]
// 2020-04-28; the date of deploying KEEP token.
// TX: 0xea22d72bc7de4c82798df7194734024a1f2fd57b173d0e065864ff4e9d3dc014
uint256 internal constant minimumStakeScheduleStart = 1588042366;
/// @notice Creates a token staking contract for a provided Standard ERC20Burnable token.
/// @param _token KEEP token contract.
/// @param _tokenGrant KEEP token grant contract.
/// @param _escrow Escrow dedicated for this staking contract.
/// @param _registry Keep contract registry contract.
/// @param _initializationPeriod To avoid certain attacks on work selection, recently created
/// operators must wait for a specific period of time before being eligible for work selection.
constructor(
ERC20Burnable _token,
TokenGrant _tokenGrant,
TokenStakingEscrow _escrow,
KeepRegistry _registry,
uint256 _initializationPeriod
) Authorizations(_registry) public {
token = _token;
tokenGrant = _tokenGrant;
escrow = _escrow;
registry = _registry;
initializationPeriod = _initializationPeriod;
deployedAt = block.timestamp;
}
/// @notice Returns minimum amount of KEEP that allows sMPC cluster client to
/// participate in the Keep network. Expressed as number with 18-decimal places.
/// Initial minimum stake is higher than the final and lowered periodically based
/// on the amount of steps and the length of the minimum stake schedule in seconds.
function minimumStake() public view returns (uint256) {
return MinimumStakeSchedule.current(minimumStakeScheduleStart);
}
/// @notice Returns the current value of the undelegation period.
/// The staking contract guarantees that an undelegated operator’s stakes
/// will stay locked for a period of time after undelegation, and thus
/// available as collateral for any work the operator is engaged in.
/// The undelegation period is two weeks for the first two months and
/// two months after that.
function undelegationPeriod() public view returns(uint256) {
return block.timestamp < deployedAt.add(twoMonths) ? twoWeeks : twoMonths;
}
/// @notice Receives approval of token transfer and stakes the approved
/// amount or adds the approved amount to an existing delegation (a “top-up”).
/// In case of a top-up, it is expected that the operator stake is not
/// undelegated and that the top-up is performed from the same source of
/// tokens as the initial delegation. That is, if the tokens were delegated
/// from a grant, top-up has to be performed from the same grant. If the
/// delegation was done using liquid tokens, only liquid tokens from the
/// same owner can be used to top-up the stake.
/// Top-up can not be cancelled so it is important to be careful with the
/// amount of KEEP added to the stake.
/// @dev Requires that the provided token contract be the same one linked to
/// this contract.
/// @param _from The owner of the tokens who approved them to transfer.
/// @param _value Approved amount for the transfer and stake.
/// @param _token Token contract address.
/// @param _extraData Data for stake delegation. This byte array must have
/// the following values concatenated:
/// - Beneficiary address (20 bytes), ignored for a top-up
/// - Operator address (20 bytes)
/// - Authorizer address (20 bytes), ignored for a top-up
/// - Grant ID (32 bytes) - required only when called by TokenStakingEscrow
function receiveApproval(
address _from,
uint256 _value,
address _token,
bytes memory _extraData
) public {
require(ERC20Burnable(_token) == token, "Unrecognized token");
require(_extraData.length >= 60, "Corrupted delegation data");
// Transfer tokens to this contract.
token.safeTransferFrom(_from, address(this), _value);
address operator = _extraData.toAddress(20);
// See if there is an existing delegation for this operator...
if (operators[operator].packedParams.getCreationTimestamp() == 0) {
// If there is no existing delegation, delegate tokens using
// beneficiary and authorizer passed in _extraData.
delegate(_from, _value, operator, _extraData);
} else {
// If there is an existing delegation, top-up the stake.
topUp(_from, _value, operator, _extraData);
}
}
/// @notice Delegates tokens to a new operator using beneficiary and
/// authorizer passed in _extraData parameter.
/// @param _from The owner of the tokens who approved them to transfer.
/// @param _value Approved amount for the transfer and stake.
/// @param _operator The new operator address.
/// @param _extraData Data for stake delegation as passed to receiveApproval.
function delegate(
address _from,
uint256 _value,
address _operator,
bytes memory _extraData
) internal {
require(_value >= minimumStake(), "Less than the minimum stake");
address payable beneficiary = address(uint160(_extraData.toAddress(0)));
address authorizer = _extraData.toAddress(40);
operators[_operator] = Operator(
OperatorParams.pack(_value, block.timestamp, 0),
_from,
beneficiary,
authorizer
);
grantStaking.tryCapturingDelegationData(
tokenGrant,
address(escrow),
_from,
_operator,
_extraData
);
emit StakeDelegated(_from, _operator);
emit OperatorStaked(_operator, beneficiary, authorizer, _value);
}
/// @notice Performs top-up to an existing operator. Tokens added during
/// stake initialization period are immediatelly added to the stake and
/// stake initialization timer is reset to the current block. Tokens added
/// in a top-up after the stake initialization period is over are not
/// included in the operator stake until the initialization period for
/// a top-up passes and top-up is committed. Operator must not have the stake
/// undelegated. It is expected that the top-up is done from the same source
/// of tokens as the initial delegation. That is, if the tokens were
/// delegated from a grant, top-up has to be performed from the same grant.
/// If the delegation was done using liquid tokens, only liquid tokens from
/// the same owner can be used to top-up the stake.
/// Top-up can not be cancelled so it is important to be careful with the
/// amount of KEEP added to the stake.
/// @param _from The owner of the tokens who approved them to transfer.
/// @param _value Approved amount for the transfer and top-up to
/// an existing stake.
/// @param _operator The new operator address.
/// @param _extraData Data for stake delegation as passed to receiveApproval
function topUp(
address _from,
uint256 _value,
address _operator,
bytes memory _extraData
) internal {
// Top-up comes from a grant if it's been initiated from TokenGrantStake
// contract or if it's been initiated from TokenStakingEscrow by
// redelegation.
bool isFromGrant = address(tokenGrant.grantStakes(_operator)) == _from ||
address(escrow) == _from;
if (grantStaking.hasGrantDelegated(_operator)) {
// Operator has grant delegated. We need to see if the top-up
// is performed also from a grant.
require(isFromGrant, "Must be from a grant");
// If it is from a grant, we need to make sure it's from the same
// grant as the original delegation. We do not want to mix unlocking
// schedules.
uint256 previousGrantId = grantStaking.getGrantForOperator(_operator);
(, uint256 grantId) = grantStaking.tryCapturingDelegationData(
tokenGrant, address(escrow), _from, _operator, _extraData
);
require(grantId == previousGrantId, "Not the same grant");
} else {
// Operator has no grant delegated. We need to see if the top-up
// is performed from liquid tokens of the same owner.
require(!isFromGrant, "Must not be from a grant");
require(operators[_operator].owner == _from, "Not the same owner");
}
uint256 operatorParams = operators[_operator].packedParams;
if (!_isInitialized(operatorParams)) {
// If the stake is not yet initialized, we add tokens immediately
// but we also reset stake initialization time counter.
operators[_operator].packedParams = topUps.instantComplete(
_value, _operator, operatorParams, escrow
);
} else {
// If the stake is initialized, we do NOT add tokens immediately.
// We initiate the top-up and will add tokens to the stake only
// after the initialization period for a top-up passes.
topUps.initiate(_value, _operator, operatorParams, escrow);
}
}
/// @notice Commits pending top-up for the provided operator. If the top-up
/// did not pass the initialization period, the function fails.
/// @param _operator The operator with a pending top-up that is getting
/// committed.
function commitTopUp(address _operator) public {
operators[_operator].packedParams = topUps.commit(
_operator,
operators[_operator].packedParams,
initializationPeriod
);
}
/// @notice Cancels stake of tokens within the operator initialization period
/// without being subjected to the token lockup for the undelegation period.
/// This can be used to undo mistaken delegation to the wrong operator address.
/// @param _operator Address of the stake operator.
function cancelStake(address _operator) public {
address owner = operators[_operator].owner;
require(
msg.sender == owner ||
msg.sender == _operator ||
grantStaking.canUndelegate(_operator, tokenGrant),
"Not authorized"
);
uint256 operatorParams = operators[_operator].packedParams;
require(
!_isInitialized(operatorParams),
"Initialized stake"
);
uint256 amount = operatorParams.getAmount();
operators[_operator].packedParams = operatorParams.setAmount(0);
transferOrDeposit(owner, _operator, amount);
}
/// @notice Undelegates staked tokens. You will be able to recover your stake by calling
/// `recoverStake()` with operator address once undelegation period is over.
/// @param _operator Address of the stake operator.
function undelegate(address _operator) public {
undelegateAt(_operator, block.timestamp);
}
/// @notice Set an undelegation time for staked tokens.
/// Undelegation will begin at the specified timestamp.
/// You will be able to recover your stake by calling
/// `recoverStake()` with operator address once undelegation period is over.
/// @param _operator Address of the stake operator.
/// @param _undelegationTimestamp The timestamp undelegation is to start at.
function undelegateAt(
address _operator,
uint256 _undelegationTimestamp
) public {
require(
msg.sender == _operator ||
msg.sender == operators[_operator].owner ||
grantStaking.canUndelegate(_operator, tokenGrant),
"Not authorized"
);
uint256 oldParams = operators[_operator].packedParams;
require(
_undelegationTimestamp >= block.timestamp &&
_undelegationTimestamp > oldParams.getCreationTimestamp().add(initializationPeriod),
"Invalid timestamp"
);
uint256 existingUndelegationTimestamp = oldParams.getUndelegationTimestamp();
require(
// Undelegation not in progress OR
existingUndelegationTimestamp == 0 ||
// Undelegating sooner than previously set time OR
existingUndelegationTimestamp > _undelegationTimestamp ||
// We have already checked above that msg.sender is owner, grantee,
// or operator. Only owner and grantee are eligible to postpone the
// delegation so it is enough if we exclude operator here.
msg.sender != _operator,
"Operator may not postpone"
);
operators[_operator].packedParams = oldParams.setUndelegationTimestamp(
_undelegationTimestamp
);
emit Undelegated(_operator, _undelegationTimestamp);
}
/// @notice Recovers staked tokens and transfers them back to the owner.
/// Recovering tokens can only be performed when the operator finished
/// undelegating.
/// @param _operator Operator address.
function recoverStake(address _operator) public {
uint256 operatorParams = operators[_operator].packedParams;
require(
operatorParams.getUndelegationTimestamp() != 0,
"Not undelegated"
);
require(
_isUndelegatingFinished(operatorParams),
"Still undelegating"
);
require(
!isStakeLocked(_operator),
"Locked stake"
);
uint256 amount = operatorParams.getAmount();
// If there is a pending top-up, force-commit it before returning tokens.
amount = amount.add(topUps.cancel(_operator));
operators[_operator].packedParams = operatorParams.setAmount(0);
transferOrDeposit(operators[_operator].owner, _operator, amount);
emit RecoveredStake(_operator);
}
/// @notice Gets stake delegation info for the given operator.
/// @param _operator Operator address.
/// @return amount The amount of tokens the given operator delegated.
/// @return createdAt The time when the stake has been delegated.
/// @return undelegatedAt The time when undelegation has been requested.
/// If undelegation has not been requested, 0 is returned.
function getDelegationInfo(address _operator)
public view returns (uint256 amount, uint256 createdAt, uint256 undelegatedAt) {
return operators[_operator].packedParams.unpack();
}
/// @notice Locks given operator stake for the specified duration.
/// Locked stake may not be recovered until the lock expires or is released,
/// even if the normal undelegation period has passed.
/// Only previously authorized operator contract can lock the stake.
/// @param operator Operator address.
/// @param duration Lock duration in seconds.
function lockStake(
address operator,
uint256 duration
) public onlyApprovedOperatorContract(msg.sender) {
require(
isAuthorizedForOperator(operator, msg.sender),
"Not authorized"
);
uint256 operatorParams = operators[operator].packedParams;
require(
_isInitialized(operatorParams),
"Inactive stake"
);
require(
!_isUndelegating(operatorParams),
"Undelegating stake"
);
locks.lockStake(operator, duration);
}
/// @notice Removes a lock the caller had previously placed on the operator.
/// @dev Only for operator contracts.
/// To remove expired or disabled locks, use `releaseExpiredLocks`.
/// The authorization check ensures that the caller must have been able
/// to place a lock on the operator sometime in the past.
/// We don't need to check for current approval status of the caller
/// because unlocking stake cannot harm the operator
/// nor interfere with other operator contracts.
/// Therefore even disabled operator contracts may freely unlock stake.
/// @param operator Operator address.
function unlockStake(
address operator
) public {
require(
isAuthorizedForOperator(operator, msg.sender),
"Not authorized"
);
locks.releaseLock(operator);
}
/// @notice Removes the lock of the specified operator contract
/// if the lock has expired or the contract has been disabled.
/// @dev Necessary for removing locks placed by contracts
/// that have been disabled by the panic button.
/// Also applicable to prevent inadvertent DoS of `recoverStake`
/// if too many operator contracts have failed to clean up their locks.
function releaseExpiredLock(
address operator,
address operatorContract
) public {
locks.releaseExpiredLock(operator, operatorContract, address(this));
}
/// @notice Check whether the operator has any active locks
/// that haven't expired yet
/// and whose creators aren't disabled by the panic button.
function isStakeLocked(address operator) public view returns (bool) {
return locks.isStakeLocked(operator, address(this));
}
/// @notice Get the locks placed on the operator.
/// @return creators The addresses of operator contracts
/// that have placed a lock on the operator.
/// @return expirations The expiration times
/// of the locks placed on the operator.
function getLocks(address operator)
public
view
returns (address[] memory creators, uint256[] memory expirations) {
return locks.getLocks(operator);
}
/// @notice Slash provided token amount from every member in the misbehaved
/// operators array and burn 100% of all the tokens.
/// @param amountToSlash Token amount to slash from every misbehaved operator.
/// @param misbehavedOperators Array of addresses to seize the tokens from.
function slash(uint256 amountToSlash, address[] memory misbehavedOperators)
public
onlyApprovedOperatorContract(msg.sender) {
uint256 totalAmountToBurn;
address authoritySource = getAuthoritySource(msg.sender);
for (uint i = 0; i < misbehavedOperators.length; i++) {
address operator = misbehavedOperators[i];
require(authorizations[authoritySource][operator], "Not authorized");
uint256 operatorParams = operators[operator].packedParams;
require(
_isInitialized(operatorParams),
"Inactive stake"
);
require(
!_isStakeReleased(operator, operatorParams, msg.sender),
"Stake is released"
);
uint256 currentAmount = operatorParams.getAmount();
if (currentAmount < amountToSlash) {
totalAmountToBurn = totalAmountToBurn.add(currentAmount);
operators[operator].packedParams = operatorParams.setAmount(0);
emit TokensSlashed(operator, currentAmount);
} else {
totalAmountToBurn = totalAmountToBurn.add(amountToSlash);
operators[operator].packedParams = operatorParams.setAmount(
currentAmount.sub(amountToSlash)
);
emit TokensSlashed(operator, amountToSlash);
}
}
token.burn(totalAmountToBurn);
}
/// @notice Seize provided token amount from every member in the misbehaved
/// operators array. The tattletale is rewarded with 5% of the total seized
/// amount scaled by the reward adjustment parameter and the rest 95% is burned.
/// @param amountToSeize Token amount to seize from every misbehaved operator.
/// @param rewardMultiplier Reward adjustment in percentage. Min 1% and 100% max.
/// @param tattletale Address to receive the 5% reward.
/// @param misbehavedOperators Array of addresses to seize the tokens from.
function seize(
uint256 amountToSeize,
uint256 rewardMultiplier,
address tattletale,
address[] memory misbehavedOperators
) public onlyApprovedOperatorContract(msg.sender) {
uint256 totalAmountToBurn;
address authoritySource = getAuthoritySource(msg.sender);
for (uint i = 0; i < misbehavedOperators.length; i++) {
address operator = misbehavedOperators[i];
require(authorizations[authoritySource][operator], "Not authorized");
uint256 operatorParams = operators[operator].packedParams;
require(
_isInitialized(operatorParams),
"Inactive stake"
);
require(
!_isStakeReleased(operator, operatorParams, msg.sender),
"Stake is released"
);
uint256 currentAmount = operatorParams.getAmount();
if (currentAmount < amountToSeize) {
totalAmountToBurn = totalAmountToBurn.add(currentAmount);
operators[operator].packedParams = operatorParams.setAmount(0);
emit TokensSeized(operator, currentAmount);
} else {
totalAmountToBurn = totalAmountToBurn.add(amountToSeize);
operators[operator].packedParams = operatorParams.setAmount(
currentAmount.sub(amountToSeize)
);
emit TokensSeized(operator, amountToSeize);
}
}
uint256 tattletaleReward = (totalAmountToBurn.percent(5)).percent(rewardMultiplier);
token.safeTransfer(tattletale, tattletaleReward);
token.burn(totalAmountToBurn.sub(tattletaleReward));
}
/// @notice Allows the current staking relationship owner to transfer the
/// ownership to someone else.
/// @param operator Address of the stake operator.
/// @param newOwner Address of the new staking relationship owner.
function transferStakeOwnership(address operator, address newOwner) public {
require(msg.sender == operators[operator].owner, "Not authorized");
operators[operator].owner = newOwner;
emit StakeOwnershipTransferred(operator, newOwner);
}
/// @notice Gets the eligible stake balance of the specified address.
/// An eligible stake is a stake that passed the initialization period
/// and is not currently undelegating. Also, the operator had to approve
/// the specified operator contract.
///
/// Operator with a minimum required amount of eligible stake can join the
/// network and participate in new work selection.
///
/// @param _operator address of stake operator.
/// @param _operatorContract address of operator contract.
/// @return an uint256 representing the eligible stake balance.
function eligibleStake(
address _operator,
address _operatorContract
) public view returns (uint256 balance) {
uint256 operatorParams = operators[_operator].packedParams;
// To be eligible for work selection, the operator must:
// - have the operator contract authorized
// - have the stake initialized
// - must not be undelegating; keep in mind the `undelegatedAt` may be
// set to a time in the future, to schedule undelegation in advance.
// In this case the operator is still eligible until the timestamp
// `undelegatedAt`.
if (
isAuthorizedForOperator(_operator, _operatorContract) &&
_isInitialized(operatorParams) &&
!_isUndelegating(operatorParams)
) {
balance = operatorParams.getAmount();
}
}
/// @notice Gets the active stake balance of the specified address.
/// An active stake is a stake that passed the initialization period,
/// and may be in the process of undelegation
/// but has not been released yet,
/// either because the undelegation period is not over,
/// or because the operator contract has an active lock on the operator.
/// Also, the operator had to approve the specified operator contract.
///
/// The difference between eligible stake is that active stake does not make
/// the operator eligible for work selection but it may be still finishing
/// earlier work until the stake is released.
/// Operator with a minimum required
/// amount of active stake can join the network but cannot be selected to any
/// new work.
///
/// @param _operator address of stake operator.
/// @param _operatorContract address of operator contract.
/// @return an uint256 representing the eligible stake balance.
function activeStake(
address _operator,
address _operatorContract
) public view returns (uint256 balance) {
uint256 operatorParams = operators[_operator].packedParams;
if (
isAuthorizedForOperator(_operator, _operatorContract) &&
_isInitialized(operatorParams) &&
!_isStakeReleased(
_operator,
operatorParams,
_operatorContract
)
) {
balance = operatorParams.getAmount();
}
}
/// @notice Checks if the specified account has enough active stake to become
/// network operator and that the specified operator contract has been
/// authorized for potential slashing.
///
/// Having the required minimum of active stake makes the operator eligible
/// to join the network. If the active stake is not currently undelegating,
/// operator is also eligible for work selection.
///
/// @param staker Staker's address
/// @param operatorContract Operator contract's address
/// @return True if has enough active stake to participate in the network,
/// false otherwise.
function hasMinimumStake(
address staker,
address operatorContract
) public view returns(bool) {
return activeStake(staker, operatorContract) >= minimumStake();
}
/// @notice Is the operator with the given params initialized
function _isInitialized(uint256 _operatorParams)
internal view returns (bool) {
return block.timestamp > _operatorParams.getCreationTimestamp().add(initializationPeriod);
}
/// @notice Is the operator with the given params undelegating
function _isUndelegating(uint256 _operatorParams)
internal view returns (bool) {
uint256 undelegatedAt = _operatorParams.getUndelegationTimestamp();
return (undelegatedAt != 0) && (block.timestamp > undelegatedAt);
}
/// @notice Has the operator with the given params finished undelegating
function _isUndelegatingFinished(uint256 _operatorParams)
internal view returns (bool) {
uint256 undelegatedAt = _operatorParams.getUndelegationTimestamp();
return (undelegatedAt != 0) && (block.timestamp > undelegatedAt.add(undelegationPeriod()));
}
/// @notice Get whether the operator's stake is released
/// as far as the operator contract is concerned.
/// If the operator contract has a lock on the operator,
/// the operator's stake is be released when the lock expires.
/// Otherwise the stake is released when the operator finishes undelegating.
function _isStakeReleased(
address _operator,
uint256 _operatorParams,
address _operatorContract
) internal view returns (bool) {
return _isUndelegatingFinished(_operatorParams) &&
locks.isStakeReleased(_operator, _operatorContract);
}
function transferOrDeposit(
address _owner,
address _operator,
uint256 _amount
) internal {
if (grantStaking.hasGrantDelegated(_operator)) {
// For tokens staked from a grant, transfer them to the escrow.
TokenSender(address(token)).approveAndCall(
address(escrow),
_amount,
abi.encode(_operator, grantStaking.getGrantForOperator(_operator))
);
} else {
// For liquid tokens staked, transfer them straight to the owner.
token.safeTransfer(_owner, _amount);
}
}
}
// File: @keep-network/keep-core/contracts/Authorizations.sol
/**
▓▓▌ ▓▓ ▐▓▓ ▓▓▓▓▓▓▓▓▓▓▌▐▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓ ▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓ ▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▄
▓▓▓▓▓▓▓▓▓▓ ▓▓▓▓▓▓▓▓▓▓▌▐▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓ ▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓ ▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓
▓▓▓▓▓▓ ▓▓▓▓▓▓▓▀ ▐▓▓▓▓▓▓ ▐▓▓▓▓▓ ▓▓▓▓▓▓ ▓▓▓▓▓ ▐▓▓▓▓▓▌ ▐▓▓▓▓▓▓
▓▓▓▓▓▓▄▄▓▓▓▓▓▓▓▀ ▐▓▓▓▓▓▓▄▄▄▄ ▓▓▓▓▓▓▄▄▄▄ ▐▓▓▓▓▓▌ ▐▓▓▓▓▓▓
▓▓▓▓▓▓▓▓▓▓▓▓▓▀ ▐▓▓▓▓▓▓▓▓▓▓ ▓▓▓▓▓▓▓▓▓▓▌ ▐▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓
▓▓▓▓▓▓▀▀▓▓▓▓▓▓▄ ▐▓▓▓▓▓▓▀▀▀▀ ▓▓▓▓▓▓▀▀▀▀ ▐▓▓▓▓▓▓▓▓▓▓▓▓▓▓▀
▓▓▓▓▓▓ ▀▓▓▓▓▓▓▄ ▐▓▓▓▓▓▓ ▓▓▓▓▓ ▓▓▓▓▓▓ ▓▓▓▓▓ ▐▓▓▓▓▓▌
▓▓▓▓▓▓▓▓▓▓ █▓▓▓▓▓▓▓▓▓ ▐▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓ ▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓ ▓▓▓▓▓▓▓▓▓▓
▓▓▓▓▓▓▓▓▓▓ ▓▓▓▓▓▓▓▓▓▓ ▐▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓ ▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓ ▓▓▓▓▓▓▓▓▓▓
Trust math, not hardware.
*/
pragma solidity 0.5.17;
import "./KeepRegistry.sol";
/// @title AuthorityDelegator
/// @notice An operator contract can delegate authority to other operator
/// contracts by implementing the AuthorityDelegator interface.
///
/// To delegate authority,
/// the recipient of delegated authority must call `claimDelegatedAuthority`,
/// specifying the contract it wants delegated authority from.
/// The staking contract calls `delegator.__isRecognized(recipient)`
/// and if the call returns `true`,
/// the named delegator contract is set as the recipient's authority delegator.
/// Any future checks of registry approval or per-operator authorization
/// will transparently mirror the delegator's status.
///
/// Authority can be delegated recursively;
/// an operator contract receiving delegated authority
/// can recognize other operator contracts as recipients of its authority.
interface AuthorityDelegator {
function __isRecognized(address delegatedAuthorityRecipient) external returns (bool);
}
/// @title AuthorityVerifier
/// @notice An operator contract can delegate authority to other operator
/// contracts. Entry in the registry is not updated and source contract remains
/// listed there as authorized. This interface is a verifier that support verification
/// of contract authorization in case of authority delegation from the source contract.
interface AuthorityVerifier {
/// @notice Returns true if the given operator contract has been approved
/// for use. The function never reverts.
function isApprovedOperatorContract(address _operatorContract)
external
view
returns (bool);
}
contract Authorizations is AuthorityVerifier {
// Authorized operator contracts.
mapping(address => mapping (address => bool)) internal authorizations;
// Granters of delegated authority to operator contracts.
// E.g. keep factories granting delegated authority to keeps.
// `delegatedAuthority[keep] = factory`
mapping(address => address) internal delegatedAuthority;
// Registry contract with a list of approved operator contracts and upgraders.
KeepRegistry internal registry;
modifier onlyApprovedOperatorContract(address operatorContract) {
require(
isApprovedOperatorContract(operatorContract),
"Operator contract unapproved"
);
_;
}
constructor(KeepRegistry _registry) public {
registry = _registry;
}
/// @notice Gets the authorizer for the specified operator address.
/// @return Authorizer address.
function authorizerOf(address _operator) public view returns (address);
/// @notice Authorizes operator contract to access staked token balance of
/// the provided operator. Can only be executed by stake operator authorizer.
/// Contracts using delegated authority
/// cannot be authorized with `authorizeOperatorContract`.
/// Instead, authorize `getAuthoritySource(_operatorContract)`.
/// @param _operator address of stake operator.
/// @param _operatorContract address of operator contract.
function authorizeOperatorContract(address _operator, address _operatorContract)
public
onlyApprovedOperatorContract(_operatorContract) {
require(
authorizerOf(_operator) == msg.sender,
"Not operator authorizer"
);
require(
getAuthoritySource(_operatorContract) == _operatorContract,
"Delegated authority used"
);
authorizations[_operatorContract][_operator] = true;
}
/// @notice Checks if operator contract has access to the staked token balance of
/// the provided operator.
/// @param _operator address of stake operator.
/// @param _operatorContract address of operator contract.
function isAuthorizedForOperator(
address _operator,
address _operatorContract
) public view returns (bool) {
return authorizations[getAuthoritySource(_operatorContract)][_operator];
}
/// @notice Grant the sender the same authority as `delegatedAuthoritySource`
/// @dev If `delegatedAuthoritySource` is an approved operator contract
/// and recognizes the claimant, this relationship will be recorded in
/// `delegatedAuthority`. Later, the claimant can slash, seize, place locks etc.
/// on operators that have authorized the `delegatedAuthoritySource`.
/// If the `delegatedAuthoritySource` is disabled with the panic button,
/// any recipients of delegated authority from it will also be disabled.
function claimDelegatedAuthority(
address delegatedAuthoritySource
) public onlyApprovedOperatorContract(delegatedAuthoritySource) {
require(
AuthorityDelegator(delegatedAuthoritySource).__isRecognized(msg.sender),
"Unrecognized claimant"
);
delegatedAuthority[msg.sender] = delegatedAuthoritySource;
}
/// @notice Checks if the operator contract is authorized in the registry.
/// If the contract uses delegated authority it checks authorization of the
/// source contract.
/// @param _operatorContract address of operator contract.
/// @return True if operator contract is approved, false if operator contract
/// has not been approved or if it was disabled by the panic button.
function isApprovedOperatorContract(address _operatorContract)
public
view
returns (bool)
{
return
registry.isApprovedOperatorContract(
getAuthoritySource(_operatorContract)
);
}
/// @notice Get the source of the operator contract's authority.
/// If the contract uses delegated authority,
/// returns the original source of the delegated authority.
/// If the contract doesn't use delegated authority,
/// returns the contract itself.
/// Authorize `getAuthoritySource(operatorContract)`
/// to grant `operatorContract` the authority to penalize an operator.
function getAuthoritySource(
address operatorContract
) public view returns (address) {
address delegatedAuthoritySource = delegatedAuthority[operatorContract];
if (delegatedAuthoritySource == address(0)) {
return operatorContract;
}
return getAuthoritySource(delegatedAuthoritySource);
}
}
// File: @keep-network/keep-core/contracts/libraries/grant/UnlockingSchedule.sol
pragma solidity 0.5.17;
import "openzeppelin-solidity/contracts/math/SafeMath.sol";
library UnlockingSchedule {
using SafeMath for uint256;
function getUnlockedAmount(
uint256 _now,
uint256 grantedAmount,
uint256 duration,
uint256 start,
uint256 cliff
) internal pure returns (uint256) {
bool cliffNotReached = _now < cliff;
if (cliffNotReached) { return 0; }
uint256 timeElapsed = _now.sub(start);
bool unlockingPeriodFinished = timeElapsed >= duration;
if (unlockingPeriodFinished) { return grantedAmount; }
return grantedAmount.mul(timeElapsed).div(duration);
}
}
// File: @keep-network/keep-core/contracts/utils/AddressArrayUtils.sol
pragma solidity 0.5.17;
library AddressArrayUtils {
function contains(address[] memory self, address _address)
internal
pure
returns (bool)
{
for (uint i = 0; i < self.length; i++) {
if (_address == self[i]) {
return true;
}
}
return false;
}
function removeAddress(address[] storage self, address _addressToRemove)
internal
returns (address[] storage)
{
for (uint i = 0; i < self.length; i++) {
// If address is found in array.
if (_addressToRemove == self[i]) {
// Delete element at index and shift array.
for (uint j = i; j < self.length-1; j++) {
self[j] = self[j+1];
}
self.length--;
i--;
}
}
return self;
}
}
// File: @keep-network/keep-core/contracts/TokenGrantStake.sol
pragma solidity 0.5.17;
import "openzeppelin-solidity/contracts/token/ERC20/ERC20Burnable.sol";
import "openzeppelin-solidity/contracts/token/ERC20/SafeERC20.sol";
import "openzeppelin-solidity/contracts/math/SafeMath.sol";
import "./TokenStaking.sol";
import "./TokenSender.sol";
import "./utils/BytesLib.sol";
/// @dev Interface of sender contract for approveAndCall pattern.
interface tokenSender {
function approveAndCall(address _spender, uint256 _value, bytes calldata _extraData) external;
}
contract TokenGrantStake {
using SafeMath for uint256;
using BytesLib for bytes;
ERC20Burnable token;
TokenStaking tokenStaking;
address tokenGrant; // Address of the master grant contract.
uint256 grantId; // ID of the grant for this stake.
uint256 amount; // Amount of staked tokens.
address operator; // Operator of the stake.
constructor(
address _tokenAddress,
uint256 _grantId,
address _tokenStaking
) public {
require(
_tokenAddress != address(0x0),
"Token address can't be zero."
);
require(
_tokenStaking != address(0x0),
"Staking contract address can't be zero."
);
token = ERC20Burnable(_tokenAddress);
tokenGrant = msg.sender;
grantId = _grantId;
tokenStaking = TokenStaking(_tokenStaking);
}
function stake(
uint256 _amount,
bytes memory _extraData
) public onlyGrant {
amount = _amount;
operator = _extraData.toAddress(20);
tokenSender(address(token)).approveAndCall(
address(tokenStaking),
_amount,
_extraData
);
}
function getGrantId() public view onlyGrant returns (uint256) {
return grantId;
}
function getAmount() public view onlyGrant returns (uint256) {
return amount;
}
function getStakingContract() public view onlyGrant returns (address) {
return address(tokenStaking);
}
function getDetails() public view onlyGrant returns (
uint256 _grantId,
uint256 _amount,
address _tokenStaking
) {
return (
grantId,
amount,
address(tokenStaking)
);
}
function cancelStake() public onlyGrant returns (uint256) {
tokenStaking.cancelStake(operator);
return returnTokens();
}
function undelegate() public onlyGrant {
tokenStaking.undelegate(operator);
}
function recoverStake() public onlyGrant returns (uint256) {
tokenStaking.recoverStake(operator);
return returnTokens();
}
function returnTokens() internal returns (uint256) {
uint256 returnedAmount = token.balanceOf(address(this));
amount -= returnedAmount;
token.transfer(tokenGrant, returnedAmount);
return returnedAmount;
}
modifier onlyGrant {
require(
msg.sender == tokenGrant,
"For token grant contract only"
);
_;
}
}
// File: @keep-network/keep-core/contracts/GrantStakingPolicy.sol
pragma solidity 0.5.17;
/// @title GrantStakingPolicy
/// @notice A staking policy defines the function `getStakeableAmount`
/// which calculates how many tokens may be staked from a token grant.
contract GrantStakingPolicy {
function getStakeableAmount(
uint256 _now,
uint256 grantedAmount,
uint256 duration,
uint256 start,
uint256 cliff,
uint256 withdrawn) public view returns (uint256);
}
// File: @keep-network/keep-core/contracts/TokenStakingEscrow.sol
/**
▓▓▌ ▓▓ ▐▓▓ ▓▓▓▓▓▓▓▓▓▓▌▐▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓ ▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓ ▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▄
▓▓▓▓▓▓▓▓▓▓ ▓▓▓▓▓▓▓▓▓▓▌▐▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓ ▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓ ▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓
▓▓▓▓▓▓ ▓▓▓▓▓▓▓▀ ▐▓▓▓▓▓▓ ▐▓▓▓▓▓ ▓▓▓▓▓▓ ▓▓▓▓▓ ▐▓▓▓▓▓▌ ▐▓▓▓▓▓▓
▓▓▓▓▓▓▄▄▓▓▓▓▓▓▓▀ ▐▓▓▓▓▓▓▄▄▄▄ ▓▓▓▓▓▓▄▄▄▄ ▐▓▓▓▓▓▌ ▐▓▓▓▓▓▓
▓▓▓▓▓▓▓▓▓▓▓▓▓▀ ▐▓▓▓▓▓▓▓▓▓▓ ▓▓▓▓▓▓▓▓▓▓▌ ▐▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓
▓▓▓▓▓▓▀▀▓▓▓▓▓▓▄ ▐▓▓▓▓▓▓▀▀▀▀ ▓▓▓▓▓▓▀▀▀▀ ▐▓▓▓▓▓▓▓▓▓▓▓▓▓▓▀
▓▓▓▓▓▓ ▀▓▓▓▓▓▓▄ ▐▓▓▓▓▓▓ ▓▓▓▓▓ ▓▓▓▓▓▓ ▓▓▓▓▓ ▐▓▓▓▓▓▌
▓▓▓▓▓▓▓▓▓▓ █▓▓▓▓▓▓▓▓▓ ▐▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓ ▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓ ▓▓▓▓▓▓▓▓▓▓
▓▓▓▓▓▓▓▓▓▓ ▓▓▓▓▓▓▓▓▓▓ ▐▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓ ▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓ ▓▓▓▓▓▓▓▓▓▓
Trust math, not hardware.
*/
pragma solidity 0.5.17;
import "openzeppelin-solidity/contracts/ownership/Ownable.sol";
import "openzeppelin-solidity/contracts/token/ERC20/SafeERC20.sol";
import "openzeppelin-solidity/contracts/math/SafeMath.sol";
import "./libraries/grant/UnlockingSchedule.sol";
import "./utils/BytesLib.sol";
import "./KeepToken.sol";
import "./utils/BytesLib.sol";
import "./TokenGrant.sol";
import "./ManagedGrant.sol";
import "./TokenSender.sol";
/// @title TokenStakingEscrow
/// @notice Escrow lets the staking contract to deposit undelegated, granted
/// tokens and either withdraw them based on the grant unlocking schedule or
/// re-delegate them to another operator.
/// @dev The owner of TokenStakingEscrow is TokenStaking contract and only owner
/// can deposit. This contract works with an assumption that operator is unique
/// in the scope of `TokenStaking`, that is, no more than one delegation in the
/// `TokenStaking` can be done do the given operator ever. Even if the previous
/// delegation ended, operator address cannot be reused.
contract TokenStakingEscrow is Ownable {
using SafeERC20 for IERC20;
using SafeMath for uint256;
using BytesLib for bytes;
using UnlockingSchedule for uint256;
event Deposited(
address indexed operator,
uint256 indexed grantId,
uint256 amount
);
event DepositRedelegated(
address indexed previousOperator,
address indexed newOperator,
uint256 indexed grantId,
uint256 amount
);
event DepositWithdrawn(
address indexed operator,
address indexed grantee,
uint256 amount
);
event RevokedDepositWithdrawn(
address indexed operator,
address indexed grantManager,
uint256 amount
);
event EscrowAuthorized(
address indexed grantManager,
address escrow
);
IERC20 public keepToken;
TokenGrant public tokenGrant;
struct Deposit {
uint256 grantId;
uint256 amount;
uint256 withdrawn;
uint256 redelegated;
}
// operator address -> KEEP deposit
mapping(address => Deposit) internal deposits;
// Other escrows authorized by grant manager. Grantee may request to migrate
// tokens to another authorized escrow.
// grant manager -> escrow -> authorized?
mapping(address => mapping (address => bool)) internal authorizedEscrows;
constructor(
KeepToken _keepToken,
TokenGrant _tokenGrant
) public {
keepToken = _keepToken;
tokenGrant = _tokenGrant;
}
/// @notice receiveApproval accepts deposits from staking contract and
/// stores them in the escrow by the operator address from which they were
/// undelegated. Function expects operator address and grant identifier to
/// be passed as ABI-encoded information in extraData. Grant with the given
/// identifier has to exist.
/// @param from Address depositing tokens - it has to be the address of
/// TokenStaking contract owning TokenStakingEscrow.
/// @param value The amount of KEEP tokens deposited.
/// @param token The address of KEEP token contract.
/// @param extraData ABI-encoded data containing operator address (32 bytes)
/// and grant ID (32 bytes).
function receiveApproval(
address from,
uint256 value,
address token,
bytes memory extraData
) public {
require(IERC20(token) == keepToken, "Not a KEEP token");
require(msg.sender == token, "KEEP token is not the sender");
require(extraData.length == 64, "Unexpected data length");
(address operator, uint256 grantId) = abi.decode(
extraData, (address, uint256)
);
receiveDeposit(from, value, operator, grantId);
}
/// @notice Redelegates deposit or part of the deposit to another operator.
/// Uses the same staking contract as the original delegation.
/// @param previousOperator Address of the operator from the undelegated/canceled
/// delegation from which tokens were deposited.
/// @dev Only grantee is allowed to call this function. For managed grant,
/// caller has to be the managed grantee.
/// @param amount Amount of tokens to delegate.
/// @param extraData Data for stake delegation. This byte array must have
/// the following values concatenated:
/// - Beneficiary address (20 bytes)
/// - Operator address (20 bytes)
/// - Authorizer address (20 bytes)
function redelegate(
address previousOperator,
uint256 amount,
bytes memory extraData
) public {
require(extraData.length == 60, "Corrupted delegation data");
Deposit memory deposit = deposits[previousOperator];
uint256 grantId = deposit.grantId;
address newOperator = extraData.toAddress(20);
require(isGrantee(msg.sender, grantId), "Not authorized");
require(getAmountRevoked(grantId) == 0, "Grant revoked");
require(
availableAmount(previousOperator) >= amount,
"Insufficient balance"
);
require(
!hasDeposit(newOperator),
"Redelegating to previously used operator is not allowed"
);
deposits[previousOperator].redelegated = deposit.redelegated.add(amount);
TokenSender(address(keepToken)).approveAndCall(
owner(), // TokenStaking contract associated with the escrow
amount,
abi.encodePacked(extraData, grantId)
);
emit DepositRedelegated(
previousOperator,
newOperator,
grantId,
amount
);
}
/// @notice Returns true if there is a deposit for the given operator in
/// the escrow. Otherwise, returns false.
/// @param operator Address of the operator from the undelegated/canceled
/// delegation from which tokens were deposited.
function hasDeposit(address operator) public view returns (bool) {
return depositedAmount(operator) > 0;
}
/// @notice Returns the currently available amount deposited in the escrow
/// that may or may not be currently withdrawable. The available amount
/// is the amount initially deposited minus the amount withdrawn and
/// redelegated so far from that deposit.
/// @param operator Address of the operator from the undelegated/canceled
/// delegation from which tokens were deposited.
function availableAmount(address operator) public view returns (uint256) {
Deposit memory deposit = deposits[operator];
return deposit.amount.sub(deposit.withdrawn).sub(deposit.redelegated);
}
/// @notice Returns the total amount deposited in the escrow after
/// undelegating it from the provided operator.
/// @param operator Address of the operator from the undelegated/canceled
/// delegation from which tokens were deposited.
function depositedAmount(address operator) public view returns (uint256) {
return deposits[operator].amount;
}
/// @notice Returns grant ID for the amount deposited in the escrow after
/// undelegating it from the provided operator.
/// @param operator Address of the operator from the undelegated/canceled
/// delegation from which tokens were deposited.
function depositGrantId(address operator) public view returns (uint256) {
return deposits[operator].grantId;
}
/// @notice Returns the amount withdrawn so far from the value deposited
/// in the escrow contract after undelegating it from the provided operator.
/// @param operator Address of the operator from the undelegated/canceled
/// delegation from which tokens were deposited.
function depositWithdrawnAmount(address operator) public view returns (uint256) {
return deposits[operator].withdrawn;
}
/// @notice Returns the total amount redelegated so far from the value
/// deposited in the escrow contract after undelegating it from the provided
/// operator.
/// @param operator Address of the operator from the undelegated/canceled
/// delegation from which tokens were deposited.
function depositRedelegatedAmount(address operator) public view returns (uint256) {
return deposits[operator].redelegated;
}
/// @notice Returns the currently withdrawable amount that was previously
/// deposited in the escrow after undelegating it from the provided operator.
/// Tokens are unlocked based on their grant unlocking schedule.
/// Function returns 0 for non-existing deposits and revoked grants if they
/// have been revoked before they fully unlocked.
/// @param operator Address of the operator from the undelegated/canceled
/// delegation from which tokens were deposited.
function withdrawable(address operator) public view returns (uint256) {
Deposit memory deposit = deposits[operator];
// Staked tokens can be only withdrawn by grantee for non-revoked grant
// assuming that grant has not fully unlocked before it's been
// revoked.
//
// It is not possible for the escrow to determine the number of tokens
// it should return to the grantee of a revoked grant given different
// possible staking contracts and staking policies.
//
// If the entire grant unlocked before it's been reverted, escrow
// lets to withdraw the entire deposited amount.
if (getAmountRevoked(deposit.grantId) == 0) {
(
uint256 duration,
uint256 start,
uint256 cliff
) = getUnlockingSchedule(deposit.grantId);
uint256 unlocked = now.getUnlockedAmount(
deposit.amount,
duration,
start,
cliff
);
if (deposit.withdrawn.add(deposit.redelegated) < unlocked) {
return unlocked.sub(deposit.withdrawn).sub(deposit.redelegated);
}
}
return 0;
}
/// @notice Withdraws currently unlocked tokens deposited in the escrow
/// after undelegating them from the provided operator. Only grantee or
/// operator can call this function. Important: this function can not be
/// called for a `ManagedGrant` grantee. This may lead to locking tokens.
/// For `ManagedGrant`, please use `withdrawToManagedGrantee` instead.
/// @param operator Address of the operator from the undelegated/canceled
/// delegation from which tokens were deposited.
function withdraw(address operator) public {
Deposit memory deposit = deposits[operator];
address grantee = getGrantee(deposit.grantId);
// Make sure this function is not called for a managed grant.
// If called for a managed grant, tokens could be locked there.
// Better be safe than sorry.
(bool success, ) = address(this).call(
abi.encodeWithSignature("getManagedGrantee(address)", grantee)
);
require(!success, "Can not be called for managed grant");
require(
msg.sender == grantee || msg.sender == operator,
"Only grantee or operator can withdraw"
);
withdraw(deposit, operator, grantee);
}
/// @notice Withdraws currently unlocked tokens deposited in the escrow
/// after undelegating them from the provided operator. Only grantee or
/// operator can call this function. This function works only for
/// `ManagedGrant` grantees. For a standard grant, please use `withdraw`
/// instead.
/// @param operator Address of the operator from the undelegated/canceled
/// delegation from which tokens were deposited.
function withdrawToManagedGrantee(address operator) public {
Deposit memory deposit = deposits[operator];
address managedGrant = getGrantee(deposit.grantId);
address grantee = getManagedGrantee(managedGrant);
require(
msg.sender == grantee || msg.sender == operator,
"Only grantee or operator can withdraw"
);
withdraw(deposit, operator, grantee);
}
/// @notice Migrates all available tokens to another authorized escrow.
/// Can be requested only by grantee.
/// @param operator Address of the operator from the undelegated/canceled
/// delegation from which tokens were deposited.
/// @param receivingEscrow Escrow to which tokens should be migrated.
/// @dev The receiving escrow needs to accept deposits from this escrow, at
/// least for the period of migration.
function migrate(
address operator,
address receivingEscrow
) public {
Deposit memory deposit = deposits[operator];
require(isGrantee(msg.sender, deposit.grantId), "Not authorized");
address grantManager = getGrantManager(deposit.grantId);
require(
authorizedEscrows[grantManager][receivingEscrow],
"Escrow not authorized"
);
uint256 amountLeft = availableAmount(operator);
deposits[operator].withdrawn = deposit.withdrawn.add(amountLeft);
TokenSender(address(keepToken)).approveAndCall(
receivingEscrow,
amountLeft,
abi.encode(operator, deposit.grantId)
);
}
/// @notice Withdraws the entire amount that is still deposited in the
/// escrow in case the grant has been revoked. Anyone can call this function
/// and the entire amount is transferred back to the grant manager.
/// @param operator Address of the operator from the undelegated/canceled
/// delegation from which tokens were deposited.
function withdrawRevoked(address operator) public {
Deposit memory deposit = deposits[operator];
require(
getAmountRevoked(deposit.grantId) > 0,
"No revoked tokens to withdraw"
);
address grantManager = getGrantManager(deposit.grantId);
withdrawRevoked(deposit, operator, grantManager);
}
/// @notice Used by grant manager to authorize another escrows for
// funds migration.
function authorizeEscrow(address anotherEscrow) public {
require(
anotherEscrow != address(0x0),
"Escrow address can't be zero"
);
authorizedEscrows[msg.sender][anotherEscrow] = true;
emit EscrowAuthorized(msg.sender, anotherEscrow);
}
/// @notice Resolves the final grantee of ManagedGrant contract. If the
/// provided address is not a ManagedGrant contract, function reverts.
/// @param managedGrant Address of the managed grant contract.
function getManagedGrantee(
address managedGrant
) public view returns(address) {
ManagedGrant grant = ManagedGrant(managedGrant);
return grant.grantee();
}
function receiveDeposit(
address from,
uint256 value,
address operator,
uint256 grantId
) internal {
// This contract works with an assumption that operator is unique.
// This is fine as long as the staking contract works with the same
// assumption so we are limiting deposits to the staking contract only.
require(from == owner(), "Only owner can deposit");
require(
getAmountGranted(grantId) > 0,
"Grant with this ID does not exist"
);
require(
!hasDeposit(operator),
"Stake for the operator already deposited in the escrow"
);
keepToken.safeTransferFrom(from, address(this), value);
deposits[operator] = Deposit(grantId, value, 0, 0);
emit Deposited(operator, grantId, value);
}
function isGrantee(
address maybeGrantee,
uint256 grantId
) internal returns (bool) {
// Let's check the simplest case first - standard grantee.
// If the given address is set as a grantee for grant with the given ID,
// we return true.
address grantee = getGrantee(grantId);
if (maybeGrantee == grantee) {
return true;
}
// If the given address is not a standard grantee, there is still
// a chance that address is a managed grantee. We are calling
// getManagedGrantee that will cast the grantee to ManagedGrant and try
// to call getGrantee() function. If this call returns non-zero address,
// it means we are dealing with a ManagedGrant.
(, bytes memory result) = address(this).call(
abi.encodeWithSignature("getManagedGrantee(address)", grantee)
);
if (result.length == 0) {
return false;
}
// At this point we know we are dealing with a ManagedGrant, so the last
// thing we need to check is whether the managed grantee of that grant
// is the grantee address passed as a parameter.
address managedGrantee = abi.decode(result, (address));
return maybeGrantee == managedGrantee;
}
function withdraw(
Deposit memory deposit,
address operator,
address grantee
) internal {
uint256 amount = withdrawable(operator);
deposits[operator].withdrawn = deposit.withdrawn.add(amount);
keepToken.safeTransfer(grantee, amount);
emit DepositWithdrawn(operator, grantee, amount);
}
function withdrawRevoked(
Deposit memory deposit,
address operator,
address grantManager
) internal {
uint256 amount = availableAmount(operator);
deposits[operator].withdrawn = amount;
keepToken.safeTransfer(grantManager, amount);
emit RevokedDepositWithdrawn(operator, grantManager, amount);
}
function getAmountGranted(uint256 grantId) internal view returns (
uint256 amountGranted
) {
(amountGranted,,,,,) = tokenGrant.getGrant(grantId);
}
function getAmountRevoked(uint256 grantId) internal view returns (
uint256 amountRevoked
) {
(,,,amountRevoked,,) = tokenGrant.getGrant(grantId);
}
function getUnlockingSchedule(uint256 grantId) internal view returns (
uint256 duration,
uint256 start,
uint256 cliff
) {
(,duration,start,cliff,) = tokenGrant.getGrantUnlockingSchedule(grantId);
}
function getGrantee(uint256 grantId) internal view returns (
address grantee
) {
(,,,,,grantee) = tokenGrant.getGrant(grantId);
}
function getGrantManager(uint256 grantId) internal view returns (
address grantManager
) {
(grantManager,,,,) = tokenGrant.getGrantUnlockingSchedule(grantId);
}
}
// File: @keep-network/keep-core/contracts/TokenSender.sol
pragma solidity 0.5.17;
/// @dev Interface of sender contract for approveAndCall pattern.
interface TokenSender {
function approveAndCall(address _spender, uint256 _value, bytes calldata _extraData) external;
}
// File: @keep-network/keep-core/contracts/KeepToken.sol
pragma solidity 0.5.17;
import "openzeppelin-solidity/contracts/token/ERC20/ERC20Burnable.sol";
import "openzeppelin-solidity/contracts/token/ERC20/ERC20Detailed.sol";
/// @dev Interface of recipient contract for approveAndCall pattern.
interface tokenRecipient { function receiveApproval(address _from, uint256 _value, address _token, bytes calldata _extraData) external; }
/// @title KEEP Token
/// @dev Standard ERC20Burnable token
contract KeepToken is ERC20Burnable, ERC20Detailed {
string public constant NAME = "KEEP Token";
string public constant SYMBOL = "KEEP";
uint8 public constant DECIMALS = 18; // The number of digits after the decimal place when displaying token values on-screen.
uint256 public constant INITIAL_SUPPLY = 10**27; // 1 billion tokens, 18 decimal places.
/// @dev Gives msg.sender all of existing tokens.
constructor() public ERC20Detailed(NAME, SYMBOL, DECIMALS) {
_mint(msg.sender, INITIAL_SUPPLY);
}
/// @notice Set allowance for other address and notify.
/// Allows `_spender` to spend no more than `_value` tokens
/// on your behalf and then ping the contract about it.
/// @param _spender The address authorized to spend.
/// @param _value The max amount they can spend.
/// @param _extraData Extra information to send to the approved contract.
function approveAndCall(address _spender, uint256 _value, bytes memory _extraData) public returns (bool success) {
tokenRecipient spender = tokenRecipient(_spender);
if (approve(_spender, _value)) {
spender.receiveApproval(msg.sender, _value, address(this), _extraData);
return true;
}
}
}
// File: @keep-network/keep-core/contracts/ManagedGrant.sol
pragma solidity ^0.5.4;
import "openzeppelin-solidity/contracts/token/ERC20/ERC20Burnable.sol";
import "openzeppelin-solidity/contracts/token/ERC20/SafeERC20.sol";
import "./TokenGrant.sol";
/// @title ManagedGrant
/// @notice A managed grant acts as the grantee towards the token grant contract,
/// proxying instructions from the actual grantee.
/// The address used by the actual grantee
/// to issue instructions and withdraw tokens
/// can be reassigned with the consent of the grant manager.
contract ManagedGrant {
using SafeERC20 for ERC20Burnable;
ERC20Burnable public token;
TokenGrant public tokenGrant;
address public grantManager;
uint256 public grantId;
address public grantee;
address public requestedNewGrantee;
event GranteeReassignmentRequested(
address newGrantee
);
event GranteeReassignmentConfirmed(
address oldGrantee,
address newGrantee
);
event GranteeReassignmentCancelled(
address cancelledRequestedGrantee
);
event GranteeReassignmentChanged(
address previouslyRequestedGrantee,
address newRequestedGrantee
);
event TokensWithdrawn(
address destination,
uint256 amount
);
constructor(
address _tokenAddress,
address _tokenGrant,
address _grantManager,
uint256 _grantId,
address _grantee
) public {
token = ERC20Burnable(_tokenAddress);
tokenGrant = TokenGrant(_tokenGrant);
grantManager = _grantManager;
grantId = _grantId;
grantee = _grantee;
}
/// @notice Request a reassignment of the grantee address.
/// Can only be called by the grantee.
/// @param _newGrantee The requested new grantee.
function requestGranteeReassignment(address _newGrantee)
public
onlyGrantee
noRequestedReassignment
{
_setRequestedNewGrantee(_newGrantee);
emit GranteeReassignmentRequested(_newGrantee);
}
/// @notice Cancel a pending grantee reassignment request.
/// Can only be called by the grantee.
function cancelReassignmentRequest()
public
onlyGrantee
withRequestedReassignment
{
address cancelledGrantee = requestedNewGrantee;
requestedNewGrantee = address(0);
emit GranteeReassignmentCancelled(cancelledGrantee);
}
/// @notice Change a pending reassignment request to a different grantee.
/// Can only be called by the grantee.
/// @param _newGrantee The address of the new requested grantee.
function changeReassignmentRequest(address _newGrantee)
public
onlyGrantee
withRequestedReassignment
{
address previouslyRequestedGrantee = requestedNewGrantee;
require(
previouslyRequestedGrantee != _newGrantee,
"Unchanged reassignment request"
);
_setRequestedNewGrantee(_newGrantee);
emit GranteeReassignmentChanged(previouslyRequestedGrantee, _newGrantee);
}
/// @notice Confirm a grantee reassignment request and set the new grantee as the grantee.
/// Can only be called by the grant manager.
/// @param _newGrantee The address of the new grantee.
/// Must match the currently requested new grantee.
function confirmGranteeReassignment(address _newGrantee)
public
onlyManager
withRequestedReassignment
{
address oldGrantee = grantee;
require(
requestedNewGrantee == _newGrantee,
"Reassignment address mismatch"
);
grantee = requestedNewGrantee;
requestedNewGrantee = address(0);
emit GranteeReassignmentConfirmed(oldGrantee, _newGrantee);
}
/// @notice Withdraw all unlocked tokens from the grant.
function withdraw() public onlyGrantee {
require(
requestedNewGrantee == address(0),
"Can not withdraw with pending reassignment"
);
tokenGrant.withdraw(grantId);
uint256 amount = token.balanceOf(address(this));
token.safeTransfer(grantee, amount);
emit TokensWithdrawn(grantee, amount);
}
/// @notice Stake tokens from the grant.
/// @param _stakingContract The contract to stake the tokens on.
/// @param _amount The amount of tokens to stake.
/// @param _extraData Data for the stake delegation.
/// This byte array must have the following values concatenated:
/// beneficiary address (20 bytes)
/// operator address (20 bytes)
/// authorizer address (20 bytes)
function stake(
address _stakingContract,
uint256 _amount,
bytes memory _extraData
) public onlyGrantee {
tokenGrant.stake(grantId, _stakingContract, _amount, _extraData);
}
/// @notice Cancel delegating tokens to the given operator.
function cancelStake(address _operator) public onlyGranteeOr(_operator) {
tokenGrant.cancelStake(_operator);
}
/// @notice Begin undelegating tokens from the given operator.
function undelegate(address _operator) public onlyGranteeOr(_operator) {
tokenGrant.undelegate(_operator);
}
/// @notice Recover tokens previously staked and delegated to the operator.
function recoverStake(address _operator) public {
tokenGrant.recoverStake(_operator);
}
function _setRequestedNewGrantee(address _newGrantee) internal {
require(_newGrantee != address(0), "Invalid new grantee address");
require(_newGrantee != grantee, "New grantee same as current grantee");
requestedNewGrantee = _newGrantee;
}
modifier withRequestedReassignment {
require(
requestedNewGrantee != address(0),
"No reassignment requested"
);
_;
}
modifier noRequestedReassignment {
require(
requestedNewGrantee == address(0),
"Reassignment already requested"
);
_;
}
modifier onlyGrantee {
require(
msg.sender == grantee,
"Only grantee may perform this action"
);
_;
}
modifier onlyGranteeOr(address _operator) {
require(
msg.sender == grantee || msg.sender == _operator,
"Only grantee or operator may perform this action"
);
_;
}
modifier onlyManager {
require(
msg.sender == grantManager,
"Only grantManager may perform this action"
);
_;
}
}
// File: @keep-network/keep-core/contracts/libraries/RolesLookup.sol
pragma solidity 0.5.17;
import "../utils/AddressArrayUtils.sol";
import "../StakeDelegatable.sol";
import "../TokenGrant.sol";
import "../ManagedGrant.sol";
/// @title Roles Lookup
/// @notice Library facilitating lookup of roles in stake delegation setup.
library RolesLookup {
using AddressArrayUtils for address[];
/// @notice Returns true if the tokenOwner delegated tokens to operator
/// using the provided stakeDelegatable contract. Othwerwise, returns false.
/// This function works only for the case when tokenOwner own those tokens
/// and those are not tokens from a grant.
function isTokenOwnerForOperator(
address tokenOwner,
address operator,
StakeDelegatable stakeDelegatable
) internal view returns (bool) {
return stakeDelegatable.ownerOf(operator) == tokenOwner;
}
/// @notice Returns true if the grantee delegated tokens to operator
/// with the provided tokenGrant contract. Otherwise, returns false.
/// This function works only for the case when tokens were generated from
/// a non-managed grant, that is, the grantee is a non-contract address to
/// which the delegated tokens were granted.
/// @dev This function does not validate the staking reltionship on
/// a particular staking contract. It only checks whether the grantee
/// staked at least one time with the given operator. If you are interested
/// in a particular token staking contract, you need to perform additional
/// check.
function isGranteeForOperator(
address grantee,
address operator,
TokenGrant tokenGrant
) internal view returns (bool) {
address[] memory operators = tokenGrant.getGranteeOperators(grantee);
return operators.contains(operator);
}
/// @notice Returns true if the grantee from the given managed grant contract
/// delegated tokens to operator with the provided tokenGrant contract.
/// Otherwise, returns false. In case the grantee declared by the managed
/// grant contract does not match the provided grantee, function reverts.
/// This function works only for cases when grantee, from TokenGrant's
/// perspective, is a smart contract exposing grantee() function returning
/// the final grantee. One possibility is the ManagedGrant contract.
/// @dev This function does not validate the staking reltionship on
/// a particular staking contract. It only checks whether the grantee
/// staked at least one time with the given operator. If you are interested
/// in a particular token staking contract, you need to perform additional
/// check.
function isManagedGranteeForOperator(
address grantee,
address operator,
address managedGrantContract,
TokenGrant tokenGrant
) internal view returns (bool) {
require(
ManagedGrant(managedGrantContract).grantee() == grantee,
"Not a grantee of the provided contract"
);
address[] memory operators = tokenGrant.getGranteeOperators(
managedGrantContract
);
return operators.contains(operator);
}
/// @notice Returns true if grant with the given ID has been created with
/// managed grant pointing currently to the grantee passed as a parameter.
/// @dev The function does not revert if grant has not been created with
/// a managed grantee. This function is not a view because it uses low-level
/// call to check if the grant has been created with a managed grant.
/// It does not however modify any state.
function isManagedGranteeForGrant(
address grantee,
uint256 grantId,
TokenGrant tokenGrant
) internal returns (bool) {
(,,,,, address managedGrant) = tokenGrant.getGrant(grantId);
(, bytes memory result) = managedGrant.call(
abi.encodeWithSignature("grantee()")
);
if (result.length == 0) {
return false;
}
address managedGrantee = abi.decode(result, (address));
return grantee == managedGrantee;
}
}
// File: @keep-network/keep-core/contracts/libraries/staking/LockUtils.sol
pragma solidity 0.5.17;
library LockUtils {
struct Lock {
address creator;
uint96 expiresAt;
}
/// @notice The LockSet is like an array of unique `uint256`s,
/// but additionally supports O(1) membership tests and removals.
/// @dev Because the LockSet relies on a mapping,
/// it can only be used in storage, not in memory.
struct LockSet {
// locks[positions[lock.creator] - 1] = lock
Lock[] locks;
mapping(address => uint256) positions;
}
/// @notice Check whether the LockSet `self` contains a lock by `creator`
function contains(LockSet storage self, address creator)
internal view returns (bool) {
return (self.positions[creator] != 0);
}
function getLockTime(LockSet storage self, address creator)
internal view returns (uint96) {
uint256 positionPlusOne = self.positions[creator];
if (positionPlusOne == 0) { return 0; }
return self.locks[positionPlusOne - 1].expiresAt;
}
/// @notice Set the lock of `creator` to `expiresAt`,
/// overriding the current value if any.
function setLock(
LockSet storage self,
address _creator,
uint96 _expiresAt
) internal {
uint256 positionPlusOne = self.positions[_creator];
Lock memory lock = Lock(_creator, _expiresAt);
// No existing lock
if (positionPlusOne == 0) {
self.locks.push(lock);
self.positions[_creator] = self.locks.length;
// Existing lock present
} else {
self.locks[positionPlusOne - 1].expiresAt = _expiresAt;
}
}
/// @notice Remove the lock of `creator`.
/// If no lock present, do nothing.
function releaseLock(
LockSet storage self,
address _creator
) internal {
uint256 positionPlusOne = self.positions[_creator];
if (positionPlusOne != 0) {
uint256 lockCount = self.locks.length;
if (positionPlusOne != lockCount) {
// Not the last lock,
// so we need to move the last lock into the emptied position.
Lock memory lastLock = self.locks[lockCount - 1];
self.locks[positionPlusOne - 1] = lastLock;
self.positions[lastLock.creator] = positionPlusOne;
}
self.locks.length--;
self.positions[_creator] = 0;
}
}
/// @notice Return the locks of the LockSet `self`.
function enumerate(LockSet storage self)
internal view returns (Lock[] memory) {
return self.locks;
}
}
// File: @keep-network/keep-core/contracts/StakeDelegatable.sol
/**
▓▓▌ ▓▓ ▐▓▓ ▓▓▓▓▓▓▓▓▓▓▌▐▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓ ▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓ ▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▄
▓▓▓▓▓▓▓▓▓▓ ▓▓▓▓▓▓▓▓▓▓▌▐▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓ ▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓ ▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓
▓▓▓▓▓▓ ▓▓▓▓▓▓▓▀ ▐▓▓▓▓▓▓ ▐▓▓▓▓▓ ▓▓▓▓▓▓ ▓▓▓▓▓ ▐▓▓▓▓▓▌ ▐▓▓▓▓▓▓
▓▓▓▓▓▓▄▄▓▓▓▓▓▓▓▀ ▐▓▓▓▓▓▓▄▄▄▄ ▓▓▓▓▓▓▄▄▄▄ ▐▓▓▓▓▓▌ ▐▓▓▓▓▓▓
▓▓▓▓▓▓▓▓▓▓▓▓▓▀ ▐▓▓▓▓▓▓▓▓▓▓ ▓▓▓▓▓▓▓▓▓▓▌ ▐▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓
▓▓▓▓▓▓▀▀▓▓▓▓▓▓▄ ▐▓▓▓▓▓▓▀▀▀▀ ▓▓▓▓▓▓▀▀▀▀ ▐▓▓▓▓▓▓▓▓▓▓▓▓▓▓▀
▓▓▓▓▓▓ ▀▓▓▓▓▓▓▄ ▐▓▓▓▓▓▓ ▓▓▓▓▓ ▓▓▓▓▓▓ ▓▓▓▓▓ ▐▓▓▓▓▓▌
▓▓▓▓▓▓▓▓▓▓ █▓▓▓▓▓▓▓▓▓ ▐▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓ ▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓ ▓▓▓▓▓▓▓▓▓▓
▓▓▓▓▓▓▓▓▓▓ ▓▓▓▓▓▓▓▓▓▓ ▐▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓ ▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓ ▓▓▓▓▓▓▓▓▓▓
Trust math, not hardware.
*/
pragma solidity 0.5.17;
import "./utils/OperatorParams.sol";
/// @title Stake Delegatable
/// @notice A base contract to allow stake delegation for staking contracts.
contract StakeDelegatable {
using OperatorParams for uint256;
mapping(address => Operator) internal operators;
struct Operator {
uint256 packedParams;
address owner;
address payable beneficiary;
address authorizer;
}
/// @notice Gets the stake balance of the specified address.
/// @param _address The address to query the balance of.
/// @return An uint256 representing the amount staked by the passed address.
function balanceOf(address _address) public view returns (uint256 balance) {
return operators[_address].packedParams.getAmount();
}
/// @notice Gets the stake owner for the specified operator address.
/// @return Stake owner address.
function ownerOf(address _operator) public view returns (address) {
return operators[_operator].owner;
}
/// @notice Gets the beneficiary for the specified operator address.
/// @return Beneficiary address.
function beneficiaryOf(address _operator) public view returns (address payable) {
return operators[_operator].beneficiary;
}
/// @notice Gets the authorizer for the specified operator address.
/// @return Authorizer address.
function authorizerOf(address _operator) public view returns (address) {
return operators[_operator].authorizer;
}
}
// File: @keep-network/keep-core/contracts/utils/OperatorParams.sol
pragma solidity 0.5.17;
library OperatorParams {
// OperatorParams packs values that are commonly used together
// into a single uint256 to reduce the cost functions
// like querying eligibility.
//
// An OperatorParams uint256 contains:
// - the operator's staked token amount (uint128)
// - the operator's creation timestamp (uint64)
// - the operator's undelegation timestamp (uint64)
//
// These are packed as [amount | createdAt | undelegatedAt]
//
// Staked KEEP is stored in an uint128,
// which is sufficient because KEEP tokens have 18 decimals (2^60)
// and there will be at most 10^9 KEEP in existence (2^30).
//
// Creation and undelegation times are stored in an uint64 each.
// Thus uint64s would be sufficient for around 3*10^11 years.
uint256 constant TIMESTAMP_WIDTH = 64;
uint256 constant AMOUNT_WIDTH = 128;
uint256 constant TIMESTAMP_MAX = (2**TIMESTAMP_WIDTH) - 1;
uint256 constant AMOUNT_MAX = (2**AMOUNT_WIDTH) - 1;
uint256 constant CREATION_SHIFT = TIMESTAMP_WIDTH;
uint256 constant AMOUNT_SHIFT = 2 * TIMESTAMP_WIDTH;
function pack(
uint256 amount,
uint256 createdAt,
uint256 undelegatedAt
) internal pure returns (uint256) {
// Check for staked amount overflow.
// We shouldn't actually ever need this.
require(
amount <= AMOUNT_MAX,
"uint128 overflow"
);
// Bitwise OR the timestamps together.
// The resulting number is equal or greater than either,
// and tells if we have a bit set outside the 64 available bits.
require(
(createdAt | undelegatedAt) <= TIMESTAMP_MAX,
"uint64 overflow"
);
return (amount << AMOUNT_SHIFT | createdAt << CREATION_SHIFT | undelegatedAt);
}
function unpack(uint256 packedParams) internal pure returns (
uint256 amount,
uint256 createdAt,
uint256 undelegatedAt
) {
amount = getAmount(packedParams);
createdAt = getCreationTimestamp(packedParams);
undelegatedAt = getUndelegationTimestamp(packedParams);
}
function getAmount(uint256 packedParams)
internal pure returns (uint256) {
return (packedParams >> AMOUNT_SHIFT) & AMOUNT_MAX;
}
function setAmount(
uint256 packedParams,
uint256 amount
) internal pure returns (uint256) {
return pack(
amount,
getCreationTimestamp(packedParams),
getUndelegationTimestamp(packedParams)
);
}
function getCreationTimestamp(uint256 packedParams)
internal pure returns (uint256) {
return (packedParams >> CREATION_SHIFT) & TIMESTAMP_MAX;
}
function setCreationTimestamp(
uint256 packedParams,
uint256 creationTimestamp
) internal pure returns (uint256) {
return pack(
getAmount(packedParams),
creationTimestamp,
getUndelegationTimestamp(packedParams)
);
}
function getUndelegationTimestamp(uint256 packedParams)
internal pure returns (uint256) {
return packedParams & TIMESTAMP_MAX;
}
function setUndelegationTimestamp(
uint256 packedParams,
uint256 undelegationTimestamp
) internal pure returns (uint256) {
return pack(
getAmount(packedParams),
getCreationTimestamp(packedParams),
undelegationTimestamp
);
}
function setAmountAndCreationTimestamp(
uint256 packedParams,
uint256 amount,
uint256 creationTimestamp
) internal pure returns (uint256) {
return pack(
amount,
creationTimestamp,
getUndelegationTimestamp(packedParams)
);
}
}
// File: @keep-network/keep-core/contracts/libraries/staking/MinimumStakeSchedule.sol
pragma solidity 0.5.17;
import "openzeppelin-solidity/contracts/math/SafeMath.sol";
/// @notice MinimumStakeSchedule defines the minimum stake parametrization and
/// schedule. It starts with a minimum stake of 100k KEEP. Over the following
/// 2 years, the minimum stake is lowered periodically using a uniform stepwise
/// function, eventually ending at 10k.
library MinimumStakeSchedule {
using SafeMath for uint256;
// 2 years in seconds (seconds per day * days in a year * years)
uint256 public constant schedule = 86400 * 365 * 2;
uint256 public constant steps = 10;
uint256 public constant base = 10000 * 1e18;
/// @notice Returns the current value of the minimum stake. The minimum
/// stake is lowered periodically over the course of 2 years since the time
/// of the shedule start and eventually ends at 10k KEEP.
function current(uint256 scheduleStart) internal view returns (uint256) {
if (now < scheduleStart.add(schedule)) {
uint256 currentStep = steps.mul(now.sub(scheduleStart)).div(schedule);
return base.mul(steps.sub(currentStep));
}
return base;
}
}
// File: @keep-network/keep-core/contracts/libraries/staking/GrantStaking.sol
pragma solidity 0.5.17;
import "../../TokenGrant.sol";
import "../../TokenStakingEscrow.sol";
import "../..//utils/BytesLib.sol";
import "../RolesLookup.sol";
/// @notice TokenStaking contract library allowing to capture the details of
/// delegated grants and offering functions allowing to check grantee
/// authentication for stake delegation management.
library GrantStaking {
using BytesLib for bytes;
using RolesLookup for address payable;
/// @dev Grant ID is flagged with the most significant bit set, to
/// distinguish the grant ID `0` from default (null) value. The flag is
/// toggled with bitwise XOR (`^`) which keeps all other bits intact but
/// flips the flag bit. The flag should be set before writing to
/// `operatorToGrant`, and unset after reading from `operatorToGrant`
/// before using the value.
uint256 constant GRANT_ID_FLAG = 1 << 255;
struct Storage {
/// @dev Do not read or write this mapping directly; please use
/// `hasGrantDelegated`, `setGrantForOperator`, and `getGrantForOperator`
/// instead.
mapping (address => uint256) _operatorToGrant;
}
/// @notice Tries to capture delegation data if the pending delegation has
/// been created from a grant. There are only two possibilities and they
/// need to be handled differently: delegation comes from the TokenGrant
/// contract or delegation comes from TokenStakingEscrow. In those two cases
/// grant ID has to be captured in a different way.
/// @dev In case of a delegation from the escrow, it is expected that grant
/// ID is passed in extraData bytes array. When the delegation comes from
/// the TokenGrant contract, delegation data are obtained directly from that
/// contract using `tryCapturingGrantId` function.
/// @param tokenGrant KEEP token grant contract reference.
/// @param escrow TokenStakingEscrow contract address.
/// @param from The owner of the tokens who approved them to transfer.
/// @param operator The operator tokens are delegated to.
/// @param extraData Data for stake delegation, as passed to
/// `receiveApproval` of `TokenStaking`.
function tryCapturingDelegationData(
Storage storage self,
TokenGrant tokenGrant,
address escrow,
address from,
address operator,
bytes memory extraData
) public returns (bool, uint256) {
if (from == escrow) {
require(extraData.length == 92, "Corrupted delegation data from escrow");
uint256 grantId = extraData.toUint(60);
setGrantForOperator(self, operator, grantId);
return (true, grantId);
} else {
return tryCapturingGrantId(self, tokenGrant, operator);
}
}
/// @notice Checks if the delegation for the given operator has been created
/// from a grant defined in the passed token grant contract and if so,
/// captures the grant ID for that delegation.
/// Grant ID can be later retrieved based on the operator address and used
/// to authenticate grantee or to fetch the information about grant
/// unlocking schedule for escrow.
/// @param tokenGrant KEEP token grant contract reference.
/// @param operator The operator tokens are delegated to.
function tryCapturingGrantId(
Storage storage self,
TokenGrant tokenGrant,
address operator
) internal returns (bool, uint256) {
(bool success, bytes memory data) = address(tokenGrant).call(
abi.encodeWithSignature("getGrantStakeDetails(address)", operator)
);
if (success) {
(uint256 grantId,,address grantStakingContract) = abi.decode(
data, (uint256, uint256, address)
);
// Double-check if the delegation in TokenGrant has been defined
// for this staking contract. If not, it means it's an old
// delegation and the current one does not come from a grant.
// The scenario covered here is:
// - grantee delegated to operator A from a TokenGrant using another
// staking contract,
// - someone delegates to operator A using liquid tokens and this
// staking contract.
// Without this check, we'd consider the second delegation as coming
// from a grant.
if (address(this) != grantStakingContract) {
return (false, 0);
}
setGrantForOperator(self, operator, grantId);
return (true, grantId);
}
return (false, 0);
}
/// @notice Returns true if the given operator operates on stake delegated
/// from a grant. false is returned otherwise.
/// @param operator The operator to which tokens from a grant are
/// potentially delegated to.
function hasGrantDelegated(
Storage storage self,
address operator
) public view returns (bool) {
return self._operatorToGrant[operator] != 0;
}
/// @notice Associates operator with the provided grant ID. It means that
/// the given operator delegates on stake from the grant with this ID.
/// @param operator The operator tokens are delegate to.
/// @param grantId Identifier of a grant from which the tokens are delegated
/// to.
function setGrantForOperator(
Storage storage self,
address operator,
uint256 grantId
) public {
self._operatorToGrant[operator] = grantId ^ GRANT_ID_FLAG;
}
/// @notice Returns grant ID for the provided operator. If the operator
/// does not operate on stake delegated from a grant, function reverts.
/// @dev To avoid reverting in case the grant ID for the operator does not
/// exist, consider calling hasGrantDelegated before.
/// @param operator The operator tokens are delegate to.
function getGrantForOperator(
Storage storage self,
address operator
) public view returns (uint256) {
uint256 grantId = self._operatorToGrant[operator];
require (grantId != 0, "No grant for the operator");
return grantId ^ GRANT_ID_FLAG;
}
/// @notice Returns true if msg.sender is grantee eligible to trigger stake
/// undelegation for this operator. Function checks both standard grantee
/// and managed grantee case.
/// @param operator The operator tokens are delegated to.
/// @param tokenGrant KEEP token grant contract reference.
function canUndelegate(
Storage storage self,
address operator,
TokenGrant tokenGrant
) public returns (bool) {
// First of all, we need to see if the operator has grant delegated.
// If not, we don't need to bother about checking grantee or
// managed grantee and we just return false.
if (!hasGrantDelegated(self, operator)) {
return false;
}
uint256 grantId = getGrantForOperator(self, operator);
(,,,,uint256 revokedAt, address grantee) = tokenGrant.getGrant(grantId);
// Is msg.sender grantee of a standard grant?
if (msg.sender == grantee) {
return true;
}
// If not, we need to dig deeper and see if we are dealing with
// a grantee from a managed grant.
if ((msg.sender).isManagedGranteeForGrant(grantId, tokenGrant)) {
return true;
}
// There is only one possibility left - grant has been revoked and
// grant manager wants to take back delegated tokens.
if (revokedAt == 0) {
return false;
}
(address grantManager,,,,) = tokenGrant.getGrantUnlockingSchedule(grantId);
return msg.sender == grantManager;
}
}
// File: @keep-network/keep-core/contracts/TokenGrant.sol
pragma solidity 0.5.17;
import "openzeppelin-solidity/contracts/token/ERC20/ERC20Burnable.sol";
import "openzeppelin-solidity/contracts/token/ERC20/SafeERC20.sol";
import "openzeppelin-solidity/contracts/math/SafeMath.sol";
import "./libraries/grant/UnlockingSchedule.sol";
import "./utils/BytesLib.sol";
import "./utils/AddressArrayUtils.sol";
import "./TokenStaking.sol";
import "./TokenGrantStake.sol";
import "./GrantStakingPolicy.sol";
/// @title TokenGrant
/// @notice A token grant contract for a specified standard ERC20Burnable token.
/// Has additional functionality to stake delegate/undelegate token grants.
/// Tokens are granted to the grantee via unlocking scheme and can be
/// withdrawn gradually based on the unlocking schedule cliff and unlocking duration.
/// Optionally grant can be revoked by the token grant manager.
contract TokenGrant {
using SafeMath for uint256;
using UnlockingSchedule for uint256;
using SafeERC20 for ERC20Burnable;
using BytesLib for bytes;
using AddressArrayUtils for address[];
event TokenGrantCreated(uint256 id);
event TokenGrantWithdrawn(uint256 indexed grantId, uint256 amount);
event TokenGrantStaked(uint256 indexed grantId, uint256 amount, address operator);
event TokenGrantRevoked(uint256 id);
event StakingContractAuthorized(address indexed grantManager, address stakingContract);
struct Grant {
address grantManager; // Token grant manager.
address grantee; // Address to which granted tokens are going to be withdrawn.
uint256 revokedAt; // Timestamp at which grant was revoked by the grant manager.
uint256 revokedAmount; // The number of tokens revoked from the grantee.
uint256 revokedWithdrawn; // The number of tokens returned to the grant creator.
bool revocable; // Whether grant manager can revoke the grant.
uint256 amount; // Amount of tokens to be granted.
uint256 duration; // Duration in seconds of the period in which the granted tokens will unlock.
uint256 start; // Timestamp at which the linear unlocking schedule will start.
uint256 cliff; // Timestamp before which no tokens will be unlocked.
uint256 withdrawn; // Amount that was withdrawn to the grantee.
uint256 staked; // Amount that was staked by the grantee.
GrantStakingPolicy stakingPolicy;
}
uint256 public numGrants;
ERC20Burnable public token;
// Staking contracts authorized by the given grant manager.
// grant manager -> staking contract -> authorized?
mapping(address => mapping (address => bool)) internal stakingContracts;
// Token grants.
mapping(uint256 => Grant) public grants;
// Token grants stakes.
mapping(address => TokenGrantStake) public grantStakes;
// Mapping of token grant IDs per particular address
// involved in a grant as a grantee or as a grant manager.
mapping(address => uint256[]) public grantIndices;
// Token grants balances. Sum of all granted tokens to a grantee.
// This includes granted tokens that are already unlocked and
// available to be withdrawn to the grantee
mapping(address => uint256) public balances;
// Mapping of operator addresses per particular grantee address.
mapping(address => address[]) public granteesToOperators;
/// @notice Creates a token grant contract for a provided Standard ERC20Burnable token.
/// @param _tokenAddress address of a token that will be linked to this contract.
constructor(address _tokenAddress) public {
require(_tokenAddress != address(0x0), "Token address can't be zero.");
token = ERC20Burnable(_tokenAddress);
}
/// @notice Used by grant manager to authorize staking contract with the given
/// address.
function authorizeStakingContract(address _stakingContract) public {
require(
_stakingContract != address(0x0),
"Staking contract address can't be zero"
);
stakingContracts[msg.sender][_stakingContract] = true;
emit StakingContractAuthorized(msg.sender, _stakingContract);
}
/// @notice Gets the amount of granted tokens to the specified address.
/// @param _owner The address to query the grants balance of.
/// @return An uint256 representing the grants balance owned by the passed address.
function balanceOf(address _owner) public view returns (uint256 balance) {
return balances[_owner];
}
/// @notice Gets the stake balance of the specified address.
/// @param _address The address to query the balance of.
/// @return An uint256 representing the amount staked by the passed address.
function stakeBalanceOf(address _address) public view returns (uint256 balance) {
for (uint i = 0; i < grantIndices[_address].length; i++) {
uint256 id = grantIndices[_address][i];
balance += grants[id].staked;
}
return balance;
}
/// @notice Gets grant by ID. Returns only basic grant data.
/// If you need unlocking schedule for the grant you must call `getGrantUnlockingSchedule()`
/// This is to avoid Ethereum `Stack too deep` issue described here:
/// https://forum.ethereum.org/discussion/2400/error-stack-too-deep-try-removing-local-variables
/// @param _id ID of the token grant.
/// @return amount The amount of tokens the grant provides.
/// @return withdrawn The amount of tokens that have already been withdrawn
/// from the grant.
/// @return staked The amount of tokens that have been staked from the grant.
/// @return revoked A boolean indicating whether the grant has been revoked,
/// which is to say that it is no longer unlocking.
/// @return grantee The grantee of grant.
function getGrant(uint256 _id) public view returns (
uint256 amount,
uint256 withdrawn,
uint256 staked,
uint256 revokedAmount,
uint256 revokedAt,
address grantee
) {
return (
grants[_id].amount,
grants[_id].withdrawn,
grants[_id].staked,
grants[_id].revokedAmount,
grants[_id].revokedAt,
grants[_id].grantee
);
}
/// @notice Gets grant unlocking schedule by grant ID.
/// @param _id ID of the token grant.
/// @return grantManager The address designated as the manager of the grant,
/// which is the only address that can revoke this grant.
/// @return duration The duration, in seconds, during which the tokens will
/// unlocking linearly.
/// @return start The start time, as a timestamp comparing to `now`.
/// @return cliff The timestamp, before which none of the tokens in the grant
/// will be unlocked, and after which a linear amount based on
/// the time elapsed since the start will be unlocked.
/// @return policy The address of the grant's staking policy.
function getGrantUnlockingSchedule(
uint256 _id
) public view returns (
address grantManager,
uint256 duration,
uint256 start,
uint256 cliff,
address policy
) {
return (
grants[_id].grantManager,
grants[_id].duration,
grants[_id].start,
grants[_id].cliff,
address(grants[_id].stakingPolicy)
);
}
/// @notice Gets grant ids of the specified address.
/// @param _granteeOrGrantManager The address to query.
/// @return An uint256 array of grant IDs.
function getGrants(address _granteeOrGrantManager) public view returns (uint256[] memory) {
return grantIndices[_granteeOrGrantManager];
}
/// @notice Gets operator addresses of the specified grantee address.
/// @param grantee The grantee address.
/// @return An array of all operators for a given grantee.
function getGranteeOperators(address grantee) public view returns (address[] memory) {
return granteesToOperators[grantee];
}
/// @notice Gets grant stake details of the given operator.
/// @param operator The operator address.
/// @return grantId ID of the token grant.
/// @return amount The amount of tokens the given operator delegated.
/// @return stakingContract The address of staking contract.
function getGrantStakeDetails(address operator) public view returns (uint256 grantId, uint256 amount, address stakingContract) {
return grantStakes[operator].getDetails();
}
/// @notice Receives approval of token transfer and creates a token grant with a unlocking
/// schedule where balance withdrawn to the grantee gradually in a linear fashion until
/// start + duration. By then all of the balance will have unlocked.
/// @param _from The owner of the tokens who approved them to transfer.
/// @param _amount Approved amount for the transfer to create token grant.
/// @param _token Token contract address.
/// @param _extraData This byte array must have the following values ABI encoded:
/// grantManager (address) Address of the grant manager.
/// grantee (address) Address of the grantee.
/// duration (uint256) Duration in seconds of the unlocking period.
/// start (uint256) Timestamp at which unlocking will start.
/// cliffDuration (uint256) Duration in seconds of the cliff;
/// no tokens will be unlocked until the time `start + cliff`.
/// revocable (bool) Whether the token grant is revocable or not (1 or 0).
/// stakingPolicy (address) Address of the staking policy for the grant.
function receiveApproval(address _from, uint256 _amount, address _token, bytes memory _extraData) public {
require(ERC20Burnable(_token) == token, "Token contract must be the same one linked to this contract.");
require(_amount <= token.balanceOf(_from), "Sender must have enough amount.");
(address _grantManager,
address _grantee,
uint256 _duration,
uint256 _start,
uint256 _cliffDuration,
bool _revocable,
address _stakingPolicy) = abi.decode(
_extraData,
(address, address, uint256, uint256, uint256, bool, address)
);
require(_grantee != address(0), "Grantee address can't be zero.");
require(
_cliffDuration <= _duration,
"Unlocking cliff duration must be less or equal total unlocking duration."
);
require(_stakingPolicy != address(0), "Staking policy can't be zero.");
uint256 id = numGrants++;
grants[id] = Grant(
_grantManager,
_grantee,
0, 0, 0,
_revocable,
_amount,
_duration,
_start,
_start.add(_cliffDuration),
0, 0,
GrantStakingPolicy(_stakingPolicy)
);
// Maintain a record to make it easier to query grants by grant manager.
grantIndices[_from].push(id);
// Maintain a record to make it easier to query grants by grantee.
grantIndices[_grantee].push(id);
token.safeTransferFrom(_from, address(this), _amount);
// Maintain a record of the unlocked amount
balances[_grantee] = balances[_grantee].add(_amount);
emit TokenGrantCreated(id);
}
/// @notice Withdraws Token grant amount to grantee.
/// @dev Transfers unlocked tokens of the token grant to grantee.
/// @param _id Grant ID.
function withdraw(uint256 _id) public {
uint256 amount = withdrawable(_id);
require(amount > 0, "Grant available to withdraw amount should be greater than zero.");
// Update withdrawn amount.
grants[_id].withdrawn = grants[_id].withdrawn.add(amount);
// Update grantee grants balance.
balances[grants[_id].grantee] = balances[grants[_id].grantee].sub(amount);
// Transfer tokens from this contract balance to the grantee token balance.
token.safeTransfer(grants[_id].grantee, amount);
emit TokenGrantWithdrawn(_id, amount);
}
/// @notice Calculates and returns unlocked grant amount.
/// @dev Calculates token grant amount that has already unlocked,
/// including any tokens that have already been withdrawn by the grantee as well
/// as any tokens that are available to withdraw but have not yet been withdrawn.
/// @param _id Grant ID.
function unlockedAmount(uint256 _id) public view returns (uint256) {
Grant storage grant = grants[_id];
return (grant.revokedAt != 0)
// Grant revoked -> return what is remaining
? grant.amount.sub(grant.revokedAmount)
// Not revoked -> calculate the unlocked amount normally
: now.getUnlockedAmount(
grant.amount,
grant.duration,
grant.start,
grant.cliff
);
}
/// @notice Calculates withdrawable granted amount.
/// @dev Calculates the amount that has already unlocked but hasn't been withdrawn yet.
/// @param _id Grant ID.
function withdrawable(uint256 _id) public view returns (uint256) {
uint256 unlocked = unlockedAmount(_id);
uint256 withdrawn = grants[_id].withdrawn;
uint256 staked = grants[_id].staked;
if (withdrawn.add(staked) >= unlocked) {
return 0;
} else {
return unlocked.sub(withdrawn).sub(staked);
}
}
/// @notice Allows the grant manager to revoke the grant.
/// @dev Granted tokens that are already unlocked (releasable amount)
/// remain in the grant so grantee can still withdraw them
/// the rest are revoked and withdrawable by token grant manager.
/// @param _id Grant ID.
function revoke(uint256 _id) public {
require(grants[_id].grantManager == msg.sender, "Only grant manager can revoke.");
require(grants[_id].revocable, "Grant must be revocable in the first place.");
require(grants[_id].revokedAt == 0, "Grant must not be already revoked.");
uint256 unlockedAmount = unlockedAmount(_id);
uint256 revokedAmount = grants[_id].amount.sub(unlockedAmount);
grants[_id].revokedAt = now;
grants[_id].revokedAmount = revokedAmount;
// Update grantee's grants balance.
balances[grants[_id].grantee] = balances[grants[_id].grantee].sub(revokedAmount);
emit TokenGrantRevoked(_id);
}
/// @notice Allows the grant manager to withdraw revoked tokens.
/// @dev Will withdraw as many of the revoked tokens as possible
/// without pushing the grant contract into a token deficit.
/// If the grantee has staked more tokens than the unlocked amount,
/// those tokens will remain in the grant until undelegated and returned,
/// after which they can be withdrawn by calling `withdrawRevoked` again.
/// @param _id Grant ID.
function withdrawRevoked(uint256 _id) public {
Grant storage grant = grants[_id];
require(
grant.grantManager == msg.sender,
"Only grant manager can withdraw revoked tokens."
);
uint256 revoked = grant.revokedAmount;
uint256 revokedWithdrawn = grant.revokedWithdrawn;
require(revokedWithdrawn < revoked, "All revoked tokens withdrawn.");
uint256 revokedRemaining = revoked.sub(revokedWithdrawn);
uint256 totalAmount = grant.amount;
uint256 staked = grant.staked;
uint256 granteeWithdrawn = grant.withdrawn;
uint256 remainingPresentInGrant =
totalAmount.sub(staked).sub(revokedWithdrawn).sub(granteeWithdrawn);
require(remainingPresentInGrant > 0, "No revoked tokens withdrawable.");
uint256 amountToWithdraw = remainingPresentInGrant < revokedRemaining
? remainingPresentInGrant
: revokedRemaining;
token.safeTransfer(msg.sender, amountToWithdraw);
grant.revokedWithdrawn += amountToWithdraw;
}
/// @notice Stake token grant.
/// @dev Stakable token grant amount is determined
/// by the grant's staking policy.
/// @param _id Grant Id.
/// @param _stakingContract Address of the staking contract.
/// @param _amount Amount to stake.
/// @param _extraData Data for stake delegation. This byte array must have
/// the following values concatenated:
/// - Beneficiary address (20 bytes)
/// - Operator address (20 bytes)
/// - Authorizer address (20 bytes)
function stake(uint256 _id, address _stakingContract, uint256 _amount, bytes memory _extraData) public {
require(grants[_id].grantee == msg.sender, "Only grantee of the grant can stake it.");
require(grants[_id].revokedAt == 0, "Revoked grant can not be staked");
require(
stakingContracts[grants[_id].grantManager][_stakingContract],
"Provided staking contract is not authorized."
);
// Expecting 60 bytes _extraData for stake delegation.
require(_extraData.length == 60, "Stake delegation data must be provided.");
address operator = _extraData.toAddress(20);
// Calculate available amount. Amount of unlocked tokens minus what user already withdrawn and staked.
require(_amount <= availableToStake(_id), "Must have available granted amount to stake.");
// Keep staking record.
TokenGrantStake grantStake = new TokenGrantStake(
address(token),
_id,
_stakingContract
);
grantStakes[operator] = grantStake;
granteesToOperators[grants[_id].grantee].push(operator);
grants[_id].staked += _amount;
token.transfer(address(grantStake), _amount);
// Staking contract expects 40 bytes _extraData for stake delegation.
// 20 bytes beneficiary's address + 20 bytes operator's address.
grantStake.stake(_amount, _extraData);
emit TokenGrantStaked(_id, _amount, operator);
}
/// @notice Returns the amount of tokens available for staking from the grant.
/// The stakeable amount is determined by the staking policy of the grant.
/// If the grantee has withdrawn some tokens
/// or the policy returns an erroneously high value,
/// the stakeable amount is limited to the number of tokens remaining.
/// @param _grantId Identifier of the grant
function availableToStake(uint256 _grantId) public view returns (uint256) {
Grant storage grant = grants[_grantId];
// Revoked grants cannot be staked.
// If the grant isn't revoked, the number of revoked tokens is 0.
if (grant.revokedAt != 0) { return 0; }
uint256 amount = grant.amount;
uint256 withdrawn = grant.withdrawn;
uint256 remaining = amount.sub(withdrawn);
uint256 stakeable = grant.stakingPolicy.getStakeableAmount(
now,
amount,
grant.duration,
grant.start,
grant.cliff,
withdrawn
);
// Clamp the stakeable amount to what is left in the grant
// in the case of a malfunctioning staking policy.
if (stakeable > remaining) {
stakeable = remaining;
}
return stakeable.sub(grant.staked);
}
/// @notice Cancels delegation within the operator initialization period
/// without being subjected to the stake lockup for the undelegation period.
/// This can be used to undo mistaken delegation to the wrong operator address.
/// @param _operator Address of the stake operator.
function cancelStake(address _operator) public {
TokenGrantStake grantStake = grantStakes[_operator];
uint256 grantId = grantStake.getGrantId();
require(
msg.sender == _operator || msg.sender == grants[grantId].grantee,
"Only operator or grantee can cancel the delegation."
);
uint256 returned = grantStake.cancelStake();
grants[grantId].staked = grants[grantId].staked.sub(returned);
}
/// @notice Undelegate the token grant.
/// @param _operator Operator of the stake.
function undelegate(address _operator) public {
TokenGrantStake grantStake = grantStakes[_operator];
uint256 grantId = grantStake.getGrantId();
require(
msg.sender == _operator || msg.sender == grants[grantId].grantee,
"Only operator or grantee can undelegate."
);
grantStake.undelegate();
}
/// @notice Force cancellation of a revoked grant's stake.
/// Can be used by the grant manager
/// to immediately withdraw tokens back into the grant,
/// from an operator still within the initialization period.
/// These tokens can then be withdrawn
/// if some revoked tokens haven't been withdrawn yet.
function cancelRevokedStake(address _operator) public {
TokenGrantStake grantStake = grantStakes[_operator];
uint256 grantId = grantStake.getGrantId();
require(
grants[grantId].revokedAt != 0,
"Grant must be revoked"
);
require(
msg.sender == grants[grantId].grantManager,
"Only grant manager can force cancellation of revoked grant stake."
);
uint256 returned = grantStake.cancelStake();
grants[grantId].staked = grants[grantId].staked.sub(returned);
}
/// @notice Force undelegation of a revoked grant's stake.
/// @dev Can be called by the grant manager once the grant is revoked.
/// Has to be done this way, instead of undelegating all operators when the
/// grant is revoked, because the latter method is vulnerable to DoS via
/// out-of-gas.
function undelegateRevoked(address _operator) public {
TokenGrantStake grantStake = grantStakes[_operator];
uint256 grantId = grantStake.getGrantId();
require(
grants[grantId].revokedAt != 0,
"Grant must be revoked"
);
require(
msg.sender == grants[grantId].grantManager,
"Only grant manager can force undelegation of revoked grant stake"
);
grantStake.undelegate();
}
/// @notice Recover stake of the token grant.
/// Recovers the tokens correctly
/// even if they were earlier recovered directly in the staking contract.
/// @param _operator Operator of the stake.
function recoverStake(address _operator) public {
TokenGrantStake grantStake = grantStakes[_operator];
uint256 returned = grantStake.recoverStake();
uint256 grantId = grantStake.getGrantId();
grants[grantId].staked = grants[grantId].staked.sub(returned);
delete grantStakes[_operator];
}
}
// File: @keep-network/keep-core/contracts/libraries/staking/Locks.sol
pragma solidity 0.5.17;
import "openzeppelin-solidity/contracts/math/SafeMath.sol";
import { AuthorityVerifier } from "../../Authorizations.sol";
import "./LockUtils.sol";
library Locks {
using SafeMath for uint256;
using LockUtils for LockUtils.LockSet;
event StakeLocked(address indexed operator, address lockCreator, uint256 until);
event LockReleased(address indexed operator, address lockCreator);
event ExpiredLockReleased(address indexed operator, address lockCreator);
uint256 public constant maximumLockDuration = 86400 * 200; // 200 days in seconds
struct Storage {
// Locks placed on the operator.
// `operatorLocks[operator]` returns all locks placed on the operator.
// Each authorized operator contract can place one lock on an operator.
mapping(address => LockUtils.LockSet) operatorLocks;
}
function lockStake(
Storage storage self,
address operator,
uint256 duration
) public {
require(duration <= maximumLockDuration, "Lock duration too long");
self.operatorLocks[operator].setLock(
msg.sender,
uint96(block.timestamp.add(duration))
);
emit StakeLocked(operator, msg.sender, block.timestamp.add(duration));
}
function releaseLock(
Storage storage self,
address operator
) public {
self.operatorLocks[operator].releaseLock(msg.sender);
emit LockReleased(operator, msg.sender);
}
function releaseExpiredLock(
Storage storage self,
address operator,
address operatorContract,
address authorityVerifier
) public {
LockUtils.LockSet storage locks = self.operatorLocks[operator];
require(
locks.contains(operatorContract),
"No matching lock present"
);
bool expired = block.timestamp >= locks.getLockTime(operatorContract);
bool disabled = !AuthorityVerifier(authorityVerifier)
.isApprovedOperatorContract(operatorContract);
require(
expired || disabled,
"Lock still active and valid"
);
locks.releaseLock(operatorContract);
emit ExpiredLockReleased(operator, operatorContract);
}
/// @dev AuthorityVerifier is a trusted implementation and not a third-party,
/// external contract. AuthorityVerifier never reverts on the check and
/// has a reasonable gas consumption.
function isStakeLocked(
Storage storage self,
address operator,
address authorityVerifier
) public view returns (bool) {
LockUtils.Lock[] storage _locks = self.operatorLocks[operator].locks;
LockUtils.Lock memory lock;
for (uint i = 0; i < _locks.length; i++) {
lock = _locks[i];
if (block.timestamp < lock.expiresAt) {
if (
AuthorityVerifier(authorityVerifier)
.isApprovedOperatorContract(lock.creator)
) {
return true;
}
}
}
return false;
}
function isStakeReleased(
Storage storage self,
address operator,
address operatorContract
) public view returns (bool) {
LockUtils.LockSet storage locks = self.operatorLocks[operator];
// `getLockTime` returns 0 if the lock doesn't exist,
// thus we don't need to check for its presence separately.
return block.timestamp >= locks.getLockTime(operatorContract);
}
function getLocks(
Storage storage self,
address operator
) public view returns (address[] memory creators, uint256[] memory expirations) {
uint256 lockCount = self.operatorLocks[operator].locks.length;
creators = new address[](lockCount);
expirations = new uint256[](lockCount);
LockUtils.Lock memory lock;
for (uint i = 0; i < lockCount; i++) {
lock = self.operatorLocks[operator].locks[i];
creators[i] = lock.creator;
expirations[i] = lock.expiresAt;
}
}
}
// File: @keep-network/keep-core/contracts/libraries/staking/TopUps.sol
pragma solidity 0.5.17;
import "openzeppelin-solidity/contracts/math/SafeMath.sol";
import "../../TokenStakingEscrow.sol";
import "../../utils/OperatorParams.sol";
/// @notice TokenStaking contract library allowing to perform two-step stake
/// top-ups for existing delegations.
/// Top-up is a two-step process: it is initiated with a declared top-up value
/// and after waiting for at least the initialization period it can be
/// committed.
library TopUps {
using SafeMath for uint256;
using OperatorParams for uint256;
event TopUpInitiated(address indexed operator, uint256 topUp);
event TopUpCompleted(address indexed operator, uint256 newAmount);
struct TopUp {
uint256 amount;
uint256 createdAt;
}
struct Storage {
// operator -> TopUp
mapping(address => TopUp) topUps;
}
/// @notice Performs top-up in one step when stake is not yet initialized by
/// adding the top-up amount to the stake and resetting stake initialization
/// time counter.
/// @dev This function should be called only for not yet initialized stake.
/// @param value Top-up value, the number of tokens added to the stake.
/// @param operator Operator The operator with existing delegation to which
/// the tokens should be added to.
/// @param operatorParams Parameters of that operator, as stored in the
/// staking contract.
/// @param escrow Reference to TokenStakingEscrow contract.
/// @return New value of parameters. It should be updated for the operator
/// in the staking contract.
function instantComplete(
Storage storage self,
uint256 value,
address operator,
uint256 operatorParams,
TokenStakingEscrow escrow
) public returns (uint256 newParams) {
// Stake is not yet initialized so we don't need to check if the
// operator is not undelegating - initializing and undelegating at the
// same time is not possible. We do however, need to check whether the
// operator has not canceled its previous stake for that operator,
// depositing the stake it in the escrow. We do not want to allow
// resurrecting operators with cancelled stake by top-ups.
require(
!escrow.hasDeposit(operator),
"Stake for the operator already deposited in the escrow"
);
require(value > 0, "Top-up value must be greater than zero");
uint256 newAmount = operatorParams.getAmount().add(value);
newParams = operatorParams.setAmountAndCreationTimestamp(
newAmount,
block.timestamp
);
emit TopUpCompleted(operator, newAmount);
}
/// @notice Initiates top-up of the given value for tokens delegated to
/// the provided operator. If there is an existing top-up still
/// initializing, top-up values are summed up and initialization period
/// is set to the current block timestamp.
/// @dev This function should be called only for active operators with
/// initialized stake.
/// @param value Top-up value, the number of tokens added to the stake.
/// @param operator Operator The operator with existing delegation to which
/// the tokens should be added to.
/// @param operatorParams Parameters of that operator, as stored in the
/// staking contract.
/// @param escrow Reference to TokenStakingEscrow contract.
function initiate(
Storage storage self,
uint256 value,
address operator,
uint256 operatorParams,
TokenStakingEscrow escrow
) public {
// Stake is initialized, the operator is still active so we need
// to check if it's not undelegating.
require(!isUndelegating(operatorParams), "Stake undelegated");
// We also need to check if the stake for the operator is not already
// in the escrow because it's been previously cancelled.
require(
!escrow.hasDeposit(operator),
"Stake for the operator already deposited in the escrow"
);
require(value > 0, "Top-up value must be greater than zero");
TopUp memory awaiting = self.topUps[operator];
self.topUps[operator] = TopUp(awaiting.amount.add(value), now);
emit TopUpInitiated(operator, value);
}
/// @notice Commits the top-up if it passed the initialization period.
/// Tokens are added to the stake once the top-up is committed.
/// @param operator Operator The operator with a pending stake top-up.
/// @param initializationPeriod Stake initialization period.
function commit(
Storage storage self,
address operator,
uint256 operatorParams,
uint256 initializationPeriod
) public returns (uint256 newParams) {
TopUp memory topUp = self.topUps[operator];
require(topUp.amount > 0, "No top up to commit");
require(
now > topUp.createdAt.add(initializationPeriod),
"Stake is initializing"
);
uint256 newAmount = operatorParams.getAmount().add(topUp.amount);
newParams = operatorParams.setAmount(newAmount);
delete self.topUps[operator];
emit TopUpCompleted(operator, newAmount);
}
/// @notice Cancels pending, initiating top-up. If there is no initiating
/// top-up for the operator, function does nothing. This function should be
/// used when the stake is recovered to return tokens from a pending,
/// initiating top-up.
/// @param operator Operator The operator from which the stake is recovered.
function cancel(
Storage storage self,
address operator
) public returns (uint256) {
TopUp memory topUp = self.topUps[operator];
if (topUp.amount == 0) {
return 0;
}
delete self.topUps[operator];
return topUp.amount;
}
/// @notice Returns true if the given operatorParams indicate that the
/// operator is undelegating its stake or that it completed stake
/// undelegation.
/// @param operatorParams Parameters of the operator, as stored in the
/// staking contract.
function isUndelegating(uint256 operatorParams)
internal view returns (bool) {
uint256 undelegatedAt = operatorParams.getUndelegationTimestamp();
return (undelegatedAt != 0) && (block.timestamp > undelegatedAt);
}
}
// File: @keep-network/keep-core/contracts/utils/PercentUtils.sol
pragma solidity 0.5.17;
import "openzeppelin-solidity/contracts/math/SafeMath.sol";
library PercentUtils {
using SafeMath for uint256;
// Return `b`% of `a`
// 200.percent(40) == 80
// Commutative, works both ways
function percent(uint256 a, uint256 b) internal pure returns (uint256) {
return a.mul(b).div(100);
}
// Return `a` as percentage of `b`:
// 80.asPercentOf(200) == 40
function asPercentOf(uint256 a, uint256 b) internal pure returns (uint256) {
return a.mul(100).div(b);
}
}
// File: @keep-network/keep-core/contracts/utils/BytesLib.sol
pragma solidity 0.5.17;
/*
Verison pulled from https://github.com/summa-tx/bitcoin-spv/blob/2535e4edaeaac4b2b095903fce684ae1c05761bc/solidity/contracts/BytesLib.sol
*/
/*
https://github.com/GNSPS/solidity-bytes-utils/
This is free and unencumbered software released into the public domain.
Anyone is free to copy, modify, publish, use, compile, sell, or
distribute this software, either in source code form or as a compiled
binary, for any purpose, commercial or non-commercial, and by any
means.
In jurisdictions that recognize copyright laws, the author or authors
of this software dedicate any and all copyright interest in the
software to the public domain. We make this dedication for the benefit
of the public at large and to the detriment of our heirs and
successors. We intend this dedication to be an overt act of
relinquishment in perpetuity of all present and future rights to this
software under copyright law.
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 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.
For more information, please refer to <https://unlicense.org>
*/
/** @title BytesLib **/
/** @author https://github.com/GNSPS **/
library BytesLib {
function concat(bytes memory _preBytes, bytes memory _postBytes) internal pure returns (bytes memory) {
bytes memory tempBytes;
assembly {
// Get a location of some free memory and store it in tempBytes as
// Solidity does for memory variables.
tempBytes := mload(0x40)
// Store the length of the first bytes array at the beginning of
// the memory for tempBytes.
let length := mload(_preBytes)
mstore(tempBytes, length)
// Maintain a memory counter for the current write location in the
// temp bytes array by adding the 32 bytes for the array length to
// the starting location.
let mc := add(tempBytes, 0x20)
// Stop copying when the memory counter reaches the length of the
// first bytes array.
let end := add(mc, length)
for {
// Initialize a copy counter to the start of the _preBytes data,
// 32 bytes into its memory.
let cc := add(_preBytes, 0x20)
} lt(mc, end) {
// Increase both counters by 32 bytes each iteration.
mc := add(mc, 0x20)
cc := add(cc, 0x20)
} {
// Write the _preBytes data into the tempBytes memory 32 bytes
// at a time.
mstore(mc, mload(cc))
}
// Add the length of _postBytes to the current length of tempBytes
// and store it as the new length in the first 32 bytes of the
// tempBytes memory.
length := mload(_postBytes)
mstore(tempBytes, add(length, mload(tempBytes)))
// Move the memory counter back from a multiple of 0x20 to the
// actual end of the _preBytes data.
mc := end
// Stop copying when the memory counter reaches the new combined
// length of the arrays.
end := add(mc, length)
for {
let cc := add(_postBytes, 0x20)
} lt(mc, end) {
mc := add(mc, 0x20)
cc := add(cc, 0x20)
} {
mstore(mc, mload(cc))
}
// Update the free-memory pointer by padding our last write location
// to 32 bytes: add 31 bytes to the end of tempBytes to move to the
// next 32 byte block, then round down to the nearest multiple of
// 32. If the sum of the length of the two arrays is zero then add
// one before rounding down to leave a blank 32 bytes (the length block with 0).
mstore(0x40, and(
add(add(end, iszero(add(length, mload(_preBytes)))), 31),
not(31) // Round down to the nearest 32 bytes.
))
}
return tempBytes;
}
function concatStorage(bytes storage _preBytes, bytes memory _postBytes) internal {
assembly {
// Read the first 32 bytes of _preBytes storage, which is the length
// of the array. (We don't need to use the offset into the slot
// because arrays use the entire slot.)
let fslot := sload(_preBytes_slot)
// Arrays of 31 bytes or less have an even value in their slot,
// while longer arrays have an odd value. The actual length is
// the slot divided by two for odd values, and the lowest order
// byte divided by two for even values.
// If the slot is even, bitwise and the slot with 255 and divide by
// two to get the length. If the slot is odd, bitwise and the slot
// with -1 and divide by two.
let slength := div(and(fslot, sub(mul(0x100, iszero(and(fslot, 1))), 1)), 2)
let mlength := mload(_postBytes)
let newlength := add(slength, mlength)
// slength can contain both the length and contents of the array
// if length < 32 bytes so let's prepare for that
// v. http://solidity.readthedocs.io/en/latest/miscellaneous.html#layout-of-state-variables-in-storage
switch add(lt(slength, 32), lt(newlength, 32))
case 2 {
// Since the new array still fits in the slot, we just need to
// update the contents of the slot.
// uint256(bytes_storage) = uint256(bytes_storage) + uint256(bytes_memory) + new_length
sstore(
_preBytes_slot,
// all the modifications to the slot are inside this
// next block
add(
// we can just add to the slot contents because the
// bytes we want to change are the LSBs
fslot,
add(
mul(
div(
// load the bytes from memory
mload(add(_postBytes, 0x20)),
// zero all bytes to the right
exp(0x100, sub(32, mlength))
),
// and now shift left the number of bytes to
// leave space for the length in the slot
exp(0x100, sub(32, newlength))
),
// increase length by the double of the memory
// bytes length
mul(mlength, 2)
)
)
)
}
case 1 {
// The stored value fits in the slot, but the combined value
// will exceed it.
// get the keccak hash to get the contents of the array
mstore(0x0, _preBytes_slot)
let sc := add(keccak256(0x0, 0x20), div(slength, 32))
// save new length
sstore(_preBytes_slot, add(mul(newlength, 2), 1))
// The contents of the _postBytes array start 32 bytes into
// the structure. Our first read should obtain the `submod`
// bytes that can fit into the unused space in the last word
// of the stored array. To get this, we read 32 bytes starting
// from `submod`, so the data we read overlaps with the array
// contents by `submod` bytes. Masking the lowest-order
// `submod` bytes allows us to add that value directly to the
// stored value.
let submod := sub(32, slength)
let mc := add(_postBytes, submod)
let end := add(_postBytes, mlength)
let mask := sub(exp(0x100, submod), 1)
sstore(
sc,
add(
and(
fslot,
0xffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff00
),
and(mload(mc), mask)
)
)
for {
mc := add(mc, 0x20)
sc := add(sc, 1)
} lt(mc, end) {
sc := add(sc, 1)
mc := add(mc, 0x20)
} {
sstore(sc, mload(mc))
}
mask := exp(0x100, sub(mc, end))
sstore(sc, mul(div(mload(mc), mask), mask))
}
default {
// get the keccak hash to get the contents of the array
mstore(0x0, _preBytes_slot)
// Start copying to the last used word of the stored array.
let sc := add(keccak256(0x0, 0x20), div(slength, 32))
// save new length
sstore(_preBytes_slot, add(mul(newlength, 2), 1))
// Copy over the first `submod` bytes of the new data as in
// case 1 above.
let slengthmod := mod(slength, 32)
let mlengthmod := mod(mlength, 32)
let submod := sub(32, slengthmod)
let mc := add(_postBytes, submod)
let end := add(_postBytes, mlength)
let mask := sub(exp(0x100, submod), 1)
sstore(sc, add(sload(sc), and(mload(mc), mask)))
for {
sc := add(sc, 1)
mc := add(mc, 0x20)
} lt(mc, end) {
sc := add(sc, 1)
mc := add(mc, 0x20)
} {
sstore(sc, mload(mc))
}
mask := exp(0x100, sub(mc, end))
sstore(sc, mul(div(mload(mc), mask), mask))
}
}
}
function slice(bytes memory _bytes, uint _start, uint _length) internal pure returns (bytes memory res) {
uint _end = _start + _length;
require(_end > _start && _bytes.length >= _end, "Slice out of bounds");
assembly {
// Alloc bytes array with additional 32 bytes afterspace and assign it's size
res := mload(0x40)
mstore(0x40, add(add(res, 64), _length))
mstore(res, _length)
// Compute distance between source and destination pointers
let diff := sub(res, add(_bytes, _start))
for {
let src := add(add(_bytes, 32), _start)
let end := add(src, _length)
} lt(src, end) {
src := add(src, 32)
} {
mstore(add(src, diff), mload(src))
}
}
}
function toAddress(bytes memory _bytes, uint _start) internal pure returns (address) {
uint _totalLen = _start + 20;
require(_totalLen > _start && _bytes.length >= _totalLen, "Address conversion out of bounds.");
address tempAddress;
assembly {
tempAddress := div(mload(add(add(_bytes, 0x20), _start)), 0x1000000000000000000000000)
}
return tempAddress;
}
function toUint8(bytes memory _bytes, uint _start) internal pure returns (uint8) {
require(_bytes.length >= (_start + 1), "Uint8 conversion out of bounds.");
uint8 tempUint;
assembly {
tempUint := mload(add(add(_bytes, 0x1), _start))
}
return tempUint;
}
function toUint(bytes memory _bytes, uint _start) internal pure returns (uint256) {
uint _totalLen = _start + 32;
require(_totalLen > _start && _bytes.length >= _totalLen, "Uint conversion out of bounds.");
uint256 tempUint;
assembly {
tempUint := mload(add(add(_bytes, 0x20), _start))
}
return tempUint;
}
function equal(bytes memory _preBytes, bytes memory _postBytes) internal pure returns (bool) {
bool success = true;
assembly {
let length := mload(_preBytes)
// if lengths don't match the arrays are not equal
switch eq(length, mload(_postBytes))
case 1 {
// cb is a circuit breaker in the for loop since there's
// no said feature for inline assembly loops
// cb = 1 - don't breaker
// cb = 0 - break
let cb := 1
let mc := add(_preBytes, 0x20)
let end := add(mc, length)
for {
let cc := add(_postBytes, 0x20)
// the next line is the loop condition:
// while(uint(mc < end) + cb == 2)
} eq(add(lt(mc, end), cb), 2) {
mc := add(mc, 0x20)
cc := add(cc, 0x20)
} {
// if any of these checks fails then arrays are not equal
if iszero(eq(mload(mc), mload(cc))) {
// unsuccess:
success := 0
cb := 0
}
}
}
default {
// unsuccess:
success := 0
}
}
return success;
}
function equalStorage(bytes storage _preBytes, bytes memory _postBytes) internal view returns (bool) {
bool success = true;
assembly {
// we know _preBytes_offset is 0
let fslot := sload(_preBytes_slot)
// Decode the length of the stored array like in concatStorage().
let slength := div(and(fslot, sub(mul(0x100, iszero(and(fslot, 1))), 1)), 2)
let mlength := mload(_postBytes)
// if lengths don't match the arrays are not equal
switch eq(slength, mlength)
case 1 {
// slength can contain both the length and contents of the array
// if length < 32 bytes so let's prepare for that
// v. http://solidity.readthedocs.io/en/latest/miscellaneous.html#layout-of-state-variables-in-storage
if iszero(iszero(slength)) {
switch lt(slength, 32)
case 1 {
// blank the last byte which is the length
fslot := mul(div(fslot, 0x100), 0x100)
if iszero(eq(fslot, mload(add(_postBytes, 0x20)))) {
// unsuccess:
success := 0
}
}
default {
// cb is a circuit breaker in the for loop since there's
// no said feature for inline assembly loops
// cb = 1 - don't breaker
// cb = 0 - break
let cb := 1
// get the keccak hash to get the contents of the array
mstore(0x0, _preBytes_slot)
let sc := keccak256(0x0, 0x20)
let mc := add(_postBytes, 0x20)
let end := add(mc, mlength)
// the next line is the loop condition:
// while(uint(mc < end) + cb == 2)
for {} eq(add(lt(mc, end), cb), 2) {
sc := add(sc, 1)
mc := add(mc, 0x20)
} {
if iszero(eq(sload(sc), mload(mc))) {
// unsuccess:
success := 0
cb := 0
}
}
}
}
}
default {
// unsuccess:
success := 0
}
}
return success;
}
function toBytes32(bytes memory _source) pure internal returns (bytes32 result) {
if (_source.length == 0) {
return 0x0;
}
assembly {
result := mload(add(_source, 32))
}
}
function keccak256Slice(bytes memory _bytes, uint _start, uint _length) pure internal returns (bytes32 result) {
uint _end = _start + _length;
require(_end > _start && _bytes.length >= _end, "Slice out of bounds");
assembly {
result := keccak256(add(add(_bytes, 32), _start), _length)
}
}
}
// File: openzeppelin-solidity/contracts/token/ERC20/ERC20Burnable.sol
pragma solidity ^0.5.0;
import "./ERC20.sol";
/**
* @dev Extension of `ERC20` that allows token holders to destroy both their own
* tokens and those that they have an allowance for, in a way that can be
* recognized off-chain (via event analysis).
*/
contract ERC20Burnable is ERC20 {
/**
* @dev Destoys `amount` tokens from the caller.
*
* See `ERC20._burn`.
*/
function burn(uint256 amount) public {
_burn(msg.sender, amount);
}
/**
* @dev See `ERC20._burnFrom`.
*/
function burnFrom(address account, uint256 amount) public {
_burnFrom(account, amount);
}
}
// File: openzeppelin-solidity/contracts/token/ERC20/ERC20.sol
pragma solidity ^0.5.0;
import "./IERC20.sol";
import "../../math/SafeMath.sol";
/**
* @dev Implementation of the `IERC20` interface.
*
* This implementation is agnostic to the way tokens are created. This means
* that a supply mechanism has to be added in a derived contract using `_mint`.
* For a generic mechanism see `ERC20Mintable`.
*
* *For a detailed writeup see our guide [How to implement supply
* mechanisms](https://forum.zeppelin.solutions/t/how-to-implement-erc20-supply-mechanisms/226).*
*
* We have followed general OpenZeppelin guidelines: functions revert instead
* of returning `false` on failure. This behavior is nonetheless conventional
* and does not conflict with the expectations of ERC20 applications.
*
* Additionally, an `Approval` event is emitted on calls to `transferFrom`.
* This allows applications to reconstruct the allowance for all accounts just
* by listening to said events. Other implementations of the EIP may not emit
* these events, as it isn't required by the specification.
*
* Finally, the non-standard `decreaseAllowance` and `increaseAllowance`
* functions have been added to mitigate the well-known issues around setting
* allowances. See `IERC20.approve`.
*/
contract ERC20 is IERC20 {
using SafeMath for uint256;
mapping (address => uint256) private _balances;
mapping (address => mapping (address => uint256)) private _allowances;
uint256 private _totalSupply;
/**
* @dev See `IERC20.totalSupply`.
*/
function totalSupply() public view returns (uint256) {
return _totalSupply;
}
/**
* @dev See `IERC20.balanceOf`.
*/
function balanceOf(address account) public view returns (uint256) {
return _balances[account];
}
/**
* @dev See `IERC20.transfer`.
*
* Requirements:
*
* - `recipient` cannot be the zero address.
* - the caller must have a balance of at least `amount`.
*/
function transfer(address recipient, uint256 amount) public returns (bool) {
_transfer(msg.sender, recipient, amount);
return true;
}
/**
* @dev See `IERC20.allowance`.
*/
function allowance(address owner, address spender) public view returns (uint256) {
return _allowances[owner][spender];
}
/**
* @dev See `IERC20.approve`.
*
* Requirements:
*
* - `spender` cannot be the zero address.
*/
function approve(address spender, uint256 value) public returns (bool) {
_approve(msg.sender, spender, value);
return true;
}
/**
* @dev See `IERC20.transferFrom`.
*
* Emits an `Approval` event indicating the updated allowance. This is not
* required by the EIP. See the note at the beginning of `ERC20`;
*
* Requirements:
* - `sender` and `recipient` cannot be the zero address.
* - `sender` must have a balance of at least `value`.
* - the caller must have allowance for `sender`'s tokens of at least
* `amount`.
*/
function transferFrom(address sender, address recipient, uint256 amount) public returns (bool) {
_transfer(sender, recipient, amount);
_approve(sender, msg.sender, _allowances[sender][msg.sender].sub(amount));
return true;
}
/**
* @dev Atomically increases the allowance granted to `spender` by the caller.
*
* This is an alternative to `approve` that can be used as a mitigation for
* problems described in `IERC20.approve`.
*
* Emits an `Approval` event indicating the updated allowance.
*
* Requirements:
*
* - `spender` cannot be the zero address.
*/
function increaseAllowance(address spender, uint256 addedValue) public returns (bool) {
_approve(msg.sender, spender, _allowances[msg.sender][spender].add(addedValue));
return true;
}
/**
* @dev Atomically decreases the allowance granted to `spender` by the caller.
*
* This is an alternative to `approve` that can be used as a mitigation for
* problems described in `IERC20.approve`.
*
* Emits an `Approval` event indicating the updated allowance.
*
* Requirements:
*
* - `spender` cannot be the zero address.
* - `spender` must have allowance for the caller of at least
* `subtractedValue`.
*/
function decreaseAllowance(address spender, uint256 subtractedValue) public returns (bool) {
_approve(msg.sender, spender, _allowances[msg.sender][spender].sub(subtractedValue));
return true;
}
/**
* @dev Moves tokens `amount` from `sender` to `recipient`.
*
* This is internal function is equivalent to `transfer`, and can be used to
* e.g. implement automatic token fees, slashing mechanisms, etc.
*
* Emits a `Transfer` event.
*
* Requirements:
*
* - `sender` cannot be the zero address.
* - `recipient` cannot be the zero address.
* - `sender` must have a balance of at least `amount`.
*/
function _transfer(address sender, address recipient, uint256 amount) internal {
require(sender != address(0), "ERC20: transfer from the zero address");
require(recipient != address(0), "ERC20: transfer to the zero address");
_balances[sender] = _balances[sender].sub(amount);
_balances[recipient] = _balances[recipient].add(amount);
emit Transfer(sender, recipient, amount);
}
/** @dev Creates `amount` tokens and assigns them to `account`, increasing
* the total supply.
*
* Emits a `Transfer` event with `from` set to the zero address.
*
* Requirements
*
* - `to` cannot be the zero address.
*/
function _mint(address account, uint256 amount) internal {
require(account != address(0), "ERC20: mint to the zero address");
_totalSupply = _totalSupply.add(amount);
_balances[account] = _balances[account].add(amount);
emit Transfer(address(0), account, amount);
}
/**
* @dev Destoys `amount` tokens from `account`, reducing the
* total supply.
*
* Emits a `Transfer` event with `to` set to the zero address.
*
* Requirements
*
* - `account` cannot be the zero address.
* - `account` must have at least `amount` tokens.
*/
function _burn(address account, uint256 value) internal {
require(account != address(0), "ERC20: burn from the zero address");
_totalSupply = _totalSupply.sub(value);
_balances[account] = _balances[account].sub(value);
emit Transfer(account, address(0), value);
}
/**
* @dev Sets `amount` as the allowance of `spender` over the `owner`s tokens.
*
* This is internal function is equivalent to `approve`, and can be used to
* e.g. set automatic allowances for certain subsystems, etc.
*
* Emits an `Approval` event.
*
* Requirements:
*
* - `owner` cannot be the zero address.
* - `spender` cannot be the zero address.
*/
function _approve(address owner, address spender, uint256 value) internal {
require(owner != address(0), "ERC20: approve from the zero address");
require(spender != address(0), "ERC20: approve to the zero address");
_allowances[owner][spender] = value;
emit Approval(owner, spender, value);
}
/**
* @dev Destoys `amount` tokens from `account`.`amount` is then deducted
* from the caller's allowance.
*
* See `_burn` and `_approve`.
*/
function _burnFrom(address account, uint256 amount) internal {
_burn(account, amount);
_approve(account, msg.sender, _allowances[account][msg.sender].sub(amount));
}
}
// File: openzeppelin-solidity/contracts/token/ERC20/ERC20Detailed.sol
pragma solidity ^0.5.0;
import "./IERC20.sol";
/**
* @dev Optional functions from the ERC20 standard.
*/
contract ERC20Detailed is IERC20 {
string private _name;
string private _symbol;
uint8 private _decimals;
/**
* @dev Sets the values for `name`, `symbol`, and `decimals`. All three of
* these values are immutable: they can only be set once during
* construction.
*/
constructor (string memory name, string memory symbol, uint8 decimals) public {
_name = name;
_symbol = symbol;
_decimals = decimals;
}
/**
* @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.
*
* > Note that 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;
}
}
// File: openzeppelin-solidity/contracts/token/ERC20/IERC20.sol
pragma solidity ^0.5.0;
/**
* @dev Interface of the ERC20 standard as defined in the EIP. Does not include
* the optional functions; to access them see `ERC20Detailed`.
*/
interface IERC20 {
/**
* @dev Returns the amount of tokens in existence.
*/
function totalSupply() external view returns (uint256);
/**
* @dev Returns the amount of tokens owned by `account`.
*/
function balanceOf(address account) external view returns (uint256);
/**
* @dev Moves `amount` tokens from the caller's account to `recipient`.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a `Transfer` event.
*/
function transfer(address recipient, uint256 amount) external returns (bool);
/**
* @dev Returns the remaining number of tokens that `spender` will be
* allowed to spend on behalf of `owner` through `transferFrom`. This is
* zero by default.
*
* This value changes when `approve` or `transferFrom` are called.
*/
function allowance(address owner, address spender) external view returns (uint256);
/**
* @dev Sets `amount` as the allowance of `spender` over the caller's tokens.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* > Beware that changing an allowance with this method brings the risk
* that someone may use both the old and the new allowance by unfortunate
* transaction ordering. One possible solution to mitigate this race
* condition is to first reduce the spender's allowance to 0 and set the
* desired value afterwards:
* https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729
*
* Emits an `Approval` event.
*/
function approve(address spender, uint256 amount) external returns (bool);
/**
* @dev Moves `amount` tokens from `sender` to `recipient` using the
* allowance mechanism. `amount` is then deducted from the caller's
* allowance.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a `Transfer` event.
*/
function transferFrom(address sender, address recipient, uint256 amount) external returns (bool);
/**
* @dev Emitted when `value` tokens are moved from one account (`from`) to
* another (`to`).
*
* Note that `value` may be zero.
*/
event Transfer(address indexed from, address indexed to, uint256 value);
/**
* @dev Emitted when the allowance of a `spender` for an `owner` is set by
* a call to `approve`. `value` is the new allowance.
*/
event Approval(address indexed owner, address indexed spender, uint256 value);
}
// File: openzeppelin-solidity/contracts/token/ERC20/SafeERC20.sol
pragma solidity ^0.5.0;
import "./IERC20.sol";
import "../../math/SafeMath.sol";
import "../../utils/Address.sol";
/**
* @title SafeERC20
* @dev Wrappers around ERC20 operations that throw on failure (when the token
* contract returns false). Tokens that return no value (and instead revert or
* throw on failure) are also supported, non-reverting calls are assumed to be
* successful.
* To use this library you can add a `using SafeERC20 for ERC20;` statement to your contract,
* which allows you to call the safe operations as `token.safeTransfer(...)`, etc.
*/
library SafeERC20 {
using SafeMath for uint256;
using Address for address;
function safeTransfer(IERC20 token, address to, uint256 value) internal {
callOptionalReturn(token, abi.encodeWithSelector(token.transfer.selector, to, value));
}
function safeTransferFrom(IERC20 token, address from, address to, uint256 value) internal {
callOptionalReturn(token, abi.encodeWithSelector(token.transferFrom.selector, from, to, value));
}
function safeApprove(IERC20 token, address spender, uint256 value) internal {
// safeApprove should only be called when setting an initial allowance,
// or when resetting it to zero. To increase and decrease it, use
// 'safeIncreaseAllowance' and 'safeDecreaseAllowance'
// solhint-disable-next-line max-line-length
require((value == 0) || (token.allowance(address(this), spender) == 0),
"SafeERC20: approve from non-zero to non-zero allowance"
);
callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, value));
}
function safeIncreaseAllowance(IERC20 token, address spender, uint256 value) internal {
uint256 newAllowance = token.allowance(address(this), spender).add(value);
callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance));
}
function safeDecreaseAllowance(IERC20 token, address spender, uint256 value) internal {
uint256 newAllowance = token.allowance(address(this), spender).sub(value);
callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance));
}
/**
* @dev Imitates a Solidity high-level call (i.e. a regular function call to a contract), relaxing the requirement
* on the return value: the return value is optional (but if data is returned, it must not be false).
* @param token The token targeted by the call.
* @param data The call data (encoded using abi.encode or one of its variants).
*/
function callOptionalReturn(IERC20 token, bytes memory data) private {
// We need to perform a low level call here, to bypass Solidity's return data size checking mechanism, since
// we're implementing it ourselves.
// A Solidity high level call has three parts:
// 1. The target address is checked to verify it contains contract code
// 2. The call itself is made, and success asserted
// 3. The return value is decoded, which in turn checks the size of the returned data.
// solhint-disable-next-line max-line-length
require(address(token).isContract(), "SafeERC20: call to non-contract");
// solhint-disable-next-line avoid-low-level-calls
(bool success, bytes memory returndata) = address(token).call(data);
require(success, "SafeERC20: low-level call failed");
if (returndata.length > 0) { // Return data is optional
// solhint-disable-next-line max-line-length
require(abi.decode(returndata, (bool)), "SafeERC20: ERC20 operation did not succeed");
}
}
}
// File: openzeppelin-solidity/contracts/utils/Address.sol
pragma solidity ^0.5.0;
/**
* @dev Collection of functions related to the address type,
*/
library Address {
/**
* @dev Returns true if `account` is a contract.
*
* This test is non-exhaustive, and there may be false-negatives: during the
* execution of a contract's constructor, its address will be reported as
* not containing a contract.
*
* > It is unsafe to assume that an address for which this function returns
* false is an externally-owned account (EOA) and not a contract.
*/
function isContract(address account) internal view returns (bool) {
// This method relies in extcodesize, which returns 0 for contracts in
// construction, since the code is only stored at the end of the
// constructor execution.
uint256 size;
// solhint-disable-next-line no-inline-assembly
assembly { size := extcodesize(account) }
return size > 0;
}
}
// File: openzeppelin-solidity/contracts/math/SafeMath.sol
pragma solidity ^0.5.0;
/**
* @dev Wrappers over Solidity's arithmetic operations with added overflow
* checks.
*
* Arithmetic operations in Solidity wrap on overflow. This can easily result
* in bugs, because programmers usually assume that an overflow raises an
* error, which is the standard behavior in high level programming languages.
* `SafeMath` restores this intuition by reverting the transaction when an
* operation overflows.
*
* Using this library instead of the unchecked operations eliminates an entire
* class of bugs, so it's recommended to use it always.
*/
library SafeMath {
/**
* @dev Returns the addition of two unsigned integers, reverting on
* overflow.
*
* Counterpart to Solidity's `+` operator.
*
* Requirements:
* - Addition cannot overflow.
*/
function add(uint256 a, uint256 b) internal pure returns (uint256) {
uint256 c = a + b;
require(c >= a, "SafeMath: addition overflow");
return c;
}
/**
* @dev Returns the subtraction of two unsigned integers, reverting on
* overflow (when the result is negative).
*
* Counterpart to Solidity's `-` operator.
*
* Requirements:
* - Subtraction cannot overflow.
*/
function sub(uint256 a, uint256 b) internal pure returns (uint256) {
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: openzeppelin-solidity/contracts/ownership/Ownable.sol
pragma solidity ^0.5.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.
*
* This module is used through inheritance. It will make available the modifier
* `onlyOwner`, which can be aplied 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), _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: solidity/contracts/KeepBonding.sol
/**
▓▓▌ ▓▓ ▐▓▓ ▓▓▓▓▓▓▓▓▓▓▌▐▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓ ▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓ ▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▄
▓▓▓▓▓▓▓▓▓▓ ▓▓▓▓▓▓▓▓▓▓▌▐▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓ ▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓ ▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓
▓▓▓▓▓▓ ▓▓▓▓▓▓▓▀ ▐▓▓▓▓▓▓ ▐▓▓▓▓▓ ▓▓▓▓▓▓ ▓▓▓▓▓ ▐▓▓▓▓▓▌ ▐▓▓▓▓▓▓
▓▓▓▓▓▓▄▄▓▓▓▓▓▓▓▀ ▐▓▓▓▓▓▓▄▄▄▄ ▓▓▓▓▓▓▄▄▄▄ ▐▓▓▓▓▓▌ ▐▓▓▓▓▓▓
▓▓▓▓▓▓▓▓▓▓▓▓▓▀ ▐▓▓▓▓▓▓▓▓▓▓ ▓▓▓▓▓▓▓▓▓▓▌ ▐▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓
▓▓▓▓▓▓▀▀▓▓▓▓▓▓▄ ▐▓▓▓▓▓▓▀▀▀▀ ▓▓▓▓▓▓▀▀▀▀ ▐▓▓▓▓▓▓▓▓▓▓▓▓▓▓▀
▓▓▓▓▓▓ ▀▓▓▓▓▓▓▄ ▐▓▓▓▓▓▓ ▓▓▓▓▓ ▓▓▓▓▓▓ ▓▓▓▓▓ ▐▓▓▓▓▓▌
▓▓▓▓▓▓▓▓▓▓ █▓▓▓▓▓▓▓▓▓ ▐▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓ ▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓ ▓▓▓▓▓▓▓▓▓▓
▓▓▓▓▓▓▓▓▓▓ ▓▓▓▓▓▓▓▓▓▓ ▐▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓ ▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓ ▓▓▓▓▓▓▓▓▓▓
Trust math, not hardware.
*/
pragma solidity 0.5.17;
import "./AbstractBonding.sol";
import "@keep-network/keep-core/contracts/TokenGrant.sol";
import "@keep-network/keep-core/contracts/libraries/RolesLookup.sol";
/// @title Keep Bonding
/// @notice Contract holding deposits from keeps' operators.
contract KeepBonding is AbstractBonding {
using RolesLookup for address payable;
// KEEP Token Staking contract.
TokenStaking internal tokenStaking;
// KEEP token grant contract.
TokenGrant internal tokenGrant;
/// @notice Initializes Keep Bonding contract.
/// @param registryAddress Keep registry contract address.
/// @param tokenStakingAddress KEEP token staking contract address.
/// @param tokenGrantAddress KEEP token grant contract address.
constructor(
address registryAddress,
address tokenStakingAddress,
address tokenGrantAddress
) public AbstractBonding(registryAddress) {
tokenStaking = TokenStaking(tokenStakingAddress);
tokenGrant = TokenGrant(tokenGrantAddress);
}
/// @notice Withdraws amount from operator's value available for bonding.
/// Should not be used by grantee of managed grants. For this case,
/// please use `withdrawAsManagedGrantee`.
///
/// This function can be called only by:
/// - operator,
/// - liquid, staked tokens owner (not a grant),
/// - direct staked tokens grantee (not a managed grant).
///
/// @param amount Value to withdraw in wei.
/// @param operator Address of the operator.
function withdraw(uint256 amount, address operator) public {
require(
msg.sender == operator ||
msg.sender.isTokenOwnerForOperator(operator, tokenStaking) ||
msg.sender.isGranteeForOperator(operator, tokenGrant),
"Only operator or the owner is allowed to withdraw bond"
);
withdrawBond(amount, operator);
}
/// @notice Withdraws amount from operator's value available for bonding.
/// Can be called only by staked tokens managed grantee.
/// @param amount Value to withdraw in wei.
/// @param operator Address of the operator.
/// @param managedGrant Address of the managed grant contract.
function withdrawAsManagedGrantee(
uint256 amount,
address operator,
address managedGrant
) public {
require(
msg.sender.isManagedGranteeForOperator(
operator,
managedGrant,
tokenGrant
),
"Only grantee is allowed to withdraw bond"
);
withdrawBond(amount, operator);
}
function isAuthorizedForOperator(
address _operator,
address _operatorContract
) public view returns (bool) {
return
tokenStaking.isAuthorizedForOperator(_operator, _operatorContract);
}
function authorizerOf(address _operator) public view returns (address) {
return tokenStaking.authorizerOf(_operator);
}
function beneficiaryOf(address _operator)
public
view
returns (address payable)
{
return tokenStaking.beneficiaryOf(_operator);
}
}
// File: solidity/contracts/AbstractBonding.sol
/**
▓▓▌ ▓▓ ▐▓▓ ▓▓▓▓▓▓▓▓▓▓▌▐▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓ ▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓ ▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▄
▓▓▓▓▓▓▓▓▓▓ ▓▓▓▓▓▓▓▓▓▓▌▐▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓ ▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓ ▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓
▓▓▓▓▓▓ ▓▓▓▓▓▓▓▀ ▐▓▓▓▓▓▓ ▐▓▓▓▓▓ ▓▓▓▓▓▓ ▓▓▓▓▓ ▐▓▓▓▓▓▌ ▐▓▓▓▓▓▓
▓▓▓▓▓▓▄▄▓▓▓▓▓▓▓▀ ▐▓▓▓▓▓▓▄▄▄▄ ▓▓▓▓▓▓▄▄▄▄ ▐▓▓▓▓▓▌ ▐▓▓▓▓▓▓
▓▓▓▓▓▓▓▓▓▓▓▓▓▀ ▐▓▓▓▓▓▓▓▓▓▓ ▓▓▓▓▓▓▓▓▓▓▌ ▐▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓
▓▓▓▓▓▓▀▀▓▓▓▓▓▓▄ ▐▓▓▓▓▓▓▀▀▀▀ ▓▓▓▓▓▓▀▀▀▀ ▐▓▓▓▓▓▓▓▓▓▓▓▓▓▓▀
▓▓▓▓▓▓ ▀▓▓▓▓▓▓▄ ▐▓▓▓▓▓▓ ▓▓▓▓▓ ▓▓▓▓▓▓ ▓▓▓▓▓ ▐▓▓▓▓▓▌
▓▓▓▓▓▓▓▓▓▓ █▓▓▓▓▓▓▓▓▓ ▐▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓ ▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓ ▓▓▓▓▓▓▓▓▓▓
▓▓▓▓▓▓▓▓▓▓ ▓▓▓▓▓▓▓▓▓▓ ▐▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓ ▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓ ▓▓▓▓▓▓▓▓▓▓
Trust math, not hardware.
*/
pragma solidity 0.5.17;
import "./api/IBondingManagement.sol";
import "@keep-network/keep-core/contracts/KeepRegistry.sol";
import "openzeppelin-solidity/contracts/math/SafeMath.sol";
/// @title Abstract Bonding
/// @notice Contract holding deposits from keeps' operators.
contract AbstractBonding is IBondingManagement {
using SafeMath for uint256;
// Registry contract with a list of approved factories (operator contracts).
KeepRegistry internal registry;
// Unassigned value in wei deposited by operators.
mapping(address => uint256) public unbondedValue;
// References to created bonds. Bond identifier is built from operator's
// address, holder's address and reference ID assigned on bond creation.
mapping(bytes32 => uint256) internal lockedBonds;
// Sortition pools authorized by operator's authorizer.
// operator -> pool -> boolean
mapping(address => mapping(address => bool)) internal authorizedPools;
event UnbondedValueDeposited(
address indexed operator,
address indexed beneficiary,
uint256 amount
);
event UnbondedValueWithdrawn(
address indexed operator,
address indexed beneficiary,
uint256 amount
);
event BondCreated(
address indexed operator,
address indexed holder,
address indexed sortitionPool,
uint256 referenceID,
uint256 amount
);
event BondReassigned(
address indexed operator,
uint256 indexed referenceID,
address newHolder,
uint256 newReferenceID
);
event BondReleased(address indexed operator, uint256 indexed referenceID);
event BondSeized(
address indexed operator,
uint256 indexed referenceID,
address destination,
uint256 amount
);
/// @notice Initializes Keep Bonding contract.
/// @param registryAddress Keep registry contract address.
constructor(address registryAddress) public {
registry = KeepRegistry(registryAddress);
}
/// @notice Add the provided value to operator's pool available for bonding.
/// @param operator Address of the operator.
function deposit(address operator) public payable {
address beneficiary = beneficiaryOf(operator);
// Beneficiary has to be set (delegation exist) before an operator can
// deposit wei. It protects from a situation when an operator wants
// to withdraw funds which are transfered to beneficiary with zero
// address.
require(
beneficiary != address(0),
"Beneficiary not defined for the operator"
);
unbondedValue[operator] = unbondedValue[operator].add(msg.value);
emit UnbondedValueDeposited(operator, beneficiary, msg.value);
}
/// @notice Withdraws amount from operator's value available for bonding.
/// @param amount Value to withdraw in wei.
/// @param operator Address of the operator.
function withdraw(uint256 amount, address operator) public;
/// @notice Returns the amount of wei the operator has made available for
/// bonding and that is still unbounded. If the operator doesn't exist or
/// bond creator is not authorized as an operator contract or it is not
/// authorized by the operator or there is no secondary authorization for
/// the provided sortition pool, function returns 0.
/// @dev Implements function expected by sortition pools' IBonding interface.
/// @param operator Address of the operator.
/// @param bondCreator Address authorized to create a bond.
/// @param authorizedSortitionPool Address of authorized sortition pool.
/// @return Amount of authorized wei deposit available for bonding.
function availableUnbondedValue(
address operator,
address bondCreator,
address authorizedSortitionPool
) public view returns (uint256) {
// Sortition pools check this condition and skips operators that
// are no longer eligible. We cannot revert here.
if (
registry.isApprovedOperatorContract(bondCreator) &&
isAuthorizedForOperator(operator, bondCreator) &&
hasSecondaryAuthorization(operator, authorizedSortitionPool)
) {
return unbondedValue[operator];
}
return 0;
}
/// @notice Create bond for the given operator, holder, reference and amount.
/// @dev Function can be executed only by authorized contract. Reference ID
/// should be unique for holder and operator.
/// @param operator Address of the operator to bond.
/// @param holder Address of the holder of the bond.
/// @param referenceID Reference ID used to track the bond by holder.
/// @param amount Value to bond in wei.
/// @param authorizedSortitionPool Address of authorized sortition pool.
function createBond(
address operator,
address holder,
uint256 referenceID,
uint256 amount,
address authorizedSortitionPool
) public {
require(
availableUnbondedValue(
operator,
msg.sender,
authorizedSortitionPool
) >= amount,
"Insufficient unbonded value"
);
bytes32 bondID = keccak256(
abi.encodePacked(operator, holder, referenceID)
);
require(
lockedBonds[bondID] == 0,
"Reference ID not unique for holder and operator"
);
unbondedValue[operator] = unbondedValue[operator].sub(amount);
lockedBonds[bondID] = lockedBonds[bondID].add(amount);
emit BondCreated(
operator,
holder,
authorizedSortitionPool,
referenceID,
amount
);
}
/// @notice Returns value of wei bonded for the operator.
/// @param operator Address of the operator.
/// @param holder Address of the holder of the bond.
/// @param referenceID Reference ID of the bond.
/// @return Amount of wei in the selected bond.
function bondAmount(
address operator,
address holder,
uint256 referenceID
) public view returns (uint256) {
bytes32 bondID = keccak256(
abi.encodePacked(operator, holder, referenceID)
);
return lockedBonds[bondID];
}
/// @notice Reassigns a bond to a new holder under a new reference.
/// @dev Function requires that a caller is the current holder of the bond
/// which is being reassigned.
/// @param operator Address of the bonded operator.
/// @param referenceID Reference ID of the bond.
/// @param newHolder Address of the new holder of the bond.
/// @param newReferenceID New reference ID to register the bond.
function reassignBond(
address operator,
uint256 referenceID,
address newHolder,
uint256 newReferenceID
) public {
address holder = msg.sender;
bytes32 bondID = keccak256(
abi.encodePacked(operator, holder, referenceID)
);
require(lockedBonds[bondID] > 0, "Bond not found");
bytes32 newBondID = keccak256(
abi.encodePacked(operator, newHolder, newReferenceID)
);
require(
lockedBonds[newBondID] == 0,
"Reference ID not unique for holder and operator"
);
lockedBonds[newBondID] = lockedBonds[bondID];
lockedBonds[bondID] = 0;
emit BondReassigned(operator, referenceID, newHolder, newReferenceID);
}
/// @notice Releases the bond and moves the bond value to the operator's
/// unbounded value pool.
/// @dev Function requires that caller is the holder of the bond which is
/// being released.
/// @param operator Address of the bonded operator.
/// @param referenceID Reference ID of the bond.
function freeBond(address operator, uint256 referenceID) public {
address holder = msg.sender;
bytes32 bondID = keccak256(
abi.encodePacked(operator, holder, referenceID)
);
require(lockedBonds[bondID] > 0, "Bond not found");
uint256 amount = lockedBonds[bondID];
lockedBonds[bondID] = 0;
unbondedValue[operator] = unbondedValue[operator].add(amount);
emit BondReleased(operator, referenceID);
}
/// @notice Seizes the bond by moving some or all of the locked bond to the
/// provided destination address.
/// @dev Function requires that a caller is the holder of the bond which is
/// being seized.
/// @param operator Address of the bonded operator.
/// @param referenceID Reference ID of the bond.
/// @param amount Amount to be seized.
/// @param destination Address to send the amount to.
function seizeBond(
address operator,
uint256 referenceID,
uint256 amount,
address payable destination
) public {
require(amount > 0, "Requested amount should be greater than zero");
address payable holder = msg.sender;
bytes32 bondID = keccak256(
abi.encodePacked(operator, holder, referenceID)
);
require(
lockedBonds[bondID] >= amount,
"Requested amount is greater than the bond"
);
lockedBonds[bondID] = lockedBonds[bondID].sub(amount);
(bool success, ) = destination.call.value(amount)("");
require(success, "Transfer failed");
emit BondSeized(operator, referenceID, destination, amount);
}
/// @notice Authorizes sortition pool for the provided operator.
/// Operator's authorizers need to authorize individual sortition pools
/// per application since they may be interested in participating only in
/// a subset of keep types used by the given application.
/// @dev Only operator's authorizer can call this function.
function authorizeSortitionPoolContract(
address _operator,
address _poolAddress
) public {
require(authorizerOf(_operator) == msg.sender, "Not authorized");
authorizedPools[_operator][_poolAddress] = true;
}
/// @notice Deauthorizes sortition pool for the provided operator.
/// Authorizer may deauthorize individual sortition pool in case the
/// operator should no longer be eligible for work selection and the
/// application represented by the sortition pool should no longer be
/// eligible to create bonds for the operator.
/// @dev Only operator's authorizer can call this function.
function deauthorizeSortitionPoolContract(
address _operator,
address _poolAddress
) public {
require(authorizerOf(_operator) == msg.sender, "Not authorized");
authorizedPools[_operator][_poolAddress] = false;
}
/// @notice Checks if the sortition pool has been authorized for the
/// provided operator by its authorizer.
/// @dev See authorizeSortitionPoolContract.
function hasSecondaryAuthorization(address _operator, address _poolAddress)
public
view
returns (bool)
{
return authorizedPools[_operator][_poolAddress];
}
/// @notice Checks if operator contract has been authorized for the provided
/// operator.
/// @param _operator Operator address.
/// @param _operatorContract Address of the operator contract.
function isAuthorizedForOperator(
address _operator,
address _operatorContract
) public view returns (bool);
/// @notice Gets the authorizer for the specified operator address.
/// @param _operator Operator address.
/// @return Authorizer address.
function authorizerOf(address _operator) public view returns (address);
/// @notice Gets the beneficiary for the specified operator address.
/// @param _operator Operator address.
/// @return Beneficiary address.
function beneficiaryOf(address _operator)
public
view
returns (address payable);
/// @notice Withdraws the provided amount from unbonded value of the
/// provided operator to operator's beneficiary. If there is no enough
/// unbonded value or the transfer failed, function fails.
function withdrawBond(uint256 amount, address operator) internal {
require(
unbondedValue[operator] >= amount,
"Insufficient unbonded value"
);
unbondedValue[operator] = unbondedValue[operator].sub(amount);
address beneficiary = beneficiaryOf(operator);
(bool success, ) = beneficiary.call.value(amount)("");
require(success, "Transfer failed");
emit UnbondedValueWithdrawn(operator, beneficiary, amount);
}
}
|
[{"anonymous":false,"inputs":[{"indexed":true,"internalType":"address","name":"submittingMember","type":"address"},{"indexed":false,"internalType":"bytes","name":"conflictingPublicKey","type":"bytes"}],"name":"ConflictingPublicKeySubmitted","type":"event"},{"anonymous":false,"inputs":[{"indexed":true,"internalType":"address","name":"token","type":"address"},{"indexed":false,"internalType":"uint256","name":"amount","type":"uint256"}],"name":"ERC20RewardDistributed","type":"event"},{"anonymous":false,"inputs":[{"indexed":false,"internalType":"uint256","name":"amount","type":"uint256"}],"name":"ETHRewardDistributed","type":"event"},{"anonymous":false,"inputs":[],"name":"KeepClosed","type":"event"},{"anonymous":false,"inputs":[],"name":"KeepTerminated","type":"event"},{"anonymous":false,"inputs":[{"indexed":false,"internalType":"bytes","name":"publicKey","type":"bytes"}],"name":"PublicKeyPublished","type":"event"},{"anonymous":false,"inputs":[{"indexed":true,"internalType":"bytes32","name":"digest","type":"bytes32"}],"name":"SignatureRequested","type":"event"},{"anonymous":false,"inputs":[{"indexed":true,"internalType":"bytes32","name":"digest","type":"bytes32"},{"indexed":false,"internalType":"bytes32","name":"r","type":"bytes32"},{"indexed":false,"internalType":"bytes32","name":"s","type":"bytes32"},{"indexed":false,"internalType":"uint8","name":"recoveryID","type":"uint8"}],"name":"SignatureSubmitted","type":"event"},{"anonymous":false,"inputs":[],"name":"SlashingFailed","type":"event"},{"constant":true,"inputs":[],"name":"checkBondAmount","outputs":[{"internalType":"uint256","name":"","type":"uint256"}],"payable":false,"stateMutability":"view","type":"function"},{"constant":true,"inputs":[{"internalType":"uint8","name":"_v","type":"uint8"},{"internalType":"bytes32","name":"_r","type":"bytes32"},{"internalType":"bytes32","name":"_s","type":"bytes32"},{"internalType":"bytes32","name":"_signedDigest","type":"bytes32"},{"internalType":"bytes","name":"_preimage","type":"bytes"}],"name":"checkSignatureFraud","outputs":[{"internalType":"bool","name":"_isFraud","type":"bool"}],"payable":false,"stateMutability":"view","type":"function"},{"constant":false,"inputs":[],"name":"closeKeep","outputs":[],"payable":false,"stateMutability":"nonpayable","type":"function"},{"constant":true,"inputs":[],"name":"digest","outputs":[{"internalType":"bytes32","name":"","type":"bytes32"}],"payable":false,"stateMutability":"view","type":"function"},{"constant":true,"inputs":[{"internalType":"bytes32","name":"","type":"bytes32"}],"name":"digests","outputs":[{"internalType":"uint256","name":"","type":"uint256"}],"payable":false,"stateMutability":"view","type":"function"},{"constant":false,"inputs":[{"internalType":"address","name":"_tokenAddress","type":"address"},{"internalType":"uint256","name":"_value","type":"uint256"}],"name":"distributeERC20Reward","outputs":[],"payable":false,"stateMutability":"nonpayable","type":"function"},{"constant":false,"inputs":[],"name":"distributeETHReward","outputs":[],"payable":true,"stateMutability":"payable","type":"function"},{"constant":true,"inputs":[{"internalType":"address","name":"_member","type":"address"}],"name":"getMemberETHBalance","outputs":[{"internalType":"uint256","name":"","type":"uint256"}],"payable":false,"stateMutability":"view","type":"function"},{"constant":true,"inputs":[],"name":"getMembers","outputs":[{"internalType":"address[]","name":"","type":"address[]"}],"payable":false,"stateMutability":"view","type":"function"},{"constant":true,"inputs":[],"name":"getOpenedTimestamp","outputs":[{"internalType":"uint256","name":"","type":"uint256"}],"payable":false,"stateMutability":"view","type":"function"},{"constant":true,"inputs":[],"name":"getOwner","outputs":[{"internalType":"address","name":"","type":"address"}],"payable":false,"stateMutability":"view","type":"function"},{"constant":true,"inputs":[],"name":"getPublicKey","outputs":[{"internalType":"bytes","name":"","type":"bytes"}],"payable":false,"stateMutability":"view","type":"function"},{"constant":true,"inputs":[],"name":"honestThreshold","outputs":[{"internalType":"uint256","name":"","type":"uint256"}],"payable":false,"stateMutability":"view","type":"function"},{"constant":false,"inputs":[{"internalType":"address","name":"_owner","type":"address"},{"internalType":"address[]","name":"_members","type":"address[]"},{"internalType":"uint256","name":"_honestThreshold","type":"uint256"},{"internalType":"uint256","name":"_memberStake","type":"uint256"},{"internalType":"uint256","name":"_stakeLockDuration","type":"uint256"},{"internalType":"address","name":"_tokenStaking","type":"address"},{"internalType":"address","name":"_keepBonding","type":"address"},{"internalType":"address payable","name":"_keepFactory","type":"address"}],"name":"initialize","outputs":[],"payable":false,"stateMutability":"nonpayable","type":"function"},{"constant":true,"inputs":[],"name":"isActive","outputs":[{"internalType":"bool","name":"","type":"bool"}],"payable":false,"stateMutability":"view","type":"function"},{"constant":true,"inputs":[{"internalType":"bytes32","name":"_digest","type":"bytes32"}],"name":"isAwaitingSignature","outputs":[{"internalType":"bool","name":"","type":"bool"}],"payable":false,"stateMutability":"view","type":"function"},{"constant":true,"inputs":[],"name":"isClosed","outputs":[{"internalType":"bool","name":"","type":"bool"}],"payable":false,"stateMutability":"view","type":"function"},{"constant":true,"inputs":[],"name":"isTerminated","outputs":[{"internalType":"bool","name":"","type":"bool"}],"payable":false,"stateMutability":"view","type":"function"},{"constant":true,"inputs":[],"name":"memberStake","outputs":[{"internalType":"uint256","name":"","type":"uint256"}],"payable":false,"stateMutability":"view","type":"function"},{"constant":true,"inputs":[{"internalType":"uint256","name":"","type":"uint256"}],"name":"members","outputs":[{"internalType":"address","name":"","type":"address"}],"payable":false,"stateMutability":"view","type":"function"},{"constant":true,"inputs":[],"name":"owner","outputs":[{"internalType":"address","name":"","type":"address"}],"payable":false,"stateMutability":"view","type":"function"},{"constant":true,"inputs":[],"name":"publicKey","outputs":[{"internalType":"bytes","name":"","type":"bytes"}],"payable":false,"stateMutability":"view","type":"function"},{"constant":false,"inputs":[],"name":"returnPartialSignerBonds","outputs":[],"payable":true,"stateMutability":"payable","type":"function"},{"constant":false,"inputs":[],"name":"seizeSignerBonds","outputs":[],"payable":false,"stateMutability":"nonpayable","type":"function"},{"constant":false,"inputs":[{"internalType":"bytes32","name":"_digest","type":"bytes32"}],"name":"sign","outputs":[],"payable":false,"stateMutability":"nonpayable","type":"function"},{"constant":false,"inputs":[{"internalType":"bytes","name":"_publicKey","type":"bytes"}],"name":"submitPublicKey","outputs":[],"payable":false,"stateMutability":"nonpayable","type":"function"},{"constant":false,"inputs":[{"internalType":"bytes32","name":"_r","type":"bytes32"},{"internalType":"bytes32","name":"_s","type":"bytes32"},{"internalType":"uint8","name":"_recoveryID","type":"uint8"}],"name":"submitSignature","outputs":[],"payable":false,"stateMutability":"nonpayable","type":"function"},{"constant":false,"inputs":[{"internalType":"uint8","name":"_v","type":"uint8"},{"internalType":"bytes32","name":"_r","type":"bytes32"},{"internalType":"bytes32","name":"_s","type":"bytes32"},{"internalType":"bytes32","name":"_signedDigest","type":"bytes32"},{"internalType":"bytes","name":"_preimage","type":"bytes"}],"name":"submitSignatureFraud","outputs":[{"internalType":"bool","name":"_isFraud","type":"bool"}],"payable":false,"stateMutability":"nonpayable","type":"function"},{"constant":false,"inputs":[{"internalType":"address","name":"_member","type":"address"}],"name":"withdraw","outputs":[],"payable":false,"stateMutability":"nonpayable","type":"function"}]
|
v0.5.17+commit.d19bba13
| true
| 200
|
Default
|
MIT
| false
|
bzzr://63a152bdeccda501f3e5b77f97918c5500bb7ae07637beba7fae76dbe818bda4
|
|||
InstaAccount
|
0x00e48df1d7dcd4e0fe97efec34a96a5f2b424ba0
|
Solidity
|
pragma solidity ^0.6.0;
pragma experimental ABIEncoderV2;
/**
* @title InstaAccount.
* @dev DeFi Smart Account Wallet.
*/
interface IndexInterface {
function connectors(uint version) external view returns (address);
function check(uint version) external view returns (address);
function list() external view returns (address);
}
interface ConnectorsInterface {
function isConnector(address[] calldata logicAddr) external view returns (bool);
function isStaticConnector(address[] calldata logicAddr) external view returns (bool);
}
interface CheckInterface {
function isOk() external view returns (bool);
}
interface ListInterface {
function addAuth(address user) external;
function removeAuth(address user) external;
}
contract Record {
event LogEnable(address indexed user);
event LogDisable(address indexed user);
event LogSwitchShield(bool _shield);
// InstaIndex Address.
address public constant instaIndex = 0x2971AdFa57b20E5a416aE5a708A8655A9c74f723;
// The Account Module Version.
uint public constant version = 1;
// Auth Module(Address of Auth => bool).
mapping (address => bool) private auth;
// Is shield true/false.
bool public shield;
/**
* @dev Check for Auth if enabled.
* @param user address/user/owner.
*/
function isAuth(address user) public view returns (bool) {
return auth[user];
}
/**
* @dev Change Shield State.
*/
function switchShield(bool _shield) external {
require(auth[msg.sender], "not-self");
require(shield != _shield, "shield is set");
shield = _shield;
emit LogSwitchShield(shield);
}
/**
* @dev Enable New User.
* @param user Owner of the Smart Account.
*/
function enable(address user) public {
require(msg.sender == address(this) || msg.sender == instaIndex, "not-self-index");
require(user != address(0), "not-valid");
require(!auth[user], "already-enabled");
auth[user] = true;
ListInterface(IndexInterface(instaIndex).list()).addAuth(user);
emit LogEnable(user);
}
/**
* @dev Disable User.
* @param user Owner of the Smart Account.
*/
function disable(address user) public {
require(msg.sender == address(this), "not-self");
require(user != address(0), "not-valid");
require(auth[user], "already-disabled");
delete auth[user];
ListInterface(IndexInterface(instaIndex).list()).removeAuth(user);
emit LogDisable(user);
}
}
contract InstaAccount is Record {
event LogCast(address indexed origin, address indexed sender, uint value);
receive() external payable {}
/**
* @dev Delegate the calls to Connector And this function is ran by cast().
* @param _target Target to of Connector.
* @param _data CallData of function in Connector.
*/
function spell(address _target, bytes memory _data) internal {
require(_target != address(0), "target-invalid");
assembly {
let succeeded := delegatecall(gas(), _target, add(_data, 0x20), mload(_data), 0, 0)
switch iszero(succeeded)
case 1 {
// throw if delegatecall failed
let size := returndatasize()
returndatacopy(0x00, 0x00, size)
revert(0x00, size)
}
}
}
/**
* @dev This is the main function, Where all the different functions are called
* from Smart Account.
* @param _targets Array of Target(s) to of Connector.
* @param _datas Array of Calldata(S) of function.
*/
function cast(
address[] calldata _targets,
bytes[] calldata _datas,
address _origin
)
external
payable
{
require(isAuth(msg.sender) || msg.sender == instaIndex, "permission-denied");
require(_targets.length == _datas.length , "array-length-invalid");
IndexInterface indexContract = IndexInterface(instaIndex);
bool isShield = shield;
if (!isShield) {
require(ConnectorsInterface(indexContract.connectors(version)).isConnector(_targets), "not-connector");
} else {
require(ConnectorsInterface(indexContract.connectors(version)).isStaticConnector(_targets), "not-static-connector");
}
for (uint i = 0; i < _targets.length; i++) {
spell(_targets[i], _datas[i]);
}
address _check = indexContract.check(version);
if (_check != address(0) && !isShield) require(CheckInterface(_check).isOk(), "not-ok");
emit LogCast(_origin, msg.sender, msg.value);
}
}
|
[{"anonymous":false,"inputs":[{"indexed":true,"internalType":"address","name":"origin","type":"address"},{"indexed":true,"internalType":"address","name":"sender","type":"address"},{"indexed":false,"internalType":"uint256","name":"value","type":"uint256"}],"name":"LogCast","type":"event"},{"anonymous":false,"inputs":[{"indexed":true,"internalType":"address","name":"user","type":"address"}],"name":"LogDisable","type":"event"},{"anonymous":false,"inputs":[{"indexed":true,"internalType":"address","name":"user","type":"address"}],"name":"LogEnable","type":"event"},{"anonymous":false,"inputs":[{"indexed":false,"internalType":"bool","name":"_shield","type":"bool"}],"name":"LogSwitchShield","type":"event"},{"inputs":[{"internalType":"address[]","name":"_targets","type":"address[]"},{"internalType":"bytes[]","name":"_datas","type":"bytes[]"},{"internalType":"address","name":"_origin","type":"address"}],"name":"cast","outputs":[],"stateMutability":"payable","type":"function"},{"inputs":[{"internalType":"address","name":"user","type":"address"}],"name":"disable","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"address","name":"user","type":"address"}],"name":"enable","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[],"name":"instaIndex","outputs":[{"internalType":"address","name":"","type":"address"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"address","name":"user","type":"address"}],"name":"isAuth","outputs":[{"internalType":"bool","name":"","type":"bool"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"shield","outputs":[{"internalType":"bool","name":"","type":"bool"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"bool","name":"_shield","type":"bool"}],"name":"switchShield","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[],"name":"version","outputs":[{"internalType":"uint256","name":"","type":"uint256"}],"stateMutability":"view","type":"function"},{"stateMutability":"payable","type":"receive"}]
|
v0.6.0+commit.26b70077
| false
| 200
|
Default
|
MIT
| false
|
ipfs://c7356d76ef680ea6649af388d2a518797700466c0a8ed7e5356ec7932509c8e8
|
|||
Forwarder
|
0xbf4764a0cd2e46b94202e5c9baf5e42970b7481b
|
Solidity
|
pragma solidity ^0.4.14;
/**
* Contract that exposes the needed erc20 token functions
*/
contract ERC20Interface {
// Send _value amount of tokens to address _to
function transfer(address _to, uint256 _value) returns (bool success);
// Get the account balance of another account with address _owner
function balanceOf(address _owner) constant returns (uint256 balance);
}
/**
* Contract that will forward any incoming Ether to its creator
*/
contract Forwarder {
// Address to which any funds sent to this contract will be forwarded
address public parentAddress;
event ForwarderDeposited(address from, uint value, bytes data);
event TokensFlushed(
address tokenContractAddress, // The contract address of the token
uint value // Amount of token sent
);
/**
* Create the contract, and set the destination address to that of the creator
*/
function Forwarder() {
parentAddress = msg.sender;
}
/**
* Modifier that will execute internal code block only if the sender is a parent of the forwarder contract
*/
modifier onlyParent {
if (msg.sender != parentAddress) {
throw;
}
_;
}
/**
* Default function; Gets called when Ether is deposited, and forwards it to the destination address
*/
function() payable {
if (!parentAddress.call.value(msg.value)(msg.data))
throw;
// Fire off the deposited event if we can forward it
ForwarderDeposited(msg.sender, msg.value, msg.data);
}
/**
* Execute a token transfer of the full balance from the forwarder token to the main wallet contract
* @param tokenContractAddress the address of the erc20 token contract
*/
function flushTokens(address tokenContractAddress) onlyParent {
ERC20Interface instance = ERC20Interface(tokenContractAddress);
var forwarderAddress = address(this);
var forwarderBalance = instance.balanceOf(forwarderAddress);
if (forwarderBalance == 0) {
return;
}
if (!instance.transfer(parentAddress, forwarderBalance)) {
throw;
}
TokensFlushed(tokenContractAddress, forwarderBalance);
}
/**
* It is possible that funds were sent to this address before the contract was deployed.
* We can flush those funds to the destination address.
*/
function flush() {
if (!parentAddress.call.value(this.balance)())
throw;
}
}
/**
* Basic multi-signer wallet designed for use in a co-signing environment where 2 signatures are required to move funds.
* Typically used in a 2-of-3 signing configuration. Uses ecrecover to allow for 2 signatures in a single transaction.
*/
contract WalletSimple {
// Events
event Deposited(address from, uint value, bytes data);
event SafeModeActivated(address msgSender);
event Transacted(
address msgSender, // Address of the sender of the message initiating the transaction
address otherSigner, // Address of the signer (second signature) used to initiate the transaction
bytes32 operation, // Operation hash (sha3 of toAddress, value, data, expireTime, sequenceId)
address toAddress, // The address the transaction was sent to
uint value, // Amount of Wei sent to the address
bytes data // Data sent when invoking the transaction
);
event TokenTransacted(
address msgSender, // Address of the sender of the message initiating the transaction
address otherSigner, // Address of the signer (second signature) used to initiate the transaction
bytes32 operation, // Operation hash (sha3 of toAddress, value, tokenContractAddress, expireTime, sequenceId)
address toAddress, // The address the transaction was sent to
uint value, // Amount of token sent
address tokenContractAddress // The contract address of the token
);
// Public fields
address[] public signers; // The addresses that can co-sign transactions on the wallet
bool public safeMode = false; // When active, wallet may only send to signer addresses
// Internal fields
uint constant SEQUENCE_ID_WINDOW_SIZE = 10;
uint[10] recentSequenceIds;
/**
* Modifier that will execute internal code block only if the sender is an authorized signer on this wallet
*/
modifier onlysigner {
if (!isSigner(msg.sender)) {
throw;
}
_;
}
/**
* Set up a simple multi-sig wallet by specifying the signers allowed to be used on this wallet.
* 2 signers will be required to send a transaction from this wallet.
* Note: The sender is NOT automatically added to the list of signers.
* Signers CANNOT be changed once they are set
*
* @param allowedSigners An array of signers on the wallet
*/
function WalletSimple(address[] allowedSigners) {
if (allowedSigners.length != 3) {
// Invalid number of signers
throw;
}
signers = allowedSigners;
}
/**
* Gets called when a transaction is received without calling a method
*/
function() payable {
if (msg.value > 0) {
// Fire deposited event if we are receiving funds
Deposited(msg.sender, msg.value, msg.data);
}
}
/**
* Create a new contract (and also address) that forwards funds to this contract
* returns address of newly created forwarder address
*/
function createForwarder() onlysigner returns (address) {
return new Forwarder();
}
/**
* Execute a multi-signature transaction from this wallet using 2 signers: one from msg.sender and the other from ecrecover.
* The signature is a signed form (using eth.sign) of tightly packed toAddress, value, data, expireTime and sequenceId
* Sequence IDs are numbers starting from 1. They are used to prevent replay attacks and may not be repeated.
*
* @param toAddress the destination address to send an outgoing transaction
* @param value the amount in Wei to be sent
* @param data the data to send to the toAddress when invoking the transaction
* @param expireTime the number of seconds since 1970 for which this transaction is valid
* @param sequenceId the unique sequence id obtainable from getNextSequenceId
* @param signature the result of eth.sign on the operationHash sha3(toAddress, value, data, expireTime, sequenceId)
*/
function sendMultiSig(address toAddress, uint value, bytes data, uint expireTime, uint sequenceId, bytes signature) onlysigner {
// Verify the other signer
var operationHash = sha3("ETHER", toAddress, value, data, expireTime, sequenceId);
var otherSigner = verifyMultiSig(toAddress, operationHash, signature, expireTime, sequenceId);
// Success, send the transaction
if (!(toAddress.call.value(value)(data))) {
// Failed executing transaction
throw;
}
Transacted(msg.sender, otherSigner, operationHash, toAddress, value, data);
}
/**
* Execute a multi-signature token transfer from this wallet using 2 signers: one from msg.sender and the other from ecrecover.
* The signature is a signed form (using eth.sign) of tightly packed toAddress, value, tokenContractAddress, expireTime and sequenceId
* Sequence IDs are numbers starting from 1. They are used to prevent replay attacks and may not be repeated.
*
* @param toAddress the destination address to send an outgoing transaction
* @param value the amount in tokens to be sent
* @param tokenContractAddress the address of the erc20 token contract
* @param expireTime the number of seconds since 1970 for which this transaction is valid
* @param sequenceId the unique sequence id obtainable from getNextSequenceId
* @param signature the result of eth.sign on the operationHash sha3(toAddress, value, tokenContractAddress, expireTime, sequenceId)
*/
function sendMultiSigToken(address toAddress, uint value, address tokenContractAddress, uint expireTime, uint sequenceId, bytes signature) onlysigner {
// Verify the other signer
var operationHash = sha3("ERC20", toAddress, value, tokenContractAddress, expireTime, sequenceId);
var otherSigner = verifyMultiSig(toAddress, operationHash, signature, expireTime, sequenceId);
ERC20Interface instance = ERC20Interface(tokenContractAddress);
if (!instance.transfer(toAddress, value)) {
throw;
}
TokenTransacted(msg.sender, otherSigner, operationHash, toAddress, value, tokenContractAddress);
}
/**
* Execute a token flush from one of the forwarder addresses. This transfer needs only a single signature and can be done by any signer
*
* @param forwarderAddress the address of the forwarder address to flush the tokens from
* @param tokenContractAddress the address of the erc20 token contract
*/
function flushForwarderTokens(address forwarderAddress, address tokenContractAddress) onlysigner {
Forwarder forwarder = Forwarder(forwarderAddress);
forwarder.flushTokens(tokenContractAddress);
}
/**
* Do common multisig verification for both eth sends and erc20token transfers
*
* @param toAddress the destination address to send an outgoing transaction
* @param operationHash the sha3 of the toAddress, value, data/tokenContractAddress and expireTime
* @param signature the tightly packed signature of r, s, and v as an array of 65 bytes (returned by eth.sign)
* @param expireTime the number of seconds since 1970 for which this transaction is valid
* @param sequenceId the unique sequence id obtainable from getNextSequenceId
* returns address of the address to send tokens or eth to
*/
function verifyMultiSig(address toAddress, bytes32 operationHash, bytes signature, uint expireTime, uint sequenceId) private returns (address) {
var otherSigner = recoverAddressFromSignature(operationHash, signature);
// Verify if we are in safe mode. In safe mode, the wallet can only send to signers
if (safeMode && !isSigner(toAddress)) {
// We are in safe mode and the toAddress is not a signer. Disallow!
throw;
}
// Verify that the transaction has not expired
if (expireTime < block.timestamp) {
// Transaction expired
throw;
}
// Try to insert the sequence ID. Will throw if the sequence id was invalid
tryInsertSequenceId(sequenceId);
if (!isSigner(otherSigner)) {
// Other signer not on this wallet or operation does not match arguments
throw;
}
if (otherSigner == msg.sender) {
// Cannot approve own transaction
throw;
}
return otherSigner;
}
/**
* Irrevocably puts contract into safe mode. When in this mode, transactions may only be sent to signing addresses.
*/
function activateSafeMode() onlysigner {
safeMode = true;
SafeModeActivated(msg.sender);
}
/**
* Determine if an address is a signer on this wallet
* @param signer address to check
* returns boolean indicating whether address is signer or not
*/
function isSigner(address signer) returns (bool) {
// Iterate through all signers on the wallet and
for (uint i = 0; i < signers.length; i++) {
if (signers[i] == signer) {
return true;
}
}
return false;
}
/**
* Gets the second signer's address using ecrecover
* @param operationHash the sha3 of the toAddress, value, data/tokenContractAddress and expireTime
* @param signature the tightly packed signature of r, s, and v as an array of 65 bytes (returned by eth.sign)
* returns address recovered from the signature
*/
function recoverAddressFromSignature(bytes32 operationHash, bytes signature) private returns (address) {
if (signature.length != 65) {
throw;
}
// We need to unpack the signature, which is given as an array of 65 bytes (from eth.sign)
bytes32 r;
bytes32 s;
uint8 v;
assembly {
r := mload(add(signature, 32))
s := mload(add(signature, 64))
v := and(mload(add(signature, 65)), 255)
}
if (v < 27) {
v += 27; // Ethereum versions are 27 or 28 as opposed to 0 or 1 which is submitted by some signing libs
}
return ecrecover(operationHash, v, r, s);
}
/**
* Verify that the sequence id has not been used before and inserts it. Throws if the sequence ID was not accepted.
* We collect a window of up to 10 recent sequence ids, and allow any sequence id that is not in the window and
* greater than the minimum element in the window.
* @param sequenceId to insert into array of stored ids
*/
function tryInsertSequenceId(uint sequenceId) onlysigner private {
// Keep a pointer to the lowest value element in the window
uint lowestValueIndex = 0;
for (uint i = 0; i < SEQUENCE_ID_WINDOW_SIZE; i++) {
if (recentSequenceIds[i] == sequenceId) {
// This sequence ID has been used before. Disallow!
throw;
}
if (recentSequenceIds[i] < recentSequenceIds[lowestValueIndex]) {
lowestValueIndex = i;
}
}
if (sequenceId < recentSequenceIds[lowestValueIndex]) {
// The sequence ID being used is lower than the lowest value in the window
// so we cannot accept it as it may have been used before
throw;
}
if (sequenceId > (recentSequenceIds[lowestValueIndex] + 10000)) {
// Block sequence IDs which are much higher than the lowest value
// This prevents people blocking the contract by using very large sequence IDs quickly
throw;
}
recentSequenceIds[lowestValueIndex] = sequenceId;
}
/**
* Gets the next available sequence ID for signing when using executeAndConfirm
* returns the sequenceId one higher than the highest currently stored
*/
function getNextSequenceId() returns (uint) {
uint highestSequenceId = 0;
for (uint i = 0; i < SEQUENCE_ID_WINDOW_SIZE; i++) {
if (recentSequenceIds[i] > highestSequenceId) {
highestSequenceId = recentSequenceIds[i];
}
}
return highestSequenceId + 1;
}
}
|
[{"constant":true,"inputs":[],"name":"parentAddress","outputs":[{"name":"","type":"address"}],"payable":false,"type":"function"},{"constant":false,"inputs":[{"name":"tokenContractAddress","type":"address"}],"name":"flushTokens","outputs":[],"payable":false,"type":"function"},{"constant":false,"inputs":[],"name":"flush","outputs":[],"payable":false,"type":"function"},{"inputs":[],"payable":false,"type":"constructor"},{"payable":true,"type":"fallback"},{"anonymous":false,"inputs":[{"indexed":false,"name":"from","type":"address"},{"indexed":false,"name":"value","type":"uint256"},{"indexed":false,"name":"data","type":"bytes"}],"name":"ForwarderDeposited","type":"event"},{"anonymous":false,"inputs":[{"indexed":false,"name":"tokenContractAddress","type":"address"},{"indexed":false,"name":"value","type":"uint256"}],"name":"TokensFlushed","type":"event"}]
|
v0.4.16-nightly.2017.8.11+commit.c84de7fa
| true
| 200
|
Default
| false
|
bzzr://d0f8838ba17108a895d34ae8ef3bff4e0dc9d639c3c51921fee1d17eaa803721
|
||||
LockToken
|
0x72db65b00e2cf901c67455c36653f1f9943b15cd
|
Solidity
|
pragma solidity ^0.4.24;
/**
* @title SafeMath
* @dev Math operations with safety checks that throw on error
*/
library SafeMath {
function mul(uint256 a, uint256 b) internal pure returns (uint256) {
uint256 c = a * b;
assert(a == 0 || c / a == b);
return c;
}
function div(uint256 a, uint256 b) internal pure returns (uint256) {
// assert(b > 0); // Solidity automatically throws when dividing by 0
uint256 c = a / b;
// assert(a == b * c + a % b); // There is no case in which this doesn't hold
return c;
}
function sub(uint256 a, uint256 b) internal pure returns (uint256) {
assert(b <= a);
return a - b;
}
function add(uint256 a, uint256 b) internal pure returns (uint256) {
uint256 c = a + b;
assert(c >= a);
return c;
}
}
contract token {
function balanceOf(address _owner) public constant returns (uint256 balance);
function transfer(address _to, uint256 _value) public returns (bool success);
}
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.
*/
constructor() public{
owner = msg.sender;
}
/**
* @dev Throws if called by any account other than the owner.
*/
modifier onlyOwner() {
require(msg.sender == owner);
_;
}
/**
* @dev Allows the current owner to transfer control of the contract to a newOwner.
* @param newOwner The address to transfer ownership to.
*/
function transferOwnership(address newOwner) onlyOwner public {
require(newOwner != address(0));
emit OwnershipTransferred(owner, newOwner);
owner = newOwner;
}
}
contract LockToken is Ownable {
using SafeMath for uint256;
token token_reward;
address public beneficiary;
bool public isLocked = false;
bool public isReleased = false;
uint256 public start_time;
uint256 public end_time;
event TokenReleased(address beneficiary, uint256 token_amount);
constructor(address tokenContractAddress, address _beneficiary) public{
token_reward = token(tokenContractAddress);
beneficiary = _beneficiary;
}
function tokenBalance() constant public returns (uint256){
return token_reward.balanceOf(this);
}
function lock(uint256 lockTime) public onlyOwner returns (bool){
require(!isLocked);
require(tokenBalance() > 0);
start_time = now;
end_time = lockTime;
isLocked = true;
}
function lockOver() constant public returns (bool){
uint256 current_time = now;
return current_time > end_time;
}
function release() onlyOwner public{
require(isLocked);
require(!isReleased);
require(lockOver());
uint256 token_amount = tokenBalance();
token_reward.transfer( beneficiary, token_amount);
emit TokenReleased(beneficiary, token_amount);
isReleased = true;
}
}
|
[{"constant":true,"inputs":[],"name":"end_time","outputs":[{"name":"","type":"uint256"}],"payable":false,"stateMutability":"view","type":"function"},{"constant":true,"inputs":[],"name":"beneficiary","outputs":[{"name":"","type":"address"}],"payable":false,"stateMutability":"view","type":"function"},{"constant":true,"inputs":[],"name":"start_time","outputs":[{"name":"","type":"uint256"}],"payable":false,"stateMutability":"view","type":"function"},{"constant":false,"inputs":[],"name":"release","outputs":[],"payable":false,"stateMutability":"nonpayable","type":"function"},{"constant":true,"inputs":[],"name":"owner","outputs":[{"name":"","type":"address"}],"payable":false,"stateMutability":"view","type":"function"},{"constant":true,"inputs":[],"name":"lockOver","outputs":[{"name":"","type":"bool"}],"payable":false,"stateMutability":"view","type":"function"},{"constant":true,"inputs":[],"name":"tokenBalance","outputs":[{"name":"","type":"uint256"}],"payable":false,"stateMutability":"view","type":"function"},{"constant":true,"inputs":[],"name":"isLocked","outputs":[{"name":"","type":"bool"}],"payable":false,"stateMutability":"view","type":"function"},{"constant":false,"inputs":[{"name":"lockTime","type":"uint256"}],"name":"lock","outputs":[{"name":"","type":"bool"}],"payable":false,"stateMutability":"nonpayable","type":"function"},{"constant":false,"inputs":[{"name":"newOwner","type":"address"}],"name":"transferOwnership","outputs":[],"payable":false,"stateMutability":"nonpayable","type":"function"},{"constant":true,"inputs":[],"name":"isReleased","outputs":[{"name":"","type":"bool"}],"payable":false,"stateMutability":"view","type":"function"},{"inputs":[{"name":"tokenContractAddress","type":"address"},{"name":"_beneficiary","type":"address"}],"payable":false,"stateMutability":"nonpayable","type":"constructor"},{"anonymous":false,"inputs":[{"indexed":false,"name":"beneficiary","type":"address"},{"indexed":false,"name":"token_amount","type":"uint256"}],"name":"TokenReleased","type":"event"},{"anonymous":false,"inputs":[{"indexed":true,"name":"previousOwner","type":"address"},{"indexed":true,"name":"newOwner","type":"address"}],"name":"OwnershipTransferred","type":"event"}]
|
v0.4.24+commit.e67f0147
| true
| 200
|
000000000000000000000000aa1ae5e57dc05981d83ec7fca0b3c7ee2565b7d6000000000000000000000000dc2bdc0c335a5f727e5353c01453cd061d934eb7
|
Default
| false
|
bzzr://99c2ec89d57327903251481ffd6add6b411f458178a9c29747e3571d81f0e629
|
|||
UserWallet
|
0xdfc4f866c5c67ba985d015651ba590af75f54bb8
|
Solidity
|
pragma solidity ^0.4.10;
// Copyright 2017 Bittrex
contract AbstractSweeper {
function sweep(address token, uint amount) returns (bool);
function () { throw; }
Controller controller;
function AbstractSweeper(address _controller) {
controller = Controller(_controller);
}
modifier canSweep() {
if (msg.sender != controller.authorizedCaller() && msg.sender != controller.owner()) throw;
if (controller.halted()) throw;
_;
}
}
contract Token {
function balanceOf(address a) returns (uint) {
(a);
return 0;
}
function transfer(address a, uint val) returns (bool) {
(a);
(val);
return false;
}
}
contract DefaultSweeper is AbstractSweeper {
function DefaultSweeper(address controller)
AbstractSweeper(controller) {}
function sweep(address _token, uint _amount)
canSweep
returns (bool) {
bool success = false;
address destination = controller.destination();
if (_token != address(0)) {
Token token = Token(_token);
uint amount = _amount;
if (amount > token.balanceOf(this)) {
return false;
}
success = token.transfer(destination, amount);
}
else {
uint amountInWei = _amount;
if (amountInWei > this.balance) {
return false;
}
success = destination.send(amountInWei);
}
if (success) {
controller.logSweep(this, destination, _token, _amount);
}
return success;
}
}
contract UserWallet {
AbstractSweeperList sweeperList;
function UserWallet(address _sweeperlist) {
sweeperList = AbstractSweeperList(_sweeperlist);
}
function () public payable { }
function tokenFallback(address _from, uint _value, bytes _data) {
(_from);
(_value);
(_data);
}
function sweep(address _token, uint _amount)
returns (bool) {
(_amount);
return sweeperList.sweeperOf(_token).delegatecall(msg.data);
}
}
contract AbstractSweeperList {
function sweeperOf(address _token) returns (address);
}
contract Controller is AbstractSweeperList {
address public owner;
address public authorizedCaller;
address public destination;
bool public halted;
event LogNewWallet(address receiver);
event LogSweep(address indexed from, address indexed to, address indexed token, uint amount);
modifier onlyOwner() {
if (msg.sender != owner) throw;
_;
}
modifier onlyAuthorizedCaller() {
if (msg.sender != authorizedCaller) throw;
_;
}
modifier onlyAdmins() {
if (msg.sender != authorizedCaller && msg.sender != owner) throw;
_;
}
function Controller()
{
owner = msg.sender;
destination = msg.sender;
authorizedCaller = msg.sender;
}
function changeAuthorizedCaller(address _newCaller) onlyOwner {
authorizedCaller = _newCaller;
}
function changeDestination(address _dest) onlyOwner {
destination = _dest;
}
function changeOwner(address _owner) onlyOwner {
owner = _owner;
}
function makeWallet() onlyAdmins returns (address wallet) {
wallet = address(new UserWallet(this));
LogNewWallet(wallet);
}
function halt() onlyAdmins {
halted = true;
}
function start() onlyOwner {
halted = false;
}
address public defaultSweeper = address(new DefaultSweeper(this));
mapping (address => address) sweepers;
function addSweeper(address _token, address _sweeper) onlyOwner {
sweepers[_token] = _sweeper;
}
function sweeperOf(address _token) returns (address) {
address sweeper = sweepers[_token];
if (sweeper == 0) sweeper = defaultSweeper;
return sweeper;
}
function logSweep(address from, address to, address token, uint amount) {
LogSweep(from, to, token, amount);
}
}
|
[{"constant":false,"inputs":[{"name":"_token","type":"address"},{"name":"_amount","type":"uint256"}],"name":"sweep","outputs":[{"name":"","type":"bool"}],"payable":false,"type":"function"},{"constant":false,"inputs":[{"name":"_from","type":"address"},{"name":"_value","type":"uint256"},{"name":"_data","type":"bytes"}],"name":"tokenFallback","outputs":[],"payable":false,"type":"function"},{"inputs":[{"name":"_sweeperlist","type":"address"}],"payable":false,"type":"constructor"},{"payable":true,"type":"fallback"}]
|
v0.4.11+commit.68ef5810
| true
| 200
|
000000000000000000000000a3C1E324CA1ce40db73eD6026c4A177F099B5770
|
Default
| false
|
bzzr://4cdd69fdcf3cf6cbee9677fe380fa5f044048aa9e060ec5619a21ca5a5bd4cd1
|
|||
UserWallet
|
0x8e928e9bf009ac062232d1ca6ee616aebb1acd71
|
Solidity
|
pragma solidity ^0.4.10;
// Copyright 2017 Bittrex
contract AbstractSweeper {
function sweep(address token, uint amount) returns (bool);
function () { throw; }
Controller controller;
function AbstractSweeper(address _controller) {
controller = Controller(_controller);
}
modifier canSweep() {
if (msg.sender != controller.authorizedCaller() && msg.sender != controller.owner()) throw;
if (controller.halted()) throw;
_;
}
}
contract Token {
function balanceOf(address a) returns (uint) {
(a);
return 0;
}
function transfer(address a, uint val) returns (bool) {
(a);
(val);
return false;
}
}
contract DefaultSweeper is AbstractSweeper {
function DefaultSweeper(address controller)
AbstractSweeper(controller) {}
function sweep(address _token, uint _amount)
canSweep
returns (bool) {
bool success = false;
address destination = controller.destination();
if (_token != address(0)) {
Token token = Token(_token);
uint amount = _amount;
if (amount > token.balanceOf(this)) {
return false;
}
success = token.transfer(destination, amount);
}
else {
uint amountInWei = _amount;
if (amountInWei > this.balance) {
return false;
}
success = destination.send(amountInWei);
}
if (success) {
controller.logSweep(this, destination, _token, _amount);
}
return success;
}
}
contract UserWallet {
AbstractSweeperList sweeperList;
function UserWallet(address _sweeperlist) {
sweeperList = AbstractSweeperList(_sweeperlist);
}
function () public payable { }
function tokenFallback(address _from, uint _value, bytes _data) {
(_from);
(_value);
(_data);
}
function sweep(address _token, uint _amount)
returns (bool) {
(_amount);
return sweeperList.sweeperOf(_token).delegatecall(msg.data);
}
}
contract AbstractSweeperList {
function sweeperOf(address _token) returns (address);
}
contract Controller is AbstractSweeperList {
address public owner;
address public authorizedCaller;
address public destination;
bool public halted;
event LogNewWallet(address receiver);
event LogSweep(address indexed from, address indexed to, address indexed token, uint amount);
modifier onlyOwner() {
if (msg.sender != owner) throw;
_;
}
modifier onlyAuthorizedCaller() {
if (msg.sender != authorizedCaller) throw;
_;
}
modifier onlyAdmins() {
if (msg.sender != authorizedCaller && msg.sender != owner) throw;
_;
}
function Controller()
{
owner = msg.sender;
destination = msg.sender;
authorizedCaller = msg.sender;
}
function changeAuthorizedCaller(address _newCaller) onlyOwner {
authorizedCaller = _newCaller;
}
function changeDestination(address _dest) onlyOwner {
destination = _dest;
}
function changeOwner(address _owner) onlyOwner {
owner = _owner;
}
function makeWallet() onlyAdmins returns (address wallet) {
wallet = address(new UserWallet(this));
LogNewWallet(wallet);
}
function halt() onlyAdmins {
halted = true;
}
function start() onlyOwner {
halted = false;
}
address public defaultSweeper = address(new DefaultSweeper(this));
mapping (address => address) sweepers;
function addSweeper(address _token, address _sweeper) onlyOwner {
sweepers[_token] = _sweeper;
}
function sweeperOf(address _token) returns (address) {
address sweeper = sweepers[_token];
if (sweeper == 0) sweeper = defaultSweeper;
return sweeper;
}
function logSweep(address from, address to, address token, uint amount) {
LogSweep(from, to, token, amount);
}
}
|
[{"constant":false,"inputs":[{"name":"_token","type":"address"},{"name":"_amount","type":"uint256"}],"name":"sweep","outputs":[{"name":"","type":"bool"}],"payable":false,"type":"function"},{"constant":false,"inputs":[{"name":"_from","type":"address"},{"name":"_value","type":"uint256"},{"name":"_data","type":"bytes"}],"name":"tokenFallback","outputs":[],"payable":false,"type":"function"},{"inputs":[{"name":"_sweeperlist","type":"address"}],"payable":false,"type":"constructor"},{"payable":true,"type":"fallback"}]
|
v0.4.11+commit.68ef5810
| true
| 200
|
000000000000000000000000a3C1E324CA1ce40db73eD6026c4A177F099B5770
|
Default
| false
|
bzzr://4cdd69fdcf3cf6cbee9677fe380fa5f044048aa9e060ec5619a21ca5a5bd4cd1
|
|||
UpgradeBeaconProxyV1
|
0x88507f1db8d0f9c54a55b0941b785288b1fa3f16
|
Solidity
|
pragma solidity 0.5.11; // optimization runs: 200, evm version: petersburg
/**
* @title UpgradeBeaconProxyV1
* @author 0age
* @notice This contract delegates all logic, including initialization, to an
* implementation contract specified by a hard-coded "upgrade beacon" contract.
* Note that this implementation can be reduced in size by stripping out the
* metadata hash, or even more significantly by using a minimal upgrade beacon
* proxy implemented using raw EVM opcodes.
*/
contract UpgradeBeaconProxyV1 {
// Set upgrade beacon address as a constant (i.e. not in contract storage).
address private constant _UPGRADE_BEACON = address(
0x000000000026750c571ce882B17016557279ADaa
);
/**
* @notice In the constructor, perform initialization via delegatecall to the
* implementation set on the upgrade beacon, supplying initialization calldata
* as a constructor argument. The deployment will revert and pass along the
* revert reason in the event that this initialization delegatecall reverts.
* @param initializationCalldata Calldata to supply when performing the
* initialization delegatecall.
*/
constructor(bytes memory initializationCalldata) public payable {
// Delegatecall into the implementation, supplying initialization calldata.
(bool ok, ) = _implementation().delegatecall(initializationCalldata);
// Revert and include revert data if delegatecall to implementation reverts.
if (!ok) {
assembly {
returndatacopy(0, 0, returndatasize)
revert(0, returndatasize)
}
}
}
/**
* @notice In the fallback, delegate execution to the implementation set on
* the upgrade beacon.
*/
function () external payable {
// Delegate execution to implementation contract provided by upgrade beacon.
_delegate(_implementation());
}
/**
* @notice Private view function to get the current implementation from the
* upgrade beacon. This is accomplished via a staticcall to the beacon with no
* data, and the beacon will return an abi-encoded implementation address.
* @return implementation Address of the implementation.
*/
function _implementation() private view returns (address implementation) {
// Get the current implementation address from the upgrade beacon.
(bool ok, bytes memory returnData) = _UPGRADE_BEACON.staticcall("");
// Revert and pass along revert message if call to upgrade beacon reverts.
require(ok, string(returnData));
// Set the implementation to the address returned from the upgrade beacon.
implementation = abi.decode(returnData, (address));
}
/**
* @notice Private function that delegates execution to an implementation
* contract. This is a low level function that doesn't return to its internal
* call site. It will return whatever is returned by the implementation to the
* external caller, reverting and returning the revert data if implementation
* reverts.
* @param implementation Address to delegate.
*/
function _delegate(address implementation) private {
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)
// Delegatecall to the implementation, supplying calldata and gas.
// Out and outsize are set to zero - instead, use the return buffer.
let result := delegatecall(gas, implementation, 0, calldatasize, 0, 0)
// Copy the returned data from the return buffer.
returndatacopy(0, 0, returndatasize)
switch result
// Delegatecall returns 0 on error.
case 0 { revert(0, returndatasize) }
default { return(0, returndatasize) }
}
}
}
|
[{"inputs":[{"internalType":"bytes","name":"initializationCalldata","type":"bytes"}],"payable":true,"stateMutability":"payable","type":"constructor"},{"payable":true,"stateMutability":"payable","type":"fallback"}]
|
v0.5.11+commit.c082d0b4
| true
| 200
|
00000000000000000000000000000000000000000000000000000000000000200000000000000000000000000000000000000000000000000000000000000024c4d66de80000000000000000000000007e4a8391c728fed9069b2962699ab416628b19fa00000000000000000000000000000000000000000000000000000000
|
Default
|
MIT
| false
|
bzzr://20202020202055706772616465426561636f6e50726f78795631202020202020
|
||
HumanStandardToken
|
0xf7fc6ee9459d16fbb46955cf686a5e48deb11a1b
|
Solidity
|
pragma solidity ^0.4.8;
contract Token{
// token总量,默认会为public变量生成一个getter函数接口,名称为totalSupply().
uint256 public totalSupply;
/// 获取账户_owner拥有token的数量
function balanceOf(address _owner) constant returns (uint256 balance);
//从消息发送者账户中往_to账户转数量为_value的token
function transfer(address _to, uint256 _value) returns (bool success);
//从账户_from中往账户_to转数量为_value的token,与approve方法配合使用
function transferFrom(address _from, address _to, uint256 _value) returns
(bool success);
//消息发送账户设置账户_spender能从发送账户中转出数量为_value的token
function approve(address _spender, uint256 _value) returns (bool success);
//获取账户_spender可以从账户_owner中转出token的数量
function allowance(address _owner, address _spender) constant returns
(uint256 remaining);
//发生转账时必须要触发的事件
event Transfer(address indexed _from, address indexed _to, uint256 _value);
//当函数approve(address _spender, uint256 _value)成功执行时必须触发的事件
event Approval(address indexed _owner, address indexed _spender, uint256
_value);
}
contract StandardToken is Token {
function transfer(address _to, uint256 _value) returns (bool success) {
//默认totalSupply 不会超过最大值 (2^256 - 1).
//如果随着时间的推移将会有新的token生成,则可以用下面这句避免溢出的异常
//require(balances[msg.sender] >= _value && balances[_to] + _value > balances[_to]);
require(balances[msg.sender] >= _value);
balances[msg.sender] -= _value;//从消息发送者账户中减去token数量_value
balances[_to] += _value;//往接收账户增加token数量_value
Transfer(msg.sender, _to, _value);//触发转币交易事件
return true;
}
function transferFrom(address _from, address _to, uint256 _value) returns
(bool success) {
//require(balances[_from] >= _value && allowed[_from][msg.sender] >=
// _value && balances[_to] + _value > balances[_to]);
require(balances[_from] >= _value && allowed[_from][msg.sender] >= _value);
balances[_to] += _value;//接收账户增加token数量_value
balances[_from] -= _value; //支出账户_from减去token数量_value
allowed[_from][msg.sender] -= _value;//消息发送者可以从账户_from中转出的数量减少_value
Transfer(_from, _to, _value);//触发转币交易事件
return true;
}
function balanceOf(address _owner) constant returns (uint256 balance) {
return balances[_owner];
}
function approve(address _spender, uint256 _value) returns (bool success)
{
allowed[msg.sender][_spender] = _value;
Approval(msg.sender, _spender, _value);
return true;
}
function allowance(address _owner, address _spender) constant returns (uint256 remaining) {
return allowed[_owner][_spender];//允许_spender从_owner中转出的token数
}
mapping (address => uint256) balances;
mapping (address => mapping (address => uint256)) allowed;
}
contract HumanStandardToken is StandardToken {
/* Public variables of the token */
string public name; //名称: eg Simon Bucks
uint8 public decimals; //最多的小数位数,How many decimals to show. ie. There could 1000 base units with 3 decimals. Meaning 0.980 SBX = 980 base units. It's like comparing 1 wei to 1 ether.
string public symbol; //token简称: eg SBX
string public version = 'H0.1'; //版本
function HumanStandardToken(uint256 _initialAmount, string _tokenName, uint8 _decimalUnits, string _tokenSymbol) {
balances[msg.sender] = _initialAmount; // 初始token数量给予消息发送者
totalSupply = _initialAmount; // 设置初始总量
name = _tokenName; // token名称
decimals = _decimalUnits; // 小数位数
symbol = _tokenSymbol; // token简称
}
/* Approves and then calls the receiving contract */
function approveAndCall(address _spender, uint256 _value, bytes _extraData) returns (bool success) {
allowed[msg.sender][_spender] = _value;
Approval(msg.sender, _spender, _value);
//call the receiveApproval function on the contract you want to be notified. This crafts the function signature manually so one doesn't have to include a contract in here just for this.
//receiveApproval(address _from, uint256 _value, address _tokenContract, bytes _extraData)
//it is assumed that when does this that the call *should* succeed, otherwise one would use vanilla approve instead.
require(_spender.call(bytes4(bytes32(sha3("receiveApproval(address,uint256,address,bytes)"))), msg.sender, _value, this, _extraData));
return true;
}
}
|
[{"constant":true,"inputs":[],"name":"name","outputs":[{"name":"","type":"string"}],"payable":false,"stateMutability":"view","type":"function"},{"constant":false,"inputs":[{"name":"_spender","type":"address"},{"name":"_value","type":"uint256"}],"name":"approve","outputs":[{"name":"success","type":"bool"}],"payable":false,"stateMutability":"nonpayable","type":"function"},{"constant":true,"inputs":[],"name":"totalSupply","outputs":[{"name":"","type":"uint256"}],"payable":false,"stateMutability":"view","type":"function"},{"constant":false,"inputs":[{"name":"_from","type":"address"},{"name":"_to","type":"address"},{"name":"_value","type":"uint256"}],"name":"transferFrom","outputs":[{"name":"success","type":"bool"}],"payable":false,"stateMutability":"nonpayable","type":"function"},{"constant":true,"inputs":[],"name":"decimals","outputs":[{"name":"","type":"uint8"}],"payable":false,"stateMutability":"view","type":"function"},{"constant":true,"inputs":[],"name":"version","outputs":[{"name":"","type":"string"}],"payable":false,"stateMutability":"view","type":"function"},{"constant":true,"inputs":[{"name":"_owner","type":"address"}],"name":"balanceOf","outputs":[{"name":"balance","type":"uint256"}],"payable":false,"stateMutability":"view","type":"function"},{"constant":true,"inputs":[],"name":"symbol","outputs":[{"name":"","type":"string"}],"payable":false,"stateMutability":"view","type":"function"},{"constant":false,"inputs":[{"name":"_to","type":"address"},{"name":"_value","type":"uint256"}],"name":"transfer","outputs":[{"name":"success","type":"bool"}],"payable":false,"stateMutability":"nonpayable","type":"function"},{"constant":false,"inputs":[{"name":"_spender","type":"address"},{"name":"_value","type":"uint256"},{"name":"_extraData","type":"bytes"}],"name":"approveAndCall","outputs":[{"name":"success","type":"bool"}],"payable":false,"stateMutability":"nonpayable","type":"function"},{"constant":true,"inputs":[{"name":"_owner","type":"address"},{"name":"_spender","type":"address"}],"name":"allowance","outputs":[{"name":"remaining","type":"uint256"}],"payable":false,"stateMutability":"view","type":"function"},{"inputs":[{"name":"_initialAmount","type":"uint256"},{"name":"_tokenName","type":"string"},{"name":"_decimalUnits","type":"uint8"},{"name":"_tokenSymbol","type":"string"}],"payable":false,"stateMutability":"nonpayable","type":"constructor"},{"anonymous":false,"inputs":[{"indexed":true,"name":"_from","type":"address"},{"indexed":true,"name":"_to","type":"address"},{"indexed":false,"name":"_value","type":"uint256"}],"name":"Transfer","type":"event"},{"anonymous":false,"inputs":[{"indexed":true,"name":"_owner","type":"address"},{"indexed":true,"name":"_spender","type":"address"},{"indexed":false,"name":"_value","type":"uint256"}],"name":"Approval","type":"event"}]
|
v0.4.21+commit.dfe3193c
| false
| 200
|
000000000000000000000000000000000000000000000000000000174876e8000000000000000000000000000000000000000000000000000000000000000080000000000000000000000000000000000000000000000000000000000000000300000000000000000000000000000000000000000000000000000000000000c00000000000000000000000000000000000000000000000000000000000000009e5b08fe58886e9989f000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000035846440000000000000000000000000000000000000000000000000000000000
|
Default
| false
|
bzzr://4ac86c576c58a62257cea6796c428f93ccbba8cd8bf99e4affd42313696ac28d
|
|||
VCoin
|
0x5ba0f310636c50a788bdd51a90f022cd15f9aad7
|
Solidity
|
pragma solidity 0.4.24;
library SafeMath {
function mul(uint256 a, uint256 b) internal pure returns (uint256 c) {
if (a == 0) {
return 0;
}
c = a * b;
assert(c / a == b);
return c;
}
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;
}
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 c) {
c = a + b;
assert(c >= a);
return c;
}
}
contract Ownable {
address public owner;
event OwnershipTransferred(address indexed previousOwner, address indexed newOwner);
constructor() public {
owner = msg.sender;
}
modifier onlyOwner() {
require(msg.sender == owner);
_;
}
function transferOwnership(address newOwner) public onlyOwner {
require(newOwner != address(0));
emit OwnershipTransferred(owner, newOwner);
owner = newOwner;
}
}
// Abstract contract for the full ERC 20 Token standard
// https://github.com/ethereum/EIPs/issues/20
contract ERC20 {
uint256 public _totalSupply;
string public name;
string public symbol;
uint8 public decimals;
function totalSupply() public constant returns (uint256 supply);
function balanceOf(address _owner) public view returns (uint256 balance);
function transfer(address _to, uint256 _value) public returns (bool success);
function transferFrom(address _from, address _to, uint256 _value) public returns (bool success);
function approve(address _spender, uint256 _value) public returns (bool success);
function allowance(address _owner, address _spender) public view returns (uint256 remaining);
event Transfer(address indexed _from, address indexed _to, uint256 _value);
event Approval(address indexed _owner, address indexed _spender, uint256 _value);
}
//Implements ERC 20 Token standard: https://github.com/ethereum/EIPs/issues/20
contract ERC20Token is ERC20 {
using SafeMath for uint256;
function totalSupply() public constant returns (uint) {
return _totalSupply.sub(balances[address(0)]);
}
function balanceOf(address _owner) view public returns (uint256 balance) {
return balances[_owner];
}
function transfer(address _to, uint256 _value) public returns (bool success) {
//require(balances[msg.sender] >= _value);
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) public returns (bool success) {
balances[_to] = balances[_to].add(_value);
balances[_from] = balances[_from].sub(_value);
allowed[_from][msg.sender] = allowed[_from][msg.sender].sub(_value);
emit Transfer(_from, _to, _value);
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;
}
function allowance(address _owner, address _spender) view public returns (uint256 remaining) {
return allowed[_owner][_spender];
}
mapping (address => uint256) balances;
mapping (address => mapping (address => uint256)) allowed;
}
/**
* @title ERC677 transferAndCall token interface
* @dev See https://github.com/ethereum/EIPs/issues/677 for specification and
* discussion.
*/
contract ERC677 {
event Transfer(address indexed _from, address indexed _to, uint256 _amount, bytes _data);
function transferAndCall(address _receiver, uint _amount, bytes _data) public;
}
/**
* @title Receiver interface for ERC677 transferAndCall
* @dev See https://github.com/ethereum/EIPs/issues/677 for specification and
* discussion.
*/
contract ERC677Receiver {
function tokenFallback(address _from, uint _amount, bytes _data) public;
}
contract ERC677Token is ERC677, ERC20Token {
function transferAndCall(address _receiver, uint _amount, bytes _data) public {
require(super.transfer(_receiver, _amount));
emit Transfer(msg.sender, _receiver, _amount, _data);
// call receiver
if (isContract(_receiver)) {
ERC677Receiver to = ERC677Receiver(_receiver);
to.tokenFallback(msg.sender, _amount, _data);
}
}
function isContract(address _addr) internal view returns (bool) {
uint len;
assembly {
len := extcodesize(_addr)
}
return len > 0;
}
}
contract Splitable is ERC677Token, Ownable {
uint32 public split;
mapping (address => uint32) public splits;
event Split(address indexed addr, uint32 multiplyer);
constructor() public {
split = 0;
}
function splitShare() onlyOwner public {
require(split * 2 >= split);
if (split == 0) split = 2;
else split *= 2;
claimShare();
}
function isSplitable() public view returns (bool) {
return splits[msg.sender] != split;
}
function claimShare() public {
uint32 s = splits[msg.sender];
if (s == split) return;
if (s == 0) s = 1;
splits[msg.sender] = split;
uint b = balances[msg.sender];
uint nb = b * split / s;
balances[msg.sender] = nb;
_totalSupply += nb - b;
}
function claimShare(address _u1, address _u2) public {
uint32 s = splits[_u1];
if (s != split) {
if (s == 0) s = 1;
splits[_u1] = split;
uint b = balances[_u1];
uint nb = b.mul(split / s);
balances[_u1] = nb;
_totalSupply += nb - b;
}
s = splits[_u2];
if (s != split) {
if (s == 0) s = 1;
splits[_u2] = split;
b = balances[_u2];
nb = b.mul(split / s);
balances[_u2] = nb;
_totalSupply += nb - b;
}
}
function transfer(address _to, uint256 _value) public returns (bool success) {
if (splits[msg.sender] != splits[_to]) claimShare(msg.sender, _to);
return super.transfer(_to, _value);
}
function transferFrom(address _from, address _to, uint256 _value) public returns (bool success) {
if (splits[_from] != splits[_to]) claimShare(msg.sender, _to);
return super.transferFrom(_from, _to, _value);
}
function transferAndCall(address _receiver, uint _amount, bytes _data) public {
if (splits[_receiver] != splits[_receiver]) claimShare(msg.sender, _receiver);
return super.transferAndCall(_receiver, _amount, _data);
}
}
contract Lockable is ERC20Token, Ownable {
using SafeMath for uint256;
mapping (address => uint256) public lockAmounts;
// function lock(address to, uint amount) public onlyOwner {
// lockAmounts[to] = lockAmounts[to].add(amount);
// }
function unlock(address to, uint amount) public onlyOwner {
lockAmounts[to] = lockAmounts[to].sub(amount);
}
function issueCoin(address to, uint amount) public onlyOwner {
lockAmounts[to] = lockAmounts[to].add(amount);
transfer(to, amount);
// balances[to] = balances[to].add(amount);
// balances[owner] = balances[owner].sub(amount);
// emit Transfer(owner, to, amount);
}
function transfer(address _to, uint256 _value) public returns (bool success) {
require(balances[msg.sender] >= _value + lockAmounts[msg.sender]);
return super.transfer(_to, _value);
}
function transferFrom(address _from, address _to, uint256 _value) public returns (bool success) {
require(balances[_from] >= _value + lockAmounts[_from]);
return super.transferFrom(_from, _to, _value);
}
}
contract VCoin is ERC677Token, Ownable, Splitable, Lockable {
uint32 public purchaseNo;
event Purchase(uint32 indexed purchaseNo, address from, uint value, bytes data);
constructor() public {
symbol = "VICT";
name = "Victory Token";
decimals = 18;
_totalSupply = 1000000000 * 10**uint(decimals);
balances[owner] = _totalSupply;
emit Transfer(address(0), owner, _totalSupply);
purchaseNo = 1;
}
function () public payable {
require(!isContract(msg.sender));
owner.transfer(msg.value);
emit Purchase(purchaseNo++, msg.sender, msg.value, msg.data);
//emit Transfer(owner, msg.sender, msg.value);
}
}
|
[{"constant":true,"inputs":[],"name":"name","outputs":[{"name":"","type":"string"}],"payable":false,"stateMutability":"view","type":"function"},{"constant":false,"inputs":[{"name":"_spender","type":"address"},{"name":"_value","type":"uint256"}],"name":"approve","outputs":[{"name":"success","type":"bool"}],"payable":false,"stateMutability":"nonpayable","type":"function"},{"constant":true,"inputs":[],"name":"totalSupply","outputs":[{"name":"","type":"uint256"}],"payable":false,"stateMutability":"view","type":"function"},{"constant":false,"inputs":[{"name":"_from","type":"address"},{"name":"_to","type":"address"},{"name":"_value","type":"uint256"}],"name":"transferFrom","outputs":[{"name":"success","type":"bool"}],"payable":false,"stateMutability":"nonpayable","type":"function"},{"constant":true,"inputs":[],"name":"purchaseNo","outputs":[{"name":"","type":"uint32"}],"payable":false,"stateMutability":"view","type":"function"},{"constant":true,"inputs":[],"name":"decimals","outputs":[{"name":"","type":"uint8"}],"payable":false,"stateMutability":"view","type":"function"},{"constant":true,"inputs":[],"name":"_totalSupply","outputs":[{"name":"","type":"uint256"}],"payable":false,"stateMutability":"view","type":"function"},{"constant":false,"inputs":[{"name":"_receiver","type":"address"},{"name":"_amount","type":"uint256"},{"name":"_data","type":"bytes"}],"name":"transferAndCall","outputs":[],"payable":false,"stateMutability":"nonpayable","type":"function"},{"constant":true,"inputs":[{"name":"","type":"address"}],"name":"splits","outputs":[{"name":"","type":"uint32"}],"payable":false,"stateMutability":"view","type":"function"},{"constant":false,"inputs":[],"name":"claimShare","outputs":[],"payable":false,"stateMutability":"nonpayable","type":"function"},{"constant":true,"inputs":[{"name":"_owner","type":"address"}],"name":"balanceOf","outputs":[{"name":"balance","type":"uint256"}],"payable":false,"stateMutability":"view","type":"function"},{"constant":true,"inputs":[],"name":"isSplitable","outputs":[{"name":"","type":"bool"}],"payable":false,"stateMutability":"view","type":"function"},{"constant":false,"inputs":[{"name":"to","type":"address"},{"name":"amount","type":"uint256"}],"name":"unlock","outputs":[],"payable":false,"stateMutability":"nonpayable","type":"function"},{"constant":true,"inputs":[],"name":"owner","outputs":[{"name":"","type":"address"}],"payable":false,"stateMutability":"view","type":"function"},{"constant":true,"inputs":[],"name":"symbol","outputs":[{"name":"","type":"string"}],"payable":false,"stateMutability":"view","type":"function"},{"constant":false,"inputs":[],"name":"splitShare","outputs":[],"payable":false,"stateMutability":"nonpayable","type":"function"},{"constant":false,"inputs":[{"name":"_to","type":"address"},{"name":"_value","type":"uint256"}],"name":"transfer","outputs":[{"name":"success","type":"bool"}],"payable":false,"stateMutability":"nonpayable","type":"function"},{"constant":false,"inputs":[{"name":"to","type":"address"},{"name":"amount","type":"uint256"}],"name":"issueCoin","outputs":[],"payable":false,"stateMutability":"nonpayable","type":"function"},{"constant":false,"inputs":[{"name":"_u1","type":"address"},{"name":"_u2","type":"address"}],"name":"claimShare","outputs":[],"payable":false,"stateMutability":"nonpayable","type":"function"},{"constant":true,"inputs":[{"name":"","type":"address"}],"name":"lockAmounts","outputs":[{"name":"","type":"uint256"}],"payable":false,"stateMutability":"view","type":"function"},{"constant":true,"inputs":[{"name":"_owner","type":"address"},{"name":"_spender","type":"address"}],"name":"allowance","outputs":[{"name":"remaining","type":"uint256"}],"payable":false,"stateMutability":"view","type":"function"},{"constant":false,"inputs":[{"name":"newOwner","type":"address"}],"name":"transferOwnership","outputs":[],"payable":false,"stateMutability":"nonpayable","type":"function"},{"constant":true,"inputs":[],"name":"split","outputs":[{"name":"","type":"uint32"}],"payable":false,"stateMutability":"view","type":"function"},{"inputs":[],"payable":false,"stateMutability":"nonpayable","type":"constructor"},{"payable":true,"stateMutability":"payable","type":"fallback"},{"anonymous":false,"inputs":[{"indexed":true,"name":"purchaseNo","type":"uint32"},{"indexed":false,"name":"from","type":"address"},{"indexed":false,"name":"value","type":"uint256"},{"indexed":false,"name":"data","type":"bytes"}],"name":"Purchase","type":"event"},{"anonymous":false,"inputs":[{"indexed":true,"name":"addr","type":"address"},{"indexed":false,"name":"multiplyer","type":"uint32"}],"name":"Split","type":"event"},{"anonymous":false,"inputs":[{"indexed":true,"name":"previousOwner","type":"address"},{"indexed":true,"name":"newOwner","type":"address"}],"name":"OwnershipTransferred","type":"event"},{"anonymous":false,"inputs":[{"indexed":true,"name":"_from","type":"address"},{"indexed":true,"name":"_to","type":"address"},{"indexed":false,"name":"_value","type":"uint256"}],"name":"Transfer","type":"event"},{"anonymous":false,"inputs":[{"indexed":true,"name":"_owner","type":"address"},{"indexed":true,"name":"_spender","type":"address"},{"indexed":false,"name":"_value","type":"uint256"}],"name":"Approval","type":"event"},{"anonymous":false,"inputs":[{"indexed":true,"name":"_from","type":"address"},{"indexed":true,"name":"_to","type":"address"},{"indexed":false,"name":"_amount","type":"uint256"},{"indexed":false,"name":"_data","type":"bytes"}],"name":"Transfer","type":"event"}]
|
v0.4.24+commit.e67f0147
| false
| 200
|
Default
| false
|
bzzr://199847e1b9feb8e0c5d2f570f030a32d5b4beb706f29af303a1bd28842c9b706
|
||||
ReversibleDemo
|
0x11200ba97df0a6ee24ed7daf86c9033738119646
|
Solidity
|
// `interface` would make a nice keyword ;)
contract TheDaoHardForkOracle {
// `ran()` manually verified true on both ETH and ETC chains
function forked() constant returns (bool);
}
// demostrates calling own function in a "reversible" manner
/* important lines are marked by multi-line comments */
contract ReversibleDemo {
// counters (all public to simplify inspection)
uint public numcalls;
uint public numcallsinternal;
uint public numfails;
uint public numsuccesses;
address owner;
// needed for "naive" and "oraclized" checks
address constant withdrawdaoaddr = 0xbf4ed7b27f1d666546e30d74d50d173d20bca754;
TheDaoHardForkOracle oracle = TheDaoHardForkOracle(0xe8e506306ddb78ee38c9b0d86c257bd97c2536b3);
event logCall(uint indexed _numcalls,
uint indexed _numfails,
uint indexed _numsuccesses);
modifier onlyOwner { if (msg.sender != owner) throw; _ }
modifier onlyThis { if (msg.sender != address(this)) throw; _ }
// constructor (setting `owner` allows later termination)
function ReversibleDemo() { owner = msg.sender; }
/* external: increments stack height */
/* onlyThis: prevent actual external calling */
function sendIfNotForked() external onlyThis returns (bool) {
numcallsinternal++;
/* naive check for "is this the classic chain" */
// guaranteed `true`: enough has been withdrawn already
// three million ------> 3'000'000
if (withdrawdaoaddr.balance < 3000000 ether) {
/* intentionally not checking return value */
owner.send(42);
}
/* "reverse" if it's actually the HF chain */
if (oracle.forked()) throw;
// not exactly a "success": send() could have failed on classic
return true;
}
// accepts value transfers
function doCall(uint _gas) onlyOwner {
numcalls++;
if (!this.sendIfNotForked.gas(_gas)()) {
numfails++;
}
else {
numsuccesses++;
}
logCall(numcalls, numfails, numsuccesses);
}
function selfDestruct() onlyOwner {
selfdestruct(owner);
}
// accepts value trasfers, but does nothing
function() {}
}
|
[{"constant":true,"inputs":[],"name":"numsuccesses","outputs":[{"name":"","type":"uint256"}],"type":"function"},{"constant":true,"inputs":[],"name":"numfails","outputs":[{"name":"","type":"uint256"}],"type":"function"},{"constant":true,"inputs":[],"name":"numcalls","outputs":[{"name":"","type":"uint256"}],"type":"function"},{"constant":true,"inputs":[],"name":"numcallsinternal","outputs":[{"name":"","type":"uint256"}],"type":"function"},{"constant":false,"inputs":[],"name":"sendIfNotForked","outputs":[{"name":"","type":"bool"}],"type":"function"},{"constant":false,"inputs":[],"name":"selfDestruct","outputs":[],"type":"function"},{"constant":false,"inputs":[{"name":"_gas","type":"uint256"}],"name":"doCall","outputs":[],"type":"function"},{"inputs":[],"type":"constructor"},{"anonymous":false,"inputs":[{"indexed":true,"name":"_numcalls","type":"uint256"},{"indexed":true,"name":"_numfails","type":"uint256"},{"indexed":true,"name":"_numsuccesses","type":"uint256"}],"name":"logCall","type":"event"}]
|
v0.3.5-2016-08-07-f7af7de
| true
| 200
|
Default
| false
| |||||
ReversibleDemo
|
0x21d66d260b5e8cb819b0ffed6394cb09a0b56c68
|
Solidity
|
// `interface` would make a nice keyword ;)
contract TheDaoHardForkOracle {
// `ran()` manually verified true on both ETH and ETC chains
function forked() constant returns (bool);
}
// demostrates calling own function in a "reversible" manner
/* important lines are marked by multi-line comments */
contract ReversibleDemo {
// counters (all public to simplify inspection)
uint public numcalls;
uint public numcallsinternal;
uint public numfails;
uint public numsuccesses;
address owner;
// needed for "naive" and "oraclized" checks
address constant withdrawdaoaddr = 0xbf4ed7b27f1d666546e30d74d50d173d20bca754;
TheDaoHardForkOracle oracle = TheDaoHardForkOracle(0xe8e506306ddb78ee38c9b0d86c257bd97c2536b3);
event logCall(uint indexed _numcalls,
uint indexed _numfails,
uint indexed _numsuccesses);
modifier onlyOwner { if (msg.sender != owner) throw; _ }
modifier onlyThis { if (msg.sender != address(this)) throw; _ }
// constructor (setting `owner` allows later termination)
function ReversibleDemo() { owner = msg.sender; }
/* external: increments stack height */
/* onlyThis: prevent actual external calling */
function sendIfNotForked() external onlyThis returns (bool) {
numcallsinternal++;
/* naive check for "is this the classic chain" */
// guaranteed `true`: enough has been withdrawn already
// three million ------> 3'000'000
if (withdrawdaoaddr.balance < 3000000 ether) {
/* intentionally not checking return value */
owner.send(42);
}
/* "reverse" if it's actually the HF chain */
if (oracle.forked()) throw;
// not exactly a "success": send() could have failed on classic
return true;
}
// accepts value transfers
function doCall(uint _gas) onlyOwner {
numcalls++;
if (!this.sendIfNotForked.gas(_gas)()) {
numfails++;
}
else {
numsuccesses++;
}
logCall(numcalls, numfails, numsuccesses);
}
function selfDestruct() onlyOwner {
selfdestruct(owner);
}
// accepts value trasfers, but does nothing
function() {}
}
|
[{"constant":true,"inputs":[],"name":"numsuccesses","outputs":[{"name":"","type":"uint256"}],"type":"function"},{"constant":true,"inputs":[],"name":"numfails","outputs":[{"name":"","type":"uint256"}],"type":"function"},{"constant":true,"inputs":[],"name":"numcalls","outputs":[{"name":"","type":"uint256"}],"type":"function"},{"constant":true,"inputs":[],"name":"numcallsinternal","outputs":[{"name":"","type":"uint256"}],"type":"function"},{"constant":false,"inputs":[],"name":"sendIfNotForked","outputs":[{"name":"","type":"bool"}],"type":"function"},{"constant":false,"inputs":[],"name":"selfDestruct","outputs":[],"type":"function"},{"constant":false,"inputs":[{"name":"_gas","type":"uint256"}],"name":"doCall","outputs":[],"type":"function"},{"inputs":[],"type":"constructor"},{"anonymous":false,"inputs":[{"indexed":true,"name":"_numcalls","type":"uint256"},{"indexed":true,"name":"_numfails","type":"uint256"},{"indexed":true,"name":"_numsuccesses","type":"uint256"}],"name":"logCall","type":"event"}]
|
v0.3.5-2016-08-07-f7af7de
| true
| 200
|
Default
| false
| |||||
Forwarder
|
0xe930ba26018f72796c3f0527e0c58ea1d228f273
|
Solidity
|
pragma solidity ^0.4.14;
/**
* Contract that exposes the needed erc20 token functions
*/
contract ERC20Interface {
// Send _value amount of tokens to address _to
function transfer(address _to, uint256 _value) returns (bool success);
// Get the account balance of another account with address _owner
function balanceOf(address _owner) constant returns (uint256 balance);
}
/**
* Contract that will forward any incoming Ether to its creator
*/
contract Forwarder {
// Address to which any funds sent to this contract will be forwarded
address public parentAddress;
event ForwarderDeposited(address from, uint value, bytes data);
event TokensFlushed(
address tokenContractAddress, // The contract address of the token
uint value // Amount of token sent
);
/**
* Create the contract, and set the destination address to that of the creator
*/
function Forwarder() {
parentAddress = msg.sender;
}
/**
* Modifier that will execute internal code block only if the sender is a parent of the forwarder contract
*/
modifier onlyParent {
if (msg.sender != parentAddress) {
throw;
}
_;
}
/**
* Default function; Gets called when Ether is deposited, and forwards it to the destination address
*/
function() payable {
if (!parentAddress.call.value(msg.value)(msg.data))
throw;
// Fire off the deposited event if we can forward it
ForwarderDeposited(msg.sender, msg.value, msg.data);
}
/**
* Execute a token transfer of the full balance from the forwarder token to the main wallet contract
* @param tokenContractAddress the address of the erc20 token contract
*/
function flushTokens(address tokenContractAddress) onlyParent {
ERC20Interface instance = ERC20Interface(tokenContractAddress);
var forwarderAddress = address(this);
var forwarderBalance = instance.balanceOf(forwarderAddress);
if (forwarderBalance == 0) {
return;
}
if (!instance.transfer(parentAddress, forwarderBalance)) {
throw;
}
TokensFlushed(tokenContractAddress, forwarderBalance);
}
/**
* It is possible that funds were sent to this address before the contract was deployed.
* We can flush those funds to the destination address.
*/
function flush() {
if (!parentAddress.call.value(this.balance)())
throw;
}
}
/**
* Basic multi-signer wallet designed for use in a co-signing environment where 2 signatures are required to move funds.
* Typically used in a 2-of-3 signing configuration. Uses ecrecover to allow for 2 signatures in a single transaction.
*/
contract WalletSimple {
// Events
event Deposited(address from, uint value, bytes data);
event SafeModeActivated(address msgSender);
event Transacted(
address msgSender, // Address of the sender of the message initiating the transaction
address otherSigner, // Address of the signer (second signature) used to initiate the transaction
bytes32 operation, // Operation hash (sha3 of toAddress, value, data, expireTime, sequenceId)
address toAddress, // The address the transaction was sent to
uint value, // Amount of Wei sent to the address
bytes data // Data sent when invoking the transaction
);
event TokenTransacted(
address msgSender, // Address of the sender of the message initiating the transaction
address otherSigner, // Address of the signer (second signature) used to initiate the transaction
bytes32 operation, // Operation hash (sha3 of toAddress, value, tokenContractAddress, expireTime, sequenceId)
address toAddress, // The address the transaction was sent to
uint value, // Amount of token sent
address tokenContractAddress // The contract address of the token
);
// Public fields
address[] public signers; // The addresses that can co-sign transactions on the wallet
bool public safeMode = false; // When active, wallet may only send to signer addresses
// Internal fields
uint constant SEQUENCE_ID_WINDOW_SIZE = 10;
uint[10] recentSequenceIds;
/**
* Modifier that will execute internal code block only if the sender is an authorized signer on this wallet
*/
modifier onlysigner {
if (!isSigner(msg.sender)) {
throw;
}
_;
}
/**
* Set up a simple multi-sig wallet by specifying the signers allowed to be used on this wallet.
* 2 signers will be required to send a transaction from this wallet.
* Note: The sender is NOT automatically added to the list of signers.
* Signers CANNOT be changed once they are set
*
* @param allowedSigners An array of signers on the wallet
*/
function WalletSimple(address[] allowedSigners) {
if (allowedSigners.length != 3) {
// Invalid number of signers
throw;
}
signers = allowedSigners;
}
/**
* Gets called when a transaction is received without calling a method
*/
function() payable {
if (msg.value > 0) {
// Fire deposited event if we are receiving funds
Deposited(msg.sender, msg.value, msg.data);
}
}
/**
* Create a new contract (and also address) that forwards funds to this contract
* returns address of newly created forwarder address
*/
function createForwarder() onlysigner returns (address) {
return new Forwarder();
}
/**
* Execute a multi-signature transaction from this wallet using 2 signers: one from msg.sender and the other from ecrecover.
* The signature is a signed form (using eth.sign) of tightly packed toAddress, value, data, expireTime and sequenceId
* Sequence IDs are numbers starting from 1. They are used to prevent replay attacks and may not be repeated.
*
* @param toAddress the destination address to send an outgoing transaction
* @param value the amount in Wei to be sent
* @param data the data to send to the toAddress when invoking the transaction
* @param expireTime the number of seconds since 1970 for which this transaction is valid
* @param sequenceId the unique sequence id obtainable from getNextSequenceId
* @param signature the result of eth.sign on the operationHash sha3(toAddress, value, data, expireTime, sequenceId)
*/
function sendMultiSig(address toAddress, uint value, bytes data, uint expireTime, uint sequenceId, bytes signature) onlysigner {
// Verify the other signer
var operationHash = sha3("ETHER", toAddress, value, data, expireTime, sequenceId);
var otherSigner = verifyMultiSig(toAddress, operationHash, signature, expireTime, sequenceId);
// Success, send the transaction
if (!(toAddress.call.value(value)(data))) {
// Failed executing transaction
throw;
}
Transacted(msg.sender, otherSigner, operationHash, toAddress, value, data);
}
/**
* Execute a multi-signature token transfer from this wallet using 2 signers: one from msg.sender and the other from ecrecover.
* The signature is a signed form (using eth.sign) of tightly packed toAddress, value, tokenContractAddress, expireTime and sequenceId
* Sequence IDs are numbers starting from 1. They are used to prevent replay attacks and may not be repeated.
*
* @param toAddress the destination address to send an outgoing transaction
* @param value the amount in tokens to be sent
* @param tokenContractAddress the address of the erc20 token contract
* @param expireTime the number of seconds since 1970 for which this transaction is valid
* @param sequenceId the unique sequence id obtainable from getNextSequenceId
* @param signature the result of eth.sign on the operationHash sha3(toAddress, value, tokenContractAddress, expireTime, sequenceId)
*/
function sendMultiSigToken(address toAddress, uint value, address tokenContractAddress, uint expireTime, uint sequenceId, bytes signature) onlysigner {
// Verify the other signer
var operationHash = sha3("ERC20", toAddress, value, tokenContractAddress, expireTime, sequenceId);
var otherSigner = verifyMultiSig(toAddress, operationHash, signature, expireTime, sequenceId);
ERC20Interface instance = ERC20Interface(tokenContractAddress);
if (!instance.transfer(toAddress, value)) {
throw;
}
TokenTransacted(msg.sender, otherSigner, operationHash, toAddress, value, tokenContractAddress);
}
/**
* Execute a token flush from one of the forwarder addresses. This transfer needs only a single signature and can be done by any signer
*
* @param forwarderAddress the address of the forwarder address to flush the tokens from
* @param tokenContractAddress the address of the erc20 token contract
*/
function flushForwarderTokens(address forwarderAddress, address tokenContractAddress) onlysigner {
Forwarder forwarder = Forwarder(forwarderAddress);
forwarder.flushTokens(tokenContractAddress);
}
/**
* Do common multisig verification for both eth sends and erc20token transfers
*
* @param toAddress the destination address to send an outgoing transaction
* @param operationHash the sha3 of the toAddress, value, data/tokenContractAddress and expireTime
* @param signature the tightly packed signature of r, s, and v as an array of 65 bytes (returned by eth.sign)
* @param expireTime the number of seconds since 1970 for which this transaction is valid
* @param sequenceId the unique sequence id obtainable from getNextSequenceId
* returns address of the address to send tokens or eth to
*/
function verifyMultiSig(address toAddress, bytes32 operationHash, bytes signature, uint expireTime, uint sequenceId) private returns (address) {
var otherSigner = recoverAddressFromSignature(operationHash, signature);
// Verify if we are in safe mode. In safe mode, the wallet can only send to signers
if (safeMode && !isSigner(toAddress)) {
// We are in safe mode and the toAddress is not a signer. Disallow!
throw;
}
// Verify that the transaction has not expired
if (expireTime < block.timestamp) {
// Transaction expired
throw;
}
// Try to insert the sequence ID. Will throw if the sequence id was invalid
tryInsertSequenceId(sequenceId);
if (!isSigner(otherSigner)) {
// Other signer not on this wallet or operation does not match arguments
throw;
}
if (otherSigner == msg.sender) {
// Cannot approve own transaction
throw;
}
return otherSigner;
}
/**
* Irrevocably puts contract into safe mode. When in this mode, transactions may only be sent to signing addresses.
*/
function activateSafeMode() onlysigner {
safeMode = true;
SafeModeActivated(msg.sender);
}
/**
* Determine if an address is a signer on this wallet
* @param signer address to check
* returns boolean indicating whether address is signer or not
*/
function isSigner(address signer) returns (bool) {
// Iterate through all signers on the wallet and
for (uint i = 0; i < signers.length; i++) {
if (signers[i] == signer) {
return true;
}
}
return false;
}
/**
* Gets the second signer's address using ecrecover
* @param operationHash the sha3 of the toAddress, value, data/tokenContractAddress and expireTime
* @param signature the tightly packed signature of r, s, and v as an array of 65 bytes (returned by eth.sign)
* returns address recovered from the signature
*/
function recoverAddressFromSignature(bytes32 operationHash, bytes signature) private returns (address) {
if (signature.length != 65) {
throw;
}
// We need to unpack the signature, which is given as an array of 65 bytes (from eth.sign)
bytes32 r;
bytes32 s;
uint8 v;
assembly {
r := mload(add(signature, 32))
s := mload(add(signature, 64))
v := and(mload(add(signature, 65)), 255)
}
if (v < 27) {
v += 27; // Ethereum versions are 27 or 28 as opposed to 0 or 1 which is submitted by some signing libs
}
return ecrecover(operationHash, v, r, s);
}
/**
* Verify that the sequence id has not been used before and inserts it. Throws if the sequence ID was not accepted.
* We collect a window of up to 10 recent sequence ids, and allow any sequence id that is not in the window and
* greater than the minimum element in the window.
* @param sequenceId to insert into array of stored ids
*/
function tryInsertSequenceId(uint sequenceId) onlysigner private {
// Keep a pointer to the lowest value element in the window
uint lowestValueIndex = 0;
for (uint i = 0; i < SEQUENCE_ID_WINDOW_SIZE; i++) {
if (recentSequenceIds[i] == sequenceId) {
// This sequence ID has been used before. Disallow!
throw;
}
if (recentSequenceIds[i] < recentSequenceIds[lowestValueIndex]) {
lowestValueIndex = i;
}
}
if (sequenceId < recentSequenceIds[lowestValueIndex]) {
// The sequence ID being used is lower than the lowest value in the window
// so we cannot accept it as it may have been used before
throw;
}
if (sequenceId > (recentSequenceIds[lowestValueIndex] + 10000)) {
// Block sequence IDs which are much higher than the lowest value
// This prevents people blocking the contract by using very large sequence IDs quickly
throw;
}
recentSequenceIds[lowestValueIndex] = sequenceId;
}
/**
* Gets the next available sequence ID for signing when using executeAndConfirm
* returns the sequenceId one higher than the highest currently stored
*/
function getNextSequenceId() returns (uint) {
uint highestSequenceId = 0;
for (uint i = 0; i < SEQUENCE_ID_WINDOW_SIZE; i++) {
if (recentSequenceIds[i] > highestSequenceId) {
highestSequenceId = recentSequenceIds[i];
}
}
return highestSequenceId + 1;
}
}
|
[{"constant":true,"inputs":[],"name":"parentAddress","outputs":[{"name":"","type":"address"}],"payable":false,"type":"function"},{"constant":false,"inputs":[{"name":"tokenContractAddress","type":"address"}],"name":"flushTokens","outputs":[],"payable":false,"type":"function"},{"constant":false,"inputs":[],"name":"flush","outputs":[],"payable":false,"type":"function"},{"inputs":[],"payable":false,"type":"constructor"},{"payable":true,"type":"fallback"},{"anonymous":false,"inputs":[{"indexed":false,"name":"from","type":"address"},{"indexed":false,"name":"value","type":"uint256"},{"indexed":false,"name":"data","type":"bytes"}],"name":"ForwarderDeposited","type":"event"},{"anonymous":false,"inputs":[{"indexed":false,"name":"tokenContractAddress","type":"address"},{"indexed":false,"name":"value","type":"uint256"}],"name":"TokensFlushed","type":"event"}]
|
v0.4.16-nightly.2017.8.11+commit.c84de7fa
| true
| 200
|
Default
| false
|
bzzr://d0f8838ba17108a895d34ae8ef3bff4e0dc9d639c3c51921fee1d17eaa803721
|
||||
UserWallet
|
0x6e66ce20450e4f229ac4b5a242cdc9ab1c3ba9c3
|
Solidity
|
pragma solidity ^0.4.10;
// Copyright 2017 Bittrex
contract AbstractSweeper {
function sweep(address token, uint amount) returns (bool);
function () { throw; }
Controller controller;
function AbstractSweeper(address _controller) {
controller = Controller(_controller);
}
modifier canSweep() {
if (msg.sender != controller.authorizedCaller() && msg.sender != controller.owner()) throw;
if (controller.halted()) throw;
_;
}
}
contract Token {
function balanceOf(address a) returns (uint) {
(a);
return 0;
}
function transfer(address a, uint val) returns (bool) {
(a);
(val);
return false;
}
}
contract DefaultSweeper is AbstractSweeper {
function DefaultSweeper(address controller)
AbstractSweeper(controller) {}
function sweep(address _token, uint _amount)
canSweep
returns (bool) {
bool success = false;
address destination = controller.destination();
if (_token != address(0)) {
Token token = Token(_token);
uint amount = _amount;
if (amount > token.balanceOf(this)) {
return false;
}
success = token.transfer(destination, amount);
}
else {
uint amountInWei = _amount;
if (amountInWei > this.balance) {
return false;
}
success = destination.send(amountInWei);
}
if (success) {
controller.logSweep(this, destination, _token, _amount);
}
return success;
}
}
contract UserWallet {
AbstractSweeperList sweeperList;
function UserWallet(address _sweeperlist) {
sweeperList = AbstractSweeperList(_sweeperlist);
}
function () public payable { }
function tokenFallback(address _from, uint _value, bytes _data) {
(_from);
(_value);
(_data);
}
function sweep(address _token, uint _amount)
returns (bool) {
(_amount);
return sweeperList.sweeperOf(_token).delegatecall(msg.data);
}
}
contract AbstractSweeperList {
function sweeperOf(address _token) returns (address);
}
contract Controller is AbstractSweeperList {
address public owner;
address public authorizedCaller;
address public destination;
bool public halted;
event LogNewWallet(address receiver);
event LogSweep(address indexed from, address indexed to, address indexed token, uint amount);
modifier onlyOwner() {
if (msg.sender != owner) throw;
_;
}
modifier onlyAuthorizedCaller() {
if (msg.sender != authorizedCaller) throw;
_;
}
modifier onlyAdmins() {
if (msg.sender != authorizedCaller && msg.sender != owner) throw;
_;
}
function Controller()
{
owner = msg.sender;
destination = msg.sender;
authorizedCaller = msg.sender;
}
function changeAuthorizedCaller(address _newCaller) onlyOwner {
authorizedCaller = _newCaller;
}
function changeDestination(address _dest) onlyOwner {
destination = _dest;
}
function changeOwner(address _owner) onlyOwner {
owner = _owner;
}
function makeWallet() onlyAdmins returns (address wallet) {
wallet = address(new UserWallet(this));
LogNewWallet(wallet);
}
function halt() onlyAdmins {
halted = true;
}
function start() onlyOwner {
halted = false;
}
address public defaultSweeper = address(new DefaultSweeper(this));
mapping (address => address) sweepers;
function addSweeper(address _token, address _sweeper) onlyOwner {
sweepers[_token] = _sweeper;
}
function sweeperOf(address _token) returns (address) {
address sweeper = sweepers[_token];
if (sweeper == 0) sweeper = defaultSweeper;
return sweeper;
}
function logSweep(address from, address to, address token, uint amount) {
LogSweep(from, to, token, amount);
}
}
|
[{"constant":false,"inputs":[{"name":"_token","type":"address"},{"name":"_amount","type":"uint256"}],"name":"sweep","outputs":[{"name":"","type":"bool"}],"payable":false,"type":"function"},{"constant":false,"inputs":[{"name":"_from","type":"address"},{"name":"_value","type":"uint256"},{"name":"_data","type":"bytes"}],"name":"tokenFallback","outputs":[],"payable":false,"type":"function"},{"inputs":[{"name":"_sweeperlist","type":"address"}],"payable":false,"type":"constructor"},{"payable":true,"type":"fallback"}]
|
v0.4.11+commit.68ef5810
| true
| 200
|
000000000000000000000000a3C1E324CA1ce40db73eD6026c4A177F099B5770
|
Default
| false
|
bzzr://4cdd69fdcf3cf6cbee9677fe380fa5f044048aa9e060ec5619a21ca5a5bd4cd1
|
|||
UserWallet
|
0x9a8321a82f80eefba8a733920a30eada8571d148
|
Solidity
|
pragma solidity ^0.4.10;
// Copyright 2017 Bittrex
contract AbstractSweeper {
function sweep(address token, uint amount) returns (bool);
function () { throw; }
Controller controller;
function AbstractSweeper(address _controller) {
controller = Controller(_controller);
}
modifier canSweep() {
if (msg.sender != controller.authorizedCaller() && msg.sender != controller.owner()) throw;
if (controller.halted()) throw;
_;
}
}
contract Token {
function balanceOf(address a) returns (uint) {
(a);
return 0;
}
function transfer(address a, uint val) returns (bool) {
(a);
(val);
return false;
}
}
contract DefaultSweeper is AbstractSweeper {
function DefaultSweeper(address controller)
AbstractSweeper(controller) {}
function sweep(address _token, uint _amount)
canSweep
returns (bool) {
bool success = false;
address destination = controller.destination();
if (_token != address(0)) {
Token token = Token(_token);
uint amount = _amount;
if (amount > token.balanceOf(this)) {
return false;
}
success = token.transfer(destination, amount);
}
else {
uint amountInWei = _amount;
if (amountInWei > this.balance) {
return false;
}
success = destination.send(amountInWei);
}
if (success) {
controller.logSweep(this, destination, _token, _amount);
}
return success;
}
}
contract UserWallet {
AbstractSweeperList sweeperList;
function UserWallet(address _sweeperlist) {
sweeperList = AbstractSweeperList(_sweeperlist);
}
function () public payable { }
function tokenFallback(address _from, uint _value, bytes _data) {
(_from);
(_value);
(_data);
}
function sweep(address _token, uint _amount)
returns (bool) {
(_amount);
return sweeperList.sweeperOf(_token).delegatecall(msg.data);
}
}
contract AbstractSweeperList {
function sweeperOf(address _token) returns (address);
}
contract Controller is AbstractSweeperList {
address public owner;
address public authorizedCaller;
address public destination;
bool public halted;
event LogNewWallet(address receiver);
event LogSweep(address indexed from, address indexed to, address indexed token, uint amount);
modifier onlyOwner() {
if (msg.sender != owner) throw;
_;
}
modifier onlyAuthorizedCaller() {
if (msg.sender != authorizedCaller) throw;
_;
}
modifier onlyAdmins() {
if (msg.sender != authorizedCaller && msg.sender != owner) throw;
_;
}
function Controller()
{
owner = msg.sender;
destination = msg.sender;
authorizedCaller = msg.sender;
}
function changeAuthorizedCaller(address _newCaller) onlyOwner {
authorizedCaller = _newCaller;
}
function changeDestination(address _dest) onlyOwner {
destination = _dest;
}
function changeOwner(address _owner) onlyOwner {
owner = _owner;
}
function makeWallet() onlyAdmins returns (address wallet) {
wallet = address(new UserWallet(this));
LogNewWallet(wallet);
}
function halt() onlyAdmins {
halted = true;
}
function start() onlyOwner {
halted = false;
}
address public defaultSweeper = address(new DefaultSweeper(this));
mapping (address => address) sweepers;
function addSweeper(address _token, address _sweeper) onlyOwner {
sweepers[_token] = _sweeper;
}
function sweeperOf(address _token) returns (address) {
address sweeper = sweepers[_token];
if (sweeper == 0) sweeper = defaultSweeper;
return sweeper;
}
function logSweep(address from, address to, address token, uint amount) {
LogSweep(from, to, token, amount);
}
}
|
[{"constant":false,"inputs":[{"name":"_token","type":"address"},{"name":"_amount","type":"uint256"}],"name":"sweep","outputs":[{"name":"","type":"bool"}],"payable":false,"type":"function"},{"constant":false,"inputs":[{"name":"_from","type":"address"},{"name":"_value","type":"uint256"},{"name":"_data","type":"bytes"}],"name":"tokenFallback","outputs":[],"payable":false,"type":"function"},{"inputs":[{"name":"_sweeperlist","type":"address"}],"payable":false,"type":"constructor"},{"payable":true,"type":"fallback"}]
|
v0.4.11+commit.68ef5810
| true
| 200
|
000000000000000000000000a3C1E324CA1ce40db73eD6026c4A177F099B5770
|
Default
| false
|
bzzr://4cdd69fdcf3cf6cbee9677fe380fa5f044048aa9e060ec5619a21ca5a5bd4cd1
|
|||
Proxy
|
0x061f88e6065cc034fed4b466e2ba6c053e70d111
|
Solidity
|
pragma solidity ^0.5.3;
/// @title Proxy - Generic proxy contract allows to execute all transactions applying the code of a master contract.
/// @author Stefan George - <[email protected]>
/// @author Richard Meissner - <[email protected]>
contract Proxy {
// masterCopy always needs to be first declared variable, to ensure that it is at the same location in the contracts to which calls are delegated.
// To reduce deployment costs this variable is internal and needs to be retrieved via `getStorageAt`
address internal masterCopy;
/// @dev Constructor function sets address of master copy contract.
/// @param _masterCopy Master copy address.
constructor(address _masterCopy)
public
{
require(_masterCopy != address(0), "Invalid master copy address provided");
masterCopy = _masterCopy;
}
/// @dev Fallback function forwards all transactions and returns all received return data.
function ()
external
payable
{
// solium-disable-next-line security/no-inline-assembly
assembly {
let masterCopy := and(sload(0), 0xffffffffffffffffffffffffffffffffffffffff)
// 0xa619486e == keccak("masterCopy()"). The value is right padded to 32-bytes with 0s
if eq(calldataload(0), 0xa619486e00000000000000000000000000000000000000000000000000000000) {
mstore(0, masterCopy)
return(0, 0x20)
}
calldatacopy(0, 0, calldatasize())
let success := delegatecall(gas, masterCopy, 0, calldatasize(), 0, 0)
returndatacopy(0, 0, returndatasize())
if eq(success, 0) { revert(0, returndatasize()) }
return(0, returndatasize())
}
}
}
|
[{"inputs":[{"internalType":"address","name":"_masterCopy","type":"address"}],"payable":false,"stateMutability":"nonpayable","type":"constructor"},{"payable":true,"stateMutability":"payable","type":"fallback"}]
|
v0.5.14+commit.1f1aaa4
| false
| 200
|
00000000000000000000000034cfac646f301356faa8b21e94227e3583fe3f5f
|
Default
|
MIT
| false
|
bzzr://d8a00dc4fe6bf675a9d7416fc2d00bb3433362aa8186b750f76c4027269667ff
|
||
OwnableDelegateProxy
|
0x253492881eeafed93c50e86be462fa002003e0c5
|
Solidity
|
contract OwnedUpgradeabilityStorage {
// Current implementation
address internal _implementation;
// Owner of the contract
address private _upgradeabilityOwner;
/**
* @dev Tells the address of the owner
* @return the address of the owner
*/
function upgradeabilityOwner() public view returns (address) {
return _upgradeabilityOwner;
}
/**
* @dev Sets the address of the owner
*/
function setUpgradeabilityOwner(address newUpgradeabilityOwner) internal {
_upgradeabilityOwner = newUpgradeabilityOwner;
}
/**
* @dev Tells the address of the current implementation
* @return address of the current implementation
*/
function implementation() public view returns (address) {
return _implementation;
}
/**
* @dev Tells the proxy type (EIP 897)
* @return Proxy type, 2 for forwarding proxy
*/
function proxyType() public pure returns (uint256 proxyTypeId) {
return 2;
}
}
contract Proxy {
/**
* @dev Tells the address of the implementation where every call will be delegated.
* @return address of the implementation to which it will be delegated
*/
function implementation() public view returns (address);
/**
* @dev Tells the type of proxy (EIP 897)
* @return Type of proxy, 2 for upgradeable proxy
*/
function proxyType() public pure returns (uint256 proxyTypeId);
/**
* @dev Fallback function allowing to perform a delegatecall to the given implementation.
* This function will return whatever the implementation call returns
*/
function () payable public {
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 OwnedUpgradeabilityProxy is Proxy, OwnedUpgradeabilityStorage {
/**
* @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);
/**
* @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);
/**
* @dev Upgrades the implementation address
* @param implementation representing the address of the new implementation to be set
*/
function _upgradeTo(address implementation) internal {
require(_implementation != implementation);
_implementation = implementation;
emit Upgraded(implementation);
}
/**
* @dev Throws if called by any account other than the owner.
*/
modifier onlyProxyOwner() {
require(msg.sender == proxyOwner());
_;
}
/**
* @dev Tells the address of the proxy owner
* @return the address of the proxy owner
*/
function proxyOwner() public view returns (address) {
return upgradeabilityOwner();
}
/**
* @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) public onlyProxyOwner {
require(newOwner != address(0));
emit ProxyOwnershipTransferred(proxyOwner(), newOwner);
setUpgradeabilityOwner(newOwner);
}
/**
* @dev Allows the upgradeability owner to upgrade the current implementation of the proxy.
* @param implementation representing the address of the new implementation to be set.
*/
function upgradeTo(address implementation) public onlyProxyOwner {
_upgradeTo(implementation);
}
/**
* @dev Allows the upgradeability owner to upgrade the current implementation of the proxy
* and delegatecall the new implementation for initialization.
* @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 data) payable public onlyProxyOwner {
upgradeTo(implementation);
require(address(this).delegatecall(data));
}
}
contract OwnableDelegateProxy is OwnedUpgradeabilityProxy {
constructor(address owner, address initialImplementation, bytes calldata)
public
{
setUpgradeabilityOwner(owner);
_upgradeTo(initialImplementation);
require(initialImplementation.delegatecall(calldata));
}
}
|
[{"constant":true,"inputs":[],"name":"proxyOwner","outputs":[{"name":"","type":"address"}],"payable":false,"stateMutability":"view","type":"function"},{"constant":false,"inputs":[{"name":"implementation","type":"address"}],"name":"upgradeTo","outputs":[],"payable":false,"stateMutability":"nonpayable","type":"function"},{"constant":true,"inputs":[],"name":"proxyType","outputs":[{"name":"proxyTypeId","type":"uint256"}],"payable":false,"stateMutability":"pure","type":"function"},{"constant":false,"inputs":[{"name":"implementation","type":"address"},{"name":"data","type":"bytes"}],"name":"upgradeToAndCall","outputs":[],"payable":true,"stateMutability":"payable","type":"function"},{"constant":true,"inputs":[],"name":"implementation","outputs":[{"name":"","type":"address"}],"payable":false,"stateMutability":"view","type":"function"},{"constant":true,"inputs":[],"name":"upgradeabilityOwner","outputs":[{"name":"","type":"address"}],"payable":false,"stateMutability":"view","type":"function"},{"constant":false,"inputs":[{"name":"newOwner","type":"address"}],"name":"transferProxyOwnership","outputs":[],"payable":false,"stateMutability":"nonpayable","type":"function"},{"inputs":[{"name":"owner","type":"address"},{"name":"initialImplementation","type":"address"},{"name":"calldata","type":"bytes"}],"payable":false,"stateMutability":"nonpayable","type":"constructor"},{"payable":true,"stateMutability":"payable","type":"fallback"},{"anonymous":false,"inputs":[{"indexed":false,"name":"previousOwner","type":"address"},{"indexed":false,"name":"newOwner","type":"address"}],"name":"ProxyOwnershipTransferred","type":"event"},{"anonymous":false,"inputs":[{"indexed":true,"name":"implementation","type":"address"}],"name":"Upgraded","type":"event"}]
|
v0.4.23+commit.124ca40d
| true
| 200
|
00000000000000000000000074451193ccf4d1c9182c973538d9d2339350ee1a000000000000000000000000f9e266af4bca5890e2781812cc6a6e89495a79f200000000000000000000000000000000000000000000000000000000000000600000000000000000000000000000000000000000000000000000000000000044485cc95500000000000000000000000074451193ccf4d1c9182c973538d9d2339350ee1a000000000000000000000000a5409ec958c83c3f309868babaca7c86dcb077c100000000000000000000000000000000000000000000000000000000
|
Default
|
MIT
| false
|
bzzr://5f26049bbc794226b505f589b2ee1130db54310d79dd8a635c6f6c61e305a777
|
||
UserWallet
|
0x2a4521f02712751f0a9893469589ee49568110ac
|
Solidity
|
pragma solidity ^0.4.10;
// Copyright 2017 Bittrex
contract AbstractSweeper {
function sweep(address token, uint amount) returns (bool);
function () { throw; }
Controller controller;
function AbstractSweeper(address _controller) {
controller = Controller(_controller);
}
modifier canSweep() {
if (msg.sender != controller.authorizedCaller() && msg.sender != controller.owner()) throw;
if (controller.halted()) throw;
_;
}
}
contract Token {
function balanceOf(address a) returns (uint) {
(a);
return 0;
}
function transfer(address a, uint val) returns (bool) {
(a);
(val);
return false;
}
}
contract DefaultSweeper is AbstractSweeper {
function DefaultSweeper(address controller)
AbstractSweeper(controller) {}
function sweep(address _token, uint _amount)
canSweep
returns (bool) {
bool success = false;
address destination = controller.destination();
if (_token != address(0)) {
Token token = Token(_token);
uint amount = _amount;
if (amount > token.balanceOf(this)) {
return false;
}
success = token.transfer(destination, amount);
}
else {
uint amountInWei = _amount;
if (amountInWei > this.balance) {
return false;
}
success = destination.send(amountInWei);
}
if (success) {
controller.logSweep(this, destination, _token, _amount);
}
return success;
}
}
contract UserWallet {
AbstractSweeperList sweeperList;
function UserWallet(address _sweeperlist) {
sweeperList = AbstractSweeperList(_sweeperlist);
}
function () public payable { }
function tokenFallback(address _from, uint _value, bytes _data) {
(_from);
(_value);
(_data);
}
function sweep(address _token, uint _amount)
returns (bool) {
(_amount);
return sweeperList.sweeperOf(_token).delegatecall(msg.data);
}
}
contract AbstractSweeperList {
function sweeperOf(address _token) returns (address);
}
contract Controller is AbstractSweeperList {
address public owner;
address public authorizedCaller;
address public destination;
bool public halted;
event LogNewWallet(address receiver);
event LogSweep(address indexed from, address indexed to, address indexed token, uint amount);
modifier onlyOwner() {
if (msg.sender != owner) throw;
_;
}
modifier onlyAuthorizedCaller() {
if (msg.sender != authorizedCaller) throw;
_;
}
modifier onlyAdmins() {
if (msg.sender != authorizedCaller && msg.sender != owner) throw;
_;
}
function Controller()
{
owner = msg.sender;
destination = msg.sender;
authorizedCaller = msg.sender;
}
function changeAuthorizedCaller(address _newCaller) onlyOwner {
authorizedCaller = _newCaller;
}
function changeDestination(address _dest) onlyOwner {
destination = _dest;
}
function changeOwner(address _owner) onlyOwner {
owner = _owner;
}
function makeWallet() onlyAdmins returns (address wallet) {
wallet = address(new UserWallet(this));
LogNewWallet(wallet);
}
function halt() onlyAdmins {
halted = true;
}
function start() onlyOwner {
halted = false;
}
address public defaultSweeper = address(new DefaultSweeper(this));
mapping (address => address) sweepers;
function addSweeper(address _token, address _sweeper) onlyOwner {
sweepers[_token] = _sweeper;
}
function sweeperOf(address _token) returns (address) {
address sweeper = sweepers[_token];
if (sweeper == 0) sweeper = defaultSweeper;
return sweeper;
}
function logSweep(address from, address to, address token, uint amount) {
LogSweep(from, to, token, amount);
}
}
|
[{"constant":false,"inputs":[{"name":"_token","type":"address"},{"name":"_amount","type":"uint256"}],"name":"sweep","outputs":[{"name":"","type":"bool"}],"payable":false,"type":"function"},{"constant":false,"inputs":[{"name":"_from","type":"address"},{"name":"_value","type":"uint256"},{"name":"_data","type":"bytes"}],"name":"tokenFallback","outputs":[],"payable":false,"type":"function"},{"inputs":[{"name":"_sweeperlist","type":"address"}],"payable":false,"type":"constructor"},{"payable":true,"type":"fallback"}]
|
v0.4.11+commit.68ef5810
| true
| 200
|
000000000000000000000000a3C1E324CA1ce40db73eD6026c4A177F099B5770
|
Default
| false
|
bzzr://4cdd69fdcf3cf6cbee9677fe380fa5f044048aa9e060ec5619a21ca5a5bd4cd1
|
|||
Forwarder
|
0x4df4861325035437ceecaa355fe7b668d3f0e2b0
|
Solidity
|
pragma solidity 0.7.5;
/*
The MIT License (MIT)
Copyright (c) 2018 Murray Software, LLC.
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.
*/
//solhint-disable max-line-length
//solhint-disable no-inline-assembly
contract CloneFactory {
function createClone(address target, bytes32 salt)
internal
returns (address payable result)
{
bytes20 targetBytes = bytes20(target);
assembly {
// load the next free memory slot as a place to store the clone contract data
let clone := mload(0x40)
// The bytecode block below is responsible for contract initialization
// during deployment, it is worth noting the proxied contract constructor will not be called during
// the cloning procedure and that is why an initialization function needs to be called after the
// clone is created
mstore(
clone,
0x3d602d80600a3d3981f3363d3d373d3d3d363d73000000000000000000000000
)
// This stores the address location of the implementation contract
// so that the proxy knows where to delegate call logic to
mstore(add(clone, 0x14), targetBytes)
// The bytecode block is the actual code that is deployed for each clone created.
// It forwards all calls to the already deployed implementation via a delegatecall
mstore(
add(clone, 0x28),
0x5af43d82803e903d91602b57fd5bf30000000000000000000000000000000000
)
// deploy the contract using the CREATE2 opcode
// this deploys the minimal proxy defined above, which will proxy all
// calls to use the logic defined in the implementation contract `target`
result := create2(0, clone, 0x37, salt)
}
}
function isClone(address target, address query)
internal
view
returns (bool result)
{
bytes20 targetBytes = bytes20(target);
assembly {
// load the next free memory slot as a place to store the comparison clone
let clone := mload(0x40)
// The next three lines store the expected bytecode for a miniml proxy
// that targets `target` as its implementation contract
mstore(
clone,
0x363d3d373d3d3d363d7300000000000000000000000000000000000000000000
)
mstore(add(clone, 0xa), targetBytes)
mstore(
add(clone, 0x1e),
0x5af43d82803e903d91602b57fd5bf30000000000000000000000000000000000
)
// the next two lines store the bytecode of the contract that we are checking in memory
let other := add(clone, 0x40)
extcodecopy(query, other, 0, 0x2d)
// Check if the expected bytecode equals the actual bytecode and return the result
result := and(
eq(mload(clone), mload(other)),
eq(mload(add(clone, 0xd)), mload(add(other, 0xd)))
)
}
}
}
/**
* Contract that exposes the needed erc20 token functions
*/
abstract contract ERC20Interface {
// Send _value amount of tokens to address _to
function transfer(address _to, uint256 _value)
public
virtual
returns (bool success);
// Get the account balance of another account with address _owner
function balanceOf(address _owner)
public
virtual
view
returns (uint256 balance);
}
// helper methods for interacting with ERC20 tokens and sending ETH that do not consistently return true/false
library TransferHelper {
function safeApprove(
address token,
address to,
uint256 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::safeApprove: approve failed'
);
}
function safeTransfer(
address token,
address to,
uint256 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::safeTransfer: transfer failed'
);
}
function safeTransferFrom(
address token,
address from,
address to,
uint256 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::transferFrom: transferFrom failed'
);
}
function safeTransferETH(address to, uint256 value) internal {
(bool success, ) = to.call{value: value}(new bytes(0));
require(success, 'TransferHelper::safeTransferETH: ETH transfer failed');
}
}
/**
* Contract that will forward any incoming Ether to the creator of the contract
*
*/
contract Forwarder {
// Address to which any funds sent to this contract will be forwarded
address public parentAddress;
event ForwarderDeposited(address from, uint256 value, bytes data);
/**
* Initialize the contract, and sets the destination address to that of the creator
*/
function init(address _parentAddress) external onlyUninitialized {
parentAddress = _parentAddress;
uint256 value = address(this).balance;
if (value == 0) {
return;
}
(bool success, ) = parentAddress.call{ value: value }('');
require(success, 'Flush failed');
// NOTE: since we are forwarding on initialization,
// we don't have the context of the original sender.
// We still emit an event about the forwarding but set
// the sender to the forwarder itself
emit ForwarderDeposited(address(this), value, msg.data);
}
/**
* Modifier that will execute internal code block only if the sender is the parent address
*/
modifier onlyParent {
require(msg.sender == parentAddress, 'Only Parent');
_;
}
/**
* Modifier that will execute internal code block only if the contract has not been initialized yet
*/
modifier onlyUninitialized {
require(parentAddress == address(0x0), 'Already initialized');
_;
}
/**
* Default function; Gets called when data is sent but does not match any other function
*/
fallback() external payable {
flush();
}
/**
* Default function; Gets called when Ether is deposited with no data, and forwards it to the parent address
*/
receive() external payable {
flush();
}
/**
* Execute a token transfer of the full balance from the forwarder token to the parent address
* @param tokenContractAddress the address of the erc20 token contract
*/
function flushTokens(address tokenContractAddress) external onlyParent {
ERC20Interface instance = ERC20Interface(tokenContractAddress);
address forwarderAddress = address(this);
uint256 forwarderBalance = instance.balanceOf(forwarderAddress);
if (forwarderBalance == 0) {
return;
}
TransferHelper.safeTransfer(
tokenContractAddress,
parentAddress,
forwarderBalance
);
}
/**
* Flush the entire balance of the contract to the parent address.
*/
function flush() public {
uint256 value = address(this).balance;
if (value == 0) {
return;
}
(bool success, ) = parentAddress.call{ value: value }('');
require(success, 'Flush failed');
emit ForwarderDeposited(msg.sender, value, msg.data);
}
}
contract ForwarderFactory is CloneFactory {
address public implementationAddress;
event ForwarderCreated(address newForwarderAddress, address parentAddress);
constructor(address _implementationAddress) {
implementationAddress = _implementationAddress;
}
function createForwarder(address parent, bytes32 salt) external {
// include the signers in the salt so any contract deployed to a given address must have the same signers
bytes32 finalSalt = keccak256(abi.encodePacked(parent, salt));
address payable clone = createClone(implementationAddress, finalSalt);
Forwarder(clone).init(parent);
emit ForwarderCreated(clone, parent);
}
}
|
[{"anonymous":false,"inputs":[{"indexed":false,"internalType":"address","name":"from","type":"address"},{"indexed":false,"internalType":"uint256","name":"value","type":"uint256"},{"indexed":false,"internalType":"bytes","name":"data","type":"bytes"}],"name":"ForwarderDeposited","type":"event"},{"stateMutability":"payable","type":"fallback"},{"inputs":[],"name":"flush","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"address","name":"tokenContractAddress","type":"address"}],"name":"flushTokens","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"address","name":"_parentAddress","type":"address"}],"name":"init","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[],"name":"parentAddress","outputs":[{"internalType":"address","name":"","type":"address"}],"stateMutability":"view","type":"function"},{"stateMutability":"payable","type":"receive"}]
|
v0.7.5+commit.eb77ed08
| false
| 200
|
Default
|
Apache-2.0
| false
|
ipfs://934a7b5f246917d20f5e049b9344e4f3d923110c9d150ea2a4118848dd414bc3
|
|||
DSProxy
|
0x6ec69dbe740cdf35551e2aac9d6428cd0767af9d
|
Solidity
|
// proxy.sol - execute actions atomically through the proxy's identity
// Copyright (C) 2017 DappHub, LLC
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
// You should have received a copy of the GNU General Public License
// along with this program. If not, see <http://www.gnu.org/licenses/>.
pragma solidity ^0.4.23;
contract DSAuthority {
function canCall(
address src, address dst, bytes4 sig
) public view returns (bool);
}
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(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, this, sig);
}
}
}
contract DSNote {
event LogNote(
bytes4 indexed sig,
address indexed guy,
bytes32 indexed foo,
bytes32 indexed bar,
uint 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);
_;
}
}
// DSProxy
// Allows code execution using a persistant identity This can be very
// useful to execute a sequence of atomic actions. Since the owner of
// the proxy can be changed, this allows for dynamic ownership models
// i.e. a multisig
contract DSProxy is DSAuth, DSNote {
DSProxyCache public cache; // global cache for contracts
constructor(address _cacheAddr) public {
require(setCache(_cacheAddr));
}
function() public payable {
}
// use the proxy to execute calldata _data on contract _code
function execute(bytes _code, bytes _data)
public
payable
returns (address target, bytes32 response)
{
target = cache.read(_code);
if (target == 0x0) {
// deploy contract & store its address in cache
target = cache.write(_code);
}
response = execute(target, _data);
}
function execute(address _target, bytes _data)
public
auth
note
payable
returns (bytes32 response)
{
require(_target != 0x0);
// call contract in current context
assembly {
let succeeded := delegatecall(sub(gas, 5000), _target, add(_data, 0x20), mload(_data), 0, 32)
response := mload(0) // load delegatecall output
switch iszero(succeeded)
case 1 {
// throw if delegatecall failed
revert(0, 0)
}
}
}
//set new cache
function setCache(address _cacheAddr)
public
auth
note
returns (bool)
{
require(_cacheAddr != 0x0); // invalid cache address
cache = DSProxyCache(_cacheAddr); // overwrite cache
return true;
}
}
// DSProxyFactory
// This factory deploys new proxy instances through build()
// Deployed proxy addresses are logged
contract DSProxyFactory {
event Created(address indexed sender, address indexed owner, address proxy, address cache);
mapping(address=>bool) public isProxy;
DSProxyCache public cache = new DSProxyCache();
// deploys a new proxy instance
// sets owner of proxy to caller
function build() public returns (DSProxy proxy) {
proxy = build(msg.sender);
}
// deploys a new proxy instance
// sets custom owner of proxy
function build(address owner) public returns (DSProxy proxy) {
proxy = new DSProxy(cache);
emit Created(msg.sender, owner, address(proxy), address(cache));
proxy.setOwner(owner);
isProxy[proxy] = true;
}
}
// DSProxyCache
// This global cache stores addresses of contracts previously deployed
// by a proxy. This saves gas from repeat deployment of the same
// contracts and eliminates blockchain bloat.
// By default, all proxies deployed from the same factory store
// contracts in the same cache. The cache a proxy instance uses can be
// changed. The cache uses the sha3 hash of a contract's bytecode to
// lookup the address
contract DSProxyCache {
mapping(bytes32 => address) cache;
function read(bytes _code) public view returns (address) {
bytes32 hash = keccak256(_code);
return cache[hash];
}
function write(bytes _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;
}
}
|
[{"constant":false,"inputs":[{"name":"owner_","type":"address"}],"name":"setOwner","outputs":[],"payable":false,"stateMutability":"nonpayable","type":"function"},{"constant":false,"inputs":[{"name":"_target","type":"address"},{"name":"_data","type":"bytes"}],"name":"execute","outputs":[{"name":"response","type":"bytes32"}],"payable":true,"stateMutability":"payable","type":"function"},{"constant":false,"inputs":[{"name":"_code","type":"bytes"},{"name":"_data","type":"bytes"}],"name":"execute","outputs":[{"name":"target","type":"address"},{"name":"response","type":"bytes32"}],"payable":true,"stateMutability":"payable","type":"function"},{"constant":true,"inputs":[],"name":"cache","outputs":[{"name":"","type":"address"}],"payable":false,"stateMutability":"view","type":"function"},{"constant":false,"inputs":[{"name":"authority_","type":"address"}],"name":"setAuthority","outputs":[],"payable":false,"stateMutability":"nonpayable","type":"function"},{"constant":true,"inputs":[],"name":"owner","outputs":[{"name":"","type":"address"}],"payable":false,"stateMutability":"view","type":"function"},{"constant":false,"inputs":[{"name":"_cacheAddr","type":"address"}],"name":"setCache","outputs":[{"name":"","type":"bool"}],"payable":false,"stateMutability":"nonpayable","type":"function"},{"constant":true,"inputs":[],"name":"authority","outputs":[{"name":"","type":"address"}],"payable":false,"stateMutability":"view","type":"function"},{"inputs":[{"name":"_cacheAddr","type":"address"}],"payable":false,"stateMutability":"nonpayable","type":"constructor"},{"payable":true,"stateMutability":"payable","type":"fallback"},{"anonymous":true,"inputs":[{"indexed":true,"name":"sig","type":"bytes4"},{"indexed":true,"name":"guy","type":"address"},{"indexed":true,"name":"foo","type":"bytes32"},{"indexed":true,"name":"bar","type":"bytes32"},{"indexed":false,"name":"wad","type":"uint256"},{"indexed":false,"name":"fax","type":"bytes"}],"name":"LogNote","type":"event"},{"anonymous":false,"inputs":[{"indexed":true,"name":"authority","type":"address"}],"name":"LogSetAuthority","type":"event"},{"anonymous":false,"inputs":[{"indexed":true,"name":"owner","type":"address"}],"name":"LogSetOwner","type":"event"}]
|
v0.4.23+commit.124ca40d
| true
| 200
|
000000000000000000000000271293c67e2d3140a0e9381eff1f9b01e07b0795
|
Default
| false
|
bzzr://e498874c9ba9e75028e0c84f1b1d83b2dad5de910c59b837b32e5a190794c5e1
|
|||
UserWallet
|
0x4823614e0af29351a6a07234dd5e4be9ef656ef9
|
Solidity
|
pragma solidity ^0.4.10;
// Copyright 2017 Bittrex
contract AbstractSweeper {
function sweep(address token, uint amount) returns (bool);
function () { throw; }
Controller controller;
function AbstractSweeper(address _controller) {
controller = Controller(_controller);
}
modifier canSweep() {
if (msg.sender != controller.authorizedCaller() && msg.sender != controller.owner()) throw;
if (controller.halted()) throw;
_;
}
}
contract Token {
function balanceOf(address a) returns (uint) {
(a);
return 0;
}
function transfer(address a, uint val) returns (bool) {
(a);
(val);
return false;
}
}
contract DefaultSweeper is AbstractSweeper {
function DefaultSweeper(address controller)
AbstractSweeper(controller) {}
function sweep(address _token, uint _amount)
canSweep
returns (bool) {
bool success = false;
address destination = controller.destination();
if (_token != address(0)) {
Token token = Token(_token);
uint amount = _amount;
if (amount > token.balanceOf(this)) {
return false;
}
success = token.transfer(destination, amount);
}
else {
uint amountInWei = _amount;
if (amountInWei > this.balance) {
return false;
}
success = destination.send(amountInWei);
}
if (success) {
controller.logSweep(this, destination, _token, _amount);
}
return success;
}
}
contract UserWallet {
AbstractSweeperList sweeperList;
function UserWallet(address _sweeperlist) {
sweeperList = AbstractSweeperList(_sweeperlist);
}
function () public payable { }
function tokenFallback(address _from, uint _value, bytes _data) {
(_from);
(_value);
(_data);
}
function sweep(address _token, uint _amount)
returns (bool) {
(_amount);
return sweeperList.sweeperOf(_token).delegatecall(msg.data);
}
}
contract AbstractSweeperList {
function sweeperOf(address _token) returns (address);
}
contract Controller is AbstractSweeperList {
address public owner;
address public authorizedCaller;
address public destination;
bool public halted;
event LogNewWallet(address receiver);
event LogSweep(address indexed from, address indexed to, address indexed token, uint amount);
modifier onlyOwner() {
if (msg.sender != owner) throw;
_;
}
modifier onlyAuthorizedCaller() {
if (msg.sender != authorizedCaller) throw;
_;
}
modifier onlyAdmins() {
if (msg.sender != authorizedCaller && msg.sender != owner) throw;
_;
}
function Controller()
{
owner = msg.sender;
destination = msg.sender;
authorizedCaller = msg.sender;
}
function changeAuthorizedCaller(address _newCaller) onlyOwner {
authorizedCaller = _newCaller;
}
function changeDestination(address _dest) onlyOwner {
destination = _dest;
}
function changeOwner(address _owner) onlyOwner {
owner = _owner;
}
function makeWallet() onlyAdmins returns (address wallet) {
wallet = address(new UserWallet(this));
LogNewWallet(wallet);
}
function halt() onlyAdmins {
halted = true;
}
function start() onlyOwner {
halted = false;
}
address public defaultSweeper = address(new DefaultSweeper(this));
mapping (address => address) sweepers;
function addSweeper(address _token, address _sweeper) onlyOwner {
sweepers[_token] = _sweeper;
}
function sweeperOf(address _token) returns (address) {
address sweeper = sweepers[_token];
if (sweeper == 0) sweeper = defaultSweeper;
return sweeper;
}
function logSweep(address from, address to, address token, uint amount) {
LogSweep(from, to, token, amount);
}
}
|
[{"constant":false,"inputs":[{"name":"_token","type":"address"},{"name":"_amount","type":"uint256"}],"name":"sweep","outputs":[{"name":"","type":"bool"}],"payable":false,"type":"function"},{"constant":false,"inputs":[{"name":"_from","type":"address"},{"name":"_value","type":"uint256"},{"name":"_data","type":"bytes"}],"name":"tokenFallback","outputs":[],"payable":false,"type":"function"},{"inputs":[{"name":"_sweeperlist","type":"address"}],"payable":false,"type":"constructor"},{"payable":true,"type":"fallback"}]
|
v0.4.11+commit.68ef5810
| true
| 200
|
000000000000000000000000a3C1E324CA1ce40db73eD6026c4A177F099B5770
|
Default
| false
|
bzzr://4cdd69fdcf3cf6cbee9677fe380fa5f044048aa9e060ec5619a21ca5a5bd4cd1
|
|||
UserWallet
|
0x51664e573049ab1ddbc2dc34f5b4fc290151cdb4
|
Solidity
|
pragma solidity ^0.4.24;
contract AbstractSweeper {
function sweepAll(address token) public returns (bool);
function() public { revert(); }
Controller controller;
constructor(address _controller) public {
controller = Controller(_controller);
}
modifier canSweep() {
if(msg.sender != controller.authorizedCaller() && msg.sender != controller.owner()){ revert(); }
if(controller.halted()){ revert(); }
_;
}
}
contract Token {
function balanceOf(address a) public pure returns (uint) {
(a);
return 0;
}
function transfer(address a, uint val) public pure returns (bool) {
(a);
(val);
return false;
}
}
contract DefaultSweeper is AbstractSweeper {
constructor(address controller) AbstractSweeper(controller) public { }
function sweepAll(address _token) public canSweep returns (bool) {
bool success = false;
address destination = controller.destination();
if(_token != address(0)){
Token token = Token(_token);
success = token.transfer(destination, token.balanceOf(this));
}else{
success = destination.send(address(this).balance);
}
return success;
}
}
contract UserWallet {
AbstractSweeperList sweeperList;
constructor(address _sweeperlist) public {
sweeperList = AbstractSweeperList(_sweeperlist);
}
function() public payable { }
function tokenFallback(address _from, uint _value, bytes _data) public pure {
(_from);
(_value);
(_data);
}
function sweepAll(address _token) public returns (bool) {
return sweeperList.sweeperOf(_token).delegatecall(msg.data);
}
}
contract AbstractSweeperList {
function sweeperOf(address _token) public returns (address);
}
contract Controller is AbstractSweeperList {
address public owner;
address public authorizedCaller;
address public destination;
bool public halted;
event NewWalletCreated(address receiver);
modifier onlyOwner() {
if(msg.sender != owner){ revert(); }
_;
}
modifier onlyAuthorizedCaller() {
if(msg.sender != authorizedCaller){ revert(); }
_;
}
modifier onlyAdmins() {
if(msg.sender != authorizedCaller && msg.sender != owner){ revert(); }
_;
}
constructor() public {
owner = msg.sender;
destination = msg.sender;
authorizedCaller = msg.sender;
}
function setAuthorizedCaller(address _newCaller) public onlyOwner {
authorizedCaller = _newCaller;
}
function setDestination(address _dest) public onlyOwner {
destination = _dest;
}
function setOwner(address _owner) public onlyOwner {
owner = _owner;
}
function newWallet() public onlyAdmins returns (address wallet) {
wallet = address(new UserWallet(this));
emit NewWalletCreated(wallet);
}
function halt() public onlyAdmins {
halted = true;
}
function start() public onlyOwner {
halted = false;
}
address public defaultSweeper = address(new DefaultSweeper(this));
mapping (address => address) sweepers;
function addSweeper(address _token, address _sweeper) public onlyOwner {
sweepers[_token] = _sweeper;
}
function sweeperOf(address _token) public returns (address) {
address sweeper = sweepers[_token];
if(sweeper == 0){ sweeper = defaultSweeper; }
return sweeper;
}
}
|
[{"constant":true,"inputs":[{"name":"_from","type":"address"},{"name":"_value","type":"uint256"},{"name":"_data","type":"bytes"}],"name":"tokenFallback","outputs":[],"payable":false,"stateMutability":"pure","type":"function"},{"constant":false,"inputs":[{"name":"_token","type":"address"}],"name":"sweepAll","outputs":[{"name":"","type":"bool"}],"payable":false,"stateMutability":"nonpayable","type":"function"},{"inputs":[{"name":"_sweeperlist","type":"address"}],"payable":false,"stateMutability":"nonpayable","type":"constructor"},{"payable":true,"stateMutability":"payable","type":"fallback"}]
|
v0.4.24+commit.e67f0147
| true
| 200
|
0000000000000000000000007142eb34d2220152dedc5868745079bc6ffa0fdd
|
Default
|
None
| false
|
bzzr://ec90d4e55fb69f839fa555767145d6ac7a8f1aa98ed098b09c220c4a34f02ba1
|
||
Forwarder
|
0x5ce5038a03128f48828f1edab17d35b2de6b55ea
|
Solidity
|
pragma solidity 0.7.5;
/*
The MIT License (MIT)
Copyright (c) 2018 Murray Software, LLC.
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.
*/
//solhint-disable max-line-length
//solhint-disable no-inline-assembly
contract CloneFactory {
function createClone(address target, bytes32 salt)
internal
returns (address payable result)
{
bytes20 targetBytes = bytes20(target);
assembly {
// load the next free memory slot as a place to store the clone contract data
let clone := mload(0x40)
// The bytecode block below is responsible for contract initialization
// during deployment, it is worth noting the proxied contract constructor will not be called during
// the cloning procedure and that is why an initialization function needs to be called after the
// clone is created
mstore(
clone,
0x3d602d80600a3d3981f3363d3d373d3d3d363d73000000000000000000000000
)
// This stores the address location of the implementation contract
// so that the proxy knows where to delegate call logic to
mstore(add(clone, 0x14), targetBytes)
// The bytecode block is the actual code that is deployed for each clone created.
// It forwards all calls to the already deployed implementation via a delegatecall
mstore(
add(clone, 0x28),
0x5af43d82803e903d91602b57fd5bf30000000000000000000000000000000000
)
// deploy the contract using the CREATE2 opcode
// this deploys the minimal proxy defined above, which will proxy all
// calls to use the logic defined in the implementation contract `target`
result := create2(0, clone, 0x37, salt)
}
}
function isClone(address target, address query)
internal
view
returns (bool result)
{
bytes20 targetBytes = bytes20(target);
assembly {
// load the next free memory slot as a place to store the comparison clone
let clone := mload(0x40)
// The next three lines store the expected bytecode for a miniml proxy
// that targets `target` as its implementation contract
mstore(
clone,
0x363d3d373d3d3d363d7300000000000000000000000000000000000000000000
)
mstore(add(clone, 0xa), targetBytes)
mstore(
add(clone, 0x1e),
0x5af43d82803e903d91602b57fd5bf30000000000000000000000000000000000
)
// the next two lines store the bytecode of the contract that we are checking in memory
let other := add(clone, 0x40)
extcodecopy(query, other, 0, 0x2d)
// Check if the expected bytecode equals the actual bytecode and return the result
result := and(
eq(mload(clone), mload(other)),
eq(mload(add(clone, 0xd)), mload(add(other, 0xd)))
)
}
}
}
/**
* Contract that exposes the needed erc20 token functions
*/
abstract contract ERC20Interface {
// Send _value amount of tokens to address _to
function transfer(address _to, uint256 _value)
public
virtual
returns (bool success);
// Get the account balance of another account with address _owner
function balanceOf(address _owner)
public
virtual
view
returns (uint256 balance);
}
// helper methods for interacting with ERC20 tokens and sending ETH that do not consistently return true/false
library TransferHelper {
function safeApprove(
address token,
address to,
uint256 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::safeApprove: approve failed'
);
}
function safeTransfer(
address token,
address to,
uint256 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::safeTransfer: transfer failed'
);
}
function safeTransferFrom(
address token,
address from,
address to,
uint256 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::transferFrom: transferFrom failed'
);
}
function safeTransferETH(address to, uint256 value) internal {
(bool success, ) = to.call{value: value}(new bytes(0));
require(success, 'TransferHelper::safeTransferETH: ETH transfer failed');
}
}
/**
* Contract that will forward any incoming Ether to the creator of the contract
*
*/
contract Forwarder {
// Address to which any funds sent to this contract will be forwarded
address public parentAddress;
event ForwarderDeposited(address from, uint256 value, bytes data);
/**
* Initialize the contract, and sets the destination address to that of the creator
*/
function init(address _parentAddress) external onlyUninitialized {
parentAddress = _parentAddress;
uint256 value = address(this).balance;
if (value == 0) {
return;
}
(bool success, ) = parentAddress.call{ value: value }('');
require(success, 'Flush failed');
// NOTE: since we are forwarding on initialization,
// we don't have the context of the original sender.
// We still emit an event about the forwarding but set
// the sender to the forwarder itself
emit ForwarderDeposited(address(this), value, msg.data);
}
/**
* Modifier that will execute internal code block only if the sender is the parent address
*/
modifier onlyParent {
require(msg.sender == parentAddress, 'Only Parent');
_;
}
/**
* Modifier that will execute internal code block only if the contract has not been initialized yet
*/
modifier onlyUninitialized {
require(parentAddress == address(0x0), 'Already initialized');
_;
}
/**
* Default function; Gets called when data is sent but does not match any other function
*/
fallback() external payable {
flush();
}
/**
* Default function; Gets called when Ether is deposited with no data, and forwards it to the parent address
*/
receive() external payable {
flush();
}
/**
* Execute a token transfer of the full balance from the forwarder token to the parent address
* @param tokenContractAddress the address of the erc20 token contract
*/
function flushTokens(address tokenContractAddress) external onlyParent {
ERC20Interface instance = ERC20Interface(tokenContractAddress);
address forwarderAddress = address(this);
uint256 forwarderBalance = instance.balanceOf(forwarderAddress);
if (forwarderBalance == 0) {
return;
}
TransferHelper.safeTransfer(
tokenContractAddress,
parentAddress,
forwarderBalance
);
}
/**
* Flush the entire balance of the contract to the parent address.
*/
function flush() public {
uint256 value = address(this).balance;
if (value == 0) {
return;
}
(bool success, ) = parentAddress.call{ value: value }('');
require(success, 'Flush failed');
emit ForwarderDeposited(msg.sender, value, msg.data);
}
}
contract ForwarderFactory is CloneFactory {
address public implementationAddress;
event ForwarderCreated(address newForwarderAddress, address parentAddress);
constructor(address _implementationAddress) {
implementationAddress = _implementationAddress;
}
function createForwarder(address parent, bytes32 salt) external {
// include the signers in the salt so any contract deployed to a given address must have the same signers
bytes32 finalSalt = keccak256(abi.encodePacked(parent, salt));
address payable clone = createClone(implementationAddress, finalSalt);
Forwarder(clone).init(parent);
emit ForwarderCreated(clone, parent);
}
}
|
[{"anonymous":false,"inputs":[{"indexed":false,"internalType":"address","name":"from","type":"address"},{"indexed":false,"internalType":"uint256","name":"value","type":"uint256"},{"indexed":false,"internalType":"bytes","name":"data","type":"bytes"}],"name":"ForwarderDeposited","type":"event"},{"stateMutability":"payable","type":"fallback"},{"inputs":[],"name":"flush","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"address","name":"tokenContractAddress","type":"address"}],"name":"flushTokens","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"address","name":"_parentAddress","type":"address"}],"name":"init","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[],"name":"parentAddress","outputs":[{"internalType":"address","name":"","type":"address"}],"stateMutability":"view","type":"function"},{"stateMutability":"payable","type":"receive"}]
|
v0.7.5+commit.eb77ed08
| false
| 200
|
Default
|
Apache-2.0
| false
|
ipfs://934a7b5f246917d20f5e049b9344e4f3d923110c9d150ea2a4118848dd414bc3
|
|||
Forwarder
|
0x9df3e9ed5a4ba68d625247800f6c8778632dbd3e
|
Solidity
|
pragma solidity 0.7.5;
/*
The MIT License (MIT)
Copyright (c) 2018 Murray Software, LLC.
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.
*/
//solhint-disable max-line-length
//solhint-disable no-inline-assembly
contract CloneFactory {
function createClone(address target, bytes32 salt)
internal
returns (address payable result)
{
bytes20 targetBytes = bytes20(target);
assembly {
// load the next free memory slot as a place to store the clone contract data
let clone := mload(0x40)
// The bytecode block below is responsible for contract initialization
// during deployment, it is worth noting the proxied contract constructor will not be called during
// the cloning procedure and that is why an initialization function needs to be called after the
// clone is created
mstore(
clone,
0x3d602d80600a3d3981f3363d3d373d3d3d363d73000000000000000000000000
)
// This stores the address location of the implementation contract
// so that the proxy knows where to delegate call logic to
mstore(add(clone, 0x14), targetBytes)
// The bytecode block is the actual code that is deployed for each clone created.
// It forwards all calls to the already deployed implementation via a delegatecall
mstore(
add(clone, 0x28),
0x5af43d82803e903d91602b57fd5bf30000000000000000000000000000000000
)
// deploy the contract using the CREATE2 opcode
// this deploys the minimal proxy defined above, which will proxy all
// calls to use the logic defined in the implementation contract `target`
result := create2(0, clone, 0x37, salt)
}
}
function isClone(address target, address query)
internal
view
returns (bool result)
{
bytes20 targetBytes = bytes20(target);
assembly {
// load the next free memory slot as a place to store the comparison clone
let clone := mload(0x40)
// The next three lines store the expected bytecode for a miniml proxy
// that targets `target` as its implementation contract
mstore(
clone,
0x363d3d373d3d3d363d7300000000000000000000000000000000000000000000
)
mstore(add(clone, 0xa), targetBytes)
mstore(
add(clone, 0x1e),
0x5af43d82803e903d91602b57fd5bf30000000000000000000000000000000000
)
// the next two lines store the bytecode of the contract that we are checking in memory
let other := add(clone, 0x40)
extcodecopy(query, other, 0, 0x2d)
// Check if the expected bytecode equals the actual bytecode and return the result
result := and(
eq(mload(clone), mload(other)),
eq(mload(add(clone, 0xd)), mload(add(other, 0xd)))
)
}
}
}
/**
* Contract that exposes the needed erc20 token functions
*/
abstract contract ERC20Interface {
// Send _value amount of tokens to address _to
function transfer(address _to, uint256 _value)
public
virtual
returns (bool success);
// Get the account balance of another account with address _owner
function balanceOf(address _owner)
public
virtual
view
returns (uint256 balance);
}
// helper methods for interacting with ERC20 tokens and sending ETH that do not consistently return true/false
library TransferHelper {
function safeApprove(
address token,
address to,
uint256 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::safeApprove: approve failed'
);
}
function safeTransfer(
address token,
address to,
uint256 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::safeTransfer: transfer failed'
);
}
function safeTransferFrom(
address token,
address from,
address to,
uint256 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::transferFrom: transferFrom failed'
);
}
function safeTransferETH(address to, uint256 value) internal {
(bool success, ) = to.call{value: value}(new bytes(0));
require(success, 'TransferHelper::safeTransferETH: ETH transfer failed');
}
}
/**
* Contract that will forward any incoming Ether to the creator of the contract
*
*/
contract Forwarder {
// Address to which any funds sent to this contract will be forwarded
address public parentAddress;
event ForwarderDeposited(address from, uint256 value, bytes data);
/**
* Initialize the contract, and sets the destination address to that of the creator
*/
function init(address _parentAddress) external onlyUninitialized {
parentAddress = _parentAddress;
uint256 value = address(this).balance;
if (value == 0) {
return;
}
(bool success, ) = parentAddress.call{ value: value }('');
require(success, 'Flush failed');
// NOTE: since we are forwarding on initialization,
// we don't have the context of the original sender.
// We still emit an event about the forwarding but set
// the sender to the forwarder itself
emit ForwarderDeposited(address(this), value, msg.data);
}
/**
* Modifier that will execute internal code block only if the sender is the parent address
*/
modifier onlyParent {
require(msg.sender == parentAddress, 'Only Parent');
_;
}
/**
* Modifier that will execute internal code block only if the contract has not been initialized yet
*/
modifier onlyUninitialized {
require(parentAddress == address(0x0), 'Already initialized');
_;
}
/**
* Default function; Gets called when data is sent but does not match any other function
*/
fallback() external payable {
flush();
}
/**
* Default function; Gets called when Ether is deposited with no data, and forwards it to the parent address
*/
receive() external payable {
flush();
}
/**
* Execute a token transfer of the full balance from the forwarder token to the parent address
* @param tokenContractAddress the address of the erc20 token contract
*/
function flushTokens(address tokenContractAddress) external onlyParent {
ERC20Interface instance = ERC20Interface(tokenContractAddress);
address forwarderAddress = address(this);
uint256 forwarderBalance = instance.balanceOf(forwarderAddress);
if (forwarderBalance == 0) {
return;
}
TransferHelper.safeTransfer(
tokenContractAddress,
parentAddress,
forwarderBalance
);
}
/**
* Flush the entire balance of the contract to the parent address.
*/
function flush() public {
uint256 value = address(this).balance;
if (value == 0) {
return;
}
(bool success, ) = parentAddress.call{ value: value }('');
require(success, 'Flush failed');
emit ForwarderDeposited(msg.sender, value, msg.data);
}
}
contract ForwarderFactory is CloneFactory {
address public implementationAddress;
event ForwarderCreated(address newForwarderAddress, address parentAddress);
constructor(address _implementationAddress) {
implementationAddress = _implementationAddress;
}
function createForwarder(address parent, bytes32 salt) external {
// include the signers in the salt so any contract deployed to a given address must have the same signers
bytes32 finalSalt = keccak256(abi.encodePacked(parent, salt));
address payable clone = createClone(implementationAddress, finalSalt);
Forwarder(clone).init(parent);
emit ForwarderCreated(clone, parent);
}
}
|
[{"anonymous":false,"inputs":[{"indexed":false,"internalType":"address","name":"from","type":"address"},{"indexed":false,"internalType":"uint256","name":"value","type":"uint256"},{"indexed":false,"internalType":"bytes","name":"data","type":"bytes"}],"name":"ForwarderDeposited","type":"event"},{"stateMutability":"payable","type":"fallback"},{"inputs":[],"name":"flush","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"address","name":"tokenContractAddress","type":"address"}],"name":"flushTokens","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"address","name":"_parentAddress","type":"address"}],"name":"init","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[],"name":"parentAddress","outputs":[{"internalType":"address","name":"","type":"address"}],"stateMutability":"view","type":"function"},{"stateMutability":"payable","type":"receive"}]
|
v0.7.5+commit.eb77ed08
| false
| 200
|
Default
|
Apache-2.0
| false
|
ipfs://934a7b5f246917d20f5e049b9344e4f3d923110c9d150ea2a4118848dd414bc3
|
|||
Forwarder
|
0xeb359feadbda935d58237952552087140b209a1a
|
Solidity
|
pragma solidity ^0.4.14;
/**
* Contract that exposes the needed erc20 token functions
*/
contract ERC20Interface {
// Send _value amount of tokens to address _to
function transfer(address _to, uint256 _value) returns (bool success);
// Get the account balance of another account with address _owner
function balanceOf(address _owner) constant returns (uint256 balance);
}
/**
* Contract that will forward any incoming Ether to its creator
*/
contract Forwarder {
// Address to which any funds sent to this contract will be forwarded
address public parentAddress;
event ForwarderDeposited(address from, uint value, bytes data);
event TokensFlushed(
address tokenContractAddress, // The contract address of the token
uint value // Amount of token sent
);
/**
* Create the contract, and set the destination address to that of the creator
*/
function Forwarder() {
parentAddress = msg.sender;
}
/**
* Modifier that will execute internal code block only if the sender is a parent of the forwarder contract
*/
modifier onlyParent {
if (msg.sender != parentAddress) {
throw;
}
_;
}
/**
* Default function; Gets called when Ether is deposited, and forwards it to the destination address
*/
function() payable {
if (!parentAddress.call.value(msg.value)(msg.data))
throw;
// Fire off the deposited event if we can forward it
ForwarderDeposited(msg.sender, msg.value, msg.data);
}
/**
* Execute a token transfer of the full balance from the forwarder token to the main wallet contract
* @param tokenContractAddress the address of the erc20 token contract
*/
function flushTokens(address tokenContractAddress) onlyParent {
ERC20Interface instance = ERC20Interface(tokenContractAddress);
var forwarderAddress = address(this);
var forwarderBalance = instance.balanceOf(forwarderAddress);
if (forwarderBalance == 0) {
return;
}
if (!instance.transfer(parentAddress, forwarderBalance)) {
throw;
}
TokensFlushed(tokenContractAddress, forwarderBalance);
}
/**
* It is possible that funds were sent to this address before the contract was deployed.
* We can flush those funds to the destination address.
*/
function flush() {
if (!parentAddress.call.value(this.balance)())
throw;
}
}
/**
* Basic multi-signer wallet designed for use in a co-signing environment where 2 signatures are required to move funds.
* Typically used in a 2-of-3 signing configuration. Uses ecrecover to allow for 2 signatures in a single transaction.
*/
contract WalletSimple {
// Events
event Deposited(address from, uint value, bytes data);
event SafeModeActivated(address msgSender);
event Transacted(
address msgSender, // Address of the sender of the message initiating the transaction
address otherSigner, // Address of the signer (second signature) used to initiate the transaction
bytes32 operation, // Operation hash (sha3 of toAddress, value, data, expireTime, sequenceId)
address toAddress, // The address the transaction was sent to
uint value, // Amount of Wei sent to the address
bytes data // Data sent when invoking the transaction
);
event TokenTransacted(
address msgSender, // Address of the sender of the message initiating the transaction
address otherSigner, // Address of the signer (second signature) used to initiate the transaction
bytes32 operation, // Operation hash (sha3 of toAddress, value, tokenContractAddress, expireTime, sequenceId)
address toAddress, // The address the transaction was sent to
uint value, // Amount of token sent
address tokenContractAddress // The contract address of the token
);
// Public fields
address[] public signers; // The addresses that can co-sign transactions on the wallet
bool public safeMode = false; // When active, wallet may only send to signer addresses
// Internal fields
uint constant SEQUENCE_ID_WINDOW_SIZE = 10;
uint[10] recentSequenceIds;
/**
* Modifier that will execute internal code block only if the sender is an authorized signer on this wallet
*/
modifier onlysigner {
if (!isSigner(msg.sender)) {
throw;
}
_;
}
/**
* Set up a simple multi-sig wallet by specifying the signers allowed to be used on this wallet.
* 2 signers will be required to send a transaction from this wallet.
* Note: The sender is NOT automatically added to the list of signers.
* Signers CANNOT be changed once they are set
*
* @param allowedSigners An array of signers on the wallet
*/
function WalletSimple(address[] allowedSigners) {
if (allowedSigners.length != 3) {
// Invalid number of signers
throw;
}
signers = allowedSigners;
}
/**
* Gets called when a transaction is received without calling a method
*/
function() payable {
if (msg.value > 0) {
// Fire deposited event if we are receiving funds
Deposited(msg.sender, msg.value, msg.data);
}
}
/**
* Create a new contract (and also address) that forwards funds to this contract
* returns address of newly created forwarder address
*/
function createForwarder() onlysigner returns (address) {
return new Forwarder();
}
/**
* Execute a multi-signature transaction from this wallet using 2 signers: one from msg.sender and the other from ecrecover.
* The signature is a signed form (using eth.sign) of tightly packed toAddress, value, data, expireTime and sequenceId
* Sequence IDs are numbers starting from 1. They are used to prevent replay attacks and may not be repeated.
*
* @param toAddress the destination address to send an outgoing transaction
* @param value the amount in Wei to be sent
* @param data the data to send to the toAddress when invoking the transaction
* @param expireTime the number of seconds since 1970 for which this transaction is valid
* @param sequenceId the unique sequence id obtainable from getNextSequenceId
* @param signature the result of eth.sign on the operationHash sha3(toAddress, value, data, expireTime, sequenceId)
*/
function sendMultiSig(address toAddress, uint value, bytes data, uint expireTime, uint sequenceId, bytes signature) onlysigner {
// Verify the other signer
var operationHash = sha3("ETHER", toAddress, value, data, expireTime, sequenceId);
var otherSigner = verifyMultiSig(toAddress, operationHash, signature, expireTime, sequenceId);
// Success, send the transaction
if (!(toAddress.call.value(value)(data))) {
// Failed executing transaction
throw;
}
Transacted(msg.sender, otherSigner, operationHash, toAddress, value, data);
}
/**
* Execute a multi-signature token transfer from this wallet using 2 signers: one from msg.sender and the other from ecrecover.
* The signature is a signed form (using eth.sign) of tightly packed toAddress, value, tokenContractAddress, expireTime and sequenceId
* Sequence IDs are numbers starting from 1. They are used to prevent replay attacks and may not be repeated.
*
* @param toAddress the destination address to send an outgoing transaction
* @param value the amount in tokens to be sent
* @param tokenContractAddress the address of the erc20 token contract
* @param expireTime the number of seconds since 1970 for which this transaction is valid
* @param sequenceId the unique sequence id obtainable from getNextSequenceId
* @param signature the result of eth.sign on the operationHash sha3(toAddress, value, tokenContractAddress, expireTime, sequenceId)
*/
function sendMultiSigToken(address toAddress, uint value, address tokenContractAddress, uint expireTime, uint sequenceId, bytes signature) onlysigner {
// Verify the other signer
var operationHash = sha3("ERC20", toAddress, value, tokenContractAddress, expireTime, sequenceId);
var otherSigner = verifyMultiSig(toAddress, operationHash, signature, expireTime, sequenceId);
ERC20Interface instance = ERC20Interface(tokenContractAddress);
if (!instance.transfer(toAddress, value)) {
throw;
}
TokenTransacted(msg.sender, otherSigner, operationHash, toAddress, value, tokenContractAddress);
}
/**
* Execute a token flush from one of the forwarder addresses. This transfer needs only a single signature and can be done by any signer
*
* @param forwarderAddress the address of the forwarder address to flush the tokens from
* @param tokenContractAddress the address of the erc20 token contract
*/
function flushForwarderTokens(address forwarderAddress, address tokenContractAddress) onlysigner {
Forwarder forwarder = Forwarder(forwarderAddress);
forwarder.flushTokens(tokenContractAddress);
}
/**
* Do common multisig verification for both eth sends and erc20token transfers
*
* @param toAddress the destination address to send an outgoing transaction
* @param operationHash the sha3 of the toAddress, value, data/tokenContractAddress and expireTime
* @param signature the tightly packed signature of r, s, and v as an array of 65 bytes (returned by eth.sign)
* @param expireTime the number of seconds since 1970 for which this transaction is valid
* @param sequenceId the unique sequence id obtainable from getNextSequenceId
* returns address of the address to send tokens or eth to
*/
function verifyMultiSig(address toAddress, bytes32 operationHash, bytes signature, uint expireTime, uint sequenceId) private returns (address) {
var otherSigner = recoverAddressFromSignature(operationHash, signature);
// Verify if we are in safe mode. In safe mode, the wallet can only send to signers
if (safeMode && !isSigner(toAddress)) {
// We are in safe mode and the toAddress is not a signer. Disallow!
throw;
}
// Verify that the transaction has not expired
if (expireTime < block.timestamp) {
// Transaction expired
throw;
}
// Try to insert the sequence ID. Will throw if the sequence id was invalid
tryInsertSequenceId(sequenceId);
if (!isSigner(otherSigner)) {
// Other signer not on this wallet or operation does not match arguments
throw;
}
if (otherSigner == msg.sender) {
// Cannot approve own transaction
throw;
}
return otherSigner;
}
/**
* Irrevocably puts contract into safe mode. When in this mode, transactions may only be sent to signing addresses.
*/
function activateSafeMode() onlysigner {
safeMode = true;
SafeModeActivated(msg.sender);
}
/**
* Determine if an address is a signer on this wallet
* @param signer address to check
* returns boolean indicating whether address is signer or not
*/
function isSigner(address signer) returns (bool) {
// Iterate through all signers on the wallet and
for (uint i = 0; i < signers.length; i++) {
if (signers[i] == signer) {
return true;
}
}
return false;
}
/**
* Gets the second signer's address using ecrecover
* @param operationHash the sha3 of the toAddress, value, data/tokenContractAddress and expireTime
* @param signature the tightly packed signature of r, s, and v as an array of 65 bytes (returned by eth.sign)
* returns address recovered from the signature
*/
function recoverAddressFromSignature(bytes32 operationHash, bytes signature) private returns (address) {
if (signature.length != 65) {
throw;
}
// We need to unpack the signature, which is given as an array of 65 bytes (from eth.sign)
bytes32 r;
bytes32 s;
uint8 v;
assembly {
r := mload(add(signature, 32))
s := mload(add(signature, 64))
v := and(mload(add(signature, 65)), 255)
}
if (v < 27) {
v += 27; // Ethereum versions are 27 or 28 as opposed to 0 or 1 which is submitted by some signing libs
}
return ecrecover(operationHash, v, r, s);
}
/**
* Verify that the sequence id has not been used before and inserts it. Throws if the sequence ID was not accepted.
* We collect a window of up to 10 recent sequence ids, and allow any sequence id that is not in the window and
* greater than the minimum element in the window.
* @param sequenceId to insert into array of stored ids
*/
function tryInsertSequenceId(uint sequenceId) onlysigner private {
// Keep a pointer to the lowest value element in the window
uint lowestValueIndex = 0;
for (uint i = 0; i < SEQUENCE_ID_WINDOW_SIZE; i++) {
if (recentSequenceIds[i] == sequenceId) {
// This sequence ID has been used before. Disallow!
throw;
}
if (recentSequenceIds[i] < recentSequenceIds[lowestValueIndex]) {
lowestValueIndex = i;
}
}
if (sequenceId < recentSequenceIds[lowestValueIndex]) {
// The sequence ID being used is lower than the lowest value in the window
// so we cannot accept it as it may have been used before
throw;
}
if (sequenceId > (recentSequenceIds[lowestValueIndex] + 10000)) {
// Block sequence IDs which are much higher than the lowest value
// This prevents people blocking the contract by using very large sequence IDs quickly
throw;
}
recentSequenceIds[lowestValueIndex] = sequenceId;
}
/**
* Gets the next available sequence ID for signing when using executeAndConfirm
* returns the sequenceId one higher than the highest currently stored
*/
function getNextSequenceId() returns (uint) {
uint highestSequenceId = 0;
for (uint i = 0; i < SEQUENCE_ID_WINDOW_SIZE; i++) {
if (recentSequenceIds[i] > highestSequenceId) {
highestSequenceId = recentSequenceIds[i];
}
}
return highestSequenceId + 1;
}
}
|
[{"constant":true,"inputs":[],"name":"parentAddress","outputs":[{"name":"","type":"address"}],"payable":false,"type":"function"},{"constant":false,"inputs":[{"name":"tokenContractAddress","type":"address"}],"name":"flushTokens","outputs":[],"payable":false,"type":"function"},{"constant":false,"inputs":[],"name":"flush","outputs":[],"payable":false,"type":"function"},{"inputs":[],"payable":false,"type":"constructor"},{"payable":true,"type":"fallback"},{"anonymous":false,"inputs":[{"indexed":false,"name":"from","type":"address"},{"indexed":false,"name":"value","type":"uint256"},{"indexed":false,"name":"data","type":"bytes"}],"name":"ForwarderDeposited","type":"event"},{"anonymous":false,"inputs":[{"indexed":false,"name":"tokenContractAddress","type":"address"},{"indexed":false,"name":"value","type":"uint256"}],"name":"TokensFlushed","type":"event"}]
|
v0.4.16-nightly.2017.8.11+commit.c84de7fa
| true
| 200
|
Default
| false
|
bzzr://d0f8838ba17108a895d34ae8ef3bff4e0dc9d639c3c51921fee1d17eaa803721
|
||||
OwnableDelegateProxy
|
0x3c042f7023705cb28d76034564370e7456aab002
|
Solidity
|
contract OwnedUpgradeabilityStorage {
// Current implementation
address internal _implementation;
// Owner of the contract
address private _upgradeabilityOwner;
/**
* @dev Tells the address of the owner
* @return the address of the owner
*/
function upgradeabilityOwner() public view returns (address) {
return _upgradeabilityOwner;
}
/**
* @dev Sets the address of the owner
*/
function setUpgradeabilityOwner(address newUpgradeabilityOwner) internal {
_upgradeabilityOwner = newUpgradeabilityOwner;
}
/**
* @dev Tells the address of the current implementation
* @return address of the current implementation
*/
function implementation() public view returns (address) {
return _implementation;
}
/**
* @dev Tells the proxy type (EIP 897)
* @return Proxy type, 2 for forwarding proxy
*/
function proxyType() public pure returns (uint256 proxyTypeId) {
return 2;
}
}
contract Proxy {
/**
* @dev Tells the address of the implementation where every call will be delegated.
* @return address of the implementation to which it will be delegated
*/
function implementation() public view returns (address);
/**
* @dev Tells the type of proxy (EIP 897)
* @return Type of proxy, 2 for upgradeable proxy
*/
function proxyType() public pure returns (uint256 proxyTypeId);
/**
* @dev Fallback function allowing to perform a delegatecall to the given implementation.
* This function will return whatever the implementation call returns
*/
function () payable public {
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 OwnedUpgradeabilityProxy is Proxy, OwnedUpgradeabilityStorage {
/**
* @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);
/**
* @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);
/**
* @dev Upgrades the implementation address
* @param implementation representing the address of the new implementation to be set
*/
function _upgradeTo(address implementation) internal {
require(_implementation != implementation);
_implementation = implementation;
emit Upgraded(implementation);
}
/**
* @dev Throws if called by any account other than the owner.
*/
modifier onlyProxyOwner() {
require(msg.sender == proxyOwner());
_;
}
/**
* @dev Tells the address of the proxy owner
* @return the address of the proxy owner
*/
function proxyOwner() public view returns (address) {
return upgradeabilityOwner();
}
/**
* @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) public onlyProxyOwner {
require(newOwner != address(0));
emit ProxyOwnershipTransferred(proxyOwner(), newOwner);
setUpgradeabilityOwner(newOwner);
}
/**
* @dev Allows the upgradeability owner to upgrade the current implementation of the proxy.
* @param implementation representing the address of the new implementation to be set.
*/
function upgradeTo(address implementation) public onlyProxyOwner {
_upgradeTo(implementation);
}
/**
* @dev Allows the upgradeability owner to upgrade the current implementation of the proxy
* and delegatecall the new implementation for initialization.
* @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 data) payable public onlyProxyOwner {
upgradeTo(implementation);
require(address(this).delegatecall(data));
}
}
contract OwnableDelegateProxy is OwnedUpgradeabilityProxy {
constructor(address owner, address initialImplementation, bytes calldata)
public
{
setUpgradeabilityOwner(owner);
_upgradeTo(initialImplementation);
require(initialImplementation.delegatecall(calldata));
}
}
|
[{"constant":true,"inputs":[],"name":"proxyOwner","outputs":[{"name":"","type":"address"}],"payable":false,"stateMutability":"view","type":"function"},{"constant":false,"inputs":[{"name":"implementation","type":"address"}],"name":"upgradeTo","outputs":[],"payable":false,"stateMutability":"nonpayable","type":"function"},{"constant":true,"inputs":[],"name":"proxyType","outputs":[{"name":"proxyTypeId","type":"uint256"}],"payable":false,"stateMutability":"pure","type":"function"},{"constant":false,"inputs":[{"name":"implementation","type":"address"},{"name":"data","type":"bytes"}],"name":"upgradeToAndCall","outputs":[],"payable":true,"stateMutability":"payable","type":"function"},{"constant":true,"inputs":[],"name":"implementation","outputs":[{"name":"","type":"address"}],"payable":false,"stateMutability":"view","type":"function"},{"constant":true,"inputs":[],"name":"upgradeabilityOwner","outputs":[{"name":"","type":"address"}],"payable":false,"stateMutability":"view","type":"function"},{"constant":false,"inputs":[{"name":"newOwner","type":"address"}],"name":"transferProxyOwnership","outputs":[],"payable":false,"stateMutability":"nonpayable","type":"function"},{"inputs":[{"name":"owner","type":"address"},{"name":"initialImplementation","type":"address"},{"name":"calldata","type":"bytes"}],"payable":false,"stateMutability":"nonpayable","type":"constructor"},{"payable":true,"stateMutability":"payable","type":"fallback"},{"anonymous":false,"inputs":[{"indexed":false,"name":"previousOwner","type":"address"},{"indexed":false,"name":"newOwner","type":"address"}],"name":"ProxyOwnershipTransferred","type":"event"},{"anonymous":false,"inputs":[{"indexed":true,"name":"implementation","type":"address"}],"name":"Upgraded","type":"event"}]
|
v0.4.23+commit.124ca40d
| true
| 200
|
00000000000000000000000074451193ccf4d1c9182c973538d9d2339350ee1a000000000000000000000000f9e266af4bca5890e2781812cc6a6e89495a79f200000000000000000000000000000000000000000000000000000000000000600000000000000000000000000000000000000000000000000000000000000044485cc95500000000000000000000000074451193ccf4d1c9182c973538d9d2339350ee1a000000000000000000000000a5409ec958c83c3f309868babaca7c86dcb077c100000000000000000000000000000000000000000000000000000000
|
Default
|
MIT
| false
|
bzzr://5f26049bbc794226b505f589b2ee1130db54310d79dd8a635c6f6c61e305a777
|
||
Forwarder
|
0x2ab499885b68b753544bb322cb4cc1a49128af38
|
Solidity
|
pragma solidity 0.7.5;
/*
The MIT License (MIT)
Copyright (c) 2018 Murray Software, LLC.
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.
*/
//solhint-disable max-line-length
//solhint-disable no-inline-assembly
contract CloneFactory {
function createClone(address target, bytes32 salt)
internal
returns (address payable result)
{
bytes20 targetBytes = bytes20(target);
assembly {
// load the next free memory slot as a place to store the clone contract data
let clone := mload(0x40)
// The bytecode block below is responsible for contract initialization
// during deployment, it is worth noting the proxied contract constructor will not be called during
// the cloning procedure and that is why an initialization function needs to be called after the
// clone is created
mstore(
clone,
0x3d602d80600a3d3981f3363d3d373d3d3d363d73000000000000000000000000
)
// This stores the address location of the implementation contract
// so that the proxy knows where to delegate call logic to
mstore(add(clone, 0x14), targetBytes)
// The bytecode block is the actual code that is deployed for each clone created.
// It forwards all calls to the already deployed implementation via a delegatecall
mstore(
add(clone, 0x28),
0x5af43d82803e903d91602b57fd5bf30000000000000000000000000000000000
)
// deploy the contract using the CREATE2 opcode
// this deploys the minimal proxy defined above, which will proxy all
// calls to use the logic defined in the implementation contract `target`
result := create2(0, clone, 0x37, salt)
}
}
function isClone(address target, address query)
internal
view
returns (bool result)
{
bytes20 targetBytes = bytes20(target);
assembly {
// load the next free memory slot as a place to store the comparison clone
let clone := mload(0x40)
// The next three lines store the expected bytecode for a miniml proxy
// that targets `target` as its implementation contract
mstore(
clone,
0x363d3d373d3d3d363d7300000000000000000000000000000000000000000000
)
mstore(add(clone, 0xa), targetBytes)
mstore(
add(clone, 0x1e),
0x5af43d82803e903d91602b57fd5bf30000000000000000000000000000000000
)
// the next two lines store the bytecode of the contract that we are checking in memory
let other := add(clone, 0x40)
extcodecopy(query, other, 0, 0x2d)
// Check if the expected bytecode equals the actual bytecode and return the result
result := and(
eq(mload(clone), mload(other)),
eq(mload(add(clone, 0xd)), mload(add(other, 0xd)))
)
}
}
}
/**
* Contract that exposes the needed erc20 token functions
*/
abstract contract ERC20Interface {
// Send _value amount of tokens to address _to
function transfer(address _to, uint256 _value)
public
virtual
returns (bool success);
// Get the account balance of another account with address _owner
function balanceOf(address _owner)
public
virtual
view
returns (uint256 balance);
}
// helper methods for interacting with ERC20 tokens and sending ETH that do not consistently return true/false
library TransferHelper {
function safeApprove(
address token,
address to,
uint256 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::safeApprove: approve failed'
);
}
function safeTransfer(
address token,
address to,
uint256 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::safeTransfer: transfer failed'
);
}
function safeTransferFrom(
address token,
address from,
address to,
uint256 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::transferFrom: transferFrom failed'
);
}
function safeTransferETH(address to, uint256 value) internal {
(bool success, ) = to.call{value: value}(new bytes(0));
require(success, 'TransferHelper::safeTransferETH: ETH transfer failed');
}
}
/**
* Contract that will forward any incoming Ether to the creator of the contract
*
*/
contract Forwarder {
// Address to which any funds sent to this contract will be forwarded
address public parentAddress;
event ForwarderDeposited(address from, uint256 value, bytes data);
/**
* Initialize the contract, and sets the destination address to that of the creator
*/
function init(address _parentAddress) external onlyUninitialized {
parentAddress = _parentAddress;
uint256 value = address(this).balance;
if (value == 0) {
return;
}
(bool success, ) = parentAddress.call{ value: value }('');
require(success, 'Flush failed');
// NOTE: since we are forwarding on initialization,
// we don't have the context of the original sender.
// We still emit an event about the forwarding but set
// the sender to the forwarder itself
emit ForwarderDeposited(address(this), value, msg.data);
}
/**
* Modifier that will execute internal code block only if the sender is the parent address
*/
modifier onlyParent {
require(msg.sender == parentAddress, 'Only Parent');
_;
}
/**
* Modifier that will execute internal code block only if the contract has not been initialized yet
*/
modifier onlyUninitialized {
require(parentAddress == address(0x0), 'Already initialized');
_;
}
/**
* Default function; Gets called when data is sent but does not match any other function
*/
fallback() external payable {
flush();
}
/**
* Default function; Gets called when Ether is deposited with no data, and forwards it to the parent address
*/
receive() external payable {
flush();
}
/**
* Execute a token transfer of the full balance from the forwarder token to the parent address
* @param tokenContractAddress the address of the erc20 token contract
*/
function flushTokens(address tokenContractAddress) external onlyParent {
ERC20Interface instance = ERC20Interface(tokenContractAddress);
address forwarderAddress = address(this);
uint256 forwarderBalance = instance.balanceOf(forwarderAddress);
if (forwarderBalance == 0) {
return;
}
TransferHelper.safeTransfer(
tokenContractAddress,
parentAddress,
forwarderBalance
);
}
/**
* Flush the entire balance of the contract to the parent address.
*/
function flush() public {
uint256 value = address(this).balance;
if (value == 0) {
return;
}
(bool success, ) = parentAddress.call{ value: value }('');
require(success, 'Flush failed');
emit ForwarderDeposited(msg.sender, value, msg.data);
}
}
contract ForwarderFactory is CloneFactory {
address public implementationAddress;
event ForwarderCreated(address newForwarderAddress, address parentAddress);
constructor(address _implementationAddress) {
implementationAddress = _implementationAddress;
}
function createForwarder(address parent, bytes32 salt) external {
// include the signers in the salt so any contract deployed to a given address must have the same signers
bytes32 finalSalt = keccak256(abi.encodePacked(parent, salt));
address payable clone = createClone(implementationAddress, finalSalt);
Forwarder(clone).init(parent);
emit ForwarderCreated(clone, parent);
}
}
|
[{"anonymous":false,"inputs":[{"indexed":false,"internalType":"address","name":"from","type":"address"},{"indexed":false,"internalType":"uint256","name":"value","type":"uint256"},{"indexed":false,"internalType":"bytes","name":"data","type":"bytes"}],"name":"ForwarderDeposited","type":"event"},{"stateMutability":"payable","type":"fallback"},{"inputs":[],"name":"flush","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"address","name":"tokenContractAddress","type":"address"}],"name":"flushTokens","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"address","name":"_parentAddress","type":"address"}],"name":"init","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[],"name":"parentAddress","outputs":[{"internalType":"address","name":"","type":"address"}],"stateMutability":"view","type":"function"},{"stateMutability":"payable","type":"receive"}]
|
v0.7.5+commit.eb77ed08
| false
| 200
|
Default
|
Apache-2.0
| false
|
ipfs://934a7b5f246917d20f5e049b9344e4f3d923110c9d150ea2a4118848dd414bc3
|
|||
UserWallet
|
0x61b5872a0b67a28cb9444cf66c5a5cd3f34033d9
|
Solidity
|
pragma solidity ^0.4.10;
// Copyright 2017 Bittrex
contract AbstractSweeper {
function sweep(address token, uint amount) returns (bool);
function () { throw; }
Controller controller;
function AbstractSweeper(address _controller) {
controller = Controller(_controller);
}
modifier canSweep() {
if (msg.sender != controller.authorizedCaller() && msg.sender != controller.owner()) throw;
if (controller.halted()) throw;
_;
}
}
contract Token {
function balanceOf(address a) returns (uint) {
(a);
return 0;
}
function transfer(address a, uint val) returns (bool) {
(a);
(val);
return false;
}
}
contract DefaultSweeper is AbstractSweeper {
function DefaultSweeper(address controller)
AbstractSweeper(controller) {}
function sweep(address _token, uint _amount)
canSweep
returns (bool) {
bool success = false;
address destination = controller.destination();
if (_token != address(0)) {
Token token = Token(_token);
uint amount = _amount;
if (amount > token.balanceOf(this)) {
return false;
}
success = token.transfer(destination, amount);
}
else {
uint amountInWei = _amount;
if (amountInWei > this.balance) {
return false;
}
success = destination.send(amountInWei);
}
if (success) {
controller.logSweep(this, destination, _token, _amount);
}
return success;
}
}
contract UserWallet {
AbstractSweeperList sweeperList;
function UserWallet(address _sweeperlist) {
sweeperList = AbstractSweeperList(_sweeperlist);
}
function () public payable { }
function tokenFallback(address _from, uint _value, bytes _data) {
(_from);
(_value);
(_data);
}
function sweep(address _token, uint _amount)
returns (bool) {
(_amount);
return sweeperList.sweeperOf(_token).delegatecall(msg.data);
}
}
contract AbstractSweeperList {
function sweeperOf(address _token) returns (address);
}
contract Controller is AbstractSweeperList {
address public owner;
address public authorizedCaller;
address public destination;
bool public halted;
event LogNewWallet(address receiver);
event LogSweep(address indexed from, address indexed to, address indexed token, uint amount);
modifier onlyOwner() {
if (msg.sender != owner) throw;
_;
}
modifier onlyAuthorizedCaller() {
if (msg.sender != authorizedCaller) throw;
_;
}
modifier onlyAdmins() {
if (msg.sender != authorizedCaller && msg.sender != owner) throw;
_;
}
function Controller()
{
owner = msg.sender;
destination = msg.sender;
authorizedCaller = msg.sender;
}
function changeAuthorizedCaller(address _newCaller) onlyOwner {
authorizedCaller = _newCaller;
}
function changeDestination(address _dest) onlyOwner {
destination = _dest;
}
function changeOwner(address _owner) onlyOwner {
owner = _owner;
}
function makeWallet() onlyAdmins returns (address wallet) {
wallet = address(new UserWallet(this));
LogNewWallet(wallet);
}
function halt() onlyAdmins {
halted = true;
}
function start() onlyOwner {
halted = false;
}
address public defaultSweeper = address(new DefaultSweeper(this));
mapping (address => address) sweepers;
function addSweeper(address _token, address _sweeper) onlyOwner {
sweepers[_token] = _sweeper;
}
function sweeperOf(address _token) returns (address) {
address sweeper = sweepers[_token];
if (sweeper == 0) sweeper = defaultSweeper;
return sweeper;
}
function logSweep(address from, address to, address token, uint amount) {
LogSweep(from, to, token, amount);
}
}
|
[{"constant":false,"inputs":[{"name":"_token","type":"address"},{"name":"_amount","type":"uint256"}],"name":"sweep","outputs":[{"name":"","type":"bool"}],"payable":false,"type":"function"},{"constant":false,"inputs":[{"name":"_from","type":"address"},{"name":"_value","type":"uint256"},{"name":"_data","type":"bytes"}],"name":"tokenFallback","outputs":[],"payable":false,"type":"function"},{"inputs":[{"name":"_sweeperlist","type":"address"}],"payable":false,"type":"constructor"},{"payable":true,"type":"fallback"}]
|
v0.4.11+commit.68ef5810
| true
| 200
|
000000000000000000000000a3C1E324CA1ce40db73eD6026c4A177F099B5770
|
Default
| false
|
bzzr://4cdd69fdcf3cf6cbee9677fe380fa5f044048aa9e060ec5619a21ca5a5bd4cd1
|
|||
UserWallet
|
0x2b85885af64bbf20473dfeceec15021eed2f7485
|
Solidity
|
pragma solidity ^0.4.10;
// Copyright 2017 Bittrex
contract AbstractSweeper {
function sweep(address token, uint amount) returns (bool);
function () { throw; }
Controller controller;
function AbstractSweeper(address _controller) {
controller = Controller(_controller);
}
modifier canSweep() {
if (msg.sender != controller.authorizedCaller() && msg.sender != controller.owner()) throw;
if (controller.halted()) throw;
_;
}
}
contract Token {
function balanceOf(address a) returns (uint) {
(a);
return 0;
}
function transfer(address a, uint val) returns (bool) {
(a);
(val);
return false;
}
}
contract DefaultSweeper is AbstractSweeper {
function DefaultSweeper(address controller)
AbstractSweeper(controller) {}
function sweep(address _token, uint _amount)
canSweep
returns (bool) {
bool success = false;
address destination = controller.destination();
if (_token != address(0)) {
Token token = Token(_token);
uint amount = _amount;
if (amount > token.balanceOf(this)) {
return false;
}
success = token.transfer(destination, amount);
}
else {
uint amountInWei = _amount;
if (amountInWei > this.balance) {
return false;
}
success = destination.send(amountInWei);
}
if (success) {
controller.logSweep(this, destination, _token, _amount);
}
return success;
}
}
contract UserWallet {
AbstractSweeperList sweeperList;
function UserWallet(address _sweeperlist) {
sweeperList = AbstractSweeperList(_sweeperlist);
}
function () public payable { }
function tokenFallback(address _from, uint _value, bytes _data) {
(_from);
(_value);
(_data);
}
function sweep(address _token, uint _amount)
returns (bool) {
(_amount);
return sweeperList.sweeperOf(_token).delegatecall(msg.data);
}
}
contract AbstractSweeperList {
function sweeperOf(address _token) returns (address);
}
contract Controller is AbstractSweeperList {
address public owner;
address public authorizedCaller;
address public destination;
bool public halted;
event LogNewWallet(address receiver);
event LogSweep(address indexed from, address indexed to, address indexed token, uint amount);
modifier onlyOwner() {
if (msg.sender != owner) throw;
_;
}
modifier onlyAuthorizedCaller() {
if (msg.sender != authorizedCaller) throw;
_;
}
modifier onlyAdmins() {
if (msg.sender != authorizedCaller && msg.sender != owner) throw;
_;
}
function Controller()
{
owner = msg.sender;
destination = msg.sender;
authorizedCaller = msg.sender;
}
function changeAuthorizedCaller(address _newCaller) onlyOwner {
authorizedCaller = _newCaller;
}
function changeDestination(address _dest) onlyOwner {
destination = _dest;
}
function changeOwner(address _owner) onlyOwner {
owner = _owner;
}
function makeWallet() onlyAdmins returns (address wallet) {
wallet = address(new UserWallet(this));
LogNewWallet(wallet);
}
function halt() onlyAdmins {
halted = true;
}
function start() onlyOwner {
halted = false;
}
address public defaultSweeper = address(new DefaultSweeper(this));
mapping (address => address) sweepers;
function addSweeper(address _token, address _sweeper) onlyOwner {
sweepers[_token] = _sweeper;
}
function sweeperOf(address _token) returns (address) {
address sweeper = sweepers[_token];
if (sweeper == 0) sweeper = defaultSweeper;
return sweeper;
}
function logSweep(address from, address to, address token, uint amount) {
LogSweep(from, to, token, amount);
}
}
|
[{"constant":false,"inputs":[{"name":"_token","type":"address"},{"name":"_amount","type":"uint256"}],"name":"sweep","outputs":[{"name":"","type":"bool"}],"payable":false,"type":"function"},{"constant":false,"inputs":[{"name":"_from","type":"address"},{"name":"_value","type":"uint256"},{"name":"_data","type":"bytes"}],"name":"tokenFallback","outputs":[],"payable":false,"type":"function"},{"inputs":[{"name":"_sweeperlist","type":"address"}],"payable":false,"type":"constructor"},{"payable":true,"type":"fallback"}]
|
v0.4.11+commit.68ef5810
| true
| 200
|
000000000000000000000000a3C1E324CA1ce40db73eD6026c4A177F099B5770
|
Default
| false
|
bzzr://4cdd69fdcf3cf6cbee9677fe380fa5f044048aa9e060ec5619a21ca5a5bd4cd1
|
|||
UserWallet
|
0x5af4c0e497f0a4086054d60af3800d061cc01fb7
|
Solidity
|
pragma solidity ^0.4.10;
// Copyright 2017 Bittrex
contract AbstractSweeper {
function sweep(address token, uint amount) returns (bool);
function () { throw; }
Controller controller;
function AbstractSweeper(address _controller) {
controller = Controller(_controller);
}
modifier canSweep() {
if (msg.sender != controller.authorizedCaller() && msg.sender != controller.owner()) throw;
if (controller.halted()) throw;
_;
}
}
contract Token {
function balanceOf(address a) returns (uint) {
(a);
return 0;
}
function transfer(address a, uint val) returns (bool) {
(a);
(val);
return false;
}
}
contract DefaultSweeper is AbstractSweeper {
function DefaultSweeper(address controller)
AbstractSweeper(controller) {}
function sweep(address _token, uint _amount)
canSweep
returns (bool) {
bool success = false;
address destination = controller.destination();
if (_token != address(0)) {
Token token = Token(_token);
uint amount = _amount;
if (amount > token.balanceOf(this)) {
return false;
}
success = token.transfer(destination, amount);
}
else {
uint amountInWei = _amount;
if (amountInWei > this.balance) {
return false;
}
success = destination.send(amountInWei);
}
if (success) {
controller.logSweep(this, destination, _token, _amount);
}
return success;
}
}
contract UserWallet {
AbstractSweeperList sweeperList;
function UserWallet(address _sweeperlist) {
sweeperList = AbstractSweeperList(_sweeperlist);
}
function () public payable { }
function tokenFallback(address _from, uint _value, bytes _data) {
(_from);
(_value);
(_data);
}
function sweep(address _token, uint _amount)
returns (bool) {
(_amount);
return sweeperList.sweeperOf(_token).delegatecall(msg.data);
}
}
contract AbstractSweeperList {
function sweeperOf(address _token) returns (address);
}
contract Controller is AbstractSweeperList {
address public owner;
address public authorizedCaller;
address public destination;
bool public halted;
event LogNewWallet(address receiver);
event LogSweep(address indexed from, address indexed to, address indexed token, uint amount);
modifier onlyOwner() {
if (msg.sender != owner) throw;
_;
}
modifier onlyAuthorizedCaller() {
if (msg.sender != authorizedCaller) throw;
_;
}
modifier onlyAdmins() {
if (msg.sender != authorizedCaller && msg.sender != owner) throw;
_;
}
function Controller()
{
owner = msg.sender;
destination = msg.sender;
authorizedCaller = msg.sender;
}
function changeAuthorizedCaller(address _newCaller) onlyOwner {
authorizedCaller = _newCaller;
}
function changeDestination(address _dest) onlyOwner {
destination = _dest;
}
function changeOwner(address _owner) onlyOwner {
owner = _owner;
}
function makeWallet() onlyAdmins returns (address wallet) {
wallet = address(new UserWallet(this));
LogNewWallet(wallet);
}
function halt() onlyAdmins {
halted = true;
}
function start() onlyOwner {
halted = false;
}
address public defaultSweeper = address(new DefaultSweeper(this));
mapping (address => address) sweepers;
function addSweeper(address _token, address _sweeper) onlyOwner {
sweepers[_token] = _sweeper;
}
function sweeperOf(address _token) returns (address) {
address sweeper = sweepers[_token];
if (sweeper == 0) sweeper = defaultSweeper;
return sweeper;
}
function logSweep(address from, address to, address token, uint amount) {
LogSweep(from, to, token, amount);
}
}
|
[{"constant":false,"inputs":[{"name":"_token","type":"address"},{"name":"_amount","type":"uint256"}],"name":"sweep","outputs":[{"name":"","type":"bool"}],"payable":false,"type":"function"},{"constant":false,"inputs":[{"name":"_from","type":"address"},{"name":"_value","type":"uint256"},{"name":"_data","type":"bytes"}],"name":"tokenFallback","outputs":[],"payable":false,"type":"function"},{"inputs":[{"name":"_sweeperlist","type":"address"}],"payable":false,"type":"constructor"},{"payable":true,"type":"fallback"}]
|
v0.4.11+commit.68ef5810
| true
| 200
|
000000000000000000000000a3C1E324CA1ce40db73eD6026c4A177F099B5770
|
Default
| false
|
bzzr://4cdd69fdcf3cf6cbee9677fe380fa5f044048aa9e060ec5619a21ca5a5bd4cd1
|
|||
OwnableDelegateProxy
|
0x3fc8e120d24fe8b44f1cbc6aae4642bbc5271798
|
Solidity
|
contract OwnedUpgradeabilityStorage {
// Current implementation
address internal _implementation;
// Owner of the contract
address private _upgradeabilityOwner;
/**
* @dev Tells the address of the owner
* @return the address of the owner
*/
function upgradeabilityOwner() public view returns (address) {
return _upgradeabilityOwner;
}
/**
* @dev Sets the address of the owner
*/
function setUpgradeabilityOwner(address newUpgradeabilityOwner) internal {
_upgradeabilityOwner = newUpgradeabilityOwner;
}
/**
* @dev Tells the address of the current implementation
* @return address of the current implementation
*/
function implementation() public view returns (address) {
return _implementation;
}
/**
* @dev Tells the proxy type (EIP 897)
* @return Proxy type, 2 for forwarding proxy
*/
function proxyType() public pure returns (uint256 proxyTypeId) {
return 2;
}
}
contract Proxy {
/**
* @dev Tells the address of the implementation where every call will be delegated.
* @return address of the implementation to which it will be delegated
*/
function implementation() public view returns (address);
/**
* @dev Tells the type of proxy (EIP 897)
* @return Type of proxy, 2 for upgradeable proxy
*/
function proxyType() public pure returns (uint256 proxyTypeId);
/**
* @dev Fallback function allowing to perform a delegatecall to the given implementation.
* This function will return whatever the implementation call returns
*/
function () payable public {
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 OwnedUpgradeabilityProxy is Proxy, OwnedUpgradeabilityStorage {
/**
* @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);
/**
* @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);
/**
* @dev Upgrades the implementation address
* @param implementation representing the address of the new implementation to be set
*/
function _upgradeTo(address implementation) internal {
require(_implementation != implementation);
_implementation = implementation;
emit Upgraded(implementation);
}
/**
* @dev Throws if called by any account other than the owner.
*/
modifier onlyProxyOwner() {
require(msg.sender == proxyOwner());
_;
}
/**
* @dev Tells the address of the proxy owner
* @return the address of the proxy owner
*/
function proxyOwner() public view returns (address) {
return upgradeabilityOwner();
}
/**
* @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) public onlyProxyOwner {
require(newOwner != address(0));
emit ProxyOwnershipTransferred(proxyOwner(), newOwner);
setUpgradeabilityOwner(newOwner);
}
/**
* @dev Allows the upgradeability owner to upgrade the current implementation of the proxy.
* @param implementation representing the address of the new implementation to be set.
*/
function upgradeTo(address implementation) public onlyProxyOwner {
_upgradeTo(implementation);
}
/**
* @dev Allows the upgradeability owner to upgrade the current implementation of the proxy
* and delegatecall the new implementation for initialization.
* @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 data) payable public onlyProxyOwner {
upgradeTo(implementation);
require(address(this).delegatecall(data));
}
}
contract OwnableDelegateProxy is OwnedUpgradeabilityProxy {
constructor(address owner, address initialImplementation, bytes calldata)
public
{
setUpgradeabilityOwner(owner);
_upgradeTo(initialImplementation);
require(initialImplementation.delegatecall(calldata));
}
}
|
[{"constant":true,"inputs":[],"name":"proxyOwner","outputs":[{"name":"","type":"address"}],"payable":false,"stateMutability":"view","type":"function"},{"constant":false,"inputs":[{"name":"implementation","type":"address"}],"name":"upgradeTo","outputs":[],"payable":false,"stateMutability":"nonpayable","type":"function"},{"constant":true,"inputs":[],"name":"proxyType","outputs":[{"name":"proxyTypeId","type":"uint256"}],"payable":false,"stateMutability":"pure","type":"function"},{"constant":false,"inputs":[{"name":"implementation","type":"address"},{"name":"data","type":"bytes"}],"name":"upgradeToAndCall","outputs":[],"payable":true,"stateMutability":"payable","type":"function"},{"constant":true,"inputs":[],"name":"implementation","outputs":[{"name":"","type":"address"}],"payable":false,"stateMutability":"view","type":"function"},{"constant":true,"inputs":[],"name":"upgradeabilityOwner","outputs":[{"name":"","type":"address"}],"payable":false,"stateMutability":"view","type":"function"},{"constant":false,"inputs":[{"name":"newOwner","type":"address"}],"name":"transferProxyOwnership","outputs":[],"payable":false,"stateMutability":"nonpayable","type":"function"},{"inputs":[{"name":"owner","type":"address"},{"name":"initialImplementation","type":"address"},{"name":"calldata","type":"bytes"}],"payable":false,"stateMutability":"nonpayable","type":"constructor"},{"payable":true,"stateMutability":"payable","type":"fallback"},{"anonymous":false,"inputs":[{"indexed":false,"name":"previousOwner","type":"address"},{"indexed":false,"name":"newOwner","type":"address"}],"name":"ProxyOwnershipTransferred","type":"event"},{"anonymous":false,"inputs":[{"indexed":true,"name":"implementation","type":"address"}],"name":"Upgraded","type":"event"}]
|
v0.4.23+commit.124ca40d
| true
| 200
|
00000000000000000000000074451193ccf4d1c9182c973538d9d2339350ee1a000000000000000000000000f9e266af4bca5890e2781812cc6a6e89495a79f200000000000000000000000000000000000000000000000000000000000000600000000000000000000000000000000000000000000000000000000000000044485cc95500000000000000000000000074451193ccf4d1c9182c973538d9d2339350ee1a000000000000000000000000a5409ec958c83c3f309868babaca7c86dcb077c100000000000000000000000000000000000000000000000000000000
|
Default
|
MIT
| false
|
bzzr://5f26049bbc794226b505f589b2ee1130db54310d79dd8a635c6f6c61e305a777
|
||
Forwarder
|
0xccd3ee29408ff375a4e549ad8f74598fab8fc4f4
|
Solidity
|
pragma solidity ^0.4.14;
/**
* Contract that exposes the needed erc20 token functions
*/
contract ERC20Interface {
// Send _value amount of tokens to address _to
function transfer(address _to, uint256 _value) returns (bool success);
// Get the account balance of another account with address _owner
function balanceOf(address _owner) constant returns (uint256 balance);
}
/**
* Contract that will forward any incoming Ether to its creator
*/
contract Forwarder {
// Address to which any funds sent to this contract will be forwarded
address public parentAddress;
event ForwarderDeposited(address from, uint value, bytes data);
event TokensFlushed(
address tokenContractAddress, // The contract address of the token
uint value // Amount of token sent
);
/**
* Create the contract, and set the destination address to that of the creator
*/
function Forwarder() {
parentAddress = msg.sender;
}
/**
* Modifier that will execute internal code block only if the sender is a parent of the forwarder contract
*/
modifier onlyParent {
if (msg.sender != parentAddress) {
throw;
}
_;
}
/**
* Default function; Gets called when Ether is deposited, and forwards it to the destination address
*/
function() payable {
if (!parentAddress.call.value(msg.value)(msg.data))
throw;
// Fire off the deposited event if we can forward it
ForwarderDeposited(msg.sender, msg.value, msg.data);
}
/**
* Execute a token transfer of the full balance from the forwarder token to the main wallet contract
* @param tokenContractAddress the address of the erc20 token contract
*/
function flushTokens(address tokenContractAddress) onlyParent {
ERC20Interface instance = ERC20Interface(tokenContractAddress);
var forwarderAddress = address(this);
var forwarderBalance = instance.balanceOf(forwarderAddress);
if (forwarderBalance == 0) {
return;
}
if (!instance.transfer(parentAddress, forwarderBalance)) {
throw;
}
TokensFlushed(tokenContractAddress, forwarderBalance);
}
/**
* It is possible that funds were sent to this address before the contract was deployed.
* We can flush those funds to the destination address.
*/
function flush() {
if (!parentAddress.call.value(this.balance)())
throw;
}
}
/**
* Basic multi-signer wallet designed for use in a co-signing environment where 2 signatures are required to move funds.
* Typically used in a 2-of-3 signing configuration. Uses ecrecover to allow for 2 signatures in a single transaction.
*/
contract WalletSimple {
// Events
event Deposited(address from, uint value, bytes data);
event SafeModeActivated(address msgSender);
event Transacted(
address msgSender, // Address of the sender of the message initiating the transaction
address otherSigner, // Address of the signer (second signature) used to initiate the transaction
bytes32 operation, // Operation hash (sha3 of toAddress, value, data, expireTime, sequenceId)
address toAddress, // The address the transaction was sent to
uint value, // Amount of Wei sent to the address
bytes data // Data sent when invoking the transaction
);
event TokenTransacted(
address msgSender, // Address of the sender of the message initiating the transaction
address otherSigner, // Address of the signer (second signature) used to initiate the transaction
bytes32 operation, // Operation hash (sha3 of toAddress, value, tokenContractAddress, expireTime, sequenceId)
address toAddress, // The address the transaction was sent to
uint value, // Amount of token sent
address tokenContractAddress // The contract address of the token
);
// Public fields
address[] public signers; // The addresses that can co-sign transactions on the wallet
bool public safeMode = false; // When active, wallet may only send to signer addresses
// Internal fields
uint constant SEQUENCE_ID_WINDOW_SIZE = 10;
uint[10] recentSequenceIds;
/**
* Modifier that will execute internal code block only if the sender is an authorized signer on this wallet
*/
modifier onlysigner {
if (!isSigner(msg.sender)) {
throw;
}
_;
}
/**
* Set up a simple multi-sig wallet by specifying the signers allowed to be used on this wallet.
* 2 signers will be required to send a transaction from this wallet.
* Note: The sender is NOT automatically added to the list of signers.
* Signers CANNOT be changed once they are set
*
* @param allowedSigners An array of signers on the wallet
*/
function WalletSimple(address[] allowedSigners) {
if (allowedSigners.length != 3) {
// Invalid number of signers
throw;
}
signers = allowedSigners;
}
/**
* Gets called when a transaction is received without calling a method
*/
function() payable {
if (msg.value > 0) {
// Fire deposited event if we are receiving funds
Deposited(msg.sender, msg.value, msg.data);
}
}
/**
* Create a new contract (and also address) that forwards funds to this contract
* returns address of newly created forwarder address
*/
function createForwarder() onlysigner returns (address) {
return new Forwarder();
}
/**
* Execute a multi-signature transaction from this wallet using 2 signers: one from msg.sender and the other from ecrecover.
* The signature is a signed form (using eth.sign) of tightly packed toAddress, value, data, expireTime and sequenceId
* Sequence IDs are numbers starting from 1. They are used to prevent replay attacks and may not be repeated.
*
* @param toAddress the destination address to send an outgoing transaction
* @param value the amount in Wei to be sent
* @param data the data to send to the toAddress when invoking the transaction
* @param expireTime the number of seconds since 1970 for which this transaction is valid
* @param sequenceId the unique sequence id obtainable from getNextSequenceId
* @param signature the result of eth.sign on the operationHash sha3(toAddress, value, data, expireTime, sequenceId)
*/
function sendMultiSig(address toAddress, uint value, bytes data, uint expireTime, uint sequenceId, bytes signature) onlysigner {
// Verify the other signer
var operationHash = sha3("ETHER", toAddress, value, data, expireTime, sequenceId);
var otherSigner = verifyMultiSig(toAddress, operationHash, signature, expireTime, sequenceId);
// Success, send the transaction
if (!(toAddress.call.value(value)(data))) {
// Failed executing transaction
throw;
}
Transacted(msg.sender, otherSigner, operationHash, toAddress, value, data);
}
/**
* Execute a multi-signature token transfer from this wallet using 2 signers: one from msg.sender and the other from ecrecover.
* The signature is a signed form (using eth.sign) of tightly packed toAddress, value, tokenContractAddress, expireTime and sequenceId
* Sequence IDs are numbers starting from 1. They are used to prevent replay attacks and may not be repeated.
*
* @param toAddress the destination address to send an outgoing transaction
* @param value the amount in tokens to be sent
* @param tokenContractAddress the address of the erc20 token contract
* @param expireTime the number of seconds since 1970 for which this transaction is valid
* @param sequenceId the unique sequence id obtainable from getNextSequenceId
* @param signature the result of eth.sign on the operationHash sha3(toAddress, value, tokenContractAddress, expireTime, sequenceId)
*/
function sendMultiSigToken(address toAddress, uint value, address tokenContractAddress, uint expireTime, uint sequenceId, bytes signature) onlysigner {
// Verify the other signer
var operationHash = sha3("ERC20", toAddress, value, tokenContractAddress, expireTime, sequenceId);
var otherSigner = verifyMultiSig(toAddress, operationHash, signature, expireTime, sequenceId);
ERC20Interface instance = ERC20Interface(tokenContractAddress);
if (!instance.transfer(toAddress, value)) {
throw;
}
TokenTransacted(msg.sender, otherSigner, operationHash, toAddress, value, tokenContractAddress);
}
/**
* Execute a token flush from one of the forwarder addresses. This transfer needs only a single signature and can be done by any signer
*
* @param forwarderAddress the address of the forwarder address to flush the tokens from
* @param tokenContractAddress the address of the erc20 token contract
*/
function flushForwarderTokens(address forwarderAddress, address tokenContractAddress) onlysigner {
Forwarder forwarder = Forwarder(forwarderAddress);
forwarder.flushTokens(tokenContractAddress);
}
/**
* Do common multisig verification for both eth sends and erc20token transfers
*
* @param toAddress the destination address to send an outgoing transaction
* @param operationHash the sha3 of the toAddress, value, data/tokenContractAddress and expireTime
* @param signature the tightly packed signature of r, s, and v as an array of 65 bytes (returned by eth.sign)
* @param expireTime the number of seconds since 1970 for which this transaction is valid
* @param sequenceId the unique sequence id obtainable from getNextSequenceId
* returns address of the address to send tokens or eth to
*/
function verifyMultiSig(address toAddress, bytes32 operationHash, bytes signature, uint expireTime, uint sequenceId) private returns (address) {
var otherSigner = recoverAddressFromSignature(operationHash, signature);
// Verify if we are in safe mode. In safe mode, the wallet can only send to signers
if (safeMode && !isSigner(toAddress)) {
// We are in safe mode and the toAddress is not a signer. Disallow!
throw;
}
// Verify that the transaction has not expired
if (expireTime < block.timestamp) {
// Transaction expired
throw;
}
// Try to insert the sequence ID. Will throw if the sequence id was invalid
tryInsertSequenceId(sequenceId);
if (!isSigner(otherSigner)) {
// Other signer not on this wallet or operation does not match arguments
throw;
}
if (otherSigner == msg.sender) {
// Cannot approve own transaction
throw;
}
return otherSigner;
}
/**
* Irrevocably puts contract into safe mode. When in this mode, transactions may only be sent to signing addresses.
*/
function activateSafeMode() onlysigner {
safeMode = true;
SafeModeActivated(msg.sender);
}
/**
* Determine if an address is a signer on this wallet
* @param signer address to check
* returns boolean indicating whether address is signer or not
*/
function isSigner(address signer) returns (bool) {
// Iterate through all signers on the wallet and
for (uint i = 0; i < signers.length; i++) {
if (signers[i] == signer) {
return true;
}
}
return false;
}
/**
* Gets the second signer's address using ecrecover
* @param operationHash the sha3 of the toAddress, value, data/tokenContractAddress and expireTime
* @param signature the tightly packed signature of r, s, and v as an array of 65 bytes (returned by eth.sign)
* returns address recovered from the signature
*/
function recoverAddressFromSignature(bytes32 operationHash, bytes signature) private returns (address) {
if (signature.length != 65) {
throw;
}
// We need to unpack the signature, which is given as an array of 65 bytes (from eth.sign)
bytes32 r;
bytes32 s;
uint8 v;
assembly {
r := mload(add(signature, 32))
s := mload(add(signature, 64))
v := and(mload(add(signature, 65)), 255)
}
if (v < 27) {
v += 27; // Ethereum versions are 27 or 28 as opposed to 0 or 1 which is submitted by some signing libs
}
return ecrecover(operationHash, v, r, s);
}
/**
* Verify that the sequence id has not been used before and inserts it. Throws if the sequence ID was not accepted.
* We collect a window of up to 10 recent sequence ids, and allow any sequence id that is not in the window and
* greater than the minimum element in the window.
* @param sequenceId to insert into array of stored ids
*/
function tryInsertSequenceId(uint sequenceId) onlysigner private {
// Keep a pointer to the lowest value element in the window
uint lowestValueIndex = 0;
for (uint i = 0; i < SEQUENCE_ID_WINDOW_SIZE; i++) {
if (recentSequenceIds[i] == sequenceId) {
// This sequence ID has been used before. Disallow!
throw;
}
if (recentSequenceIds[i] < recentSequenceIds[lowestValueIndex]) {
lowestValueIndex = i;
}
}
if (sequenceId < recentSequenceIds[lowestValueIndex]) {
// The sequence ID being used is lower than the lowest value in the window
// so we cannot accept it as it may have been used before
throw;
}
if (sequenceId > (recentSequenceIds[lowestValueIndex] + 10000)) {
// Block sequence IDs which are much higher than the lowest value
// This prevents people blocking the contract by using very large sequence IDs quickly
throw;
}
recentSequenceIds[lowestValueIndex] = sequenceId;
}
/**
* Gets the next available sequence ID for signing when using executeAndConfirm
* returns the sequenceId one higher than the highest currently stored
*/
function getNextSequenceId() returns (uint) {
uint highestSequenceId = 0;
for (uint i = 0; i < SEQUENCE_ID_WINDOW_SIZE; i++) {
if (recentSequenceIds[i] > highestSequenceId) {
highestSequenceId = recentSequenceIds[i];
}
}
return highestSequenceId + 1;
}
}
|
[{"constant":true,"inputs":[],"name":"parentAddress","outputs":[{"name":"","type":"address"}],"payable":false,"type":"function"},{"constant":false,"inputs":[{"name":"tokenContractAddress","type":"address"}],"name":"flushTokens","outputs":[],"payable":false,"type":"function"},{"constant":false,"inputs":[],"name":"flush","outputs":[],"payable":false,"type":"function"},{"inputs":[],"payable":false,"type":"constructor"},{"payable":true,"type":"fallback"},{"anonymous":false,"inputs":[{"indexed":false,"name":"from","type":"address"},{"indexed":false,"name":"value","type":"uint256"},{"indexed":false,"name":"data","type":"bytes"}],"name":"ForwarderDeposited","type":"event"},{"anonymous":false,"inputs":[{"indexed":false,"name":"tokenContractAddress","type":"address"},{"indexed":false,"name":"value","type":"uint256"}],"name":"TokensFlushed","type":"event"}]
|
v0.4.16-nightly.2017.8.11+commit.c84de7fa
| true
| 200
|
Default
| false
|
bzzr://d0f8838ba17108a895d34ae8ef3bff4e0dc9d639c3c51921fee1d17eaa803721
|
||||
OwnableDelegateProxy
|
0x8c2c8e6bd0451f03a65a25e5d4bbe78385faaeaf
|
Solidity
|
contract OwnedUpgradeabilityStorage {
// Current implementation
address internal _implementation;
// Owner of the contract
address private _upgradeabilityOwner;
/**
* @dev Tells the address of the owner
* @return the address of the owner
*/
function upgradeabilityOwner() public view returns (address) {
return _upgradeabilityOwner;
}
/**
* @dev Sets the address of the owner
*/
function setUpgradeabilityOwner(address newUpgradeabilityOwner) internal {
_upgradeabilityOwner = newUpgradeabilityOwner;
}
/**
* @dev Tells the address of the current implementation
* @return address of the current implementation
*/
function implementation() public view returns (address) {
return _implementation;
}
/**
* @dev Tells the proxy type (EIP 897)
* @return Proxy type, 2 for forwarding proxy
*/
function proxyType() public pure returns (uint256 proxyTypeId) {
return 2;
}
}
contract Proxy {
/**
* @dev Tells the address of the implementation where every call will be delegated.
* @return address of the implementation to which it will be delegated
*/
function implementation() public view returns (address);
/**
* @dev Tells the type of proxy (EIP 897)
* @return Type of proxy, 2 for upgradeable proxy
*/
function proxyType() public pure returns (uint256 proxyTypeId);
/**
* @dev Fallback function allowing to perform a delegatecall to the given implementation.
* This function will return whatever the implementation call returns
*/
function () payable public {
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 OwnedUpgradeabilityProxy is Proxy, OwnedUpgradeabilityStorage {
/**
* @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);
/**
* @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);
/**
* @dev Upgrades the implementation address
* @param implementation representing the address of the new implementation to be set
*/
function _upgradeTo(address implementation) internal {
require(_implementation != implementation);
_implementation = implementation;
emit Upgraded(implementation);
}
/**
* @dev Throws if called by any account other than the owner.
*/
modifier onlyProxyOwner() {
require(msg.sender == proxyOwner());
_;
}
/**
* @dev Tells the address of the proxy owner
* @return the address of the proxy owner
*/
function proxyOwner() public view returns (address) {
return upgradeabilityOwner();
}
/**
* @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) public onlyProxyOwner {
require(newOwner != address(0));
emit ProxyOwnershipTransferred(proxyOwner(), newOwner);
setUpgradeabilityOwner(newOwner);
}
/**
* @dev Allows the upgradeability owner to upgrade the current implementation of the proxy.
* @param implementation representing the address of the new implementation to be set.
*/
function upgradeTo(address implementation) public onlyProxyOwner {
_upgradeTo(implementation);
}
/**
* @dev Allows the upgradeability owner to upgrade the current implementation of the proxy
* and delegatecall the new implementation for initialization.
* @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 data) payable public onlyProxyOwner {
upgradeTo(implementation);
require(address(this).delegatecall(data));
}
}
contract OwnableDelegateProxy is OwnedUpgradeabilityProxy {
constructor(address owner, address initialImplementation, bytes calldata)
public
{
setUpgradeabilityOwner(owner);
_upgradeTo(initialImplementation);
require(initialImplementation.delegatecall(calldata));
}
}
|
[{"constant":true,"inputs":[],"name":"proxyOwner","outputs":[{"name":"","type":"address"}],"payable":false,"stateMutability":"view","type":"function"},{"constant":false,"inputs":[{"name":"implementation","type":"address"}],"name":"upgradeTo","outputs":[],"payable":false,"stateMutability":"nonpayable","type":"function"},{"constant":true,"inputs":[],"name":"proxyType","outputs":[{"name":"proxyTypeId","type":"uint256"}],"payable":false,"stateMutability":"pure","type":"function"},{"constant":false,"inputs":[{"name":"implementation","type":"address"},{"name":"data","type":"bytes"}],"name":"upgradeToAndCall","outputs":[],"payable":true,"stateMutability":"payable","type":"function"},{"constant":true,"inputs":[],"name":"implementation","outputs":[{"name":"","type":"address"}],"payable":false,"stateMutability":"view","type":"function"},{"constant":true,"inputs":[],"name":"upgradeabilityOwner","outputs":[{"name":"","type":"address"}],"payable":false,"stateMutability":"view","type":"function"},{"constant":false,"inputs":[{"name":"newOwner","type":"address"}],"name":"transferProxyOwnership","outputs":[],"payable":false,"stateMutability":"nonpayable","type":"function"},{"inputs":[{"name":"owner","type":"address"},{"name":"initialImplementation","type":"address"},{"name":"calldata","type":"bytes"}],"payable":false,"stateMutability":"nonpayable","type":"constructor"},{"payable":true,"stateMutability":"payable","type":"fallback"},{"anonymous":false,"inputs":[{"indexed":false,"name":"previousOwner","type":"address"},{"indexed":false,"name":"newOwner","type":"address"}],"name":"ProxyOwnershipTransferred","type":"event"},{"anonymous":false,"inputs":[{"indexed":true,"name":"implementation","type":"address"}],"name":"Upgraded","type":"event"}]
|
v0.4.23+commit.124ca40d
| true
| 200
|
00000000000000000000000074451193ccf4d1c9182c973538d9d2339350ee1a000000000000000000000000f9e266af4bca5890e2781812cc6a6e89495a79f200000000000000000000000000000000000000000000000000000000000000600000000000000000000000000000000000000000000000000000000000000044485cc95500000000000000000000000074451193ccf4d1c9182c973538d9d2339350ee1a000000000000000000000000a5409ec958c83c3f309868babaca7c86dcb077c100000000000000000000000000000000000000000000000000000000
|
Default
|
MIT
| false
|
bzzr://5f26049bbc794226b505f589b2ee1130db54310d79dd8a635c6f6c61e305a777
|
||
UserWallet
|
0x3caf45dd8bc1d0be4424235430dbcc8aba715648
|
Solidity
|
pragma solidity ^0.4.10;
// Copyright 2017 Bittrex
contract AbstractSweeper {
function sweep(address token, uint amount) returns (bool);
function () { throw; }
Controller controller;
function AbstractSweeper(address _controller) {
controller = Controller(_controller);
}
modifier canSweep() {
if (msg.sender != controller.authorizedCaller() && msg.sender != controller.owner()) throw;
if (controller.halted()) throw;
_;
}
}
contract Token {
function balanceOf(address a) returns (uint) {
(a);
return 0;
}
function transfer(address a, uint val) returns (bool) {
(a);
(val);
return false;
}
}
contract DefaultSweeper is AbstractSweeper {
function DefaultSweeper(address controller)
AbstractSweeper(controller) {}
function sweep(address _token, uint _amount)
canSweep
returns (bool) {
bool success = false;
address destination = controller.destination();
if (_token != address(0)) {
Token token = Token(_token);
uint amount = _amount;
if (amount > token.balanceOf(this)) {
return false;
}
success = token.transfer(destination, amount);
}
else {
uint amountInWei = _amount;
if (amountInWei > this.balance) {
return false;
}
success = destination.send(amountInWei);
}
if (success) {
controller.logSweep(this, destination, _token, _amount);
}
return success;
}
}
contract UserWallet {
AbstractSweeperList sweeperList;
function UserWallet(address _sweeperlist) {
sweeperList = AbstractSweeperList(_sweeperlist);
}
function () public payable { }
function tokenFallback(address _from, uint _value, bytes _data) {
(_from);
(_value);
(_data);
}
function sweep(address _token, uint _amount)
returns (bool) {
(_amount);
return sweeperList.sweeperOf(_token).delegatecall(msg.data);
}
}
contract AbstractSweeperList {
function sweeperOf(address _token) returns (address);
}
contract Controller is AbstractSweeperList {
address public owner;
address public authorizedCaller;
address public destination;
bool public halted;
event LogNewWallet(address receiver);
event LogSweep(address indexed from, address indexed to, address indexed token, uint amount);
modifier onlyOwner() {
if (msg.sender != owner) throw;
_;
}
modifier onlyAuthorizedCaller() {
if (msg.sender != authorizedCaller) throw;
_;
}
modifier onlyAdmins() {
if (msg.sender != authorizedCaller && msg.sender != owner) throw;
_;
}
function Controller()
{
owner = msg.sender;
destination = msg.sender;
authorizedCaller = msg.sender;
}
function changeAuthorizedCaller(address _newCaller) onlyOwner {
authorizedCaller = _newCaller;
}
function changeDestination(address _dest) onlyOwner {
destination = _dest;
}
function changeOwner(address _owner) onlyOwner {
owner = _owner;
}
function makeWallet() onlyAdmins returns (address wallet) {
wallet = address(new UserWallet(this));
LogNewWallet(wallet);
}
function halt() onlyAdmins {
halted = true;
}
function start() onlyOwner {
halted = false;
}
address public defaultSweeper = address(new DefaultSweeper(this));
mapping (address => address) sweepers;
function addSweeper(address _token, address _sweeper) onlyOwner {
sweepers[_token] = _sweeper;
}
function sweeperOf(address _token) returns (address) {
address sweeper = sweepers[_token];
if (sweeper == 0) sweeper = defaultSweeper;
return sweeper;
}
function logSweep(address from, address to, address token, uint amount) {
LogSweep(from, to, token, amount);
}
}
|
[{"constant":false,"inputs":[{"name":"_token","type":"address"},{"name":"_amount","type":"uint256"}],"name":"sweep","outputs":[{"name":"","type":"bool"}],"payable":false,"type":"function"},{"constant":false,"inputs":[{"name":"_from","type":"address"},{"name":"_value","type":"uint256"},{"name":"_data","type":"bytes"}],"name":"tokenFallback","outputs":[],"payable":false,"type":"function"},{"inputs":[{"name":"_sweeperlist","type":"address"}],"payable":false,"type":"constructor"},{"payable":true,"type":"fallback"}]
|
v0.4.11+commit.68ef5810
| true
| 200
|
000000000000000000000000a3C1E324CA1ce40db73eD6026c4A177F099B5770
|
Default
| false
|
bzzr://4cdd69fdcf3cf6cbee9677fe380fa5f044048aa9e060ec5619a21ca5a5bd4cd1
|
|||
DSProxy
|
0xf1c319e92fe2ba54893db49b6dcbc7b022a86aac
|
Solidity
|
// proxy.sol - execute actions atomically through the proxy's identity
// Copyright (C) 2017 DappHub, LLC
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
// You should have received a copy of the GNU General Public License
// along with this program. If not, see <http://www.gnu.org/licenses/>.
pragma solidity ^0.4.23;
contract DSAuthority {
function canCall(
address src, address dst, bytes4 sig
) public view returns (bool);
}
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(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, this, sig);
}
}
}
contract DSNote {
event LogNote(
bytes4 indexed sig,
address indexed guy,
bytes32 indexed foo,
bytes32 indexed bar,
uint 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);
_;
}
}
// DSProxy
// Allows code execution using a persistant identity This can be very
// useful to execute a sequence of atomic actions. Since the owner of
// the proxy can be changed, this allows for dynamic ownership models
// i.e. a multisig
contract DSProxy is DSAuth, DSNote {
DSProxyCache public cache; // global cache for contracts
constructor(address _cacheAddr) public {
require(setCache(_cacheAddr));
}
function() public payable {
}
// use the proxy to execute calldata _data on contract _code
function execute(bytes _code, bytes _data)
public
payable
returns (address target, bytes32 response)
{
target = cache.read(_code);
if (target == 0x0) {
// deploy contract & store its address in cache
target = cache.write(_code);
}
response = execute(target, _data);
}
function execute(address _target, bytes _data)
public
auth
note
payable
returns (bytes32 response)
{
require(_target != 0x0);
// call contract in current context
assembly {
let succeeded := delegatecall(sub(gas, 5000), _target, add(_data, 0x20), mload(_data), 0, 32)
response := mload(0) // load delegatecall output
switch iszero(succeeded)
case 1 {
// throw if delegatecall failed
revert(0, 0)
}
}
}
//set new cache
function setCache(address _cacheAddr)
public
auth
note
returns (bool)
{
require(_cacheAddr != 0x0); // invalid cache address
cache = DSProxyCache(_cacheAddr); // overwrite cache
return true;
}
}
// DSProxyFactory
// This factory deploys new proxy instances through build()
// Deployed proxy addresses are logged
contract DSProxyFactory {
event Created(address indexed sender, address indexed owner, address proxy, address cache);
mapping(address=>bool) public isProxy;
DSProxyCache public cache = new DSProxyCache();
// deploys a new proxy instance
// sets owner of proxy to caller
function build() public returns (DSProxy proxy) {
proxy = build(msg.sender);
}
// deploys a new proxy instance
// sets custom owner of proxy
function build(address owner) public returns (DSProxy proxy) {
proxy = new DSProxy(cache);
emit Created(msg.sender, owner, address(proxy), address(cache));
proxy.setOwner(owner);
isProxy[proxy] = true;
}
}
// DSProxyCache
// This global cache stores addresses of contracts previously deployed
// by a proxy. This saves gas from repeat deployment of the same
// contracts and eliminates blockchain bloat.
// By default, all proxies deployed from the same factory store
// contracts in the same cache. The cache a proxy instance uses can be
// changed. The cache uses the sha3 hash of a contract's bytecode to
// lookup the address
contract DSProxyCache {
mapping(bytes32 => address) cache;
function read(bytes _code) public view returns (address) {
bytes32 hash = keccak256(_code);
return cache[hash];
}
function write(bytes _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;
}
}
|
[{"constant":false,"inputs":[{"name":"owner_","type":"address"}],"name":"setOwner","outputs":[],"payable":false,"stateMutability":"nonpayable","type":"function"},{"constant":false,"inputs":[{"name":"_target","type":"address"},{"name":"_data","type":"bytes"}],"name":"execute","outputs":[{"name":"response","type":"bytes32"}],"payable":true,"stateMutability":"payable","type":"function"},{"constant":false,"inputs":[{"name":"_code","type":"bytes"},{"name":"_data","type":"bytes"}],"name":"execute","outputs":[{"name":"target","type":"address"},{"name":"response","type":"bytes32"}],"payable":true,"stateMutability":"payable","type":"function"},{"constant":true,"inputs":[],"name":"cache","outputs":[{"name":"","type":"address"}],"payable":false,"stateMutability":"view","type":"function"},{"constant":false,"inputs":[{"name":"authority_","type":"address"}],"name":"setAuthority","outputs":[],"payable":false,"stateMutability":"nonpayable","type":"function"},{"constant":true,"inputs":[],"name":"owner","outputs":[{"name":"","type":"address"}],"payable":false,"stateMutability":"view","type":"function"},{"constant":false,"inputs":[{"name":"_cacheAddr","type":"address"}],"name":"setCache","outputs":[{"name":"","type":"bool"}],"payable":false,"stateMutability":"nonpayable","type":"function"},{"constant":true,"inputs":[],"name":"authority","outputs":[{"name":"","type":"address"}],"payable":false,"stateMutability":"view","type":"function"},{"inputs":[{"name":"_cacheAddr","type":"address"}],"payable":false,"stateMutability":"nonpayable","type":"constructor"},{"payable":true,"stateMutability":"payable","type":"fallback"},{"anonymous":true,"inputs":[{"indexed":true,"name":"sig","type":"bytes4"},{"indexed":true,"name":"guy","type":"address"},{"indexed":true,"name":"foo","type":"bytes32"},{"indexed":true,"name":"bar","type":"bytes32"},{"indexed":false,"name":"wad","type":"uint256"},{"indexed":false,"name":"fax","type":"bytes"}],"name":"LogNote","type":"event"},{"anonymous":false,"inputs":[{"indexed":true,"name":"authority","type":"address"}],"name":"LogSetAuthority","type":"event"},{"anonymous":false,"inputs":[{"indexed":true,"name":"owner","type":"address"}],"name":"LogSetOwner","type":"event"}]
|
v0.4.23+commit.124ca40d
| true
| 200
|
000000000000000000000000271293c67e2d3140a0e9381eff1f9b01e07b0795
|
Default
| false
|
bzzr://e498874c9ba9e75028e0c84f1b1d83b2dad5de910c59b837b32e5a190794c5e1
|
|||
Forwarder
|
0x88cbb2c759e8cca17cf5e0a7f875d248dbb6b48c
|
Solidity
|
pragma solidity 0.7.5;
/*
The MIT License (MIT)
Copyright (c) 2018 Murray Software, LLC.
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.
*/
//solhint-disable max-line-length
//solhint-disable no-inline-assembly
contract CloneFactory {
function createClone(address target, bytes32 salt)
internal
returns (address payable result)
{
bytes20 targetBytes = bytes20(target);
assembly {
// load the next free memory slot as a place to store the clone contract data
let clone := mload(0x40)
// The bytecode block below is responsible for contract initialization
// during deployment, it is worth noting the proxied contract constructor will not be called during
// the cloning procedure and that is why an initialization function needs to be called after the
// clone is created
mstore(
clone,
0x3d602d80600a3d3981f3363d3d373d3d3d363d73000000000000000000000000
)
// This stores the address location of the implementation contract
// so that the proxy knows where to delegate call logic to
mstore(add(clone, 0x14), targetBytes)
// The bytecode block is the actual code that is deployed for each clone created.
// It forwards all calls to the already deployed implementation via a delegatecall
mstore(
add(clone, 0x28),
0x5af43d82803e903d91602b57fd5bf30000000000000000000000000000000000
)
// deploy the contract using the CREATE2 opcode
// this deploys the minimal proxy defined above, which will proxy all
// calls to use the logic defined in the implementation contract `target`
result := create2(0, clone, 0x37, salt)
}
}
function isClone(address target, address query)
internal
view
returns (bool result)
{
bytes20 targetBytes = bytes20(target);
assembly {
// load the next free memory slot as a place to store the comparison clone
let clone := mload(0x40)
// The next three lines store the expected bytecode for a miniml proxy
// that targets `target` as its implementation contract
mstore(
clone,
0x363d3d373d3d3d363d7300000000000000000000000000000000000000000000
)
mstore(add(clone, 0xa), targetBytes)
mstore(
add(clone, 0x1e),
0x5af43d82803e903d91602b57fd5bf30000000000000000000000000000000000
)
// the next two lines store the bytecode of the contract that we are checking in memory
let other := add(clone, 0x40)
extcodecopy(query, other, 0, 0x2d)
// Check if the expected bytecode equals the actual bytecode and return the result
result := and(
eq(mload(clone), mload(other)),
eq(mload(add(clone, 0xd)), mload(add(other, 0xd)))
)
}
}
}
/**
* Contract that exposes the needed erc20 token functions
*/
abstract contract ERC20Interface {
// Send _value amount of tokens to address _to
function transfer(address _to, uint256 _value)
public
virtual
returns (bool success);
// Get the account balance of another account with address _owner
function balanceOf(address _owner)
public
virtual
view
returns (uint256 balance);
}
// helper methods for interacting with ERC20 tokens and sending ETH that do not consistently return true/false
library TransferHelper {
function safeApprove(
address token,
address to,
uint256 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::safeApprove: approve failed'
);
}
function safeTransfer(
address token,
address to,
uint256 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::safeTransfer: transfer failed'
);
}
function safeTransferFrom(
address token,
address from,
address to,
uint256 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::transferFrom: transferFrom failed'
);
}
function safeTransferETH(address to, uint256 value) internal {
(bool success, ) = to.call{value: value}(new bytes(0));
require(success, 'TransferHelper::safeTransferETH: ETH transfer failed');
}
}
/**
* Contract that will forward any incoming Ether to the creator of the contract
*
*/
contract Forwarder {
// Address to which any funds sent to this contract will be forwarded
address public parentAddress;
event ForwarderDeposited(address from, uint256 value, bytes data);
/**
* Initialize the contract, and sets the destination address to that of the creator
*/
function init(address _parentAddress) external onlyUninitialized {
parentAddress = _parentAddress;
uint256 value = address(this).balance;
if (value == 0) {
return;
}
(bool success, ) = parentAddress.call{ value: value }('');
require(success, 'Flush failed');
// NOTE: since we are forwarding on initialization,
// we don't have the context of the original sender.
// We still emit an event about the forwarding but set
// the sender to the forwarder itself
emit ForwarderDeposited(address(this), value, msg.data);
}
/**
* Modifier that will execute internal code block only if the sender is the parent address
*/
modifier onlyParent {
require(msg.sender == parentAddress, 'Only Parent');
_;
}
/**
* Modifier that will execute internal code block only if the contract has not been initialized yet
*/
modifier onlyUninitialized {
require(parentAddress == address(0x0), 'Already initialized');
_;
}
/**
* Default function; Gets called when data is sent but does not match any other function
*/
fallback() external payable {
flush();
}
/**
* Default function; Gets called when Ether is deposited with no data, and forwards it to the parent address
*/
receive() external payable {
flush();
}
/**
* Execute a token transfer of the full balance from the forwarder token to the parent address
* @param tokenContractAddress the address of the erc20 token contract
*/
function flushTokens(address tokenContractAddress) external onlyParent {
ERC20Interface instance = ERC20Interface(tokenContractAddress);
address forwarderAddress = address(this);
uint256 forwarderBalance = instance.balanceOf(forwarderAddress);
if (forwarderBalance == 0) {
return;
}
TransferHelper.safeTransfer(
tokenContractAddress,
parentAddress,
forwarderBalance
);
}
/**
* Flush the entire balance of the contract to the parent address.
*/
function flush() public {
uint256 value = address(this).balance;
if (value == 0) {
return;
}
(bool success, ) = parentAddress.call{ value: value }('');
require(success, 'Flush failed');
emit ForwarderDeposited(msg.sender, value, msg.data);
}
}
contract ForwarderFactory is CloneFactory {
address public implementationAddress;
event ForwarderCreated(address newForwarderAddress, address parentAddress);
constructor(address _implementationAddress) {
implementationAddress = _implementationAddress;
}
function createForwarder(address parent, bytes32 salt) external {
// include the signers in the salt so any contract deployed to a given address must have the same signers
bytes32 finalSalt = keccak256(abi.encodePacked(parent, salt));
address payable clone = createClone(implementationAddress, finalSalt);
Forwarder(clone).init(parent);
emit ForwarderCreated(clone, parent);
}
}
|
[{"anonymous":false,"inputs":[{"indexed":false,"internalType":"address","name":"from","type":"address"},{"indexed":false,"internalType":"uint256","name":"value","type":"uint256"},{"indexed":false,"internalType":"bytes","name":"data","type":"bytes"}],"name":"ForwarderDeposited","type":"event"},{"stateMutability":"payable","type":"fallback"},{"inputs":[],"name":"flush","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"address","name":"tokenContractAddress","type":"address"}],"name":"flushTokens","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"address","name":"_parentAddress","type":"address"}],"name":"init","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[],"name":"parentAddress","outputs":[{"internalType":"address","name":"","type":"address"}],"stateMutability":"view","type":"function"},{"stateMutability":"payable","type":"receive"}]
|
v0.7.5+commit.eb77ed08
| false
| 200
|
Default
|
Apache-2.0
| false
|
ipfs://934a7b5f246917d20f5e049b9344e4f3d923110c9d150ea2a4118848dd414bc3
|
|||
UserWallet
|
0x8df381c569e4e834df08622dc4ca967d072138a0
|
Solidity
|
pragma solidity ^0.4.10;
// Copyright 2017 Bittrex
contract AbstractSweeper {
function sweep(address token, uint amount) returns (bool);
function () { throw; }
Controller controller;
function AbstractSweeper(address _controller) {
controller = Controller(_controller);
}
modifier canSweep() {
if (msg.sender != controller.authorizedCaller() && msg.sender != controller.owner()) throw;
if (controller.halted()) throw;
_;
}
}
contract Token {
function balanceOf(address a) returns (uint) {
(a);
return 0;
}
function transfer(address a, uint val) returns (bool) {
(a);
(val);
return false;
}
}
contract DefaultSweeper is AbstractSweeper {
function DefaultSweeper(address controller)
AbstractSweeper(controller) {}
function sweep(address _token, uint _amount)
canSweep
returns (bool) {
bool success = false;
address destination = controller.destination();
if (_token != address(0)) {
Token token = Token(_token);
uint amount = _amount;
if (amount > token.balanceOf(this)) {
return false;
}
success = token.transfer(destination, amount);
}
else {
uint amountInWei = _amount;
if (amountInWei > this.balance) {
return false;
}
success = destination.send(amountInWei);
}
if (success) {
controller.logSweep(this, destination, _token, _amount);
}
return success;
}
}
contract UserWallet {
AbstractSweeperList sweeperList;
function UserWallet(address _sweeperlist) {
sweeperList = AbstractSweeperList(_sweeperlist);
}
function () public payable { }
function tokenFallback(address _from, uint _value, bytes _data) {
(_from);
(_value);
(_data);
}
function sweep(address _token, uint _amount)
returns (bool) {
(_amount);
return sweeperList.sweeperOf(_token).delegatecall(msg.data);
}
}
contract AbstractSweeperList {
function sweeperOf(address _token) returns (address);
}
contract Controller is AbstractSweeperList {
address public owner;
address public authorizedCaller;
address public destination;
bool public halted;
event LogNewWallet(address receiver);
event LogSweep(address indexed from, address indexed to, address indexed token, uint amount);
modifier onlyOwner() {
if (msg.sender != owner) throw;
_;
}
modifier onlyAuthorizedCaller() {
if (msg.sender != authorizedCaller) throw;
_;
}
modifier onlyAdmins() {
if (msg.sender != authorizedCaller && msg.sender != owner) throw;
_;
}
function Controller()
{
owner = msg.sender;
destination = msg.sender;
authorizedCaller = msg.sender;
}
function changeAuthorizedCaller(address _newCaller) onlyOwner {
authorizedCaller = _newCaller;
}
function changeDestination(address _dest) onlyOwner {
destination = _dest;
}
function changeOwner(address _owner) onlyOwner {
owner = _owner;
}
function makeWallet() onlyAdmins returns (address wallet) {
wallet = address(new UserWallet(this));
LogNewWallet(wallet);
}
function halt() onlyAdmins {
halted = true;
}
function start() onlyOwner {
halted = false;
}
address public defaultSweeper = address(new DefaultSweeper(this));
mapping (address => address) sweepers;
function addSweeper(address _token, address _sweeper) onlyOwner {
sweepers[_token] = _sweeper;
}
function sweeperOf(address _token) returns (address) {
address sweeper = sweepers[_token];
if (sweeper == 0) sweeper = defaultSweeper;
return sweeper;
}
function logSweep(address from, address to, address token, uint amount) {
LogSweep(from, to, token, amount);
}
}
|
[{"constant":false,"inputs":[{"name":"_token","type":"address"},{"name":"_amount","type":"uint256"}],"name":"sweep","outputs":[{"name":"","type":"bool"}],"payable":false,"type":"function"},{"constant":false,"inputs":[{"name":"_from","type":"address"},{"name":"_value","type":"uint256"},{"name":"_data","type":"bytes"}],"name":"tokenFallback","outputs":[],"payable":false,"type":"function"},{"inputs":[{"name":"_sweeperlist","type":"address"}],"payable":false,"type":"constructor"},{"payable":true,"type":"fallback"}]
|
v0.4.11+commit.68ef5810
| true
| 200
|
000000000000000000000000a3C1E324CA1ce40db73eD6026c4A177F099B5770
|
Default
| false
|
bzzr://4cdd69fdcf3cf6cbee9677fe380fa5f044048aa9e060ec5619a21ca5a5bd4cd1
|
|||
UserWallet
|
0x194a198bdc5559d783c99e6121d6602da4fb88db
|
Solidity
|
pragma solidity ^0.4.10;
// Copyright 2017 Bittrex
contract AbstractSweeper {
function sweep(address token, uint amount) returns (bool);
function () { throw; }
Controller controller;
function AbstractSweeper(address _controller) {
controller = Controller(_controller);
}
modifier canSweep() {
if (msg.sender != controller.authorizedCaller() && msg.sender != controller.owner()) throw;
if (controller.halted()) throw;
_;
}
}
contract Token {
function balanceOf(address a) returns (uint) {
(a);
return 0;
}
function transfer(address a, uint val) returns (bool) {
(a);
(val);
return false;
}
}
contract DefaultSweeper is AbstractSweeper {
function DefaultSweeper(address controller)
AbstractSweeper(controller) {}
function sweep(address _token, uint _amount)
canSweep
returns (bool) {
bool success = false;
address destination = controller.destination();
if (_token != address(0)) {
Token token = Token(_token);
uint amount = _amount;
if (amount > token.balanceOf(this)) {
return false;
}
success = token.transfer(destination, amount);
}
else {
uint amountInWei = _amount;
if (amountInWei > this.balance) {
return false;
}
success = destination.send(amountInWei);
}
if (success) {
controller.logSweep(this, destination, _token, _amount);
}
return success;
}
}
contract UserWallet {
AbstractSweeperList sweeperList;
function UserWallet(address _sweeperlist) {
sweeperList = AbstractSweeperList(_sweeperlist);
}
function () public payable { }
function tokenFallback(address _from, uint _value, bytes _data) {
(_from);
(_value);
(_data);
}
function sweep(address _token, uint _amount)
returns (bool) {
(_amount);
return sweeperList.sweeperOf(_token).delegatecall(msg.data);
}
}
contract AbstractSweeperList {
function sweeperOf(address _token) returns (address);
}
contract Controller is AbstractSweeperList {
address public owner;
address public authorizedCaller;
address public destination;
bool public halted;
event LogNewWallet(address receiver);
event LogSweep(address indexed from, address indexed to, address indexed token, uint amount);
modifier onlyOwner() {
if (msg.sender != owner) throw;
_;
}
modifier onlyAuthorizedCaller() {
if (msg.sender != authorizedCaller) throw;
_;
}
modifier onlyAdmins() {
if (msg.sender != authorizedCaller && msg.sender != owner) throw;
_;
}
function Controller()
{
owner = msg.sender;
destination = msg.sender;
authorizedCaller = msg.sender;
}
function changeAuthorizedCaller(address _newCaller) onlyOwner {
authorizedCaller = _newCaller;
}
function changeDestination(address _dest) onlyOwner {
destination = _dest;
}
function changeOwner(address _owner) onlyOwner {
owner = _owner;
}
function makeWallet() onlyAdmins returns (address wallet) {
wallet = address(new UserWallet(this));
LogNewWallet(wallet);
}
function halt() onlyAdmins {
halted = true;
}
function start() onlyOwner {
halted = false;
}
address public defaultSweeper = address(new DefaultSweeper(this));
mapping (address => address) sweepers;
function addSweeper(address _token, address _sweeper) onlyOwner {
sweepers[_token] = _sweeper;
}
function sweeperOf(address _token) returns (address) {
address sweeper = sweepers[_token];
if (sweeper == 0) sweeper = defaultSweeper;
return sweeper;
}
function logSweep(address from, address to, address token, uint amount) {
LogSweep(from, to, token, amount);
}
}
|
[{"constant":false,"inputs":[{"name":"_token","type":"address"},{"name":"_amount","type":"uint256"}],"name":"sweep","outputs":[{"name":"","type":"bool"}],"payable":false,"type":"function"},{"constant":false,"inputs":[{"name":"_from","type":"address"},{"name":"_value","type":"uint256"},{"name":"_data","type":"bytes"}],"name":"tokenFallback","outputs":[],"payable":false,"type":"function"},{"inputs":[{"name":"_sweeperlist","type":"address"}],"payable":false,"type":"constructor"},{"payable":true,"type":"fallback"}]
|
v0.4.11+commit.68ef5810
| true
| 200
|
000000000000000000000000a3C1E324CA1ce40db73eD6026c4A177F099B5770
|
Default
| false
|
bzzr://4cdd69fdcf3cf6cbee9677fe380fa5f044048aa9e060ec5619a21ca5a5bd4cd1
|
|||
UserWallet
|
0xe87229e01b20c1b7e96dc71248a54c3004af1099
|
Solidity
|
pragma solidity ^0.4.10;
// Copyright 2017 Bittrex
contract AbstractSweeper {
function sweep(address token, uint amount) returns (bool);
function () { throw; }
Controller controller;
function AbstractSweeper(address _controller) {
controller = Controller(_controller);
}
modifier canSweep() {
if (msg.sender != controller.authorizedCaller() && msg.sender != controller.owner()) throw;
if (controller.halted()) throw;
_;
}
}
contract Token {
function balanceOf(address a) returns (uint) {
(a);
return 0;
}
function transfer(address a, uint val) returns (bool) {
(a);
(val);
return false;
}
}
contract DefaultSweeper is AbstractSweeper {
function DefaultSweeper(address controller)
AbstractSweeper(controller) {}
function sweep(address _token, uint _amount)
canSweep
returns (bool) {
bool success = false;
address destination = controller.destination();
if (_token != address(0)) {
Token token = Token(_token);
uint amount = _amount;
if (amount > token.balanceOf(this)) {
return false;
}
success = token.transfer(destination, amount);
}
else {
uint amountInWei = _amount;
if (amountInWei > this.balance) {
return false;
}
success = destination.send(amountInWei);
}
if (success) {
controller.logSweep(this, destination, _token, _amount);
}
return success;
}
}
contract UserWallet {
AbstractSweeperList sweeperList;
function UserWallet(address _sweeperlist) {
sweeperList = AbstractSweeperList(_sweeperlist);
}
function () public payable { }
function tokenFallback(address _from, uint _value, bytes _data) {
(_from);
(_value);
(_data);
}
function sweep(address _token, uint _amount)
returns (bool) {
(_amount);
return sweeperList.sweeperOf(_token).delegatecall(msg.data);
}
}
contract AbstractSweeperList {
function sweeperOf(address _token) returns (address);
}
contract Controller is AbstractSweeperList {
address public owner;
address public authorizedCaller;
address public destination;
bool public halted;
event LogNewWallet(address receiver);
event LogSweep(address indexed from, address indexed to, address indexed token, uint amount);
modifier onlyOwner() {
if (msg.sender != owner) throw;
_;
}
modifier onlyAuthorizedCaller() {
if (msg.sender != authorizedCaller) throw;
_;
}
modifier onlyAdmins() {
if (msg.sender != authorizedCaller && msg.sender != owner) throw;
_;
}
function Controller()
{
owner = msg.sender;
destination = msg.sender;
authorizedCaller = msg.sender;
}
function changeAuthorizedCaller(address _newCaller) onlyOwner {
authorizedCaller = _newCaller;
}
function changeDestination(address _dest) onlyOwner {
destination = _dest;
}
function changeOwner(address _owner) onlyOwner {
owner = _owner;
}
function makeWallet() onlyAdmins returns (address wallet) {
wallet = address(new UserWallet(this));
LogNewWallet(wallet);
}
function halt() onlyAdmins {
halted = true;
}
function start() onlyOwner {
halted = false;
}
address public defaultSweeper = address(new DefaultSweeper(this));
mapping (address => address) sweepers;
function addSweeper(address _token, address _sweeper) onlyOwner {
sweepers[_token] = _sweeper;
}
function sweeperOf(address _token) returns (address) {
address sweeper = sweepers[_token];
if (sweeper == 0) sweeper = defaultSweeper;
return sweeper;
}
function logSweep(address from, address to, address token, uint amount) {
LogSweep(from, to, token, amount);
}
}
|
[{"constant":false,"inputs":[{"name":"_token","type":"address"},{"name":"_amount","type":"uint256"}],"name":"sweep","outputs":[{"name":"","type":"bool"}],"payable":false,"type":"function"},{"constant":false,"inputs":[{"name":"_from","type":"address"},{"name":"_value","type":"uint256"},{"name":"_data","type":"bytes"}],"name":"tokenFallback","outputs":[],"payable":false,"type":"function"},{"inputs":[{"name":"_sweeperlist","type":"address"}],"payable":false,"type":"constructor"},{"payable":true,"type":"fallback"}]
|
v0.4.11+commit.68ef5810
| true
| 200
|
000000000000000000000000a3C1E324CA1ce40db73eD6026c4A177F099B5770
|
Default
| false
|
bzzr://4cdd69fdcf3cf6cbee9677fe380fa5f044048aa9e060ec5619a21ca5a5bd4cd1
|
|||
Forwarder
|
0x28fba33cad723d775f17646ebae4293aa0bf7f55
|
Solidity
|
pragma solidity 0.7.5;
/*
The MIT License (MIT)
Copyright (c) 2018 Murray Software, LLC.
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.
*/
//solhint-disable max-line-length
//solhint-disable no-inline-assembly
contract CloneFactory {
function createClone(address target, bytes32 salt)
internal
returns (address payable result)
{
bytes20 targetBytes = bytes20(target);
assembly {
// load the next free memory slot as a place to store the clone contract data
let clone := mload(0x40)
// The bytecode block below is responsible for contract initialization
// during deployment, it is worth noting the proxied contract constructor will not be called during
// the cloning procedure and that is why an initialization function needs to be called after the
// clone is created
mstore(
clone,
0x3d602d80600a3d3981f3363d3d373d3d3d363d73000000000000000000000000
)
// This stores the address location of the implementation contract
// so that the proxy knows where to delegate call logic to
mstore(add(clone, 0x14), targetBytes)
// The bytecode block is the actual code that is deployed for each clone created.
// It forwards all calls to the already deployed implementation via a delegatecall
mstore(
add(clone, 0x28),
0x5af43d82803e903d91602b57fd5bf30000000000000000000000000000000000
)
// deploy the contract using the CREATE2 opcode
// this deploys the minimal proxy defined above, which will proxy all
// calls to use the logic defined in the implementation contract `target`
result := create2(0, clone, 0x37, salt)
}
}
function isClone(address target, address query)
internal
view
returns (bool result)
{
bytes20 targetBytes = bytes20(target);
assembly {
// load the next free memory slot as a place to store the comparison clone
let clone := mload(0x40)
// The next three lines store the expected bytecode for a miniml proxy
// that targets `target` as its implementation contract
mstore(
clone,
0x363d3d373d3d3d363d7300000000000000000000000000000000000000000000
)
mstore(add(clone, 0xa), targetBytes)
mstore(
add(clone, 0x1e),
0x5af43d82803e903d91602b57fd5bf30000000000000000000000000000000000
)
// the next two lines store the bytecode of the contract that we are checking in memory
let other := add(clone, 0x40)
extcodecopy(query, other, 0, 0x2d)
// Check if the expected bytecode equals the actual bytecode and return the result
result := and(
eq(mload(clone), mload(other)),
eq(mload(add(clone, 0xd)), mload(add(other, 0xd)))
)
}
}
}
/**
* Contract that exposes the needed erc20 token functions
*/
abstract contract ERC20Interface {
// Send _value amount of tokens to address _to
function transfer(address _to, uint256 _value)
public
virtual
returns (bool success);
// Get the account balance of another account with address _owner
function balanceOf(address _owner)
public
virtual
view
returns (uint256 balance);
}
// helper methods for interacting with ERC20 tokens and sending ETH that do not consistently return true/false
library TransferHelper {
function safeApprove(
address token,
address to,
uint256 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::safeApprove: approve failed'
);
}
function safeTransfer(
address token,
address to,
uint256 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::safeTransfer: transfer failed'
);
}
function safeTransferFrom(
address token,
address from,
address to,
uint256 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::transferFrom: transferFrom failed'
);
}
function safeTransferETH(address to, uint256 value) internal {
(bool success, ) = to.call{value: value}(new bytes(0));
require(success, 'TransferHelper::safeTransferETH: ETH transfer failed');
}
}
/**
* Contract that will forward any incoming Ether to the creator of the contract
*
*/
contract Forwarder {
// Address to which any funds sent to this contract will be forwarded
address public parentAddress;
event ForwarderDeposited(address from, uint256 value, bytes data);
/**
* Initialize the contract, and sets the destination address to that of the creator
*/
function init(address _parentAddress) external onlyUninitialized {
parentAddress = _parentAddress;
uint256 value = address(this).balance;
if (value == 0) {
return;
}
(bool success, ) = parentAddress.call{ value: value }('');
require(success, 'Flush failed');
// NOTE: since we are forwarding on initialization,
// we don't have the context of the original sender.
// We still emit an event about the forwarding but set
// the sender to the forwarder itself
emit ForwarderDeposited(address(this), value, msg.data);
}
/**
* Modifier that will execute internal code block only if the sender is the parent address
*/
modifier onlyParent {
require(msg.sender == parentAddress, 'Only Parent');
_;
}
/**
* Modifier that will execute internal code block only if the contract has not been initialized yet
*/
modifier onlyUninitialized {
require(parentAddress == address(0x0), 'Already initialized');
_;
}
/**
* Default function; Gets called when data is sent but does not match any other function
*/
fallback() external payable {
flush();
}
/**
* Default function; Gets called when Ether is deposited with no data, and forwards it to the parent address
*/
receive() external payable {
flush();
}
/**
* Execute a token transfer of the full balance from the forwarder token to the parent address
* @param tokenContractAddress the address of the erc20 token contract
*/
function flushTokens(address tokenContractAddress) external onlyParent {
ERC20Interface instance = ERC20Interface(tokenContractAddress);
address forwarderAddress = address(this);
uint256 forwarderBalance = instance.balanceOf(forwarderAddress);
if (forwarderBalance == 0) {
return;
}
TransferHelper.safeTransfer(
tokenContractAddress,
parentAddress,
forwarderBalance
);
}
/**
* Flush the entire balance of the contract to the parent address.
*/
function flush() public {
uint256 value = address(this).balance;
if (value == 0) {
return;
}
(bool success, ) = parentAddress.call{ value: value }('');
require(success, 'Flush failed');
emit ForwarderDeposited(msg.sender, value, msg.data);
}
}
contract ForwarderFactory is CloneFactory {
address public implementationAddress;
event ForwarderCreated(address newForwarderAddress, address parentAddress);
constructor(address _implementationAddress) {
implementationAddress = _implementationAddress;
}
function createForwarder(address parent, bytes32 salt) external {
// include the signers in the salt so any contract deployed to a given address must have the same signers
bytes32 finalSalt = keccak256(abi.encodePacked(parent, salt));
address payable clone = createClone(implementationAddress, finalSalt);
Forwarder(clone).init(parent);
emit ForwarderCreated(clone, parent);
}
}
|
[{"anonymous":false,"inputs":[{"indexed":false,"internalType":"address","name":"from","type":"address"},{"indexed":false,"internalType":"uint256","name":"value","type":"uint256"},{"indexed":false,"internalType":"bytes","name":"data","type":"bytes"}],"name":"ForwarderDeposited","type":"event"},{"stateMutability":"payable","type":"fallback"},{"inputs":[],"name":"flush","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"address","name":"tokenContractAddress","type":"address"}],"name":"flushTokens","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"address","name":"_parentAddress","type":"address"}],"name":"init","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[],"name":"parentAddress","outputs":[{"internalType":"address","name":"","type":"address"}],"stateMutability":"view","type":"function"},{"stateMutability":"payable","type":"receive"}]
|
v0.7.5+commit.eb77ed08
| false
| 200
|
Default
|
Apache-2.0
| false
|
ipfs://934a7b5f246917d20f5e049b9344e4f3d923110c9d150ea2a4118848dd414bc3
|
|||
Forwarder
|
0x918110ca9e1cc405a93203dfd362f5a584829fc3
|
Solidity
|
pragma solidity ^0.4.14;
/**
* Contract that exposes the needed erc20 token functions
*/
contract ERC20Interface {
// Send _value amount of tokens to address _to
function transfer(address _to, uint256 _value) returns (bool success);
// Get the account balance of another account with address _owner
function balanceOf(address _owner) constant returns (uint256 balance);
}
/**
* Contract that will forward any incoming Ether to its creator
*/
contract Forwarder {
// Address to which any funds sent to this contract will be forwarded
address public parentAddress;
event ForwarderDeposited(address from, uint value, bytes data);
event TokensFlushed(
address tokenContractAddress, // The contract address of the token
uint value // Amount of token sent
);
/**
* Create the contract, and set the destination address to that of the creator
*/
function Forwarder() {
parentAddress = msg.sender;
}
/**
* Modifier that will execute internal code block only if the sender is a parent of the forwarder contract
*/
modifier onlyParent {
if (msg.sender != parentAddress) {
throw;
}
_;
}
/**
* Default function; Gets called when Ether is deposited, and forwards it to the destination address
*/
function() payable {
if (!parentAddress.call.value(msg.value)(msg.data))
throw;
// Fire off the deposited event if we can forward it
ForwarderDeposited(msg.sender, msg.value, msg.data);
}
/**
* Execute a token transfer of the full balance from the forwarder token to the main wallet contract
* @param tokenContractAddress the address of the erc20 token contract
*/
function flushTokens(address tokenContractAddress) onlyParent {
ERC20Interface instance = ERC20Interface(tokenContractAddress);
var forwarderAddress = address(this);
var forwarderBalance = instance.balanceOf(forwarderAddress);
if (forwarderBalance == 0) {
return;
}
if (!instance.transfer(parentAddress, forwarderBalance)) {
throw;
}
TokensFlushed(tokenContractAddress, forwarderBalance);
}
/**
* It is possible that funds were sent to this address before the contract was deployed.
* We can flush those funds to the destination address.
*/
function flush() {
if (!parentAddress.call.value(this.balance)())
throw;
}
}
/**
* Basic multi-signer wallet designed for use in a co-signing environment where 2 signatures are required to move funds.
* Typically used in a 2-of-3 signing configuration. Uses ecrecover to allow for 2 signatures in a single transaction.
*/
contract WalletSimple {
// Events
event Deposited(address from, uint value, bytes data);
event SafeModeActivated(address msgSender);
event Transacted(
address msgSender, // Address of the sender of the message initiating the transaction
address otherSigner, // Address of the signer (second signature) used to initiate the transaction
bytes32 operation, // Operation hash (sha3 of toAddress, value, data, expireTime, sequenceId)
address toAddress, // The address the transaction was sent to
uint value, // Amount of Wei sent to the address
bytes data // Data sent when invoking the transaction
);
event TokenTransacted(
address msgSender, // Address of the sender of the message initiating the transaction
address otherSigner, // Address of the signer (second signature) used to initiate the transaction
bytes32 operation, // Operation hash (sha3 of toAddress, value, tokenContractAddress, expireTime, sequenceId)
address toAddress, // The address the transaction was sent to
uint value, // Amount of token sent
address tokenContractAddress // The contract address of the token
);
// Public fields
address[] public signers; // The addresses that can co-sign transactions on the wallet
bool public safeMode = false; // When active, wallet may only send to signer addresses
// Internal fields
uint constant SEQUENCE_ID_WINDOW_SIZE = 10;
uint[10] recentSequenceIds;
/**
* Modifier that will execute internal code block only if the sender is an authorized signer on this wallet
*/
modifier onlysigner {
if (!isSigner(msg.sender)) {
throw;
}
_;
}
/**
* Set up a simple multi-sig wallet by specifying the signers allowed to be used on this wallet.
* 2 signers will be required to send a transaction from this wallet.
* Note: The sender is NOT automatically added to the list of signers.
* Signers CANNOT be changed once they are set
*
* @param allowedSigners An array of signers on the wallet
*/
function WalletSimple(address[] allowedSigners) {
if (allowedSigners.length != 3) {
// Invalid number of signers
throw;
}
signers = allowedSigners;
}
/**
* Gets called when a transaction is received without calling a method
*/
function() payable {
if (msg.value > 0) {
// Fire deposited event if we are receiving funds
Deposited(msg.sender, msg.value, msg.data);
}
}
/**
* Create a new contract (and also address) that forwards funds to this contract
* returns address of newly created forwarder address
*/
function createForwarder() onlysigner returns (address) {
return new Forwarder();
}
/**
* Execute a multi-signature transaction from this wallet using 2 signers: one from msg.sender and the other from ecrecover.
* The signature is a signed form (using eth.sign) of tightly packed toAddress, value, data, expireTime and sequenceId
* Sequence IDs are numbers starting from 1. They are used to prevent replay attacks and may not be repeated.
*
* @param toAddress the destination address to send an outgoing transaction
* @param value the amount in Wei to be sent
* @param data the data to send to the toAddress when invoking the transaction
* @param expireTime the number of seconds since 1970 for which this transaction is valid
* @param sequenceId the unique sequence id obtainable from getNextSequenceId
* @param signature the result of eth.sign on the operationHash sha3(toAddress, value, data, expireTime, sequenceId)
*/
function sendMultiSig(address toAddress, uint value, bytes data, uint expireTime, uint sequenceId, bytes signature) onlysigner {
// Verify the other signer
var operationHash = sha3("ETHER", toAddress, value, data, expireTime, sequenceId);
var otherSigner = verifyMultiSig(toAddress, operationHash, signature, expireTime, sequenceId);
// Success, send the transaction
if (!(toAddress.call.value(value)(data))) {
// Failed executing transaction
throw;
}
Transacted(msg.sender, otherSigner, operationHash, toAddress, value, data);
}
/**
* Execute a multi-signature token transfer from this wallet using 2 signers: one from msg.sender and the other from ecrecover.
* The signature is a signed form (using eth.sign) of tightly packed toAddress, value, tokenContractAddress, expireTime and sequenceId
* Sequence IDs are numbers starting from 1. They are used to prevent replay attacks and may not be repeated.
*
* @param toAddress the destination address to send an outgoing transaction
* @param value the amount in tokens to be sent
* @param tokenContractAddress the address of the erc20 token contract
* @param expireTime the number of seconds since 1970 for which this transaction is valid
* @param sequenceId the unique sequence id obtainable from getNextSequenceId
* @param signature the result of eth.sign on the operationHash sha3(toAddress, value, tokenContractAddress, expireTime, sequenceId)
*/
function sendMultiSigToken(address toAddress, uint value, address tokenContractAddress, uint expireTime, uint sequenceId, bytes signature) onlysigner {
// Verify the other signer
var operationHash = sha3("ERC20", toAddress, value, tokenContractAddress, expireTime, sequenceId);
var otherSigner = verifyMultiSig(toAddress, operationHash, signature, expireTime, sequenceId);
ERC20Interface instance = ERC20Interface(tokenContractAddress);
if (!instance.transfer(toAddress, value)) {
throw;
}
TokenTransacted(msg.sender, otherSigner, operationHash, toAddress, value, tokenContractAddress);
}
/**
* Execute a token flush from one of the forwarder addresses. This transfer needs only a single signature and can be done by any signer
*
* @param forwarderAddress the address of the forwarder address to flush the tokens from
* @param tokenContractAddress the address of the erc20 token contract
*/
function flushForwarderTokens(address forwarderAddress, address tokenContractAddress) onlysigner {
Forwarder forwarder = Forwarder(forwarderAddress);
forwarder.flushTokens(tokenContractAddress);
}
/**
* Do common multisig verification for both eth sends and erc20token transfers
*
* @param toAddress the destination address to send an outgoing transaction
* @param operationHash the sha3 of the toAddress, value, data/tokenContractAddress and expireTime
* @param signature the tightly packed signature of r, s, and v as an array of 65 bytes (returned by eth.sign)
* @param expireTime the number of seconds since 1970 for which this transaction is valid
* @param sequenceId the unique sequence id obtainable from getNextSequenceId
* returns address of the address to send tokens or eth to
*/
function verifyMultiSig(address toAddress, bytes32 operationHash, bytes signature, uint expireTime, uint sequenceId) private returns (address) {
var otherSigner = recoverAddressFromSignature(operationHash, signature);
// Verify if we are in safe mode. In safe mode, the wallet can only send to signers
if (safeMode && !isSigner(toAddress)) {
// We are in safe mode and the toAddress is not a signer. Disallow!
throw;
}
// Verify that the transaction has not expired
if (expireTime < block.timestamp) {
// Transaction expired
throw;
}
// Try to insert the sequence ID. Will throw if the sequence id was invalid
tryInsertSequenceId(sequenceId);
if (!isSigner(otherSigner)) {
// Other signer not on this wallet or operation does not match arguments
throw;
}
if (otherSigner == msg.sender) {
// Cannot approve own transaction
throw;
}
return otherSigner;
}
/**
* Irrevocably puts contract into safe mode. When in this mode, transactions may only be sent to signing addresses.
*/
function activateSafeMode() onlysigner {
safeMode = true;
SafeModeActivated(msg.sender);
}
/**
* Determine if an address is a signer on this wallet
* @param signer address to check
* returns boolean indicating whether address is signer or not
*/
function isSigner(address signer) returns (bool) {
// Iterate through all signers on the wallet and
for (uint i = 0; i < signers.length; i++) {
if (signers[i] == signer) {
return true;
}
}
return false;
}
/**
* Gets the second signer's address using ecrecover
* @param operationHash the sha3 of the toAddress, value, data/tokenContractAddress and expireTime
* @param signature the tightly packed signature of r, s, and v as an array of 65 bytes (returned by eth.sign)
* returns address recovered from the signature
*/
function recoverAddressFromSignature(bytes32 operationHash, bytes signature) private returns (address) {
if (signature.length != 65) {
throw;
}
// We need to unpack the signature, which is given as an array of 65 bytes (from eth.sign)
bytes32 r;
bytes32 s;
uint8 v;
assembly {
r := mload(add(signature, 32))
s := mload(add(signature, 64))
v := and(mload(add(signature, 65)), 255)
}
if (v < 27) {
v += 27; // Ethereum versions are 27 or 28 as opposed to 0 or 1 which is submitted by some signing libs
}
return ecrecover(operationHash, v, r, s);
}
/**
* Verify that the sequence id has not been used before and inserts it. Throws if the sequence ID was not accepted.
* We collect a window of up to 10 recent sequence ids, and allow any sequence id that is not in the window and
* greater than the minimum element in the window.
* @param sequenceId to insert into array of stored ids
*/
function tryInsertSequenceId(uint sequenceId) onlysigner private {
// Keep a pointer to the lowest value element in the window
uint lowestValueIndex = 0;
for (uint i = 0; i < SEQUENCE_ID_WINDOW_SIZE; i++) {
if (recentSequenceIds[i] == sequenceId) {
// This sequence ID has been used before. Disallow!
throw;
}
if (recentSequenceIds[i] < recentSequenceIds[lowestValueIndex]) {
lowestValueIndex = i;
}
}
if (sequenceId < recentSequenceIds[lowestValueIndex]) {
// The sequence ID being used is lower than the lowest value in the window
// so we cannot accept it as it may have been used before
throw;
}
if (sequenceId > (recentSequenceIds[lowestValueIndex] + 10000)) {
// Block sequence IDs which are much higher than the lowest value
// This prevents people blocking the contract by using very large sequence IDs quickly
throw;
}
recentSequenceIds[lowestValueIndex] = sequenceId;
}
/**
* Gets the next available sequence ID for signing when using executeAndConfirm
* returns the sequenceId one higher than the highest currently stored
*/
function getNextSequenceId() returns (uint) {
uint highestSequenceId = 0;
for (uint i = 0; i < SEQUENCE_ID_WINDOW_SIZE; i++) {
if (recentSequenceIds[i] > highestSequenceId) {
highestSequenceId = recentSequenceIds[i];
}
}
return highestSequenceId + 1;
}
}
|
[{"constant":true,"inputs":[],"name":"parentAddress","outputs":[{"name":"","type":"address"}],"payable":false,"type":"function"},{"constant":false,"inputs":[{"name":"tokenContractAddress","type":"address"}],"name":"flushTokens","outputs":[],"payable":false,"type":"function"},{"constant":false,"inputs":[],"name":"flush","outputs":[],"payable":false,"type":"function"},{"inputs":[],"payable":false,"type":"constructor"},{"payable":true,"type":"fallback"},{"anonymous":false,"inputs":[{"indexed":false,"name":"from","type":"address"},{"indexed":false,"name":"value","type":"uint256"},{"indexed":false,"name":"data","type":"bytes"}],"name":"ForwarderDeposited","type":"event"},{"anonymous":false,"inputs":[{"indexed":false,"name":"tokenContractAddress","type":"address"},{"indexed":false,"name":"value","type":"uint256"}],"name":"TokensFlushed","type":"event"}]
|
v0.4.16-nightly.2017.8.11+commit.c84de7fa
| true
| 200
|
Default
| false
|
bzzr://d0f8838ba17108a895d34ae8ef3bff4e0dc9d639c3c51921fee1d17eaa803721
|
||||
UserWallet
|
0xc48cb6b950c604ce87e7fdb9c325621c322e0b67
|
Solidity
|
pragma solidity ^0.4.10;
// Copyright 2017 Bittrex
contract AbstractSweeper {
function sweep(address token, uint amount) returns (bool);
function () { throw; }
Controller controller;
function AbstractSweeper(address _controller) {
controller = Controller(_controller);
}
modifier canSweep() {
if (msg.sender != controller.authorizedCaller() && msg.sender != controller.owner()) throw;
if (controller.halted()) throw;
_;
}
}
contract Token {
function balanceOf(address a) returns (uint) {
(a);
return 0;
}
function transfer(address a, uint val) returns (bool) {
(a);
(val);
return false;
}
}
contract DefaultSweeper is AbstractSweeper {
function DefaultSweeper(address controller)
AbstractSweeper(controller) {}
function sweep(address _token, uint _amount)
canSweep
returns (bool) {
bool success = false;
address destination = controller.destination();
if (_token != address(0)) {
Token token = Token(_token);
uint amount = _amount;
if (amount > token.balanceOf(this)) {
return false;
}
success = token.transfer(destination, amount);
}
else {
uint amountInWei = _amount;
if (amountInWei > this.balance) {
return false;
}
success = destination.send(amountInWei);
}
if (success) {
controller.logSweep(this, destination, _token, _amount);
}
return success;
}
}
contract UserWallet {
AbstractSweeperList sweeperList;
function UserWallet(address _sweeperlist) {
sweeperList = AbstractSweeperList(_sweeperlist);
}
function () public payable { }
function tokenFallback(address _from, uint _value, bytes _data) {
(_from);
(_value);
(_data);
}
function sweep(address _token, uint _amount)
returns (bool) {
(_amount);
return sweeperList.sweeperOf(_token).delegatecall(msg.data);
}
}
contract AbstractSweeperList {
function sweeperOf(address _token) returns (address);
}
contract Controller is AbstractSweeperList {
address public owner;
address public authorizedCaller;
address public destination;
bool public halted;
event LogNewWallet(address receiver);
event LogSweep(address indexed from, address indexed to, address indexed token, uint amount);
modifier onlyOwner() {
if (msg.sender != owner) throw;
_;
}
modifier onlyAuthorizedCaller() {
if (msg.sender != authorizedCaller) throw;
_;
}
modifier onlyAdmins() {
if (msg.sender != authorizedCaller && msg.sender != owner) throw;
_;
}
function Controller()
{
owner = msg.sender;
destination = msg.sender;
authorizedCaller = msg.sender;
}
function changeAuthorizedCaller(address _newCaller) onlyOwner {
authorizedCaller = _newCaller;
}
function changeDestination(address _dest) onlyOwner {
destination = _dest;
}
function changeOwner(address _owner) onlyOwner {
owner = _owner;
}
function makeWallet() onlyAdmins returns (address wallet) {
wallet = address(new UserWallet(this));
LogNewWallet(wallet);
}
function halt() onlyAdmins {
halted = true;
}
function start() onlyOwner {
halted = false;
}
address public defaultSweeper = address(new DefaultSweeper(this));
mapping (address => address) sweepers;
function addSweeper(address _token, address _sweeper) onlyOwner {
sweepers[_token] = _sweeper;
}
function sweeperOf(address _token) returns (address) {
address sweeper = sweepers[_token];
if (sweeper == 0) sweeper = defaultSweeper;
return sweeper;
}
function logSweep(address from, address to, address token, uint amount) {
LogSweep(from, to, token, amount);
}
}
|
[{"constant":false,"inputs":[{"name":"_token","type":"address"},{"name":"_amount","type":"uint256"}],"name":"sweep","outputs":[{"name":"","type":"bool"}],"payable":false,"type":"function"},{"constant":false,"inputs":[{"name":"_from","type":"address"},{"name":"_value","type":"uint256"},{"name":"_data","type":"bytes"}],"name":"tokenFallback","outputs":[],"payable":false,"type":"function"},{"inputs":[{"name":"_sweeperlist","type":"address"}],"payable":false,"type":"constructor"},{"payable":true,"type":"fallback"}]
|
v0.4.11+commit.68ef5810
| true
| 200
|
000000000000000000000000a3C1E324CA1ce40db73eD6026c4A177F099B5770
|
Default
| false
|
bzzr://4cdd69fdcf3cf6cbee9677fe380fa5f044048aa9e060ec5619a21ca5a5bd4cd1
|
|||
DSProxy
|
0xc61765d2ad9c0f4bed2a77f4aa4ad9c3f3a3fbbf
|
Solidity
|
// proxy.sol - execute actions atomically through the proxy's identity
// Copyright (C) 2017 DappHub, LLC
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
// You should have received a copy of the GNU General Public License
// along with this program. If not, see <http://www.gnu.org/licenses/>.
pragma solidity ^0.4.23;
contract DSAuthority {
function canCall(
address src, address dst, bytes4 sig
) public view returns (bool);
}
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(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, this, sig);
}
}
}
contract DSNote {
event LogNote(
bytes4 indexed sig,
address indexed guy,
bytes32 indexed foo,
bytes32 indexed bar,
uint 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);
_;
}
}
// DSProxy
// Allows code execution using a persistant identity This can be very
// useful to execute a sequence of atomic actions. Since the owner of
// the proxy can be changed, this allows for dynamic ownership models
// i.e. a multisig
contract DSProxy is DSAuth, DSNote {
DSProxyCache public cache; // global cache for contracts
constructor(address _cacheAddr) public {
require(setCache(_cacheAddr));
}
function() public payable {
}
// use the proxy to execute calldata _data on contract _code
function execute(bytes _code, bytes _data)
public
payable
returns (address target, bytes32 response)
{
target = cache.read(_code);
if (target == 0x0) {
// deploy contract & store its address in cache
target = cache.write(_code);
}
response = execute(target, _data);
}
function execute(address _target, bytes _data)
public
auth
note
payable
returns (bytes32 response)
{
require(_target != 0x0);
// call contract in current context
assembly {
let succeeded := delegatecall(sub(gas, 5000), _target, add(_data, 0x20), mload(_data), 0, 32)
response := mload(0) // load delegatecall output
switch iszero(succeeded)
case 1 {
// throw if delegatecall failed
revert(0, 0)
}
}
}
//set new cache
function setCache(address _cacheAddr)
public
auth
note
returns (bool)
{
require(_cacheAddr != 0x0); // invalid cache address
cache = DSProxyCache(_cacheAddr); // overwrite cache
return true;
}
}
// DSProxyFactory
// This factory deploys new proxy instances through build()
// Deployed proxy addresses are logged
contract DSProxyFactory {
event Created(address indexed sender, address indexed owner, address proxy, address cache);
mapping(address=>bool) public isProxy;
DSProxyCache public cache = new DSProxyCache();
// deploys a new proxy instance
// sets owner of proxy to caller
function build() public returns (DSProxy proxy) {
proxy = build(msg.sender);
}
// deploys a new proxy instance
// sets custom owner of proxy
function build(address owner) public returns (DSProxy proxy) {
proxy = new DSProxy(cache);
emit Created(msg.sender, owner, address(proxy), address(cache));
proxy.setOwner(owner);
isProxy[proxy] = true;
}
}
// DSProxyCache
// This global cache stores addresses of contracts previously deployed
// by a proxy. This saves gas from repeat deployment of the same
// contracts and eliminates blockchain bloat.
// By default, all proxies deployed from the same factory store
// contracts in the same cache. The cache a proxy instance uses can be
// changed. The cache uses the sha3 hash of a contract's bytecode to
// lookup the address
contract DSProxyCache {
mapping(bytes32 => address) cache;
function read(bytes _code) public view returns (address) {
bytes32 hash = keccak256(_code);
return cache[hash];
}
function write(bytes _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;
}
}
|
[{"constant":false,"inputs":[{"name":"owner_","type":"address"}],"name":"setOwner","outputs":[],"payable":false,"stateMutability":"nonpayable","type":"function"},{"constant":false,"inputs":[{"name":"_target","type":"address"},{"name":"_data","type":"bytes"}],"name":"execute","outputs":[{"name":"response","type":"bytes32"}],"payable":true,"stateMutability":"payable","type":"function"},{"constant":false,"inputs":[{"name":"_code","type":"bytes"},{"name":"_data","type":"bytes"}],"name":"execute","outputs":[{"name":"target","type":"address"},{"name":"response","type":"bytes32"}],"payable":true,"stateMutability":"payable","type":"function"},{"constant":true,"inputs":[],"name":"cache","outputs":[{"name":"","type":"address"}],"payable":false,"stateMutability":"view","type":"function"},{"constant":false,"inputs":[{"name":"authority_","type":"address"}],"name":"setAuthority","outputs":[],"payable":false,"stateMutability":"nonpayable","type":"function"},{"constant":true,"inputs":[],"name":"owner","outputs":[{"name":"","type":"address"}],"payable":false,"stateMutability":"view","type":"function"},{"constant":false,"inputs":[{"name":"_cacheAddr","type":"address"}],"name":"setCache","outputs":[{"name":"","type":"bool"}],"payable":false,"stateMutability":"nonpayable","type":"function"},{"constant":true,"inputs":[],"name":"authority","outputs":[{"name":"","type":"address"}],"payable":false,"stateMutability":"view","type":"function"},{"inputs":[{"name":"_cacheAddr","type":"address"}],"payable":false,"stateMutability":"nonpayable","type":"constructor"},{"payable":true,"stateMutability":"payable","type":"fallback"},{"anonymous":true,"inputs":[{"indexed":true,"name":"sig","type":"bytes4"},{"indexed":true,"name":"guy","type":"address"},{"indexed":true,"name":"foo","type":"bytes32"},{"indexed":true,"name":"bar","type":"bytes32"},{"indexed":false,"name":"wad","type":"uint256"},{"indexed":false,"name":"fax","type":"bytes"}],"name":"LogNote","type":"event"},{"anonymous":false,"inputs":[{"indexed":true,"name":"authority","type":"address"}],"name":"LogSetAuthority","type":"event"},{"anonymous":false,"inputs":[{"indexed":true,"name":"owner","type":"address"}],"name":"LogSetOwner","type":"event"}]
|
v0.4.23+commit.124ca40d
| true
| 200
|
000000000000000000000000271293c67e2d3140a0e9381eff1f9b01e07b0795
|
Default
| false
|
bzzr://e498874c9ba9e75028e0c84f1b1d83b2dad5de910c59b837b32e5a190794c5e1
|
|||
UserWallet
|
0x0d8c07e25534124dec0f90a1ae5d222299851239
|
Solidity
|
pragma solidity ^0.4.10;
// Copyright 2017 Bittrex
contract AbstractSweeper {
function sweep(address token, uint amount) returns (bool);
function () { throw; }
Controller controller;
function AbstractSweeper(address _controller) {
controller = Controller(_controller);
}
modifier canSweep() {
if (msg.sender != controller.authorizedCaller() && msg.sender != controller.owner()) throw;
if (controller.halted()) throw;
_;
}
}
contract Token {
function balanceOf(address a) returns (uint) {
(a);
return 0;
}
function transfer(address a, uint val) returns (bool) {
(a);
(val);
return false;
}
}
contract DefaultSweeper is AbstractSweeper {
function DefaultSweeper(address controller)
AbstractSweeper(controller) {}
function sweep(address _token, uint _amount)
canSweep
returns (bool) {
bool success = false;
address destination = controller.destination();
if (_token != address(0)) {
Token token = Token(_token);
uint amount = _amount;
if (amount > token.balanceOf(this)) {
return false;
}
success = token.transfer(destination, amount);
}
else {
uint amountInWei = _amount;
if (amountInWei > this.balance) {
return false;
}
success = destination.send(amountInWei);
}
if (success) {
controller.logSweep(this, destination, _token, _amount);
}
return success;
}
}
contract UserWallet {
AbstractSweeperList sweeperList;
function UserWallet(address _sweeperlist) {
sweeperList = AbstractSweeperList(_sweeperlist);
}
function () public payable { }
function tokenFallback(address _from, uint _value, bytes _data) {
(_from);
(_value);
(_data);
}
function sweep(address _token, uint _amount)
returns (bool) {
(_amount);
return sweeperList.sweeperOf(_token).delegatecall(msg.data);
}
}
contract AbstractSweeperList {
function sweeperOf(address _token) returns (address);
}
contract Controller is AbstractSweeperList {
address public owner;
address public authorizedCaller;
address public destination;
bool public halted;
event LogNewWallet(address receiver);
event LogSweep(address indexed from, address indexed to, address indexed token, uint amount);
modifier onlyOwner() {
if (msg.sender != owner) throw;
_;
}
modifier onlyAuthorizedCaller() {
if (msg.sender != authorizedCaller) throw;
_;
}
modifier onlyAdmins() {
if (msg.sender != authorizedCaller && msg.sender != owner) throw;
_;
}
function Controller()
{
owner = msg.sender;
destination = msg.sender;
authorizedCaller = msg.sender;
}
function changeAuthorizedCaller(address _newCaller) onlyOwner {
authorizedCaller = _newCaller;
}
function changeDestination(address _dest) onlyOwner {
destination = _dest;
}
function changeOwner(address _owner) onlyOwner {
owner = _owner;
}
function makeWallet() onlyAdmins returns (address wallet) {
wallet = address(new UserWallet(this));
LogNewWallet(wallet);
}
function halt() onlyAdmins {
halted = true;
}
function start() onlyOwner {
halted = false;
}
address public defaultSweeper = address(new DefaultSweeper(this));
mapping (address => address) sweepers;
function addSweeper(address _token, address _sweeper) onlyOwner {
sweepers[_token] = _sweeper;
}
function sweeperOf(address _token) returns (address) {
address sweeper = sweepers[_token];
if (sweeper == 0) sweeper = defaultSweeper;
return sweeper;
}
function logSweep(address from, address to, address token, uint amount) {
LogSweep(from, to, token, amount);
}
}
|
[{"constant":false,"inputs":[{"name":"_token","type":"address"},{"name":"_amount","type":"uint256"}],"name":"sweep","outputs":[{"name":"","type":"bool"}],"payable":false,"type":"function"},{"constant":false,"inputs":[{"name":"_from","type":"address"},{"name":"_value","type":"uint256"},{"name":"_data","type":"bytes"}],"name":"tokenFallback","outputs":[],"payable":false,"type":"function"},{"inputs":[{"name":"_sweeperlist","type":"address"}],"payable":false,"type":"constructor"},{"payable":true,"type":"fallback"}]
|
v0.4.11+commit.68ef5810
| true
| 200
|
000000000000000000000000a3C1E324CA1ce40db73eD6026c4A177F099B5770
|
Default
| false
|
bzzr://4cdd69fdcf3cf6cbee9677fe380fa5f044048aa9e060ec5619a21ca5a5bd4cd1
|
|||
DSProxy
|
0x6c5573915e809129e306d8b819aa716abd1da795
|
Solidity
|
// proxy.sol - execute actions atomically through the proxy's identity
// Copyright (C) 2017 DappHub, LLC
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
// You should have received a copy of the GNU General Public License
// along with this program. If not, see <http://www.gnu.org/licenses/>.
pragma solidity ^0.4.23;
contract DSAuthority {
function canCall(
address src, address dst, bytes4 sig
) public view returns (bool);
}
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(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, this, sig);
}
}
}
contract DSNote {
event LogNote(
bytes4 indexed sig,
address indexed guy,
bytes32 indexed foo,
bytes32 indexed bar,
uint 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);
_;
}
}
// DSProxy
// Allows code execution using a persistant identity This can be very
// useful to execute a sequence of atomic actions. Since the owner of
// the proxy can be changed, this allows for dynamic ownership models
// i.e. a multisig
contract DSProxy is DSAuth, DSNote {
DSProxyCache public cache; // global cache for contracts
constructor(address _cacheAddr) public {
require(setCache(_cacheAddr));
}
function() public payable {
}
// use the proxy to execute calldata _data on contract _code
function execute(bytes _code, bytes _data)
public
payable
returns (address target, bytes32 response)
{
target = cache.read(_code);
if (target == 0x0) {
// deploy contract & store its address in cache
target = cache.write(_code);
}
response = execute(target, _data);
}
function execute(address _target, bytes _data)
public
auth
note
payable
returns (bytes32 response)
{
require(_target != 0x0);
// call contract in current context
assembly {
let succeeded := delegatecall(sub(gas, 5000), _target, add(_data, 0x20), mload(_data), 0, 32)
response := mload(0) // load delegatecall output
switch iszero(succeeded)
case 1 {
// throw if delegatecall failed
revert(0, 0)
}
}
}
//set new cache
function setCache(address _cacheAddr)
public
auth
note
returns (bool)
{
require(_cacheAddr != 0x0); // invalid cache address
cache = DSProxyCache(_cacheAddr); // overwrite cache
return true;
}
}
// DSProxyFactory
// This factory deploys new proxy instances through build()
// Deployed proxy addresses are logged
contract DSProxyFactory {
event Created(address indexed sender, address indexed owner, address proxy, address cache);
mapping(address=>bool) public isProxy;
DSProxyCache public cache = new DSProxyCache();
// deploys a new proxy instance
// sets owner of proxy to caller
function build() public returns (DSProxy proxy) {
proxy = build(msg.sender);
}
// deploys a new proxy instance
// sets custom owner of proxy
function build(address owner) public returns (DSProxy proxy) {
proxy = new DSProxy(cache);
emit Created(msg.sender, owner, address(proxy), address(cache));
proxy.setOwner(owner);
isProxy[proxy] = true;
}
}
// DSProxyCache
// This global cache stores addresses of contracts previously deployed
// by a proxy. This saves gas from repeat deployment of the same
// contracts and eliminates blockchain bloat.
// By default, all proxies deployed from the same factory store
// contracts in the same cache. The cache a proxy instance uses can be
// changed. The cache uses the sha3 hash of a contract's bytecode to
// lookup the address
contract DSProxyCache {
mapping(bytes32 => address) cache;
function read(bytes _code) public view returns (address) {
bytes32 hash = keccak256(_code);
return cache[hash];
}
function write(bytes _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;
}
}
|
[{"constant":false,"inputs":[{"name":"owner_","type":"address"}],"name":"setOwner","outputs":[],"payable":false,"stateMutability":"nonpayable","type":"function"},{"constant":false,"inputs":[{"name":"_target","type":"address"},{"name":"_data","type":"bytes"}],"name":"execute","outputs":[{"name":"response","type":"bytes32"}],"payable":true,"stateMutability":"payable","type":"function"},{"constant":false,"inputs":[{"name":"_code","type":"bytes"},{"name":"_data","type":"bytes"}],"name":"execute","outputs":[{"name":"target","type":"address"},{"name":"response","type":"bytes32"}],"payable":true,"stateMutability":"payable","type":"function"},{"constant":true,"inputs":[],"name":"cache","outputs":[{"name":"","type":"address"}],"payable":false,"stateMutability":"view","type":"function"},{"constant":false,"inputs":[{"name":"authority_","type":"address"}],"name":"setAuthority","outputs":[],"payable":false,"stateMutability":"nonpayable","type":"function"},{"constant":true,"inputs":[],"name":"owner","outputs":[{"name":"","type":"address"}],"payable":false,"stateMutability":"view","type":"function"},{"constant":false,"inputs":[{"name":"_cacheAddr","type":"address"}],"name":"setCache","outputs":[{"name":"","type":"bool"}],"payable":false,"stateMutability":"nonpayable","type":"function"},{"constant":true,"inputs":[],"name":"authority","outputs":[{"name":"","type":"address"}],"payable":false,"stateMutability":"view","type":"function"},{"inputs":[{"name":"_cacheAddr","type":"address"}],"payable":false,"stateMutability":"nonpayable","type":"constructor"},{"payable":true,"stateMutability":"payable","type":"fallback"},{"anonymous":true,"inputs":[{"indexed":true,"name":"sig","type":"bytes4"},{"indexed":true,"name":"guy","type":"address"},{"indexed":true,"name":"foo","type":"bytes32"},{"indexed":true,"name":"bar","type":"bytes32"},{"indexed":false,"name":"wad","type":"uint256"},{"indexed":false,"name":"fax","type":"bytes"}],"name":"LogNote","type":"event"},{"anonymous":false,"inputs":[{"indexed":true,"name":"authority","type":"address"}],"name":"LogSetAuthority","type":"event"},{"anonymous":false,"inputs":[{"indexed":true,"name":"owner","type":"address"}],"name":"LogSetOwner","type":"event"}]
|
v0.4.23+commit.124ca40d
| true
| 200
|
000000000000000000000000271293c67e2d3140a0e9381eff1f9b01e07b0795
|
Default
| false
|
bzzr://e498874c9ba9e75028e0c84f1b1d83b2dad5de910c59b837b32e5a190794c5e1
|
|||
UserWallet
|
0x25efcf9baef4d80e9cedd5bbd68f706452e27d51
|
Solidity
|
pragma solidity ^0.4.10;
// Copyright 2017 Bittrex
contract AbstractSweeper {
function sweep(address token, uint amount) returns (bool);
function () { throw; }
Controller controller;
function AbstractSweeper(address _controller) {
controller = Controller(_controller);
}
modifier canSweep() {
if (msg.sender != controller.authorizedCaller() && msg.sender != controller.owner()) throw;
if (controller.halted()) throw;
_;
}
}
contract Token {
function balanceOf(address a) returns (uint) {
(a);
return 0;
}
function transfer(address a, uint val) returns (bool) {
(a);
(val);
return false;
}
}
contract DefaultSweeper is AbstractSweeper {
function DefaultSweeper(address controller)
AbstractSweeper(controller) {}
function sweep(address _token, uint _amount)
canSweep
returns (bool) {
bool success = false;
address destination = controller.destination();
if (_token != address(0)) {
Token token = Token(_token);
uint amount = _amount;
if (amount > token.balanceOf(this)) {
return false;
}
success = token.transfer(destination, amount);
}
else {
uint amountInWei = _amount;
if (amountInWei > this.balance) {
return false;
}
success = destination.send(amountInWei);
}
if (success) {
controller.logSweep(this, destination, _token, _amount);
}
return success;
}
}
contract UserWallet {
AbstractSweeperList sweeperList;
function UserWallet(address _sweeperlist) {
sweeperList = AbstractSweeperList(_sweeperlist);
}
function () public payable { }
function tokenFallback(address _from, uint _value, bytes _data) {
(_from);
(_value);
(_data);
}
function sweep(address _token, uint _amount)
returns (bool) {
(_amount);
return sweeperList.sweeperOf(_token).delegatecall(msg.data);
}
}
contract AbstractSweeperList {
function sweeperOf(address _token) returns (address);
}
contract Controller is AbstractSweeperList {
address public owner;
address public authorizedCaller;
address public destination;
bool public halted;
event LogNewWallet(address receiver);
event LogSweep(address indexed from, address indexed to, address indexed token, uint amount);
modifier onlyOwner() {
if (msg.sender != owner) throw;
_;
}
modifier onlyAuthorizedCaller() {
if (msg.sender != authorizedCaller) throw;
_;
}
modifier onlyAdmins() {
if (msg.sender != authorizedCaller && msg.sender != owner) throw;
_;
}
function Controller()
{
owner = msg.sender;
destination = msg.sender;
authorizedCaller = msg.sender;
}
function changeAuthorizedCaller(address _newCaller) onlyOwner {
authorizedCaller = _newCaller;
}
function changeDestination(address _dest) onlyOwner {
destination = _dest;
}
function changeOwner(address _owner) onlyOwner {
owner = _owner;
}
function makeWallet() onlyAdmins returns (address wallet) {
wallet = address(new UserWallet(this));
LogNewWallet(wallet);
}
function halt() onlyAdmins {
halted = true;
}
function start() onlyOwner {
halted = false;
}
address public defaultSweeper = address(new DefaultSweeper(this));
mapping (address => address) sweepers;
function addSweeper(address _token, address _sweeper) onlyOwner {
sweepers[_token] = _sweeper;
}
function sweeperOf(address _token) returns (address) {
address sweeper = sweepers[_token];
if (sweeper == 0) sweeper = defaultSweeper;
return sweeper;
}
function logSweep(address from, address to, address token, uint amount) {
LogSweep(from, to, token, amount);
}
}
|
[{"constant":false,"inputs":[{"name":"_token","type":"address"},{"name":"_amount","type":"uint256"}],"name":"sweep","outputs":[{"name":"","type":"bool"}],"payable":false,"type":"function"},{"constant":false,"inputs":[{"name":"_from","type":"address"},{"name":"_value","type":"uint256"},{"name":"_data","type":"bytes"}],"name":"tokenFallback","outputs":[],"payable":false,"type":"function"},{"inputs":[{"name":"_sweeperlist","type":"address"}],"payable":false,"type":"constructor"},{"payable":true,"type":"fallback"}]
|
v0.4.11+commit.68ef5810
| true
| 200
|
000000000000000000000000a3C1E324CA1ce40db73eD6026c4A177F099B5770
|
Default
| false
|
bzzr://4cdd69fdcf3cf6cbee9677fe380fa5f044048aa9e060ec5619a21ca5a5bd4cd1
|
|||
DSProxy
|
0xcf3fc7f340324928052b3bf6232fb645d31dc1ce
|
Solidity
|
// proxy.sol - execute actions atomically through the proxy's identity
// Copyright (C) 2017 DappHub, LLC
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
// You should have received a copy of the GNU General Public License
// along with this program. If not, see <http://www.gnu.org/licenses/>.
pragma solidity ^0.4.23;
contract DSAuthority {
function canCall(
address src, address dst, bytes4 sig
) public view returns (bool);
}
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(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, this, sig);
}
}
}
contract DSNote {
event LogNote(
bytes4 indexed sig,
address indexed guy,
bytes32 indexed foo,
bytes32 indexed bar,
uint 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);
_;
}
}
// DSProxy
// Allows code execution using a persistant identity This can be very
// useful to execute a sequence of atomic actions. Since the owner of
// the proxy can be changed, this allows for dynamic ownership models
// i.e. a multisig
contract DSProxy is DSAuth, DSNote {
DSProxyCache public cache; // global cache for contracts
constructor(address _cacheAddr) public {
require(setCache(_cacheAddr));
}
function() public payable {
}
// use the proxy to execute calldata _data on contract _code
function execute(bytes _code, bytes _data)
public
payable
returns (address target, bytes32 response)
{
target = cache.read(_code);
if (target == 0x0) {
// deploy contract & store its address in cache
target = cache.write(_code);
}
response = execute(target, _data);
}
function execute(address _target, bytes _data)
public
auth
note
payable
returns (bytes32 response)
{
require(_target != 0x0);
// call contract in current context
assembly {
let succeeded := delegatecall(sub(gas, 5000), _target, add(_data, 0x20), mload(_data), 0, 32)
response := mload(0) // load delegatecall output
switch iszero(succeeded)
case 1 {
// throw if delegatecall failed
revert(0, 0)
}
}
}
//set new cache
function setCache(address _cacheAddr)
public
auth
note
returns (bool)
{
require(_cacheAddr != 0x0); // invalid cache address
cache = DSProxyCache(_cacheAddr); // overwrite cache
return true;
}
}
// DSProxyFactory
// This factory deploys new proxy instances through build()
// Deployed proxy addresses are logged
contract DSProxyFactory {
event Created(address indexed sender, address indexed owner, address proxy, address cache);
mapping(address=>bool) public isProxy;
DSProxyCache public cache = new DSProxyCache();
// deploys a new proxy instance
// sets owner of proxy to caller
function build() public returns (DSProxy proxy) {
proxy = build(msg.sender);
}
// deploys a new proxy instance
// sets custom owner of proxy
function build(address owner) public returns (DSProxy proxy) {
proxy = new DSProxy(cache);
emit Created(msg.sender, owner, address(proxy), address(cache));
proxy.setOwner(owner);
isProxy[proxy] = true;
}
}
// DSProxyCache
// This global cache stores addresses of contracts previously deployed
// by a proxy. This saves gas from repeat deployment of the same
// contracts and eliminates blockchain bloat.
// By default, all proxies deployed from the same factory store
// contracts in the same cache. The cache a proxy instance uses can be
// changed. The cache uses the sha3 hash of a contract's bytecode to
// lookup the address
contract DSProxyCache {
mapping(bytes32 => address) cache;
function read(bytes _code) public view returns (address) {
bytes32 hash = keccak256(_code);
return cache[hash];
}
function write(bytes _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;
}
}
|
[{"constant":false,"inputs":[{"name":"owner_","type":"address"}],"name":"setOwner","outputs":[],"payable":false,"stateMutability":"nonpayable","type":"function"},{"constant":false,"inputs":[{"name":"_target","type":"address"},{"name":"_data","type":"bytes"}],"name":"execute","outputs":[{"name":"response","type":"bytes32"}],"payable":true,"stateMutability":"payable","type":"function"},{"constant":false,"inputs":[{"name":"_code","type":"bytes"},{"name":"_data","type":"bytes"}],"name":"execute","outputs":[{"name":"target","type":"address"},{"name":"response","type":"bytes32"}],"payable":true,"stateMutability":"payable","type":"function"},{"constant":true,"inputs":[],"name":"cache","outputs":[{"name":"","type":"address"}],"payable":false,"stateMutability":"view","type":"function"},{"constant":false,"inputs":[{"name":"authority_","type":"address"}],"name":"setAuthority","outputs":[],"payable":false,"stateMutability":"nonpayable","type":"function"},{"constant":true,"inputs":[],"name":"owner","outputs":[{"name":"","type":"address"}],"payable":false,"stateMutability":"view","type":"function"},{"constant":false,"inputs":[{"name":"_cacheAddr","type":"address"}],"name":"setCache","outputs":[{"name":"","type":"bool"}],"payable":false,"stateMutability":"nonpayable","type":"function"},{"constant":true,"inputs":[],"name":"authority","outputs":[{"name":"","type":"address"}],"payable":false,"stateMutability":"view","type":"function"},{"inputs":[{"name":"_cacheAddr","type":"address"}],"payable":false,"stateMutability":"nonpayable","type":"constructor"},{"payable":true,"stateMutability":"payable","type":"fallback"},{"anonymous":true,"inputs":[{"indexed":true,"name":"sig","type":"bytes4"},{"indexed":true,"name":"guy","type":"address"},{"indexed":true,"name":"foo","type":"bytes32"},{"indexed":true,"name":"bar","type":"bytes32"},{"indexed":false,"name":"wad","type":"uint256"},{"indexed":false,"name":"fax","type":"bytes"}],"name":"LogNote","type":"event"},{"anonymous":false,"inputs":[{"indexed":true,"name":"authority","type":"address"}],"name":"LogSetAuthority","type":"event"},{"anonymous":false,"inputs":[{"indexed":true,"name":"owner","type":"address"}],"name":"LogSetOwner","type":"event"}]
|
v0.4.23+commit.124ca40d
| true
| 200
|
000000000000000000000000271293c67e2d3140a0e9381eff1f9b01e07b0795
|
Default
| false
|
bzzr://e498874c9ba9e75028e0c84f1b1d83b2dad5de910c59b837b32e5a190794c5e1
|
|||
UserWallet
|
0x22ea30fe710088ee106545e91e4332d0c42b52ac
|
Solidity
|
pragma solidity ^0.4.10;
// Copyright 2017 Bittrex
contract AbstractSweeper {
function sweep(address token, uint amount) returns (bool);
function () { throw; }
Controller controller;
function AbstractSweeper(address _controller) {
controller = Controller(_controller);
}
modifier canSweep() {
if (msg.sender != controller.authorizedCaller() && msg.sender != controller.owner()) throw;
if (controller.halted()) throw;
_;
}
}
contract Token {
function balanceOf(address a) returns (uint) {
(a);
return 0;
}
function transfer(address a, uint val) returns (bool) {
(a);
(val);
return false;
}
}
contract DefaultSweeper is AbstractSweeper {
function DefaultSweeper(address controller)
AbstractSweeper(controller) {}
function sweep(address _token, uint _amount)
canSweep
returns (bool) {
bool success = false;
address destination = controller.destination();
if (_token != address(0)) {
Token token = Token(_token);
uint amount = _amount;
if (amount > token.balanceOf(this)) {
return false;
}
success = token.transfer(destination, amount);
}
else {
uint amountInWei = _amount;
if (amountInWei > this.balance) {
return false;
}
success = destination.send(amountInWei);
}
if (success) {
controller.logSweep(this, destination, _token, _amount);
}
return success;
}
}
contract UserWallet {
AbstractSweeperList sweeperList;
function UserWallet(address _sweeperlist) {
sweeperList = AbstractSweeperList(_sweeperlist);
}
function () public payable { }
function tokenFallback(address _from, uint _value, bytes _data) {
(_from);
(_value);
(_data);
}
function sweep(address _token, uint _amount)
returns (bool) {
(_amount);
return sweeperList.sweeperOf(_token).delegatecall(msg.data);
}
}
contract AbstractSweeperList {
function sweeperOf(address _token) returns (address);
}
contract Controller is AbstractSweeperList {
address public owner;
address public authorizedCaller;
address public destination;
bool public halted;
event LogNewWallet(address receiver);
event LogSweep(address indexed from, address indexed to, address indexed token, uint amount);
modifier onlyOwner() {
if (msg.sender != owner) throw;
_;
}
modifier onlyAuthorizedCaller() {
if (msg.sender != authorizedCaller) throw;
_;
}
modifier onlyAdmins() {
if (msg.sender != authorizedCaller && msg.sender != owner) throw;
_;
}
function Controller()
{
owner = msg.sender;
destination = msg.sender;
authorizedCaller = msg.sender;
}
function changeAuthorizedCaller(address _newCaller) onlyOwner {
authorizedCaller = _newCaller;
}
function changeDestination(address _dest) onlyOwner {
destination = _dest;
}
function changeOwner(address _owner) onlyOwner {
owner = _owner;
}
function makeWallet() onlyAdmins returns (address wallet) {
wallet = address(new UserWallet(this));
LogNewWallet(wallet);
}
function halt() onlyAdmins {
halted = true;
}
function start() onlyOwner {
halted = false;
}
address public defaultSweeper = address(new DefaultSweeper(this));
mapping (address => address) sweepers;
function addSweeper(address _token, address _sweeper) onlyOwner {
sweepers[_token] = _sweeper;
}
function sweeperOf(address _token) returns (address) {
address sweeper = sweepers[_token];
if (sweeper == 0) sweeper = defaultSweeper;
return sweeper;
}
function logSweep(address from, address to, address token, uint amount) {
LogSweep(from, to, token, amount);
}
}
|
[{"constant":false,"inputs":[{"name":"_token","type":"address"},{"name":"_amount","type":"uint256"}],"name":"sweep","outputs":[{"name":"","type":"bool"}],"payable":false,"type":"function"},{"constant":false,"inputs":[{"name":"_from","type":"address"},{"name":"_value","type":"uint256"},{"name":"_data","type":"bytes"}],"name":"tokenFallback","outputs":[],"payable":false,"type":"function"},{"inputs":[{"name":"_sweeperlist","type":"address"}],"payable":false,"type":"constructor"},{"payable":true,"type":"fallback"}]
|
v0.4.11+commit.68ef5810
| true
| 200
|
000000000000000000000000a3C1E324CA1ce40db73eD6026c4A177F099B5770
|
Default
| false
|
bzzr://4cdd69fdcf3cf6cbee9677fe380fa5f044048aa9e060ec5619a21ca5a5bd4cd1
|
|||
BYTC
|
0xc9a52fde36f4aeed087c2131d807ae5f8fd24df0
|
Solidity
|
pragma solidity ^0.4.18;
library SafeMath {
function mul(uint256 a, uint256 b) internal pure returns (uint256) {
uint256 c = a * b;
assert(a == 0 || c / a == b);
return c;
}
function div(uint256 a, uint256 b) internal pure returns (uint256) {
// assert(b > 0); // Solidity automatically throws when dividing by 0
uint256 c = a / b;
// assert(a == b * c + a % b); // There is no case in which this doesn't hold
return c;
}
function sub(uint256 a, uint256 b) internal pure returns (uint256) {
assert(b <= a);
return a - b;
}
function add(uint256 a, uint256 b) internal pure returns (uint256) {
uint256 c = a + b;
assert(c >= a);
return c;
}
function 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 Ownable {
address public owner;
function Ownable() public {
owner = msg.sender;
}
modifier onlyOwner() {
if (msg.sender != owner) {
revert();
}
_;
}
function transferOwnership(address newOwner) public onlyOwner {
if (newOwner != address(0)) {
owner = newOwner;
}
}
function destruct() public onlyOwner {
selfdestruct(owner);
}
}
contract ERC20Basic {
function balanceOf(address who) public constant returns (uint256);
function transfer(address to, uint256 value) public;
event Transfer(address indexed from, address indexed to, uint256 value);
}
contract ERC20 is ERC20Basic {
function allowance(address owner, address spender) public constant returns (uint256);
function transferFrom(address from, address to, uint256 value) public;
function approve(address spender, uint256 value) public;
event Approval(address indexed owner, address indexed spender, uint256 value);
}
contract BasicToken is ERC20Basic {
using SafeMath for uint256;
mapping(address => uint256) balances;
uint256 public totalSupply;
modifier onlyPayloadSize(uint256 size) {
if(msg.data.length < size + 4) {
revert();
}
_;
}
function transfer(address _to, uint256 _value) public onlyPayloadSize(2 * 32) {
balances[msg.sender] = balances[msg.sender].sub(_value);
balances[_to] = balances[_to].add(_value);
Transfer(msg.sender, _to, _value);
}
function balanceOf(address _owner) public constant returns (uint256 balance) {
return balances[_owner];
}
}
contract StandardToken is BasicToken, ERC20 {
mapping (address => mapping (address => uint256)) allowed;
function transferFrom(address _from, address _to, uint256 _value) public onlyPayloadSize(3 * 32) {
var _allowance = allowed[_from][msg.sender];
balances[_to] = balances[_to].add(_value);
balances[_from] = balances[_from].sub(_value);
allowed[_from][msg.sender] = _allowance.sub(_value);
Transfer(_from, _to, _value);
}
function approve(address _spender, uint256 _value) public {
if ((_value != 0) && (allowed[msg.sender][_spender] != 0)) revert();
allowed[msg.sender][_spender] = _value;
Approval(msg.sender, _spender, _value);
}
function allowance(address _owner, address _spender) public constant returns (uint256 remaining) {
return allowed[_owner][_spender];
}
}
contract BYTC is StandardToken, Ownable {
string public constant name = "佰优乐购";
string public constant symbol = "BYTC";
uint256 public constant decimals = 8;
function BYTC() public {
owner = msg.sender;
totalSupply=100000000000000000;
balances[owner]=totalSupply;
}
function () public {
revert();
}
}
|
[{"constant":true,"inputs":[],"name":"name","outputs":[{"name":"","type":"string"}],"payable":false,"stateMutability":"view","type":"function"},{"constant":false,"inputs":[{"name":"_spender","type":"address"},{"name":"_value","type":"uint256"}],"name":"approve","outputs":[],"payable":false,"stateMutability":"nonpayable","type":"function"},{"constant":true,"inputs":[],"name":"totalSupply","outputs":[{"name":"","type":"uint256"}],"payable":false,"stateMutability":"view","type":"function"},{"constant":false,"inputs":[{"name":"_from","type":"address"},{"name":"_to","type":"address"},{"name":"_value","type":"uint256"}],"name":"transferFrom","outputs":[],"payable":false,"stateMutability":"nonpayable","type":"function"},{"constant":false,"inputs":[],"name":"destruct","outputs":[],"payable":false,"stateMutability":"nonpayable","type":"function"},{"constant":true,"inputs":[],"name":"decimals","outputs":[{"name":"","type":"uint256"}],"payable":false,"stateMutability":"view","type":"function"},{"constant":true,"inputs":[{"name":"_owner","type":"address"}],"name":"balanceOf","outputs":[{"name":"balance","type":"uint256"}],"payable":false,"stateMutability":"view","type":"function"},{"constant":true,"inputs":[],"name":"owner","outputs":[{"name":"","type":"address"}],"payable":false,"stateMutability":"view","type":"function"},{"constant":true,"inputs":[],"name":"symbol","outputs":[{"name":"","type":"string"}],"payable":false,"stateMutability":"view","type":"function"},{"constant":false,"inputs":[{"name":"_to","type":"address"},{"name":"_value","type":"uint256"}],"name":"transfer","outputs":[],"payable":false,"stateMutability":"nonpayable","type":"function"},{"constant":true,"inputs":[{"name":"_owner","type":"address"},{"name":"_spender","type":"address"}],"name":"allowance","outputs":[{"name":"remaining","type":"uint256"}],"payable":false,"stateMutability":"view","type":"function"},{"constant":false,"inputs":[{"name":"newOwner","type":"address"}],"name":"transferOwnership","outputs":[],"payable":false,"stateMutability":"nonpayable","type":"function"},{"inputs":[],"payable":false,"stateMutability":"nonpayable","type":"constructor"},{"payable":false,"stateMutability":"nonpayable","type":"fallback"},{"anonymous":false,"inputs":[{"indexed":true,"name":"owner","type":"address"},{"indexed":true,"name":"spender","type":"address"},{"indexed":false,"name":"value","type":"uint256"}],"name":"Approval","type":"event"},{"anonymous":false,"inputs":[{"indexed":true,"name":"from","type":"address"},{"indexed":true,"name":"to","type":"address"},{"indexed":false,"name":"value","type":"uint256"}],"name":"Transfer","type":"event"}]
|
v0.4.18+commit.9cf6e910
| true
| 200
|
Default
| false
|
bzzr://0118be04c0a1954dcea55e06fd6eef09b47e1df757ad407acd4c7cae021d8b0f
|
||||
CollectionContract
|
0x31f8dd3b8258bd91b1cabaadcc928dc8e6780bbf
|
Solidity
|
// File: contracts/CollectionContract.sol
// SPDX-License-Identifier: MIT OR Apache-2.0
pragma solidity ^0.8.0;
import "@openzeppelin/contracts-upgradeable/token/ERC721/extensions/ERC721BurnableUpgradeable.sol";
import "@openzeppelin/contracts-upgradeable/utils/AddressUpgradeable.sol";
import "./interfaces/ICollectionContractInitializer.sol";
import "./interfaces/ICollectionFactory.sol";
import "./interfaces/IGetRoyalties.sol";
import "./interfaces/IProxyCall.sol";
import "./interfaces/ITokenCreator.sol";
import "./interfaces/ITokenCreatorPaymentAddress.sol";
import "./interfaces/IGetFees.sol";
import "./libraries/AccountMigrationLibrary.sol";
import "./libraries/ProxyCall.sol";
import "./libraries/BytesLibrary.sol";
import "./interfaces/IRoyaltyInfo.sol";
/**
* @title A collection of NFTs.
* @notice All NFTs from this contract are minted by the same creator.
* A 10% royalty to the creator is included which may be split with collaborators.
*/
contract CollectionContract is
ICollectionContractInitializer,
IGetRoyalties,
IGetFees,
IRoyaltyInfo,
ITokenCreator,
ITokenCreatorPaymentAddress,
ERC721BurnableUpgradeable
{
using AccountMigrationLibrary for address;
using AddressUpgradeable for address;
using BytesLibrary for bytes;
using ProxyCall for IProxyCall;
uint256 private constant ROYALTY_IN_BASIS_POINTS = 1000;
uint256 private constant ROYALTY_RATIO = 10;
/**
* @notice The baseURI to use for the tokenURI, if undefined then `ipfs://` is used.
*/
string private baseURI_;
/**
* @dev Stores hashes minted to prevent duplicates.
*/
mapping(string => bool) private cidToMinted;
/**
* @notice The factory which was used to create this collection.
* @dev This is used to read common config.
*/
ICollectionFactory public immutable collectionFactory;
/**
* @notice The tokenId of the most recently created NFT.
* @dev Minting starts at tokenId 1. Each mint will use this value + 1.
*/
uint256 public latestTokenId;
/**
* @notice The max tokenId which can be minted, or 0 if there's no limit.
* @dev This value may be set at any time, but once set it cannot be increased.
*/
uint256 public maxTokenId;
/**
* @notice The owner/creator of this NFT collection.
*/
address payable public owner;
/**
* @dev Stores an optional alternate address to receive creator revenue and royalty payments.
* The target address may be a contract which could split or escrow payments.
*/
mapping(uint256 => address payable) private tokenIdToCreatorPaymentAddress;
/**
* @dev Tracks how many tokens have been burned, used to calc the total supply efficiently.
*/
uint256 private burnCounter;
/**
* @dev Stores a CID for each NFT.
*/
mapping(uint256 => string) private _tokenCIDs;
event BaseURIUpdated(string baseURI);
event CreatorMigrated(address indexed originalAddress, address indexed newAddress);
event MaxTokenIdUpdated(uint256 indexed maxTokenId);
event Minted(address indexed creator, uint256 indexed tokenId, string indexed indexedTokenCID, string tokenCID);
event NFTOwnerMigrated(uint256 indexed tokenId, address indexed originalAddress, address indexed newAddress);
event PaymentAddressMigrated(
uint256 indexed tokenId,
address indexed originalAddress,
address indexed newAddress,
address originalPaymentAddress,
address newPaymentAddress
);
event SelfDestruct(address indexed owner);
event TokenCreatorPaymentAddressSet(
address indexed fromPaymentAddress,
address indexed toPaymentAddress,
uint256 indexed tokenId
);
modifier onlyOwner() {
require(msg.sender == owner, "CollectionContract: Caller is not owner");
_;
}
modifier onlyOperator() {
require(collectionFactory.rolesContract().isOperator(msg.sender), "CollectionContract: Caller is not an operator");
_;
}
/**
* @dev The constructor for a proxy can only be used to assign immutable variables.
*/
constructor(address _collectionFactory) {
require(_collectionFactory.isContract(), "CollectionContract: collectionFactory is not a contract");
collectionFactory = ICollectionFactory(_collectionFactory);
}
/**
* @notice Called by the factory on creation.
* @dev This may only be called once.
*/
function initialize(
address payable _creator,
string memory _name,
string memory _symbol
) external initializer {
require(msg.sender == address(collectionFactory), "CollectionContract: Collection must be created via the factory");
__ERC721_init_unchained(_name, _symbol);
owner = _creator;
}
/**
* @notice Allows the owner to mint an NFT defined by its metadata path.
*/
function mint(string memory tokenCID) public returns (uint256 tokenId) {
tokenId = _mint(tokenCID);
}
/**
* @notice Allows the owner to mint and sets approval for all for the provided operator.
* @dev This can be used by creators the first time they mint an NFT to save having to issue a separate approval
* transaction before starting an auction.
*/
function mintAndApprove(string memory tokenCID, address operator) public returns (uint256 tokenId) {
tokenId = _mint(tokenCID);
setApprovalForAll(operator, true);
}
/**
* @notice Allows the owner to mint an NFT and have creator revenue/royalties sent to an alternate address.
*/
function mintWithCreatorPaymentAddress(string memory tokenCID, address payable tokenCreatorPaymentAddress)
public
returns (uint256 tokenId)
{
require(tokenCreatorPaymentAddress != address(0), "CollectionContract: tokenCreatorPaymentAddress is required");
tokenId = mint(tokenCID);
_setTokenCreatorPaymentAddress(tokenId, tokenCreatorPaymentAddress);
}
/**
* @notice Allows the owner to mint an NFT and have creator revenue/royalties sent to an alternate address.
* Also sets approval for all for the provided operator.
* @dev This can be used by creators the first time they mint an NFT to save having to issue a separate approval
* transaction before starting an auction.
*/
function mintWithCreatorPaymentAddressAndApprove(
string memory tokenCID,
address payable tokenCreatorPaymentAddress,
address operator
) public returns (uint256 tokenId) {
tokenId = mintWithCreatorPaymentAddress(tokenCID, tokenCreatorPaymentAddress);
setApprovalForAll(operator, true);
}
/**
* @notice Allows the owner to mint an NFT and have creator revenue/royalties sent to an alternate address
* which is defined by a contract call, typically a proxy contract address representing the payment terms.
* @param paymentAddressFactory The contract to call which will return the address to use for payments.
* @param paymentAddressCallData The call details to sent to the factory provided.
*/
function mintWithCreatorPaymentFactory(
string memory tokenCID,
address paymentAddressFactory,
bytes memory paymentAddressCallData
) public returns (uint256 tokenId) {
address payable tokenCreatorPaymentAddress = collectionFactory
.proxyCallContract()
.proxyCallAndReturnContractAddress(paymentAddressFactory, paymentAddressCallData);
tokenId = mintWithCreatorPaymentAddress(tokenCID, tokenCreatorPaymentAddress);
}
/**
* @notice Allows the owner to mint an NFT and have creator revenue/royalties sent to an alternate address
* which is defined by a contract call, typically a proxy contract address representing the payment terms.
* Also sets approval for all for the provided operator.
* @param paymentAddressFactory The contract to call which will return the address to use for payments.
* @param paymentAddressCallData The call details to sent to the factory provided.
* @dev This can be used by creators the first time they mint an NFT to save having to issue a separate approval
* transaction before starting an auction.
*/
function mintWithCreatorPaymentFactoryAndApprove(
string memory tokenCID,
address paymentAddressFactory,
bytes memory paymentAddressCallData,
address operator
) public returns (uint256 tokenId) {
tokenId = mintWithCreatorPaymentFactory(tokenCID, paymentAddressFactory, paymentAddressCallData);
setApprovalForAll(operator, true);
}
/**
* @notice Allows the owner to set a max tokenID.
* This provides a guarantee to collectors about the limit of this collection contract, if applicable.
* @dev Once this value has been set, it may be decreased but can never be increased.
*/
function updateMaxTokenId(uint256 _maxTokenId) external onlyOwner {
require(_maxTokenId > 0, "CollectionContract: Max token ID may not be cleared");
require(maxTokenId == 0 || _maxTokenId < maxTokenId, "CollectionContract: Max token ID may not increase");
require(latestTokenId + 1 <= _maxTokenId, "CollectionContract: Max token ID must be greater than last mint");
maxTokenId = _maxTokenId;
emit MaxTokenIdUpdated(_maxTokenId);
}
/**
* @notice Allows the owner to assign a baseURI to use for the tokenURI instead of the default `ipfs://`.
*/
function updateBaseURI(string calldata baseURIOverride) external onlyOwner {
baseURI_ = baseURIOverride;
emit BaseURIUpdated(baseURIOverride);
}
/**
* @notice Allows the creator to burn if they currently own the NFT.
*/
function burn(uint256 tokenId) public override onlyOwner {
super.burn(tokenId);
}
/**
* @notice Allows the collection owner to destroy this contract only if
* no NFTs have been minted yet.
*/
function selfDestruct() external onlyOwner {
require(totalSupply() == 0, "CollectionContract: Any NFTs minted must be burned first");
emit SelfDestruct(msg.sender);
selfdestruct(payable(msg.sender));
}
/**
* @notice Allows an NFT owner or creator and Foundation to work together in order to update the creator
* to a new account and/or transfer NFTs to that account.
* @param signature Message `I authorize Foundation to migrate my account to ${newAccount.address.toLowerCase()}`
* signed by the original account.
* @dev This will gracefully skip any NFTs that have been burned or transferred.
*/
function adminAccountMigration(
uint256[] calldata ownedTokenIds,
address originalAddress,
address payable newAddress,
bytes calldata signature
) public onlyOperator {
originalAddress.requireAuthorizedAccountMigration(newAddress, signature);
for (uint256 i = 0; i < ownedTokenIds.length; i++) {
uint256 tokenId = ownedTokenIds[i];
// Check that the token exists and still is owned by the originalAddress
// so that frontrunning a burn or transfer will not cause the entire tx to revert
if (_exists(tokenId) && ownerOf(tokenId) == originalAddress) {
_transfer(originalAddress, newAddress, tokenId);
emit NFTOwnerMigrated(tokenId, originalAddress, newAddress);
}
}
if (owner == originalAddress) {
owner = newAddress;
emit CreatorMigrated(originalAddress, newAddress);
}
}
/**
* @notice Allows a split recipient and Foundation to work together in order to update the payment address
* to a new account.
* @param signature Message `I authorize Foundation to migrate my account to ${newAccount.address.toLowerCase()}`
* signed by the original account.
*/
function adminAccountMigrationForPaymentAddresses(
uint256[] calldata paymentAddressTokenIds,
address paymentAddressFactory,
bytes memory paymentAddressCallData,
uint256 addressLocationInCallData,
address originalAddress,
address payable newAddress,
bytes calldata signature
) public onlyOperator {
originalAddress.requireAuthorizedAccountMigration(newAddress, signature);
_adminAccountRecoveryForPaymentAddresses(
paymentAddressTokenIds,
paymentAddressFactory,
paymentAddressCallData,
addressLocationInCallData,
originalAddress,
newAddress
);
}
function baseURI() external view returns (string memory) {
return _baseURI();
}
/**
* @notice Returns an array of recipient addresses to which royalties for secondary sales should be sent.
* The expected royalty amount is communicated with `getFeeBps`.
*/
function getFeeRecipients(uint256 id) external view returns (address payable[] memory recipients) {
recipients = new address payable[](1);
recipients[0] = getTokenCreatorPaymentAddress(id);
}
/**
* @notice Returns an array of royalties to be sent for secondary sales in basis points.
* The expected recipients is communicated with `getFeeRecipients`.
*/
function getFeeBps(
uint256 /* id */
) external pure returns (uint256[] memory feesInBasisPoints) {
feesInBasisPoints = new uint256[](1);
feesInBasisPoints[0] = ROYALTY_IN_BASIS_POINTS;
}
/**
* @notice Checks if the creator has already minted a given NFT using this collection contract.
*/
function getHasMintedCID(string memory tokenCID) public view returns (bool) {
return cidToMinted[tokenCID];
}
/**
* @notice Returns an array of royalties to be sent for secondary sales.
*/
function getRoyalties(uint256 tokenId)
external
view
returns (address payable[] memory recipients, uint256[] memory feesInBasisPoints)
{
recipients = new address payable[](1);
recipients[0] = getTokenCreatorPaymentAddress(tokenId);
feesInBasisPoints = new uint256[](1);
feesInBasisPoints[0] = ROYALTY_IN_BASIS_POINTS;
}
/**
* @notice Returns the receiver and the amount to be sent for a secondary sale.
*/
function royaltyInfo(uint256 _tokenId, uint256 _salePrice)
external
view
returns (address receiver, uint256 royaltyAmount)
{
receiver = getTokenCreatorPaymentAddress(_tokenId);
unchecked {
royaltyAmount = _salePrice / ROYALTY_RATIO;
}
}
/**
* @notice Returns the creator for an NFT, which is always the collection owner.
*/
function tokenCreator(
uint256 /* tokenId */
) external view returns (address payable) {
return owner;
}
/**
* @notice Returns the desired payment address to be used for any transfers to the creator.
* @dev The payment address may be assigned for each individual NFT, if not defined the collection owner is returned.
*/
function getTokenCreatorPaymentAddress(uint256 tokenId)
public
view
returns (address payable tokenCreatorPaymentAddress)
{
tokenCreatorPaymentAddress = tokenIdToCreatorPaymentAddress[tokenId];
if (tokenCreatorPaymentAddress == address(0)) {
tokenCreatorPaymentAddress = owner;
}
}
/**
* @notice Count of NFTs tracked by this contract.
* @dev From the ERC-721 enumerable standard.
*/
function totalSupply() public view returns (uint256) {
unchecked {
return latestTokenId - burnCounter;
}
}
function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) {
if (
interfaceId == type(IGetRoyalties).interfaceId ||
interfaceId == type(ITokenCreator).interfaceId ||
interfaceId == type(ITokenCreatorPaymentAddress).interfaceId ||
interfaceId == type(IGetFees).interfaceId ||
interfaceId == type(IRoyaltyInfo).interfaceId
) {
return true;
}
return super.supportsInterface(interfaceId);
}
function tokenURI(uint256 tokenId) public view virtual override returns (string memory) {
require(_exists(tokenId), "CollectionContract: URI query for nonexistent token");
return string(abi.encodePacked(_baseURI(), _tokenCIDs[tokenId]));
}
function _mint(string memory tokenCID) private onlyOwner returns (uint256 tokenId) {
require(bytes(tokenCID).length > 0, "CollectionContract: tokenCID is required");
require(!cidToMinted[tokenCID], "CollectionContract: NFT was already minted");
unchecked {
tokenId = ++latestTokenId;
require(maxTokenId == 0 || tokenId <= maxTokenId, "CollectionContract: Max token count has already been minted");
cidToMinted[tokenCID] = true;
_tokenCIDs[tokenId] = tokenCID;
_safeMint(msg.sender, tokenId, "");
emit Minted(msg.sender, tokenId, tokenCID, tokenCID);
}
}
/**
* @dev Allow setting a different address to send payments to for both primary sale revenue
* and secondary sales royalties.
*/
function _setTokenCreatorPaymentAddress(uint256 tokenId, address payable tokenCreatorPaymentAddress) internal {
emit TokenCreatorPaymentAddressSet(tokenIdToCreatorPaymentAddress[tokenId], tokenCreatorPaymentAddress, tokenId);
tokenIdToCreatorPaymentAddress[tokenId] = tokenCreatorPaymentAddress;
}
function _burn(uint256 tokenId) internal override {
delete cidToMinted[_tokenCIDs[tokenId]];
delete tokenIdToCreatorPaymentAddress[tokenId];
delete _tokenCIDs[tokenId];
unchecked {
burnCounter++;
}
super._burn(tokenId);
}
/**
* @dev Split into a second function to avoid stack too deep errors
*/
function _adminAccountRecoveryForPaymentAddresses(
uint256[] calldata paymentAddressTokenIds,
address paymentAddressFactory,
bytes memory paymentAddressCallData,
uint256 addressLocationInCallData,
address originalAddress,
address payable newAddress
) private {
// Call the factory and get the originalPaymentAddress
address payable originalPaymentAddress = collectionFactory.proxyCallContract().proxyCallAndReturnContractAddress(
paymentAddressFactory,
paymentAddressCallData
);
// Confirm the original address and swap with the new address
paymentAddressCallData.replaceAtIf(addressLocationInCallData, originalAddress, newAddress);
// Call the factory and get the newPaymentAddress
address payable newPaymentAddress = collectionFactory.proxyCallContract().proxyCallAndReturnContractAddress(
paymentAddressFactory,
paymentAddressCallData
);
// For each token, confirm the expected payment address and then update to the new one
for (uint256 i = 0; i < paymentAddressTokenIds.length; i++) {
uint256 tokenId = paymentAddressTokenIds[i];
require(
tokenIdToCreatorPaymentAddress[tokenId] == originalPaymentAddress,
"CollectionContract: Payment address is not the expected value"
);
_setTokenCreatorPaymentAddress(tokenId, newPaymentAddress);
emit PaymentAddressMigrated(tokenId, originalAddress, newAddress, originalPaymentAddress, newPaymentAddress);
}
}
function _baseURI() internal view override returns (string memory) {
if (bytes(baseURI_).length > 0) {
return baseURI_;
}
return "ipfs://";
}
}
// File: @openzeppelin/contracts-upgradeable/token/ERC721/extensions/ERC721BurnableUpgradeable.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (token/ERC721/extensions/ERC721Burnable.sol)
pragma solidity ^0.8.0;
import "../ERC721Upgradeable.sol";
import "../../../utils/ContextUpgradeable.sol";
import "../../../proxy/utils/Initializable.sol";
/**
* @title ERC721 Burnable Token
* @dev ERC721 Token that can be irreversibly burned (destroyed).
*/
abstract contract ERC721BurnableUpgradeable is Initializable, ContextUpgradeable, ERC721Upgradeable {
function __ERC721Burnable_init() internal onlyInitializing {
__Context_init_unchained();
__ERC165_init_unchained();
__ERC721Burnable_init_unchained();
}
function __ERC721Burnable_init_unchained() internal onlyInitializing {
}
/**
* @dev Burns `tokenId`. See {ERC721-_burn}.
*
* Requirements:
*
* - The caller must own `tokenId` or be an approved operator.
*/
function burn(uint256 tokenId) public virtual {
//solhint-disable-next-line max-line-length
require(_isApprovedOrOwner(_msgSender(), tokenId), "ERC721Burnable: caller is not owner nor approved");
_burn(tokenId);
}
uint256[50] private __gap;
}
// File: @openzeppelin/contracts-upgradeable/utils/AddressUpgradeable.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (utils/Address.sol)
pragma solidity ^0.8.0;
/**
* @dev Collection of functions related to the address type
*/
library AddressUpgradeable {
/**
* @dev Returns true if `account` is a contract.
*
* [IMPORTANT]
* ====
* It is unsafe to assume that an address for which this function returns
* false is an externally-owned account (EOA) and not a contract.
*
* Among others, `isContract` will return false for the following
* types of addresses:
*
* - an externally-owned account
* - a contract in construction
* - an address where a contract will be created
* - an address where a contract lived, but was destroyed
* ====
*/
function isContract(address account) internal view returns (bool) {
// This method relies on extcodesize, which returns 0 for contracts in
// construction, since the code is only stored at the end of the
// constructor execution.
uint256 size;
assembly {
size := extcodesize(account)
}
return size > 0;
}
/**
* @dev Replacement for Solidity's `transfer`: sends `amount` wei to
* `recipient`, forwarding all available gas and reverting on errors.
*
* https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost
* of certain opcodes, possibly making contracts go over the 2300 gas limit
* imposed by `transfer`, making them unable to receive funds via
* `transfer`. {sendValue} removes this limitation.
*
* https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more].
*
* IMPORTANT: because control is transferred to `recipient`, care must be
* taken to not create reentrancy vulnerabilities. Consider using
* {ReentrancyGuard} or the
* https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern].
*/
function sendValue(address payable recipient, uint256 amount) internal {
require(address(this).balance >= amount, "Address: insufficient balance");
(bool success, ) = recipient.call{value: amount}("");
require(success, "Address: unable to send value, recipient may have reverted");
}
/**
* @dev Performs a Solidity function call using a low level `call`. A
* plain `call` is an unsafe replacement for a function call: use this
* function instead.
*
* If `target` reverts with a revert reason, it is bubbled up by this
* function (like regular Solidity function calls).
*
* Returns the raw returned data. To convert to the expected return value,
* use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`].
*
* Requirements:
*
* - `target` must be a contract.
* - calling `target` with `data` must not revert.
*
* _Available since v3.1._
*/
function functionCall(address target, bytes memory data) internal returns (bytes memory) {
return functionCall(target, data, "Address: low-level call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with
* `errorMessage` as a fallback revert reason when `target` reverts.
*
* _Available since v3.1._
*/
function functionCall(
address target,
bytes memory data,
string memory errorMessage
) internal returns (bytes memory) {
return functionCallWithValue(target, data, 0, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but also transferring `value` wei to `target`.
*
* Requirements:
*
* - the calling contract must have an ETH balance of at least `value`.
* - the called Solidity function must be `payable`.
*
* _Available since v3.1._
*/
function functionCallWithValue(
address target,
bytes memory data,
uint256 value
) internal returns (bytes memory) {
return functionCallWithValue(target, data, value, "Address: low-level call with value failed");
}
/**
* @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but
* with `errorMessage` as a fallback revert reason when `target` reverts.
*
* _Available since v3.1._
*/
function functionCallWithValue(
address target,
bytes memory data,
uint256 value,
string memory errorMessage
) internal returns (bytes memory) {
require(address(this).balance >= value, "Address: insufficient balance for call");
require(isContract(target), "Address: call to non-contract");
(bool success, bytes memory returndata) = target.call{value: value}(data);
return verifyCallResult(success, returndata, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but performing a static call.
*
* _Available since v3.3._
*/
function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) {
return functionStaticCall(target, data, "Address: low-level static call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`],
* but performing a static call.
*
* _Available since v3.3._
*/
function functionStaticCall(
address target,
bytes memory data,
string memory errorMessage
) internal view returns (bytes memory) {
require(isContract(target), "Address: static call to non-contract");
(bool success, bytes memory returndata) = target.staticcall(data);
return verifyCallResult(success, returndata, errorMessage);
}
/**
* @dev Tool to verifies that a low level call was successful, and revert if it wasn't, either by bubbling the
* revert reason using the provided one.
*
* _Available since v4.3._
*/
function verifyCallResult(
bool success,
bytes memory returndata,
string memory errorMessage
) internal pure returns (bytes memory) {
if (success) {
return returndata;
} else {
// Look for revert reason and bubble it up if present
if (returndata.length > 0) {
// The easiest way to bubble the revert reason is using memory via assembly
assembly {
let returndata_size := mload(returndata)
revert(add(32, returndata), returndata_size)
}
} else {
revert(errorMessage);
}
}
}
}
// File: contracts/interfaces/ICollectionContractInitializer.sol
// SPDX-License-Identifier: MIT OR Apache-2.0
pragma solidity ^0.8.0;
interface ICollectionContractInitializer {
function initialize(
address payable _creator,
string memory _name,
string memory _symbol
) external;
}
// File: contracts/interfaces/ICollectionFactory.sol
// SPDX-License-Identifier: MIT OR Apache-2.0
pragma solidity ^0.8.0;
import "./IRoles.sol";
import "./IProxyCall.sol";
interface ICollectionFactory {
function rolesContract() external returns (IRoles);
function proxyCallContract() external returns (IProxyCall);
}
// File: contracts/interfaces/IGetRoyalties.sol
// SPDX-License-Identifier: MIT OR Apache-2.0
pragma solidity ^0.8.0;
interface IGetRoyalties {
function getRoyalties(uint256 tokenId)
external
view
returns (address payable[] memory recipients, uint256[] memory feesInBasisPoints);
}
// File: contracts/interfaces/IProxyCall.sol
// SPDX-License-Identifier: MIT OR Apache-2.0
pragma solidity ^0.8.0;
interface IProxyCall {
function proxyCallAndReturnAddress(address externalContract, bytes calldata callData)
external
returns (address payable result);
}
// File: contracts/interfaces/ITokenCreator.sol
// SPDX-License-Identifier: MIT OR Apache-2.0
pragma solidity ^0.8.0;
interface ITokenCreator {
function tokenCreator(uint256 tokenId) external view returns (address payable);
}
// File: contracts/interfaces/ITokenCreatorPaymentAddress.sol
// SPDX-License-Identifier: MIT OR Apache-2.0
pragma solidity ^0.8.0;
interface ITokenCreatorPaymentAddress {
function getTokenCreatorPaymentAddress(uint256 tokenId)
external
view
returns (address payable tokenCreatorPaymentAddress);
}
// File: contracts/interfaces/IGetFees.sol
// SPDX-License-Identifier: MIT OR Apache-2.0
pragma solidity ^0.8.0;
/**
* @notice An interface for communicating fees to 3rd party marketplaces.
* @dev Originally implemented in mainnet contract 0x44d6e8933f8271abcf253c72f9ed7e0e4c0323b3
*/
interface IGetFees {
function getFeeRecipients(uint256 id) external view returns (address payable[] memory);
function getFeeBps(uint256 id) external view returns (uint256[] memory);
}
// File: contracts/libraries/AccountMigrationLibrary.sol
// SPDX-License-Identifier: MIT OR Apache-2.0
pragma solidity ^0.8.0;
import "@openzeppelin/contracts/utils/cryptography/ECDSA.sol";
import "@openzeppelin/contracts/utils/cryptography/SignatureChecker.sol";
import "@openzeppelin/contracts/utils/Strings.sol";
/**
* @notice Checks for a valid signature authorizing the migration of an account to a new address.
* @dev This is shared by both the NFT contracts and FNDNFTMarket, and the same signature authorizes both.
*/
library AccountMigrationLibrary {
using ECDSA for bytes;
using SignatureChecker for address;
using Strings for uint256;
// From https://ethereum.stackexchange.com/questions/8346/convert-address-to-string
function _toAsciiString(address x) private pure returns (string memory) {
bytes memory s = new bytes(42);
s[0] = "0";
s[1] = "x";
for (uint256 i = 0; i < 20; i++) {
bytes1 b = bytes1(uint8(uint256(uint160(x)) / (2**(8 * (19 - i)))));
bytes1 hi = bytes1(uint8(b) / 16);
bytes1 lo = bytes1(uint8(b) - 16 * uint8(hi));
s[2 * i + 2] = _char(hi);
s[2 * i + 3] = _char(lo);
}
return string(s);
}
function _char(bytes1 b) private pure returns (bytes1 c) {
if (uint8(b) < 10) return bytes1(uint8(b) + 0x30);
else return bytes1(uint8(b) + 0x57);
}
/**
* @dev Confirms the msg.sender is a Foundation operator and that the signature provided is valid.
* @param signature Message `I authorize Foundation to migrate my account to ${newAccount.address.toLowerCase()}`
* signed by the original account.
*/
function requireAuthorizedAccountMigration(
address originalAddress,
address newAddress,
bytes memory signature
) internal view {
require(originalAddress != newAddress, "AccountMigration: Cannot migrate to the same account");
bytes32 hash = abi
.encodePacked("I authorize Foundation to migrate my account to ", _toAsciiString(newAddress))
.toEthSignedMessageHash();
require(
originalAddress.isValidSignatureNow(hash, signature),
"AccountMigration: Signature must be from the original account"
);
}
}
// File: contracts/libraries/ProxyCall.sol
// SPDX-License-Identifier: MIT OR Apache-2.0
pragma solidity ^0.8.0;
import "@openzeppelin/contracts-upgradeable/utils/AddressUpgradeable.sol";
import "../interfaces/IProxyCall.sol";
/**
* @notice Forwards arbitrary calls to an external contract to be processed.
* @dev This is used so that the from address of the calling contract does not have
* any special permissions (e.g. ERC-20 transfer).
*/
library ProxyCall {
using AddressUpgradeable for address payable;
/**
* @dev Used by other mixins to make external calls through the proxy contract.
* This will fail if the proxyCall address is address(0).
*/
function proxyCallAndReturnContractAddress(
IProxyCall proxyCall,
address externalContract,
bytes memory callData
) internal returns (address payable result) {
result = proxyCall.proxyCallAndReturnAddress(externalContract, callData);
require(result.isContract(), "ProxyCall: address returned is not a contract");
}
}
// File: contracts/libraries/BytesLibrary.sol
// SPDX-License-Identifier: MIT OR Apache-2.0
pragma solidity ^0.8.0;
/**
* @notice A library for manipulation of byte arrays.
*/
library BytesLibrary {
/**
* @dev Replace the address at the given location in a byte array if the contents at that location
* match the expected address.
*/
function replaceAtIf(
bytes memory data,
uint256 startLocation,
address expectedAddress,
address newAddress
) internal pure {
bytes memory expectedData = abi.encodePacked(expectedAddress);
bytes memory newData = abi.encodePacked(newAddress);
// An address is 20 bytes long
for (uint256 i = 0; i < 20; i++) {
uint256 dataLocation = startLocation + i;
require(data[dataLocation] == expectedData[i], "Bytes: Data provided does not include the expectedAddress");
data[dataLocation] = newData[i];
}
}
/**
* @dev Checks if the call data starts with the given function signature.
*/
function startsWith(bytes memory callData, bytes4 functionSig) internal pure returns (bool) {
// A signature is 4 bytes long
if (callData.length < 4) {
return false;
}
for (uint256 i = 0; i < 4; i++) {
if (callData[i] != functionSig[i]) {
return false;
}
}
return true;
}
}
// File: contracts/interfaces/IRoyaltyInfo.sol
// SPDX-License-Identifier: MIT OR Apache-2.0
pragma solidity ^0.8.0;
/**
* @notice Interface for EIP-2981: NFT Royalty Standard.
* For more see: https://eips.ethereum.org/EIPS/eip-2981.
*/
interface IRoyaltyInfo {
/// @notice Called with the sale price to determine how much royalty
// is owed and to whom.
/// @param _tokenId - the NFT asset queried for royalty information
/// @param _salePrice - the sale price of the NFT asset specified by _tokenId
/// @return receiver - address of who should be sent the royalty payment
/// @return royaltyAmount - the royalty payment amount for _salePrice
function royaltyInfo(uint256 _tokenId, uint256 _salePrice)
external
view
returns (address receiver, uint256 royaltyAmount);
}
// File: @openzeppelin/contracts-upgradeable/token/ERC721/ERC721Upgradeable.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (token/ERC721/ERC721.sol)
pragma solidity ^0.8.0;
import "./IERC721Upgradeable.sol";
import "./IERC721ReceiverUpgradeable.sol";
import "./extensions/IERC721MetadataUpgradeable.sol";
import "../../utils/AddressUpgradeable.sol";
import "../../utils/ContextUpgradeable.sol";
import "../../utils/StringsUpgradeable.sol";
import "../../utils/introspection/ERC165Upgradeable.sol";
import "../../proxy/utils/Initializable.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 ERC721Upgradeable is Initializable, ContextUpgradeable, ERC165Upgradeable, IERC721Upgradeable, IERC721MetadataUpgradeable {
using AddressUpgradeable for address;
using StringsUpgradeable 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.
*/
function __ERC721_init(string memory name_, string memory symbol_) internal onlyInitializing {
__Context_init_unchained();
__ERC165_init_unchained();
__ERC721_init_unchained(name_, symbol_);
}
function __ERC721_init_unchained(string memory name_, string memory symbol_) internal onlyInitializing {
_name = name_;
_symbol = symbol_;
}
/**
* @dev See {IERC165-supportsInterface}.
*/
function supportsInterface(bytes4 interfaceId) public view virtual override(ERC165Upgradeable, IERC165Upgradeable) returns (bool) {
return
interfaceId == type(IERC721Upgradeable).interfaceId ||
interfaceId == type(IERC721MetadataUpgradeable).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 = ERC721Upgradeable.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 = ERC721Upgradeable.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 = ERC721Upgradeable.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(ERC721Upgradeable.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(ERC721Upgradeable.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 IERC721ReceiverUpgradeable(to).onERC721Received(_msgSender(), from, tokenId, _data) returns (bytes4 retval) {
return retval == IERC721ReceiverUpgradeable.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 {}
uint256[44] private __gap;
}
// File: @openzeppelin/contracts-upgradeable/utils/ContextUpgradeable.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (utils/Context.sol)
pragma solidity ^0.8.0;
import "../proxy/utils/Initializable.sol";
/**
* @dev Provides information about the current execution context, including the
* sender of the transaction and its data. While these are generally available
* via msg.sender and msg.data, they should not be accessed in such a direct
* manner, since when dealing with meta-transactions the account sending and
* paying for execution may not be the actual sender (as far as an application
* is concerned).
*
* This contract is only required for intermediate, library-like contracts.
*/
abstract contract ContextUpgradeable is Initializable {
function __Context_init() internal onlyInitializing {
__Context_init_unchained();
}
function __Context_init_unchained() internal onlyInitializing {
}
function _msgSender() internal view virtual returns (address) {
return msg.sender;
}
function _msgData() internal view virtual returns (bytes calldata) {
return msg.data;
}
uint256[50] private __gap;
}
// File: @openzeppelin/contracts-upgradeable/proxy/utils/Initializable.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (proxy/utils/Initializable.sol)
pragma solidity ^0.8.0;
import "../../utils/AddressUpgradeable.sol";
/**
* @dev This is a base contract to aid in writing upgradeable contracts, or any kind of contract that will be deployed
* behind a proxy. Since a proxied contract can't have a constructor, it's common to move constructor logic to an
* external initializer function, usually called `initialize`. It then becomes necessary to protect this initializer
* function so it can only be called once. The {initializer} modifier provided by this contract will have this effect.
*
* TIP: To avoid leaving the proxy in an uninitialized state, the initializer function should be called as early as
* possible by providing the encoded function call as the `_data` argument to {ERC1967Proxy-constructor}.
*
* CAUTION: When used with inheritance, manual care must be taken to not invoke a parent initializer twice, or to ensure
* that all initializers are idempotent. This is not verified automatically as constructors are by Solidity.
*
* [CAUTION]
* ====
* Avoid leaving a contract uninitialized.
*
* An uninitialized contract can be taken over by an attacker. This applies to both a proxy and its implementation
* contract, which may impact the proxy. To initialize the implementation contract, you can either invoke the
* initializer manually, or you can include a constructor to automatically mark it as initialized when it is deployed:
*
* [.hljs-theme-light.nopadding]
* ```
* /// @custom:oz-upgrades-unsafe-allow constructor
* constructor() initializer {}
* ```
* ====
*/
abstract contract Initializable {
/**
* @dev Indicates that the contract has been initialized.
*/
bool private _initialized;
/**
* @dev Indicates that the contract is in the process of being initialized.
*/
bool private _initializing;
/**
* @dev Modifier to protect an initializer function from being invoked twice.
*/
modifier initializer() {
// If the contract is initializing we ignore whether _initialized is set in order to support multiple
// inheritance patterns, but we only do this in the context of a constructor, because in other contexts the
// contract may have been reentered.
require(_initializing ? _isConstructor() : !_initialized, "Initializable: contract is already initialized");
bool isTopLevelCall = !_initializing;
if (isTopLevelCall) {
_initializing = true;
_initialized = true;
}
_;
if (isTopLevelCall) {
_initializing = false;
}
}
/**
* @dev Modifier to protect an initialization function so that it can only be invoked by functions with the
* {initializer} modifier, directly or indirectly.
*/
modifier onlyInitializing() {
require(_initializing, "Initializable: contract is not initializing");
_;
}
function _isConstructor() private view returns (bool) {
return !AddressUpgradeable.isContract(address(this));
}
}
// File: @openzeppelin/contracts-upgradeable/token/ERC721/IERC721Upgradeable.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (token/ERC721/IERC721.sol)
pragma solidity ^0.8.0;
import "../../utils/introspection/IERC165Upgradeable.sol";
/**
* @dev Required interface of an ERC721 compliant contract.
*/
interface IERC721Upgradeable is IERC165Upgradeable {
/**
* @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-upgradeable/token/ERC721/IERC721ReceiverUpgradeable.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (token/ERC721/IERC721Receiver.sol)
pragma solidity ^0.8.0;
/**
* @title ERC721 token receiver interface
* @dev Interface for any contract that wants to support safeTransfers
* from ERC721 asset contracts.
*/
interface IERC721ReceiverUpgradeable {
/**
* @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-upgradeable/token/ERC721/extensions/IERC721MetadataUpgradeable.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (token/ERC721/extensions/IERC721Metadata.sol)
pragma solidity ^0.8.0;
import "../IERC721Upgradeable.sol";
/**
* @title ERC-721 Non-Fungible Token Standard, optional metadata extension
* @dev See https://eips.ethereum.org/EIPS/eip-721
*/
interface IERC721MetadataUpgradeable is IERC721Upgradeable {
/**
* @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-upgradeable/utils/StringsUpgradeable.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (utils/Strings.sol)
pragma solidity ^0.8.0;
/**
* @dev String operations.
*/
library StringsUpgradeable {
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-upgradeable/utils/introspection/ERC165Upgradeable.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (utils/introspection/ERC165.sol)
pragma solidity ^0.8.0;
import "./IERC165Upgradeable.sol";
import "../../proxy/utils/Initializable.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 ERC165Upgradeable is Initializable, IERC165Upgradeable {
function __ERC165_init() internal onlyInitializing {
__ERC165_init_unchained();
}
function __ERC165_init_unchained() internal onlyInitializing {
}
/**
* @dev See {IERC165-supportsInterface}.
*/
function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) {
return interfaceId == type(IERC165Upgradeable).interfaceId;
}
uint256[50] private __gap;
}
// File: @openzeppelin/contracts-upgradeable/utils/introspection/IERC165Upgradeable.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (utils/introspection/IERC165.sol)
pragma solidity ^0.8.0;
/**
* @dev Interface of the ERC165 standard, as defined in the
* https://eips.ethereum.org/EIPS/eip-165[EIP].
*
* Implementers can declare support of contract interfaces, which can then be
* queried by others ({ERC165Checker}).
*
* For an implementation, see {ERC165}.
*/
interface IERC165Upgradeable {
/**
* @dev Returns true if this contract implements the interface defined by
* `interfaceId`. See the corresponding
* https://eips.ethereum.org/EIPS/eip-165#how-interfaces-are-identified[EIP section]
* to learn more about how these ids are created.
*
* This function call must use less than 30 000 gas.
*/
function supportsInterface(bytes4 interfaceId) external view returns (bool);
}
// File: contracts/interfaces/IRoles.sol
// SPDX-License-Identifier: MIT OR Apache-2.0
pragma solidity ^0.8.0;
/**
* @notice Interface for a contract which implements admin roles.
*/
interface IRoles {
function isAdmin(address account) external view returns (bool);
function isOperator(address account) external view returns (bool);
}
// File: @openzeppelin/contracts/utils/cryptography/ECDSA.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (utils/cryptography/ECDSA.sol)
pragma solidity ^0.8.0;
import "../Strings.sol";
/**
* @dev Elliptic Curve Digital Signature Algorithm (ECDSA) operations.
*
* These functions can be used to verify that a message was signed by the holder
* of the private keys of a given address.
*/
library ECDSA {
enum RecoverError {
NoError,
InvalidSignature,
InvalidSignatureLength,
InvalidSignatureS,
InvalidSignatureV
}
function _throwError(RecoverError error) private pure {
if (error == RecoverError.NoError) {
return; // no error: do nothing
} else if (error == RecoverError.InvalidSignature) {
revert("ECDSA: invalid signature");
} else if (error == RecoverError.InvalidSignatureLength) {
revert("ECDSA: invalid signature length");
} else if (error == RecoverError.InvalidSignatureS) {
revert("ECDSA: invalid signature 's' value");
} else if (error == RecoverError.InvalidSignatureV) {
revert("ECDSA: invalid signature 'v' value");
}
}
/**
* @dev Returns the address that signed a hashed message (`hash`) with
* `signature` or error string. This address can then be used for verification purposes.
*
* The `ecrecover` EVM opcode allows for malleable (non-unique) signatures:
* this function rejects them by requiring the `s` value to be in the lower
* half order, and the `v` value to be either 27 or 28.
*
* IMPORTANT: `hash` _must_ be the result of a hash operation for the
* verification to be secure: it is possible to craft signatures that
* recover to arbitrary addresses for non-hashed data. A safe way to ensure
* this is by receiving a hash of the original message (which may otherwise
* be too long), and then calling {toEthSignedMessageHash} on it.
*
* Documentation for signature generation:
* - with https://web3js.readthedocs.io/en/v1.3.4/web3-eth-accounts.html#sign[Web3.js]
* - with https://docs.ethers.io/v5/api/signer/#Signer-signMessage[ethers]
*
* _Available since v4.3._
*/
function tryRecover(bytes32 hash, bytes memory signature) internal pure returns (address, RecoverError) {
// Check the signature length
// - case 65: r,s,v signature (standard)
// - case 64: r,vs signature (cf https://eips.ethereum.org/EIPS/eip-2098) _Available since v4.1._
if (signature.length == 65) {
bytes32 r;
bytes32 s;
uint8 v;
// ecrecover takes the signature parameters, and the only way to get them
// currently is to use assembly.
assembly {
r := mload(add(signature, 0x20))
s := mload(add(signature, 0x40))
v := byte(0, mload(add(signature, 0x60)))
}
return tryRecover(hash, v, r, s);
} else if (signature.length == 64) {
bytes32 r;
bytes32 vs;
// ecrecover takes the signature parameters, and the only way to get them
// currently is to use assembly.
assembly {
r := mload(add(signature, 0x20))
vs := mload(add(signature, 0x40))
}
return tryRecover(hash, r, vs);
} else {
return (address(0), RecoverError.InvalidSignatureLength);
}
}
/**
* @dev Returns the address that signed a hashed message (`hash`) with
* `signature`. This address can then be used for verification purposes.
*
* The `ecrecover` EVM opcode allows for malleable (non-unique) signatures:
* this function rejects them by requiring the `s` value to be in the lower
* half order, and the `v` value to be either 27 or 28.
*
* IMPORTANT: `hash` _must_ be the result of a hash operation for the
* verification to be secure: it is possible to craft signatures that
* recover to arbitrary addresses for non-hashed data. A safe way to ensure
* this is by receiving a hash of the original message (which may otherwise
* be too long), and then calling {toEthSignedMessageHash} on it.
*/
function recover(bytes32 hash, bytes memory signature) internal pure returns (address) {
(address recovered, RecoverError error) = tryRecover(hash, signature);
_throwError(error);
return recovered;
}
/**
* @dev Overload of {ECDSA-tryRecover} that receives the `r` and `vs` short-signature fields separately.
*
* See https://eips.ethereum.org/EIPS/eip-2098[EIP-2098 short signatures]
*
* _Available since v4.3._
*/
function tryRecover(
bytes32 hash,
bytes32 r,
bytes32 vs
) internal pure returns (address, RecoverError) {
bytes32 s;
uint8 v;
assembly {
s := and(vs, 0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff)
v := add(shr(255, vs), 27)
}
return tryRecover(hash, v, r, s);
}
/**
* @dev Overload of {ECDSA-recover} that receives the `r and `vs` short-signature fields separately.
*
* _Available since v4.2._
*/
function recover(
bytes32 hash,
bytes32 r,
bytes32 vs
) internal pure returns (address) {
(address recovered, RecoverError error) = tryRecover(hash, r, vs);
_throwError(error);
return recovered;
}
/**
* @dev Overload of {ECDSA-tryRecover} that receives the `v`,
* `r` and `s` signature fields separately.
*
* _Available since v4.3._
*/
function tryRecover(
bytes32 hash,
uint8 v,
bytes32 r,
bytes32 s
) internal pure returns (address, RecoverError) {
// EIP-2 still allows signature malleability for ecrecover(). Remove this possibility and make the signature
// unique. Appendix F in the Ethereum Yellow paper (https://ethereum.github.io/yellowpaper/paper.pdf), defines
// the valid range for s in (301): 0 < s < secp256k1n ÷ 2 + 1, and for v in (302): v ∈ {27, 28}. Most
// signatures from current libraries generate a unique signature with an s-value in the lower half order.
//
// If your library generates malleable signatures, such as s-values in the upper range, calculate a new s-value
// with 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFEBAAEDCE6AF48A03BBFD25E8CD0364141 - s1 and flip v from 27 to 28 or
// vice versa. If your library also generates signatures with 0/1 for v instead 27/28, add 27 to v to accept
// these malleable signatures as well.
if (uint256(s) > 0x7FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF5D576E7357A4501DDFE92F46681B20A0) {
return (address(0), RecoverError.InvalidSignatureS);
}
if (v != 27 && v != 28) {
return (address(0), RecoverError.InvalidSignatureV);
}
// If the signature is valid (and not malleable), return the signer address
address signer = ecrecover(hash, v, r, s);
if (signer == address(0)) {
return (address(0), RecoverError.InvalidSignature);
}
return (signer, RecoverError.NoError);
}
/**
* @dev Overload of {ECDSA-recover} that receives the `v`,
* `r` and `s` signature fields separately.
*/
function recover(
bytes32 hash,
uint8 v,
bytes32 r,
bytes32 s
) internal pure returns (address) {
(address recovered, RecoverError error) = tryRecover(hash, v, r, s);
_throwError(error);
return recovered;
}
/**
* @dev Returns an Ethereum Signed Message, created from a `hash`. This
* produces hash corresponding to the one signed with the
* https://eth.wiki/json-rpc/API#eth_sign[`eth_sign`]
* JSON-RPC method as part of EIP-191.
*
* See {recover}.
*/
function toEthSignedMessageHash(bytes32 hash) internal pure returns (bytes32) {
// 32 is the length in bytes of hash,
// enforced by the type signature above
return keccak256(abi.encodePacked("\x19Ethereum Signed Message:\n32", hash));
}
/**
* @dev Returns an Ethereum Signed Message, created from `s`. This
* produces hash corresponding to the one signed with the
* https://eth.wiki/json-rpc/API#eth_sign[`eth_sign`]
* JSON-RPC method as part of EIP-191.
*
* See {recover}.
*/
function toEthSignedMessageHash(bytes memory s) internal pure returns (bytes32) {
return keccak256(abi.encodePacked("\x19Ethereum Signed Message:\n", Strings.toString(s.length), s));
}
/**
* @dev Returns an Ethereum Signed Typed Data, created from a
* `domainSeparator` and a `structHash`. This produces hash corresponding
* to the one signed with the
* https://eips.ethereum.org/EIPS/eip-712[`eth_signTypedData`]
* JSON-RPC method as part of EIP-712.
*
* See {recover}.
*/
function toTypedDataHash(bytes32 domainSeparator, bytes32 structHash) internal pure returns (bytes32) {
return keccak256(abi.encodePacked("\x19\x01", domainSeparator, structHash));
}
}
// File: @openzeppelin/contracts/utils/cryptography/SignatureChecker.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (utils/cryptography/SignatureChecker.sol)
pragma solidity ^0.8.0;
import "./ECDSA.sol";
import "../Address.sol";
import "../../interfaces/IERC1271.sol";
/**
* @dev Signature verification helper: Provide a single mechanism to verify both private-key (EOA) ECDSA signature and
* ERC1271 contract signatures. Using this instead of ECDSA.recover in your contract will make them compatible with
* smart contract wallets such as Argent and Gnosis.
*
* Note: unlike ECDSA signatures, contract signature's are revocable, and the outcome of this function can thus change
* through time. It could return true at block N and false at block N+1 (or the opposite).
*
* _Available since v4.1._
*/
library SignatureChecker {
function isValidSignatureNow(
address signer,
bytes32 hash,
bytes memory signature
) internal view returns (bool) {
(address recovered, ECDSA.RecoverError error) = ECDSA.tryRecover(hash, signature);
if (error == ECDSA.RecoverError.NoError && recovered == signer) {
return true;
}
(bool success, bytes memory result) = signer.staticcall(
abi.encodeWithSelector(IERC1271.isValidSignature.selector, hash, signature)
);
return (success && result.length == 32 && abi.decode(result, (bytes4)) == IERC1271.isValidSignature.selector);
}
}
// File: @openzeppelin/contracts/utils/Strings.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (utils/Strings.sol)
pragma solidity ^0.8.0;
/**
* @dev String operations.
*/
library Strings {
bytes16 private constant _HEX_SYMBOLS = "0123456789abcdef";
/**
* @dev Converts a `uint256` to its ASCII `string` decimal representation.
*/
function toString(uint256 value) internal pure returns (string memory) {
// Inspired by OraclizeAPI's implementation - MIT licence
// https://github.com/oraclize/ethereum-api/blob/b42146b063c7d6ee1358846c198246239e9360e8/oraclizeAPI_0.4.25.sol
if (value == 0) {
return "0";
}
uint256 temp = value;
uint256 digits;
while (temp != 0) {
digits++;
temp /= 10;
}
bytes memory buffer = new bytes(digits);
while (value != 0) {
digits -= 1;
buffer[digits] = bytes1(uint8(48 + uint256(value % 10)));
value /= 10;
}
return string(buffer);
}
/**
* @dev Converts a `uint256` to its ASCII `string` hexadecimal representation.
*/
function toHexString(uint256 value) internal pure returns (string memory) {
if (value == 0) {
return "0x00";
}
uint256 temp = value;
uint256 length = 0;
while (temp != 0) {
length++;
temp >>= 8;
}
return toHexString(value, length);
}
/**
* @dev Converts a `uint256` to its ASCII `string` hexadecimal representation with fixed length.
*/
function toHexString(uint256 value, uint256 length) internal pure returns (string memory) {
bytes memory buffer = new bytes(2 * length + 2);
buffer[0] = "0";
buffer[1] = "x";
for (uint256 i = 2 * length + 1; i > 1; --i) {
buffer[i] = _HEX_SYMBOLS[value & 0xf];
value >>= 4;
}
require(value == 0, "Strings: hex length insufficient");
return string(buffer);
}
}
// File: @openzeppelin/contracts/utils/Address.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (utils/Address.sol)
pragma solidity ^0.8.0;
/**
* @dev Collection of functions related to the address type
*/
library Address {
/**
* @dev Returns true if `account` is a contract.
*
* [IMPORTANT]
* ====
* It is unsafe to assume that an address for which this function returns
* false is an externally-owned account (EOA) and not a contract.
*
* Among others, `isContract` will return false for the following
* types of addresses:
*
* - an externally-owned account
* - a contract in construction
* - an address where a contract will be created
* - an address where a contract lived, but was destroyed
* ====
*/
function isContract(address account) internal view returns (bool) {
// This method relies on extcodesize, which returns 0 for contracts in
// construction, since the code is only stored at the end of the
// constructor execution.
uint256 size;
assembly {
size := extcodesize(account)
}
return size > 0;
}
/**
* @dev Replacement for Solidity's `transfer`: sends `amount` wei to
* `recipient`, forwarding all available gas and reverting on errors.
*
* https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost
* of certain opcodes, possibly making contracts go over the 2300 gas limit
* imposed by `transfer`, making them unable to receive funds via
* `transfer`. {sendValue} removes this limitation.
*
* https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more].
*
* IMPORTANT: because control is transferred to `recipient`, care must be
* taken to not create reentrancy vulnerabilities. Consider using
* {ReentrancyGuard} or the
* https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern].
*/
function sendValue(address payable recipient, uint256 amount) internal {
require(address(this).balance >= amount, "Address: insufficient balance");
(bool success, ) = recipient.call{value: amount}("");
require(success, "Address: unable to send value, recipient may have reverted");
}
/**
* @dev Performs a Solidity function call using a low level `call`. A
* plain `call` is an unsafe replacement for a function call: use this
* function instead.
*
* If `target` reverts with a revert reason, it is bubbled up by this
* function (like regular Solidity function calls).
*
* Returns the raw returned data. To convert to the expected return value,
* use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`].
*
* Requirements:
*
* - `target` must be a contract.
* - calling `target` with `data` must not revert.
*
* _Available since v3.1._
*/
function functionCall(address target, bytes memory data) internal returns (bytes memory) {
return functionCall(target, data, "Address: low-level call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with
* `errorMessage` as a fallback revert reason when `target` reverts.
*
* _Available since v3.1._
*/
function functionCall(
address target,
bytes memory data,
string memory errorMessage
) internal returns (bytes memory) {
return functionCallWithValue(target, data, 0, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but also transferring `value` wei to `target`.
*
* Requirements:
*
* - the calling contract must have an ETH balance of at least `value`.
* - the called Solidity function must be `payable`.
*
* _Available since v3.1._
*/
function functionCallWithValue(
address target,
bytes memory data,
uint256 value
) internal returns (bytes memory) {
return functionCallWithValue(target, data, value, "Address: low-level call with value failed");
}
/**
* @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but
* with `errorMessage` as a fallback revert reason when `target` reverts.
*
* _Available since v3.1._
*/
function functionCallWithValue(
address target,
bytes memory data,
uint256 value,
string memory errorMessage
) internal returns (bytes memory) {
require(address(this).balance >= value, "Address: insufficient balance for call");
require(isContract(target), "Address: call to non-contract");
(bool success, bytes memory returndata) = target.call{value: value}(data);
return verifyCallResult(success, returndata, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but performing a static call.
*
* _Available since v3.3._
*/
function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) {
return functionStaticCall(target, data, "Address: low-level static call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`],
* but performing a static call.
*
* _Available since v3.3._
*/
function functionStaticCall(
address target,
bytes memory data,
string memory errorMessage
) internal view returns (bytes memory) {
require(isContract(target), "Address: static call to non-contract");
(bool success, bytes memory returndata) = target.staticcall(data);
return verifyCallResult(success, returndata, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but performing a delegate call.
*
* _Available since v3.4._
*/
function functionDelegateCall(address target, bytes memory data) internal returns (bytes memory) {
return functionDelegateCall(target, data, "Address: low-level delegate call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`],
* but performing a delegate call.
*
* _Available since v3.4._
*/
function functionDelegateCall(
address target,
bytes memory data,
string memory errorMessage
) internal returns (bytes memory) {
require(isContract(target), "Address: delegate call to non-contract");
(bool success, bytes memory returndata) = target.delegatecall(data);
return verifyCallResult(success, returndata, errorMessage);
}
/**
* @dev Tool to verifies that a low level call was successful, and revert if it wasn't, either by bubbling the
* revert reason using the provided one.
*
* _Available since v4.3._
*/
function verifyCallResult(
bool success,
bytes memory returndata,
string memory errorMessage
) internal pure returns (bytes memory) {
if (success) {
return returndata;
} else {
// Look for revert reason and bubble it up if present
if (returndata.length > 0) {
// The easiest way to bubble the revert reason is using memory via assembly
assembly {
let returndata_size := mload(returndata)
revert(add(32, returndata), returndata_size)
}
} else {
revert(errorMessage);
}
}
}
}
// File: @openzeppelin/contracts/interfaces/IERC1271.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (interfaces/IERC1271.sol)
pragma solidity ^0.8.0;
/**
* @dev Interface of the ERC1271 standard signature validation method for
* contracts as defined in https://eips.ethereum.org/EIPS/eip-1271[ERC-1271].
*
* _Available since v4.1._
*/
interface IERC1271 {
/**
* @dev Should return whether the signature provided is valid for the provided data
* @param hash Hash of the data to be signed
* @param signature Signature byte array associated with _data
*/
function isValidSignature(bytes32 hash, bytes memory signature) external view returns (bytes4 magicValue);
}
|
[{"inputs":[{"internalType":"address","name":"_collectionFactory","type":"address"}],"stateMutability":"nonpayable","type":"constructor"},{"anonymous":false,"inputs":[{"indexed":true,"internalType":"address","name":"owner","type":"address"},{"indexed":true,"internalType":"address","name":"approved","type":"address"},{"indexed":true,"internalType":"uint256","name":"tokenId","type":"uint256"}],"name":"Approval","type":"event"},{"anonymous":false,"inputs":[{"indexed":true,"internalType":"address","name":"owner","type":"address"},{"indexed":true,"internalType":"address","name":"operator","type":"address"},{"indexed":false,"internalType":"bool","name":"approved","type":"bool"}],"name":"ApprovalForAll","type":"event"},{"anonymous":false,"inputs":[{"indexed":false,"internalType":"string","name":"baseURI","type":"string"}],"name":"BaseURIUpdated","type":"event"},{"anonymous":false,"inputs":[{"indexed":true,"internalType":"address","name":"originalAddress","type":"address"},{"indexed":true,"internalType":"address","name":"newAddress","type":"address"}],"name":"CreatorMigrated","type":"event"},{"anonymous":false,"inputs":[{"indexed":true,"internalType":"uint256","name":"maxTokenId","type":"uint256"}],"name":"MaxTokenIdUpdated","type":"event"},{"anonymous":false,"inputs":[{"indexed":true,"internalType":"address","name":"creator","type":"address"},{"indexed":true,"internalType":"uint256","name":"tokenId","type":"uint256"},{"indexed":true,"internalType":"string","name":"indexedTokenCID","type":"string"},{"indexed":false,"internalType":"string","name":"tokenCID","type":"string"}],"name":"Minted","type":"event"},{"anonymous":false,"inputs":[{"indexed":true,"internalType":"uint256","name":"tokenId","type":"uint256"},{"indexed":true,"internalType":"address","name":"originalAddress","type":"address"},{"indexed":true,"internalType":"address","name":"newAddress","type":"address"}],"name":"NFTOwnerMigrated","type":"event"},{"anonymous":false,"inputs":[{"indexed":true,"internalType":"uint256","name":"tokenId","type":"uint256"},{"indexed":true,"internalType":"address","name":"originalAddress","type":"address"},{"indexed":true,"internalType":"address","name":"newAddress","type":"address"},{"indexed":false,"internalType":"address","name":"originalPaymentAddress","type":"address"},{"indexed":false,"internalType":"address","name":"newPaymentAddress","type":"address"}],"name":"PaymentAddressMigrated","type":"event"},{"anonymous":false,"inputs":[{"indexed":true,"internalType":"address","name":"owner","type":"address"}],"name":"SelfDestruct","type":"event"},{"anonymous":false,"inputs":[{"indexed":true,"internalType":"address","name":"fromPaymentAddress","type":"address"},{"indexed":true,"internalType":"address","name":"toPaymentAddress","type":"address"},{"indexed":true,"internalType":"uint256","name":"tokenId","type":"uint256"}],"name":"TokenCreatorPaymentAddressSet","type":"event"},{"anonymous":false,"inputs":[{"indexed":true,"internalType":"address","name":"from","type":"address"},{"indexed":true,"internalType":"address","name":"to","type":"address"},{"indexed":true,"internalType":"uint256","name":"tokenId","type":"uint256"}],"name":"Transfer","type":"event"},{"inputs":[{"internalType":"uint256[]","name":"ownedTokenIds","type":"uint256[]"},{"internalType":"address","name":"originalAddress","type":"address"},{"internalType":"address payable","name":"newAddress","type":"address"},{"internalType":"bytes","name":"signature","type":"bytes"}],"name":"adminAccountMigration","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"uint256[]","name":"paymentAddressTokenIds","type":"uint256[]"},{"internalType":"address","name":"paymentAddressFactory","type":"address"},{"internalType":"bytes","name":"paymentAddressCallData","type":"bytes"},{"internalType":"uint256","name":"addressLocationInCallData","type":"uint256"},{"internalType":"address","name":"originalAddress","type":"address"},{"internalType":"address payable","name":"newAddress","type":"address"},{"internalType":"bytes","name":"signature","type":"bytes"}],"name":"adminAccountMigrationForPaymentAddresses","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"address","name":"to","type":"address"},{"internalType":"uint256","name":"tokenId","type":"uint256"}],"name":"approve","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"address","name":"owner","type":"address"}],"name":"balanceOf","outputs":[{"internalType":"uint256","name":"","type":"uint256"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"baseURI","outputs":[{"internalType":"string","name":"","type":"string"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"uint256","name":"tokenId","type":"uint256"}],"name":"burn","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[],"name":"collectionFactory","outputs":[{"internalType":"contract ICollectionFactory","name":"","type":"address"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"uint256","name":"tokenId","type":"uint256"}],"name":"getApproved","outputs":[{"internalType":"address","name":"","type":"address"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"uint256","name":"","type":"uint256"}],"name":"getFeeBps","outputs":[{"internalType":"uint256[]","name":"feesInBasisPoints","type":"uint256[]"}],"stateMutability":"pure","type":"function"},{"inputs":[{"internalType":"uint256","name":"id","type":"uint256"}],"name":"getFeeRecipients","outputs":[{"internalType":"address payable[]","name":"recipients","type":"address[]"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"string","name":"tokenCID","type":"string"}],"name":"getHasMintedCID","outputs":[{"internalType":"bool","name":"","type":"bool"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"uint256","name":"tokenId","type":"uint256"}],"name":"getRoyalties","outputs":[{"internalType":"address payable[]","name":"recipients","type":"address[]"},{"internalType":"uint256[]","name":"feesInBasisPoints","type":"uint256[]"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"uint256","name":"tokenId","type":"uint256"}],"name":"getTokenCreatorPaymentAddress","outputs":[{"internalType":"address payable","name":"tokenCreatorPaymentAddress","type":"address"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"address payable","name":"_creator","type":"address"},{"internalType":"string","name":"_name","type":"string"},{"internalType":"string","name":"_symbol","type":"string"}],"name":"initialize","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"address","name":"owner","type":"address"},{"internalType":"address","name":"operator","type":"address"}],"name":"isApprovedForAll","outputs":[{"internalType":"bool","name":"","type":"bool"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"latestTokenId","outputs":[{"internalType":"uint256","name":"","type":"uint256"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"maxTokenId","outputs":[{"internalType":"uint256","name":"","type":"uint256"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"string","name":"tokenCID","type":"string"}],"name":"mint","outputs":[{"internalType":"uint256","name":"tokenId","type":"uint256"}],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"string","name":"tokenCID","type":"string"},{"internalType":"address","name":"operator","type":"address"}],"name":"mintAndApprove","outputs":[{"internalType":"uint256","name":"tokenId","type":"uint256"}],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"string","name":"tokenCID","type":"string"},{"internalType":"address payable","name":"tokenCreatorPaymentAddress","type":"address"}],"name":"mintWithCreatorPaymentAddress","outputs":[{"internalType":"uint256","name":"tokenId","type":"uint256"}],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"string","name":"tokenCID","type":"string"},{"internalType":"address payable","name":"tokenCreatorPaymentAddress","type":"address"},{"internalType":"address","name":"operator","type":"address"}],"name":"mintWithCreatorPaymentAddressAndApprove","outputs":[{"internalType":"uint256","name":"tokenId","type":"uint256"}],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"string","name":"tokenCID","type":"string"},{"internalType":"address","name":"paymentAddressFactory","type":"address"},{"internalType":"bytes","name":"paymentAddressCallData","type":"bytes"}],"name":"mintWithCreatorPaymentFactory","outputs":[{"internalType":"uint256","name":"tokenId","type":"uint256"}],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"string","name":"tokenCID","type":"string"},{"internalType":"address","name":"paymentAddressFactory","type":"address"},{"internalType":"bytes","name":"paymentAddressCallData","type":"bytes"},{"internalType":"address","name":"operator","type":"address"}],"name":"mintWithCreatorPaymentFactoryAndApprove","outputs":[{"internalType":"uint256","name":"tokenId","type":"uint256"}],"stateMutability":"nonpayable","type":"function"},{"inputs":[],"name":"name","outputs":[{"internalType":"string","name":"","type":"string"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"owner","outputs":[{"internalType":"address payable","name":"","type":"address"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"uint256","name":"tokenId","type":"uint256"}],"name":"ownerOf","outputs":[{"internalType":"address","name":"","type":"address"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"uint256","name":"_tokenId","type":"uint256"},{"internalType":"uint256","name":"_salePrice","type":"uint256"}],"name":"royaltyInfo","outputs":[{"internalType":"address","name":"receiver","type":"address"},{"internalType":"uint256","name":"royaltyAmount","type":"uint256"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"address","name":"from","type":"address"},{"internalType":"address","name":"to","type":"address"},{"internalType":"uint256","name":"tokenId","type":"uint256"}],"name":"safeTransferFrom","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"address","name":"from","type":"address"},{"internalType":"address","name":"to","type":"address"},{"internalType":"uint256","name":"tokenId","type":"uint256"},{"internalType":"bytes","name":"_data","type":"bytes"}],"name":"safeTransferFrom","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[],"name":"selfDestruct","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"address","name":"operator","type":"address"},{"internalType":"bool","name":"approved","type":"bool"}],"name":"setApprovalForAll","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"bytes4","name":"interfaceId","type":"bytes4"}],"name":"supportsInterface","outputs":[{"internalType":"bool","name":"","type":"bool"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"symbol","outputs":[{"internalType":"string","name":"","type":"string"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"uint256","name":"","type":"uint256"}],"name":"tokenCreator","outputs":[{"internalType":"address payable","name":"","type":"address"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"uint256","name":"tokenId","type":"uint256"}],"name":"tokenURI","outputs":[{"internalType":"string","name":"","type":"string"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"totalSupply","outputs":[{"internalType":"uint256","name":"","type":"uint256"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"address","name":"from","type":"address"},{"internalType":"address","name":"to","type":"address"},{"internalType":"uint256","name":"tokenId","type":"uint256"}],"name":"transferFrom","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"string","name":"baseURIOverride","type":"string"}],"name":"updateBaseURI","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"uint256","name":"_maxTokenId","type":"uint256"}],"name":"updateMaxTokenId","outputs":[],"stateMutability":"nonpayable","type":"function"}]
|
v0.8.11+commit.d7f03943
| true
| 1,337
|
0000000000000000000000003b612a5b49e025a6e4ba4ee4fb1ef46d13588059
|
Default
| false
| ||||
BucketLenderProxy
|
0x4e28e1933d0d5ae3b1951b07648d245b2811cf14
|
Solidity
|
pragma solidity 0.4.24;
pragma experimental "v0.5.0";
// File: canonical-weth/contracts/WETH9.sol
contract WETH9 {
string public name = "Wrapped Ether";
string public symbol = "WETH";
uint8 public decimals = 18;
event Approval(address indexed src, address indexed guy, uint wad);
event Transfer(address indexed src, address indexed dst, uint wad);
event Deposit(address indexed dst, uint wad);
event Withdrawal(address indexed src, uint wad);
mapping (address => uint) public balanceOf;
mapping (address => mapping (address => uint)) public allowance;
function() external payable {
deposit();
}
function deposit() public payable {
balanceOf[msg.sender] += msg.value;
emit Deposit(msg.sender, msg.value);
}
function withdraw(uint wad) public {
require(balanceOf[msg.sender] >= wad);
balanceOf[msg.sender] -= wad;
msg.sender.transfer(wad);
emit Withdrawal(msg.sender, wad);
}
function totalSupply() public view returns (uint) {
return address(this).balance;
}
function approve(address guy, uint wad) public returns (bool) {
allowance[msg.sender][guy] = wad;
emit Approval(msg.sender, guy, wad);
return true;
}
function transfer(address dst, uint wad) public returns (bool) {
return transferFrom(msg.sender, dst, wad);
}
function transferFrom(address src, address dst, uint wad)
public
returns (bool)
{
require(balanceOf[src] >= wad);
if (src != msg.sender && allowance[src][msg.sender] != uint(-1)) {
require(allowance[src][msg.sender] >= wad);
allowance[src][msg.sender] -= wad;
}
balanceOf[src] -= wad;
balanceOf[dst] += wad;
emit Transfer(src, dst, wad);
return true;
}
}
// File: openzeppelin-solidity/contracts/math/Math.sol
/**
* @title Math
* @dev Assorted math operations
*/
library Math {
function max64(uint64 _a, uint64 _b) internal pure returns (uint64) {
return _a >= _b ? _a : _b;
}
function min64(uint64 _a, uint64 _b) internal pure returns (uint64) {
return _a < _b ? _a : _b;
}
function max256(uint256 _a, uint256 _b) internal pure returns (uint256) {
return _a >= _b ? _a : _b;
}
function min256(uint256 _a, uint256 _b) internal pure returns (uint256) {
return _a < _b ? _a : _b;
}
}
// File: openzeppelin-solidity/contracts/math/SafeMath.sol
/**
* @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: openzeppelin-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 OwnershipRenounced(address indexed previousOwner);
event OwnershipTransferred(
address indexed previousOwner,
address indexed newOwner
);
/**
* @dev The Ownable constructor sets the original `owner` of the contract to the sender
* account.
*/
constructor() public {
owner = msg.sender;
}
/**
* @dev Throws if called by any account other than the owner.
*/
modifier onlyOwner() {
require(msg.sender == owner);
_;
}
/**
* @dev Allows the current owner to relinquish control of the contract.
* @notice Renouncing to ownership will leave the contract without an owner.
* It will not be possible to call the functions with the `onlyOwner`
* modifier anymore.
*/
function renounceOwnership() public onlyOwner {
emit OwnershipRenounced(owner);
owner = address(0);
}
/**
* @dev Allows the current owner to transfer control of the contract to a newOwner.
* @param _newOwner The address to transfer ownership to.
*/
function transferOwnership(address _newOwner) public onlyOwner {
_transferOwnership(_newOwner);
}
/**
* @dev Transfers control of the contract to a newOwner.
* @param _newOwner The address to transfer ownership to.
*/
function _transferOwnership(address _newOwner) internal {
require(_newOwner != address(0));
emit OwnershipTransferred(owner, _newOwner);
owner = _newOwner;
}
}
// File: contracts/lib/AccessControlledBase.sol
/**
* @title AccessControlledBase
* @author dYdX
*
* Base functionality for access control. Requires an implementation to
* provide a way to grant and optionally revoke access
*/
contract AccessControlledBase {
// ============ State Variables ============
mapping (address => bool) public authorized;
// ============ Events ============
event AccessGranted(
address who
);
event AccessRevoked(
address who
);
// ============ Modifiers ============
modifier requiresAuthorization() {
require(
authorized[msg.sender],
"AccessControlledBase#requiresAuthorization: Sender not authorized"
);
_;
}
}
// File: contracts/lib/StaticAccessControlled.sol
/**
* @title StaticAccessControlled
* @author dYdX
*
* Allows for functions to be access controled
* Permissions cannot be changed after a grace period
*/
contract StaticAccessControlled is AccessControlledBase, Ownable {
using SafeMath for uint256;
// ============ State Variables ============
// Timestamp after which no additional access can be granted
uint256 public GRACE_PERIOD_EXPIRATION;
// ============ Constructor ============
constructor(
uint256 gracePeriod
)
public
Ownable()
{
GRACE_PERIOD_EXPIRATION = block.timestamp.add(gracePeriod);
}
// ============ Owner-Only State-Changing Functions ============
function grantAccess(
address who
)
external
onlyOwner
{
require(
block.timestamp < GRACE_PERIOD_EXPIRATION,
"StaticAccessControlled#grantAccess: Cannot grant access after grace period"
);
emit AccessGranted(who);
authorized[who] = true;
}
}
// File: contracts/lib/GeneralERC20.sol
/**
* @title GeneralERC20
* @author dYdX
*
* Interface for using ERC20 Tokens. We have to use a special interface to call ERC20 functions so
* that we dont automatically revert when calling non-compliant tokens that have no return value for
* transfer(), transferFrom(), or approve().
*/
interface GeneralERC20 {
function totalSupply(
)
external
view
returns (uint256);
function balanceOf(
address who
)
external
view
returns (uint256);
function allowance(
address owner,
address spender
)
external
view
returns (uint256);
function transfer(
address to,
uint256 value
)
external;
function transferFrom(
address from,
address to,
uint256 value
)
external;
function approve(
address spender,
uint256 value
)
external;
}
// File: contracts/lib/TokenInteract.sol
/**
* @title TokenInteract
* @author dYdX
*
* This library contains basic functions for interacting with ERC20 tokens
*/
library TokenInteract {
function balanceOf(
address token,
address owner
)
internal
view
returns (uint256)
{
return GeneralERC20(token).balanceOf(owner);
}
function allowance(
address token,
address owner,
address spender
)
internal
view
returns (uint256)
{
return GeneralERC20(token).allowance(owner, spender);
}
function approve(
address token,
address spender,
uint256 amount
)
internal
{
GeneralERC20(token).approve(spender, amount);
require(
checkSuccess(),
"TokenInteract#approve: Approval failed"
);
}
function transfer(
address token,
address to,
uint256 amount
)
internal
{
address from = address(this);
if (
amount == 0
|| from == to
) {
return;
}
GeneralERC20(token).transfer(to, amount);
require(
checkSuccess(),
"TokenInteract#transfer: Transfer failed"
);
}
function transferFrom(
address token,
address from,
address to,
uint256 amount
)
internal
{
if (
amount == 0
|| from == to
) {
return;
}
GeneralERC20(token).transferFrom(from, to, amount);
require(
checkSuccess(),
"TokenInteract#transferFrom: TransferFrom failed"
);
}
// ============ Private Helper-Functions ============
/**
* Checks the return value of the previous function up to 32 bytes. Returns true if the previous
* function returned 0 bytes or 32 bytes that are not all-zero.
*/
function checkSuccess(
)
private
pure
returns (bool)
{
uint256 returnValue = 0;
/* solium-disable-next-line security/no-inline-assembly */
assembly {
// check number of bytes returned from last function call
switch returndatasize
// no bytes returned: assume success
case 0x0 {
returnValue := 1
}
// 32 bytes returned: check if non-zero
case 0x20 {
// copy 32 bytes into scratch space
returndatacopy(0x0, 0x0, 0x20)
// load those bytes into returnValue
returnValue := mload(0x0)
}
// not sure what was returned: dont mark as success
default { }
}
return returnValue != 0;
}
}
// File: contracts/margin/TokenProxy.sol
/**
* @title TokenProxy
* @author dYdX
*
* Used to transfer tokens between addresses which have set allowance on this contract.
*/
contract TokenProxy is StaticAccessControlled {
using SafeMath for uint256;
// ============ Constructor ============
constructor(
uint256 gracePeriod
)
public
StaticAccessControlled(gracePeriod)
{}
// ============ Authorized-Only State Changing Functions ============
/**
* Transfers tokens from an address (that has set allowance on the proxy) to another address.
*
* @param token The address of the ERC20 token
* @param from The address to transfer token from
* @param to The address to transfer tokens to
* @param value The number of tokens to transfer
*/
function transferTokens(
address token,
address from,
address to,
uint256 value
)
external
requiresAuthorization
{
TokenInteract.transferFrom(
token,
from,
to,
value
);
}
// ============ Public Constant Functions ============
/**
* Getter function to get the amount of token that the proxy is able to move for a particular
* address. The minimum of 1) the balance of that address and 2) the allowance given to proxy.
*
* @param who The owner of the tokens
* @param token The address of the ERC20 token
* @return The number of tokens able to be moved by the proxy from the address specified
*/
function available(
address who,
address token
)
external
view
returns (uint256)
{
return Math.min256(
TokenInteract.allowance(token, who, address(this)),
TokenInteract.balanceOf(token, who)
);
}
}
// File: contracts/margin/Vault.sol
/**
* @title Vault
* @author dYdX
*
* Holds and transfers tokens in vaults denominated by id
*
* Vault only supports ERC20 tokens, and will not accept any tokens that require
* a tokenFallback or equivalent function (See ERC223, ERC777, etc.)
*/
contract Vault is StaticAccessControlled
{
using SafeMath for uint256;
// ============ Events ============
event ExcessTokensWithdrawn(
address indexed token,
address indexed to,
address caller
);
// ============ State Variables ============
// Address of the TokenProxy contract. Used for moving tokens.
address public TOKEN_PROXY;
// Map from vault ID to map from token address to amount of that token attributed to the
// particular vault ID.
mapping (bytes32 => mapping (address => uint256)) public balances;
// Map from token address to total amount of that token attributed to some account.
mapping (address => uint256) public totalBalances;
// ============ Constructor ============
constructor(
address proxy,
uint256 gracePeriod
)
public
StaticAccessControlled(gracePeriod)
{
TOKEN_PROXY = proxy;
}
// ============ Owner-Only State-Changing Functions ============
/**
* Allows the owner to withdraw any excess tokens sent to the vault by unconventional means,
* including (but not limited-to) token airdrops. Any tokens moved to the vault by TOKEN_PROXY
* will be accounted for and will not be withdrawable by this function.
*
* @param token ERC20 token address
* @param to Address to transfer tokens to
* @return Amount of tokens withdrawn
*/
function withdrawExcessToken(
address token,
address to
)
external
onlyOwner
returns (uint256)
{
uint256 actualBalance = TokenInteract.balanceOf(token, address(this));
uint256 accountedBalance = totalBalances[token];
uint256 withdrawableBalance = actualBalance.sub(accountedBalance);
require(
withdrawableBalance != 0,
"Vault#withdrawExcessToken: Withdrawable token amount must be non-zero"
);
TokenInteract.transfer(token, to, withdrawableBalance);
emit ExcessTokensWithdrawn(token, to, msg.sender);
return withdrawableBalance;
}
// ============ Authorized-Only State-Changing Functions ============
/**
* Transfers tokens from an address (that has approved the proxy) to the vault.
*
* @param id The vault which will receive the tokens
* @param token ERC20 token address
* @param from Address from which the tokens will be taken
* @param amount Number of the token to be sent
*/
function transferToVault(
bytes32 id,
address token,
address from,
uint256 amount
)
external
requiresAuthorization
{
// First send tokens to this contract
TokenProxy(TOKEN_PROXY).transferTokens(
token,
from,
address(this),
amount
);
// Then increment balances
balances[id][token] = balances[id][token].add(amount);
totalBalances[token] = totalBalances[token].add(amount);
// This should always be true. If not, something is very wrong
assert(totalBalances[token] >= balances[id][token]);
validateBalance(token);
}
/**
* Transfers a certain amount of funds to an address.
*
* @param id The vault from which to send the tokens
* @param token ERC20 token address
* @param to Address to transfer tokens to
* @param amount Number of the token to be sent
*/
function transferFromVault(
bytes32 id,
address token,
address to,
uint256 amount
)
external
requiresAuthorization
{
// Next line also asserts that (balances[id][token] >= amount);
balances[id][token] = balances[id][token].sub(amount);
// Next line also asserts that (totalBalances[token] >= amount);
totalBalances[token] = totalBalances[token].sub(amount);
// This should always be true. If not, something is very wrong
assert(totalBalances[token] >= balances[id][token]);
// Do the sending
TokenInteract.transfer(token, to, amount); // asserts transfer succeeded
// Final validation
validateBalance(token);
}
// ============ Private Helper-Functions ============
/**
* Verifies that this contract is in control of at least as many tokens as accounted for
*
* @param token Address of ERC20 token
*/
function validateBalance(
address token
)
private
view
{
// The actual balance could be greater than totalBalances[token] because anyone
// can send tokens to the contract's address which cannot be accounted for
assert(TokenInteract.balanceOf(token, address(this)) >= totalBalances[token]);
}
}
// File: contracts/lib/ReentrancyGuard.sol
/**
* @title ReentrancyGuard
* @author dYdX
*
* Optimized version of the well-known ReentrancyGuard contract
*/
contract ReentrancyGuard {
uint256 private _guardCounter = 1;
modifier nonReentrant() {
uint256 localCounter = _guardCounter + 1;
_guardCounter = localCounter;
_;
require(
_guardCounter == localCounter,
"Reentrancy check failure"
);
}
}
// File: openzeppelin-solidity/contracts/AddressUtils.sol
/**
* Utility library of inline functions on addresses
*/
library AddressUtils {
/**
* Returns whether the target address is a contract
* @dev This function will return false if invoked during the constructor of a contract,
* as the code is not actually created until after the constructor finishes.
* @param _addr address to check
* @return whether the target address is a contract
*/
function isContract(address _addr) internal view returns (bool) {
uint256 size;
// XXX Currently there is no better way to check if there is a contract in an address
// than to check the size of the code at that address.
// See https://ethereum.stackexchange.com/a/14016/36603
// for more details about how this works.
// TODO Check this again before the Serenity release, because all addresses will be
// contracts then.
// solium-disable-next-line security/no-inline-assembly
assembly { size := extcodesize(_addr) }
return size > 0;
}
}
// File: contracts/lib/Fraction.sol
/**
* @title Fraction
* @author dYdX
*
* This library contains implementations for fraction structs.
*/
library Fraction {
struct Fraction128 {
uint128 num;
uint128 den;
}
}
// File: contracts/lib/FractionMath.sol
/**
* @title FractionMath
* @author dYdX
*
* This library contains safe math functions for manipulating fractions.
*/
library FractionMath {
using SafeMath for uint256;
using SafeMath for uint128;
/**
* Returns a Fraction128 that is equal to a + b
*
* @param a The first Fraction128
* @param b The second Fraction128
* @return The result (sum)
*/
function add(
Fraction.Fraction128 memory a,
Fraction.Fraction128 memory b
)
internal
pure
returns (Fraction.Fraction128 memory)
{
uint256 left = a.num.mul(b.den);
uint256 right = b.num.mul(a.den);
uint256 denominator = a.den.mul(b.den);
// if left + right overflows, prevent overflow
if (left + right < left) {
left = left.div(2);
right = right.div(2);
denominator = denominator.div(2);
}
return bound(left.add(right), denominator);
}
/**
* Returns a Fraction128 that is equal to a - (1/2)^d
*
* @param a The Fraction128
* @param d The power of (1/2)
* @return The result
*/
function sub1Over(
Fraction.Fraction128 memory a,
uint128 d
)
internal
pure
returns (Fraction.Fraction128 memory)
{
if (a.den % d == 0) {
return bound(
a.num.sub(a.den.div(d)),
a.den
);
}
return bound(
a.num.mul(d).sub(a.den),
a.den.mul(d)
);
}
/**
* Returns a Fraction128 that is equal to a / d
*
* @param a The first Fraction128
* @param d The divisor
* @return The result (quotient)
*/
function div(
Fraction.Fraction128 memory a,
uint128 d
)
internal
pure
returns (Fraction.Fraction128 memory)
{
if (a.num % d == 0) {
return bound(
a.num.div(d),
a.den
);
}
return bound(
a.num,
a.den.mul(d)
);
}
/**
* Returns a Fraction128 that is equal to a * b.
*
* @param a The first Fraction128
* @param b The second Fraction128
* @return The result (product)
*/
function mul(
Fraction.Fraction128 memory a,
Fraction.Fraction128 memory b
)
internal
pure
returns (Fraction.Fraction128 memory)
{
return bound(
a.num.mul(b.num),
a.den.mul(b.den)
);
}
/**
* Returns a fraction from two uint256's. Fits them into uint128 if necessary.
*
* @param num The numerator
* @param den The denominator
* @return The Fraction128 that matches num/den most closely
*/
/* solium-disable-next-line security/no-assign-params */
function bound(
uint256 num,
uint256 den
)
internal
pure
returns (Fraction.Fraction128 memory)
{
uint256 max = num > den ? num : den;
uint256 first128Bits = (max >> 128);
if (first128Bits != 0) {
first128Bits += 1;
num /= first128Bits;
den /= first128Bits;
}
assert(den != 0); // coverage-enable-line
assert(den < 2**128);
assert(num < 2**128);
return Fraction.Fraction128({
num: uint128(num),
den: uint128(den)
});
}
/**
* Returns an in-memory copy of a Fraction128
*
* @param a The Fraction128 to copy
* @return A copy of the Fraction128
*/
function copy(
Fraction.Fraction128 memory a
)
internal
pure
returns (Fraction.Fraction128 memory)
{
validate(a);
return Fraction.Fraction128({ num: a.num, den: a.den });
}
// ============ Private Helper-Functions ============
/**
* Asserts that a Fraction128 is valid (i.e. the denominator is non-zero)
*
* @param a The Fraction128 to validate
*/
function validate(
Fraction.Fraction128 memory a
)
private
pure
{
assert(a.den != 0); // coverage-enable-line
}
}
// File: contracts/lib/Exponent.sol
/**
* @title Exponent
* @author dYdX
*
* This library contains an implementation for calculating e^X for arbitrary fraction X
*/
library Exponent {
using SafeMath for uint256;
using FractionMath for Fraction.Fraction128;
// ============ Constants ============
// 2**128 - 1
uint128 constant public MAX_NUMERATOR = 340282366920938463463374607431768211455;
// Number of precomputed integers, X, for E^((1/2)^X)
uint256 constant public MAX_PRECOMPUTE_PRECISION = 32;
// Number of precomputed integers, X, for E^X
uint256 constant public NUM_PRECOMPUTED_INTEGERS = 32;
// ============ Public Implementation Functions ============
/**
* Returns e^X for any fraction X
*
* @param X The exponent
* @param precomputePrecision Accuracy of precomputed terms
* @param maclaurinPrecision Accuracy of Maclaurin terms
* @return e^X
*/
function exp(
Fraction.Fraction128 memory X,
uint256 precomputePrecision,
uint256 maclaurinPrecision
)
internal
pure
returns (Fraction.Fraction128 memory)
{
require(
precomputePrecision <= MAX_PRECOMPUTE_PRECISION,
"Exponent#exp: Precompute precision over maximum"
);
Fraction.Fraction128 memory Xcopy = X.copy();
if (Xcopy.num == 0) { // e^0 = 1
return ONE();
}
// get the integer value of the fraction (example: 9/4 is 2.25 so has integerValue of 2)
uint256 integerX = uint256(Xcopy.num).div(Xcopy.den);
// if X is less than 1, then just calculate X
if (integerX == 0) {
return expHybrid(Xcopy, precomputePrecision, maclaurinPrecision);
}
// get e^integerX
Fraction.Fraction128 memory expOfInt =
getPrecomputedEToThe(integerX % NUM_PRECOMPUTED_INTEGERS);
while (integerX >= NUM_PRECOMPUTED_INTEGERS) {
expOfInt = expOfInt.mul(getPrecomputedEToThe(NUM_PRECOMPUTED_INTEGERS));
integerX -= NUM_PRECOMPUTED_INTEGERS;
}
// multiply e^integerX by e^decimalX
Fraction.Fraction128 memory decimalX = Fraction.Fraction128({
num: Xcopy.num % Xcopy.den,
den: Xcopy.den
});
return expHybrid(decimalX, precomputePrecision, maclaurinPrecision).mul(expOfInt);
}
/**
* Returns e^X for any X < 1. Multiplies precomputed values to get close to the real value, then
* Maclaurin Series approximation to reduce error.
*
* @param X Exponent
* @param precomputePrecision Accuracy of precomputed terms
* @param maclaurinPrecision Accuracy of Maclaurin terms
* @return e^X
*/
function expHybrid(
Fraction.Fraction128 memory X,
uint256 precomputePrecision,
uint256 maclaurinPrecision
)
internal
pure
returns (Fraction.Fraction128 memory)
{
assert(precomputePrecision <= MAX_PRECOMPUTE_PRECISION);
assert(X.num < X.den);
// will also throw if precomputePrecision is larger than the array length in getDenominator
Fraction.Fraction128 memory Xtemp = X.copy();
if (Xtemp.num == 0) { // e^0 = 1
return ONE();
}
Fraction.Fraction128 memory result = ONE();
uint256 d = 1; // 2^i
for (uint256 i = 1; i <= precomputePrecision; i++) {
d *= 2;
// if Fraction > 1/d, subtract 1/d and multiply result by precomputed e^(1/d)
if (d.mul(Xtemp.num) >= Xtemp.den) {
Xtemp = Xtemp.sub1Over(uint128(d));
result = result.mul(getPrecomputedEToTheHalfToThe(i));
}
}
return result.mul(expMaclaurin(Xtemp, maclaurinPrecision));
}
/**
* Returns e^X for any X, using Maclaurin Series approximation
*
* e^X = SUM(X^n / n!) for n >= 0
* e^X = 1 + X/1! + X^2/2! + X^3/3! ...
*
* @param X Exponent
* @param precision Accuracy of Maclaurin terms
* @return e^X
*/
function expMaclaurin(
Fraction.Fraction128 memory X,
uint256 precision
)
internal
pure
returns (Fraction.Fraction128 memory)
{
Fraction.Fraction128 memory Xcopy = X.copy();
if (Xcopy.num == 0) { // e^0 = 1
return ONE();
}
Fraction.Fraction128 memory result = ONE();
Fraction.Fraction128 memory Xtemp = ONE();
for (uint256 i = 1; i <= precision; i++) {
Xtemp = Xtemp.mul(Xcopy.div(uint128(i)));
result = result.add(Xtemp);
}
return result;
}
/**
* Returns a fraction roughly equaling E^((1/2)^x) for integer x
*/
function getPrecomputedEToTheHalfToThe(
uint256 x
)
internal
pure
returns (Fraction.Fraction128 memory)
{
assert(x <= MAX_PRECOMPUTE_PRECISION);
uint128 denominator = [
125182886983370532117250726298150828301,
206391688497133195273760705512282642279,
265012173823417992016237332255925138361,
300298134811882980317033350418940119802,
319665700530617779809390163992561606014,
329812979126047300897653247035862915816,
335006777809430963166468914297166288162,
337634268532609249517744113622081347950,
338955731696479810470146282672867036734,
339618401537809365075354109784799900812,
339950222128463181389559457827561204959,
340116253979683015278260491021941090650,
340199300311581465057079429423749235412,
340240831081268226777032180141478221816,
340261598367316729254995498374473399540,
340271982485676106947851156443492415142,
340277174663693808406010255284800906112,
340279770782412691177936847400746725466,
340281068849199706686796915841848278311,
340281717884450116236033378667952410919,
340282042402539547492367191008339680733,
340282204661700319870089970029119685699,
340282285791309720262481214385569134454,
340282326356121674011576912006427792656,
340282346638529464274601981200276914173,
340282356779733812753265346086924801364,
340282361850336100329388676752133324799,
340282364385637272451648746721404212564,
340282365653287865596328444437856608255,
340282366287113163939555716675618384724,
340282366604025813553891209601455838559,
340282366762482138471739420386372790954,
340282366841710300958333641874363209044
][x];
return Fraction.Fraction128({
num: MAX_NUMERATOR,
den: denominator
});
}
/**
* Returns a fraction roughly equaling E^(x) for integer x
*/
function getPrecomputedEToThe(
uint256 x
)
internal
pure
returns (Fraction.Fraction128 memory)
{
assert(x <= NUM_PRECOMPUTED_INTEGERS);
uint128 denominator = [
340282366920938463463374607431768211455,
125182886983370532117250726298150828301,
46052210507670172419625860892627118820,
16941661466271327126146327822211253888,
6232488952727653950957829210887653621,
2292804553036637136093891217529878878,
843475657686456657683449904934172134,
310297353591408453462393329342695980,
114152017036184782947077973323212575,
41994180235864621538772677139808695,
15448795557622704876497742989562086,
5683294276510101335127414470015662,
2090767122455392675095471286328463,
769150240628514374138961856925097,
282954560699298259527814398449860,
104093165666968799599694528310221,
38293735615330848145349245349513,
14087478058534870382224480725096,
5182493555688763339001418388912,
1906532833141383353974257736699,
701374233231058797338605168652,
258021160973090761055471434334,
94920680509187392077350434438,
34919366901332874995585576427,
12846117181722897538509298435,
4725822410035083116489797150,
1738532907279185132707372378,
639570514388029575350057932,
235284843422800231081973821,
86556456714490055457751527,
31842340925906738090071268,
11714142585413118080082437,
4309392228124372433711936
][x];
return Fraction.Fraction128({
num: MAX_NUMERATOR,
den: denominator
});
}
// ============ Private Helper-Functions ============
function ONE()
private
pure
returns (Fraction.Fraction128 memory)
{
return Fraction.Fraction128({ num: 1, den: 1 });
}
}
// File: contracts/lib/MathHelpers.sol
/**
* @title MathHelpers
* @author dYdX
*
* This library helps with common math functions in Solidity
*/
library MathHelpers {
using SafeMath for uint256;
/**
* Calculates partial value given a numerator and denominator.
*
* @param numerator Numerator
* @param denominator Denominator
* @param target Value to calculate partial of
* @return target * numerator / denominator
*/
function getPartialAmount(
uint256 numerator,
uint256 denominator,
uint256 target
)
internal
pure
returns (uint256)
{
return numerator.mul(target).div(denominator);
}
/**
* Calculates partial value given a numerator and denominator, rounded up.
*
* @param numerator Numerator
* @param denominator Denominator
* @param target Value to calculate partial of
* @return Rounded-up result of target * numerator / denominator
*/
function getPartialAmountRoundedUp(
uint256 numerator,
uint256 denominator,
uint256 target
)
internal
pure
returns (uint256)
{
return divisionRoundedUp(numerator.mul(target), denominator);
}
/**
* Calculates division given a numerator and denominator, rounded up.
*
* @param numerator Numerator.
* @param denominator Denominator.
* @return Rounded-up result of numerator / denominator
*/
function divisionRoundedUp(
uint256 numerator,
uint256 denominator
)
internal
pure
returns (uint256)
{
assert(denominator != 0); // coverage-enable-line
if (numerator == 0) {
return 0;
}
return numerator.sub(1).div(denominator).add(1);
}
/**
* Calculates and returns the maximum value for a uint256 in solidity
*
* @return The maximum value for uint256
*/
function maxUint256(
)
internal
pure
returns (uint256)
{
return 2 ** 256 - 1;
}
/**
* Calculates and returns the maximum value for a uint256 in solidity
*
* @return The maximum value for uint256
*/
function maxUint32(
)
internal
pure
returns (uint32)
{
return 2 ** 32 - 1;
}
/**
* Returns the number of bits in a uint256. That is, the lowest number, x, such that n >> x == 0
*
* @param n The uint256 to get the number of bits in
* @return The number of bits in n
*/
function getNumBits(
uint256 n
)
internal
pure
returns (uint256)
{
uint256 first = 0;
uint256 last = 256;
while (first < last) {
uint256 check = (first + last) / 2;
if ((n >> check) == 0) {
last = check;
} else {
first = check + 1;
}
}
assert(first <= 256);
return first;
}
}
// File: contracts/margin/impl/InterestImpl.sol
/**
* @title InterestImpl
* @author dYdX
*
* A library that calculates continuously compounded interest for principal, time period, and
* interest rate.
*/
library InterestImpl {
using SafeMath for uint256;
using FractionMath for Fraction.Fraction128;
// ============ Constants ============
uint256 constant DEFAULT_PRECOMPUTE_PRECISION = 11;
uint256 constant DEFAULT_MACLAURIN_PRECISION = 5;
uint256 constant MAXIMUM_EXPONENT = 80;
uint128 constant E_TO_MAXIUMUM_EXPONENT = 55406223843935100525711733958316613;
// ============ Public Implementation Functions ============
/**
* Returns total tokens owed after accruing interest. Continuously compounding and accurate to
* roughly 10^18 decimal places. Continuously compounding interest follows the formula:
* I = P * e^(R*T)
*
* @param principal Principal of the interest calculation
* @param interestRate Annual nominal interest percentage times 10**6.
* (example: 5% = 5e6)
* @param secondsOfInterest Number of seconds that interest has been accruing
* @return Total amount of tokens owed. Greater than tokenAmount.
*/
function getCompoundedInterest(
uint256 principal,
uint256 interestRate,
uint256 secondsOfInterest
)
public
pure
returns (uint256)
{
uint256 numerator = interestRate.mul(secondsOfInterest);
uint128 denominator = (10**8) * (365 * 1 days);
// interestRate and secondsOfInterest should both be uint32
assert(numerator < 2**128);
// fraction representing (Rate * Time)
Fraction.Fraction128 memory rt = Fraction.Fraction128({
num: uint128(numerator),
den: denominator
});
// calculate e^(RT)
Fraction.Fraction128 memory eToRT;
if (numerator.div(denominator) >= MAXIMUM_EXPONENT) {
// degenerate case: cap calculation
eToRT = Fraction.Fraction128({
num: E_TO_MAXIUMUM_EXPONENT,
den: 1
});
} else {
// normal case: calculate e^(RT)
eToRT = Exponent.exp(
rt,
DEFAULT_PRECOMPUTE_PRECISION,
DEFAULT_MACLAURIN_PRECISION
);
}
// e^X for positive X should be greater-than or equal to 1
assert(eToRT.num >= eToRT.den);
return safeMultiplyUint256ByFraction(principal, eToRT);
}
// ============ Private Helper-Functions ============
/**
* Returns n * f, trying to prevent overflow as much as possible. Assumes that the numerator
* and denominator of f are less than 2**128.
*/
function safeMultiplyUint256ByFraction(
uint256 n,
Fraction.Fraction128 memory f
)
private
pure
returns (uint256)
{
uint256 term1 = n.div(2 ** 128); // first 128 bits
uint256 term2 = n % (2 ** 128); // second 128 bits
// uncommon scenario, requires n >= 2**128. calculates term1 = term1 * f
if (term1 > 0) {
term1 = term1.mul(f.num);
uint256 numBits = MathHelpers.getNumBits(term1);
// reduce rounding error by shifting all the way to the left before dividing
term1 = MathHelpers.divisionRoundedUp(
term1 << (uint256(256).sub(numBits)),
f.den);
// continue shifting or reduce shifting to get the right number
if (numBits > 128) {
term1 = term1 << (numBits.sub(128));
} else if (numBits < 128) {
term1 = term1 >> (uint256(128).sub(numBits));
}
}
// calculates term2 = term2 * f
term2 = MathHelpers.getPartialAmountRoundedUp(
f.num,
f.den,
term2
);
return term1.add(term2);
}
}
// File: contracts/margin/impl/MarginState.sol
/**
* @title MarginState
* @author dYdX
*
* Contains state for the Margin contract. Also used by libraries that implement Margin functions.
*/
library MarginState {
struct State {
// Address of the Vault contract
address VAULT;
// Address of the TokenProxy contract
address TOKEN_PROXY;
// Mapping from loanHash -> amount, which stores the amount of a loan which has
// already been filled.
mapping (bytes32 => uint256) loanFills;
// Mapping from loanHash -> amount, which stores the amount of a loan which has
// already been canceled.
mapping (bytes32 => uint256) loanCancels;
// Mapping from positionId -> Position, which stores all the open margin positions.
mapping (bytes32 => MarginCommon.Position) positions;
// Mapping from positionId -> bool, which stores whether the position has previously been
// open, but is now closed.
mapping (bytes32 => bool) closedPositions;
// Mapping from positionId -> uint256, which stores the total amount of owedToken that has
// ever been repaid to the lender for each position. Does not reset.
mapping (bytes32 => uint256) totalOwedTokenRepaidToLender;
}
}
// File: contracts/margin/interfaces/lender/LoanOwner.sol
/**
* @title LoanOwner
* @author dYdX
*
* Interface that smart contracts must implement in order to own loans on behalf of other accounts.
*
* NOTE: Any contract implementing this interface should also use OnlyMargin to control access
* to these functions
*/
interface LoanOwner {
// ============ Public Interface functions ============
/**
* Function a contract must implement in order to receive ownership of a loan sell via the
* transferLoan function or the atomic-assign to the "owner" field in a loan offering.
*
* @param from Address of the previous owner
* @param positionId Unique ID of the position
* @return This address to keep ownership, a different address to pass-on ownership
*/
function receiveLoanOwnership(
address from,
bytes32 positionId
)
external
/* onlyMargin */
returns (address);
}
// File: contracts/margin/interfaces/owner/PositionOwner.sol
/**
* @title PositionOwner
* @author dYdX
*
* Interface that smart contracts must implement in order to own position on behalf of other
* accounts
*
* NOTE: Any contract implementing this interface should also use OnlyMargin to control access
* to these functions
*/
interface PositionOwner {
// ============ Public Interface functions ============
/**
* Function a contract must implement in order to receive ownership of a position via the
* transferPosition function or the atomic-assign to the "owner" field when opening a position.
*
* @param from Address of the previous owner
* @param positionId Unique ID of the position
* @return This address to keep ownership, a different address to pass-on ownership
*/
function receivePositionOwnership(
address from,
bytes32 positionId
)
external
/* onlyMargin */
returns (address);
}
// File: contracts/margin/impl/TransferInternal.sol
/**
* @title TransferInternal
* @author dYdX
*
* This library contains the implementation for transferring ownership of loans and positions.
*/
library TransferInternal {
// ============ Events ============
/**
* Ownership of a loan was transferred to a new address
*/
event LoanTransferred(
bytes32 indexed positionId,
address indexed from,
address indexed to
);
/**
* Ownership of a postion was transferred to a new address
*/
event PositionTransferred(
bytes32 indexed positionId,
address indexed from,
address indexed to
);
// ============ Internal Implementation Functions ============
/**
* Returns either the address of the new loan owner, or the address to which they wish to
* pass ownership of the loan. This function does not actually set the state of the position
*
* @param positionId The Unique ID of the position
* @param oldOwner The previous owner of the loan
* @param newOwner The intended owner of the loan
* @return The address that the intended owner wishes to assign the loan to (may be
* the same as the intended owner).
*/
function grantLoanOwnership(
bytes32 positionId,
address oldOwner,
address newOwner
)
internal
returns (address)
{
// log event except upon position creation
if (oldOwner != address(0)) {
emit LoanTransferred(positionId, oldOwner, newOwner);
}
if (AddressUtils.isContract(newOwner)) {
address nextOwner =
LoanOwner(newOwner).receiveLoanOwnership(oldOwner, positionId);
if (nextOwner != newOwner) {
return grantLoanOwnership(positionId, newOwner, nextOwner);
}
}
require(
newOwner != address(0),
"TransferInternal#grantLoanOwnership: New owner did not consent to owning loan"
);
return newOwner;
}
/**
* Returns either the address of the new position owner, or the address to which they wish to
* pass ownership of the position. This function does not actually set the state of the position
*
* @param positionId The Unique ID of the position
* @param oldOwner The previous owner of the position
* @param newOwner The intended owner of the position
* @return The address that the intended owner wishes to assign the position to (may
* be the same as the intended owner).
*/
function grantPositionOwnership(
bytes32 positionId,
address oldOwner,
address newOwner
)
internal
returns (address)
{
// log event except upon position creation
if (oldOwner != address(0)) {
emit PositionTransferred(positionId, oldOwner, newOwner);
}
if (AddressUtils.isContract(newOwner)) {
address nextOwner =
PositionOwner(newOwner).receivePositionOwnership(oldOwner, positionId);
if (nextOwner != newOwner) {
return grantPositionOwnership(positionId, newOwner, nextOwner);
}
}
require(
newOwner != address(0),
"TransferInternal#grantPositionOwnership: New owner did not consent to owning position"
);
return newOwner;
}
}
// File: contracts/lib/TimestampHelper.sol
/**
* @title TimestampHelper
* @author dYdX
*
* Helper to get block timestamps in other formats
*/
library TimestampHelper {
function getBlockTimestamp32()
internal
view
returns (uint32)
{
// Should not still be in-use in the year 2106
assert(uint256(uint32(block.timestamp)) == block.timestamp);
assert(block.timestamp > 0);
return uint32(block.timestamp);
}
}
// File: contracts/margin/impl/MarginCommon.sol
/**
* @title MarginCommon
* @author dYdX
*
* This library contains common functions for implementations of public facing Margin functions
*/
library MarginCommon {
using SafeMath for uint256;
// ============ Structs ============
struct Position {
address owedToken; // Immutable
address heldToken; // Immutable
address lender;
address owner;
uint256 principal;
uint256 requiredDeposit;
uint32 callTimeLimit; // Immutable
uint32 startTimestamp; // Immutable, cannot be 0
uint32 callTimestamp;
uint32 maxDuration; // Immutable
uint32 interestRate; // Immutable
uint32 interestPeriod; // Immutable
}
struct LoanOffering {
address owedToken;
address heldToken;
address payer;
address owner;
address taker;
address positionOwner;
address feeRecipient;
address lenderFeeToken;
address takerFeeToken;
LoanRates rates;
uint256 expirationTimestamp;
uint32 callTimeLimit;
uint32 maxDuration;
uint256 salt;
bytes32 loanHash;
bytes signature;
}
struct LoanRates {
uint256 maxAmount;
uint256 minAmount;
uint256 minHeldToken;
uint256 lenderFee;
uint256 takerFee;
uint32 interestRate;
uint32 interestPeriod;
}
// ============ Internal Implementation Functions ============
function storeNewPosition(
MarginState.State storage state,
bytes32 positionId,
Position memory position,
address loanPayer
)
internal
{
assert(!positionHasExisted(state, positionId));
assert(position.owedToken != address(0));
assert(position.heldToken != address(0));
assert(position.owedToken != position.heldToken);
assert(position.owner != address(0));
assert(position.lender != address(0));
assert(position.maxDuration != 0);
assert(position.interestPeriod <= position.maxDuration);
assert(position.callTimestamp == 0);
assert(position.requiredDeposit == 0);
state.positions[positionId].owedToken = position.owedToken;
state.positions[positionId].heldToken = position.heldToken;
state.positions[positionId].principal = position.principal;
state.positions[positionId].callTimeLimit = position.callTimeLimit;
state.positions[positionId].startTimestamp = TimestampHelper.getBlockTimestamp32();
state.positions[positionId].maxDuration = position.maxDuration;
state.positions[positionId].interestRate = position.interestRate;
state.positions[positionId].interestPeriod = position.interestPeriod;
state.positions[positionId].owner = TransferInternal.grantPositionOwnership(
positionId,
(position.owner != msg.sender) ? msg.sender : address(0),
position.owner
);
state.positions[positionId].lender = TransferInternal.grantLoanOwnership(
positionId,
(position.lender != loanPayer) ? loanPayer : address(0),
position.lender
);
}
function getPositionIdFromNonce(
uint256 nonce
)
internal
view
returns (bytes32)
{
return keccak256(abi.encodePacked(msg.sender, nonce));
}
function getUnavailableLoanOfferingAmountImpl(
MarginState.State storage state,
bytes32 loanHash
)
internal
view
returns (uint256)
{
return state.loanFills[loanHash].add(state.loanCancels[loanHash]);
}
function cleanupPosition(
MarginState.State storage state,
bytes32 positionId
)
internal
{
delete state.positions[positionId];
state.closedPositions[positionId] = true;
}
function calculateOwedAmount(
Position storage position,
uint256 closeAmount,
uint256 endTimestamp
)
internal
view
returns (uint256)
{
uint256 timeElapsed = calculateEffectiveTimeElapsed(position, endTimestamp);
return InterestImpl.getCompoundedInterest(
closeAmount,
position.interestRate,
timeElapsed
);
}
/**
* Calculates time elapsed rounded up to the nearest interestPeriod
*/
function calculateEffectiveTimeElapsed(
Position storage position,
uint256 timestamp
)
internal
view
returns (uint256)
{
uint256 elapsed = timestamp.sub(position.startTimestamp);
// round up to interestPeriod
uint256 period = position.interestPeriod;
if (period > 1) {
elapsed = MathHelpers.divisionRoundedUp(elapsed, period).mul(period);
}
// bound by maxDuration
return Math.min256(
elapsed,
position.maxDuration
);
}
function calculateLenderAmountForIncreasePosition(
Position storage position,
uint256 principalToAdd,
uint256 endTimestamp
)
internal
view
returns (uint256)
{
uint256 timeElapsed = calculateEffectiveTimeElapsedForNewLender(position, endTimestamp);
return InterestImpl.getCompoundedInterest(
principalToAdd,
position.interestRate,
timeElapsed
);
}
function getLoanOfferingHash(
LoanOffering loanOffering
)
internal
view
returns (bytes32)
{
return keccak256(
abi.encodePacked(
address(this),
loanOffering.owedToken,
loanOffering.heldToken,
loanOffering.payer,
loanOffering.owner,
loanOffering.taker,
loanOffering.positionOwner,
loanOffering.feeRecipient,
loanOffering.lenderFeeToken,
loanOffering.takerFeeToken,
getValuesHash(loanOffering)
)
);
}
function getPositionBalanceImpl(
MarginState.State storage state,
bytes32 positionId
)
internal
view
returns(uint256)
{
return Vault(state.VAULT).balances(positionId, state.positions[positionId].heldToken);
}
function containsPositionImpl(
MarginState.State storage state,
bytes32 positionId
)
internal
view
returns (bool)
{
return state.positions[positionId].startTimestamp != 0;
}
function positionHasExisted(
MarginState.State storage state,
bytes32 positionId
)
internal
view
returns (bool)
{
return containsPositionImpl(state, positionId) || state.closedPositions[positionId];
}
function getPositionFromStorage(
MarginState.State storage state,
bytes32 positionId
)
internal
view
returns (Position storage)
{
Position storage position = state.positions[positionId];
require(
position.startTimestamp != 0,
"MarginCommon#getPositionFromStorage: The position does not exist"
);
return position;
}
// ============ Private Helper-Functions ============
/**
* Calculates time elapsed rounded down to the nearest interestPeriod
*/
function calculateEffectiveTimeElapsedForNewLender(
Position storage position,
uint256 timestamp
)
private
view
returns (uint256)
{
uint256 elapsed = timestamp.sub(position.startTimestamp);
// round down to interestPeriod
uint256 period = position.interestPeriod;
if (period > 1) {
elapsed = elapsed.div(period).mul(period);
}
// bound by maxDuration
return Math.min256(
elapsed,
position.maxDuration
);
}
function getValuesHash(
LoanOffering loanOffering
)
private
pure
returns (bytes32)
{
return keccak256(
abi.encodePacked(
loanOffering.rates.maxAmount,
loanOffering.rates.minAmount,
loanOffering.rates.minHeldToken,
loanOffering.rates.lenderFee,
loanOffering.rates.takerFee,
loanOffering.expirationTimestamp,
loanOffering.salt,
loanOffering.callTimeLimit,
loanOffering.maxDuration,
loanOffering.rates.interestRate,
loanOffering.rates.interestPeriod
)
);
}
}
// File: contracts/margin/interfaces/PayoutRecipient.sol
/**
* @title PayoutRecipient
* @author dYdX
*
* Interface that smart contracts must implement in order to be the payoutRecipient in a
* closePosition transaction.
*
* NOTE: Any contract implementing this interface should also use OnlyMargin to control access
* to these functions
*/
interface PayoutRecipient {
// ============ Public Interface functions ============
/**
* Function a contract must implement in order to receive payout from being the payoutRecipient
* in a closePosition transaction. May redistribute any payout as necessary. Throws on error.
*
* @param positionId Unique ID of the position
* @param closeAmount Amount of the position that was closed
* @param closer Address of the account or contract that closed the position
* @param positionOwner Address of the owner of the position
* @param heldToken Address of the ERC20 heldToken
* @param payout Number of tokens received from the payout
* @param totalHeldToken Total amount of heldToken removed from vault during close
* @param payoutInHeldToken True if payout is in heldToken, false if in owedToken
* @return True if approved by the receiver
*/
function receiveClosePositionPayout(
bytes32 positionId,
uint256 closeAmount,
address closer,
address positionOwner,
address heldToken,
uint256 payout,
uint256 totalHeldToken,
bool payoutInHeldToken
)
external
/* onlyMargin */
returns (bool);
}
// File: contracts/margin/interfaces/lender/CloseLoanDelegator.sol
/**
* @title CloseLoanDelegator
* @author dYdX
*
* Interface that smart contracts must implement in order to let other addresses close a loan
* owned by the smart contract.
*
* NOTE: Any contract implementing this interface should also use OnlyMargin to control access
* to these functions
*/
interface CloseLoanDelegator {
// ============ Public Interface functions ============
/**
* Function a contract must implement in order to let other addresses call
* closeWithoutCounterparty().
*
* NOTE: If not returning zero (or not reverting), this contract must assume that Margin will
* either revert the entire transaction or that (at most) the specified amount of the loan was
* successfully closed.
*
* @param closer Address of the caller of closeWithoutCounterparty()
* @param payoutRecipient Address of the recipient of tokens paid out from closing
* @param positionId Unique ID of the position
* @param requestedAmount Requested principal amount of the loan to close
* @return 1) This address to accept, a different address to ask that contract
* 2) The maximum amount that this contract is allowing
*/
function closeLoanOnBehalfOf(
address closer,
address payoutRecipient,
bytes32 positionId,
uint256 requestedAmount
)
external
/* onlyMargin */
returns (address, uint256);
}
// File: contracts/margin/interfaces/owner/ClosePositionDelegator.sol
/**
* @title ClosePositionDelegator
* @author dYdX
*
* Interface that smart contracts must implement in order to let other addresses close a position
* owned by the smart contract, allowing more complex logic to control positions.
*
* NOTE: Any contract implementing this interface should also use OnlyMargin to control access
* to these functions
*/
interface ClosePositionDelegator {
// ============ Public Interface functions ============
/**
* Function a contract must implement in order to let other addresses call closePosition().
*
* NOTE: If not returning zero (or not reverting), this contract must assume that Margin will
* either revert the entire transaction or that (at-most) the specified amount of the position
* was successfully closed.
*
* @param closer Address of the caller of the closePosition() function
* @param payoutRecipient Address of the recipient of tokens paid out from closing
* @param positionId Unique ID of the position
* @param requestedAmount Requested principal amount of the position to close
* @return 1) This address to accept, a different address to ask that contract
* 2) The maximum amount that this contract is allowing
*/
function closeOnBehalfOf(
address closer,
address payoutRecipient,
bytes32 positionId,
uint256 requestedAmount
)
external
/* onlyMargin */
returns (address, uint256);
}
// File: contracts/margin/impl/ClosePositionShared.sol
/**
* @title ClosePositionShared
* @author dYdX
*
* This library contains shared functionality between ClosePositionImpl and
* CloseWithoutCounterpartyImpl
*/
library ClosePositionShared {
using SafeMath for uint256;
// ============ Structs ============
struct CloseTx {
bytes32 positionId;
uint256 originalPrincipal;
uint256 closeAmount;
uint256 owedTokenOwed;
uint256 startingHeldTokenBalance;
uint256 availableHeldToken;
address payoutRecipient;
address owedToken;
address heldToken;
address positionOwner;
address positionLender;
address exchangeWrapper;
bool payoutInHeldToken;
}
// ============ Internal Implementation Functions ============
function closePositionStateUpdate(
MarginState.State storage state,
CloseTx memory transaction
)
internal
{
// Delete the position, or just decrease the principal
if (transaction.closeAmount == transaction.originalPrincipal) {
MarginCommon.cleanupPosition(state, transaction.positionId);
} else {
assert(
transaction.originalPrincipal == state.positions[transaction.positionId].principal
);
state.positions[transaction.positionId].principal =
transaction.originalPrincipal.sub(transaction.closeAmount);
}
}
function sendTokensToPayoutRecipient(
MarginState.State storage state,
ClosePositionShared.CloseTx memory transaction,
uint256 buybackCostInHeldToken,
uint256 receivedOwedToken
)
internal
returns (uint256)
{
uint256 payout;
if (transaction.payoutInHeldToken) {
// Send remaining heldToken to payoutRecipient
payout = transaction.availableHeldToken.sub(buybackCostInHeldToken);
Vault(state.VAULT).transferFromVault(
transaction.positionId,
transaction.heldToken,
transaction.payoutRecipient,
payout
);
} else {
assert(transaction.exchangeWrapper != address(0));
payout = receivedOwedToken.sub(transaction.owedTokenOwed);
TokenProxy(state.TOKEN_PROXY).transferTokens(
transaction.owedToken,
transaction.exchangeWrapper,
transaction.payoutRecipient,
payout
);
}
if (AddressUtils.isContract(transaction.payoutRecipient)) {
require(
PayoutRecipient(transaction.payoutRecipient).receiveClosePositionPayout(
transaction.positionId,
transaction.closeAmount,
msg.sender,
transaction.positionOwner,
transaction.heldToken,
payout,
transaction.availableHeldToken,
transaction.payoutInHeldToken
),
"ClosePositionShared#sendTokensToPayoutRecipient: Payout recipient does not consent"
);
}
// The ending heldToken balance of the vault should be the starting heldToken balance
// minus the available heldToken amount
assert(
MarginCommon.getPositionBalanceImpl(state, transaction.positionId)
== transaction.startingHeldTokenBalance.sub(transaction.availableHeldToken)
);
return payout;
}
function createCloseTx(
MarginState.State storage state,
bytes32 positionId,
uint256 requestedAmount,
address payoutRecipient,
address exchangeWrapper,
bool payoutInHeldToken,
bool isWithoutCounterparty
)
internal
returns (CloseTx memory)
{
// Validate
require(
payoutRecipient != address(0),
"ClosePositionShared#createCloseTx: Payout recipient cannot be 0"
);
require(
requestedAmount > 0,
"ClosePositionShared#createCloseTx: Requested close amount cannot be 0"
);
MarginCommon.Position storage position =
MarginCommon.getPositionFromStorage(state, positionId);
uint256 closeAmount = getApprovedAmount(
position,
positionId,
requestedAmount,
payoutRecipient,
isWithoutCounterparty
);
return parseCloseTx(
state,
position,
positionId,
closeAmount,
payoutRecipient,
exchangeWrapper,
payoutInHeldToken,
isWithoutCounterparty
);
}
// ============ Private Helper-Functions ============
function getApprovedAmount(
MarginCommon.Position storage position,
bytes32 positionId,
uint256 requestedAmount,
address payoutRecipient,
bool requireLenderApproval
)
private
returns (uint256)
{
// Ensure enough principal
uint256 allowedAmount = Math.min256(requestedAmount, position.principal);
// Ensure owner consent
allowedAmount = closePositionOnBehalfOfRecurse(
position.owner,
msg.sender,
payoutRecipient,
positionId,
allowedAmount
);
// Ensure lender consent
if (requireLenderApproval) {
allowedAmount = closeLoanOnBehalfOfRecurse(
position.lender,
msg.sender,
payoutRecipient,
positionId,
allowedAmount
);
}
assert(allowedAmount > 0);
assert(allowedAmount <= position.principal);
assert(allowedAmount <= requestedAmount);
return allowedAmount;
}
function closePositionOnBehalfOfRecurse(
address contractAddr,
address closer,
address payoutRecipient,
bytes32 positionId,
uint256 closeAmount
)
private
returns (uint256)
{
// no need to ask for permission
if (closer == contractAddr) {
return closeAmount;
}
(
address newContractAddr,
uint256 newCloseAmount
) = ClosePositionDelegator(contractAddr).closeOnBehalfOf(
closer,
payoutRecipient,
positionId,
closeAmount
);
require(
newCloseAmount <= closeAmount,
"ClosePositionShared#closePositionRecurse: newCloseAmount is greater than closeAmount"
);
require(
newCloseAmount > 0,
"ClosePositionShared#closePositionRecurse: newCloseAmount is zero"
);
if (newContractAddr != contractAddr) {
closePositionOnBehalfOfRecurse(
newContractAddr,
closer,
payoutRecipient,
positionId,
newCloseAmount
);
}
return newCloseAmount;
}
function closeLoanOnBehalfOfRecurse(
address contractAddr,
address closer,
address payoutRecipient,
bytes32 positionId,
uint256 closeAmount
)
private
returns (uint256)
{
// no need to ask for permission
if (closer == contractAddr) {
return closeAmount;
}
(
address newContractAddr,
uint256 newCloseAmount
) = CloseLoanDelegator(contractAddr).closeLoanOnBehalfOf(
closer,
payoutRecipient,
positionId,
closeAmount
);
require(
newCloseAmount <= closeAmount,
"ClosePositionShared#closeLoanRecurse: newCloseAmount is greater than closeAmount"
);
require(
newCloseAmount > 0,
"ClosePositionShared#closeLoanRecurse: newCloseAmount is zero"
);
if (newContractAddr != contractAddr) {
closeLoanOnBehalfOfRecurse(
newContractAddr,
closer,
payoutRecipient,
positionId,
newCloseAmount
);
}
return newCloseAmount;
}
// ============ Parsing Functions ============
function parseCloseTx(
MarginState.State storage state,
MarginCommon.Position storage position,
bytes32 positionId,
uint256 closeAmount,
address payoutRecipient,
address exchangeWrapper,
bool payoutInHeldToken,
bool isWithoutCounterparty
)
private
view
returns (CloseTx memory)
{
uint256 startingHeldTokenBalance = MarginCommon.getPositionBalanceImpl(state, positionId);
uint256 availableHeldToken = MathHelpers.getPartialAmount(
closeAmount,
position.principal,
startingHeldTokenBalance
);
uint256 owedTokenOwed = 0;
if (!isWithoutCounterparty) {
owedTokenOwed = MarginCommon.calculateOwedAmount(
position,
closeAmount,
block.timestamp
);
}
return CloseTx({
positionId: positionId,
originalPrincipal: position.principal,
closeAmount: closeAmount,
owedTokenOwed: owedTokenOwed,
startingHeldTokenBalance: startingHeldTokenBalance,
availableHeldToken: availableHeldToken,
payoutRecipient: payoutRecipient,
owedToken: position.owedToken,
heldToken: position.heldToken,
positionOwner: position.owner,
positionLender: position.lender,
exchangeWrapper: exchangeWrapper,
payoutInHeldToken: payoutInHeldToken
});
}
}
// File: contracts/margin/interfaces/ExchangeWrapper.sol
/**
* @title ExchangeWrapper
* @author dYdX
*
* Contract interface that Exchange Wrapper smart contracts must implement in order to interface
* with other smart contracts through a common interface.
*/
interface ExchangeWrapper {
// ============ Public Functions ============
/**
* Exchange some amount of takerToken for makerToken.
*
* @param tradeOriginator Address of the initiator of the trade (however, this value
* cannot always be trusted as it is set at the discretion of the
* msg.sender)
* @param receiver Address to set allowance on once the trade has completed
* @param makerToken Address of makerToken, the token to receive
* @param takerToken Address of takerToken, the token to pay
* @param requestedFillAmount Amount of takerToken being paid
* @param orderData Arbitrary bytes data for any information to pass to the exchange
* @return The amount of makerToken received
*/
function exchange(
address tradeOriginator,
address receiver,
address makerToken,
address takerToken,
uint256 requestedFillAmount,
bytes orderData
)
external
returns (uint256);
/**
* Get amount of takerToken required to buy a certain amount of makerToken for a given trade.
* Should match the takerToken amount used in exchangeForAmount. If the order cannot provide
* exactly desiredMakerToken, then it must return the price to buy the minimum amount greater
* than desiredMakerToken
*
* @param makerToken Address of makerToken, the token to receive
* @param takerToken Address of takerToken, the token to pay
* @param desiredMakerToken Amount of makerToken requested
* @param orderData Arbitrary bytes data for any information to pass to the exchange
* @return Amount of takerToken the needed to complete the transaction
*/
function getExchangeCost(
address makerToken,
address takerToken,
uint256 desiredMakerToken,
bytes orderData
)
external
view
returns (uint256);
}
// File: contracts/margin/impl/ClosePositionImpl.sol
/**
* @title ClosePositionImpl
* @author dYdX
*
* This library contains the implementation for the closePosition function of Margin
*/
library ClosePositionImpl {
using SafeMath for uint256;
// ============ Events ============
/**
* A position was closed or partially closed
*/
event PositionClosed(
bytes32 indexed positionId,
address indexed closer,
address indexed payoutRecipient,
uint256 closeAmount,
uint256 remainingAmount,
uint256 owedTokenPaidToLender,
uint256 payoutAmount,
uint256 buybackCostInHeldToken,
bool payoutInHeldToken
);
// ============ Public Implementation Functions ============
function closePositionImpl(
MarginState.State storage state,
bytes32 positionId,
uint256 requestedCloseAmount,
address payoutRecipient,
address exchangeWrapper,
bool payoutInHeldToken,
bytes memory orderData
)
public
returns (uint256, uint256, uint256)
{
ClosePositionShared.CloseTx memory transaction = ClosePositionShared.createCloseTx(
state,
positionId,
requestedCloseAmount,
payoutRecipient,
exchangeWrapper,
payoutInHeldToken,
false
);
(
uint256 buybackCostInHeldToken,
uint256 receivedOwedToken
) = returnOwedTokensToLender(
state,
transaction,
orderData
);
uint256 payout = ClosePositionShared.sendTokensToPayoutRecipient(
state,
transaction,
buybackCostInHeldToken,
receivedOwedToken
);
ClosePositionShared.closePositionStateUpdate(state, transaction);
logEventOnClose(
transaction,
buybackCostInHeldToken,
payout
);
return (
transaction.closeAmount,
payout,
transaction.owedTokenOwed
);
}
// ============ Private Helper-Functions ============
function returnOwedTokensToLender(
MarginState.State storage state,
ClosePositionShared.CloseTx memory transaction,
bytes memory orderData
)
private
returns (uint256, uint256)
{
uint256 buybackCostInHeldToken = 0;
uint256 receivedOwedToken = 0;
uint256 lenderOwedToken = transaction.owedTokenOwed;
// Setting exchangeWrapper to 0x000... indicates owedToken should be taken directly
// from msg.sender
if (transaction.exchangeWrapper == address(0)) {
require(
transaction.payoutInHeldToken,
"ClosePositionImpl#returnOwedTokensToLender: Cannot payout in owedToken"
);
// No DEX Order; send owedTokens directly from the closer to the lender
TokenProxy(state.TOKEN_PROXY).transferTokens(
transaction.owedToken,
msg.sender,
transaction.positionLender,
lenderOwedToken
);
} else {
// Buy back owedTokens using DEX Order and send to lender
(buybackCostInHeldToken, receivedOwedToken) = buyBackOwedToken(
state,
transaction,
orderData
);
// If no owedToken needed for payout: give lender all owedToken, even if more than owed
if (transaction.payoutInHeldToken) {
assert(receivedOwedToken >= lenderOwedToken);
lenderOwedToken = receivedOwedToken;
}
// Transfer owedToken from the exchange wrapper to the lender
TokenProxy(state.TOKEN_PROXY).transferTokens(
transaction.owedToken,
transaction.exchangeWrapper,
transaction.positionLender,
lenderOwedToken
);
}
state.totalOwedTokenRepaidToLender[transaction.positionId] =
state.totalOwedTokenRepaidToLender[transaction.positionId].add(lenderOwedToken);
return (buybackCostInHeldToken, receivedOwedToken);
}
function buyBackOwedToken(
MarginState.State storage state,
ClosePositionShared.CloseTx transaction,
bytes memory orderData
)
private
returns (uint256, uint256)
{
// Ask the exchange wrapper the cost in heldToken to buy back the close
// amount of owedToken
uint256 buybackCostInHeldToken;
if (transaction.payoutInHeldToken) {
buybackCostInHeldToken = ExchangeWrapper(transaction.exchangeWrapper)
.getExchangeCost(
transaction.owedToken,
transaction.heldToken,
transaction.owedTokenOwed,
orderData
);
// Require enough available heldToken to pay for the buyback
require(
buybackCostInHeldToken <= transaction.availableHeldToken,
"ClosePositionImpl#buyBackOwedToken: Not enough available heldToken"
);
} else {
buybackCostInHeldToken = transaction.availableHeldToken;
}
// Send the requisite heldToken to do the buyback from vault to exchange wrapper
Vault(state.VAULT).transferFromVault(
transaction.positionId,
transaction.heldToken,
transaction.exchangeWrapper,
buybackCostInHeldToken
);
// Trade the heldToken for the owedToken
uint256 receivedOwedToken = ExchangeWrapper(transaction.exchangeWrapper).exchange(
msg.sender,
state.TOKEN_PROXY,
transaction.owedToken,
transaction.heldToken,
buybackCostInHeldToken,
orderData
);
require(
receivedOwedToken >= transaction.owedTokenOwed,
"ClosePositionImpl#buyBackOwedToken: Did not receive enough owedToken"
);
return (buybackCostInHeldToken, receivedOwedToken);
}
function logEventOnClose(
ClosePositionShared.CloseTx transaction,
uint256 buybackCostInHeldToken,
uint256 payout
)
private
{
emit PositionClosed(
transaction.positionId,
msg.sender,
transaction.payoutRecipient,
transaction.closeAmount,
transaction.originalPrincipal.sub(transaction.closeAmount),
transaction.owedTokenOwed,
payout,
buybackCostInHeldToken,
transaction.payoutInHeldToken
);
}
}
// File: contracts/margin/impl/CloseWithoutCounterpartyImpl.sol
/**
* @title CloseWithoutCounterpartyImpl
* @author dYdX
*
* This library contains the implementation for the closeWithoutCounterpartyImpl function of
* Margin
*/
library CloseWithoutCounterpartyImpl {
using SafeMath for uint256;
// ============ Events ============
/**
* A position was closed or partially closed
*/
event PositionClosed(
bytes32 indexed positionId,
address indexed closer,
address indexed payoutRecipient,
uint256 closeAmount,
uint256 remainingAmount,
uint256 owedTokenPaidToLender,
uint256 payoutAmount,
uint256 buybackCostInHeldToken,
bool payoutInHeldToken
);
// ============ Public Implementation Functions ============
function closeWithoutCounterpartyImpl(
MarginState.State storage state,
bytes32 positionId,
uint256 requestedCloseAmount,
address payoutRecipient
)
public
returns (uint256, uint256)
{
ClosePositionShared.CloseTx memory transaction = ClosePositionShared.createCloseTx(
state,
positionId,
requestedCloseAmount,
payoutRecipient,
address(0),
true,
true
);
uint256 heldTokenPayout = ClosePositionShared.sendTokensToPayoutRecipient(
state,
transaction,
0, // No buyback cost
0 // Did not receive any owedToken
);
ClosePositionShared.closePositionStateUpdate(state, transaction);
logEventOnCloseWithoutCounterparty(transaction);
return (
transaction.closeAmount,
heldTokenPayout
);
}
// ============ Private Helper-Functions ============
function logEventOnCloseWithoutCounterparty(
ClosePositionShared.CloseTx transaction
)
private
{
emit PositionClosed(
transaction.positionId,
msg.sender,
transaction.payoutRecipient,
transaction.closeAmount,
transaction.originalPrincipal.sub(transaction.closeAmount),
0,
transaction.availableHeldToken,
0,
true
);
}
}
// File: contracts/margin/interfaces/owner/DepositCollateralDelegator.sol
/**
* @title DepositCollateralDelegator
* @author dYdX
*
* Interface that smart contracts must implement in order to let other addresses deposit heldTokens
* into a position owned by the smart contract.
*
* NOTE: Any contract implementing this interface should also use OnlyMargin to control access
* to these functions
*/
interface DepositCollateralDelegator {
// ============ Public Interface functions ============
/**
* Function a contract must implement in order to let other addresses call depositCollateral().
*
* @param depositor Address of the caller of the depositCollateral() function
* @param positionId Unique ID of the position
* @param amount Requested deposit amount
* @return This address to accept, a different address to ask that contract
*/
function depositCollateralOnBehalfOf(
address depositor,
bytes32 positionId,
uint256 amount
)
external
/* onlyMargin */
returns (address);
}
// File: contracts/margin/impl/DepositCollateralImpl.sol
/**
* @title DepositCollateralImpl
* @author dYdX
*
* This library contains the implementation for the deposit function of Margin
*/
library DepositCollateralImpl {
using SafeMath for uint256;
// ============ Events ============
/**
* Additional collateral for a position was posted by the owner
*/
event AdditionalCollateralDeposited(
bytes32 indexed positionId,
uint256 amount,
address depositor
);
/**
* A margin call was canceled
*/
event MarginCallCanceled(
bytes32 indexed positionId,
address indexed lender,
address indexed owner,
uint256 depositAmount
);
// ============ Public Implementation Functions ============
function depositCollateralImpl(
MarginState.State storage state,
bytes32 positionId,
uint256 depositAmount
)
public
{
MarginCommon.Position storage position =
MarginCommon.getPositionFromStorage(state, positionId);
require(
depositAmount > 0,
"DepositCollateralImpl#depositCollateralImpl: Deposit amount cannot be 0"
);
// Ensure owner consent
depositCollateralOnBehalfOfRecurse(
position.owner,
msg.sender,
positionId,
depositAmount
);
Vault(state.VAULT).transferToVault(
positionId,
position.heldToken,
msg.sender,
depositAmount
);
// cancel margin call if applicable
bool marginCallCanceled = false;
uint256 requiredDeposit = position.requiredDeposit;
if (position.callTimestamp > 0 && requiredDeposit > 0) {
if (depositAmount >= requiredDeposit) {
position.requiredDeposit = 0;
position.callTimestamp = 0;
marginCallCanceled = true;
} else {
position.requiredDeposit = position.requiredDeposit.sub(depositAmount);
}
}
emit AdditionalCollateralDeposited(
positionId,
depositAmount,
msg.sender
);
if (marginCallCanceled) {
emit MarginCallCanceled(
positionId,
position.lender,
msg.sender,
depositAmount
);
}
}
// ============ Private Helper-Functions ============
function depositCollateralOnBehalfOfRecurse(
address contractAddr,
address depositor,
bytes32 positionId,
uint256 amount
)
private
{
// no need to ask for permission
if (depositor == contractAddr) {
return;
}
address newContractAddr =
DepositCollateralDelegator(contractAddr).depositCollateralOnBehalfOf(
depositor,
positionId,
amount
);
// if not equal, recurse
if (newContractAddr != contractAddr) {
depositCollateralOnBehalfOfRecurse(
newContractAddr,
depositor,
positionId,
amount
);
}
}
}
// File: contracts/margin/interfaces/lender/ForceRecoverCollateralDelegator.sol
/**
* @title ForceRecoverCollateralDelegator
* @author dYdX
*
* Interface that smart contracts must implement in order to let other addresses
* forceRecoverCollateral() a loan owned by the smart contract.
*
* NOTE: Any contract implementing this interface should also use OnlyMargin to control access
* to these functions
*/
interface ForceRecoverCollateralDelegator {
// ============ Public Interface functions ============
/**
* Function a contract must implement in order to let other addresses call
* forceRecoverCollateral().
*
* NOTE: If not returning zero address (or not reverting), this contract must assume that Margin
* will either revert the entire transaction or that the collateral was forcibly recovered.
*
* @param recoverer Address of the caller of the forceRecoverCollateral() function
* @param positionId Unique ID of the position
* @param recipient Address to send the recovered tokens to
* @return This address to accept, a different address to ask that contract
*/
function forceRecoverCollateralOnBehalfOf(
address recoverer,
bytes32 positionId,
address recipient
)
external
/* onlyMargin */
returns (address);
}
// File: contracts/margin/impl/ForceRecoverCollateralImpl.sol
/* solium-disable-next-line max-len*/
/**
* @title ForceRecoverCollateralImpl
* @author dYdX
*
* This library contains the implementation for the forceRecoverCollateral function of Margin
*/
library ForceRecoverCollateralImpl {
using SafeMath for uint256;
// ============ Events ============
/**
* Collateral for a position was forcibly recovered
*/
event CollateralForceRecovered(
bytes32 indexed positionId,
address indexed recipient,
uint256 amount
);
// ============ Public Implementation Functions ============
function forceRecoverCollateralImpl(
MarginState.State storage state,
bytes32 positionId,
address recipient
)
public
returns (uint256)
{
MarginCommon.Position storage position =
MarginCommon.getPositionFromStorage(state, positionId);
// Can only force recover after either:
// 1) The loan was called and the call period has elapsed
// 2) The maxDuration of the position has elapsed
require( /* solium-disable-next-line */
(
position.callTimestamp > 0
&& block.timestamp >= uint256(position.callTimestamp).add(position.callTimeLimit)
) || (
block.timestamp >= uint256(position.startTimestamp).add(position.maxDuration)
),
"ForceRecoverCollateralImpl#forceRecoverCollateralImpl: Cannot recover yet"
);
// Ensure lender consent
forceRecoverCollateralOnBehalfOfRecurse(
position.lender,
msg.sender,
positionId,
recipient
);
// Send the tokens
uint256 heldTokenRecovered = MarginCommon.getPositionBalanceImpl(state, positionId);
Vault(state.VAULT).transferFromVault(
positionId,
position.heldToken,
recipient,
heldTokenRecovered
);
// Delete the position
// NOTE: Since position is a storage pointer, this will also set all fields on
// the position variable to 0
MarginCommon.cleanupPosition(
state,
positionId
);
// Log an event
emit CollateralForceRecovered(
positionId,
recipient,
heldTokenRecovered
);
return heldTokenRecovered;
}
// ============ Private Helper-Functions ============
function forceRecoverCollateralOnBehalfOfRecurse(
address contractAddr,
address recoverer,
bytes32 positionId,
address recipient
)
private
{
// no need to ask for permission
if (recoverer == contractAddr) {
return;
}
address newContractAddr =
ForceRecoverCollateralDelegator(contractAddr).forceRecoverCollateralOnBehalfOf(
recoverer,
positionId,
recipient
);
if (newContractAddr != contractAddr) {
forceRecoverCollateralOnBehalfOfRecurse(
newContractAddr,
recoverer,
positionId,
recipient
);
}
}
}
// File: contracts/lib/TypedSignature.sol
/**
* @title TypedSignature
* @author dYdX
*
* Allows for ecrecovery of signed hashes with three different prepended messages:
* 1) ""
* 2) "\x19Ethereum Signed Message:\n32"
* 3) "\x19Ethereum Signed Message:\n\x20"
*/
library TypedSignature {
// Solidity does not offer guarantees about enum values, so we define them explicitly
uint8 private constant SIGTYPE_INVALID = 0;
uint8 private constant SIGTYPE_ECRECOVER_DEC = 1;
uint8 private constant SIGTYPE_ECRECOVER_HEX = 2;
uint8 private constant SIGTYPE_UNSUPPORTED = 3;
// prepended message with the length of the signed hash in hexadecimal
bytes constant private PREPEND_HEX = "\x19Ethereum Signed Message:\n\x20";
// prepended message with the length of the signed hash in decimal
bytes constant private PREPEND_DEC = "\x19Ethereum Signed Message:\n32";
/**
* Gives the address of the signer of a hash. Allows for three common prepended strings.
*
* @param hash Hash that was signed (does not include prepended message)
* @param signatureWithType Type and ECDSA signature with structure: {1:type}{1:v}{32:r}{32:s}
* @return address of the signer of the hash
*/
function recover(
bytes32 hash,
bytes signatureWithType
)
internal
pure
returns (address)
{
require(
signatureWithType.length == 66,
"SignatureValidator#validateSignature: invalid signature length"
);
uint8 sigType = uint8(signatureWithType[0]);
require(
sigType > uint8(SIGTYPE_INVALID),
"SignatureValidator#validateSignature: invalid signature type"
);
require(
sigType < uint8(SIGTYPE_UNSUPPORTED),
"SignatureValidator#validateSignature: unsupported signature type"
);
uint8 v = uint8(signatureWithType[1]);
bytes32 r;
bytes32 s;
/* solium-disable-next-line security/no-inline-assembly */
assembly {
r := mload(add(signatureWithType, 34))
s := mload(add(signatureWithType, 66))
}
bytes32 signedHash;
if (sigType == SIGTYPE_ECRECOVER_DEC) {
signedHash = keccak256(abi.encodePacked(PREPEND_DEC, hash));
} else {
assert(sigType == SIGTYPE_ECRECOVER_HEX);
signedHash = keccak256(abi.encodePacked(PREPEND_HEX, hash));
}
return ecrecover(
signedHash,
v,
r,
s
);
}
}
// File: contracts/margin/interfaces/LoanOfferingVerifier.sol
/**
* @title LoanOfferingVerifier
* @author dYdX
*
* Interface that smart contracts must implement to be able to make off-chain generated
* loan offerings.
*
* NOTE: Any contract implementing this interface should also use OnlyMargin to control access
* to these functions
*/
interface LoanOfferingVerifier {
/**
* Function a smart contract must implement to be able to consent to a loan. The loan offering
* will be generated off-chain. The "loan owner" address will own the loan-side of the resulting
* position.
*
* If true is returned, and no errors are thrown by the Margin contract, the loan will have
* occurred. This means that verifyLoanOffering can also be used to update internal contract
* state on a loan.
*
* @param addresses Array of addresses:
*
* [0] = owedToken
* [1] = heldToken
* [2] = loan payer
* [3] = loan owner
* [4] = loan taker
* [5] = loan positionOwner
* [6] = loan fee recipient
* [7] = loan lender fee token
* [8] = loan taker fee token
*
* @param values256 Values corresponding to:
*
* [0] = loan maximum amount
* [1] = loan minimum amount
* [2] = loan minimum heldToken
* [3] = loan lender fee
* [4] = loan taker fee
* [5] = loan expiration timestamp (in seconds)
* [6] = loan salt
*
* @param values32 Values corresponding to:
*
* [0] = loan call time limit (in seconds)
* [1] = loan maxDuration (in seconds)
* [2] = loan interest rate (annual nominal percentage times 10**6)
* [3] = loan interest update period (in seconds)
*
* @param positionId Unique ID of the position
* @param signature Arbitrary bytes; may or may not be an ECDSA signature
* @return This address to accept, a different address to ask that contract
*/
function verifyLoanOffering(
address[9] addresses,
uint256[7] values256,
uint32[4] values32,
bytes32 positionId,
bytes signature
)
external
/* onlyMargin */
returns (address);
}
// File: contracts/margin/impl/BorrowShared.sol
/**
* @title BorrowShared
* @author dYdX
*
* This library contains shared functionality between OpenPositionImpl and IncreasePositionImpl.
* Both use a Loan Offering and a DEX Order to open or increase a position.
*/
library BorrowShared {
using SafeMath for uint256;
// ============ Structs ============
struct Tx {
bytes32 positionId;
address owner;
uint256 principal;
uint256 lenderAmount;
MarginCommon.LoanOffering loanOffering;
address exchangeWrapper;
bool depositInHeldToken;
uint256 depositAmount;
uint256 collateralAmount;
uint256 heldTokenFromSell;
}
// ============ Internal Implementation Functions ============
/**
* Validate the transaction before exchanging heldToken for owedToken
*/
function validateTxPreSell(
MarginState.State storage state,
Tx memory transaction
)
internal
{
assert(transaction.lenderAmount >= transaction.principal);
require(
transaction.principal > 0,
"BorrowShared#validateTxPreSell: Positions with 0 principal are not allowed"
);
// If the taker is 0x0 then any address can take it. Otherwise only the taker can use it.
if (transaction.loanOffering.taker != address(0)) {
require(
msg.sender == transaction.loanOffering.taker,
"BorrowShared#validateTxPreSell: Invalid loan offering taker"
);
}
// If the positionOwner is 0x0 then any address can be set as the position owner.
// Otherwise only the specified positionOwner can be set as the position owner.
if (transaction.loanOffering.positionOwner != address(0)) {
require(
transaction.owner == transaction.loanOffering.positionOwner,
"BorrowShared#validateTxPreSell: Invalid position owner"
);
}
// Require the loan offering to be approved by the payer
if (AddressUtils.isContract(transaction.loanOffering.payer)) {
getConsentFromSmartContractLender(transaction);
} else {
require(
transaction.loanOffering.payer == TypedSignature.recover(
transaction.loanOffering.loanHash,
transaction.loanOffering.signature
),
"BorrowShared#validateTxPreSell: Invalid loan offering signature"
);
}
// Validate the amount is <= than max and >= min
uint256 unavailable = MarginCommon.getUnavailableLoanOfferingAmountImpl(
state,
transaction.loanOffering.loanHash
);
require(
transaction.lenderAmount.add(unavailable) <= transaction.loanOffering.rates.maxAmount,
"BorrowShared#validateTxPreSell: Loan offering does not have enough available"
);
require(
transaction.lenderAmount >= transaction.loanOffering.rates.minAmount,
"BorrowShared#validateTxPreSell: Lender amount is below loan offering minimum amount"
);
require(
transaction.loanOffering.owedToken != transaction.loanOffering.heldToken,
"BorrowShared#validateTxPreSell: owedToken cannot be equal to heldToken"
);
require(
transaction.owner != address(0),
"BorrowShared#validateTxPreSell: Position owner cannot be 0"
);
require(
transaction.loanOffering.owner != address(0),
"BorrowShared#validateTxPreSell: Loan owner cannot be 0"
);
require(
transaction.loanOffering.expirationTimestamp > block.timestamp,
"BorrowShared#validateTxPreSell: Loan offering is expired"
);
require(
transaction.loanOffering.maxDuration > 0,
"BorrowShared#validateTxPreSell: Loan offering has 0 maximum duration"
);
require(
transaction.loanOffering.rates.interestPeriod <= transaction.loanOffering.maxDuration,
"BorrowShared#validateTxPreSell: Loan offering interestPeriod > maxDuration"
);
// The minimum heldToken is validated after executing the sell
// Position and loan ownership is validated in TransferInternal
}
/**
* Validate the transaction after exchanging heldToken for owedToken, pay out fees, and store
* how much of the loan was used.
*/
function doPostSell(
MarginState.State storage state,
Tx memory transaction
)
internal
{
validateTxPostSell(transaction);
// Transfer feeTokens from trader and lender
transferLoanFees(state, transaction);
// Update global amounts for the loan
state.loanFills[transaction.loanOffering.loanHash] =
state.loanFills[transaction.loanOffering.loanHash].add(transaction.lenderAmount);
}
/**
* Sells the owedToken from the lender (and from the deposit if in owedToken) using the
* exchangeWrapper, then puts the resulting heldToken into the vault. Only trades for
* maxHeldTokenToBuy of heldTokens at most.
*/
function doSell(
MarginState.State storage state,
Tx transaction,
bytes orderData,
uint256 maxHeldTokenToBuy
)
internal
returns (uint256)
{
// Move owedTokens from lender to exchange wrapper
pullOwedTokensFromLender(state, transaction);
// Sell just the lender's owedToken (if trader deposit is in heldToken)
// Otherwise sell both the lender's owedToken and the trader's deposit in owedToken
uint256 sellAmount = transaction.depositInHeldToken ?
transaction.lenderAmount :
transaction.lenderAmount.add(transaction.depositAmount);
// Do the trade, taking only the maxHeldTokenToBuy if more is returned
uint256 heldTokenFromSell = Math.min256(
maxHeldTokenToBuy,
ExchangeWrapper(transaction.exchangeWrapper).exchange(
msg.sender,
state.TOKEN_PROXY,
transaction.loanOffering.heldToken,
transaction.loanOffering.owedToken,
sellAmount,
orderData
)
);
// Move the tokens to the vault
Vault(state.VAULT).transferToVault(
transaction.positionId,
transaction.loanOffering.heldToken,
transaction.exchangeWrapper,
heldTokenFromSell
);
// Update collateral amount
transaction.collateralAmount = transaction.collateralAmount.add(heldTokenFromSell);
return heldTokenFromSell;
}
/**
* Take the owedToken deposit from the trader and give it to the exchange wrapper so that it can
* be sold for heldToken.
*/
function doDepositOwedToken(
MarginState.State storage state,
Tx transaction
)
internal
{
TokenProxy(state.TOKEN_PROXY).transferTokens(
transaction.loanOffering.owedToken,
msg.sender,
transaction.exchangeWrapper,
transaction.depositAmount
);
}
/**
* Take the heldToken deposit from the trader and move it to the vault.
*/
function doDepositHeldToken(
MarginState.State storage state,
Tx transaction
)
internal
{
Vault(state.VAULT).transferToVault(
transaction.positionId,
transaction.loanOffering.heldToken,
msg.sender,
transaction.depositAmount
);
// Update collateral amount
transaction.collateralAmount = transaction.collateralAmount.add(transaction.depositAmount);
}
// ============ Private Helper-Functions ============
function validateTxPostSell(
Tx transaction
)
private
pure
{
uint256 expectedCollateral = transaction.depositInHeldToken ?
transaction.heldTokenFromSell.add(transaction.depositAmount) :
transaction.heldTokenFromSell;
assert(transaction.collateralAmount == expectedCollateral);
uint256 loanOfferingMinimumHeldToken = MathHelpers.getPartialAmountRoundedUp(
transaction.lenderAmount,
transaction.loanOffering.rates.maxAmount,
transaction.loanOffering.rates.minHeldToken
);
require(
transaction.collateralAmount >= loanOfferingMinimumHeldToken,
"BorrowShared#validateTxPostSell: Loan offering minimum held token not met"
);
}
function getConsentFromSmartContractLender(
Tx transaction
)
private
{
verifyLoanOfferingRecurse(
transaction.loanOffering.payer,
getLoanOfferingAddresses(transaction),
getLoanOfferingValues256(transaction),
getLoanOfferingValues32(transaction),
transaction.positionId,
transaction.loanOffering.signature
);
}
function verifyLoanOfferingRecurse(
address contractAddr,
address[9] addresses,
uint256[7] values256,
uint32[4] values32,
bytes32 positionId,
bytes signature
)
private
{
address newContractAddr = LoanOfferingVerifier(contractAddr).verifyLoanOffering(
addresses,
values256,
values32,
positionId,
signature
);
if (newContractAddr != contractAddr) {
verifyLoanOfferingRecurse(
newContractAddr,
addresses,
values256,
values32,
positionId,
signature
);
}
}
function pullOwedTokensFromLender(
MarginState.State storage state,
Tx transaction
)
private
{
// Transfer owedToken to the exchange wrapper
TokenProxy(state.TOKEN_PROXY).transferTokens(
transaction.loanOffering.owedToken,
transaction.loanOffering.payer,
transaction.exchangeWrapper,
transaction.lenderAmount
);
}
function transferLoanFees(
MarginState.State storage state,
Tx transaction
)
private
{
// 0 fee address indicates no fees
if (transaction.loanOffering.feeRecipient == address(0)) {
return;
}
TokenProxy proxy = TokenProxy(state.TOKEN_PROXY);
uint256 lenderFee = MathHelpers.getPartialAmount(
transaction.lenderAmount,
transaction.loanOffering.rates.maxAmount,
transaction.loanOffering.rates.lenderFee
);
uint256 takerFee = MathHelpers.getPartialAmount(
transaction.lenderAmount,
transaction.loanOffering.rates.maxAmount,
transaction.loanOffering.rates.takerFee
);
if (lenderFee > 0) {
proxy.transferTokens(
transaction.loanOffering.lenderFeeToken,
transaction.loanOffering.payer,
transaction.loanOffering.feeRecipient,
lenderFee
);
}
if (takerFee > 0) {
proxy.transferTokens(
transaction.loanOffering.takerFeeToken,
msg.sender,
transaction.loanOffering.feeRecipient,
takerFee
);
}
}
function getLoanOfferingAddresses(
Tx transaction
)
private
pure
returns (address[9])
{
return [
transaction.loanOffering.owedToken,
transaction.loanOffering.heldToken,
transaction.loanOffering.payer,
transaction.loanOffering.owner,
transaction.loanOffering.taker,
transaction.loanOffering.positionOwner,
transaction.loanOffering.feeRecipient,
transaction.loanOffering.lenderFeeToken,
transaction.loanOffering.takerFeeToken
];
}
function getLoanOfferingValues256(
Tx transaction
)
private
pure
returns (uint256[7])
{
return [
transaction.loanOffering.rates.maxAmount,
transaction.loanOffering.rates.minAmount,
transaction.loanOffering.rates.minHeldToken,
transaction.loanOffering.rates.lenderFee,
transaction.loanOffering.rates.takerFee,
transaction.loanOffering.expirationTimestamp,
transaction.loanOffering.salt
];
}
function getLoanOfferingValues32(
Tx transaction
)
private
pure
returns (uint32[4])
{
return [
transaction.loanOffering.callTimeLimit,
transaction.loanOffering.maxDuration,
transaction.loanOffering.rates.interestRate,
transaction.loanOffering.rates.interestPeriod
];
}
}
// File: contracts/margin/interfaces/lender/IncreaseLoanDelegator.sol
/**
* @title IncreaseLoanDelegator
* @author dYdX
*
* Interface that smart contracts must implement in order to own loans on behalf of other accounts.
*
* NOTE: Any contract implementing this interface should also use OnlyMargin to control access
* to these functions
*/
interface IncreaseLoanDelegator {
// ============ Public Interface functions ============
/**
* Function a contract must implement in order to allow additional value to be added onto
* an owned loan. Margin will call this on the owner of a loan during increasePosition().
*
* NOTE: If not returning zero (or not reverting), this contract must assume that Margin will
* either revert the entire transaction or that the loan size was successfully increased.
*
* @param payer Lender adding additional funds to the position
* @param positionId Unique ID of the position
* @param principalAdded Principal amount to be added to the position
* @param lentAmount Amount of owedToken lent by the lender (principal plus interest, or
* zero if increaseWithoutCounterparty() is used).
* @return This address to accept, a different address to ask that contract
*/
function increaseLoanOnBehalfOf(
address payer,
bytes32 positionId,
uint256 principalAdded,
uint256 lentAmount
)
external
/* onlyMargin */
returns (address);
}
// File: contracts/margin/interfaces/owner/IncreasePositionDelegator.sol
/**
* @title IncreasePositionDelegator
* @author dYdX
*
* Interface that smart contracts must implement in order to own position on behalf of other
* accounts
*
* NOTE: Any contract implementing this interface should also use OnlyMargin to control access
* to these functions
*/
interface IncreasePositionDelegator {
// ============ Public Interface functions ============
/**
* Function a contract must implement in order to allow additional value to be added onto
* an owned position. Margin will call this on the owner of a position during increasePosition()
*
* NOTE: If not returning zero (or not reverting), this contract must assume that Margin will
* either revert the entire transaction or that the position size was successfully increased.
*
* @param trader Address initiating the addition of funds to the position
* @param positionId Unique ID of the position
* @param principalAdded Amount of principal to be added to the position
* @return This address to accept, a different address to ask that contract
*/
function increasePositionOnBehalfOf(
address trader,
bytes32 positionId,
uint256 principalAdded
)
external
/* onlyMargin */
returns (address);
}
// File: contracts/margin/impl/IncreasePositionImpl.sol
/**
* @title IncreasePositionImpl
* @author dYdX
*
* This library contains the implementation for the increasePosition function of Margin
*/
library IncreasePositionImpl {
using SafeMath for uint256;
// ============ Events ============
/*
* A position was increased
*/
event PositionIncreased(
bytes32 indexed positionId,
address indexed trader,
address indexed lender,
address positionOwner,
address loanOwner,
bytes32 loanHash,
address loanFeeRecipient,
uint256 amountBorrowed,
uint256 principalAdded,
uint256 heldTokenFromSell,
uint256 depositAmount,
bool depositInHeldToken
);
// ============ Public Implementation Functions ============
function increasePositionImpl(
MarginState.State storage state,
bytes32 positionId,
address[7] addresses,
uint256[8] values256,
uint32[2] values32,
bool depositInHeldToken,
bytes signature,
bytes orderData
)
public
returns (uint256)
{
// Also ensures that the position exists
MarginCommon.Position storage position =
MarginCommon.getPositionFromStorage(state, positionId);
BorrowShared.Tx memory transaction = parseIncreasePositionTx(
position,
positionId,
addresses,
values256,
values32,
depositInHeldToken,
signature
);
validateIncrease(state, transaction, position);
doBorrowAndSell(state, transaction, orderData);
updateState(
position,
transaction.positionId,
transaction.principal,
transaction.lenderAmount,
transaction.loanOffering.payer
);
// LOG EVENT
recordPositionIncreased(transaction, position);
return transaction.lenderAmount;
}
function increaseWithoutCounterpartyImpl(
MarginState.State storage state,
bytes32 positionId,
uint256 principalToAdd
)
public
returns (uint256)
{
MarginCommon.Position storage position =
MarginCommon.getPositionFromStorage(state, positionId);
// Disallow adding 0 principal
require(
principalToAdd > 0,
"IncreasePositionImpl#increaseWithoutCounterpartyImpl: Cannot add 0 principal"
);
// Disallow additions after maximum duration
require(
block.timestamp < uint256(position.startTimestamp).add(position.maxDuration),
"IncreasePositionImpl#increaseWithoutCounterpartyImpl: Cannot increase after maxDuration"
);
uint256 heldTokenAmount = getCollateralNeededForAddedPrincipal(
state,
position,
positionId,
principalToAdd
);
Vault(state.VAULT).transferToVault(
positionId,
position.heldToken,
msg.sender,
heldTokenAmount
);
updateState(
position,
positionId,
principalToAdd,
0, // lent amount
msg.sender
);
emit PositionIncreased(
positionId,
msg.sender,
msg.sender,
position.owner,
position.lender,
"",
address(0),
0,
principalToAdd,
0,
heldTokenAmount,
true
);
return heldTokenAmount;
}
// ============ Private Helper-Functions ============
function doBorrowAndSell(
MarginState.State storage state,
BorrowShared.Tx memory transaction,
bytes orderData
)
private
{
// Calculate the number of heldTokens to add
uint256 collateralToAdd = getCollateralNeededForAddedPrincipal(
state,
state.positions[transaction.positionId],
transaction.positionId,
transaction.principal
);
// Do pre-exchange validations
BorrowShared.validateTxPreSell(state, transaction);
// Calculate and deposit owedToken
uint256 maxHeldTokenFromSell = MathHelpers.maxUint256();
if (!transaction.depositInHeldToken) {
transaction.depositAmount =
getOwedTokenDeposit(transaction, collateralToAdd, orderData);
BorrowShared.doDepositOwedToken(state, transaction);
maxHeldTokenFromSell = collateralToAdd;
}
// Sell owedToken for heldToken using the exchange wrapper
transaction.heldTokenFromSell = BorrowShared.doSell(
state,
transaction,
orderData,
maxHeldTokenFromSell
);
// Calculate and deposit heldToken
if (transaction.depositInHeldToken) {
require(
transaction.heldTokenFromSell <= collateralToAdd,
"IncreasePositionImpl#doBorrowAndSell: DEX order gives too much heldToken"
);
transaction.depositAmount = collateralToAdd.sub(transaction.heldTokenFromSell);
BorrowShared.doDepositHeldToken(state, transaction);
}
// Make sure the actual added collateral is what is expected
assert(transaction.collateralAmount == collateralToAdd);
// Do post-exchange validations
BorrowShared.doPostSell(state, transaction);
}
function getOwedTokenDeposit(
BorrowShared.Tx transaction,
uint256 collateralToAdd,
bytes orderData
)
private
view
returns (uint256)
{
uint256 totalOwedToken = ExchangeWrapper(transaction.exchangeWrapper).getExchangeCost(
transaction.loanOffering.heldToken,
transaction.loanOffering.owedToken,
collateralToAdd,
orderData
);
require(
transaction.lenderAmount <= totalOwedToken,
"IncreasePositionImpl#getOwedTokenDeposit: Lender amount is more than required"
);
return totalOwedToken.sub(transaction.lenderAmount);
}
function validateIncrease(
MarginState.State storage state,
BorrowShared.Tx transaction,
MarginCommon.Position storage position
)
private
view
{
assert(MarginCommon.containsPositionImpl(state, transaction.positionId));
require(
position.callTimeLimit <= transaction.loanOffering.callTimeLimit,
"IncreasePositionImpl#validateIncrease: Loan callTimeLimit is less than the position"
);
// require the position to end no later than the loanOffering's maximum acceptable end time
uint256 positionEndTimestamp = uint256(position.startTimestamp).add(position.maxDuration);
uint256 offeringEndTimestamp = block.timestamp.add(transaction.loanOffering.maxDuration);
require(
positionEndTimestamp <= offeringEndTimestamp,
"IncreasePositionImpl#validateIncrease: Loan end timestamp is less than the position"
);
require(
block.timestamp < positionEndTimestamp,
"IncreasePositionImpl#validateIncrease: Position has passed its maximum duration"
);
}
function getCollateralNeededForAddedPrincipal(
MarginState.State storage state,
MarginCommon.Position storage position,
bytes32 positionId,
uint256 principalToAdd
)
private
view
returns (uint256)
{
uint256 heldTokenBalance = MarginCommon.getPositionBalanceImpl(state, positionId);
return MathHelpers.getPartialAmountRoundedUp(
principalToAdd,
position.principal,
heldTokenBalance
);
}
function updateState(
MarginCommon.Position storage position,
bytes32 positionId,
uint256 principalAdded,
uint256 owedTokenLent,
address loanPayer
)
private
{
position.principal = position.principal.add(principalAdded);
address owner = position.owner;
address lender = position.lender;
// Ensure owner consent
increasePositionOnBehalfOfRecurse(
owner,
msg.sender,
positionId,
principalAdded
);
// Ensure lender consent
increaseLoanOnBehalfOfRecurse(
lender,
loanPayer,
positionId,
principalAdded,
owedTokenLent
);
}
function increasePositionOnBehalfOfRecurse(
address contractAddr,
address trader,
bytes32 positionId,
uint256 principalAdded
)
private
{
// Assume owner approval if not a smart contract and they increased their own position
if (trader == contractAddr && !AddressUtils.isContract(contractAddr)) {
return;
}
address newContractAddr =
IncreasePositionDelegator(contractAddr).increasePositionOnBehalfOf(
trader,
positionId,
principalAdded
);
if (newContractAddr != contractAddr) {
increasePositionOnBehalfOfRecurse(
newContractAddr,
trader,
positionId,
principalAdded
);
}
}
function increaseLoanOnBehalfOfRecurse(
address contractAddr,
address payer,
bytes32 positionId,
uint256 principalAdded,
uint256 amountLent
)
private
{
// Assume lender approval if not a smart contract and they increased their own loan
if (payer == contractAddr && !AddressUtils.isContract(contractAddr)) {
return;
}
address newContractAddr =
IncreaseLoanDelegator(contractAddr).increaseLoanOnBehalfOf(
payer,
positionId,
principalAdded,
amountLent
);
if (newContractAddr != contractAddr) {
increaseLoanOnBehalfOfRecurse(
newContractAddr,
payer,
positionId,
principalAdded,
amountLent
);
}
}
function recordPositionIncreased(
BorrowShared.Tx transaction,
MarginCommon.Position storage position
)
private
{
emit PositionIncreased(
transaction.positionId,
msg.sender,
transaction.loanOffering.payer,
position.owner,
position.lender,
transaction.loanOffering.loanHash,
transaction.loanOffering.feeRecipient,
transaction.lenderAmount,
transaction.principal,
transaction.heldTokenFromSell,
transaction.depositAmount,
transaction.depositInHeldToken
);
}
// ============ Parsing Functions ============
function parseIncreasePositionTx(
MarginCommon.Position storage position,
bytes32 positionId,
address[7] addresses,
uint256[8] values256,
uint32[2] values32,
bool depositInHeldToken,
bytes signature
)
private
view
returns (BorrowShared.Tx memory)
{
uint256 principal = values256[7];
uint256 lenderAmount = MarginCommon.calculateLenderAmountForIncreasePosition(
position,
principal,
block.timestamp
);
assert(lenderAmount >= principal);
BorrowShared.Tx memory transaction = BorrowShared.Tx({
positionId: positionId,
owner: position.owner,
principal: principal,
lenderAmount: lenderAmount,
loanOffering: parseLoanOfferingFromIncreasePositionTx(
position,
addresses,
values256,
values32,
signature
),
exchangeWrapper: addresses[6],
depositInHeldToken: depositInHeldToken,
depositAmount: 0, // set later
collateralAmount: 0, // set later
heldTokenFromSell: 0 // set later
});
return transaction;
}
function parseLoanOfferingFromIncreasePositionTx(
MarginCommon.Position storage position,
address[7] addresses,
uint256[8] values256,
uint32[2] values32,
bytes signature
)
private
view
returns (MarginCommon.LoanOffering memory)
{
MarginCommon.LoanOffering memory loanOffering = MarginCommon.LoanOffering({
owedToken: position.owedToken,
heldToken: position.heldToken,
payer: addresses[0],
owner: position.lender,
taker: addresses[1],
positionOwner: addresses[2],
feeRecipient: addresses[3],
lenderFeeToken: addresses[4],
takerFeeToken: addresses[5],
rates: parseLoanOfferingRatesFromIncreasePositionTx(position, values256),
expirationTimestamp: values256[5],
callTimeLimit: values32[0],
maxDuration: values32[1],
salt: values256[6],
loanHash: 0,
signature: signature
});
loanOffering.loanHash = MarginCommon.getLoanOfferingHash(loanOffering);
return loanOffering;
}
function parseLoanOfferingRatesFromIncreasePositionTx(
MarginCommon.Position storage position,
uint256[8] values256
)
private
view
returns (MarginCommon.LoanRates memory)
{
MarginCommon.LoanRates memory rates = MarginCommon.LoanRates({
maxAmount: values256[0],
minAmount: values256[1],
minHeldToken: values256[2],
lenderFee: values256[3],
takerFee: values256[4],
interestRate: position.interestRate,
interestPeriod: position.interestPeriod
});
return rates;
}
}
// File: contracts/margin/impl/MarginStorage.sol
/**
* @title MarginStorage
* @author dYdX
*
* This contract serves as the storage for the entire state of MarginStorage
*/
contract MarginStorage {
MarginState.State state;
}
// File: contracts/margin/impl/LoanGetters.sol
/**
* @title LoanGetters
* @author dYdX
*
* A collection of public constant getter functions that allows reading of the state of any loan
* offering stored in the dYdX protocol.
*/
contract LoanGetters is MarginStorage {
// ============ Public Constant Functions ============
/**
* Gets the principal amount of a loan offering that is no longer available.
*
* @param loanHash Unique hash of the loan offering
* @return The total unavailable amount of the loan offering, which is equal to the
* filled amount plus the canceled amount.
*/
function getLoanUnavailableAmount(
bytes32 loanHash
)
external
view
returns (uint256)
{
return MarginCommon.getUnavailableLoanOfferingAmountImpl(state, loanHash);
}
/**
* Gets the total amount of owed token lent for a loan.
*
* @param loanHash Unique hash of the loan offering
* @return The total filled amount of the loan offering.
*/
function getLoanFilledAmount(
bytes32 loanHash
)
external
view
returns (uint256)
{
return state.loanFills[loanHash];
}
/**
* Gets the amount of a loan offering that has been canceled.
*
* @param loanHash Unique hash of the loan offering
* @return The total canceled amount of the loan offering.
*/
function getLoanCanceledAmount(
bytes32 loanHash
)
external
view
returns (uint256)
{
return state.loanCancels[loanHash];
}
}
// File: contracts/margin/interfaces/lender/CancelMarginCallDelegator.sol
/**
* @title CancelMarginCallDelegator
* @author dYdX
*
* Interface that smart contracts must implement in order to let other addresses cancel a
* margin-call for a loan owned by the smart contract.
*
* NOTE: Any contract implementing this interface should also use OnlyMargin to control access
* to these functions
*/
interface CancelMarginCallDelegator {
// ============ Public Interface functions ============
/**
* Function a contract must implement in order to let other addresses call cancelMarginCall().
*
* NOTE: If not returning zero (or not reverting), this contract must assume that Margin will
* either revert the entire transaction or that the margin-call was successfully canceled.
*
* @param canceler Address of the caller of the cancelMarginCall function
* @param positionId Unique ID of the position
* @return This address to accept, a different address to ask that contract
*/
function cancelMarginCallOnBehalfOf(
address canceler,
bytes32 positionId
)
external
/* onlyMargin */
returns (address);
}
// File: contracts/margin/interfaces/lender/MarginCallDelegator.sol
/**
* @title MarginCallDelegator
* @author dYdX
*
* Interface that smart contracts must implement in order to let other addresses margin-call a loan
* owned by the smart contract.
*
* NOTE: Any contract implementing this interface should also use OnlyMargin to control access
* to these functions
*/
interface MarginCallDelegator {
// ============ Public Interface functions ============
/**
* Function a contract must implement in order to let other addresses call marginCall().
*
* NOTE: If not returning zero (or not reverting), this contract must assume that Margin will
* either revert the entire transaction or that the loan was successfully margin-called.
*
* @param caller Address of the caller of the marginCall function
* @param positionId Unique ID of the position
* @param depositAmount Amount of heldToken deposit that will be required to cancel the call
* @return This address to accept, a different address to ask that contract
*/
function marginCallOnBehalfOf(
address caller,
bytes32 positionId,
uint256 depositAmount
)
external
/* onlyMargin */
returns (address);
}
// File: contracts/margin/impl/LoanImpl.sol
/**
* @title LoanImpl
* @author dYdX
*
* This library contains the implementation for the following functions of Margin:
*
* - marginCall
* - cancelMarginCallImpl
* - cancelLoanOffering
*/
library LoanImpl {
using SafeMath for uint256;
// ============ Events ============
/**
* A position was margin-called
*/
event MarginCallInitiated(
bytes32 indexed positionId,
address indexed lender,
address indexed owner,
uint256 requiredDeposit
);
/**
* A margin call was canceled
*/
event MarginCallCanceled(
bytes32 indexed positionId,
address indexed lender,
address indexed owner,
uint256 depositAmount
);
/**
* A loan offering was canceled before it was used. Any amount less than the
* total for the loan offering can be canceled.
*/
event LoanOfferingCanceled(
bytes32 indexed loanHash,
address indexed payer,
address indexed feeRecipient,
uint256 cancelAmount
);
// ============ Public Implementation Functions ============
function marginCallImpl(
MarginState.State storage state,
bytes32 positionId,
uint256 requiredDeposit
)
public
{
MarginCommon.Position storage position =
MarginCommon.getPositionFromStorage(state, positionId);
require(
position.callTimestamp == 0,
"LoanImpl#marginCallImpl: The position has already been margin-called"
);
// Ensure lender consent
marginCallOnBehalfOfRecurse(
position.lender,
msg.sender,
positionId,
requiredDeposit
);
position.callTimestamp = TimestampHelper.getBlockTimestamp32();
position.requiredDeposit = requiredDeposit;
emit MarginCallInitiated(
positionId,
position.lender,
position.owner,
requiredDeposit
);
}
function cancelMarginCallImpl(
MarginState.State storage state,
bytes32 positionId
)
public
{
MarginCommon.Position storage position =
MarginCommon.getPositionFromStorage(state, positionId);
require(
position.callTimestamp > 0,
"LoanImpl#cancelMarginCallImpl: Position has not been margin-called"
);
// Ensure lender consent
cancelMarginCallOnBehalfOfRecurse(
position.lender,
msg.sender,
positionId
);
state.positions[positionId].callTimestamp = 0;
state.positions[positionId].requiredDeposit = 0;
emit MarginCallCanceled(
positionId,
position.lender,
position.owner,
0
);
}
function cancelLoanOfferingImpl(
MarginState.State storage state,
address[9] addresses,
uint256[7] values256,
uint32[4] values32,
uint256 cancelAmount
)
public
returns (uint256)
{
MarginCommon.LoanOffering memory loanOffering = parseLoanOffering(
addresses,
values256,
values32
);
require(
msg.sender == loanOffering.payer,
"LoanImpl#cancelLoanOfferingImpl: Only loan offering payer can cancel"
);
require(
loanOffering.expirationTimestamp > block.timestamp,
"LoanImpl#cancelLoanOfferingImpl: Loan offering has already expired"
);
uint256 remainingAmount = loanOffering.rates.maxAmount.sub(
MarginCommon.getUnavailableLoanOfferingAmountImpl(state, loanOffering.loanHash)
);
uint256 amountToCancel = Math.min256(remainingAmount, cancelAmount);
// If the loan was already fully canceled, then just return 0 amount was canceled
if (amountToCancel == 0) {
return 0;
}
state.loanCancels[loanOffering.loanHash] =
state.loanCancels[loanOffering.loanHash].add(amountToCancel);
emit LoanOfferingCanceled(
loanOffering.loanHash,
loanOffering.payer,
loanOffering.feeRecipient,
amountToCancel
);
return amountToCancel;
}
// ============ Private Helper-Functions ============
function marginCallOnBehalfOfRecurse(
address contractAddr,
address who,
bytes32 positionId,
uint256 requiredDeposit
)
private
{
// no need to ask for permission
if (who == contractAddr) {
return;
}
address newContractAddr =
MarginCallDelegator(contractAddr).marginCallOnBehalfOf(
msg.sender,
positionId,
requiredDeposit
);
if (newContractAddr != contractAddr) {
marginCallOnBehalfOfRecurse(
newContractAddr,
who,
positionId,
requiredDeposit
);
}
}
function cancelMarginCallOnBehalfOfRecurse(
address contractAddr,
address who,
bytes32 positionId
)
private
{
// no need to ask for permission
if (who == contractAddr) {
return;
}
address newContractAddr =
CancelMarginCallDelegator(contractAddr).cancelMarginCallOnBehalfOf(
msg.sender,
positionId
);
if (newContractAddr != contractAddr) {
cancelMarginCallOnBehalfOfRecurse(
newContractAddr,
who,
positionId
);
}
}
// ============ Parsing Functions ============
function parseLoanOffering(
address[9] addresses,
uint256[7] values256,
uint32[4] values32
)
private
view
returns (MarginCommon.LoanOffering memory)
{
MarginCommon.LoanOffering memory loanOffering = MarginCommon.LoanOffering({
owedToken: addresses[0],
heldToken: addresses[1],
payer: addresses[2],
owner: addresses[3],
taker: addresses[4],
positionOwner: addresses[5],
feeRecipient: addresses[6],
lenderFeeToken: addresses[7],
takerFeeToken: addresses[8],
rates: parseLoanOfferRates(values256, values32),
expirationTimestamp: values256[5],
callTimeLimit: values32[0],
maxDuration: values32[1],
salt: values256[6],
loanHash: 0,
signature: new bytes(0)
});
loanOffering.loanHash = MarginCommon.getLoanOfferingHash(loanOffering);
return loanOffering;
}
function parseLoanOfferRates(
uint256[7] values256,
uint32[4] values32
)
private
pure
returns (MarginCommon.LoanRates memory)
{
MarginCommon.LoanRates memory rates = MarginCommon.LoanRates({
maxAmount: values256[0],
minAmount: values256[1],
minHeldToken: values256[2],
interestRate: values32[2],
lenderFee: values256[3],
takerFee: values256[4],
interestPeriod: values32[3]
});
return rates;
}
}
// File: contracts/margin/impl/MarginAdmin.sol
/**
* @title MarginAdmin
* @author dYdX
*
* Contains admin functions for the Margin contract
* The owner can put Margin into various close-only modes, which will disallow new position creation
*/
contract MarginAdmin is Ownable {
// ============ Enums ============
// All functionality enabled
uint8 private constant OPERATION_STATE_OPERATIONAL = 0;
// Only closing functions + cancelLoanOffering allowed (marginCall, closePosition,
// cancelLoanOffering, closePositionDirectly, forceRecoverCollateral)
uint8 private constant OPERATION_STATE_CLOSE_AND_CANCEL_LOAN_ONLY = 1;
// Only closing functions allowed (marginCall, closePosition, closePositionDirectly,
// forceRecoverCollateral)
uint8 private constant OPERATION_STATE_CLOSE_ONLY = 2;
// Only closing functions allowed (marginCall, closePositionDirectly, forceRecoverCollateral)
uint8 private constant OPERATION_STATE_CLOSE_DIRECTLY_ONLY = 3;
// This operation state (and any higher) is invalid
uint8 private constant OPERATION_STATE_INVALID = 4;
// ============ Events ============
/**
* Event indicating the operation state has changed
*/
event OperationStateChanged(
uint8 from,
uint8 to
);
// ============ State Variables ============
uint8 public operationState;
// ============ Constructor ============
constructor()
public
Ownable()
{
operationState = OPERATION_STATE_OPERATIONAL;
}
// ============ Modifiers ============
modifier onlyWhileOperational() {
require(
operationState == OPERATION_STATE_OPERATIONAL,
"MarginAdmin#onlyWhileOperational: Can only call while operational"
);
_;
}
modifier cancelLoanOfferingStateControl() {
require(
operationState == OPERATION_STATE_OPERATIONAL
|| operationState == OPERATION_STATE_CLOSE_AND_CANCEL_LOAN_ONLY,
"MarginAdmin#cancelLoanOfferingStateControl: Invalid operation state"
);
_;
}
modifier closePositionStateControl() {
require(
operationState == OPERATION_STATE_OPERATIONAL
|| operationState == OPERATION_STATE_CLOSE_AND_CANCEL_LOAN_ONLY
|| operationState == OPERATION_STATE_CLOSE_ONLY,
"MarginAdmin#closePositionStateControl: Invalid operation state"
);
_;
}
modifier closePositionDirectlyStateControl() {
_;
}
// ============ Owner-Only State-Changing Functions ============
function setOperationState(
uint8 newState
)
external
onlyOwner
{
require(
newState < OPERATION_STATE_INVALID,
"MarginAdmin#setOperationState: newState is not a valid operation state"
);
if (newState != operationState) {
emit OperationStateChanged(
operationState,
newState
);
operationState = newState;
}
}
}
// File: contracts/margin/impl/MarginEvents.sol
/**
* @title MarginEvents
* @author dYdX
*
* Contains events for the Margin contract.
*
* NOTE: Any Margin function libraries that use events will need to both define the event here
* and copy the event into the library itself as libraries don't support sharing events
*/
contract MarginEvents {
// ============ Events ============
/**
* A position was opened
*/
event PositionOpened(
bytes32 indexed positionId,
address indexed trader,
address indexed lender,
bytes32 loanHash,
address owedToken,
address heldToken,
address loanFeeRecipient,
uint256 principal,
uint256 heldTokenFromSell,
uint256 depositAmount,
uint256 interestRate,
uint32 callTimeLimit,
uint32 maxDuration,
bool depositInHeldToken
);
/*
* A position was increased
*/
event PositionIncreased(
bytes32 indexed positionId,
address indexed trader,
address indexed lender,
address positionOwner,
address loanOwner,
bytes32 loanHash,
address loanFeeRecipient,
uint256 amountBorrowed,
uint256 principalAdded,
uint256 heldTokenFromSell,
uint256 depositAmount,
bool depositInHeldToken
);
/**
* A position was closed or partially closed
*/
event PositionClosed(
bytes32 indexed positionId,
address indexed closer,
address indexed payoutRecipient,
uint256 closeAmount,
uint256 remainingAmount,
uint256 owedTokenPaidToLender,
uint256 payoutAmount,
uint256 buybackCostInHeldToken,
bool payoutInHeldToken
);
/**
* Collateral for a position was forcibly recovered
*/
event CollateralForceRecovered(
bytes32 indexed positionId,
address indexed recipient,
uint256 amount
);
/**
* A position was margin-called
*/
event MarginCallInitiated(
bytes32 indexed positionId,
address indexed lender,
address indexed owner,
uint256 requiredDeposit
);
/**
* A margin call was canceled
*/
event MarginCallCanceled(
bytes32 indexed positionId,
address indexed lender,
address indexed owner,
uint256 depositAmount
);
/**
* A loan offering was canceled before it was used. Any amount less than the
* total for the loan offering can be canceled.
*/
event LoanOfferingCanceled(
bytes32 indexed loanHash,
address indexed payer,
address indexed feeRecipient,
uint256 cancelAmount
);
/**
* Additional collateral for a position was posted by the owner
*/
event AdditionalCollateralDeposited(
bytes32 indexed positionId,
uint256 amount,
address depositor
);
/**
* Ownership of a loan was transferred to a new address
*/
event LoanTransferred(
bytes32 indexed positionId,
address indexed from,
address indexed to
);
/**
* Ownership of a position was transferred to a new address
*/
event PositionTransferred(
bytes32 indexed positionId,
address indexed from,
address indexed to
);
}
// File: contracts/margin/impl/OpenPositionImpl.sol
/**
* @title OpenPositionImpl
* @author dYdX
*
* This library contains the implementation for the openPosition function of Margin
*/
library OpenPositionImpl {
using SafeMath for uint256;
// ============ Events ============
/**
* A position was opened
*/
event PositionOpened(
bytes32 indexed positionId,
address indexed trader,
address indexed lender,
bytes32 loanHash,
address owedToken,
address heldToken,
address loanFeeRecipient,
uint256 principal,
uint256 heldTokenFromSell,
uint256 depositAmount,
uint256 interestRate,
uint32 callTimeLimit,
uint32 maxDuration,
bool depositInHeldToken
);
// ============ Public Implementation Functions ============
function openPositionImpl(
MarginState.State storage state,
address[11] addresses,
uint256[10] values256,
uint32[4] values32,
bool depositInHeldToken,
bytes signature,
bytes orderData
)
public
returns (bytes32)
{
BorrowShared.Tx memory transaction = parseOpenTx(
addresses,
values256,
values32,
depositInHeldToken,
signature
);
require(
!MarginCommon.positionHasExisted(state, transaction.positionId),
"OpenPositionImpl#openPositionImpl: positionId already exists"
);
doBorrowAndSell(state, transaction, orderData);
// Before doStoreNewPosition() so that PositionOpened event is before Transferred events
recordPositionOpened(
transaction
);
doStoreNewPosition(
state,
transaction
);
return transaction.positionId;
}
// ============ Private Helper-Functions ============
function doBorrowAndSell(
MarginState.State storage state,
BorrowShared.Tx memory transaction,
bytes orderData
)
private
{
BorrowShared.validateTxPreSell(state, transaction);
if (transaction.depositInHeldToken) {
BorrowShared.doDepositHeldToken(state, transaction);
} else {
BorrowShared.doDepositOwedToken(state, transaction);
}
transaction.heldTokenFromSell = BorrowShared.doSell(
state,
transaction,
orderData,
MathHelpers.maxUint256()
);
BorrowShared.doPostSell(state, transaction);
}
function doStoreNewPosition(
MarginState.State storage state,
BorrowShared.Tx memory transaction
)
private
{
MarginCommon.storeNewPosition(
state,
transaction.positionId,
MarginCommon.Position({
owedToken: transaction.loanOffering.owedToken,
heldToken: transaction.loanOffering.heldToken,
lender: transaction.loanOffering.owner,
owner: transaction.owner,
principal: transaction.principal,
requiredDeposit: 0,
callTimeLimit: transaction.loanOffering.callTimeLimit,
startTimestamp: 0,
callTimestamp: 0,
maxDuration: transaction.loanOffering.maxDuration,
interestRate: transaction.loanOffering.rates.interestRate,
interestPeriod: transaction.loanOffering.rates.interestPeriod
}),
transaction.loanOffering.payer
);
}
function recordPositionOpened(
BorrowShared.Tx transaction
)
private
{
emit PositionOpened(
transaction.positionId,
msg.sender,
transaction.loanOffering.payer,
transaction.loanOffering.loanHash,
transaction.loanOffering.owedToken,
transaction.loanOffering.heldToken,
transaction.loanOffering.feeRecipient,
transaction.principal,
transaction.heldTokenFromSell,
transaction.depositAmount,
transaction.loanOffering.rates.interestRate,
transaction.loanOffering.callTimeLimit,
transaction.loanOffering.maxDuration,
transaction.depositInHeldToken
);
}
// ============ Parsing Functions ============
function parseOpenTx(
address[11] addresses,
uint256[10] values256,
uint32[4] values32,
bool depositInHeldToken,
bytes signature
)
private
view
returns (BorrowShared.Tx memory)
{
BorrowShared.Tx memory transaction = BorrowShared.Tx({
positionId: MarginCommon.getPositionIdFromNonce(values256[9]),
owner: addresses[0],
principal: values256[7],
lenderAmount: values256[7],
loanOffering: parseLoanOffering(
addresses,
values256,
values32,
signature
),
exchangeWrapper: addresses[10],
depositInHeldToken: depositInHeldToken,
depositAmount: values256[8],
collateralAmount: 0, // set later
heldTokenFromSell: 0 // set later
});
return transaction;
}
function parseLoanOffering(
address[11] addresses,
uint256[10] values256,
uint32[4] values32,
bytes signature
)
private
view
returns (MarginCommon.LoanOffering memory)
{
MarginCommon.LoanOffering memory loanOffering = MarginCommon.LoanOffering({
owedToken: addresses[1],
heldToken: addresses[2],
payer: addresses[3],
owner: addresses[4],
taker: addresses[5],
positionOwner: addresses[6],
feeRecipient: addresses[7],
lenderFeeToken: addresses[8],
takerFeeToken: addresses[9],
rates: parseLoanOfferRates(values256, values32),
expirationTimestamp: values256[5],
callTimeLimit: values32[0],
maxDuration: values32[1],
salt: values256[6],
loanHash: 0,
signature: signature
});
loanOffering.loanHash = MarginCommon.getLoanOfferingHash(loanOffering);
return loanOffering;
}
function parseLoanOfferRates(
uint256[10] values256,
uint32[4] values32
)
private
pure
returns (MarginCommon.LoanRates memory)
{
MarginCommon.LoanRates memory rates = MarginCommon.LoanRates({
maxAmount: values256[0],
minAmount: values256[1],
minHeldToken: values256[2],
lenderFee: values256[3],
takerFee: values256[4],
interestRate: values32[2],
interestPeriod: values32[3]
});
return rates;
}
}
// File: contracts/margin/impl/OpenWithoutCounterpartyImpl.sol
/**
* @title OpenWithoutCounterpartyImpl
* @author dYdX
*
* This library contains the implementation for the openWithoutCounterparty
* function of Margin
*/
library OpenWithoutCounterpartyImpl {
// ============ Structs ============
struct Tx {
bytes32 positionId;
address positionOwner;
address owedToken;
address heldToken;
address loanOwner;
uint256 principal;
uint256 deposit;
uint32 callTimeLimit;
uint32 maxDuration;
uint32 interestRate;
uint32 interestPeriod;
}
// ============ Events ============
/**
* A position was opened
*/
event PositionOpened(
bytes32 indexed positionId,
address indexed trader,
address indexed lender,
bytes32 loanHash,
address owedToken,
address heldToken,
address loanFeeRecipient,
uint256 principal,
uint256 heldTokenFromSell,
uint256 depositAmount,
uint256 interestRate,
uint32 callTimeLimit,
uint32 maxDuration,
bool depositInHeldToken
);
// ============ Public Implementation Functions ============
function openWithoutCounterpartyImpl(
MarginState.State storage state,
address[4] addresses,
uint256[3] values256,
uint32[4] values32
)
public
returns (bytes32)
{
Tx memory openTx = parseTx(
addresses,
values256,
values32
);
validate(
state,
openTx
);
Vault(state.VAULT).transferToVault(
openTx.positionId,
openTx.heldToken,
msg.sender,
openTx.deposit
);
recordPositionOpened(
openTx
);
doStoreNewPosition(
state,
openTx
);
return openTx.positionId;
}
// ============ Private Helper-Functions ============
function doStoreNewPosition(
MarginState.State storage state,
Tx memory openTx
)
private
{
MarginCommon.storeNewPosition(
state,
openTx.positionId,
MarginCommon.Position({
owedToken: openTx.owedToken,
heldToken: openTx.heldToken,
lender: openTx.loanOwner,
owner: openTx.positionOwner,
principal: openTx.principal,
requiredDeposit: 0,
callTimeLimit: openTx.callTimeLimit,
startTimestamp: 0,
callTimestamp: 0,
maxDuration: openTx.maxDuration,
interestRate: openTx.interestRate,
interestPeriod: openTx.interestPeriod
}),
msg.sender
);
}
function validate(
MarginState.State storage state,
Tx memory openTx
)
private
view
{
require(
!MarginCommon.positionHasExisted(state, openTx.positionId),
"openWithoutCounterpartyImpl#validate: positionId already exists"
);
require(
openTx.principal > 0,
"openWithoutCounterpartyImpl#validate: principal cannot be 0"
);
require(
openTx.owedToken != address(0),
"openWithoutCounterpartyImpl#validate: owedToken cannot be 0"
);
require(
openTx.owedToken != openTx.heldToken,
"openWithoutCounterpartyImpl#validate: owedToken cannot be equal to heldToken"
);
require(
openTx.positionOwner != address(0),
"openWithoutCounterpartyImpl#validate: positionOwner cannot be 0"
);
require(
openTx.loanOwner != address(0),
"openWithoutCounterpartyImpl#validate: loanOwner cannot be 0"
);
require(
openTx.maxDuration > 0,
"openWithoutCounterpartyImpl#validate: maxDuration cannot be 0"
);
require(
openTx.interestPeriod <= openTx.maxDuration,
"openWithoutCounterpartyImpl#validate: interestPeriod must be <= maxDuration"
);
}
function recordPositionOpened(
Tx memory openTx
)
private
{
emit PositionOpened(
openTx.positionId,
msg.sender,
msg.sender,
bytes32(0),
openTx.owedToken,
openTx.heldToken,
address(0),
openTx.principal,
0,
openTx.deposit,
openTx.interestRate,
openTx.callTimeLimit,
openTx.maxDuration,
true
);
}
// ============ Parsing Functions ============
function parseTx(
address[4] addresses,
uint256[3] values256,
uint32[4] values32
)
private
view
returns (Tx memory)
{
Tx memory openTx = Tx({
positionId: MarginCommon.getPositionIdFromNonce(values256[2]),
positionOwner: addresses[0],
owedToken: addresses[1],
heldToken: addresses[2],
loanOwner: addresses[3],
principal: values256[0],
deposit: values256[1],
callTimeLimit: values32[0],
maxDuration: values32[1],
interestRate: values32[2],
interestPeriod: values32[3]
});
return openTx;
}
}
// File: contracts/margin/impl/PositionGetters.sol
/**
* @title PositionGetters
* @author dYdX
*
* A collection of public constant getter functions that allows reading of the state of any position
* stored in the dYdX protocol.
*/
contract PositionGetters is MarginStorage {
using SafeMath for uint256;
// ============ Public Constant Functions ============
/**
* Gets if a position is currently open.
*
* @param positionId Unique ID of the position
* @return True if the position is exists and is open
*/
function containsPosition(
bytes32 positionId
)
external
view
returns (bool)
{
return MarginCommon.containsPositionImpl(state, positionId);
}
/**
* Gets if a position is currently margin-called.
*
* @param positionId Unique ID of the position
* @return True if the position is margin-called
*/
function isPositionCalled(
bytes32 positionId
)
external
view
returns (bool)
{
return (state.positions[positionId].callTimestamp > 0);
}
/**
* Gets if a position was previously open and is now closed.
*
* @param positionId Unique ID of the position
* @return True if the position is now closed
*/
function isPositionClosed(
bytes32 positionId
)
external
view
returns (bool)
{
return state.closedPositions[positionId];
}
/**
* Gets the total amount of owedToken ever repaid to the lender for a position.
*
* @param positionId Unique ID of the position
* @return Total amount of owedToken ever repaid
*/
function getTotalOwedTokenRepaidToLender(
bytes32 positionId
)
external
view
returns (uint256)
{
return state.totalOwedTokenRepaidToLender[positionId];
}
/**
* Gets the amount of heldToken currently locked up in Vault for a particular position.
*
* @param positionId Unique ID of the position
* @return The amount of heldToken
*/
function getPositionBalance(
bytes32 positionId
)
external
view
returns (uint256)
{
return MarginCommon.getPositionBalanceImpl(state, positionId);
}
/**
* Gets the time until the interest fee charged for the position will increase.
* Returns 1 if the interest fee increases every second.
* Returns 0 if the interest fee will never increase again.
*
* @param positionId Unique ID of the position
* @return The number of seconds until the interest fee will increase
*/
function getTimeUntilInterestIncrease(
bytes32 positionId
)
external
view
returns (uint256)
{
MarginCommon.Position storage position =
MarginCommon.getPositionFromStorage(state, positionId);
uint256 effectiveTimeElapsed = MarginCommon.calculateEffectiveTimeElapsed(
position,
block.timestamp
);
uint256 absoluteTimeElapsed = block.timestamp.sub(position.startTimestamp);
if (absoluteTimeElapsed > effectiveTimeElapsed) { // past maxDuration
return 0;
} else {
// nextStep is the final second at which the calculated interest fee is the same as it
// is currently, so add 1 to get the correct value
return effectiveTimeElapsed.add(1).sub(absoluteTimeElapsed);
}
}
/**
* Gets the amount of owedTokens currently needed to close the position completely, including
* interest fees.
*
* @param positionId Unique ID of the position
* @return The number of owedTokens
*/
function getPositionOwedAmount(
bytes32 positionId
)
external
view
returns (uint256)
{
MarginCommon.Position storage position =
MarginCommon.getPositionFromStorage(state, positionId);
return MarginCommon.calculateOwedAmount(
position,
position.principal,
block.timestamp
);
}
/**
* Gets the amount of owedTokens needed to close a given principal amount of the position at a
* given time, including interest fees.
*
* @param positionId Unique ID of the position
* @param principalToClose Amount of principal being closed
* @param timestamp Block timestamp in seconds of close
* @return The number of owedTokens owed
*/
function getPositionOwedAmountAtTime(
bytes32 positionId,
uint256 principalToClose,
uint32 timestamp
)
external
view
returns (uint256)
{
MarginCommon.Position storage position =
MarginCommon.getPositionFromStorage(state, positionId);
require(
timestamp >= position.startTimestamp,
"PositionGetters#getPositionOwedAmountAtTime: Requested time before position started"
);
return MarginCommon.calculateOwedAmount(
position,
principalToClose,
timestamp
);
}
/**
* Gets the amount of owedTokens that can be borrowed from a lender to add a given principal
* amount to the position at a given time.
*
* @param positionId Unique ID of the position
* @param principalToAdd Amount being added to principal
* @param timestamp Block timestamp in seconds of addition
* @return The number of owedTokens that will be borrowed
*/
function getLenderAmountForIncreasePositionAtTime(
bytes32 positionId,
uint256 principalToAdd,
uint32 timestamp
)
external
view
returns (uint256)
{
MarginCommon.Position storage position =
MarginCommon.getPositionFromStorage(state, positionId);
require(
timestamp >= position.startTimestamp,
"PositionGetters#getLenderAmountForIncreasePositionAtTime: timestamp < position start"
);
return MarginCommon.calculateLenderAmountForIncreasePosition(
position,
principalToAdd,
timestamp
);
}
// ============ All Properties ============
/**
* Get a Position by id. This does not validate the position exists. If the position does not
* exist, all 0's will be returned.
*
* @param positionId Unique ID of the position
* @return Addresses corresponding to:
*
* [0] = owedToken
* [1] = heldToken
* [2] = lender
* [3] = owner
*
* Values corresponding to:
*
* [0] = principal
* [1] = requiredDeposit
*
* Values corresponding to:
*
* [0] = callTimeLimit
* [1] = startTimestamp
* [2] = callTimestamp
* [3] = maxDuration
* [4] = interestRate
* [5] = interestPeriod
*/
function getPosition(
bytes32 positionId
)
external
view
returns (
address[4],
uint256[2],
uint32[6]
)
{
MarginCommon.Position storage position = state.positions[positionId];
return (
[
position.owedToken,
position.heldToken,
position.lender,
position.owner
],
[
position.principal,
position.requiredDeposit
],
[
position.callTimeLimit,
position.startTimestamp,
position.callTimestamp,
position.maxDuration,
position.interestRate,
position.interestPeriod
]
);
}
// ============ Individual Properties ============
function getPositionLender(
bytes32 positionId
)
external
view
returns (address)
{
return state.positions[positionId].lender;
}
function getPositionOwner(
bytes32 positionId
)
external
view
returns (address)
{
return state.positions[positionId].owner;
}
function getPositionHeldToken(
bytes32 positionId
)
external
view
returns (address)
{
return state.positions[positionId].heldToken;
}
function getPositionOwedToken(
bytes32 positionId
)
external
view
returns (address)
{
return state.positions[positionId].owedToken;
}
function getPositionPrincipal(
bytes32 positionId
)
external
view
returns (uint256)
{
return state.positions[positionId].principal;
}
function getPositionInterestRate(
bytes32 positionId
)
external
view
returns (uint256)
{
return state.positions[positionId].interestRate;
}
function getPositionRequiredDeposit(
bytes32 positionId
)
external
view
returns (uint256)
{
return state.positions[positionId].requiredDeposit;
}
function getPositionStartTimestamp(
bytes32 positionId
)
external
view
returns (uint32)
{
return state.positions[positionId].startTimestamp;
}
function getPositionCallTimestamp(
bytes32 positionId
)
external
view
returns (uint32)
{
return state.positions[positionId].callTimestamp;
}
function getPositionCallTimeLimit(
bytes32 positionId
)
external
view
returns (uint32)
{
return state.positions[positionId].callTimeLimit;
}
function getPositionMaxDuration(
bytes32 positionId
)
external
view
returns (uint32)
{
return state.positions[positionId].maxDuration;
}
function getPositioninterestPeriod(
bytes32 positionId
)
external
view
returns (uint32)
{
return state.positions[positionId].interestPeriod;
}
}
// File: contracts/margin/impl/TransferImpl.sol
/**
* @title TransferImpl
* @author dYdX
*
* This library contains the implementation for the transferPosition and transferLoan functions of
* Margin
*/
library TransferImpl {
// ============ Public Implementation Functions ============
function transferLoanImpl(
MarginState.State storage state,
bytes32 positionId,
address newLender
)
public
{
require(
MarginCommon.containsPositionImpl(state, positionId),
"TransferImpl#transferLoanImpl: Position does not exist"
);
address originalLender = state.positions[positionId].lender;
require(
msg.sender == originalLender,
"TransferImpl#transferLoanImpl: Only lender can transfer ownership"
);
require(
newLender != originalLender,
"TransferImpl#transferLoanImpl: Cannot transfer ownership to self"
);
// Doesn't change the state of positionId; figures out the final owner of loan.
// That is, newLender may pass ownership to a different address.
address finalLender = TransferInternal.grantLoanOwnership(
positionId,
originalLender,
newLender);
require(
finalLender != originalLender,
"TransferImpl#transferLoanImpl: Cannot ultimately transfer ownership to self"
);
// Set state only after resolving the new owner (to reduce the number of storage calls)
state.positions[positionId].lender = finalLender;
}
function transferPositionImpl(
MarginState.State storage state,
bytes32 positionId,
address newOwner
)
public
{
require(
MarginCommon.containsPositionImpl(state, positionId),
"TransferImpl#transferPositionImpl: Position does not exist"
);
address originalOwner = state.positions[positionId].owner;
require(
msg.sender == originalOwner,
"TransferImpl#transferPositionImpl: Only position owner can transfer ownership"
);
require(
newOwner != originalOwner,
"TransferImpl#transferPositionImpl: Cannot transfer ownership to self"
);
// Doesn't change the state of positionId; figures out the final owner of position.
// That is, newOwner may pass ownership to a different address.
address finalOwner = TransferInternal.grantPositionOwnership(
positionId,
originalOwner,
newOwner);
require(
finalOwner != originalOwner,
"TransferImpl#transferPositionImpl: Cannot ultimately transfer ownership to self"
);
// Set state only after resolving the new owner (to reduce the number of storage calls)
state.positions[positionId].owner = finalOwner;
}
}
// File: contracts/margin/Margin.sol
/**
* @title Margin
* @author dYdX
*
* This contract is used to facilitate margin trading as per the dYdX protocol
*/
contract Margin is
ReentrancyGuard,
MarginStorage,
MarginEvents,
MarginAdmin,
LoanGetters,
PositionGetters
{
using SafeMath for uint256;
// ============ Constructor ============
constructor(
address vault,
address proxy
)
public
MarginAdmin()
{
state = MarginState.State({
VAULT: vault,
TOKEN_PROXY: proxy
});
}
// ============ Public State Changing Functions ============
/**
* Open a margin position. Called by the margin trader who must provide both a
* signed loan offering as well as a DEX Order with which to sell the owedToken.
*
* @param addresses Addresses corresponding to:
*
* [0] = position owner
* [1] = owedToken
* [2] = heldToken
* [3] = loan payer
* [4] = loan owner
* [5] = loan taker
* [6] = loan position owner
* [7] = loan fee recipient
* [8] = loan lender fee token
* [9] = loan taker fee token
* [10] = exchange wrapper address
*
* @param values256 Values corresponding to:
*
* [0] = loan maximum amount
* [1] = loan minimum amount
* [2] = loan minimum heldToken
* [3] = loan lender fee
* [4] = loan taker fee
* [5] = loan expiration timestamp (in seconds)
* [6] = loan salt
* [7] = position amount of principal
* [8] = deposit amount
* [9] = nonce (used to calculate positionId)
*
* @param values32 Values corresponding to:
*
* [0] = loan call time limit (in seconds)
* [1] = loan maxDuration (in seconds)
* [2] = loan interest rate (annual nominal percentage times 10**6)
* [3] = loan interest update period (in seconds)
*
* @param depositInHeldToken True if the trader wishes to pay the margin deposit in heldToken.
* False if the margin deposit will be in owedToken
* and then sold along with the owedToken borrowed from the lender
* @param signature If loan payer is an account, then this must be the tightly-packed
* ECDSA V/R/S parameters from signing the loan hash. If loan payer
* is a smart contract, these are arbitrary bytes that the contract
* will recieve when choosing whether to approve the loan.
* @param order Order object to be passed to the exchange wrapper
* @return Unique ID for the new position
*/
function openPosition(
address[11] addresses,
uint256[10] values256,
uint32[4] values32,
bool depositInHeldToken,
bytes signature,
bytes order
)
external
onlyWhileOperational
nonReentrant
returns (bytes32)
{
return OpenPositionImpl.openPositionImpl(
state,
addresses,
values256,
values32,
depositInHeldToken,
signature,
order
);
}
/**
* Open a margin position without a counterparty. The caller will serve as both the
* lender and the position owner
*
* @param addresses Addresses corresponding to:
*
* [0] = position owner
* [1] = owedToken
* [2] = heldToken
* [3] = loan owner
*
* @param values256 Values corresponding to:
*
* [0] = principal
* [1] = deposit amount
* [2] = nonce (used to calculate positionId)
*
* @param values32 Values corresponding to:
*
* [0] = call time limit (in seconds)
* [1] = maxDuration (in seconds)
* [2] = interest rate (annual nominal percentage times 10**6)
* [3] = interest update period (in seconds)
*
* @return Unique ID for the new position
*/
function openWithoutCounterparty(
address[4] addresses,
uint256[3] values256,
uint32[4] values32
)
external
onlyWhileOperational
nonReentrant
returns (bytes32)
{
return OpenWithoutCounterpartyImpl.openWithoutCounterpartyImpl(
state,
addresses,
values256,
values32
);
}
/**
* Increase the size of a position. Funds will be borrowed from the loan payer and sold as per
* the position. The amount of owedToken borrowed from the lender will be >= the amount of
* principal added, as it will incorporate interest already earned by the position so far.
*
* @param positionId Unique ID of the position
* @param addresses Addresses corresponding to:
*
* [0] = loan payer
* [1] = loan taker
* [2] = loan position owner
* [3] = loan fee recipient
* [4] = loan lender fee token
* [5] = loan taker fee token
* [6] = exchange wrapper address
*
* @param values256 Values corresponding to:
*
* [0] = loan maximum amount
* [1] = loan minimum amount
* [2] = loan minimum heldToken
* [3] = loan lender fee
* [4] = loan taker fee
* [5] = loan expiration timestamp (in seconds)
* [6] = loan salt
* [7] = amount of principal to add to the position (NOTE: the amount pulled from the lender
* will be >= this amount)
*
* @param values32 Values corresponding to:
*
* [0] = loan call time limit (in seconds)
* [1] = loan maxDuration (in seconds)
*
* @param depositInHeldToken True if the trader wishes to pay the margin deposit in heldToken.
* False if the margin deposit will be pulled in owedToken
* and then sold along with the owedToken borrowed from the lender
* @param signature If loan payer is an account, then this must be the tightly-packed
* ECDSA V/R/S parameters from signing the loan hash. If loan payer
* is a smart contract, these are arbitrary bytes that the contract
* will recieve when choosing whether to approve the loan.
* @param order Order object to be passed to the exchange wrapper
* @return Amount of owedTokens pulled from the lender
*/
function increasePosition(
bytes32 positionId,
address[7] addresses,
uint256[8] values256,
uint32[2] values32,
bool depositInHeldToken,
bytes signature,
bytes order
)
external
onlyWhileOperational
nonReentrant
returns (uint256)
{
return IncreasePositionImpl.increasePositionImpl(
state,
positionId,
addresses,
values256,
values32,
depositInHeldToken,
signature,
order
);
}
/**
* Increase a position directly by putting up heldToken. The caller will serve as both the
* lender and the position owner
*
* @param positionId Unique ID of the position
* @param principalToAdd Principal amount to add to the position
* @return Amount of heldToken pulled from the msg.sender
*/
function increaseWithoutCounterparty(
bytes32 positionId,
uint256 principalToAdd
)
external
onlyWhileOperational
nonReentrant
returns (uint256)
{
return IncreasePositionImpl.increaseWithoutCounterpartyImpl(
state,
positionId,
principalToAdd
);
}
/**
* Close a position. May be called by the owner or with the approval of the owner. May provide
* an order and exchangeWrapper to facilitate the closing of the position. The payoutRecipient
* is sent the resulting payout.
*
* @param positionId Unique ID of the position
* @param requestedCloseAmount Principal amount of the position to close. The actual amount
* closed is also bounded by:
* 1) The principal of the position
* 2) The amount allowed by the owner if closer != owner
* @param payoutRecipient Address of the recipient of tokens paid out from closing
* @param exchangeWrapper Address of the exchange wrapper
* @param payoutInHeldToken True to pay out the payoutRecipient in heldToken,
* False to pay out the payoutRecipient in owedToken
* @param order Order object to be passed to the exchange wrapper
* @return Values corresponding to:
* 1) Principal of position closed
* 2) Amount of tokens (heldToken if payoutInHeldtoken is true,
* owedToken otherwise) received by the payoutRecipient
* 3) Amount of owedToken paid (incl. interest fee) to the lender
*/
function closePosition(
bytes32 positionId,
uint256 requestedCloseAmount,
address payoutRecipient,
address exchangeWrapper,
bool payoutInHeldToken,
bytes order
)
external
closePositionStateControl
nonReentrant
returns (uint256, uint256, uint256)
{
return ClosePositionImpl.closePositionImpl(
state,
positionId,
requestedCloseAmount,
payoutRecipient,
exchangeWrapper,
payoutInHeldToken,
order
);
}
/**
* Helper to close a position by paying owedToken directly rather than using an exchangeWrapper.
*
* @param positionId Unique ID of the position
* @param requestedCloseAmount Principal amount of the position to close. The actual amount
* closed is also bounded by:
* 1) The principal of the position
* 2) The amount allowed by the owner if closer != owner
* @param payoutRecipient Address of the recipient of tokens paid out from closing
* @return Values corresponding to:
* 1) Principal amount of position closed
* 2) Amount of heldToken received by the payoutRecipient
* 3) Amount of owedToken paid (incl. interest fee) to the lender
*/
function closePositionDirectly(
bytes32 positionId,
uint256 requestedCloseAmount,
address payoutRecipient
)
external
closePositionDirectlyStateControl
nonReentrant
returns (uint256, uint256, uint256)
{
return ClosePositionImpl.closePositionImpl(
state,
positionId,
requestedCloseAmount,
payoutRecipient,
address(0),
true,
new bytes(0)
);
}
/**
* Reduce the size of a position and withdraw a proportional amount of heldToken from the vault.
* Must be approved by both the position owner and lender.
*
* @param positionId Unique ID of the position
* @param requestedCloseAmount Principal amount of the position to close. The actual amount
* closed is also bounded by:
* 1) The principal of the position
* 2) The amount allowed by the owner if closer != owner
* 3) The amount allowed by the lender if closer != lender
* @return Values corresponding to:
* 1) Principal amount of position closed
* 2) Amount of heldToken received by the msg.sender
*/
function closeWithoutCounterparty(
bytes32 positionId,
uint256 requestedCloseAmount,
address payoutRecipient
)
external
closePositionStateControl
nonReentrant
returns (uint256, uint256)
{
return CloseWithoutCounterpartyImpl.closeWithoutCounterpartyImpl(
state,
positionId,
requestedCloseAmount,
payoutRecipient
);
}
/**
* Margin-call a position. Only callable with the approval of the position lender. After the
* call, the position owner will have time equal to the callTimeLimit of the position to close
* the position. If the owner does not close the position, the lender can recover the collateral
* in the position.
*
* @param positionId Unique ID of the position
* @param requiredDeposit Amount of deposit the position owner will have to put up to cancel
* the margin-call. Passing in 0 means the margin call cannot be
* canceled by depositing
*/
function marginCall(
bytes32 positionId,
uint256 requiredDeposit
)
external
nonReentrant
{
LoanImpl.marginCallImpl(
state,
positionId,
requiredDeposit
);
}
/**
* Cancel a margin-call. Only callable with the approval of the position lender.
*
* @param positionId Unique ID of the position
*/
function cancelMarginCall(
bytes32 positionId
)
external
onlyWhileOperational
nonReentrant
{
LoanImpl.cancelMarginCallImpl(state, positionId);
}
/**
* Used to recover the heldTokens held as collateral. Is callable after the maximum duration of
* the loan has expired or the loan has been margin-called for the duration of the callTimeLimit
* but remains unclosed. Only callable with the approval of the position lender.
*
* @param positionId Unique ID of the position
* @param recipient Address to send the recovered tokens to
* @return Amount of heldToken recovered
*/
function forceRecoverCollateral(
bytes32 positionId,
address recipient
)
external
nonReentrant
returns (uint256)
{
return ForceRecoverCollateralImpl.forceRecoverCollateralImpl(
state,
positionId,
recipient
);
}
/**
* Deposit additional heldToken as collateral for a position. Cancels margin-call if:
* 0 < position.requiredDeposit < depositAmount. Only callable by the position owner.
*
* @param positionId Unique ID of the position
* @param depositAmount Additional amount in heldToken to deposit
*/
function depositCollateral(
bytes32 positionId,
uint256 depositAmount
)
external
onlyWhileOperational
nonReentrant
{
DepositCollateralImpl.depositCollateralImpl(
state,
positionId,
depositAmount
);
}
/**
* Cancel an amount of a loan offering. Only callable by the loan offering's payer.
*
* @param addresses Array of addresses:
*
* [0] = owedToken
* [1] = heldToken
* [2] = loan payer
* [3] = loan owner
* [4] = loan taker
* [5] = loan position owner
* [6] = loan fee recipient
* [7] = loan lender fee token
* [8] = loan taker fee token
*
* @param values256 Values corresponding to:
*
* [0] = loan maximum amount
* [1] = loan minimum amount
* [2] = loan minimum heldToken
* [3] = loan lender fee
* [4] = loan taker fee
* [5] = loan expiration timestamp (in seconds)
* [6] = loan salt
*
* @param values32 Values corresponding to:
*
* [0] = loan call time limit (in seconds)
* [1] = loan maxDuration (in seconds)
* [2] = loan interest rate (annual nominal percentage times 10**6)
* [3] = loan interest update period (in seconds)
*
* @param cancelAmount Amount to cancel
* @return Amount that was canceled
*/
function cancelLoanOffering(
address[9] addresses,
uint256[7] values256,
uint32[4] values32,
uint256 cancelAmount
)
external
cancelLoanOfferingStateControl
nonReentrant
returns (uint256)
{
return LoanImpl.cancelLoanOfferingImpl(
state,
addresses,
values256,
values32,
cancelAmount
);
}
/**
* Transfer ownership of a loan to a new address. This new address will be entitled to all
* payouts for this loan. Only callable by the lender for a position. If "who" is a contract, it
* must implement the LoanOwner interface.
*
* @param positionId Unique ID of the position
* @param who New owner of the loan
*/
function transferLoan(
bytes32 positionId,
address who
)
external
nonReentrant
{
TransferImpl.transferLoanImpl(
state,
positionId,
who);
}
/**
* Transfer ownership of a position to a new address. This new address will be entitled to all
* payouts. Only callable by the owner of a position. If "who" is a contract, it must implement
* the PositionOwner interface.
*
* @param positionId Unique ID of the position
* @param who New owner of the position
*/
function transferPosition(
bytes32 positionId,
address who
)
external
nonReentrant
{
TransferImpl.transferPositionImpl(
state,
positionId,
who);
}
// ============ Public Constant Functions ============
/**
* Gets the address of the Vault contract that holds and accounts for tokens.
*
* @return The address of the Vault contract
*/
function getVaultAddress()
external
view
returns (address)
{
return state.VAULT;
}
/**
* Gets the address of the TokenProxy contract that accounts must set allowance on in order to
* make loans or open/close positions.
*
* @return The address of the TokenProxy contract
*/
function getTokenProxyAddress()
external
view
returns (address)
{
return state.TOKEN_PROXY;
}
}
// File: contracts/margin/interfaces/OnlyMargin.sol
/**
* @title OnlyMargin
* @author dYdX
*
* Contract to store the address of the main Margin contract and trust only that address to call
* certain functions.
*/
contract OnlyMargin {
// ============ Constants ============
// Address of the known and trusted Margin contract on the blockchain
address public DYDX_MARGIN;
// ============ Constructor ============
constructor(
address margin
)
public
{
DYDX_MARGIN = margin;
}
// ============ Modifiers ============
modifier onlyMargin()
{
require(
msg.sender == DYDX_MARGIN,
"OnlyMargin#onlyMargin: Only Margin can call"
);
_;
}
}
// File: contracts/margin/external/lib/LoanOfferingParser.sol
/**
* @title LoanOfferingParser
* @author dYdX
*
* Contract for LoanOfferingVerifiers to parse arguments
*/
contract LoanOfferingParser {
// ============ Parsing Functions ============
function parseLoanOffering(
address[9] addresses,
uint256[7] values256,
uint32[4] values32,
bytes signature
)
internal
pure
returns (MarginCommon.LoanOffering memory)
{
MarginCommon.LoanOffering memory loanOffering;
fillLoanOfferingAddresses(loanOffering, addresses);
fillLoanOfferingValues256(loanOffering, values256);
fillLoanOfferingValues32(loanOffering, values32);
loanOffering.signature = signature;
return loanOffering;
}
function fillLoanOfferingAddresses(
MarginCommon.LoanOffering memory loanOffering,
address[9] addresses
)
private
pure
{
loanOffering.owedToken = addresses[0];
loanOffering.heldToken = addresses[1];
loanOffering.payer = addresses[2];
loanOffering.owner = addresses[3];
loanOffering.taker = addresses[4];
loanOffering.positionOwner = addresses[5];
loanOffering.feeRecipient = addresses[6];
loanOffering.lenderFeeToken = addresses[7];
loanOffering.takerFeeToken = addresses[8];
}
function fillLoanOfferingValues256(
MarginCommon.LoanOffering memory loanOffering,
uint256[7] values256
)
private
pure
{
loanOffering.rates.maxAmount = values256[0];
loanOffering.rates.minAmount = values256[1];
loanOffering.rates.minHeldToken = values256[2];
loanOffering.rates.lenderFee = values256[3];
loanOffering.rates.takerFee = values256[4];
loanOffering.expirationTimestamp = values256[5];
loanOffering.salt = values256[6];
}
function fillLoanOfferingValues32(
MarginCommon.LoanOffering memory loanOffering,
uint32[4] values32
)
private
pure
{
loanOffering.callTimeLimit = values32[0];
loanOffering.maxDuration = values32[1];
loanOffering.rates.interestRate = values32[2];
loanOffering.rates.interestPeriod = values32[3];
}
}
// File: contracts/margin/external/lib/MarginHelper.sol
/**
* @title MarginHelper
* @author dYdX
*
* This library contains helper functions for interacting with Margin
*/
library MarginHelper {
function getPosition(
address DYDX_MARGIN,
bytes32 positionId
)
internal
view
returns (MarginCommon.Position memory)
{
(
address[4] memory addresses,
uint256[2] memory values256,
uint32[6] memory values32
) = Margin(DYDX_MARGIN).getPosition(positionId);
return MarginCommon.Position({
owedToken: addresses[0],
heldToken: addresses[1],
lender: addresses[2],
owner: addresses[3],
principal: values256[0],
requiredDeposit: values256[1],
callTimeLimit: values32[0],
startTimestamp: values32[1],
callTimestamp: values32[2],
maxDuration: values32[3],
interestRate: values32[4],
interestPeriod: values32[5]
});
}
}
// File: contracts/margin/external/BucketLender/BucketLender.sol
/* solium-disable-next-line max-len*/
/**
* @title BucketLender
* @author dYdX
*
* On-chain shared lender that allows anyone to deposit tokens into this contract to be used to
* lend tokens for a particular margin position.
*
* - Each bucket has three variables:
* - Available Amount
* - The available amount of tokens that the bucket has to lend out
* - Outstanding Principal
* - The amount of principal that the bucket is responsible for in the margin position
* - Weight
* - Used to keep track of each account's weighted ownership within a bucket
* - Relative weight between buckets is meaningless
* - Only accounts' relative weight within a bucket matters
*
* - Token Deposits:
* - Go into a particular bucket, determined by time since the start of the position
* - If the position has not started: bucket = 0
* - If the position has started: bucket = ceiling(time_since_start / BUCKET_TIME)
* - This is always the highest bucket; no higher bucket yet exists
* - Increase the bucket's Available Amount
* - Increase the bucket's weight and the account's weight in that bucket
*
* - Token Withdrawals:
* - Can be from any bucket with available amount
* - Decrease the bucket's Available Amount
* - Decrease the bucket's weight and the account's weight in that bucket
*
* - Increasing the Position (Lending):
* - The lowest buckets with Available Amount are used first
* - Decreases Available Amount
* - Increases Outstanding Principal
*
* - Decreasing the Position (Being Paid-Back)
* - The highest buckets with Outstanding Principal are paid back first
* - Decreases Outstanding Principal
* - Increases Available Amount
*
*
* - Over time, this gives highest interest rates to earlier buckets, but disallows withdrawals from
* those buckets for a longer period of time.
* - Deposits in the same bucket earn the same interest rate.
* - Lenders can withdraw their funds at any time if they are not being lent (and are therefore not
* making the maximum interest).
* - The highest bucket with Outstanding Principal is always less-than-or-equal-to the lowest bucket
with Available Amount
*/
contract BucketLender is
Ownable,
OnlyMargin,
LoanOwner,
IncreaseLoanDelegator,
MarginCallDelegator,
CancelMarginCallDelegator,
ForceRecoverCollateralDelegator,
LoanOfferingParser,
LoanOfferingVerifier,
ReentrancyGuard
{
using SafeMath for uint256;
using TokenInteract for address;
// ============ Events ============
event Deposit(
address indexed beneficiary,
uint256 bucket,
uint256 amount,
uint256 weight
);
event Withdraw(
address indexed withdrawer,
uint256 bucket,
uint256 weight,
uint256 owedTokenWithdrawn,
uint256 heldTokenWithdrawn
);
event PrincipalIncreased(
uint256 principalTotal,
uint256 bucketNumber,
uint256 principalForBucket,
uint256 amount
);
event PrincipalDecreased(
uint256 principalTotal,
uint256 bucketNumber,
uint256 principalForBucket,
uint256 amount
);
event AvailableIncreased(
uint256 availableTotal,
uint256 bucketNumber,
uint256 availableForBucket,
uint256 amount
);
event AvailableDecreased(
uint256 availableTotal,
uint256 bucketNumber,
uint256 availableForBucket,
uint256 amount
);
// ============ State Variables ============
/**
* Available Amount is the amount of tokens that is available to be lent by each bucket.
* These tokens are also available to be withdrawn by the accounts that have weight in the
* bucket.
*/
// Available Amount for each bucket
mapping(uint256 => uint256) public availableForBucket;
// Total Available Amount
uint256 public availableTotal;
/**
* Outstanding Principal is the share of the margin position's principal that each bucket
* is responsible for. That is, each bucket with Outstanding Principal is owed
* (Outstanding Principal)*E^(RT) owedTokens in repayment.
*/
// Outstanding Principal for each bucket
mapping(uint256 => uint256) public principalForBucket;
// Total Outstanding Principal
uint256 public principalTotal;
/**
* Weight determines an account's proportional share of a bucket. Relative weights have no
* meaning if they are not for the same bucket. Likewise, the relative weight of two buckets has
* no meaning. However, the relative weight of two accounts within the same bucket is equal to
* the accounts' shares in the bucket and are therefore proportional to the payout that they
* should expect from withdrawing from that bucket.
*/
// Weight for each account in each bucket
mapping(uint256 => mapping(address => uint256)) public weightForBucketForAccount;
// Total Weight for each bucket
mapping(uint256 => uint256) public weightForBucket;
/**
* The critical bucket is:
* - Greater-than-or-equal-to The highest bucket with Outstanding Principal
* - Less-than-or-equal-to the lowest bucket with Available Amount
*
* It is equal to both of these values in most cases except in an edge cases where the two
* buckets are different. This value is cached to find such a bucket faster than looping through
* all possible buckets.
*/
uint256 public criticalBucket = 0;
/**
* Latest cached value for totalOwedTokenRepaidToLender.
* This number updates on the dYdX Margin base protocol whenever the position is
* partially-closed, but this contract is not notified at that time. Therefore, it is updated
* upon increasing the position or when depositing/withdrawing
*/
uint256 public cachedRepaidAmount = 0;
// True if the position was closed from force-recovering the collateral
bool public wasForceClosed = false;
// ============ Constants ============
// Unique ID of the position
bytes32 public POSITION_ID;
// Address of the token held in the position as collateral
address public HELD_TOKEN;
// Address of the token being lent
address public OWED_TOKEN;
// Time between new buckets
uint32 public BUCKET_TIME;
// Interest rate of the position
uint32 public INTEREST_RATE;
// Interest period of the position
uint32 public INTEREST_PERIOD;
// Maximum duration of the position
uint32 public MAX_DURATION;
// Margin-call time-limit of the position
uint32 public CALL_TIMELIMIT;
// (NUMERATOR/DENOMINATOR) denotes the minimum collateralization ratio of the position
uint32 public MIN_HELD_TOKEN_NUMERATOR;
uint32 public MIN_HELD_TOKEN_DENOMINATOR;
// Accounts that are permitted to margin-call positions (or cancel the margin call)
mapping(address => bool) public TRUSTED_MARGIN_CALLERS;
// Accounts that are permitted to withdraw on behalf of any address
mapping(address => bool) public TRUSTED_WITHDRAWERS;
// ============ Constructor ============
constructor(
address margin,
bytes32 positionId,
address heldToken,
address owedToken,
uint32[7] parameters,
address[] trustedMarginCallers,
address[] trustedWithdrawers
)
public
OnlyMargin(margin)
{
POSITION_ID = positionId;
HELD_TOKEN = heldToken;
OWED_TOKEN = owedToken;
require(
parameters[0] != 0,
"BucketLender#constructor: BUCKET_TIME cannot be zero"
);
BUCKET_TIME = parameters[0];
INTEREST_RATE = parameters[1];
INTEREST_PERIOD = parameters[2];
MAX_DURATION = parameters[3];
CALL_TIMELIMIT = parameters[4];
MIN_HELD_TOKEN_NUMERATOR = parameters[5];
MIN_HELD_TOKEN_DENOMINATOR = parameters[6];
// Initialize TRUSTED_MARGIN_CALLERS and TRUSTED_WITHDRAWERS
uint256 i = 0;
for (i = 0; i < trustedMarginCallers.length; i++) {
TRUSTED_MARGIN_CALLERS[trustedMarginCallers[i]] = true;
}
for (i = 0; i < trustedWithdrawers.length; i++) {
TRUSTED_WITHDRAWERS[trustedWithdrawers[i]] = true;
}
// Set maximum allowance on proxy
OWED_TOKEN.approve(
Margin(margin).getTokenProxyAddress(),
MathHelpers.maxUint256()
);
}
// ============ Modifiers ============
modifier onlyPosition(bytes32 positionId) {
require(
POSITION_ID == positionId,
"BucketLender#onlyPosition: Incorrect position"
);
_;
}
// ============ Margin-Only State-Changing Functions ============
/**
* Function a smart contract must implement to be able to consent to a loan. The loan offering
* will be generated off-chain. The "loan owner" address will own the loan-side of the resulting
* position.
*
* @param addresses Loan offering addresses
* @param values256 Loan offering uint256s
* @param values32 Loan offering uint32s
* @param positionId Unique ID of the position
* @param signature Arbitrary bytes
* @return This address to accept, a different address to ask that contract
*/
function verifyLoanOffering(
address[9] addresses,
uint256[7] values256,
uint32[4] values32,
bytes32 positionId,
bytes signature
)
external
onlyMargin
nonReentrant
onlyPosition(positionId)
returns (address)
{
require(
Margin(DYDX_MARGIN).containsPosition(POSITION_ID),
"BucketLender#verifyLoanOffering: This contract should not open a new position"
);
MarginCommon.LoanOffering memory loanOffering = parseLoanOffering(
addresses,
values256,
values32,
signature
);
// CHECK ADDRESSES
assert(loanOffering.owedToken == OWED_TOKEN);
assert(loanOffering.heldToken == HELD_TOKEN);
assert(loanOffering.payer == address(this));
assert(loanOffering.owner == address(this));
require(
loanOffering.taker == address(0),
"BucketLender#verifyLoanOffering: loanOffering.taker is non-zero"
);
require(
loanOffering.feeRecipient == address(0),
"BucketLender#verifyLoanOffering: loanOffering.feeRecipient is non-zero"
);
require(
loanOffering.positionOwner == address(0),
"BucketLender#verifyLoanOffering: loanOffering.positionOwner is non-zero"
);
require(
loanOffering.lenderFeeToken == address(0),
"BucketLender#verifyLoanOffering: loanOffering.lenderFeeToken is non-zero"
);
require(
loanOffering.takerFeeToken == address(0),
"BucketLender#verifyLoanOffering: loanOffering.takerFeeToken is non-zero"
);
// CHECK VALUES256
require(
loanOffering.rates.maxAmount == MathHelpers.maxUint256(),
"BucketLender#verifyLoanOffering: loanOffering.maxAmount is incorrect"
);
require(
loanOffering.rates.minAmount == 0,
"BucketLender#verifyLoanOffering: loanOffering.minAmount is non-zero"
);
require(
loanOffering.rates.minHeldToken == 0,
"BucketLender#verifyLoanOffering: loanOffering.minHeldToken is non-zero"
);
require(
loanOffering.rates.lenderFee == 0,
"BucketLender#verifyLoanOffering: loanOffering.lenderFee is non-zero"
);
require(
loanOffering.rates.takerFee == 0,
"BucketLender#verifyLoanOffering: loanOffering.takerFee is non-zero"
);
require(
loanOffering.expirationTimestamp == MathHelpers.maxUint256(),
"BucketLender#verifyLoanOffering: expirationTimestamp is incorrect"
);
require(
loanOffering.salt == 0,
"BucketLender#verifyLoanOffering: loanOffering.salt is non-zero"
);
// CHECK VALUES32
require(
loanOffering.callTimeLimit == MathHelpers.maxUint32(),
"BucketLender#verifyLoanOffering: loanOffering.callTimelimit is incorrect"
);
require(
loanOffering.maxDuration == MathHelpers.maxUint32(),
"BucketLender#verifyLoanOffering: loanOffering.maxDuration is incorrect"
);
assert(loanOffering.rates.interestRate == INTEREST_RATE);
assert(loanOffering.rates.interestPeriod == INTEREST_PERIOD);
// no need to require anything about loanOffering.signature
return address(this);
}
/**
* Called by the Margin contract when anyone transfers ownership of a loan to this contract.
* This function initializes this contract and returns this address to indicate to Margin
* that it is willing to take ownership of the loan.
*
* @param from Address of the previous owner
* @param positionId Unique ID of the position
* @return This address on success, throw otherwise
*/
function receiveLoanOwnership(
address from,
bytes32 positionId
)
external
onlyMargin
nonReentrant
onlyPosition(positionId)
returns (address)
{
MarginCommon.Position memory position = MarginHelper.getPosition(DYDX_MARGIN, POSITION_ID);
uint256 initialPrincipal = position.principal;
uint256 minHeldToken = MathHelpers.getPartialAmount(
uint256(MIN_HELD_TOKEN_NUMERATOR),
uint256(MIN_HELD_TOKEN_DENOMINATOR),
initialPrincipal
);
assert(initialPrincipal > 0);
assert(principalTotal == 0);
assert(from != address(this)); // position must be opened without lending from this position
require(
position.owedToken == OWED_TOKEN,
"BucketLender#receiveLoanOwnership: Position owedToken mismatch"
);
require(
position.heldToken == HELD_TOKEN,
"BucketLender#receiveLoanOwnership: Position heldToken mismatch"
);
require(
position.maxDuration == MAX_DURATION,
"BucketLender#receiveLoanOwnership: Position maxDuration mismatch"
);
require(
position.callTimeLimit == CALL_TIMELIMIT,
"BucketLender#receiveLoanOwnership: Position callTimeLimit mismatch"
);
require(
position.interestRate == INTEREST_RATE,
"BucketLender#receiveLoanOwnership: Position interestRate mismatch"
);
require(
position.interestPeriod == INTEREST_PERIOD,
"BucketLender#receiveLoanOwnership: Position interestPeriod mismatch"
);
require(
Margin(DYDX_MARGIN).getPositionBalance(POSITION_ID) >= minHeldToken,
"BucketLender#receiveLoanOwnership: Not enough heldToken as collateral"
);
// set relevant constants
principalForBucket[0] = initialPrincipal;
principalTotal = initialPrincipal;
weightForBucket[0] = weightForBucket[0].add(initialPrincipal);
weightForBucketForAccount[0][from] =
weightForBucketForAccount[0][from].add(initialPrincipal);
return address(this);
}
/**
* Called by Margin when additional value is added onto the position this contract
* is lending for. Balance is added to the address that loaned the additional tokens.
*
* @param payer Address that loaned the additional tokens
* @param positionId Unique ID of the position
* @param principalAdded Amount that was added to the position
* @param lentAmount Amount of owedToken lent
* @return This address to accept, a different address to ask that contract
*/
function increaseLoanOnBehalfOf(
address payer,
bytes32 positionId,
uint256 principalAdded,
uint256 lentAmount
)
external
onlyMargin
nonReentrant
onlyPosition(positionId)
returns (address)
{
Margin margin = Margin(DYDX_MARGIN);
require(
payer == address(this),
"BucketLender#increaseLoanOnBehalfOf: Other lenders cannot lend for this position"
);
require(
!margin.isPositionCalled(POSITION_ID),
"BucketLender#increaseLoanOnBehalfOf: No lending while the position is margin-called"
);
// This function is only called after the state has been updated in the base protocol;
// thus, the principal in the base protocol will equal the principal after the increase
uint256 principalAfterIncrease = margin.getPositionPrincipal(POSITION_ID);
uint256 principalBeforeIncrease = principalAfterIncrease.sub(principalAdded);
// principalTotal was the principal after the previous increase
accountForClose(principalTotal.sub(principalBeforeIncrease));
accountForIncrease(principalAdded, lentAmount);
assert(principalTotal == principalAfterIncrease);
return address(this);
}
/**
* Function a contract must implement in order to let other addresses call marginCall().
*
* @param caller Address of the caller of the marginCall function
* @param positionId Unique ID of the position
* @param depositAmount Amount of heldToken deposit that will be required to cancel the call
* @return This address to accept, a different address to ask that contract
*/
function marginCallOnBehalfOf(
address caller,
bytes32 positionId,
uint256 depositAmount
)
external
onlyMargin
nonReentrant
onlyPosition(positionId)
returns (address)
{
require(
TRUSTED_MARGIN_CALLERS[caller],
"BucketLender#marginCallOnBehalfOf: Margin-caller must be trusted"
);
require(
depositAmount == 0, // prevents depositing from canceling the margin-call
"BucketLender#marginCallOnBehalfOf: Deposit amount must be zero"
);
return address(this);
}
/**
* Function a contract must implement in order to let other addresses call cancelMarginCall().
*
* @param canceler Address of the caller of the cancelMarginCall function
* @param positionId Unique ID of the position
* @return This address to accept, a different address to ask that contract
*/
function cancelMarginCallOnBehalfOf(
address canceler,
bytes32 positionId
)
external
onlyMargin
nonReentrant
onlyPosition(positionId)
returns (address)
{
require(
TRUSTED_MARGIN_CALLERS[canceler],
"BucketLender#cancelMarginCallOnBehalfOf: Margin-call-canceler must be trusted"
);
return address(this);
}
/**
* Function a contract must implement in order to let other addresses call
* forceRecoverCollateral().
*
* param recoverer Address of the caller of the forceRecoverCollateral() function
* @param positionId Unique ID of the position
* @param recipient Address to send the recovered tokens to
* @return This address to accept, a different address to ask that contract
*/
function forceRecoverCollateralOnBehalfOf(
address /* recoverer */,
bytes32 positionId,
address recipient
)
external
onlyMargin
nonReentrant
onlyPosition(positionId)
returns (address)
{
return forceRecoverCollateralInternal(recipient);
}
// ============ Public State-Changing Functions ============
/**
* Allow anyone to recalculate the Outstanding Principal and Available Amount for the buckets if
* part of the position has been closed since the last position increase.
*/
function rebalanceBuckets()
external
nonReentrant
{
rebalanceBucketsInternal();
}
/**
* Allows users to deposit owedToken into this contract. Allowance must be set on this contract
* for "token" in at least the amount "amount".
*
* @param beneficiary The account that will be entitled to this depoit
* @param amount The amount of owedToken to deposit
* @return The bucket number that was deposited into
*/
function deposit(
address beneficiary,
uint256 amount
)
external
nonReentrant
returns (uint256)
{
Margin margin = Margin(DYDX_MARGIN);
bytes32 positionId = POSITION_ID;
require(
beneficiary != address(0),
"BucketLender#deposit: Beneficiary cannot be the zero address"
);
require(
amount != 0,
"BucketLender#deposit: Cannot deposit zero tokens"
);
require(
!margin.isPositionClosed(positionId),
"BucketLender#deposit: Cannot deposit after the position is closed"
);
require(
!margin.isPositionCalled(positionId),
"BucketLender#deposit: Cannot deposit while the position is margin-called"
);
rebalanceBucketsInternal();
OWED_TOKEN.transferFrom(
msg.sender,
address(this),
amount
);
uint256 bucket = getCurrentBucket();
uint256 effectiveAmount = availableForBucket[bucket].add(getBucketOwedAmount(bucket));
uint256 weightToAdd = 0;
if (effectiveAmount == 0) {
weightToAdd = amount; // first deposit in bucket
} else {
weightToAdd = MathHelpers.getPartialAmount(
amount,
effectiveAmount,
weightForBucket[bucket]
);
}
require(
weightToAdd != 0,
"BucketLender#deposit: Cannot deposit for zero weight"
);
// update state
updateAvailable(bucket, amount, true);
weightForBucketForAccount[bucket][beneficiary] =
weightForBucketForAccount[bucket][beneficiary].add(weightToAdd);
weightForBucket[bucket] = weightForBucket[bucket].add(weightToAdd);
emit Deposit(
beneficiary,
bucket,
amount,
weightToAdd
);
return bucket;
}
/**
* Allows users to withdraw their lent funds. An account can withdraw its weighted share of the
* bucket.
*
* While the position is open, a bucket's share is equal to:
* Owed Token: (Available Amount) + (Outstanding Principal) * (1 + interest)
* Held Token: 0
*
* After the position is closed, a bucket's share is equal to:
* Owed Token: (Available Amount)
* Held Token: (Held Token Balance) * (Outstanding Principal) / (Total Outstanding Principal)
*
* @param buckets The bucket numbers to withdraw from
* @param maxWeights The maximum weight to withdraw from each bucket. The amount of tokens
* withdrawn will be at least this amount, but not necessarily more.
* Withdrawing the same weight from different buckets does not necessarily
* return the same amounts from those buckets. In order to withdraw as many
* tokens as possible, use the maximum uint256.
* @param onBehalfOf The address to withdraw on behalf of
* @return 1) The number of owedTokens withdrawn
* 2) The number of heldTokens withdrawn
*/
function withdraw(
uint256[] buckets,
uint256[] maxWeights,
address onBehalfOf
)
external
nonReentrant
returns (uint256, uint256)
{
require(
buckets.length == maxWeights.length,
"BucketLender#withdraw: The lengths of the input arrays must match"
);
if (onBehalfOf != msg.sender) {
require(
TRUSTED_WITHDRAWERS[msg.sender],
"BucketLender#withdraw: Only trusted withdrawers can withdraw on behalf of others"
);
}
rebalanceBucketsInternal();
// decide if some bucket is unable to be withdrawn from (is locked)
// the zero value represents no-lock
uint256 lockedBucket = 0;
if (
Margin(DYDX_MARGIN).containsPosition(POSITION_ID) &&
criticalBucket == getCurrentBucket()
) {
lockedBucket = criticalBucket;
}
uint256[2] memory results; // [0] = totalOwedToken, [1] = totalHeldToken
uint256 maxHeldToken = 0;
if (wasForceClosed) {
maxHeldToken = HELD_TOKEN.balanceOf(address(this));
}
for (uint256 i = 0; i < buckets.length; i++) {
uint256 bucket = buckets[i];
// prevent withdrawing from the current bucket if it is also the critical bucket
if ((bucket != 0) && (bucket == lockedBucket)) {
continue;
}
(uint256 owedTokenForBucket, uint256 heldTokenForBucket) = withdrawSingleBucket(
onBehalfOf,
bucket,
maxWeights[i],
maxHeldToken
);
results[0] = results[0].add(owedTokenForBucket);
results[1] = results[1].add(heldTokenForBucket);
}
// Transfer share of owedToken
OWED_TOKEN.transfer(msg.sender, results[0]);
HELD_TOKEN.transfer(msg.sender, results[1]);
return (results[0], results[1]);
}
/**
* Allows the owner to withdraw any excess tokens sent to the vault by unconventional means,
* including (but not limited-to) token airdrops. Any tokens moved to this contract by calling
* deposit() will be accounted for and will not be withdrawable by this function.
*
* @param token ERC20 token address
* @param to Address to transfer tokens to
* @return Amount of tokens withdrawn
*/
function withdrawExcessToken(
address token,
address to
)
external
onlyOwner
returns (uint256)
{
rebalanceBucketsInternal();
uint256 amount = token.balanceOf(address(this));
if (token == OWED_TOKEN) {
amount = amount.sub(availableTotal);
} else if (token == HELD_TOKEN) {
require(
!wasForceClosed,
"BucketLender#withdrawExcessToken: heldToken cannot be withdrawn if force-closed"
);
}
token.transfer(to, amount);
return amount;
}
// ============ Public Getter Functions ============
/**
* Get the current bucket number that funds will be deposited into. This is also the highest
* bucket so far.
*
* @return The highest bucket and the one that funds will be deposited into
*/
function getCurrentBucket()
public
view
returns (uint256)
{
// load variables from storage;
Margin margin = Margin(DYDX_MARGIN);
bytes32 positionId = POSITION_ID;
uint32 bucketTime = BUCKET_TIME;
assert(!margin.isPositionClosed(positionId));
// if position not created, allow deposits in the first bucket
if (!margin.containsPosition(positionId)) {
return 0;
}
// return the number of BUCKET_TIME periods elapsed since the position start, rounded-up
uint256 startTimestamp = margin.getPositionStartTimestamp(positionId);
return block.timestamp.sub(startTimestamp).div(bucketTime).add(1);
}
/**
* Gets the outstanding amount of owedToken owed to a bucket. This is the principal amount of
* the bucket multiplied by the interest accrued in the position. If the position is closed,
* then any outstanding principal will never be repaid in the form of owedToken.
*
* @param bucket The bucket number
* @return The amount of owedToken that this bucket expects to be paid-back if the posi
*/
function getBucketOwedAmount(
uint256 bucket
)
public
view
returns (uint256)
{
// if the position is completely closed, then the outstanding principal will never be repaid
if (Margin(DYDX_MARGIN).isPositionClosed(POSITION_ID)) {
return 0;
}
uint256 lentPrincipal = principalForBucket[bucket];
// the bucket has no outstanding principal
if (lentPrincipal == 0) {
return 0;
}
// get the total amount of owedToken that would be paid back at this time
uint256 owedAmount = Margin(DYDX_MARGIN).getPositionOwedAmountAtTime(
POSITION_ID,
principalTotal,
uint32(block.timestamp)
);
// return the bucket's share
return MathHelpers.getPartialAmount(
lentPrincipal,
principalTotal,
owedAmount
);
}
// ============ Internal Functions ============
function forceRecoverCollateralInternal(
address recipient
)
internal
returns (address)
{
require(
recipient == address(this),
"BucketLender#forceRecoverCollateralOnBehalfOf: Recipient must be this contract"
);
rebalanceBucketsInternal();
wasForceClosed = true;
return address(this);
}
// ============ Private Helper Functions ============
/**
* Recalculates the Outstanding Principal and Available Amount for the buckets. Only changes the
* state if part of the position has been closed since the last position increase.
*/
function rebalanceBucketsInternal()
private
{
// if force-closed, don't update the outstanding principal values; they are needed to repay
// lenders with heldToken
if (wasForceClosed) {
return;
}
uint256 marginPrincipal = Margin(DYDX_MARGIN).getPositionPrincipal(POSITION_ID);
accountForClose(principalTotal.sub(marginPrincipal));
assert(principalTotal == marginPrincipal);
}
/**
* Updates the state variables at any time. Only does anything after the position has been
* closed or partially-closed since the last time this function was called.
*
* - Increases the available amount in the highest buckets with outstanding principal
* - Decreases the principal amount in those buckets
*
* @param principalRemoved Amount of principal closed since the last update
*/
function accountForClose(
uint256 principalRemoved
)
private
{
if (principalRemoved == 0) {
return;
}
uint256 newRepaidAmount = Margin(DYDX_MARGIN).getTotalOwedTokenRepaidToLender(POSITION_ID);
assert(newRepaidAmount.sub(cachedRepaidAmount) >= principalRemoved);
uint256 principalToSub = principalRemoved;
uint256 availableToAdd = newRepaidAmount.sub(cachedRepaidAmount);
uint256 criticalBucketTemp = criticalBucket;
// loop over buckets in reverse order starting with the critical bucket
for (
uint256 bucket = criticalBucketTemp;
principalToSub > 0;
bucket--
) {
assert(bucket <= criticalBucketTemp); // no underflow on bucket
uint256 principalTemp = Math.min256(principalToSub, principalForBucket[bucket]);
if (principalTemp == 0) {
continue;
}
uint256 availableTemp = MathHelpers.getPartialAmount(
principalTemp,
principalToSub,
availableToAdd
);
updateAvailable(bucket, availableTemp, true);
updatePrincipal(bucket, principalTemp, false);
principalToSub = principalToSub.sub(principalTemp);
availableToAdd = availableToAdd.sub(availableTemp);
criticalBucketTemp = bucket;
}
assert(principalToSub == 0);
assert(availableToAdd == 0);
setCriticalBucket(criticalBucketTemp);
cachedRepaidAmount = newRepaidAmount;
}
/**
* Updates the state variables when a position is increased.
*
* - Decreases the available amount in the lowest buckets with available token
* - Increases the principal amount in those buckets
*
* @param principalAdded Amount of principal added to the position
* @param lentAmount Amount of owedToken lent
*/
function accountForIncrease(
uint256 principalAdded,
uint256 lentAmount
)
private
{
require(
lentAmount <= availableTotal,
"BucketLender#accountForIncrease: No lending not-accounted-for funds"
);
uint256 principalToAdd = principalAdded;
uint256 availableToSub = lentAmount;
uint256 criticalBucketTemp;
// loop over buckets in order starting from the critical bucket
uint256 lastBucket = getCurrentBucket();
for (
uint256 bucket = criticalBucket;
principalToAdd > 0;
bucket++
) {
assert(bucket <= lastBucket); // should never go past the last bucket
uint256 availableTemp = Math.min256(availableToSub, availableForBucket[bucket]);
if (availableTemp == 0) {
continue;
}
uint256 principalTemp = MathHelpers.getPartialAmount(
availableTemp,
availableToSub,
principalToAdd
);
updateAvailable(bucket, availableTemp, false);
updatePrincipal(bucket, principalTemp, true);
principalToAdd = principalToAdd.sub(principalTemp);
availableToSub = availableToSub.sub(availableTemp);
criticalBucketTemp = bucket;
}
assert(principalToAdd == 0);
assert(availableToSub == 0);
setCriticalBucket(criticalBucketTemp);
}
/**
* Withdraw
*
* @param onBehalfOf The account for which to withdraw for
* @param bucket The bucket number to withdraw from
* @param maxWeight The maximum weight to withdraw
* @param maxHeldToken The total amount of heldToken that has been force-recovered
* @return 1) The number of owedTokens withdrawn
* 2) The number of heldTokens withdrawn
*/
function withdrawSingleBucket(
address onBehalfOf,
uint256 bucket,
uint256 maxWeight,
uint256 maxHeldToken
)
private
returns (uint256, uint256)
{
// calculate the user's share
uint256 bucketWeight = weightForBucket[bucket];
if (bucketWeight == 0) {
return (0, 0);
}
uint256 userWeight = weightForBucketForAccount[bucket][onBehalfOf];
uint256 weightToWithdraw = Math.min256(maxWeight, userWeight);
if (weightToWithdraw == 0) {
return (0, 0);
}
// update state
weightForBucket[bucket] = weightForBucket[bucket].sub(weightToWithdraw);
weightForBucketForAccount[bucket][onBehalfOf] = userWeight.sub(weightToWithdraw);
// calculate for owedToken
uint256 owedTokenToWithdraw = withdrawOwedToken(
bucket,
weightToWithdraw,
bucketWeight
);
// calculate for heldToken
uint256 heldTokenToWithdraw = withdrawHeldToken(
bucket,
weightToWithdraw,
bucketWeight,
maxHeldToken
);
emit Withdraw(
onBehalfOf,
bucket,
weightToWithdraw,
owedTokenToWithdraw,
heldTokenToWithdraw
);
return (owedTokenToWithdraw, heldTokenToWithdraw);
}
/**
* Helper function to withdraw earned owedToken from this contract.
*
* @param bucket The bucket number to withdraw from
* @param userWeight The amount of weight the user is using to withdraw
* @param bucketWeight The total weight of the bucket
* @return The amount of owedToken being withdrawn
*/
function withdrawOwedToken(
uint256 bucket,
uint256 userWeight,
uint256 bucketWeight
)
private
returns (uint256)
{
// amount to return for the bucket
uint256 owedTokenToWithdraw = MathHelpers.getPartialAmount(
userWeight,
bucketWeight,
availableForBucket[bucket].add(getBucketOwedAmount(bucket))
);
// check that there is enough token to give back
require(
owedTokenToWithdraw <= availableForBucket[bucket],
"BucketLender#withdrawOwedToken: There must be enough available owedToken"
);
// update amounts
updateAvailable(bucket, owedTokenToWithdraw, false);
return owedTokenToWithdraw;
}
/**
* Helper function to withdraw heldToken from this contract.
*
* @param bucket The bucket number to withdraw from
* @param userWeight The amount of weight the user is using to withdraw
* @param bucketWeight The total weight of the bucket
* @param maxHeldToken The total amount of heldToken available to withdraw
* @return The amount of heldToken being withdrawn
*/
function withdrawHeldToken(
uint256 bucket,
uint256 userWeight,
uint256 bucketWeight,
uint256 maxHeldToken
)
private
returns (uint256)
{
if (maxHeldToken == 0) {
return 0;
}
// user's principal for the bucket
uint256 principalForBucketForAccount = MathHelpers.getPartialAmount(
userWeight,
bucketWeight,
principalForBucket[bucket]
);
uint256 heldTokenToWithdraw = MathHelpers.getPartialAmount(
principalForBucketForAccount,
principalTotal,
maxHeldToken
);
updatePrincipal(bucket, principalForBucketForAccount, false);
return heldTokenToWithdraw;
}
// ============ Setter Functions ============
/**
* Changes the critical bucket variable
*
* @param bucket The value to set criticalBucket to
*/
function setCriticalBucket(
uint256 bucket
)
private
{
// don't spend the gas to sstore unless we need to change the value
if (criticalBucket == bucket) {
return;
}
criticalBucket = bucket;
}
/**
* Changes the available owedToken amount. This changes both the variable to track the total
* amount as well as the variable to track a particular bucket.
*
* @param bucket The bucket number
* @param amount The amount to change the available amount by
* @param increase True if positive change, false if negative change
*/
function updateAvailable(
uint256 bucket,
uint256 amount,
bool increase
)
private
{
if (amount == 0) {
return;
}
uint256 newTotal;
uint256 newForBucket;
if (increase) {
newTotal = availableTotal.add(amount);
newForBucket = availableForBucket[bucket].add(amount);
emit AvailableIncreased(newTotal, bucket, newForBucket, amount); // solium-disable-line
} else {
newTotal = availableTotal.sub(amount);
newForBucket = availableForBucket[bucket].sub(amount);
emit AvailableDecreased(newTotal, bucket, newForBucket, amount); // solium-disable-line
}
availableTotal = newTotal;
availableForBucket[bucket] = newForBucket;
}
/**
* Changes the principal amount. This changes both the variable to track the total
* amount as well as the variable to track a particular bucket.
*
* @param bucket The bucket number
* @param amount The amount to change the principal amount by
* @param increase True if positive change, false if negative change
*/
function updatePrincipal(
uint256 bucket,
uint256 amount,
bool increase
)
private
{
if (amount == 0) {
return;
}
uint256 newTotal;
uint256 newForBucket;
if (increase) {
newTotal = principalTotal.add(amount);
newForBucket = principalForBucket[bucket].add(amount);
emit PrincipalIncreased(newTotal, bucket, newForBucket, amount); // solium-disable-line
} else {
newTotal = principalTotal.sub(amount);
newForBucket = principalForBucket[bucket].sub(amount);
emit PrincipalDecreased(newTotal, bucket, newForBucket, amount); // solium-disable-line
}
principalTotal = newTotal;
principalForBucket[bucket] = newForBucket;
}
}
// File: contracts/lib/AdvancedTokenInteract.sol
/**
* @title AdvancedTokenInteract
* @author dYdX
*
* This library contains advanced functions for interacting with ERC20 tokens
*/
library AdvancedTokenInteract {
using TokenInteract for address;
/**
* Checks if the spender has some amount of allowance. If it doesn't, then set allowance at
* the maximum value.
*
* @param token Address of the ERC20 token
* @param spender Argument of the allowance function
* @param amount The minimum amount of allownce the the spender should be guaranteed
*/
function ensureAllowance(
address token,
address spender,
uint256 amount
)
internal
{
if (token.allowance(address(this), spender) < amount) {
token.approve(spender, MathHelpers.maxUint256());
}
}
}
// File: contracts/margin/external/BucketLender/BucketLenderProxy.sol
/**
* @title BucketLenderProxy
* @author dYdX
*
* TokenProxy for BucketLender contracts
*/
contract BucketLenderProxy
{
using TokenInteract for address;
using AdvancedTokenInteract for address;
// ============ Constants ============
// Address of the WETH token
address public WETH;
// ============ Constructor ============
constructor(
address weth
)
public
{
WETH = weth;
}
// ============ Public Functions ============
/**
* Fallback function. Disallows ETH to be sent to this contract without data except when
* unwrapping WETH.
*/
function ()
external
payable
{
require( // coverage-disable-line
msg.sender == WETH,
"BucketLenderProxy#fallback: Cannot recieve ETH directly unless unwrapping WETH"
);
}
/**
* Send ETH directly to this contract, convert it to WETH, and sent it to a BucketLender
*
* @param bucketLender The address of the BucketLender contract to deposit into
* @return The bucket number that was deposited into
*/
function depositEth(
address bucketLender
)
external
payable
returns (uint256)
{
address weth = WETH;
require(
weth == BucketLender(bucketLender).OWED_TOKEN(),
"BucketLenderProxy#depositEth: BucketLender does not take WETH"
);
WETH9(weth).deposit.value(msg.value)();
return depositInternal(
bucketLender,
weth,
msg.value
);
}
/**
* Deposits tokens from msg.sender into a BucketLender
*
* @param bucketLender The address of the BucketLender contract to deposit into
* @param amount The amount of token to deposit
* @return The bucket number that was deposited into
*/
function deposit(
address bucketLender,
uint256 amount
)
external
returns (uint256)
{
address token = BucketLender(bucketLender).OWED_TOKEN();
token.transferFrom(msg.sender, address(this), amount);
return depositInternal(
bucketLender,
token,
amount
);
}
/**
* Withdraw tokens from a BucketLender
*
* @param bucketLender The address of the BucketLender contract to withdraw from
* @param buckets The buckets to withdraw from
* @param maxWeights The maximum weight to withdraw from each bucket
* @return Values corresponding to:
* [0] = The number of owedTokens withdrawn
* [1] = The number of heldTokens withdrawn
*/
function withdraw(
address bucketLender,
uint256[] buckets,
uint256[] maxWeights
)
external
returns (uint256, uint256)
{
address owedToken = BucketLender(bucketLender).OWED_TOKEN();
address heldToken = BucketLender(bucketLender).HELD_TOKEN();
(
uint256 owedTokenAmount,
uint256 heldTokenAmount
) = BucketLender(bucketLender).withdraw(
buckets,
maxWeights,
msg.sender
);
transferInternal(owedToken, msg.sender, owedTokenAmount);
transferInternal(heldToken, msg.sender, heldTokenAmount);
return (owedTokenAmount, heldTokenAmount);
}
/**
* Reinvest tokens by withdrawing them from one BucketLender and depositing them into another
*
* @param withdrawFrom The address of the BucketLender contract to withdraw from
* @param depositInto The address of the BucketLender contract to deposit into
* @param buckets The buckets to withdraw from
* @param maxWeights The maximum weight to withdraw from each bucket
* @return Values corresponding to:
* [0] = The bucket number that was deposited into
* [1] = The number of owedTokens reinvested
* [2] = The number of heldTokens withdrawn
*/
function rollover(
address withdrawFrom,
address depositInto,
uint256[] buckets,
uint256[] maxWeights
)
external
returns (uint256, uint256, uint256)
{
address owedToken = BucketLender(depositInto).OWED_TOKEN();
// the owedTokens of the two BucketLenders must be the same
require (
owedToken == BucketLender(withdrawFrom).OWED_TOKEN(),
"BucketLenderTokenProxy#rollover: Token mismatch"
);
// withdraw from the first BucketLender
(
uint256 owedTokenAmount,
uint256 heldTokenAmount
) = BucketLender(withdrawFrom).withdraw(
buckets,
maxWeights,
msg.sender
);
// reinvest any owedToken into the second BucketLender
uint256 bucket = depositInternal(
depositInto,
owedToken,
owedTokenAmount
);
// return any heldToken to the msg.sender
address heldToken = BucketLender(withdrawFrom).HELD_TOKEN();
transferInternal(heldToken, msg.sender, heldTokenAmount);
return (bucket, owedTokenAmount, heldTokenAmount);
}
// ============ Private Functions ============
function depositInternal(
address bucketLender,
address token,
uint256 amount
)
private
returns (uint256)
{
token.ensureAllowance(bucketLender, amount);
return BucketLender(bucketLender).deposit(msg.sender, amount);
}
function transferInternal(
address token,
address recipient,
uint256 amount
)
private
{
address weth = WETH;
if (token == weth) {
if (amount != 0) {
WETH9(weth).withdraw(amount);
msg.sender.transfer(amount);
}
} else {
token.transfer(recipient, amount);
}
}
}
|
[{"constant":false,"inputs":[{"name":"bucketLender","type":"address"},{"name":"amount","type":"uint256"}],"name":"deposit","outputs":[{"name":"","type":"uint256"}],"payable":false,"stateMutability":"nonpayable","type":"function"},{"constant":false,"inputs":[{"name":"withdrawFrom","type":"address"},{"name":"depositInto","type":"address"},{"name":"buckets","type":"uint256[]"},{"name":"maxWeights","type":"uint256[]"}],"name":"rollover","outputs":[{"name":"","type":"uint256"},{"name":"","type":"uint256"},{"name":"","type":"uint256"}],"payable":false,"stateMutability":"nonpayable","type":"function"},{"constant":false,"inputs":[{"name":"bucketLender","type":"address"},{"name":"buckets","type":"uint256[]"},{"name":"maxWeights","type":"uint256[]"}],"name":"withdraw","outputs":[{"name":"","type":"uint256"},{"name":"","type":"uint256"}],"payable":false,"stateMutability":"nonpayable","type":"function"},{"constant":true,"inputs":[],"name":"WETH","outputs":[{"name":"","type":"address"}],"payable":false,"stateMutability":"view","type":"function"},{"constant":false,"inputs":[{"name":"bucketLender","type":"address"}],"name":"depositEth","outputs":[{"name":"","type":"uint256"}],"payable":true,"stateMutability":"payable","type":"function"},{"inputs":[{"name":"weth","type":"address"}],"payable":false,"stateMutability":"nonpayable","type":"constructor"},{"payable":true,"stateMutability":"payable","type":"fallback"}]
|
v0.4.24+commit.e67f0147
| true
| 10,000
|
000000000000000000000000c02aaa39b223fe8d0a0e5c4f27ead9083c756cc2
|
Default
| false
|
bzzr://38a5fba27c4b7194a285af585748d0b8a0c81dcde4dcad13651a78da9349e7ab
|
|||
GnosisSafeProxy
|
0x36c75d6f4b411787965769d4c24f838c035364b6
|
Solidity
|
// SPDX-License-Identifier: LGPL-3.0-only
pragma solidity >=0.7.0 <0.9.0;
/// @title IProxy - Helper interface to access masterCopy of the Proxy on-chain
/// @author Richard Meissner - <[email protected]>
interface IProxy {
function masterCopy() external view returns (address);
}
/// @title GnosisSafeProxy - Generic proxy contract allows to execute all transactions applying the code of a master contract.
/// @author Stefan George - <[email protected]>
/// @author Richard Meissner - <[email protected]>
contract GnosisSafeProxy {
// singleton always needs to be first declared variable, to ensure that it is at the same location in the contracts to which calls are delegated.
// To reduce deployment costs this variable is internal and needs to be retrieved via `getStorageAt`
address internal singleton;
/// @dev Constructor function sets address of singleton contract.
/// @param _singleton Singleton address.
constructor(address _singleton) {
require(_singleton != address(0), "Invalid singleton address provided");
singleton = _singleton;
}
/// @dev Fallback function forwards all transactions and returns all received return data.
fallback() external payable {
// solhint-disable-next-line no-inline-assembly
assembly {
let _singleton := and(sload(0), 0xffffffffffffffffffffffffffffffffffffffff)
// 0xa619486e == keccak("masterCopy()"). The value is right padded to 32-bytes with 0s
if eq(calldataload(0), 0xa619486e00000000000000000000000000000000000000000000000000000000) {
mstore(0, _singleton)
return(0, 0x20)
}
calldatacopy(0, 0, calldatasize())
let success := delegatecall(gas(), _singleton, 0, calldatasize(), 0, 0)
returndatacopy(0, 0, returndatasize())
if eq(success, 0) {
revert(0, returndatasize())
}
return(0, returndatasize())
}
}
}
/// @title Proxy Factory - Allows to create new proxy contact and execute a message call to the new proxy within one transaction.
/// @author Stefan George - <[email protected]>
contract GnosisSafeProxyFactory {
event ProxyCreation(GnosisSafeProxy proxy, address singleton);
/// @dev Allows to create new proxy contact and execute a message call to the new proxy within one transaction.
/// @param singleton Address of singleton contract.
/// @param data Payload for message call sent to new proxy contract.
function createProxy(address singleton, bytes memory data) public returns (GnosisSafeProxy proxy) {
proxy = new GnosisSafeProxy(singleton);
if (data.length > 0)
// solhint-disable-next-line no-inline-assembly
assembly {
if eq(call(gas(), proxy, 0, add(data, 0x20), mload(data), 0, 0), 0) {
revert(0, 0)
}
}
emit ProxyCreation(proxy, singleton);
}
/// @dev Allows to retrieve the runtime code of a deployed Proxy. This can be used to check that the expected Proxy was deployed.
function proxyRuntimeCode() public pure returns (bytes memory) {
return type(GnosisSafeProxy).runtimeCode;
}
/// @dev Allows to retrieve the creation code used for the Proxy deployment. With this it is easily possible to calculate predicted address.
function proxyCreationCode() public pure returns (bytes memory) {
return type(GnosisSafeProxy).creationCode;
}
/// @dev Allows to create new proxy contact using CREATE2 but it doesn't run the initializer.
/// This method is only meant as an utility to be called from other methods
/// @param _singleton Address of singleton contract.
/// @param initializer Payload for message call sent to new proxy contract.
/// @param saltNonce Nonce that will be used to generate the salt to calculate the address of the new proxy contract.
function deployProxyWithNonce(
address _singleton,
bytes memory initializer,
uint256 saltNonce
) internal returns (GnosisSafeProxy proxy) {
// If the initializer changes the proxy address should change too. Hashing the initializer data is cheaper than just concatinating it
bytes32 salt = keccak256(abi.encodePacked(keccak256(initializer), saltNonce));
bytes memory deploymentData = abi.encodePacked(type(GnosisSafeProxy).creationCode, uint256(uint160(_singleton)));
// solhint-disable-next-line no-inline-assembly
assembly {
proxy := create2(0x0, add(0x20, deploymentData), mload(deploymentData), salt)
}
require(address(proxy) != address(0), "Create2 call failed");
}
/// @dev Allows to create new proxy contact and execute a message call to the new proxy within one transaction.
/// @param _singleton Address of singleton contract.
/// @param initializer Payload for message call sent to new proxy contract.
/// @param saltNonce Nonce that will be used to generate the salt to calculate the address of the new proxy contract.
function createProxyWithNonce(
address _singleton,
bytes memory initializer,
uint256 saltNonce
) public returns (GnosisSafeProxy proxy) {
proxy = deployProxyWithNonce(_singleton, initializer, saltNonce);
if (initializer.length > 0)
// solhint-disable-next-line no-inline-assembly
assembly {
if eq(call(gas(), proxy, 0, add(initializer, 0x20), mload(initializer), 0, 0), 0) {
revert(0, 0)
}
}
emit ProxyCreation(proxy, _singleton);
}
/// @dev Allows to create new proxy contact, execute a message call to the new proxy and call a specified callback within one transaction
/// @param _singleton Address of singleton contract.
/// @param initializer Payload for message call sent to new proxy contract.
/// @param saltNonce Nonce that will be used to generate the salt to calculate the address of the new proxy contract.
/// @param callback Callback that will be invoced after the new proxy contract has been successfully deployed and initialized.
function createProxyWithCallback(
address _singleton,
bytes memory initializer,
uint256 saltNonce,
IProxyCreationCallback callback
) public returns (GnosisSafeProxy proxy) {
uint256 saltNonceWithCallback = uint256(keccak256(abi.encodePacked(saltNonce, callback)));
proxy = createProxyWithNonce(_singleton, initializer, saltNonceWithCallback);
if (address(callback) != address(0)) callback.proxyCreated(proxy, _singleton, initializer, saltNonce);
}
/// @dev Allows to get the address for a new proxy contact created via `createProxyWithNonce`
/// This method is only meant for address calculation purpose when you use an initializer that would revert,
/// therefore the response is returned with a revert. When calling this method set `from` to the address of the proxy factory.
/// @param _singleton Address of singleton contract.
/// @param initializer Payload for message call sent to new proxy contract.
/// @param saltNonce Nonce that will be used to generate the salt to calculate the address of the new proxy contract.
function calculateCreateProxyWithNonceAddress(
address _singleton,
bytes calldata initializer,
uint256 saltNonce
) external returns (GnosisSafeProxy proxy) {
proxy = deployProxyWithNonce(_singleton, initializer, saltNonce);
revert(string(abi.encodePacked(proxy)));
}
}
interface IProxyCreationCallback {
function proxyCreated(
GnosisSafeProxy proxy,
address _singleton,
bytes calldata initializer,
uint256 saltNonce
) external;
}
|
[{"inputs":[{"internalType":"address","name":"_singleton","type":"address"}],"stateMutability":"nonpayable","type":"constructor"},{"stateMutability":"payable","type":"fallback"}]
|
v0.7.6+commit.7338295f
| false
| 200
|
000000000000000000000000d9Db270c1B5E3Bd161E8c8503c55cEABeE709552
|
Default
|
GNU LGPLv3
| false
|
ipfs://d1429297349653a4918076d650332de1a1068c5f3e07c5c82360c277770b9552
|
||
LockToken
|
0x57cd86bcbf7918855bf715ea6d394b12e8235f94
|
Solidity
|
pragma solidity ^0.4.24;
/**
* @title SafeMath
* @dev Math operations with safety checks that throw on error
*/
library SafeMath {
function mul(uint256 a, uint256 b) internal pure returns (uint256) {
uint256 c = a * b;
assert(a == 0 || c / a == b);
return c;
}
function div(uint256 a, uint256 b) internal pure returns (uint256) {
// assert(b > 0); // Solidity automatically throws when dividing by 0
uint256 c = a / b;
// assert(a == b * c + a % b); // There is no case in which this doesn't hold
return c;
}
function sub(uint256 a, uint256 b) internal pure returns (uint256) {
assert(b <= a);
return a - b;
}
function add(uint256 a, uint256 b) internal pure returns (uint256) {
uint256 c = a + b;
assert(c >= a);
return c;
}
}
contract token {
function balanceOf(address _owner) public constant returns (uint256 balance);
function transfer(address _to, uint256 _value) public returns (bool success);
}
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.
*/
constructor() public{
owner = msg.sender;
}
/**
* @dev Throws if called by any account other than the owner.
*/
modifier onlyOwner() {
require(msg.sender == owner);
_;
}
/**
* @dev Allows the current owner to transfer control of the contract to a newOwner.
* @param newOwner The address to transfer ownership to.
*/
function transferOwnership(address newOwner) onlyOwner public {
require(newOwner != address(0));
emit OwnershipTransferred(owner, newOwner);
owner = newOwner;
}
}
contract LockToken is Ownable {
using SafeMath for uint256;
token token_reward;
address public beneficiary;
bool public isLocked = false;
bool public isReleased = false;
uint256 public start_time;
uint256 public end_time;
event TokenReleased(address beneficiary, uint256 token_amount);
constructor(address tokenContractAddress, address _beneficiary) public{
token_reward = token(tokenContractAddress);
beneficiary = _beneficiary;
}
function tokenBalance() constant public returns (uint256){
return token_reward.balanceOf(this);
}
function lock(uint256 lockTime) public onlyOwner returns (bool){
require(!isLocked);
require(tokenBalance() > 0);
start_time = now;
end_time = lockTime;
isLocked = true;
}
function lockOver() constant public returns (bool){
uint256 current_time = now;
return current_time > end_time;
}
function release() onlyOwner public{
require(isLocked);
require(!isReleased);
require(lockOver());
uint256 token_amount = tokenBalance();
token_reward.transfer( beneficiary, token_amount);
emit TokenReleased(beneficiary, token_amount);
isReleased = true;
}
}
|
[{"constant":true,"inputs":[],"name":"end_time","outputs":[{"name":"","type":"uint256"}],"payable":false,"stateMutability":"view","type":"function"},{"constant":true,"inputs":[],"name":"beneficiary","outputs":[{"name":"","type":"address"}],"payable":false,"stateMutability":"view","type":"function"},{"constant":true,"inputs":[],"name":"start_time","outputs":[{"name":"","type":"uint256"}],"payable":false,"stateMutability":"view","type":"function"},{"constant":false,"inputs":[],"name":"release","outputs":[],"payable":false,"stateMutability":"nonpayable","type":"function"},{"constant":true,"inputs":[],"name":"owner","outputs":[{"name":"","type":"address"}],"payable":false,"stateMutability":"view","type":"function"},{"constant":true,"inputs":[],"name":"lockOver","outputs":[{"name":"","type":"bool"}],"payable":false,"stateMutability":"view","type":"function"},{"constant":true,"inputs":[],"name":"tokenBalance","outputs":[{"name":"","type":"uint256"}],"payable":false,"stateMutability":"view","type":"function"},{"constant":true,"inputs":[],"name":"isLocked","outputs":[{"name":"","type":"bool"}],"payable":false,"stateMutability":"view","type":"function"},{"constant":false,"inputs":[{"name":"lockTime","type":"uint256"}],"name":"lock","outputs":[{"name":"","type":"bool"}],"payable":false,"stateMutability":"nonpayable","type":"function"},{"constant":false,"inputs":[{"name":"newOwner","type":"address"}],"name":"transferOwnership","outputs":[],"payable":false,"stateMutability":"nonpayable","type":"function"},{"constant":true,"inputs":[],"name":"isReleased","outputs":[{"name":"","type":"bool"}],"payable":false,"stateMutability":"view","type":"function"},{"inputs":[{"name":"tokenContractAddress","type":"address"},{"name":"_beneficiary","type":"address"}],"payable":false,"stateMutability":"nonpayable","type":"constructor"},{"anonymous":false,"inputs":[{"indexed":false,"name":"beneficiary","type":"address"},{"indexed":false,"name":"token_amount","type":"uint256"}],"name":"TokenReleased","type":"event"},{"anonymous":false,"inputs":[{"indexed":true,"name":"previousOwner","type":"address"},{"indexed":true,"name":"newOwner","type":"address"}],"name":"OwnershipTransferred","type":"event"}]
|
v0.4.24+commit.e67f0147
| true
| 200
|
000000000000000000000000aa1ae5e57dc05981d83ec7fca0b3c7ee2565b7d6000000000000000000000000aa829ef1cf818b4dd0efabad3315fe8589fe3c49
|
Default
| false
|
bzzr://d4d57bded519fd293c8346659ab8cc581784e4f69b4ee9c5f930a97d08cc0656
|
|||
Forwarder
|
0x7726834e93a6fceaca54836bfc2a430151a94e44
|
Solidity
|
pragma solidity ^0.4.14;
/**
* Contract that exposes the needed erc20 token functions
*/
contract ERC20Interface {
// Send _value amount of tokens to address _to
function transfer(address _to, uint256 _value) returns (bool success);
// Get the account balance of another account with address _owner
function balanceOf(address _owner) constant returns (uint256 balance);
}
/**
* Contract that will forward any incoming Ether to its creator
*/
contract Forwarder {
// Address to which any funds sent to this contract will be forwarded
address public parentAddress;
event ForwarderDeposited(address from, uint value, bytes data);
event TokensFlushed(
address tokenContractAddress, // The contract address of the token
uint value // Amount of token sent
);
/**
* Create the contract, and set the destination address to that of the creator
*/
function Forwarder() {
parentAddress = msg.sender;
}
/**
* Modifier that will execute internal code block only if the sender is a parent of the forwarder contract
*/
modifier onlyParent {
if (msg.sender != parentAddress) {
throw;
}
_;
}
/**
* Default function; Gets called when Ether is deposited, and forwards it to the destination address
*/
function() payable {
if (!parentAddress.call.value(msg.value)(msg.data))
throw;
// Fire off the deposited event if we can forward it
ForwarderDeposited(msg.sender, msg.value, msg.data);
}
/**
* Execute a token transfer of the full balance from the forwarder token to the main wallet contract
* @param tokenContractAddress the address of the erc20 token contract
*/
function flushTokens(address tokenContractAddress) onlyParent {
ERC20Interface instance = ERC20Interface(tokenContractAddress);
var forwarderAddress = address(this);
var forwarderBalance = instance.balanceOf(forwarderAddress);
if (forwarderBalance == 0) {
return;
}
if (!instance.transfer(parentAddress, forwarderBalance)) {
throw;
}
TokensFlushed(tokenContractAddress, forwarderBalance);
}
/**
* It is possible that funds were sent to this address before the contract was deployed.
* We can flush those funds to the destination address.
*/
function flush() {
if (!parentAddress.call.value(this.balance)())
throw;
}
}
/**
* Basic multi-signer wallet designed for use in a co-signing environment where 2 signatures are required to move funds.
* Typically used in a 2-of-3 signing configuration. Uses ecrecover to allow for 2 signatures in a single transaction.
*/
contract WalletSimple {
// Events
event Deposited(address from, uint value, bytes data);
event SafeModeActivated(address msgSender);
event Transacted(
address msgSender, // Address of the sender of the message initiating the transaction
address otherSigner, // Address of the signer (second signature) used to initiate the transaction
bytes32 operation, // Operation hash (sha3 of toAddress, value, data, expireTime, sequenceId)
address toAddress, // The address the transaction was sent to
uint value, // Amount of Wei sent to the address
bytes data // Data sent when invoking the transaction
);
event TokenTransacted(
address msgSender, // Address of the sender of the message initiating the transaction
address otherSigner, // Address of the signer (second signature) used to initiate the transaction
bytes32 operation, // Operation hash (sha3 of toAddress, value, tokenContractAddress, expireTime, sequenceId)
address toAddress, // The address the transaction was sent to
uint value, // Amount of token sent
address tokenContractAddress // The contract address of the token
);
// Public fields
address[] public signers; // The addresses that can co-sign transactions on the wallet
bool public safeMode = false; // When active, wallet may only send to signer addresses
// Internal fields
uint constant SEQUENCE_ID_WINDOW_SIZE = 10;
uint[10] recentSequenceIds;
/**
* Modifier that will execute internal code block only if the sender is an authorized signer on this wallet
*/
modifier onlysigner {
if (!isSigner(msg.sender)) {
throw;
}
_;
}
/**
* Set up a simple multi-sig wallet by specifying the signers allowed to be used on this wallet.
* 2 signers will be required to send a transaction from this wallet.
* Note: The sender is NOT automatically added to the list of signers.
* Signers CANNOT be changed once they are set
*
* @param allowedSigners An array of signers on the wallet
*/
function WalletSimple(address[] allowedSigners) {
if (allowedSigners.length != 3) {
// Invalid number of signers
throw;
}
signers = allowedSigners;
}
/**
* Gets called when a transaction is received without calling a method
*/
function() payable {
if (msg.value > 0) {
// Fire deposited event if we are receiving funds
Deposited(msg.sender, msg.value, msg.data);
}
}
/**
* Create a new contract (and also address) that forwards funds to this contract
* returns address of newly created forwarder address
*/
function createForwarder() onlysigner returns (address) {
return new Forwarder();
}
/**
* Execute a multi-signature transaction from this wallet using 2 signers: one from msg.sender and the other from ecrecover.
* The signature is a signed form (using eth.sign) of tightly packed toAddress, value, data, expireTime and sequenceId
* Sequence IDs are numbers starting from 1. They are used to prevent replay attacks and may not be repeated.
*
* @param toAddress the destination address to send an outgoing transaction
* @param value the amount in Wei to be sent
* @param data the data to send to the toAddress when invoking the transaction
* @param expireTime the number of seconds since 1970 for which this transaction is valid
* @param sequenceId the unique sequence id obtainable from getNextSequenceId
* @param signature the result of eth.sign on the operationHash sha3(toAddress, value, data, expireTime, sequenceId)
*/
function sendMultiSig(address toAddress, uint value, bytes data, uint expireTime, uint sequenceId, bytes signature) onlysigner {
// Verify the other signer
var operationHash = sha3("ETHER", toAddress, value, data, expireTime, sequenceId);
var otherSigner = verifyMultiSig(toAddress, operationHash, signature, expireTime, sequenceId);
// Success, send the transaction
if (!(toAddress.call.value(value)(data))) {
// Failed executing transaction
throw;
}
Transacted(msg.sender, otherSigner, operationHash, toAddress, value, data);
}
/**
* Execute a multi-signature token transfer from this wallet using 2 signers: one from msg.sender and the other from ecrecover.
* The signature is a signed form (using eth.sign) of tightly packed toAddress, value, tokenContractAddress, expireTime and sequenceId
* Sequence IDs are numbers starting from 1. They are used to prevent replay attacks and may not be repeated.
*
* @param toAddress the destination address to send an outgoing transaction
* @param value the amount in tokens to be sent
* @param tokenContractAddress the address of the erc20 token contract
* @param expireTime the number of seconds since 1970 for which this transaction is valid
* @param sequenceId the unique sequence id obtainable from getNextSequenceId
* @param signature the result of eth.sign on the operationHash sha3(toAddress, value, tokenContractAddress, expireTime, sequenceId)
*/
function sendMultiSigToken(address toAddress, uint value, address tokenContractAddress, uint expireTime, uint sequenceId, bytes signature) onlysigner {
// Verify the other signer
var operationHash = sha3("ERC20", toAddress, value, tokenContractAddress, expireTime, sequenceId);
var otherSigner = verifyMultiSig(toAddress, operationHash, signature, expireTime, sequenceId);
ERC20Interface instance = ERC20Interface(tokenContractAddress);
if (!instance.transfer(toAddress, value)) {
throw;
}
TokenTransacted(msg.sender, otherSigner, operationHash, toAddress, value, tokenContractAddress);
}
/**
* Execute a token flush from one of the forwarder addresses. This transfer needs only a single signature and can be done by any signer
*
* @param forwarderAddress the address of the forwarder address to flush the tokens from
* @param tokenContractAddress the address of the erc20 token contract
*/
function flushForwarderTokens(address forwarderAddress, address tokenContractAddress) onlysigner {
Forwarder forwarder = Forwarder(forwarderAddress);
forwarder.flushTokens(tokenContractAddress);
}
/**
* Do common multisig verification for both eth sends and erc20token transfers
*
* @param toAddress the destination address to send an outgoing transaction
* @param operationHash the sha3 of the toAddress, value, data/tokenContractAddress and expireTime
* @param signature the tightly packed signature of r, s, and v as an array of 65 bytes (returned by eth.sign)
* @param expireTime the number of seconds since 1970 for which this transaction is valid
* @param sequenceId the unique sequence id obtainable from getNextSequenceId
* returns address of the address to send tokens or eth to
*/
function verifyMultiSig(address toAddress, bytes32 operationHash, bytes signature, uint expireTime, uint sequenceId) private returns (address) {
var otherSigner = recoverAddressFromSignature(operationHash, signature);
// Verify if we are in safe mode. In safe mode, the wallet can only send to signers
if (safeMode && !isSigner(toAddress)) {
// We are in safe mode and the toAddress is not a signer. Disallow!
throw;
}
// Verify that the transaction has not expired
if (expireTime < block.timestamp) {
// Transaction expired
throw;
}
// Try to insert the sequence ID. Will throw if the sequence id was invalid
tryInsertSequenceId(sequenceId);
if (!isSigner(otherSigner)) {
// Other signer not on this wallet or operation does not match arguments
throw;
}
if (otherSigner == msg.sender) {
// Cannot approve own transaction
throw;
}
return otherSigner;
}
/**
* Irrevocably puts contract into safe mode. When in this mode, transactions may only be sent to signing addresses.
*/
function activateSafeMode() onlysigner {
safeMode = true;
SafeModeActivated(msg.sender);
}
/**
* Determine if an address is a signer on this wallet
* @param signer address to check
* returns boolean indicating whether address is signer or not
*/
function isSigner(address signer) returns (bool) {
// Iterate through all signers on the wallet and
for (uint i = 0; i < signers.length; i++) {
if (signers[i] == signer) {
return true;
}
}
return false;
}
/**
* Gets the second signer's address using ecrecover
* @param operationHash the sha3 of the toAddress, value, data/tokenContractAddress and expireTime
* @param signature the tightly packed signature of r, s, and v as an array of 65 bytes (returned by eth.sign)
* returns address recovered from the signature
*/
function recoverAddressFromSignature(bytes32 operationHash, bytes signature) private returns (address) {
if (signature.length != 65) {
throw;
}
// We need to unpack the signature, which is given as an array of 65 bytes (from eth.sign)
bytes32 r;
bytes32 s;
uint8 v;
assembly {
r := mload(add(signature, 32))
s := mload(add(signature, 64))
v := and(mload(add(signature, 65)), 255)
}
if (v < 27) {
v += 27; // Ethereum versions are 27 or 28 as opposed to 0 or 1 which is submitted by some signing libs
}
return ecrecover(operationHash, v, r, s);
}
/**
* Verify that the sequence id has not been used before and inserts it. Throws if the sequence ID was not accepted.
* We collect a window of up to 10 recent sequence ids, and allow any sequence id that is not in the window and
* greater than the minimum element in the window.
* @param sequenceId to insert into array of stored ids
*/
function tryInsertSequenceId(uint sequenceId) onlysigner private {
// Keep a pointer to the lowest value element in the window
uint lowestValueIndex = 0;
for (uint i = 0; i < SEQUENCE_ID_WINDOW_SIZE; i++) {
if (recentSequenceIds[i] == sequenceId) {
// This sequence ID has been used before. Disallow!
throw;
}
if (recentSequenceIds[i] < recentSequenceIds[lowestValueIndex]) {
lowestValueIndex = i;
}
}
if (sequenceId < recentSequenceIds[lowestValueIndex]) {
// The sequence ID being used is lower than the lowest value in the window
// so we cannot accept it as it may have been used before
throw;
}
if (sequenceId > (recentSequenceIds[lowestValueIndex] + 10000)) {
// Block sequence IDs which are much higher than the lowest value
// This prevents people blocking the contract by using very large sequence IDs quickly
throw;
}
recentSequenceIds[lowestValueIndex] = sequenceId;
}
/**
* Gets the next available sequence ID for signing when using executeAndConfirm
* returns the sequenceId one higher than the highest currently stored
*/
function getNextSequenceId() returns (uint) {
uint highestSequenceId = 0;
for (uint i = 0; i < SEQUENCE_ID_WINDOW_SIZE; i++) {
if (recentSequenceIds[i] > highestSequenceId) {
highestSequenceId = recentSequenceIds[i];
}
}
return highestSequenceId + 1;
}
}
|
[{"constant":true,"inputs":[],"name":"parentAddress","outputs":[{"name":"","type":"address"}],"payable":false,"type":"function"},{"constant":false,"inputs":[{"name":"tokenContractAddress","type":"address"}],"name":"flushTokens","outputs":[],"payable":false,"type":"function"},{"constant":false,"inputs":[],"name":"flush","outputs":[],"payable":false,"type":"function"},{"inputs":[],"payable":false,"type":"constructor"},{"payable":true,"type":"fallback"},{"anonymous":false,"inputs":[{"indexed":false,"name":"from","type":"address"},{"indexed":false,"name":"value","type":"uint256"},{"indexed":false,"name":"data","type":"bytes"}],"name":"ForwarderDeposited","type":"event"},{"anonymous":false,"inputs":[{"indexed":false,"name":"tokenContractAddress","type":"address"},{"indexed":false,"name":"value","type":"uint256"}],"name":"TokensFlushed","type":"event"}]
|
v0.4.16-nightly.2017.8.11+commit.c84de7fa
| true
| 200
|
Default
| false
|
bzzr://d0f8838ba17108a895d34ae8ef3bff4e0dc9d639c3c51921fee1d17eaa803721
|
||||
lockEtherPay
|
0xf81f8bf750fe6c8f1139a6ee32a9013e76f287f6
|
Solidity
|
pragma solidity ^0.4.18;
/**
* @title SafeMath
* @dev Math operations with safety checks that throw on error
*/
library SafeMath {
function mul(uint256 a, uint256 b) internal pure returns (uint256) {
uint256 c = a * b;
assert(a == 0 || c / a == b);
return c;
}
function div(uint256 a, uint256 b) internal pure returns (uint256) {
// assert(b > 0); // Solidity automatically throws when dividing by 0
uint256 c = a / b;
// assert(a == b * c + a % b); // There is no case in which this doesn't hold
return c;
}
function sub(uint256 a, uint256 b) internal pure returns (uint256) {
assert(b <= a);
return a - b;
}
function add(uint256 a, uint256 b) internal pure returns (uint256) {
uint256 c = a + b;
assert(c >= a);
return c;
}
}
contract token {
function balanceOf(address _owner) public constant returns (uint256 balance);
function transfer(address _to, uint256 _value) public returns (bool success);
}
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.
*/
constructor() public{
owner = msg.sender;
}
/**
* @dev Throws if called by any account other than the owner.
*/
modifier onlyOwner() {
require(msg.sender == owner);
_;
}
/**
* @dev Allows the current owner to transfer control of the contract to a newOwner.
* @param newOwner The address to transfer ownership to.
*/
function transferOwnership(address newOwner) onlyOwner public {
require(newOwner != address(0));
emit OwnershipTransferred(owner, newOwner);
owner = newOwner;
}
}
contract lockEtherPay is Ownable {
using SafeMath for uint256;
token token_reward;
address public beneficiary;
bool public isLocked = false;
bool public isReleased = false;
uint256 public start_time;
uint256 public end_time;
uint256 public fifty_two_weeks = 29980800;
event TokenReleased(address beneficiary, uint256 token_amount);
constructor() public{
token_reward = token(0xAa1ae5e57dc05981D83eC7FcA0b3c7ee2565B7D6);
beneficiary = 0x82051C53Ec29B52e3Fc14d8daD03aeAB96C7e3D4;
}
function tokenBalance() constant public returns (uint256){
return token_reward.balanceOf(this);
}
function lock() public onlyOwner returns (bool){
require(!isLocked);
require(tokenBalance() > 0);
start_time = now;
end_time = start_time.add(fifty_two_weeks);
isLocked = true;
}
function lockOver() constant public returns (bool){
uint256 current_time = now;
return current_time > end_time;
}
function release() onlyOwner public{
require(isLocked);
require(!isReleased);
require(lockOver());
uint256 token_amount = tokenBalance();
token_reward.transfer( beneficiary, token_amount);
emit TokenReleased(beneficiary, token_amount);
isReleased = true;
}
}
|
[{"constant":true,"inputs":[],"name":"end_time","outputs":[{"name":"","type":"uint256"}],"payable":false,"stateMutability":"view","type":"function"},{"constant":true,"inputs":[],"name":"beneficiary","outputs":[{"name":"","type":"address"}],"payable":false,"stateMutability":"view","type":"function"},{"constant":true,"inputs":[],"name":"fifty_two_weeks","outputs":[{"name":"","type":"uint256"}],"payable":false,"stateMutability":"view","type":"function"},{"constant":true,"inputs":[],"name":"start_time","outputs":[{"name":"","type":"uint256"}],"payable":false,"stateMutability":"view","type":"function"},{"constant":false,"inputs":[],"name":"release","outputs":[],"payable":false,"stateMutability":"nonpayable","type":"function"},{"constant":true,"inputs":[],"name":"owner","outputs":[{"name":"","type":"address"}],"payable":false,"stateMutability":"view","type":"function"},{"constant":true,"inputs":[],"name":"lockOver","outputs":[{"name":"","type":"bool"}],"payable":false,"stateMutability":"view","type":"function"},{"constant":true,"inputs":[],"name":"tokenBalance","outputs":[{"name":"","type":"uint256"}],"payable":false,"stateMutability":"view","type":"function"},{"constant":true,"inputs":[],"name":"isLocked","outputs":[{"name":"","type":"bool"}],"payable":false,"stateMutability":"view","type":"function"},{"constant":false,"inputs":[{"name":"newOwner","type":"address"}],"name":"transferOwnership","outputs":[],"payable":false,"stateMutability":"nonpayable","type":"function"},{"constant":false,"inputs":[],"name":"lock","outputs":[{"name":"","type":"bool"}],"payable":false,"stateMutability":"nonpayable","type":"function"},{"constant":true,"inputs":[],"name":"isReleased","outputs":[{"name":"","type":"bool"}],"payable":false,"stateMutability":"view","type":"function"},{"inputs":[],"payable":false,"stateMutability":"nonpayable","type":"constructor"},{"anonymous":false,"inputs":[{"indexed":false,"name":"beneficiary","type":"address"},{"indexed":false,"name":"token_amount","type":"uint256"}],"name":"TokenReleased","type":"event"},{"anonymous":false,"inputs":[{"indexed":true,"name":"previousOwner","type":"address"},{"indexed":true,"name":"newOwner","type":"address"}],"name":"OwnershipTransferred","type":"event"}]
|
v0.4.24-nightly.2018.5.10+commit.85d417a8
| true
| 200
|
Default
| false
|
bzzr://07ddfa2137a8a86cfa94065eecfc0d311f3731e6995edc2956f709f737b15120
|
||||
UserWallet
|
0xf5949c84434cd720c4cabe39b6b514856cfab933
|
Solidity
|
pragma solidity ^0.4.10;
// Copyright 2017 Bittrex
contract AbstractSweeper {
function sweep(address token, uint amount) returns (bool);
function () { throw; }
Controller controller;
function AbstractSweeper(address _controller) {
controller = Controller(_controller);
}
modifier canSweep() {
if (msg.sender != controller.authorizedCaller() && msg.sender != controller.owner()) throw;
if (controller.halted()) throw;
_;
}
}
contract Token {
function balanceOf(address a) returns (uint) {
(a);
return 0;
}
function transfer(address a, uint val) returns (bool) {
(a);
(val);
return false;
}
}
contract DefaultSweeper is AbstractSweeper {
function DefaultSweeper(address controller)
AbstractSweeper(controller) {}
function sweep(address _token, uint _amount)
canSweep
returns (bool) {
bool success = false;
address destination = controller.destination();
if (_token != address(0)) {
Token token = Token(_token);
uint amount = _amount;
if (amount > token.balanceOf(this)) {
return false;
}
success = token.transfer(destination, amount);
}
else {
uint amountInWei = _amount;
if (amountInWei > this.balance) {
return false;
}
success = destination.send(amountInWei);
}
if (success) {
controller.logSweep(this, destination, _token, _amount);
}
return success;
}
}
contract UserWallet {
AbstractSweeperList sweeperList;
function UserWallet(address _sweeperlist) {
sweeperList = AbstractSweeperList(_sweeperlist);
}
function () public payable { }
function tokenFallback(address _from, uint _value, bytes _data) {
(_from);
(_value);
(_data);
}
function sweep(address _token, uint _amount)
returns (bool) {
(_amount);
return sweeperList.sweeperOf(_token).delegatecall(msg.data);
}
}
contract AbstractSweeperList {
function sweeperOf(address _token) returns (address);
}
contract Controller is AbstractSweeperList {
address public owner;
address public authorizedCaller;
address public destination;
bool public halted;
event LogNewWallet(address receiver);
event LogSweep(address indexed from, address indexed to, address indexed token, uint amount);
modifier onlyOwner() {
if (msg.sender != owner) throw;
_;
}
modifier onlyAuthorizedCaller() {
if (msg.sender != authorizedCaller) throw;
_;
}
modifier onlyAdmins() {
if (msg.sender != authorizedCaller && msg.sender != owner) throw;
_;
}
function Controller()
{
owner = msg.sender;
destination = msg.sender;
authorizedCaller = msg.sender;
}
function changeAuthorizedCaller(address _newCaller) onlyOwner {
authorizedCaller = _newCaller;
}
function changeDestination(address _dest) onlyOwner {
destination = _dest;
}
function changeOwner(address _owner) onlyOwner {
owner = _owner;
}
function makeWallet() onlyAdmins returns (address wallet) {
wallet = address(new UserWallet(this));
LogNewWallet(wallet);
}
function halt() onlyAdmins {
halted = true;
}
function start() onlyOwner {
halted = false;
}
address public defaultSweeper = address(new DefaultSweeper(this));
mapping (address => address) sweepers;
function addSweeper(address _token, address _sweeper) onlyOwner {
sweepers[_token] = _sweeper;
}
function sweeperOf(address _token) returns (address) {
address sweeper = sweepers[_token];
if (sweeper == 0) sweeper = defaultSweeper;
return sweeper;
}
function logSweep(address from, address to, address token, uint amount) {
LogSweep(from, to, token, amount);
}
}
|
[{"constant":false,"inputs":[{"name":"_token","type":"address"},{"name":"_amount","type":"uint256"}],"name":"sweep","outputs":[{"name":"","type":"bool"}],"payable":false,"type":"function"},{"constant":false,"inputs":[{"name":"_from","type":"address"},{"name":"_value","type":"uint256"},{"name":"_data","type":"bytes"}],"name":"tokenFallback","outputs":[],"payable":false,"type":"function"},{"inputs":[{"name":"_sweeperlist","type":"address"}],"payable":false,"type":"constructor"},{"payable":true,"type":"fallback"}]
|
v0.4.11+commit.68ef5810
| true
| 200
|
000000000000000000000000a3C1E324CA1ce40db73eD6026c4A177F099B5770
|
Default
| false
|
bzzr://4cdd69fdcf3cf6cbee9677fe380fa5f044048aa9e060ec5619a21ca5a5bd4cd1
|
|||
Forwarder
|
0xae566f556f2bcb10f745758beb7d1f9ed20cb723
|
Solidity
|
pragma solidity 0.7.5;
/*
The MIT License (MIT)
Copyright (c) 2018 Murray Software, LLC.
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.
*/
//solhint-disable max-line-length
//solhint-disable no-inline-assembly
contract CloneFactory {
function createClone(address target, bytes32 salt)
internal
returns (address payable result)
{
bytes20 targetBytes = bytes20(target);
assembly {
// load the next free memory slot as a place to store the clone contract data
let clone := mload(0x40)
// The bytecode block below is responsible for contract initialization
// during deployment, it is worth noting the proxied contract constructor will not be called during
// the cloning procedure and that is why an initialization function needs to be called after the
// clone is created
mstore(
clone,
0x3d602d80600a3d3981f3363d3d373d3d3d363d73000000000000000000000000
)
// This stores the address location of the implementation contract
// so that the proxy knows where to delegate call logic to
mstore(add(clone, 0x14), targetBytes)
// The bytecode block is the actual code that is deployed for each clone created.
// It forwards all calls to the already deployed implementation via a delegatecall
mstore(
add(clone, 0x28),
0x5af43d82803e903d91602b57fd5bf30000000000000000000000000000000000
)
// deploy the contract using the CREATE2 opcode
// this deploys the minimal proxy defined above, which will proxy all
// calls to use the logic defined in the implementation contract `target`
result := create2(0, clone, 0x37, salt)
}
}
function isClone(address target, address query)
internal
view
returns (bool result)
{
bytes20 targetBytes = bytes20(target);
assembly {
// load the next free memory slot as a place to store the comparison clone
let clone := mload(0x40)
// The next three lines store the expected bytecode for a miniml proxy
// that targets `target` as its implementation contract
mstore(
clone,
0x363d3d373d3d3d363d7300000000000000000000000000000000000000000000
)
mstore(add(clone, 0xa), targetBytes)
mstore(
add(clone, 0x1e),
0x5af43d82803e903d91602b57fd5bf30000000000000000000000000000000000
)
// the next two lines store the bytecode of the contract that we are checking in memory
let other := add(clone, 0x40)
extcodecopy(query, other, 0, 0x2d)
// Check if the expected bytecode equals the actual bytecode and return the result
result := and(
eq(mload(clone), mload(other)),
eq(mload(add(clone, 0xd)), mload(add(other, 0xd)))
)
}
}
}
/**
* Contract that exposes the needed erc20 token functions
*/
abstract contract ERC20Interface {
// Send _value amount of tokens to address _to
function transfer(address _to, uint256 _value)
public
virtual
returns (bool success);
// Get the account balance of another account with address _owner
function balanceOf(address _owner)
public
virtual
view
returns (uint256 balance);
}
// helper methods for interacting with ERC20 tokens and sending ETH that do not consistently return true/false
library TransferHelper {
function safeApprove(
address token,
address to,
uint256 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::safeApprove: approve failed'
);
}
function safeTransfer(
address token,
address to,
uint256 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::safeTransfer: transfer failed'
);
}
function safeTransferFrom(
address token,
address from,
address to,
uint256 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::transferFrom: transferFrom failed'
);
}
function safeTransferETH(address to, uint256 value) internal {
(bool success, ) = to.call{value: value}(new bytes(0));
require(success, 'TransferHelper::safeTransferETH: ETH transfer failed');
}
}
/**
* Contract that will forward any incoming Ether to the creator of the contract
*
*/
contract Forwarder {
// Address to which any funds sent to this contract will be forwarded
address public parentAddress;
event ForwarderDeposited(address from, uint256 value, bytes data);
/**
* Initialize the contract, and sets the destination address to that of the creator
*/
function init(address _parentAddress) external onlyUninitialized {
parentAddress = _parentAddress;
uint256 value = address(this).balance;
if (value == 0) {
return;
}
(bool success, ) = parentAddress.call{ value: value }('');
require(success, 'Flush failed');
// NOTE: since we are forwarding on initialization,
// we don't have the context of the original sender.
// We still emit an event about the forwarding but set
// the sender to the forwarder itself
emit ForwarderDeposited(address(this), value, msg.data);
}
/**
* Modifier that will execute internal code block only if the sender is the parent address
*/
modifier onlyParent {
require(msg.sender == parentAddress, 'Only Parent');
_;
}
/**
* Modifier that will execute internal code block only if the contract has not been initialized yet
*/
modifier onlyUninitialized {
require(parentAddress == address(0x0), 'Already initialized');
_;
}
/**
* Default function; Gets called when data is sent but does not match any other function
*/
fallback() external payable {
flush();
}
/**
* Default function; Gets called when Ether is deposited with no data, and forwards it to the parent address
*/
receive() external payable {
flush();
}
/**
* Execute a token transfer of the full balance from the forwarder token to the parent address
* @param tokenContractAddress the address of the erc20 token contract
*/
function flushTokens(address tokenContractAddress) external onlyParent {
ERC20Interface instance = ERC20Interface(tokenContractAddress);
address forwarderAddress = address(this);
uint256 forwarderBalance = instance.balanceOf(forwarderAddress);
if (forwarderBalance == 0) {
return;
}
TransferHelper.safeTransfer(
tokenContractAddress,
parentAddress,
forwarderBalance
);
}
/**
* Flush the entire balance of the contract to the parent address.
*/
function flush() public {
uint256 value = address(this).balance;
if (value == 0) {
return;
}
(bool success, ) = parentAddress.call{ value: value }('');
require(success, 'Flush failed');
emit ForwarderDeposited(msg.sender, value, msg.data);
}
}
contract ForwarderFactory is CloneFactory {
address public implementationAddress;
event ForwarderCreated(address newForwarderAddress, address parentAddress);
constructor(address _implementationAddress) {
implementationAddress = _implementationAddress;
}
function createForwarder(address parent, bytes32 salt) external {
// include the signers in the salt so any contract deployed to a given address must have the same signers
bytes32 finalSalt = keccak256(abi.encodePacked(parent, salt));
address payable clone = createClone(implementationAddress, finalSalt);
Forwarder(clone).init(parent);
emit ForwarderCreated(clone, parent);
}
}
|
[{"anonymous":false,"inputs":[{"indexed":false,"internalType":"address","name":"from","type":"address"},{"indexed":false,"internalType":"uint256","name":"value","type":"uint256"},{"indexed":false,"internalType":"bytes","name":"data","type":"bytes"}],"name":"ForwarderDeposited","type":"event"},{"stateMutability":"payable","type":"fallback"},{"inputs":[],"name":"flush","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"address","name":"tokenContractAddress","type":"address"}],"name":"flushTokens","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"address","name":"_parentAddress","type":"address"}],"name":"init","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[],"name":"parentAddress","outputs":[{"internalType":"address","name":"","type":"address"}],"stateMutability":"view","type":"function"},{"stateMutability":"payable","type":"receive"}]
|
v0.7.5+commit.eb77ed08
| false
| 200
|
Default
|
Apache-2.0
| false
|
ipfs://934a7b5f246917d20f5e049b9344e4f3d923110c9d150ea2a4118848dd414bc3
|
|||
UserWallet
|
0x044d035f631ec8f62e3f52908d0c2a743fedf0fa
|
Solidity
|
pragma solidity ^0.4.10;
// Copyright 2017 Bittrex
contract AbstractSweeper {
function sweep(address token, uint amount) returns (bool);
function () { throw; }
Controller controller;
function AbstractSweeper(address _controller) {
controller = Controller(_controller);
}
modifier canSweep() {
if (msg.sender != controller.authorizedCaller() && msg.sender != controller.owner()) throw;
if (controller.halted()) throw;
_;
}
}
contract Token {
function balanceOf(address a) returns (uint) {
(a);
return 0;
}
function transfer(address a, uint val) returns (bool) {
(a);
(val);
return false;
}
}
contract DefaultSweeper is AbstractSweeper {
function DefaultSweeper(address controller)
AbstractSweeper(controller) {}
function sweep(address _token, uint _amount)
canSweep
returns (bool) {
bool success = false;
address destination = controller.destination();
if (_token != address(0)) {
Token token = Token(_token);
uint amount = _amount;
if (amount > token.balanceOf(this)) {
return false;
}
success = token.transfer(destination, amount);
}
else {
uint amountInWei = _amount;
if (amountInWei > this.balance) {
return false;
}
success = destination.send(amountInWei);
}
if (success) {
controller.logSweep(this, destination, _token, _amount);
}
return success;
}
}
contract UserWallet {
AbstractSweeperList sweeperList;
function UserWallet(address _sweeperlist) {
sweeperList = AbstractSweeperList(_sweeperlist);
}
function () public payable { }
function tokenFallback(address _from, uint _value, bytes _data) {
(_from);
(_value);
(_data);
}
function sweep(address _token, uint _amount)
returns (bool) {
(_amount);
return sweeperList.sweeperOf(_token).delegatecall(msg.data);
}
}
contract AbstractSweeperList {
function sweeperOf(address _token) returns (address);
}
contract Controller is AbstractSweeperList {
address public owner;
address public authorizedCaller;
address public destination;
bool public halted;
event LogNewWallet(address receiver);
event LogSweep(address indexed from, address indexed to, address indexed token, uint amount);
modifier onlyOwner() {
if (msg.sender != owner) throw;
_;
}
modifier onlyAuthorizedCaller() {
if (msg.sender != authorizedCaller) throw;
_;
}
modifier onlyAdmins() {
if (msg.sender != authorizedCaller && msg.sender != owner) throw;
_;
}
function Controller()
{
owner = msg.sender;
destination = msg.sender;
authorizedCaller = msg.sender;
}
function changeAuthorizedCaller(address _newCaller) onlyOwner {
authorizedCaller = _newCaller;
}
function changeDestination(address _dest) onlyOwner {
destination = _dest;
}
function changeOwner(address _owner) onlyOwner {
owner = _owner;
}
function makeWallet() onlyAdmins returns (address wallet) {
wallet = address(new UserWallet(this));
LogNewWallet(wallet);
}
function halt() onlyAdmins {
halted = true;
}
function start() onlyOwner {
halted = false;
}
address public defaultSweeper = address(new DefaultSweeper(this));
mapping (address => address) sweepers;
function addSweeper(address _token, address _sweeper) onlyOwner {
sweepers[_token] = _sweeper;
}
function sweeperOf(address _token) returns (address) {
address sweeper = sweepers[_token];
if (sweeper == 0) sweeper = defaultSweeper;
return sweeper;
}
function logSweep(address from, address to, address token, uint amount) {
LogSweep(from, to, token, amount);
}
}
|
[{"constant":false,"inputs":[{"name":"_token","type":"address"},{"name":"_amount","type":"uint256"}],"name":"sweep","outputs":[{"name":"","type":"bool"}],"payable":false,"type":"function"},{"constant":false,"inputs":[{"name":"_from","type":"address"},{"name":"_value","type":"uint256"},{"name":"_data","type":"bytes"}],"name":"tokenFallback","outputs":[],"payable":false,"type":"function"},{"inputs":[{"name":"_sweeperlist","type":"address"}],"payable":false,"type":"constructor"},{"payable":true,"type":"fallback"}]
|
v0.4.11+commit.68ef5810
| true
| 200
|
000000000000000000000000a3C1E324CA1ce40db73eD6026c4A177F099B5770
|
Default
| false
|
bzzr://4cdd69fdcf3cf6cbee9677fe380fa5f044048aa9e060ec5619a21ca5a5bd4cd1
|
|||
UserWallet
|
0x21d95517ac3fdeb77d96b2f5f2d12d5e88c44544
|
Solidity
|
pragma solidity ^0.4.10;
// Copyright 2017 Bittrex
contract AbstractSweeper {
function sweep(address token, uint amount) returns (bool);
function () { throw; }
Controller controller;
function AbstractSweeper(address _controller) {
controller = Controller(_controller);
}
modifier canSweep() {
if (msg.sender != controller.authorizedCaller() && msg.sender != controller.owner()) throw;
if (controller.halted()) throw;
_;
}
}
contract Token {
function balanceOf(address a) returns (uint) {
(a);
return 0;
}
function transfer(address a, uint val) returns (bool) {
(a);
(val);
return false;
}
}
contract DefaultSweeper is AbstractSweeper {
function DefaultSweeper(address controller)
AbstractSweeper(controller) {}
function sweep(address _token, uint _amount)
canSweep
returns (bool) {
bool success = false;
address destination = controller.destination();
if (_token != address(0)) {
Token token = Token(_token);
uint amount = _amount;
if (amount > token.balanceOf(this)) {
return false;
}
success = token.transfer(destination, amount);
}
else {
uint amountInWei = _amount;
if (amountInWei > this.balance) {
return false;
}
success = destination.send(amountInWei);
}
if (success) {
controller.logSweep(this, destination, _token, _amount);
}
return success;
}
}
contract UserWallet {
AbstractSweeperList sweeperList;
function UserWallet(address _sweeperlist) {
sweeperList = AbstractSweeperList(_sweeperlist);
}
function () public payable { }
function tokenFallback(address _from, uint _value, bytes _data) {
(_from);
(_value);
(_data);
}
function sweep(address _token, uint _amount)
returns (bool) {
(_amount);
return sweeperList.sweeperOf(_token).delegatecall(msg.data);
}
}
contract AbstractSweeperList {
function sweeperOf(address _token) returns (address);
}
contract Controller is AbstractSweeperList {
address public owner;
address public authorizedCaller;
address public destination;
bool public halted;
event LogNewWallet(address receiver);
event LogSweep(address indexed from, address indexed to, address indexed token, uint amount);
modifier onlyOwner() {
if (msg.sender != owner) throw;
_;
}
modifier onlyAuthorizedCaller() {
if (msg.sender != authorizedCaller) throw;
_;
}
modifier onlyAdmins() {
if (msg.sender != authorizedCaller && msg.sender != owner) throw;
_;
}
function Controller()
{
owner = msg.sender;
destination = msg.sender;
authorizedCaller = msg.sender;
}
function changeAuthorizedCaller(address _newCaller) onlyOwner {
authorizedCaller = _newCaller;
}
function changeDestination(address _dest) onlyOwner {
destination = _dest;
}
function changeOwner(address _owner) onlyOwner {
owner = _owner;
}
function makeWallet() onlyAdmins returns (address wallet) {
wallet = address(new UserWallet(this));
LogNewWallet(wallet);
}
function halt() onlyAdmins {
halted = true;
}
function start() onlyOwner {
halted = false;
}
address public defaultSweeper = address(new DefaultSweeper(this));
mapping (address => address) sweepers;
function addSweeper(address _token, address _sweeper) onlyOwner {
sweepers[_token] = _sweeper;
}
function sweeperOf(address _token) returns (address) {
address sweeper = sweepers[_token];
if (sweeper == 0) sweeper = defaultSweeper;
return sweeper;
}
function logSweep(address from, address to, address token, uint amount) {
LogSweep(from, to, token, amount);
}
}
|
[{"constant":false,"inputs":[{"name":"_token","type":"address"},{"name":"_amount","type":"uint256"}],"name":"sweep","outputs":[{"name":"","type":"bool"}],"payable":false,"type":"function"},{"constant":false,"inputs":[{"name":"_from","type":"address"},{"name":"_value","type":"uint256"},{"name":"_data","type":"bytes"}],"name":"tokenFallback","outputs":[],"payable":false,"type":"function"},{"inputs":[{"name":"_sweeperlist","type":"address"}],"payable":false,"type":"constructor"},{"payable":true,"type":"fallback"}]
|
v0.4.11+commit.68ef5810
| true
| 200
|
000000000000000000000000a3C1E324CA1ce40db73eD6026c4A177F099B5770
|
Default
| false
|
bzzr://4cdd69fdcf3cf6cbee9677fe380fa5f044048aa9e060ec5619a21ca5a5bd4cd1
|
|||
InstaAccount
|
0x656766514daf51927f7218362ae2a6fe6464d1a6
|
Solidity
|
pragma solidity ^0.6.0;
pragma experimental ABIEncoderV2;
/**
* @title InstaAccount.
* @dev DeFi Smart Account Wallet.
*/
interface IndexInterface {
function connectors(uint version) external view returns (address);
function check(uint version) external view returns (address);
function list() external view returns (address);
}
interface ConnectorsInterface {
function isConnector(address[] calldata logicAddr) external view returns (bool);
function isStaticConnector(address[] calldata logicAddr) external view returns (bool);
}
interface CheckInterface {
function isOk() external view returns (bool);
}
interface ListInterface {
function addAuth(address user) external;
function removeAuth(address user) external;
}
contract Record {
event LogEnable(address indexed user);
event LogDisable(address indexed user);
event LogSwitchShield(bool _shield);
// InstaIndex Address.
address public constant instaIndex = 0x2971AdFa57b20E5a416aE5a708A8655A9c74f723;
// The Account Module Version.
uint public constant version = 1;
// Auth Module(Address of Auth => bool).
mapping (address => bool) private auth;
// Is shield true/false.
bool public shield;
/**
* @dev Check for Auth if enabled.
* @param user address/user/owner.
*/
function isAuth(address user) public view returns (bool) {
return auth[user];
}
/**
* @dev Change Shield State.
*/
function switchShield(bool _shield) external {
require(auth[msg.sender], "not-self");
require(shield != _shield, "shield is set");
shield = _shield;
emit LogSwitchShield(shield);
}
/**
* @dev Enable New User.
* @param user Owner of the Smart Account.
*/
function enable(address user) public {
require(msg.sender == address(this) || msg.sender == instaIndex, "not-self-index");
require(user != address(0), "not-valid");
require(!auth[user], "already-enabled");
auth[user] = true;
ListInterface(IndexInterface(instaIndex).list()).addAuth(user);
emit LogEnable(user);
}
/**
* @dev Disable User.
* @param user Owner of the Smart Account.
*/
function disable(address user) public {
require(msg.sender == address(this), "not-self");
require(user != address(0), "not-valid");
require(auth[user], "already-disabled");
delete auth[user];
ListInterface(IndexInterface(instaIndex).list()).removeAuth(user);
emit LogDisable(user);
}
}
contract InstaAccount is Record {
event LogCast(address indexed origin, address indexed sender, uint value);
receive() external payable {}
/**
* @dev Delegate the calls to Connector And this function is ran by cast().
* @param _target Target to of Connector.
* @param _data CallData of function in Connector.
*/
function spell(address _target, bytes memory _data) internal {
require(_target != address(0), "target-invalid");
assembly {
let succeeded := delegatecall(gas(), _target, add(_data, 0x20), mload(_data), 0, 0)
switch iszero(succeeded)
case 1 {
// throw if delegatecall failed
let size := returndatasize()
returndatacopy(0x00, 0x00, size)
revert(0x00, size)
}
}
}
/**
* @dev This is the main function, Where all the different functions are called
* from Smart Account.
* @param _targets Array of Target(s) to of Connector.
* @param _datas Array of Calldata(S) of function.
*/
function cast(
address[] calldata _targets,
bytes[] calldata _datas,
address _origin
)
external
payable
{
require(isAuth(msg.sender) || msg.sender == instaIndex, "permission-denied");
require(_targets.length == _datas.length , "array-length-invalid");
IndexInterface indexContract = IndexInterface(instaIndex);
bool isShield = shield;
if (!isShield) {
require(ConnectorsInterface(indexContract.connectors(version)).isConnector(_targets), "not-connector");
} else {
require(ConnectorsInterface(indexContract.connectors(version)).isStaticConnector(_targets), "not-static-connector");
}
for (uint i = 0; i < _targets.length; i++) {
spell(_targets[i], _datas[i]);
}
address _check = indexContract.check(version);
if (_check != address(0) && !isShield) require(CheckInterface(_check).isOk(), "not-ok");
emit LogCast(_origin, msg.sender, msg.value);
}
}
|
[{"anonymous":false,"inputs":[{"indexed":true,"internalType":"address","name":"origin","type":"address"},{"indexed":true,"internalType":"address","name":"sender","type":"address"},{"indexed":false,"internalType":"uint256","name":"value","type":"uint256"}],"name":"LogCast","type":"event"},{"anonymous":false,"inputs":[{"indexed":true,"internalType":"address","name":"user","type":"address"}],"name":"LogDisable","type":"event"},{"anonymous":false,"inputs":[{"indexed":true,"internalType":"address","name":"user","type":"address"}],"name":"LogEnable","type":"event"},{"anonymous":false,"inputs":[{"indexed":false,"internalType":"bool","name":"_shield","type":"bool"}],"name":"LogSwitchShield","type":"event"},{"inputs":[{"internalType":"address[]","name":"_targets","type":"address[]"},{"internalType":"bytes[]","name":"_datas","type":"bytes[]"},{"internalType":"address","name":"_origin","type":"address"}],"name":"cast","outputs":[],"stateMutability":"payable","type":"function"},{"inputs":[{"internalType":"address","name":"user","type":"address"}],"name":"disable","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"address","name":"user","type":"address"}],"name":"enable","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[],"name":"instaIndex","outputs":[{"internalType":"address","name":"","type":"address"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"address","name":"user","type":"address"}],"name":"isAuth","outputs":[{"internalType":"bool","name":"","type":"bool"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"shield","outputs":[{"internalType":"bool","name":"","type":"bool"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"bool","name":"_shield","type":"bool"}],"name":"switchShield","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[],"name":"version","outputs":[{"internalType":"uint256","name":"","type":"uint256"}],"stateMutability":"view","type":"function"},{"stateMutability":"payable","type":"receive"}]
|
v0.6.0+commit.26b70077
| false
| 200
|
Default
|
MIT
| false
|
ipfs://c7356d76ef680ea6649af388d2a518797700466c0a8ed7e5356ec7932509c8e8
|
|||
Forwarder
|
0xc6f1d4740918983df297ba7d1b6c9677c73351d1
|
Solidity
|
pragma solidity ^0.4.14;
/**
* Contract that exposes the needed erc20 token functions
*/
contract ERC20Interface {
// Send _value amount of tokens to address _to
function transfer(address _to, uint256 _value) returns (bool success);
// Get the account balance of another account with address _owner
function balanceOf(address _owner) constant returns (uint256 balance);
}
/**
* Contract that will forward any incoming Ether to its creator
*/
contract Forwarder {
// Address to which any funds sent to this contract will be forwarded
address public parentAddress;
event ForwarderDeposited(address from, uint value, bytes data);
event TokensFlushed(
address tokenContractAddress, // The contract address of the token
uint value // Amount of token sent
);
/**
* Create the contract, and set the destination address to that of the creator
*/
function Forwarder() {
parentAddress = msg.sender;
}
/**
* Modifier that will execute internal code block only if the sender is a parent of the forwarder contract
*/
modifier onlyParent {
if (msg.sender != parentAddress) {
throw;
}
_;
}
/**
* Default function; Gets called when Ether is deposited, and forwards it to the destination address
*/
function() payable {
if (!parentAddress.call.value(msg.value)(msg.data))
throw;
// Fire off the deposited event if we can forward it
ForwarderDeposited(msg.sender, msg.value, msg.data);
}
/**
* Execute a token transfer of the full balance from the forwarder token to the main wallet contract
* @param tokenContractAddress the address of the erc20 token contract
*/
function flushTokens(address tokenContractAddress) onlyParent {
ERC20Interface instance = ERC20Interface(tokenContractAddress);
var forwarderAddress = address(this);
var forwarderBalance = instance.balanceOf(forwarderAddress);
if (forwarderBalance == 0) {
return;
}
if (!instance.transfer(parentAddress, forwarderBalance)) {
throw;
}
TokensFlushed(tokenContractAddress, forwarderBalance);
}
/**
* It is possible that funds were sent to this address before the contract was deployed.
* We can flush those funds to the destination address.
*/
function flush() {
if (!parentAddress.call.value(this.balance)())
throw;
}
}
/**
* Basic multi-signer wallet designed for use in a co-signing environment where 2 signatures are required to move funds.
* Typically used in a 2-of-3 signing configuration. Uses ecrecover to allow for 2 signatures in a single transaction.
*/
contract WalletSimple {
// Events
event Deposited(address from, uint value, bytes data);
event SafeModeActivated(address msgSender);
event Transacted(
address msgSender, // Address of the sender of the message initiating the transaction
address otherSigner, // Address of the signer (second signature) used to initiate the transaction
bytes32 operation, // Operation hash (sha3 of toAddress, value, data, expireTime, sequenceId)
address toAddress, // The address the transaction was sent to
uint value, // Amount of Wei sent to the address
bytes data // Data sent when invoking the transaction
);
event TokenTransacted(
address msgSender, // Address of the sender of the message initiating the transaction
address otherSigner, // Address of the signer (second signature) used to initiate the transaction
bytes32 operation, // Operation hash (sha3 of toAddress, value, tokenContractAddress, expireTime, sequenceId)
address toAddress, // The address the transaction was sent to
uint value, // Amount of token sent
address tokenContractAddress // The contract address of the token
);
// Public fields
address[] public signers; // The addresses that can co-sign transactions on the wallet
bool public safeMode = false; // When active, wallet may only send to signer addresses
// Internal fields
uint constant SEQUENCE_ID_WINDOW_SIZE = 10;
uint[10] recentSequenceIds;
/**
* Modifier that will execute internal code block only if the sender is an authorized signer on this wallet
*/
modifier onlysigner {
if (!isSigner(msg.sender)) {
throw;
}
_;
}
/**
* Set up a simple multi-sig wallet by specifying the signers allowed to be used on this wallet.
* 2 signers will be required to send a transaction from this wallet.
* Note: The sender is NOT automatically added to the list of signers.
* Signers CANNOT be changed once they are set
*
* @param allowedSigners An array of signers on the wallet
*/
function WalletSimple(address[] allowedSigners) {
if (allowedSigners.length != 3) {
// Invalid number of signers
throw;
}
signers = allowedSigners;
}
/**
* Gets called when a transaction is received without calling a method
*/
function() payable {
if (msg.value > 0) {
// Fire deposited event if we are receiving funds
Deposited(msg.sender, msg.value, msg.data);
}
}
/**
* Create a new contract (and also address) that forwards funds to this contract
* returns address of newly created forwarder address
*/
function createForwarder() onlysigner returns (address) {
return new Forwarder();
}
/**
* Execute a multi-signature transaction from this wallet using 2 signers: one from msg.sender and the other from ecrecover.
* The signature is a signed form (using eth.sign) of tightly packed toAddress, value, data, expireTime and sequenceId
* Sequence IDs are numbers starting from 1. They are used to prevent replay attacks and may not be repeated.
*
* @param toAddress the destination address to send an outgoing transaction
* @param value the amount in Wei to be sent
* @param data the data to send to the toAddress when invoking the transaction
* @param expireTime the number of seconds since 1970 for which this transaction is valid
* @param sequenceId the unique sequence id obtainable from getNextSequenceId
* @param signature the result of eth.sign on the operationHash sha3(toAddress, value, data, expireTime, sequenceId)
*/
function sendMultiSig(address toAddress, uint value, bytes data, uint expireTime, uint sequenceId, bytes signature) onlysigner {
// Verify the other signer
var operationHash = sha3("ETHER", toAddress, value, data, expireTime, sequenceId);
var otherSigner = verifyMultiSig(toAddress, operationHash, signature, expireTime, sequenceId);
// Success, send the transaction
if (!(toAddress.call.value(value)(data))) {
// Failed executing transaction
throw;
}
Transacted(msg.sender, otherSigner, operationHash, toAddress, value, data);
}
/**
* Execute a multi-signature token transfer from this wallet using 2 signers: one from msg.sender and the other from ecrecover.
* The signature is a signed form (using eth.sign) of tightly packed toAddress, value, tokenContractAddress, expireTime and sequenceId
* Sequence IDs are numbers starting from 1. They are used to prevent replay attacks and may not be repeated.
*
* @param toAddress the destination address to send an outgoing transaction
* @param value the amount in tokens to be sent
* @param tokenContractAddress the address of the erc20 token contract
* @param expireTime the number of seconds since 1970 for which this transaction is valid
* @param sequenceId the unique sequence id obtainable from getNextSequenceId
* @param signature the result of eth.sign on the operationHash sha3(toAddress, value, tokenContractAddress, expireTime, sequenceId)
*/
function sendMultiSigToken(address toAddress, uint value, address tokenContractAddress, uint expireTime, uint sequenceId, bytes signature) onlysigner {
// Verify the other signer
var operationHash = sha3("ERC20", toAddress, value, tokenContractAddress, expireTime, sequenceId);
var otherSigner = verifyMultiSig(toAddress, operationHash, signature, expireTime, sequenceId);
ERC20Interface instance = ERC20Interface(tokenContractAddress);
if (!instance.transfer(toAddress, value)) {
throw;
}
TokenTransacted(msg.sender, otherSigner, operationHash, toAddress, value, tokenContractAddress);
}
/**
* Execute a token flush from one of the forwarder addresses. This transfer needs only a single signature and can be done by any signer
*
* @param forwarderAddress the address of the forwarder address to flush the tokens from
* @param tokenContractAddress the address of the erc20 token contract
*/
function flushForwarderTokens(address forwarderAddress, address tokenContractAddress) onlysigner {
Forwarder forwarder = Forwarder(forwarderAddress);
forwarder.flushTokens(tokenContractAddress);
}
/**
* Do common multisig verification for both eth sends and erc20token transfers
*
* @param toAddress the destination address to send an outgoing transaction
* @param operationHash the sha3 of the toAddress, value, data/tokenContractAddress and expireTime
* @param signature the tightly packed signature of r, s, and v as an array of 65 bytes (returned by eth.sign)
* @param expireTime the number of seconds since 1970 for which this transaction is valid
* @param sequenceId the unique sequence id obtainable from getNextSequenceId
* returns address of the address to send tokens or eth to
*/
function verifyMultiSig(address toAddress, bytes32 operationHash, bytes signature, uint expireTime, uint sequenceId) private returns (address) {
var otherSigner = recoverAddressFromSignature(operationHash, signature);
// Verify if we are in safe mode. In safe mode, the wallet can only send to signers
if (safeMode && !isSigner(toAddress)) {
// We are in safe mode and the toAddress is not a signer. Disallow!
throw;
}
// Verify that the transaction has not expired
if (expireTime < block.timestamp) {
// Transaction expired
throw;
}
// Try to insert the sequence ID. Will throw if the sequence id was invalid
tryInsertSequenceId(sequenceId);
if (!isSigner(otherSigner)) {
// Other signer not on this wallet or operation does not match arguments
throw;
}
if (otherSigner == msg.sender) {
// Cannot approve own transaction
throw;
}
return otherSigner;
}
/**
* Irrevocably puts contract into safe mode. When in this mode, transactions may only be sent to signing addresses.
*/
function activateSafeMode() onlysigner {
safeMode = true;
SafeModeActivated(msg.sender);
}
/**
* Determine if an address is a signer on this wallet
* @param signer address to check
* returns boolean indicating whether address is signer or not
*/
function isSigner(address signer) returns (bool) {
// Iterate through all signers on the wallet and
for (uint i = 0; i < signers.length; i++) {
if (signers[i] == signer) {
return true;
}
}
return false;
}
/**
* Gets the second signer's address using ecrecover
* @param operationHash the sha3 of the toAddress, value, data/tokenContractAddress and expireTime
* @param signature the tightly packed signature of r, s, and v as an array of 65 bytes (returned by eth.sign)
* returns address recovered from the signature
*/
function recoverAddressFromSignature(bytes32 operationHash, bytes signature) private returns (address) {
if (signature.length != 65) {
throw;
}
// We need to unpack the signature, which is given as an array of 65 bytes (from eth.sign)
bytes32 r;
bytes32 s;
uint8 v;
assembly {
r := mload(add(signature, 32))
s := mload(add(signature, 64))
v := and(mload(add(signature, 65)), 255)
}
if (v < 27) {
v += 27; // Ethereum versions are 27 or 28 as opposed to 0 or 1 which is submitted by some signing libs
}
return ecrecover(operationHash, v, r, s);
}
/**
* Verify that the sequence id has not been used before and inserts it. Throws if the sequence ID was not accepted.
* We collect a window of up to 10 recent sequence ids, and allow any sequence id that is not in the window and
* greater than the minimum element in the window.
* @param sequenceId to insert into array of stored ids
*/
function tryInsertSequenceId(uint sequenceId) onlysigner private {
// Keep a pointer to the lowest value element in the window
uint lowestValueIndex = 0;
for (uint i = 0; i < SEQUENCE_ID_WINDOW_SIZE; i++) {
if (recentSequenceIds[i] == sequenceId) {
// This sequence ID has been used before. Disallow!
throw;
}
if (recentSequenceIds[i] < recentSequenceIds[lowestValueIndex]) {
lowestValueIndex = i;
}
}
if (sequenceId < recentSequenceIds[lowestValueIndex]) {
// The sequence ID being used is lower than the lowest value in the window
// so we cannot accept it as it may have been used before
throw;
}
if (sequenceId > (recentSequenceIds[lowestValueIndex] + 10000)) {
// Block sequence IDs which are much higher than the lowest value
// This prevents people blocking the contract by using very large sequence IDs quickly
throw;
}
recentSequenceIds[lowestValueIndex] = sequenceId;
}
/**
* Gets the next available sequence ID for signing when using executeAndConfirm
* returns the sequenceId one higher than the highest currently stored
*/
function getNextSequenceId() returns (uint) {
uint highestSequenceId = 0;
for (uint i = 0; i < SEQUENCE_ID_WINDOW_SIZE; i++) {
if (recentSequenceIds[i] > highestSequenceId) {
highestSequenceId = recentSequenceIds[i];
}
}
return highestSequenceId + 1;
}
}
|
[{"constant":true,"inputs":[],"name":"parentAddress","outputs":[{"name":"","type":"address"}],"payable":false,"type":"function"},{"constant":false,"inputs":[{"name":"tokenContractAddress","type":"address"}],"name":"flushTokens","outputs":[],"payable":false,"type":"function"},{"constant":false,"inputs":[],"name":"flush","outputs":[],"payable":false,"type":"function"},{"inputs":[],"payable":false,"type":"constructor"},{"payable":true,"type":"fallback"},{"anonymous":false,"inputs":[{"indexed":false,"name":"from","type":"address"},{"indexed":false,"name":"value","type":"uint256"},{"indexed":false,"name":"data","type":"bytes"}],"name":"ForwarderDeposited","type":"event"},{"anonymous":false,"inputs":[{"indexed":false,"name":"tokenContractAddress","type":"address"},{"indexed":false,"name":"value","type":"uint256"}],"name":"TokensFlushed","type":"event"}]
|
v0.4.16-nightly.2017.8.11+commit.c84de7fa
| true
| 200
|
Default
| false
|
bzzr://d0f8838ba17108a895d34ae8ef3bff4e0dc9d639c3c51921fee1d17eaa803721
|
||||
ERC1967Proxy
|
0xa9fd280e65f3519da4aa0ace95ad0d6f867f9533
|
Solidity
|
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
/**
* @dev This abstract contract provides a fallback function that delegates all calls to another contract using the EVM
* instruction `delegatecall`. We refer to the second contract as the _implementation_ behind the proxy, and it has to
* be specified by overriding the virtual {_implementation} function.
*
* Additionally, delegation to the implementation can be triggered manually through the {_fallback} function, or to a
* different contract through the {_delegate} function.
*
* The success and return data of the delegated call will be returned back to the caller of the proxy.
*/
abstract contract Proxy {
/**
* @dev Delegates the current call to `implementation`.
*
* This function does not return to its internall call site, it will return directly to the external caller.
*/
function _delegate(address implementation) internal virtual {
// solhint-disable-next-line no-inline-assembly
assembly {
// Copy msg.data. We take full control of memory in this inline assembly
// block because it will not return to Solidity code. We overwrite the
// Solidity scratch pad at memory position 0.
calldatacopy(0, 0, calldatasize())
// Call the implementation.
// out and outsize are 0 because we don't know the size yet.
let result := delegatecall(gas(), implementation, 0, calldatasize(), 0, 0)
// Copy the returned data.
returndatacopy(0, 0, returndatasize())
switch result
// delegatecall returns 0 on error.
case 0 { revert(0, returndatasize()) }
default { return(0, returndatasize()) }
}
}
/**
* @dev This is a virtual function that should be overriden so it returns the address to which the fallback function
* and {_fallback} should delegate.
*/
function _implementation() internal view virtual returns (address);
/**
* @dev Delegates the current call to the address returned by `_implementation()`.
*
* This function does not return to its internall call site, it will return directly to the external caller.
*/
function _fallback() internal virtual {
_beforeFallback();
_delegate(_implementation());
}
/**
* @dev Fallback function that delegates calls to the address returned by `_implementation()`. Will run if no other
* function in the contract matches the call data.
*/
fallback () external payable virtual {
_fallback();
}
/**
* @dev Fallback function that delegates calls to the address returned by `_implementation()`. Will run if call data
* is empty.
*/
receive () external payable virtual {
_fallback();
}
/**
* @dev Hook that is called before falling back to the implementation. Can happen as part of a manual `_fallback`
* call, or as part of the Solidity `fallback` or `receive` functions.
*
* If overriden should call `super._beforeFallback()`.
*/
function _beforeFallback() internal virtual {
}
}
/**
* @dev This abstract contract provides getters and event emitting update functions for
* https://eips.ethereum.org/EIPS/eip-1967[EIP1967] slots.
*
* _Available since v4.1._
*
*/
abstract contract ERC1967Upgrade {
// This is the keccak-256 hash of "eip1967.proxy.rollback" subtracted by 1
bytes32 private constant _ROLLBACK_SLOT = 0x4910fdfa16fed3260ed0e7147f7cc6da11a60208b5b9406d12a635614ffd9143;
/**
* @dev Storage slot with the address of the current implementation.
* This is the keccak-256 hash of "eip1967.proxy.implementation" subtracted by 1, and is
* validated in the constructor.
*/
bytes32 internal constant _IMPLEMENTATION_SLOT = 0x360894a13ba1a3210667c828492db98dca3e2076cc3735a920a3ca505d382bbc;
/**
* @dev Emitted when the implementation is upgraded.
*/
event Upgraded(address indexed implementation);
/**
* @dev Returns the current implementation address.
*/
function _getImplementation() internal view returns (address) {
return StorageSlot.getAddressSlot(_IMPLEMENTATION_SLOT).value;
}
/**
* @dev Stores a new address in the EIP1967 implementation slot.
*/
function _setImplementation(address newImplementation) private {
require(Address.isContract(newImplementation), "ERC1967: new implementation is not a contract");
StorageSlot.getAddressSlot(_IMPLEMENTATION_SLOT).value = newImplementation;
}
/**
* @dev Perform implementation upgrade
*
* Emits an {Upgraded} event.
*/
function _upgradeTo(address newImplementation) internal {
_setImplementation(newImplementation);
emit Upgraded(newImplementation);
}
/**
* @dev Perform implementation upgrade with additional setup call.
*
* Emits an {Upgraded} event.
*/
function _upgradeToAndCall(address newImplementation, bytes memory data, bool forceCall) internal {
_setImplementation(newImplementation);
emit Upgraded(newImplementation);
if (data.length > 0 || forceCall) {
Address.functionDelegateCall(newImplementation, data);
}
}
/**
* @dev Perform implementation upgrade with security checks for UUPS proxies, and additional setup call.
*
* Emits an {Upgraded} event.
*/
function _upgradeToAndCallSecure(address newImplementation, bytes memory data, bool forceCall) internal {
address oldImplementation = _getImplementation();
// Initial upgrade and setup call
_setImplementation(newImplementation);
if (data.length > 0 || forceCall) {
Address.functionDelegateCall(newImplementation, data);
}
// Perform rollback test if not already in progress
StorageSlot.BooleanSlot storage rollbackTesting = StorageSlot.getBooleanSlot(_ROLLBACK_SLOT);
if (!rollbackTesting.value) {
// Trigger rollback using upgradeTo from the new implementation
rollbackTesting.value = true;
Address.functionDelegateCall(
newImplementation,
abi.encodeWithSignature(
"upgradeTo(address)",
oldImplementation
)
);
rollbackTesting.value = false;
// Check rollback was effective
require(oldImplementation == _getImplementation(), "ERC1967Upgrade: upgrade breaks further upgrades");
// Finally reset to the new implementation and log the upgrade
_setImplementation(newImplementation);
emit Upgraded(newImplementation);
}
}
/**
* @dev Perform beacon upgrade with additional setup call. Note: This upgrades the address of the beacon, it does
* not upgrade the implementation contained in the beacon (see {UpgradeableBeacon-_setImplementation} for that).
*
* Emits a {BeaconUpgraded} event.
*/
function _upgradeBeaconToAndCall(address newBeacon, bytes memory data, bool forceCall) internal {
_setBeacon(newBeacon);
emit BeaconUpgraded(newBeacon);
if (data.length > 0 || forceCall) {
Address.functionDelegateCall(IBeacon(newBeacon).implementation(), data);
}
}
/**
* @dev Storage slot with the admin of the contract.
* This is the keccak-256 hash of "eip1967.proxy.admin" subtracted by 1, and is
* validated in the constructor.
*/
bytes32 internal constant _ADMIN_SLOT = 0xb53127684a568b3173ae13b9f8a6016e243e63b6e8ee1178d6a717850b5d6103;
/**
* @dev Emitted when the admin account has changed.
*/
event AdminChanged(address previousAdmin, address newAdmin);
/**
* @dev Returns the current admin.
*/
function _getAdmin() internal view returns (address) {
return StorageSlot.getAddressSlot(_ADMIN_SLOT).value;
}
/**
* @dev Stores a new address in the EIP1967 admin slot.
*/
function _setAdmin(address newAdmin) private {
require(newAdmin != address(0), "ERC1967: new admin is the zero address");
StorageSlot.getAddressSlot(_ADMIN_SLOT).value = newAdmin;
}
/**
* @dev Changes the admin of the proxy.
*
* Emits an {AdminChanged} event.
*/
function _changeAdmin(address newAdmin) internal {
emit AdminChanged(_getAdmin(), newAdmin);
_setAdmin(newAdmin);
}
/**
* @dev The storage slot of the UpgradeableBeacon contract which defines the implementation for this proxy.
* This is bytes32(uint256(keccak256('eip1967.proxy.beacon')) - 1)) and is validated in the constructor.
*/
bytes32 internal constant _BEACON_SLOT = 0xa3f0ad74e5423aebfd80d3ef4346578335a9a72aeaee59ff6cb3582b35133d50;
/**
* @dev Emitted when the beacon is upgraded.
*/
event BeaconUpgraded(address indexed beacon);
/**
* @dev Returns the current beacon.
*/
function _getBeacon() internal view returns (address) {
return StorageSlot.getAddressSlot(_BEACON_SLOT).value;
}
/**
* @dev Stores a new beacon in the EIP1967 beacon slot.
*/
function _setBeacon(address newBeacon) private {
require(
Address.isContract(newBeacon),
"ERC1967: new beacon is not a contract"
);
require(
Address.isContract(IBeacon(newBeacon).implementation()),
"ERC1967: beacon implementation is not a contract"
);
StorageSlot.getAddressSlot(_BEACON_SLOT).value = newBeacon;
}
}
/**
* @dev This is the interface that {BeaconProxy} expects of its beacon.
*/
interface IBeacon {
/**
* @dev Must return an address that can be used as a delegate call target.
*
* {BeaconProxy} will check that this address is a contract.
*/
function implementation() external view returns (address);
}
/**
* @dev Collection of functions related to the address type
*/
library Address {
/**
* @dev Returns true if `account` is a contract.
*
* [IMPORTANT]
* ====
* It is unsafe to assume that an address for which this function returns
* false is an externally-owned account (EOA) and not a contract.
*
* Among others, `isContract` will return false for the following
* types of addresses:
*
* - an externally-owned account
* - a contract in construction
* - an address where a contract will be created
* - an address where a contract lived, but was destroyed
* ====
*/
function isContract(address account) internal view returns (bool) {
// This method relies on extcodesize, which returns 0 for contracts in
// construction, since the code is only stored at the end of the
// constructor execution.
uint256 size;
// solhint-disable-next-line no-inline-assembly
assembly { size := extcodesize(account) }
return size > 0;
}
/**
* @dev Replacement for Solidity's `transfer`: sends `amount` wei to
* `recipient`, forwarding all available gas and reverting on errors.
*
* https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost
* of certain opcodes, possibly making contracts go over the 2300 gas limit
* imposed by `transfer`, making them unable to receive funds via
* `transfer`. {sendValue} removes this limitation.
*
* https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more].
*
* IMPORTANT: because control is transferred to `recipient`, care must be
* taken to not create reentrancy vulnerabilities. Consider using
* {ReentrancyGuard} or the
* https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern].
*/
function sendValue(address payable recipient, uint256 amount) internal {
require(address(this).balance >= amount, "Address: insufficient balance");
// solhint-disable-next-line avoid-low-level-calls, avoid-call-value
(bool success, ) = recipient.call{ value: amount }("");
require(success, "Address: unable to send value, recipient may have reverted");
}
/**
* @dev Performs a Solidity function call using a low level `call`. A
* plain`call` is an unsafe replacement for a function call: use this
* function instead.
*
* If `target` reverts with a revert reason, it is bubbled up by this
* function (like regular Solidity function calls).
*
* Returns the raw returned data. To convert to the expected return value,
* use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`].
*
* Requirements:
*
* - `target` must be a contract.
* - calling `target` with `data` must not revert.
*
* _Available since v3.1._
*/
function functionCall(address target, bytes memory data) internal returns (bytes memory) {
return functionCall(target, data, "Address: low-level call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with
* `errorMessage` as a fallback revert reason when `target` reverts.
*
* _Available since v3.1._
*/
function functionCall(address target, bytes memory data, string memory errorMessage) internal returns (bytes memory) {
return functionCallWithValue(target, data, 0, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but also transferring `value` wei to `target`.
*
* Requirements:
*
* - the calling contract must have an ETH balance of at least `value`.
* - the called Solidity function must be `payable`.
*
* _Available since v3.1._
*/
function functionCallWithValue(address target, bytes memory data, uint256 value) internal returns (bytes memory) {
return functionCallWithValue(target, data, value, "Address: low-level call with value failed");
}
/**
* @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but
* with `errorMessage` as a fallback revert reason when `target` reverts.
*
* _Available since v3.1._
*/
function functionCallWithValue(address target, bytes memory data, uint256 value, string memory errorMessage) internal returns (bytes memory) {
require(address(this).balance >= value, "Address: insufficient balance for call");
require(isContract(target), "Address: call to non-contract");
// solhint-disable-next-line avoid-low-level-calls
(bool success, bytes memory returndata) = target.call{ value: value }(data);
return _verifyCallResult(success, returndata, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but performing a static call.
*
* _Available since v3.3._
*/
function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) {
return functionStaticCall(target, data, "Address: low-level static call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`],
* but performing a static call.
*
* _Available since v3.3._
*/
function functionStaticCall(address target, bytes memory data, string memory errorMessage) internal view returns (bytes memory) {
require(isContract(target), "Address: static call to non-contract");
// solhint-disable-next-line avoid-low-level-calls
(bool success, bytes memory returndata) = target.staticcall(data);
return _verifyCallResult(success, returndata, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but performing a delegate call.
*
* _Available since v3.4._
*/
function functionDelegateCall(address target, bytes memory data) internal returns (bytes memory) {
return functionDelegateCall(target, data, "Address: low-level delegate call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`],
* but performing a delegate call.
*
* _Available since v3.4._
*/
function functionDelegateCall(address target, bytes memory data, string memory errorMessage) internal returns (bytes memory) {
require(isContract(target), "Address: delegate call to non-contract");
// solhint-disable-next-line avoid-low-level-calls
(bool success, bytes memory returndata) = target.delegatecall(data);
return _verifyCallResult(success, returndata, errorMessage);
}
function _verifyCallResult(bool success, bytes memory returndata, string memory errorMessage) private pure returns(bytes memory) {
if (success) {
return returndata;
} else {
// Look for revert reason and bubble it up if present
if (returndata.length > 0) {
// The easiest way to bubble the revert reason is using memory via assembly
// solhint-disable-next-line no-inline-assembly
assembly {
let returndata_size := mload(returndata)
revert(add(32, returndata), returndata_size)
}
} else {
revert(errorMessage);
}
}
}
}
/**
* @dev Library for reading and writing primitive types to specific storage slots.
*
* Storage slots are often used to avoid storage conflict when dealing with upgradeable contracts.
* This library helps with reading and writing to such slots without the need for inline assembly.
*
* The functions in this library return Slot structs that contain a `value` member that can be used to read or write.
*
* Example usage to set ERC1967 implementation slot:
* ```
* contract ERC1967 {
* bytes32 internal constant _IMPLEMENTATION_SLOT = 0x360894a13ba1a3210667c828492db98dca3e2076cc3735a920a3ca505d382bbc;
*
* function _getImplementation() internal view returns (address) {
* return StorageSlot.getAddressSlot(_IMPLEMENTATION_SLOT).value;
* }
*
* function _setImplementation(address newImplementation) internal {
* require(Address.isContract(newImplementation), "ERC1967: new implementation is not a contract");
* StorageSlot.getAddressSlot(_IMPLEMENTATION_SLOT).value = newImplementation;
* }
* }
* ```
*
* _Available since v4.1 for `address`, `bool`, `bytes32`, and `uint256`._
*/
library StorageSlot {
struct AddressSlot {
address value;
}
struct BooleanSlot {
bool value;
}
struct Bytes32Slot {
bytes32 value;
}
struct Uint256Slot {
uint256 value;
}
/**
* @dev Returns an `AddressSlot` with member `value` located at `slot`.
*/
function getAddressSlot(bytes32 slot) internal pure returns (AddressSlot storage r) {
assembly {
r.slot := slot
}
}
/**
* @dev Returns an `BooleanSlot` with member `value` located at `slot`.
*/
function getBooleanSlot(bytes32 slot) internal pure returns (BooleanSlot storage r) {
assembly {
r.slot := slot
}
}
/**
* @dev Returns an `Bytes32Slot` with member `value` located at `slot`.
*/
function getBytes32Slot(bytes32 slot) internal pure returns (Bytes32Slot storage r) {
assembly {
r.slot := slot
}
}
/**
* @dev Returns an `Uint256Slot` with member `value` located at `slot`.
*/
function getUint256Slot(bytes32 slot) internal pure returns (Uint256Slot storage r) {
assembly {
r.slot := slot
}
}
}
/*
* @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;
}
}
/**
* @dev Contract module which provides a basic access control mechanism, where
* there is an account (an owner) that can be granted exclusive access to
* specific functions.
*
* By default, the owner account will be the one that deploys the contract. This
* can later be changed with {transferOwnership}.
*
* This module is used through inheritance. It will make available the modifier
* `onlyOwner`, which can be applied to your functions to restrict their use to
* the owner.
*/
abstract contract Ownable is Context {
address private _owner;
event OwnershipTransferred(address indexed previousOwner, address indexed newOwner);
/**
* @dev Initializes the contract setting the deployer as the initial owner.
*/
constructor () {
address msgSender = _msgSender();
_owner = msgSender;
emit OwnershipTransferred(address(0), msgSender);
}
/**
* @dev Returns the address of the current owner.
*/
function owner() public view virtual returns (address) {
return _owner;
}
/**
* @dev Throws if called by any account other than the owner.
*/
modifier onlyOwner() {
require(owner() == _msgSender(), "Ownable: caller is not the owner");
_;
}
/**
* @dev Leaves the contract without owner. It will not be possible to call
* `onlyOwner` functions anymore. Can only be called by the current owner.
*
* NOTE: Renouncing ownership will leave the contract without an owner,
* thereby removing any functionality that is only available to the owner.
*/
function renounceOwnership() public virtual onlyOwner {
emit OwnershipTransferred(_owner, address(0));
_owner = address(0);
}
/**
* @dev Transfers ownership of the contract to a new account (`newOwner`).
* Can only be called by the current owner.
*/
function transferOwnership(address newOwner) public virtual onlyOwner {
require(newOwner != address(0), "Ownable: new owner is the zero address");
emit OwnershipTransferred(_owner, newOwner);
_owner = newOwner;
}
}
/**
* @dev This is an auxiliary contract meant to be assigned as the admin of a {TransparentUpgradeableProxy}. For an
* explanation of why you would want to use this see the documentation for {TransparentUpgradeableProxy}.
*/
contract ProxyAdmin is Ownable {
/**
* @dev Returns the current implementation of `proxy`.
*
* Requirements:
*
* - This contract must be the admin of `proxy`.
*/
function getProxyImplementation(TransparentUpgradeableProxy proxy) public view virtual returns (address) {
// We need to manually run the static call since the getter cannot be flagged as view
// bytes4(keccak256("implementation()")) == 0x5c60da1b
(bool success, bytes memory returndata) = address(proxy).staticcall(hex"5c60da1b");
require(success);
return abi.decode(returndata, (address));
}
/**
* @dev Returns the current admin of `proxy`.
*
* Requirements:
*
* - This contract must be the admin of `proxy`.
*/
function getProxyAdmin(TransparentUpgradeableProxy proxy) public view virtual returns (address) {
// We need to manually run the static call since the getter cannot be flagged as view
// bytes4(keccak256("admin()")) == 0xf851a440
(bool success, bytes memory returndata) = address(proxy).staticcall(hex"f851a440");
require(success);
return abi.decode(returndata, (address));
}
/**
* @dev Changes the admin of `proxy` to `newAdmin`.
*
* Requirements:
*
* - This contract must be the current admin of `proxy`.
*/
function changeProxyAdmin(TransparentUpgradeableProxy proxy, address newAdmin) public virtual onlyOwner {
proxy.changeAdmin(newAdmin);
}
/**
* @dev Upgrades `proxy` to `implementation`. See {TransparentUpgradeableProxy-upgradeTo}.
*
* Requirements:
*
* - This contract must be the admin of `proxy`.
*/
function upgrade(TransparentUpgradeableProxy proxy, address implementation) public virtual onlyOwner {
proxy.upgradeTo(implementation);
}
/**
* @dev Upgrades `proxy` to `implementation` and calls a function on the new implementation. See
* {TransparentUpgradeableProxy-upgradeToAndCall}.
*
* Requirements:
*
* - This contract must be the admin of `proxy`.
*/
function upgradeAndCall(TransparentUpgradeableProxy proxy, address implementation, bytes memory data) public payable virtual onlyOwner {
proxy.upgradeToAndCall{value: msg.value}(implementation, data);
}
}
/**
* @dev Base contract for building openzeppelin-upgrades compatible implementations for the {ERC1967Proxy}. It includes
* publicly available upgrade functions that are called by the plugin and by the secure upgrade mechanism to verify
* continuation of the upgradability.
*
* The {_authorizeUpgrade} function MUST be overridden to include access restriction to the upgrade mechanism.
*
* _Available since v4.1._
*/
abstract contract UUPSUpgradeable is ERC1967Upgrade {
function upgradeTo(address newImplementation) external virtual {
_authorizeUpgrade(newImplementation);
_upgradeToAndCallSecure(newImplementation, bytes(""), false);
}
function upgradeToAndCall(address newImplementation, bytes memory data) external payable virtual {
_authorizeUpgrade(newImplementation);
_upgradeToAndCallSecure(newImplementation, data, true);
}
function _authorizeUpgrade(address newImplementation) internal virtual;
}
abstract contract Proxiable is UUPSUpgradeable {
function _authorizeUpgrade(address newImplementation) internal override {
_beforeUpgrade(newImplementation);
}
function _beforeUpgrade(address newImplementation) internal virtual;
}
contract ChildOfProxiable is Proxiable {
function _beforeUpgrade(address newImplementation) internal virtual override {}
}
/**
* @dev This contract implements an upgradeable proxy. It is upgradeable because calls are delegated to an
* implementation address that can be changed. This address is stored in storage in the location specified by
* https://eips.ethereum.org/EIPS/eip-1967[EIP1967], so that it doesn't conflict with the storage layout of the
* implementation behind the proxy.
*/
contract ERC1967Proxy is Proxy, ERC1967Upgrade {
/**
* @dev Initializes the upgradeable proxy with an initial implementation specified by `_logic`.
*
* If `_data` is nonempty, it's used as data in a delegate call to `_logic`. This will typically be an encoded
* function call, and allows initializating the storage of the proxy like a Solidity constructor.
*/
constructor(address _logic, bytes memory _data) payable {
assert(_IMPLEMENTATION_SLOT == bytes32(uint256(keccak256("eip1967.proxy.implementation")) - 1));
_upgradeToAndCall(_logic, _data, false);
}
/**
* @dev Returns the current implementation address.
*/
function _implementation() internal view virtual override returns (address impl) {
return ERC1967Upgrade._getImplementation();
}
}
/**
* @dev This contract implements a proxy that is upgradeable by an admin.
*
* To avoid https://medium.com/nomic-labs-blog/malicious-backdoors-in-ethereum-proxies-62629adf3357[proxy selector
* clashing], which can potentially be used in an attack, this contract uses the
* https://blog.openzeppelin.com/the-transparent-proxy-pattern/[transparent proxy pattern]. This pattern implies two
* things that go hand in hand:
*
* 1. If any account other than the admin calls the proxy, the call will be forwarded to the implementation, even if
* that call matches one of the admin functions exposed by the proxy itself.
* 2. If the admin calls the proxy, it can access the admin functions, but its calls will never be forwarded to the
* implementation. If the admin tries to call a function on the implementation it will fail with an error that says
* "admin cannot fallback to proxy target".
*
* These properties mean that the admin account can only be used for admin actions like upgrading the proxy or changing
* the admin, so it's best if it's a dedicated account that is not used for anything else. This will avoid headaches due
* to sudden errors when trying to call a function from the proxy implementation.
*
* Our recommendation is for the dedicated account to be an instance of the {ProxyAdmin} contract. If set up this way,
* you should think of the `ProxyAdmin` instance as the real administrative interface of your proxy.
*/
contract TransparentUpgradeableProxy is ERC1967Proxy {
/**
* @dev Initializes an upgradeable proxy managed by `_admin`, backed by the implementation at `_logic`, and
* optionally initialized with `_data` as explained in {ERC1967Proxy-constructor}.
*/
constructor(address _logic, address admin_, bytes memory _data) payable ERC1967Proxy(_logic, _data) {
assert(_ADMIN_SLOT == bytes32(uint256(keccak256("eip1967.proxy.admin")) - 1));
_changeAdmin(admin_);
}
/**
* @dev Modifier used internally that will delegate the call to the implementation unless the sender is the admin.
*/
modifier ifAdmin() {
if (msg.sender == _getAdmin()) {
_;
} else {
_fallback();
}
}
/**
* @dev Returns the current admin.
*
* NOTE: Only the admin can call this function. See {ProxyAdmin-getProxyAdmin}.
*
* TIP: To get this value clients can read directly from the storage slot shown below (specified by EIP1967) using the
* https://eth.wiki/json-rpc/API#eth_getstorageat[`eth_getStorageAt`] RPC call.
* `0xb53127684a568b3173ae13b9f8a6016e243e63b6e8ee1178d6a717850b5d6103`
*/
function admin() external ifAdmin returns (address admin_) {
admin_ = _getAdmin();
}
/**
* @dev Returns the current implementation.
*
* NOTE: Only the admin can call this function. See {ProxyAdmin-getProxyImplementation}.
*
* TIP: To get this value clients can read directly from the storage slot shown below (specified by EIP1967) using the
* https://eth.wiki/json-rpc/API#eth_getstorageat[`eth_getStorageAt`] RPC call.
* `0x360894a13ba1a3210667c828492db98dca3e2076cc3735a920a3ca505d382bbc`
*/
function implementation() external ifAdmin returns (address implementation_) {
implementation_ = _implementation();
}
/**
* @dev Changes the admin of the proxy.
*
* Emits an {AdminChanged} event.
*
* NOTE: Only the admin can call this function. See {ProxyAdmin-changeProxyAdmin}.
*/
function changeAdmin(address newAdmin) external virtual ifAdmin {
_changeAdmin(newAdmin);
}
/**
* @dev Upgrade the implementation of the proxy.
*
* NOTE: Only the admin can call this function. See {ProxyAdmin-upgrade}.
*/
function upgradeTo(address newImplementation) external ifAdmin {
_upgradeToAndCall(newImplementation, bytes(""), false);
}
/**
* @dev Upgrade the implementation of the proxy, and then call a function from the new implementation as specified
* by `data`, which should be an encoded function call. This is useful to initialize new storage variables in the
* proxied contract.
*
* NOTE: Only the admin can call this function. See {ProxyAdmin-upgradeAndCall}.
*/
function upgradeToAndCall(address newImplementation, bytes calldata data) external payable ifAdmin {
_upgradeToAndCall(newImplementation, data, true);
}
/**
* @dev Returns the current admin.
*/
function _admin() internal view virtual returns (address) {
return _getAdmin();
}
/**
* @dev Makes sure the admin cannot access the fallback function. See {Proxy-_beforeFallback}.
*/
function _beforeFallback() internal virtual override {
require(msg.sender != _getAdmin(), "TransparentUpgradeableProxy: admin cannot fallback to proxy target");
super._beforeFallback();
}
}
// Kept for backwards compatibility with older versions of Hardhat and Truffle plugins.
contract AdminUpgradeabilityProxy is TransparentUpgradeableProxy {
constructor(address logic, address admin, bytes memory data) payable TransparentUpgradeableProxy(logic, admin, data) {}
}
|
[{"inputs":[{"internalType":"address","name":"_logic","type":"address"},{"internalType":"bytes","name":"_data","type":"bytes"}],"stateMutability":"payable","type":"constructor"},{"anonymous":false,"inputs":[{"indexed":false,"internalType":"address","name":"previousAdmin","type":"address"},{"indexed":false,"internalType":"address","name":"newAdmin","type":"address"}],"name":"AdminChanged","type":"event"},{"anonymous":false,"inputs":[{"indexed":true,"internalType":"address","name":"beacon","type":"address"}],"name":"BeaconUpgraded","type":"event"},{"anonymous":false,"inputs":[{"indexed":true,"internalType":"address","name":"implementation","type":"address"}],"name":"Upgraded","type":"event"},{"stateMutability":"payable","type":"fallback"},{"stateMutability":"payable","type":"receive"}]
|
v0.8.2+commit.661d1103
| true
| 200
|
0000000000000000000000008fd46e7f74e5976837135a42c4bfc946fe5a229f00000000000000000000000000000000000000000000000000000000000000400000000000000000000000000000000000000000000000000000000000000044485cc9550000000000000000000000001111111111accdf36dbee012fc26bb9fcc1d140d0000000000000000000000009978be4de5beb786da4727a545b14fec2266511700000000000000000000000000000000000000000000000000000000
|
Default
|
MIT
| false
|
ipfs://9b8470f06e8a3960c912103fc2be177edaad69584ee3c7d2809ee737e79408e7
|
||
ReversibleDemo
|
0x16a454d340610f8809967bcbfe432a6853640983
|
Solidity
|
// `interface` would make a nice keyword ;)
contract TheDaoHardForkOracle {
// `ran()` manually verified true on both ETH and ETC chains
function forked() constant returns (bool);
}
// demostrates calling own function in a "reversible" manner
/* important lines are marked by multi-line comments */
contract ReversibleDemo {
// counters (all public to simplify inspection)
uint public numcalls;
uint public numcallsinternal;
uint public numfails;
uint public numsuccesses;
address owner;
// needed for "naive" and "oraclized" checks
address constant withdrawdaoaddr = 0xbf4ed7b27f1d666546e30d74d50d173d20bca754;
TheDaoHardForkOracle oracle = TheDaoHardForkOracle(0xe8e506306ddb78ee38c9b0d86c257bd97c2536b3);
event logCall(uint indexed _numcalls,
uint indexed _numfails,
uint indexed _numsuccesses);
modifier onlyOwner { if (msg.sender != owner) throw; _ }
modifier onlyThis { if (msg.sender != address(this)) throw; _ }
// constructor (setting `owner` allows later termination)
function ReversibleDemo() { owner = msg.sender; }
/* external: increments stack height */
/* onlyThis: prevent actual external calling */
function sendIfNotForked() external onlyThis returns (bool) {
numcallsinternal++;
/* naive check for "is this the classic chain" */
// guaranteed `true`: enough has been withdrawn already
// three million ------> 3'000'000
if (withdrawdaoaddr.balance < 3000000 ether) {
/* intentionally not checking return value */
owner.send(42);
}
/* "reverse" if it's actually the HF chain */
if (oracle.forked()) throw;
// not exactly a "success": send() could have failed on classic
return true;
}
// accepts value transfers
function doCall(uint _gas) onlyOwner {
numcalls++;
if (!this.sendIfNotForked.gas(_gas)()) {
numfails++;
}
else {
numsuccesses++;
}
logCall(numcalls, numfails, numsuccesses);
}
function selfDestruct() onlyOwner {
selfdestruct(owner);
}
// accepts value trasfers, but does nothing
function() {}
}
|
[{"constant":true,"inputs":[],"name":"numsuccesses","outputs":[{"name":"","type":"uint256"}],"type":"function"},{"constant":true,"inputs":[],"name":"numfails","outputs":[{"name":"","type":"uint256"}],"type":"function"},{"constant":true,"inputs":[],"name":"numcalls","outputs":[{"name":"","type":"uint256"}],"type":"function"},{"constant":true,"inputs":[],"name":"numcallsinternal","outputs":[{"name":"","type":"uint256"}],"type":"function"},{"constant":false,"inputs":[],"name":"sendIfNotForked","outputs":[{"name":"","type":"bool"}],"type":"function"},{"constant":false,"inputs":[],"name":"selfDestruct","outputs":[],"type":"function"},{"constant":false,"inputs":[{"name":"_gas","type":"uint256"}],"name":"doCall","outputs":[],"type":"function"},{"inputs":[],"type":"constructor"},{"anonymous":false,"inputs":[{"indexed":true,"name":"_numcalls","type":"uint256"},{"indexed":true,"name":"_numfails","type":"uint256"},{"indexed":true,"name":"_numsuccesses","type":"uint256"}],"name":"logCall","type":"event"}]
|
v0.3.5-2016-08-07-f7af7de
| true
| 200
|
Default
| false
| |||||
SaffronLPBalanceToken
|
0x96853eadcf9da67d6f7a4b6ad28bdc81a96c2188
|
Solidity
|
// File: contracts/lib/Context.sol
// SPDX-License-Identifier: MIT
pragma solidity ^0.7.1;
/*
* @dev Provides information about the current execution context, including the
* sender of the transaction and its data. While these are generally available
* via msg.sender and msg.data, they should not be accessed in such a direct
* manner, since when dealing with GSN meta-transactions the account sending and
* paying for execution may not be the actual sender (as far as an application
* is concerned).
*
* This contract is only required for intermediate, library-like contracts.
*/
abstract contract Context {
function _msgSender() internal view virtual returns (address payable) {
return msg.sender;
}
function _msgData() internal view virtual returns (bytes memory) {
this; // silence state mutability warning without generating bytecode - see https://github.com/ethereum/solidity/issues/2691
return msg.data;
}
}
// File: contracts/lib/IERC20.sol
pragma solidity ^0.7.1;
/**
* @dev Interface of the ERC20 standard as defined in the EIP.
*/
interface IERC20 {
/**
* @dev Returns the amount of tokens in existence.
*/
function totalSupply() external view returns (uint256);
/**
* @dev Returns the amount of tokens owned by `account`.
*/
function balanceOf(address account) external view returns (uint256);
/**
* @dev Moves `amount` tokens from the caller's account to `recipient`.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/
function transfer(address recipient, uint256 amount) external returns (bool);
/**
* @dev Returns the remaining number of tokens that `spender` will be
* allowed to spend on behalf of `owner` through {transferFrom}. This is
* zero by default.
*
* This value changes when {approve} or {transferFrom} are called.
*/
function allowance(address owner, address spender) external view returns (uint256);
/**
* @dev Sets `amount` as the allowance of `spender` over the caller's tokens.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* IMPORTANT: Beware that changing an allowance with this method brings the risk
* that someone may use both the old and the new allowance by unfortunate
* transaction ordering. One possible solution to mitigate this race
* condition is to first reduce the spender's allowance to 0 and set the
* desired value afterwards:
* https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729
*
* Emits an {Approval} event.
*/
function approve(address spender, uint256 amount) external returns (bool);
/**
* @dev Moves `amount` tokens from `sender` to `recipient` using the
* allowance mechanism. `amount` is then deducted from the caller's
* allowance.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/
function transferFrom(address sender, address recipient, uint256 amount) external returns (bool);
/**
* @dev Emitted when `value` tokens are moved from one account (`from`) to
* another (`to`).
*
* Note that `value` may be zero.
*/
event Transfer(address indexed from, address indexed to, uint256 value);
/**
* @dev Emitted when the allowance of a `spender` for an `owner` is set by
* a call to {approve}. `value` is the new allowance.
*/
event Approval(address indexed owner, address indexed spender, uint256 value);
}
// File: contracts/lib/SafeMath.sol
pragma solidity ^0.7.1;
/**
* @dev Wrappers over Solidity's arithmetic operations with added overflow
* checks.
*
* Arithmetic operations in Solidity wrap on overflow. This can easily result
* in bugs, because programmers usually assume that an overflow raises an
* error, which is the standard behavior in high level programming languages.
* `SafeMath` restores this intuition by reverting the transaction when an
* operation overflows.
*
* Using this library instead of the unchecked operations eliminates an entire
* class of bugs, so it's recommended to use it always.
*/
library SafeMath {
/**
* @dev Returns the addition of two unsigned integers, reverting on
* overflow.
*
* Counterpart to Solidity's `+` operator.
*
* Requirements:
*
* - Addition cannot overflow.
*/
function add(uint256 a, uint256 b) internal pure returns (uint256) {
uint256 c = a + b;
require(c >= a, "SafeMath: addition overflow");
return c;
}
/**
* @dev Returns the subtraction of two unsigned integers, reverting on
* overflow (when the result is negative).
*
* Counterpart to Solidity's `-` operator.
*
* Requirements:
*
* - Subtraction cannot overflow.
*/
function sub(uint256 a, uint256 b) internal pure returns (uint256) {
return sub(a, b, "SafeMath: subtraction overflow");
}
/**
* @dev Returns the subtraction of two unsigned integers, reverting with custom message on
* overflow (when the result is negative).
*
* Counterpart to Solidity's `-` operator.
*
* Requirements:
*
* - Subtraction cannot overflow.
*/
function sub(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
require(b <= a, errorMessage);
uint256 c = a - b;
return c;
}
/**
* @dev Returns the multiplication of two unsigned integers, reverting on
* overflow.
*
* Counterpart to Solidity's `*` operator.
*
* Requirements:
*
* - Multiplication cannot overflow.
*/
function mul(uint256 a, uint256 b) internal pure returns (uint256) {
// Gas optimization: this is cheaper than requiring 'a' not being zero, but the
// benefit is lost if 'b' is also tested.
// See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522
if (a == 0) {
return 0;
}
uint256 c = a * b;
require(c / a == b, "SafeMath: multiplication overflow");
return c;
}
/**
* @dev Returns the integer division of two unsigned integers. Reverts on
* division by zero. The result is rounded towards zero.
*
* Counterpart to Solidity's `/` operator. Note: this function uses a
* `revert` opcode (which leaves remaining gas untouched) while Solidity
* uses an invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function div(uint256 a, uint256 b) internal pure returns (uint256) {
return div(a, b, "SafeMath: division by zero");
}
/**
* @dev Returns the integer division of two unsigned integers. Reverts with custom message on
* division by zero. The result is rounded towards zero.
*
* Counterpart to Solidity's `/` operator. Note: this function uses a
* `revert` opcode (which leaves remaining gas untouched) while Solidity
* uses an invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function div(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
require(b > 0, errorMessage);
uint256 c = a / b;
// assert(a == b * c + a % b); // There is no case in which this doesn't hold
return c;
}
/**
* @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo),
* Reverts when dividing by zero.
*
* Counterpart to Solidity's `%` operator. This function uses a `revert`
* opcode (which leaves remaining gas untouched) while Solidity uses an
* invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function mod(uint256 a, uint256 b) internal pure returns (uint256) {
return mod(a, b, "SafeMath: modulo by zero");
}
/**
* @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo),
* Reverts with custom message when dividing by zero.
*
* Counterpart to Solidity's `%` operator. This function uses a `revert`
* opcode (which leaves remaining gas untouched) while Solidity uses an
* invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function mod(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
require(b != 0, errorMessage);
return a % b;
}
}
// File: contracts/lib/Address.sol
pragma solidity ^0.7.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
* ====
*/
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.3._
*/
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.3._
*/
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: contracts/lib/ERC20.sol
pragma solidity ^0.7.1;
/**
* @dev Implementation of the {IERC20} interface.
*
* This implementation is agnostic to the way tokens are created. This means
* that a supply mechanism has to be added in a derived contract using {_mint}.
* For a generic mechanism see {ERC20PresetMinterPauser}.
*
* TIP: For a detailed writeup see our guide
* https://forum.zeppelin.solutions/t/how-to-implement-erc20-supply-mechanisms/226[How
* to implement supply mechanisms].
*
* We have followed general OpenZeppelin guidelines: functions revert instead
* of returning `false` on failure. This behavior is nonetheless conventional
* and does not conflict with the expectations of ERC20 applications.
*
* Additionally, an {Approval} event is emitted on calls to {transferFrom}.
* This allows applications to reconstruct the allowance for all accounts just
* by listening to said events. Other implementations of the EIP may not emit
* these events, as it isn't required by the specification.
*
* Finally, the non-standard {decreaseAllowance} and {increaseAllowance}
* functions have been added to mitigate the well-known issues around setting
* allowances. See {IERC20-approve}.
*/
contract ERC20 is Context, IERC20 {
using SafeMath for uint256;
using Address for address;
mapping (address => uint256) private _balances;
mapping (address => mapping (address => uint256)) private _allowances;
uint256 private _totalSupply;
string private _name;
string private _symbol;
uint8 private _decimals;
/**
* @dev Sets the values for {name} and {symbol}, initializes {decimals} with
* a default value of 18.
*
* To select a different value for {decimals}, use {_setupDecimals}.
*
* All three of these values are immutable: they can only be set once during
* construction.
*/
constructor (string memory name_, string memory symbol_) {
_name = name_;
_symbol = symbol_;
_decimals = 18;
}
/**
* @dev Returns the name of the token.
*/
function name() public view returns (string memory) {
return _name;
}
/**
* @dev Returns the symbol of the token, usually a shorter version of the
* name.
*/
function symbol() public view returns (string memory) {
return _symbol;
}
/**
* @dev Returns the number of decimals used to get its user representation.
* For example, if `decimals` equals `2`, a balance of `505` tokens should
* be displayed to a user as `5,05` (`505 / 10 ** 2`).
*
* Tokens usually opt for a value of 18, imitating the relationship between
* Ether and Wei. This is the value {ERC20} uses, unless {_setupDecimals} is
* called.
*
* NOTE: This information is only used for _display_ purposes: it in
* no way affects any of the arithmetic of the contract, including
* {IERC20-balanceOf} and {IERC20-transfer}.
*/
function decimals() public view returns (uint8) {
return _decimals;
}
/**
* @dev See {IERC20-totalSupply}.
*/
function totalSupply() public view override returns (uint256) {
return _totalSupply;
}
/**
* @dev See {IERC20-balanceOf}.
*/
function balanceOf(address account) public view override returns (uint256) {
return _balances[account];
}
/**
* @dev See {IERC20-transfer}.
*
* Requirements:
*
* - `recipient` cannot be the zero address.
* - the caller must have a balance of at least `amount`.
*/
function transfer(address recipient, uint256 amount) public virtual override returns (bool) {
_transfer(_msgSender(), recipient, amount);
return true;
}
/**
* @dev See {IERC20-allowance}.
*/
function allowance(address owner, address spender) public view virtual override returns (uint256) {
return _allowances[owner][spender];
}
/**
* @dev See {IERC20-approve}.
*
* Requirements:
*
* - `spender` cannot be the zero address.
*/
function approve(address spender, uint256 amount) public virtual override returns (bool) {
_approve(_msgSender(), spender, amount);
return true;
}
/**
* @dev See {IERC20-transferFrom}.
*
* Emits an {Approval} event indicating the updated allowance. This is not
* required by the EIP. See the note at the beginning of {ERC20};
*
* Requirements:
* - `sender` and `recipient` cannot be the zero address.
* - `sender` must have a balance of at least `amount`.
* - the caller must have allowance for ``sender``'s tokens of at least
* `amount`.
*/
function transferFrom(address sender, address recipient, uint256 amount) public virtual override returns (bool) {
_transfer(sender, recipient, amount);
_approve(sender, _msgSender(), _allowances[sender][_msgSender()].sub(amount, "ERC20: transfer amount exceeds allowance"));
return true;
}
/**
* @dev Atomically increases the allowance granted to `spender` by the caller.
*
* This is an alternative to {approve} that can be used as a mitigation for
* problems described in {IERC20-approve}.
*
* Emits an {Approval} event indicating the updated allowance.
*
* Requirements:
*
* - `spender` cannot be the zero address.
*/
function increaseAllowance(address spender, uint256 addedValue) public virtual returns (bool) {
_approve(_msgSender(), spender, _allowances[_msgSender()][spender].add(addedValue));
return true;
}
/**
* @dev Atomically decreases the allowance granted to `spender` by the caller.
*
* This is an alternative to {approve} that can be used as a mitigation for
* problems described in {IERC20-approve}.
*
* Emits an {Approval} event indicating the updated allowance.
*
* Requirements:
*
* - `spender` cannot be the zero address.
* - `spender` must have allowance for the caller of at least
* `subtractedValue`.
*/
function decreaseAllowance(address spender, uint256 subtractedValue) public virtual returns (bool) {
_approve(_msgSender(), spender, _allowances[_msgSender()][spender].sub(subtractedValue, "ERC20: decreased allowance below zero"));
return true;
}
/**
* @dev Moves tokens `amount` from `sender` to `recipient`.
*
* This is internal function is equivalent to {transfer}, and can be used to
* e.g. implement automatic token fees, slashing mechanisms, etc.
*
* Emits a {Transfer} event.
*
* Requirements:
*
* - `sender` cannot be the zero address.
* - `recipient` cannot be the zero address.
* - `sender` must have a balance of at least `amount`.
*/
function _transfer(address sender, address recipient, uint256 amount) internal virtual {
require(sender != address(0), "ERC20: transfer from the zero address");
require(recipient != address(0), "ERC20: transfer to the zero address");
_beforeTokenTransfer(sender, recipient, amount);
_balances[sender] = _balances[sender].sub(amount, "ERC20: transfer amount exceeds balance");
_balances[recipient] = _balances[recipient].add(amount);
emit Transfer(sender, recipient, amount);
}
/** @dev Creates `amount` tokens and assigns them to `account`, increasing
* the total supply.
*
* Emits a {Transfer} event with `from` set to the zero address.
*
* Requirements
*
* - `to` cannot be the zero address.
*/
function _mint(address account, uint256 amount) internal virtual {
require(account != address(0), "ERC20: mint to the zero address");
_beforeTokenTransfer(address(0), account, amount);
_totalSupply = _totalSupply.add(amount);
_balances[account] = _balances[account].add(amount);
emit Transfer(address(0), account, amount);
}
/**
* @dev Destroys `amount` tokens from `account`, reducing the
* total supply.
*
* Emits a {Transfer} event with `to` set to the zero address.
*
* Requirements
*
* - `account` cannot be the zero address.
* - `account` must have at least `amount` tokens.
*/
function _burn(address account, uint256 amount) internal virtual {
require(account != address(0), "ERC20: burn from the zero address");
_beforeTokenTransfer(account, address(0), amount);
_balances[account] = _balances[account].sub(amount, "ERC20: burn amount exceeds balance");
_totalSupply = _totalSupply.sub(amount);
emit Transfer(account, address(0), amount);
}
/**
* @dev Sets `amount` as the allowance of `spender` over the `owner`s tokens.
*
* This is internal function is equivalent to `approve`, and can be used to
* e.g. set automatic allowances for certain subsystems, etc.
*
* Emits an {Approval} event.
*
* Requirements:
*
* - `owner` cannot be the zero address.
* - `spender` cannot be the zero address.
*/
function _approve(address owner, address spender, uint256 amount) internal virtual {
require(owner != address(0), "ERC20: approve from the zero address");
require(spender != address(0), "ERC20: approve to the zero address");
_allowances[owner][spender] = amount;
emit Approval(owner, spender, amount);
}
/**
* @dev Sets {decimals} to a value other than the default one of 18.
*
* WARNING: This function should only be called from the constructor. Most
* applications that interact with token contracts will not expect
* {decimals} to ever change, and may work incorrectly if it does.
*/
function _setupDecimals(uint8 decimals_) internal {
_decimals = decimals_;
}
/**
* @dev Hook that is called before any transfer of tokens. This includes
* minting and burning.
*
* Calling conditions:
*
* - when `from` and `to` are both non-zero, `amount` of ``from``'s tokens
* will be to transferred to `to`.
* - when `from` is zero, `amount` tokens will be minted for `to`.
* - when `to` is zero, `amount` of ``from``'s tokens will be burned.
* - `from` and `to` are never both zero.
*
* To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks].
*/
function _beforeTokenTransfer(address from, address to, uint256 amount) internal virtual { }
}
// File: contracts/SaffronLPBalanceToken.sol
pragma solidity ^0.7.1;
contract SaffronLPBalanceToken is ERC20 {
address public pool_address;
constructor (string memory name, string memory symbol) ERC20(name, symbol) {
// Set pool_address to saffron pool that created token
pool_address = msg.sender;
}
// Allow creating new tranche tokens
function mint(address to, uint256 amount) public {
require(msg.sender == pool_address, "must be pool");
_mint(to, amount);
}
function burn(address account, uint256 amount) public {
require(msg.sender == pool_address, "must be pool");
_burn(account, amount);
}
function set_governance(address to) external {
require(msg.sender == pool_address, "must be pool");
pool_address = to;
}
}
|
[{"inputs":[{"internalType":"string","name":"name","type":"string"},{"internalType":"string","name":"symbol","type":"string"}],"stateMutability":"nonpayable","type":"constructor"},{"anonymous":false,"inputs":[{"indexed":true,"internalType":"address","name":"owner","type":"address"},{"indexed":true,"internalType":"address","name":"spender","type":"address"},{"indexed":false,"internalType":"uint256","name":"value","type":"uint256"}],"name":"Approval","type":"event"},{"anonymous":false,"inputs":[{"indexed":true,"internalType":"address","name":"from","type":"address"},{"indexed":true,"internalType":"address","name":"to","type":"address"},{"indexed":false,"internalType":"uint256","name":"value","type":"uint256"}],"name":"Transfer","type":"event"},{"inputs":[{"internalType":"address","name":"owner","type":"address"},{"internalType":"address","name":"spender","type":"address"}],"name":"allowance","outputs":[{"internalType":"uint256","name":"","type":"uint256"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"address","name":"spender","type":"address"},{"internalType":"uint256","name":"amount","type":"uint256"}],"name":"approve","outputs":[{"internalType":"bool","name":"","type":"bool"}],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"address","name":"account","type":"address"}],"name":"balanceOf","outputs":[{"internalType":"uint256","name":"","type":"uint256"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"address","name":"account","type":"address"},{"internalType":"uint256","name":"amount","type":"uint256"}],"name":"burn","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[],"name":"decimals","outputs":[{"internalType":"uint8","name":"","type":"uint8"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"address","name":"spender","type":"address"},{"internalType":"uint256","name":"subtractedValue","type":"uint256"}],"name":"decreaseAllowance","outputs":[{"internalType":"bool","name":"","type":"bool"}],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"address","name":"spender","type":"address"},{"internalType":"uint256","name":"addedValue","type":"uint256"}],"name":"increaseAllowance","outputs":[{"internalType":"bool","name":"","type":"bool"}],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"address","name":"to","type":"address"},{"internalType":"uint256","name":"amount","type":"uint256"}],"name":"mint","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[],"name":"name","outputs":[{"internalType":"string","name":"","type":"string"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"pool_address","outputs":[{"internalType":"address","name":"","type":"address"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"address","name":"to","type":"address"}],"name":"set_governance","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[],"name":"symbol","outputs":[{"internalType":"string","name":"","type":"string"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"totalSupply","outputs":[{"internalType":"uint256","name":"","type":"uint256"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"address","name":"recipient","type":"address"},{"internalType":"uint256","name":"amount","type":"uint256"}],"name":"transfer","outputs":[{"internalType":"bool","name":"","type":"bool"}],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"address","name":"sender","type":"address"},{"internalType":"address","name":"recipient","type":"address"},{"internalType":"uint256","name":"amount","type":"uint256"}],"name":"transferFrom","outputs":[{"internalType":"bool","name":"","type":"bool"}],"stateMutability":"nonpayable","type":"function"}]
|
v0.7.4+commit.3f05b770
| true
| 99,999
|
000000000000000000000000000000000000000000000000000000000000004000000000000000000000000000000000000000000000000000000000000000a0000000000000000000000000000000000000000000000000000000000000002353616666726f6e204c502065706f6368203133205320444149207072696e636970616c00000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000007534146462d4c5000000000000000000000000000000000000000000000000000
|
Default
|
MIT
| false
|
ipfs://987173ae06a00aaf418e92fd1f57b81c2c1341970dc2d243d753c1adfa0346ca
|
||
UserWallet
|
0x3df996d80b3b1d010678ca183a2f489e7e32eed3
|
Solidity
|
pragma solidity ^0.4.10;
// Copyright 2017 Bittrex
contract AbstractSweeper {
function sweep(address token, uint amount) returns (bool);
function () { throw; }
Controller controller;
function AbstractSweeper(address _controller) {
controller = Controller(_controller);
}
modifier canSweep() {
if (msg.sender != controller.authorizedCaller() && msg.sender != controller.owner()) throw;
if (controller.halted()) throw;
_;
}
}
contract Token {
function balanceOf(address a) returns (uint) {
(a);
return 0;
}
function transfer(address a, uint val) returns (bool) {
(a);
(val);
return false;
}
}
contract DefaultSweeper is AbstractSweeper {
function DefaultSweeper(address controller)
AbstractSweeper(controller) {}
function sweep(address _token, uint _amount)
canSweep
returns (bool) {
bool success = false;
address destination = controller.destination();
if (_token != address(0)) {
Token token = Token(_token);
uint amount = _amount;
if (amount > token.balanceOf(this)) {
return false;
}
success = token.transfer(destination, amount);
}
else {
uint amountInWei = _amount;
if (amountInWei > this.balance) {
return false;
}
success = destination.send(amountInWei);
}
if (success) {
controller.logSweep(this, destination, _token, _amount);
}
return success;
}
}
contract UserWallet {
AbstractSweeperList sweeperList;
function UserWallet(address _sweeperlist) {
sweeperList = AbstractSweeperList(_sweeperlist);
}
function () public payable { }
function tokenFallback(address _from, uint _value, bytes _data) {
(_from);
(_value);
(_data);
}
function sweep(address _token, uint _amount)
returns (bool) {
(_amount);
return sweeperList.sweeperOf(_token).delegatecall(msg.data);
}
}
contract AbstractSweeperList {
function sweeperOf(address _token) returns (address);
}
contract Controller is AbstractSweeperList {
address public owner;
address public authorizedCaller;
address public destination;
bool public halted;
event LogNewWallet(address receiver);
event LogSweep(address indexed from, address indexed to, address indexed token, uint amount);
modifier onlyOwner() {
if (msg.sender != owner) throw;
_;
}
modifier onlyAuthorizedCaller() {
if (msg.sender != authorizedCaller) throw;
_;
}
modifier onlyAdmins() {
if (msg.sender != authorizedCaller && msg.sender != owner) throw;
_;
}
function Controller()
{
owner = msg.sender;
destination = msg.sender;
authorizedCaller = msg.sender;
}
function changeAuthorizedCaller(address _newCaller) onlyOwner {
authorizedCaller = _newCaller;
}
function changeDestination(address _dest) onlyOwner {
destination = _dest;
}
function changeOwner(address _owner) onlyOwner {
owner = _owner;
}
function makeWallet() onlyAdmins returns (address wallet) {
wallet = address(new UserWallet(this));
LogNewWallet(wallet);
}
function halt() onlyAdmins {
halted = true;
}
function start() onlyOwner {
halted = false;
}
address public defaultSweeper = address(new DefaultSweeper(this));
mapping (address => address) sweepers;
function addSweeper(address _token, address _sweeper) onlyOwner {
sweepers[_token] = _sweeper;
}
function sweeperOf(address _token) returns (address) {
address sweeper = sweepers[_token];
if (sweeper == 0) sweeper = defaultSweeper;
return sweeper;
}
function logSweep(address from, address to, address token, uint amount) {
LogSweep(from, to, token, amount);
}
}
|
[{"constant":false,"inputs":[{"name":"_token","type":"address"},{"name":"_amount","type":"uint256"}],"name":"sweep","outputs":[{"name":"","type":"bool"}],"payable":false,"type":"function"},{"constant":false,"inputs":[{"name":"_from","type":"address"},{"name":"_value","type":"uint256"},{"name":"_data","type":"bytes"}],"name":"tokenFallback","outputs":[],"payable":false,"type":"function"},{"inputs":[{"name":"_sweeperlist","type":"address"}],"payable":false,"type":"constructor"},{"payable":true,"type":"fallback"}]
|
v0.4.11+commit.68ef5810
| true
| 200
|
000000000000000000000000a3C1E324CA1ce40db73eD6026c4A177F099B5770
|
Default
| false
|
bzzr://4cdd69fdcf3cf6cbee9677fe380fa5f044048aa9e060ec5619a21ca5a5bd4cd1
|
|||
ReversibleDemo
|
0xf3ce598921fb6ecd758c0803cdfc83e447124a30
|
Solidity
|
// `interface` would make a nice keyword ;)
contract TheDaoHardForkOracle {
// `ran()` manually verified true on both ETH and ETC chains
function forked() constant returns (bool);
}
// demostrates calling own function in a "reversible" manner
/* important lines are marked by multi-line comments */
contract ReversibleDemo {
// counters (all public to simplify inspection)
uint public numcalls;
uint public numcallsinternal;
uint public numfails;
uint public numsuccesses;
address owner;
// needed for "naive" and "oraclized" checks
address constant withdrawdaoaddr = 0xbf4ed7b27f1d666546e30d74d50d173d20bca754;
TheDaoHardForkOracle oracle = TheDaoHardForkOracle(0xe8e506306ddb78ee38c9b0d86c257bd97c2536b3);
event logCall(uint indexed _numcalls,
uint indexed _numfails,
uint indexed _numsuccesses);
modifier onlyOwner { if (msg.sender != owner) throw; _ }
modifier onlyThis { if (msg.sender != address(this)) throw; _ }
// constructor (setting `owner` allows later termination)
function ReversibleDemo() { owner = msg.sender; }
/* external: increments stack height */
/* onlyThis: prevent actual external calling */
function sendIfNotForked() external onlyThis returns (bool) {
numcallsinternal++;
/* naive check for "is this the classic chain" */
// guaranteed `true`: enough has been withdrawn already
// three million ------> 3'000'000
if (withdrawdaoaddr.balance < 3000000 ether) {
/* intentionally not checking return value */
owner.send(42);
}
/* "reverse" if it's actually the HF chain */
if (oracle.forked()) throw;
// not exactly a "success": send() could have failed on classic
return true;
}
// accepts value transfers
function doCall(uint _gas) onlyOwner {
numcalls++;
if (!this.sendIfNotForked.gas(_gas)()) {
numfails++;
}
else {
numsuccesses++;
}
logCall(numcalls, numfails, numsuccesses);
}
function selfDestruct() onlyOwner {
selfdestruct(owner);
}
// accepts value trasfers, but does nothing
function() {}
}
|
[{"constant":true,"inputs":[],"name":"numsuccesses","outputs":[{"name":"","type":"uint256"}],"type":"function"},{"constant":true,"inputs":[],"name":"numfails","outputs":[{"name":"","type":"uint256"}],"type":"function"},{"constant":true,"inputs":[],"name":"numcalls","outputs":[{"name":"","type":"uint256"}],"type":"function"},{"constant":true,"inputs":[],"name":"numcallsinternal","outputs":[{"name":"","type":"uint256"}],"type":"function"},{"constant":false,"inputs":[],"name":"sendIfNotForked","outputs":[{"name":"","type":"bool"}],"type":"function"},{"constant":false,"inputs":[],"name":"selfDestruct","outputs":[],"type":"function"},{"constant":false,"inputs":[{"name":"_gas","type":"uint256"}],"name":"doCall","outputs":[],"type":"function"},{"inputs":[],"type":"constructor"},{"anonymous":false,"inputs":[{"indexed":true,"name":"_numcalls","type":"uint256"},{"indexed":true,"name":"_numfails","type":"uint256"},{"indexed":true,"name":"_numsuccesses","type":"uint256"}],"name":"logCall","type":"event"}]
|
v0.3.5-2016-08-07-f7af7de
| true
| 200
|
Default
| false
| |||||
Forwarder
|
0xe9d2aeae563fc487684b4c1fb5847cd148ad0887
|
Solidity
|
pragma solidity ^0.4.14;
/**
* Contract that exposes the needed erc20 token functions
*/
contract ERC20Interface {
// Send _value amount of tokens to address _to
function transfer(address _to, uint256 _value) returns (bool success);
// Get the account balance of another account with address _owner
function balanceOf(address _owner) constant returns (uint256 balance);
}
/**
* Contract that will forward any incoming Ether to its creator
*/
contract Forwarder {
// Address to which any funds sent to this contract will be forwarded
address public parentAddress;
event ForwarderDeposited(address from, uint value, bytes data);
event TokensFlushed(
address tokenContractAddress, // The contract address of the token
uint value // Amount of token sent
);
/**
* Create the contract, and set the destination address to that of the creator
*/
function Forwarder() {
parentAddress = msg.sender;
}
/**
* Modifier that will execute internal code block only if the sender is a parent of the forwarder contract
*/
modifier onlyParent {
if (msg.sender != parentAddress) {
throw;
}
_;
}
/**
* Default function; Gets called when Ether is deposited, and forwards it to the destination address
*/
function() payable {
if (!parentAddress.call.value(msg.value)(msg.data))
throw;
// Fire off the deposited event if we can forward it
ForwarderDeposited(msg.sender, msg.value, msg.data);
}
/**
* Execute a token transfer of the full balance from the forwarder token to the main wallet contract
* @param tokenContractAddress the address of the erc20 token contract
*/
function flushTokens(address tokenContractAddress) onlyParent {
ERC20Interface instance = ERC20Interface(tokenContractAddress);
var forwarderAddress = address(this);
var forwarderBalance = instance.balanceOf(forwarderAddress);
if (forwarderBalance == 0) {
return;
}
if (!instance.transfer(parentAddress, forwarderBalance)) {
throw;
}
TokensFlushed(tokenContractAddress, forwarderBalance);
}
/**
* It is possible that funds were sent to this address before the contract was deployed.
* We can flush those funds to the destination address.
*/
function flush() {
if (!parentAddress.call.value(this.balance)())
throw;
}
}
/**
* Basic multi-signer wallet designed for use in a co-signing environment where 2 signatures are required to move funds.
* Typically used in a 2-of-3 signing configuration. Uses ecrecover to allow for 2 signatures in a single transaction.
*/
contract WalletSimple {
// Events
event Deposited(address from, uint value, bytes data);
event SafeModeActivated(address msgSender);
event Transacted(
address msgSender, // Address of the sender of the message initiating the transaction
address otherSigner, // Address of the signer (second signature) used to initiate the transaction
bytes32 operation, // Operation hash (sha3 of toAddress, value, data, expireTime, sequenceId)
address toAddress, // The address the transaction was sent to
uint value, // Amount of Wei sent to the address
bytes data // Data sent when invoking the transaction
);
event TokenTransacted(
address msgSender, // Address of the sender of the message initiating the transaction
address otherSigner, // Address of the signer (second signature) used to initiate the transaction
bytes32 operation, // Operation hash (sha3 of toAddress, value, tokenContractAddress, expireTime, sequenceId)
address toAddress, // The address the transaction was sent to
uint value, // Amount of token sent
address tokenContractAddress // The contract address of the token
);
// Public fields
address[] public signers; // The addresses that can co-sign transactions on the wallet
bool public safeMode = false; // When active, wallet may only send to signer addresses
// Internal fields
uint constant SEQUENCE_ID_WINDOW_SIZE = 10;
uint[10] recentSequenceIds;
/**
* Modifier that will execute internal code block only if the sender is an authorized signer on this wallet
*/
modifier onlysigner {
if (!isSigner(msg.sender)) {
throw;
}
_;
}
/**
* Set up a simple multi-sig wallet by specifying the signers allowed to be used on this wallet.
* 2 signers will be required to send a transaction from this wallet.
* Note: The sender is NOT automatically added to the list of signers.
* Signers CANNOT be changed once they are set
*
* @param allowedSigners An array of signers on the wallet
*/
function WalletSimple(address[] allowedSigners) {
if (allowedSigners.length != 3) {
// Invalid number of signers
throw;
}
signers = allowedSigners;
}
/**
* Gets called when a transaction is received without calling a method
*/
function() payable {
if (msg.value > 0) {
// Fire deposited event if we are receiving funds
Deposited(msg.sender, msg.value, msg.data);
}
}
/**
* Create a new contract (and also address) that forwards funds to this contract
* returns address of newly created forwarder address
*/
function createForwarder() onlysigner returns (address) {
return new Forwarder();
}
/**
* Execute a multi-signature transaction from this wallet using 2 signers: one from msg.sender and the other from ecrecover.
* The signature is a signed form (using eth.sign) of tightly packed toAddress, value, data, expireTime and sequenceId
* Sequence IDs are numbers starting from 1. They are used to prevent replay attacks and may not be repeated.
*
* @param toAddress the destination address to send an outgoing transaction
* @param value the amount in Wei to be sent
* @param data the data to send to the toAddress when invoking the transaction
* @param expireTime the number of seconds since 1970 for which this transaction is valid
* @param sequenceId the unique sequence id obtainable from getNextSequenceId
* @param signature the result of eth.sign on the operationHash sha3(toAddress, value, data, expireTime, sequenceId)
*/
function sendMultiSig(address toAddress, uint value, bytes data, uint expireTime, uint sequenceId, bytes signature) onlysigner {
// Verify the other signer
var operationHash = sha3("ETHER", toAddress, value, data, expireTime, sequenceId);
var otherSigner = verifyMultiSig(toAddress, operationHash, signature, expireTime, sequenceId);
// Success, send the transaction
if (!(toAddress.call.value(value)(data))) {
// Failed executing transaction
throw;
}
Transacted(msg.sender, otherSigner, operationHash, toAddress, value, data);
}
/**
* Execute a multi-signature token transfer from this wallet using 2 signers: one from msg.sender and the other from ecrecover.
* The signature is a signed form (using eth.sign) of tightly packed toAddress, value, tokenContractAddress, expireTime and sequenceId
* Sequence IDs are numbers starting from 1. They are used to prevent replay attacks and may not be repeated.
*
* @param toAddress the destination address to send an outgoing transaction
* @param value the amount in tokens to be sent
* @param tokenContractAddress the address of the erc20 token contract
* @param expireTime the number of seconds since 1970 for which this transaction is valid
* @param sequenceId the unique sequence id obtainable from getNextSequenceId
* @param signature the result of eth.sign on the operationHash sha3(toAddress, value, tokenContractAddress, expireTime, sequenceId)
*/
function sendMultiSigToken(address toAddress, uint value, address tokenContractAddress, uint expireTime, uint sequenceId, bytes signature) onlysigner {
// Verify the other signer
var operationHash = sha3("ERC20", toAddress, value, tokenContractAddress, expireTime, sequenceId);
var otherSigner = verifyMultiSig(toAddress, operationHash, signature, expireTime, sequenceId);
ERC20Interface instance = ERC20Interface(tokenContractAddress);
if (!instance.transfer(toAddress, value)) {
throw;
}
TokenTransacted(msg.sender, otherSigner, operationHash, toAddress, value, tokenContractAddress);
}
/**
* Execute a token flush from one of the forwarder addresses. This transfer needs only a single signature and can be done by any signer
*
* @param forwarderAddress the address of the forwarder address to flush the tokens from
* @param tokenContractAddress the address of the erc20 token contract
*/
function flushForwarderTokens(address forwarderAddress, address tokenContractAddress) onlysigner {
Forwarder forwarder = Forwarder(forwarderAddress);
forwarder.flushTokens(tokenContractAddress);
}
/**
* Do common multisig verification for both eth sends and erc20token transfers
*
* @param toAddress the destination address to send an outgoing transaction
* @param operationHash the sha3 of the toAddress, value, data/tokenContractAddress and expireTime
* @param signature the tightly packed signature of r, s, and v as an array of 65 bytes (returned by eth.sign)
* @param expireTime the number of seconds since 1970 for which this transaction is valid
* @param sequenceId the unique sequence id obtainable from getNextSequenceId
* returns address of the address to send tokens or eth to
*/
function verifyMultiSig(address toAddress, bytes32 operationHash, bytes signature, uint expireTime, uint sequenceId) private returns (address) {
var otherSigner = recoverAddressFromSignature(operationHash, signature);
// Verify if we are in safe mode. In safe mode, the wallet can only send to signers
if (safeMode && !isSigner(toAddress)) {
// We are in safe mode and the toAddress is not a signer. Disallow!
throw;
}
// Verify that the transaction has not expired
if (expireTime < block.timestamp) {
// Transaction expired
throw;
}
// Try to insert the sequence ID. Will throw if the sequence id was invalid
tryInsertSequenceId(sequenceId);
if (!isSigner(otherSigner)) {
// Other signer not on this wallet or operation does not match arguments
throw;
}
if (otherSigner == msg.sender) {
// Cannot approve own transaction
throw;
}
return otherSigner;
}
/**
* Irrevocably puts contract into safe mode. When in this mode, transactions may only be sent to signing addresses.
*/
function activateSafeMode() onlysigner {
safeMode = true;
SafeModeActivated(msg.sender);
}
/**
* Determine if an address is a signer on this wallet
* @param signer address to check
* returns boolean indicating whether address is signer or not
*/
function isSigner(address signer) returns (bool) {
// Iterate through all signers on the wallet and
for (uint i = 0; i < signers.length; i++) {
if (signers[i] == signer) {
return true;
}
}
return false;
}
/**
* Gets the second signer's address using ecrecover
* @param operationHash the sha3 of the toAddress, value, data/tokenContractAddress and expireTime
* @param signature the tightly packed signature of r, s, and v as an array of 65 bytes (returned by eth.sign)
* returns address recovered from the signature
*/
function recoverAddressFromSignature(bytes32 operationHash, bytes signature) private returns (address) {
if (signature.length != 65) {
throw;
}
// We need to unpack the signature, which is given as an array of 65 bytes (from eth.sign)
bytes32 r;
bytes32 s;
uint8 v;
assembly {
r := mload(add(signature, 32))
s := mload(add(signature, 64))
v := and(mload(add(signature, 65)), 255)
}
if (v < 27) {
v += 27; // Ethereum versions are 27 or 28 as opposed to 0 or 1 which is submitted by some signing libs
}
return ecrecover(operationHash, v, r, s);
}
/**
* Verify that the sequence id has not been used before and inserts it. Throws if the sequence ID was not accepted.
* We collect a window of up to 10 recent sequence ids, and allow any sequence id that is not in the window and
* greater than the minimum element in the window.
* @param sequenceId to insert into array of stored ids
*/
function tryInsertSequenceId(uint sequenceId) onlysigner private {
// Keep a pointer to the lowest value element in the window
uint lowestValueIndex = 0;
for (uint i = 0; i < SEQUENCE_ID_WINDOW_SIZE; i++) {
if (recentSequenceIds[i] == sequenceId) {
// This sequence ID has been used before. Disallow!
throw;
}
if (recentSequenceIds[i] < recentSequenceIds[lowestValueIndex]) {
lowestValueIndex = i;
}
}
if (sequenceId < recentSequenceIds[lowestValueIndex]) {
// The sequence ID being used is lower than the lowest value in the window
// so we cannot accept it as it may have been used before
throw;
}
if (sequenceId > (recentSequenceIds[lowestValueIndex] + 10000)) {
// Block sequence IDs which are much higher than the lowest value
// This prevents people blocking the contract by using very large sequence IDs quickly
throw;
}
recentSequenceIds[lowestValueIndex] = sequenceId;
}
/**
* Gets the next available sequence ID for signing when using executeAndConfirm
* returns the sequenceId one higher than the highest currently stored
*/
function getNextSequenceId() returns (uint) {
uint highestSequenceId = 0;
for (uint i = 0; i < SEQUENCE_ID_WINDOW_SIZE; i++) {
if (recentSequenceIds[i] > highestSequenceId) {
highestSequenceId = recentSequenceIds[i];
}
}
return highestSequenceId + 1;
}
}
|
[{"constant":true,"inputs":[],"name":"parentAddress","outputs":[{"name":"","type":"address"}],"payable":false,"type":"function"},{"constant":false,"inputs":[{"name":"tokenContractAddress","type":"address"}],"name":"flushTokens","outputs":[],"payable":false,"type":"function"},{"constant":false,"inputs":[],"name":"flush","outputs":[],"payable":false,"type":"function"},{"inputs":[],"payable":false,"type":"constructor"},{"payable":true,"type":"fallback"},{"anonymous":false,"inputs":[{"indexed":false,"name":"from","type":"address"},{"indexed":false,"name":"value","type":"uint256"},{"indexed":false,"name":"data","type":"bytes"}],"name":"ForwarderDeposited","type":"event"},{"anonymous":false,"inputs":[{"indexed":false,"name":"tokenContractAddress","type":"address"},{"indexed":false,"name":"value","type":"uint256"}],"name":"TokensFlushed","type":"event"}]
|
v0.4.16-nightly.2017.8.11+commit.c84de7fa
| true
| 200
|
Default
| false
|
bzzr://d0f8838ba17108a895d34ae8ef3bff4e0dc9d639c3c51921fee1d17eaa803721
|
||||
UserWallet
|
0x69048dba3eac9d8490bd66a3d66cc00acb75fe7a
|
Solidity
|
pragma solidity ^0.4.10;
// Copyright 2017 Bittrex
contract AbstractSweeper {
function sweep(address token, uint amount) returns (bool);
function () { throw; }
Controller controller;
function AbstractSweeper(address _controller) {
controller = Controller(_controller);
}
modifier canSweep() {
if (msg.sender != controller.authorizedCaller() && msg.sender != controller.owner()) throw;
if (controller.halted()) throw;
_;
}
}
contract Token {
function balanceOf(address a) returns (uint) {
(a);
return 0;
}
function transfer(address a, uint val) returns (bool) {
(a);
(val);
return false;
}
}
contract DefaultSweeper is AbstractSweeper {
function DefaultSweeper(address controller)
AbstractSweeper(controller) {}
function sweep(address _token, uint _amount)
canSweep
returns (bool) {
bool success = false;
address destination = controller.destination();
if (_token != address(0)) {
Token token = Token(_token);
uint amount = _amount;
if (amount > token.balanceOf(this)) {
return false;
}
success = token.transfer(destination, amount);
}
else {
uint amountInWei = _amount;
if (amountInWei > this.balance) {
return false;
}
success = destination.send(amountInWei);
}
if (success) {
controller.logSweep(this, destination, _token, _amount);
}
return success;
}
}
contract UserWallet {
AbstractSweeperList sweeperList;
function UserWallet(address _sweeperlist) {
sweeperList = AbstractSweeperList(_sweeperlist);
}
function () public payable { }
function tokenFallback(address _from, uint _value, bytes _data) {
(_from);
(_value);
(_data);
}
function sweep(address _token, uint _amount)
returns (bool) {
(_amount);
return sweeperList.sweeperOf(_token).delegatecall(msg.data);
}
}
contract AbstractSweeperList {
function sweeperOf(address _token) returns (address);
}
contract Controller is AbstractSweeperList {
address public owner;
address public authorizedCaller;
address public destination;
bool public halted;
event LogNewWallet(address receiver);
event LogSweep(address indexed from, address indexed to, address indexed token, uint amount);
modifier onlyOwner() {
if (msg.sender != owner) throw;
_;
}
modifier onlyAuthorizedCaller() {
if (msg.sender != authorizedCaller) throw;
_;
}
modifier onlyAdmins() {
if (msg.sender != authorizedCaller && msg.sender != owner) throw;
_;
}
function Controller()
{
owner = msg.sender;
destination = msg.sender;
authorizedCaller = msg.sender;
}
function changeAuthorizedCaller(address _newCaller) onlyOwner {
authorizedCaller = _newCaller;
}
function changeDestination(address _dest) onlyOwner {
destination = _dest;
}
function changeOwner(address _owner) onlyOwner {
owner = _owner;
}
function makeWallet() onlyAdmins returns (address wallet) {
wallet = address(new UserWallet(this));
LogNewWallet(wallet);
}
function halt() onlyAdmins {
halted = true;
}
function start() onlyOwner {
halted = false;
}
address public defaultSweeper = address(new DefaultSweeper(this));
mapping (address => address) sweepers;
function addSweeper(address _token, address _sweeper) onlyOwner {
sweepers[_token] = _sweeper;
}
function sweeperOf(address _token) returns (address) {
address sweeper = sweepers[_token];
if (sweeper == 0) sweeper = defaultSweeper;
return sweeper;
}
function logSweep(address from, address to, address token, uint amount) {
LogSweep(from, to, token, amount);
}
}
|
[{"constant":false,"inputs":[{"name":"_token","type":"address"},{"name":"_amount","type":"uint256"}],"name":"sweep","outputs":[{"name":"","type":"bool"}],"payable":false,"type":"function"},{"constant":false,"inputs":[{"name":"_from","type":"address"},{"name":"_value","type":"uint256"},{"name":"_data","type":"bytes"}],"name":"tokenFallback","outputs":[],"payable":false,"type":"function"},{"inputs":[{"name":"_sweeperlist","type":"address"}],"payable":false,"type":"constructor"},{"payable":true,"type":"fallback"}]
|
v0.4.11+commit.68ef5810
| true
| 200
|
000000000000000000000000a3C1E324CA1ce40db73eD6026c4A177F099B5770
|
Default
| false
|
bzzr://4cdd69fdcf3cf6cbee9677fe380fa5f044048aa9e060ec5619a21ca5a5bd4cd1
|
|||
TokenMintERC20Token
|
0x18d28b85dee46db2c60aa92c1392971fef177362
|
Solidity
|
// File: contracts\open-zeppelin-contracts\token\ERC20\IERC20.sol
pragma solidity ^0.5.0;
/**
* @title ERC20 interface
* @dev see https://github.com/ethereum/EIPs/issues/20
*/
interface IERC20 {
function transfer(address to, uint256 value) external returns (bool);
function approve(address spender, uint256 value) external returns (bool);
function transferFrom(address from, address to, uint256 value) external returns (bool);
function totalSupply() external view returns (uint256);
function balanceOf(address who) external view returns (uint256);
function allowance(address owner, address spender) external view returns (uint256);
event Transfer(address indexed from, address indexed to, uint256 value);
event Approval(address indexed owner, address indexed spender, uint256 value);
}
// File: contracts\open-zeppelin-contracts\math\SafeMath.sol
pragma solidity ^0.5.0;
/**
* @title SafeMath
* @dev Unsigned math operations with safety checks that revert on error
*/
library SafeMath {
/**
* @dev Multiplies two unsigned integers, reverts on overflow.
*/
function mul(uint256 a, uint256 b) internal pure returns (uint256) {
// Gas optimization: this is cheaper than requiring 'a' not being zero, but the
// benefit is lost if 'b' is also tested.
// See: https://github.com/OpenZeppelin/openzeppelin-solidity/pull/522
if (a == 0) {
return 0;
}
uint256 c = a * b;
require(c / a == b);
return c;
}
/**
* @dev Integer division of two unsigned integers truncating the quotient, reverts on division by zero.
*/
function div(uint256 a, uint256 b) internal pure returns (uint256) {
// Solidity only automatically asserts when dividing by 0
require(b > 0);
uint256 c = a / b;
// assert(a == b * c + a % b); // There is no case in which this doesn't hold
return c;
}
/**
* @dev Subtracts two unsigned integers, reverts on overflow (i.e. if subtrahend is greater than minuend).
*/
function sub(uint256 a, uint256 b) internal pure returns (uint256) {
require(b <= a);
uint256 c = a - b;
return c;
}
/**
* @dev Adds two unsigned integers, reverts on overflow.
*/
function add(uint256 a, uint256 b) internal pure returns (uint256) {
uint256 c = a + b;
require(c >= a);
return c;
}
/**
* @dev Divides two unsigned integers and returns the remainder (unsigned integer modulo),
* reverts when dividing by zero.
*/
function mod(uint256 a, uint256 b) internal pure returns (uint256) {
require(b != 0);
return a % b;
}
}
// File: contracts\open-zeppelin-contracts\token\ERC20\ERC20.sol
pragma solidity ^0.5.0;
/**
* @title Standard ERC20 token
*
* @dev Implementation of the basic standard token.
* https://github.com/ethereum/EIPs/blob/master/EIPS/eip-20.md
* Originally based on code by FirstBlood:
* https://github.com/Firstbloodio/token/blob/master/smart_contract/FirstBloodToken.sol
*
* This implementation emits additional Approval events, allowing applications to reconstruct the allowance status for
* all accounts just by listening to said events. Note that this isn't required by the specification, and other
* compliant implementations may not do it.
*/
contract ERC20 is IERC20 {
using SafeMath for uint256;
mapping (address => uint256) private _balances;
mapping (address => mapping (address => uint256)) private _allowed;
uint256 private _totalSupply;
/**
* @dev Total number of tokens in existence
*/
function totalSupply() public view returns (uint256) {
return _totalSupply;
}
/**
* @dev Gets the balance of the specified address.
* @param owner The address to query the balance of.
* @return An uint256 representing the amount owned by the passed address.
*/
function balanceOf(address owner) public view returns (uint256) {
return _balances[owner];
}
/**
* @dev Function to check the amount of tokens that an owner allowed to a spender.
* @param owner address The address which owns the funds.
* @param spender address The address which will spend the funds.
* @return A uint256 specifying the amount of tokens still available for the spender.
*/
function allowance(address owner, address spender) public view returns (uint256) {
return _allowed[owner][spender];
}
/**
* @dev Transfer token for a specified address
* @param to The address to transfer to.
* @param value The amount to be transferred.
*/
function transfer(address to, uint256 value) public returns (bool) {
_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_[_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_[_spender] == 0. To decrement
* allowed value is better to use this function to avoid 2 calls (and wait until
* the first transaction is mined)
* From MonolithDAO Token.sol
* Emits an Approval event.
* @param spender The address which will spend the funds.
* @param subtractedValue The amount of tokens to decrease the allowance by.
*/
function decreaseAllowance(address spender, uint256 subtractedValue) public returns (bool) {
_approve(msg.sender, spender, _allowed[msg.sender][spender].sub(subtractedValue));
return true;
}
/**
* @dev Transfer token for a specified addresses
* @param from The address to transfer from.
* @param to The address to transfer to.
* @param value The amount to be transferred.
*/
function _transfer(address from, address to, uint256 value) internal {
require(to != address(0));
_balances[from] = _balances[from].sub(value);
_balances[to] = _balances[to].add(value);
emit Transfer(from, to, value);
}
/**
* @dev Internal function that mints an amount of the token and assigns it to
* an account. This encapsulates the modification of balances such that the
* proper events are emitted.
* @param account The account that will receive the created tokens.
* @param value The amount that will be created.
*/
function _mint(address account, uint256 value) internal {
require(account != address(0));
_totalSupply = _totalSupply.add(value);
_balances[account] = _balances[account].add(value);
emit Transfer(address(0), account, value);
}
/**
* @dev Internal function that burns an amount of the token of a given
* account.
* @param account The account whose tokens will be burnt.
* @param value The amount that will be burnt.
*/
function _burn(address account, uint256 value) internal {
require(account != address(0));
_totalSupply = _totalSupply.sub(value);
_balances[account] = _balances[account].sub(value);
emit Transfer(account, address(0), value);
}
/**
* @dev Approve an address to spend another addresses' tokens.
* @param owner The address that owns the tokens.
* @param spender The address that will spend the tokens.
* @param value The number of tokens that can be spent.
*/
function _approve(address owner, address spender, uint256 value) internal {
require(spender != address(0));
require(owner != address(0));
_allowed[owner][spender] = value;
emit Approval(owner, spender, value);
}
/**
* @dev Internal function that burns an amount of the token of a given
* account, deducting from the sender's allowance for said account. Uses the
* internal burn function.
* Emits an Approval event (reflecting the reduced allowance).
* @param account The account whose tokens will be burnt.
* @param value The amount that will be burnt.
*/
function _burnFrom(address account, uint256 value) internal {
_burn(account, value);
_approve(account, msg.sender, _allowed[account][msg.sender].sub(value));
}
}
// File: contracts\ERC20\TokenMintERC20Token.sol
pragma solidity ^0.5.0;
/**
* @title TokenMintERC20Token
* @author TokenMint (visit https://tokenmint.io)
*
* @dev Standard ERC20 token with optional functions implemented.
* For full specification of ERC-20 standard see:
* https://github.com/ethereum/EIPs/blob/master/EIPS/eip-20.md
*/
contract TokenMintERC20Token is ERC20 {
string private _name;
string private _symbol;
uint8 private _decimals;
constructor(string memory name, string memory symbol, uint8 decimals, uint256 totalSupply, address payable feeReceiver, address tokenOwnerAddress) public payable {
_name = name;
_symbol = symbol;
_decimals = decimals;
// set tokenOwnerAddress as owner of all tokens
_mint(tokenOwnerAddress, totalSupply);
// pay the service fee for contract deployment
feeReceiver.transfer(msg.value);
}
// optional functions from ERC20 stardard
/**
* @return the name of the token.
*/
function name() public view returns (string memory) {
return _name;
}
/**
* @return the symbol of the token.
*/
function symbol() public view returns (string memory) {
return _symbol;
}
/**
* @return the number of decimals of the token.
*/
function decimals() public view returns (uint8) {
return _decimals;
}
}
|
[{"constant":true,"inputs":[],"name":"name","outputs":[{"name":"","type":"string"}],"payable":false,"stateMutability":"view","type":"function"},{"constant":false,"inputs":[{"name":"spender","type":"address"},{"name":"value","type":"uint256"}],"name":"approve","outputs":[{"name":"","type":"bool"}],"payable":false,"stateMutability":"nonpayable","type":"function"},{"constant":true,"inputs":[],"name":"totalSupply","outputs":[{"name":"","type":"uint256"}],"payable":false,"stateMutability":"view","type":"function"},{"constant":false,"inputs":[{"name":"from","type":"address"},{"name":"to","type":"address"},{"name":"value","type":"uint256"}],"name":"transferFrom","outputs":[{"name":"","type":"bool"}],"payable":false,"stateMutability":"nonpayable","type":"function"},{"constant":true,"inputs":[],"name":"decimals","outputs":[{"name":"","type":"uint8"}],"payable":false,"stateMutability":"view","type":"function"},{"constant":false,"inputs":[{"name":"spender","type":"address"},{"name":"addedValue","type":"uint256"}],"name":"increaseAllowance","outputs":[{"name":"","type":"bool"}],"payable":false,"stateMutability":"nonpayable","type":"function"},{"constant":true,"inputs":[{"name":"owner","type":"address"}],"name":"balanceOf","outputs":[{"name":"","type":"uint256"}],"payable":false,"stateMutability":"view","type":"function"},{"constant":true,"inputs":[],"name":"symbol","outputs":[{"name":"","type":"string"}],"payable":false,"stateMutability":"view","type":"function"},{"constant":false,"inputs":[{"name":"spender","type":"address"},{"name":"subtractedValue","type":"uint256"}],"name":"decreaseAllowance","outputs":[{"name":"","type":"bool"}],"payable":false,"stateMutability":"nonpayable","type":"function"},{"constant":false,"inputs":[{"name":"to","type":"address"},{"name":"value","type":"uint256"}],"name":"transfer","outputs":[{"name":"","type":"bool"}],"payable":false,"stateMutability":"nonpayable","type":"function"},{"constant":true,"inputs":[{"name":"owner","type":"address"},{"name":"spender","type":"address"}],"name":"allowance","outputs":[{"name":"","type":"uint256"}],"payable":false,"stateMutability":"view","type":"function"},{"inputs":[{"name":"name","type":"string"},{"name":"symbol","type":"string"},{"name":"decimals","type":"uint8"},{"name":"totalSupply","type":"uint256"},{"name":"feeReceiver","type":"address"},{"name":"tokenOwnerAddress","type":"address"}],"payable":true,"stateMutability":"payable","type":"constructor"},{"anonymous":false,"inputs":[{"indexed":true,"name":"from","type":"address"},{"indexed":true,"name":"to","type":"address"},{"indexed":false,"name":"value","type":"uint256"}],"name":"Transfer","type":"event"},{"anonymous":false,"inputs":[{"indexed":true,"name":"owner","type":"address"},{"indexed":true,"name":"spender","type":"address"},{"indexed":false,"name":"value","type":"uint256"}],"name":"Approval","type":"event"}]
|
v0.5.0+commit.1d4f565a
| false
| 200
|
00000000000000000000000000000000000000000000000000000000000000c000000000000000000000000000000000000000000000000000000000000001000000000000000000000000000000000000000000000000000000000000000012000000000000000000000000000000000000000002e87669c308736a040000000000000000000000000000006603cb70464ca51481d4edbb3b927f66f53f4f420000000000000000000000006eca6d64c4146ef43a771a207afe93a9b93609ea000000000000000000000000000000000000000000000000000000000000000b427572676572546f6b656e00000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000034252470000000000000000000000000000000000000000000000000000000000
|
Default
| false
|
bzzr://ecca2e71e781ae786e694fe0e6d93d213af6a0d2b35dd9f341359c517abdca1b
|
|||
UserWallet
|
0x3f646964a86be0b7f1a22e8af10e575fdb6cea53
|
Solidity
|
pragma solidity ^0.4.10;
// Copyright 2017 Bittrex
contract AbstractSweeper {
function sweep(address token, uint amount) returns (bool);
function () { throw; }
Controller controller;
function AbstractSweeper(address _controller) {
controller = Controller(_controller);
}
modifier canSweep() {
if (msg.sender != controller.authorizedCaller() && msg.sender != controller.owner()) throw;
if (controller.halted()) throw;
_;
}
}
contract Token {
function balanceOf(address a) returns (uint) {
(a);
return 0;
}
function transfer(address a, uint val) returns (bool) {
(a);
(val);
return false;
}
}
contract DefaultSweeper is AbstractSweeper {
function DefaultSweeper(address controller)
AbstractSweeper(controller) {}
function sweep(address _token, uint _amount)
canSweep
returns (bool) {
bool success = false;
address destination = controller.destination();
if (_token != address(0)) {
Token token = Token(_token);
uint amount = _amount;
if (amount > token.balanceOf(this)) {
return false;
}
success = token.transfer(destination, amount);
}
else {
uint amountInWei = _amount;
if (amountInWei > this.balance) {
return false;
}
success = destination.send(amountInWei);
}
if (success) {
controller.logSweep(this, destination, _token, _amount);
}
return success;
}
}
contract UserWallet {
AbstractSweeperList sweeperList;
function UserWallet(address _sweeperlist) {
sweeperList = AbstractSweeperList(_sweeperlist);
}
function () public payable { }
function tokenFallback(address _from, uint _value, bytes _data) {
(_from);
(_value);
(_data);
}
function sweep(address _token, uint _amount)
returns (bool) {
(_amount);
return sweeperList.sweeperOf(_token).delegatecall(msg.data);
}
}
contract AbstractSweeperList {
function sweeperOf(address _token) returns (address);
}
contract Controller is AbstractSweeperList {
address public owner;
address public authorizedCaller;
address public destination;
bool public halted;
event LogNewWallet(address receiver);
event LogSweep(address indexed from, address indexed to, address indexed token, uint amount);
modifier onlyOwner() {
if (msg.sender != owner) throw;
_;
}
modifier onlyAuthorizedCaller() {
if (msg.sender != authorizedCaller) throw;
_;
}
modifier onlyAdmins() {
if (msg.sender != authorizedCaller && msg.sender != owner) throw;
_;
}
function Controller()
{
owner = msg.sender;
destination = msg.sender;
authorizedCaller = msg.sender;
}
function changeAuthorizedCaller(address _newCaller) onlyOwner {
authorizedCaller = _newCaller;
}
function changeDestination(address _dest) onlyOwner {
destination = _dest;
}
function changeOwner(address _owner) onlyOwner {
owner = _owner;
}
function makeWallet() onlyAdmins returns (address wallet) {
wallet = address(new UserWallet(this));
LogNewWallet(wallet);
}
function halt() onlyAdmins {
halted = true;
}
function start() onlyOwner {
halted = false;
}
address public defaultSweeper = address(new DefaultSweeper(this));
mapping (address => address) sweepers;
function addSweeper(address _token, address _sweeper) onlyOwner {
sweepers[_token] = _sweeper;
}
function sweeperOf(address _token) returns (address) {
address sweeper = sweepers[_token];
if (sweeper == 0) sweeper = defaultSweeper;
return sweeper;
}
function logSweep(address from, address to, address token, uint amount) {
LogSweep(from, to, token, amount);
}
}
|
[{"constant":false,"inputs":[{"name":"_token","type":"address"},{"name":"_amount","type":"uint256"}],"name":"sweep","outputs":[{"name":"","type":"bool"}],"payable":false,"type":"function"},{"constant":false,"inputs":[{"name":"_from","type":"address"},{"name":"_value","type":"uint256"},{"name":"_data","type":"bytes"}],"name":"tokenFallback","outputs":[],"payable":false,"type":"function"},{"inputs":[{"name":"_sweeperlist","type":"address"}],"payable":false,"type":"constructor"},{"payable":true,"type":"fallback"}]
|
v0.4.11+commit.68ef5810
| true
| 200
|
000000000000000000000000a3C1E324CA1ce40db73eD6026c4A177F099B5770
|
Default
| false
|
bzzr://4cdd69fdcf3cf6cbee9677fe380fa5f044048aa9e060ec5619a21ca5a5bd4cd1
|
|||
UserWallet
|
0x446c45b049abe566d476491e8a54f2a893ac75eb
|
Solidity
|
pragma solidity ^0.4.10;
// Copyright 2017 Bittrex
contract AbstractSweeper {
function sweep(address token, uint amount) returns (bool);
function () { throw; }
Controller controller;
function AbstractSweeper(address _controller) {
controller = Controller(_controller);
}
modifier canSweep() {
if (msg.sender != controller.authorizedCaller() && msg.sender != controller.owner()) throw;
if (controller.halted()) throw;
_;
}
}
contract Token {
function balanceOf(address a) returns (uint) {
(a);
return 0;
}
function transfer(address a, uint val) returns (bool) {
(a);
(val);
return false;
}
}
contract DefaultSweeper is AbstractSweeper {
function DefaultSweeper(address controller)
AbstractSweeper(controller) {}
function sweep(address _token, uint _amount)
canSweep
returns (bool) {
bool success = false;
address destination = controller.destination();
if (_token != address(0)) {
Token token = Token(_token);
uint amount = _amount;
if (amount > token.balanceOf(this)) {
return false;
}
success = token.transfer(destination, amount);
}
else {
uint amountInWei = _amount;
if (amountInWei > this.balance) {
return false;
}
success = destination.send(amountInWei);
}
if (success) {
controller.logSweep(this, destination, _token, _amount);
}
return success;
}
}
contract UserWallet {
AbstractSweeperList sweeperList;
function UserWallet(address _sweeperlist) {
sweeperList = AbstractSweeperList(_sweeperlist);
}
function () public payable { }
function tokenFallback(address _from, uint _value, bytes _data) {
(_from);
(_value);
(_data);
}
function sweep(address _token, uint _amount)
returns (bool) {
(_amount);
return sweeperList.sweeperOf(_token).delegatecall(msg.data);
}
}
contract AbstractSweeperList {
function sweeperOf(address _token) returns (address);
}
contract Controller is AbstractSweeperList {
address public owner;
address public authorizedCaller;
address public destination;
bool public halted;
event LogNewWallet(address receiver);
event LogSweep(address indexed from, address indexed to, address indexed token, uint amount);
modifier onlyOwner() {
if (msg.sender != owner) throw;
_;
}
modifier onlyAuthorizedCaller() {
if (msg.sender != authorizedCaller) throw;
_;
}
modifier onlyAdmins() {
if (msg.sender != authorizedCaller && msg.sender != owner) throw;
_;
}
function Controller()
{
owner = msg.sender;
destination = msg.sender;
authorizedCaller = msg.sender;
}
function changeAuthorizedCaller(address _newCaller) onlyOwner {
authorizedCaller = _newCaller;
}
function changeDestination(address _dest) onlyOwner {
destination = _dest;
}
function changeOwner(address _owner) onlyOwner {
owner = _owner;
}
function makeWallet() onlyAdmins returns (address wallet) {
wallet = address(new UserWallet(this));
LogNewWallet(wallet);
}
function halt() onlyAdmins {
halted = true;
}
function start() onlyOwner {
halted = false;
}
address public defaultSweeper = address(new DefaultSweeper(this));
mapping (address => address) sweepers;
function addSweeper(address _token, address _sweeper) onlyOwner {
sweepers[_token] = _sweeper;
}
function sweeperOf(address _token) returns (address) {
address sweeper = sweepers[_token];
if (sweeper == 0) sweeper = defaultSweeper;
return sweeper;
}
function logSweep(address from, address to, address token, uint amount) {
LogSweep(from, to, token, amount);
}
}
|
[{"constant":false,"inputs":[{"name":"_token","type":"address"},{"name":"_amount","type":"uint256"}],"name":"sweep","outputs":[{"name":"","type":"bool"}],"payable":false,"type":"function"},{"constant":false,"inputs":[{"name":"_from","type":"address"},{"name":"_value","type":"uint256"},{"name":"_data","type":"bytes"}],"name":"tokenFallback","outputs":[],"payable":false,"type":"function"},{"inputs":[{"name":"_sweeperlist","type":"address"}],"payable":false,"type":"constructor"},{"payable":true,"type":"fallback"}]
|
v0.4.11+commit.68ef5810
| true
| 200
|
000000000000000000000000a3C1E324CA1ce40db73eD6026c4A177F099B5770
|
Default
| false
|
bzzr://4cdd69fdcf3cf6cbee9677fe380fa5f044048aa9e060ec5619a21ca5a5bd4cd1
|
|||
UserWallet
|
0x1bf193003ebfea4a8a72905253b9e316ebfc1b7b
|
Solidity
|
pragma solidity ^0.4.10;
// Copyright 2017 Bittrex
contract AbstractSweeper {
function sweep(address token, uint amount) returns (bool);
function () { throw; }
Controller controller;
function AbstractSweeper(address _controller) {
controller = Controller(_controller);
}
modifier canSweep() {
if (msg.sender != controller.authorizedCaller() && msg.sender != controller.owner()) throw;
if (controller.halted()) throw;
_;
}
}
contract Token {
function balanceOf(address a) returns (uint) {
(a);
return 0;
}
function transfer(address a, uint val) returns (bool) {
(a);
(val);
return false;
}
}
contract DefaultSweeper is AbstractSweeper {
function DefaultSweeper(address controller)
AbstractSweeper(controller) {}
function sweep(address _token, uint _amount)
canSweep
returns (bool) {
bool success = false;
address destination = controller.destination();
if (_token != address(0)) {
Token token = Token(_token);
uint amount = _amount;
if (amount > token.balanceOf(this)) {
return false;
}
success = token.transfer(destination, amount);
}
else {
uint amountInWei = _amount;
if (amountInWei > this.balance) {
return false;
}
success = destination.send(amountInWei);
}
if (success) {
controller.logSweep(this, destination, _token, _amount);
}
return success;
}
}
contract UserWallet {
AbstractSweeperList sweeperList;
function UserWallet(address _sweeperlist) {
sweeperList = AbstractSweeperList(_sweeperlist);
}
function () public payable { }
function tokenFallback(address _from, uint _value, bytes _data) {
(_from);
(_value);
(_data);
}
function sweep(address _token, uint _amount)
returns (bool) {
(_amount);
return sweeperList.sweeperOf(_token).delegatecall(msg.data);
}
}
contract AbstractSweeperList {
function sweeperOf(address _token) returns (address);
}
contract Controller is AbstractSweeperList {
address public owner;
address public authorizedCaller;
address public destination;
bool public halted;
event LogNewWallet(address receiver);
event LogSweep(address indexed from, address indexed to, address indexed token, uint amount);
modifier onlyOwner() {
if (msg.sender != owner) throw;
_;
}
modifier onlyAuthorizedCaller() {
if (msg.sender != authorizedCaller) throw;
_;
}
modifier onlyAdmins() {
if (msg.sender != authorizedCaller && msg.sender != owner) throw;
_;
}
function Controller()
{
owner = msg.sender;
destination = msg.sender;
authorizedCaller = msg.sender;
}
function changeAuthorizedCaller(address _newCaller) onlyOwner {
authorizedCaller = _newCaller;
}
function changeDestination(address _dest) onlyOwner {
destination = _dest;
}
function changeOwner(address _owner) onlyOwner {
owner = _owner;
}
function makeWallet() onlyAdmins returns (address wallet) {
wallet = address(new UserWallet(this));
LogNewWallet(wallet);
}
function halt() onlyAdmins {
halted = true;
}
function start() onlyOwner {
halted = false;
}
address public defaultSweeper = address(new DefaultSweeper(this));
mapping (address => address) sweepers;
function addSweeper(address _token, address _sweeper) onlyOwner {
sweepers[_token] = _sweeper;
}
function sweeperOf(address _token) returns (address) {
address sweeper = sweepers[_token];
if (sweeper == 0) sweeper = defaultSweeper;
return sweeper;
}
function logSweep(address from, address to, address token, uint amount) {
LogSweep(from, to, token, amount);
}
}
|
[{"constant":false,"inputs":[{"name":"_token","type":"address"},{"name":"_amount","type":"uint256"}],"name":"sweep","outputs":[{"name":"","type":"bool"}],"payable":false,"type":"function"},{"constant":false,"inputs":[{"name":"_from","type":"address"},{"name":"_value","type":"uint256"},{"name":"_data","type":"bytes"}],"name":"tokenFallback","outputs":[],"payable":false,"type":"function"},{"inputs":[{"name":"_sweeperlist","type":"address"}],"payable":false,"type":"constructor"},{"payable":true,"type":"fallback"}]
|
v0.4.11+commit.68ef5810
| true
| 200
|
000000000000000000000000a3C1E324CA1ce40db73eD6026c4A177F099B5770
|
Default
| false
|
bzzr://4cdd69fdcf3cf6cbee9677fe380fa5f044048aa9e060ec5619a21ca5a5bd4cd1
|
|||
Proxy
|
0xaa668ff173fd18dcc3d588c5882399718a70c747
|
Solidity
|
pragma solidity ^0.6.12;
// Copyright (C) 2018 Argent Labs Ltd. <https://argent.xyz>
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
// You should have received a copy of the GNU General Public License
// along with this program. If not, see <http://www.gnu.org/licenses/>.
// SPDX-License-Identifier: GPL-3.0-only
/**
* @title Proxy
* @notice Basic proxy that delegates all calls to a fixed implementing contract.
* The implementing contract cannot be upgraded.
* @author Julien Niset - <[email protected]>
*/
contract Proxy {
address implementation;
event Received(uint indexed value, address indexed sender, bytes data);
constructor(address _implementation) public {
implementation = _implementation;
}
fallback() external payable {
// solhint-disable-next-line no-inline-assembly
assembly {
let target := sload(0)
calldatacopy(0, 0, calldatasize())
let result := delegatecall(gas(), target, 0, calldatasize(), 0, 0)
returndatacopy(0, 0, returndatasize())
switch result
case 0 {revert(0, returndatasize())}
default {return (0, returndatasize())}
}
}
receive() external payable {
emit Received(msg.value, msg.sender, msg.data);
}
}
|
[{"inputs":[{"internalType":"address","name":"_implementation","type":"address"}],"stateMutability":"nonpayable","type":"constructor"},{"anonymous":false,"inputs":[{"indexed":true,"internalType":"uint256","name":"value","type":"uint256"},{"indexed":true,"internalType":"address","name":"sender","type":"address"},{"indexed":false,"internalType":"bytes","name":"data","type":"bytes"}],"name":"Received","type":"event"},{"stateMutability":"payable","type":"fallback"},{"stateMutability":"payable","type":"receive"}]
|
v0.6.12+commit.27d51765
| true
| 999
|
000000000000000000000000bc0b5970a01ba7c22104c85a4e2b05e01157638d
|
Default
|
GNU GPLv3
| false
|
ipfs://81653946f6f0f024eb94b19bdaf1d69dc04d346dcb6092fa1369c9e2dacfa421
|
||
VITA
|
0x81f8f0bb1cb2a06649e51913a151f0e7ef6fa321
|
Solidity
|
// File: contracts/VITA.sol
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.4;
import "@openzeppelin/contracts/utils/Context.sol";
import "@openzeppelin/contracts/access/Ownable.sol";
import "@openzeppelin/contracts/token/ERC20/extensions/ERC20Capped.sol";
import "./IVITA.sol";
contract VITA is IVITA, ERC20Capped, Ownable {
constructor(
string memory name_,
string memory symbol_,
uint256 cap_
) ERC20(name_, symbol_) ERC20Capped(cap_) {
}
function mint(address account, uint256 amount) public override onlyOwner {
_mint(account, amount);
}
}
// File: @openzeppelin/contracts/utils/Context.sol
// 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;
}
}
// File: @openzeppelin/contracts/access/Ownable.sol
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import "../utils/Context.sol";
/**
* @dev Contract module which provides a basic access control mechanism, where
* there is an account (an owner) that can be granted exclusive access to
* specific functions.
*
* By default, the owner account will be the one that deploys the contract. This
* can later be changed with {transferOwnership}.
*
* This module is used through inheritance. It will make available the modifier
* `onlyOwner`, which can be applied to your functions to restrict their use to
* the owner.
*/
abstract contract Ownable is Context {
address private _owner;
event OwnershipTransferred(address indexed previousOwner, address indexed newOwner);
/**
* @dev Initializes the contract setting the deployer as the initial owner.
*/
constructor () {
address msgSender = _msgSender();
_owner = msgSender;
emit OwnershipTransferred(address(0), msgSender);
}
/**
* @dev Returns the address of the current owner.
*/
function owner() public view virtual returns (address) {
return _owner;
}
/**
* @dev Throws if called by any account other than the owner.
*/
modifier onlyOwner() {
require(owner() == _msgSender(), "Ownable: caller is not the owner");
_;
}
/**
* @dev Leaves the contract without owner. It will not be possible to call
* `onlyOwner` functions anymore. Can only be called by the current owner.
*
* NOTE: Renouncing ownership will leave the contract without an owner,
* thereby removing any functionality that is only available to the owner.
*/
function renounceOwnership() public virtual onlyOwner {
emit OwnershipTransferred(_owner, address(0));
_owner = address(0);
}
/**
* @dev Transfers ownership of the contract to a new account (`newOwner`).
* Can only be called by the current owner.
*/
function transferOwnership(address newOwner) public virtual onlyOwner {
require(newOwner != address(0), "Ownable: new owner is the zero address");
emit OwnershipTransferred(_owner, newOwner);
_owner = newOwner;
}
}
// File: @openzeppelin/contracts/token/ERC20/extensions/ERC20Capped.sol
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import "../ERC20.sol";
/**
* @dev Extension of {ERC20} that adds a cap to the supply of tokens.
*/
abstract contract ERC20Capped is ERC20 {
uint256 immutable private _cap;
/**
* @dev Sets the value of the `cap`. This value is immutable, it can only be
* set once during construction.
*/
constructor (uint256 cap_) {
require(cap_ > 0, "ERC20Capped: cap is 0");
_cap = cap_;
}
/**
* @dev Returns the cap on the token's total supply.
*/
function cap() public view virtual returns (uint256) {
return _cap;
}
/**
* @dev See {ERC20-_mint}.
*/
function _mint(address account, uint256 amount) internal virtual override {
require(ERC20.totalSupply() + amount <= cap(), "ERC20Capped: cap exceeded");
super._mint(account, amount);
}
}
// File: contracts/IVITA.sol
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.4;
import "@openzeppelin/contracts/token/ERC20/IERC20.sol";
interface IVITA is IERC20 {
function mint(address account, uint256 amount) external;
}
// File: @openzeppelin/contracts/token/ERC20/ERC20.sol
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import "./IERC20.sol";
import "../../utils/Context.sol";
/**
* @dev Implementation of the {IERC20} interface.
*
* This implementation is agnostic to the way tokens are created. This means
* that a supply mechanism has to be added in a derived contract using {_mint}.
* For a generic mechanism see {ERC20PresetMinterPauser}.
*
* TIP: For a detailed writeup see our guide
* https://forum.zeppelin.solutions/t/how-to-implement-erc20-supply-mechanisms/226[How
* to implement supply mechanisms].
*
* We have followed general OpenZeppelin 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 {
mapping (address => uint256) private _balances;
mapping (address => mapping (address => uint256)) private _allowances;
uint256 private _totalSupply;
string private _name;
string private _symbol;
/**
* @dev Sets the values for {name} and {symbol}.
*
* The defaut value of {decimals} is 18. To select a different value for
* {decimals} you should overload it.
*
* All three of these values are immutable: they can only be set once during
* construction.
*/
constructor (string memory name_, string memory symbol_) {
_name = name_;
_symbol = symbol_;
}
/**
* @dev Returns the name of the token.
*/
function name() public view virtual returns (string memory) {
return _name;
}
/**
* @dev Returns the symbol of the token, usually a shorter version of the
* name.
*/
function symbol() public view virtual returns (string memory) {
return _symbol;
}
/**
* @dev Returns the number of decimals used to get its user representation.
* For example, if `decimals` equals `2`, a balance of `505` tokens should
* be displayed to a user as `5,05` (`505 / 10 ** 2`).
*
* Tokens usually opt for a value of 18, imitating the relationship between
* Ether and Wei. This is the value {ERC20} uses, unless this function is
* overloaded;
*
* NOTE: This information is only used for _display_ purposes: it in
* no way affects any of the arithmetic of the contract, including
* {IERC20-balanceOf} and {IERC20-transfer}.
*/
function decimals() public view virtual returns (uint8) {
return 18;
}
/**
* @dev See {IERC20-totalSupply}.
*/
function totalSupply() public view virtual override returns (uint256) {
return _totalSupply;
}
/**
* @dev See {IERC20-balanceOf}.
*/
function balanceOf(address account) public view virtual override returns (uint256) {
return _balances[account];
}
/**
* @dev See {IERC20-transfer}.
*
* Requirements:
*
* - `recipient` cannot be the zero address.
* - the caller must have a balance of at least `amount`.
*/
function transfer(address recipient, uint256 amount) public virtual override returns (bool) {
_transfer(_msgSender(), recipient, amount);
return true;
}
/**
* @dev See {IERC20-allowance}.
*/
function allowance(address owner, address spender) public view virtual override returns (uint256) {
return _allowances[owner][spender];
}
/**
* @dev See {IERC20-approve}.
*
* Requirements:
*
* - `spender` cannot be the zero address.
*/
function approve(address spender, uint256 amount) public virtual override returns (bool) {
_approve(_msgSender(), spender, amount);
return true;
}
/**
* @dev See {IERC20-transferFrom}.
*
* Emits an {Approval} event indicating the updated allowance. This is not
* required by the EIP. See the note at the beginning of {ERC20}.
*
* Requirements:
*
* - `sender` and `recipient` cannot be the zero address.
* - `sender` must have a balance of at least `amount`.
* - the caller must have allowance for ``sender``'s tokens of at least
* `amount`.
*/
function transferFrom(address sender, address recipient, uint256 amount) public virtual override returns (bool) {
_transfer(sender, recipient, amount);
uint256 currentAllowance = _allowances[sender][_msgSender()];
require(currentAllowance >= amount, "ERC20: transfer amount exceeds allowance");
_approve(sender, _msgSender(), currentAllowance - amount);
return true;
}
/**
* @dev Atomically increases the allowance granted to `spender` by the caller.
*
* This is an alternative to {approve} that can be used as a mitigation for
* problems described in {IERC20-approve}.
*
* Emits an {Approval} event indicating the updated allowance.
*
* Requirements:
*
* - `spender` cannot be the zero address.
*/
function increaseAllowance(address spender, uint256 addedValue) public virtual returns (bool) {
_approve(_msgSender(), spender, _allowances[_msgSender()][spender] + addedValue);
return true;
}
/**
* @dev Atomically decreases the allowance granted to `spender` by the caller.
*
* This is an alternative to {approve} that can be used as a mitigation for
* problems described in {IERC20-approve}.
*
* Emits an {Approval} event indicating the updated allowance.
*
* Requirements:
*
* - `spender` cannot be the zero address.
* - `spender` must have allowance for the caller of at least
* `subtractedValue`.
*/
function decreaseAllowance(address spender, uint256 subtractedValue) public virtual returns (bool) {
uint256 currentAllowance = _allowances[_msgSender()][spender];
require(currentAllowance >= subtractedValue, "ERC20: decreased allowance below zero");
_approve(_msgSender(), spender, currentAllowance - subtractedValue);
return true;
}
/**
* @dev Moves tokens `amount` from `sender` to `recipient`.
*
* This is internal function is equivalent to {transfer}, and can be used to
* e.g. implement automatic token fees, slashing mechanisms, etc.
*
* Emits a {Transfer} event.
*
* Requirements:
*
* - `sender` cannot be the zero address.
* - `recipient` cannot be the zero address.
* - `sender` must have a balance of at least `amount`.
*/
function _transfer(address sender, address recipient, uint256 amount) internal virtual {
require(sender != address(0), "ERC20: transfer from the zero address");
require(recipient != address(0), "ERC20: transfer to the zero address");
_beforeTokenTransfer(sender, recipient, amount);
uint256 senderBalance = _balances[sender];
require(senderBalance >= amount, "ERC20: transfer amount exceeds balance");
_balances[sender] = senderBalance - amount;
_balances[recipient] += amount;
emit Transfer(sender, recipient, amount);
}
/** @dev Creates `amount` tokens and assigns them to `account`, increasing
* the total supply.
*
* Emits a {Transfer} event with `from` set to the zero address.
*
* Requirements:
*
* - `to` cannot be the zero address.
*/
function _mint(address account, uint256 amount) internal virtual {
require(account != address(0), "ERC20: mint to the zero address");
_beforeTokenTransfer(address(0), account, amount);
_totalSupply += amount;
_balances[account] += amount;
emit Transfer(address(0), account, amount);
}
/**
* @dev Destroys `amount` tokens from `account`, reducing the
* total supply.
*
* Emits a {Transfer} event with `to` set to the zero address.
*
* Requirements:
*
* - `account` cannot be the zero address.
* - `account` must have at least `amount` tokens.
*/
function _burn(address account, uint256 amount) internal virtual {
require(account != address(0), "ERC20: burn from the zero address");
_beforeTokenTransfer(account, address(0), amount);
uint256 accountBalance = _balances[account];
require(accountBalance >= amount, "ERC20: burn amount exceeds balance");
_balances[account] = accountBalance - amount;
_totalSupply -= amount;
emit Transfer(account, address(0), amount);
}
/**
* @dev Sets `amount` as the allowance of `spender` over the `owner` s tokens.
*
* This internal function is equivalent to `approve`, and can be used to
* e.g. set automatic allowances for certain subsystems, etc.
*
* Emits an {Approval} event.
*
* Requirements:
*
* - `owner` cannot be the zero address.
* - `spender` cannot be the zero address.
*/
function _approve(address owner, address spender, uint256 amount) internal virtual {
require(owner != address(0), "ERC20: approve from the zero address");
require(spender != address(0), "ERC20: approve to the zero address");
_allowances[owner][spender] = amount;
emit Approval(owner, spender, amount);
}
/**
* @dev Hook that is called before any transfer of tokens. This includes
* minting and burning.
*
* Calling conditions:
*
* - when `from` and `to` are both non-zero, `amount` of ``from``'s tokens
* will be to transferred to `to`.
* - when `from` is zero, `amount` tokens will be minted for `to`.
* - when `to` is zero, `amount` of ``from``'s tokens will be burned.
* - `from` and `to` are never both zero.
*
* To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks].
*/
function _beforeTokenTransfer(address from, address to, uint256 amount) internal virtual { }
}
// File: @openzeppelin/contracts/token/ERC20/IERC20.sol
// 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);
}
|
[{"inputs":[{"internalType":"string","name":"name_","type":"string"},{"internalType":"string","name":"symbol_","type":"string"},{"internalType":"uint256","name":"cap_","type":"uint256"}],"stateMutability":"nonpayable","type":"constructor"},{"anonymous":false,"inputs":[{"indexed":true,"internalType":"address","name":"owner","type":"address"},{"indexed":true,"internalType":"address","name":"spender","type":"address"},{"indexed":false,"internalType":"uint256","name":"value","type":"uint256"}],"name":"Approval","type":"event"},{"anonymous":false,"inputs":[{"indexed":true,"internalType":"address","name":"previousOwner","type":"address"},{"indexed":true,"internalType":"address","name":"newOwner","type":"address"}],"name":"OwnershipTransferred","type":"event"},{"anonymous":false,"inputs":[{"indexed":true,"internalType":"address","name":"from","type":"address"},{"indexed":true,"internalType":"address","name":"to","type":"address"},{"indexed":false,"internalType":"uint256","name":"value","type":"uint256"}],"name":"Transfer","type":"event"},{"inputs":[{"internalType":"address","name":"owner","type":"address"},{"internalType":"address","name":"spender","type":"address"}],"name":"allowance","outputs":[{"internalType":"uint256","name":"","type":"uint256"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"address","name":"spender","type":"address"},{"internalType":"uint256","name":"amount","type":"uint256"}],"name":"approve","outputs":[{"internalType":"bool","name":"","type":"bool"}],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"address","name":"account","type":"address"}],"name":"balanceOf","outputs":[{"internalType":"uint256","name":"","type":"uint256"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"cap","outputs":[{"internalType":"uint256","name":"","type":"uint256"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"decimals","outputs":[{"internalType":"uint8","name":"","type":"uint8"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"address","name":"spender","type":"address"},{"internalType":"uint256","name":"subtractedValue","type":"uint256"}],"name":"decreaseAllowance","outputs":[{"internalType":"bool","name":"","type":"bool"}],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"address","name":"spender","type":"address"},{"internalType":"uint256","name":"addedValue","type":"uint256"}],"name":"increaseAllowance","outputs":[{"internalType":"bool","name":"","type":"bool"}],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"address","name":"account","type":"address"},{"internalType":"uint256","name":"amount","type":"uint256"}],"name":"mint","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[],"name":"name","outputs":[{"internalType":"string","name":"","type":"string"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"owner","outputs":[{"internalType":"address","name":"","type":"address"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"renounceOwnership","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[],"name":"symbol","outputs":[{"internalType":"string","name":"","type":"string"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"totalSupply","outputs":[{"internalType":"uint256","name":"","type":"uint256"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"address","name":"recipient","type":"address"},{"internalType":"uint256","name":"amount","type":"uint256"}],"name":"transfer","outputs":[{"internalType":"bool","name":"","type":"bool"}],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"address","name":"sender","type":"address"},{"internalType":"address","name":"recipient","type":"address"},{"internalType":"uint256","name":"amount","type":"uint256"}],"name":"transferFrom","outputs":[{"internalType":"bool","name":"","type":"bool"}],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"address","name":"newOwner","type":"address"}],"name":"transferOwnership","outputs":[],"stateMutability":"nonpayable","type":"function"}]
|
v0.8.4+commit.c7e474f2
| false
| 200
|
000000000000000000000000000000000000000000000000000000000000006000000000000000000000000000000000000000000000000000000000000000a0000000000000000000000000000000000000000000352fd144eb8d4cce000000000000000000000000000000000000000000000000000000000000000000000d5669746144414f20546f6b656e0000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000045649544100000000000000000000000000000000000000000000000000000000
|
Default
| false
| ||||
Forwarder
|
0xc8240ced417f28c5a25fce5e0cca7de79f028c4a
|
Solidity
|
pragma solidity ^0.4.14;
/**
* Contract that exposes the needed erc20 token functions
*/
contract ERC20Interface {
// Send _value amount of tokens to address _to
function transfer(address _to, uint256 _value) returns (bool success);
// Get the account balance of another account with address _owner
function balanceOf(address _owner) constant returns (uint256 balance);
}
/**
* Contract that will forward any incoming Ether to its creator
*/
contract Forwarder {
// Address to which any funds sent to this contract will be forwarded
address public parentAddress;
event ForwarderDeposited(address from, uint value, bytes data);
event TokensFlushed(
address tokenContractAddress, // The contract address of the token
uint value // Amount of token sent
);
/**
* Create the contract, and set the destination address to that of the creator
*/
function Forwarder() {
parentAddress = msg.sender;
}
/**
* Modifier that will execute internal code block only if the sender is a parent of the forwarder contract
*/
modifier onlyParent {
if (msg.sender != parentAddress) {
throw;
}
_;
}
/**
* Default function; Gets called when Ether is deposited, and forwards it to the destination address
*/
function() payable {
if (!parentAddress.call.value(msg.value)(msg.data))
throw;
// Fire off the deposited event if we can forward it
ForwarderDeposited(msg.sender, msg.value, msg.data);
}
/**
* Execute a token transfer of the full balance from the forwarder token to the main wallet contract
* @param tokenContractAddress the address of the erc20 token contract
*/
function flushTokens(address tokenContractAddress) onlyParent {
ERC20Interface instance = ERC20Interface(tokenContractAddress);
var forwarderAddress = address(this);
var forwarderBalance = instance.balanceOf(forwarderAddress);
if (forwarderBalance == 0) {
return;
}
if (!instance.transfer(parentAddress, forwarderBalance)) {
throw;
}
TokensFlushed(tokenContractAddress, forwarderBalance);
}
/**
* It is possible that funds were sent to this address before the contract was deployed.
* We can flush those funds to the destination address.
*/
function flush() {
if (!parentAddress.call.value(this.balance)())
throw;
}
}
/**
* Basic multi-signer wallet designed for use in a co-signing environment where 2 signatures are required to move funds.
* Typically used in a 2-of-3 signing configuration. Uses ecrecover to allow for 2 signatures in a single transaction.
*/
contract WalletSimple {
// Events
event Deposited(address from, uint value, bytes data);
event SafeModeActivated(address msgSender);
event Transacted(
address msgSender, // Address of the sender of the message initiating the transaction
address otherSigner, // Address of the signer (second signature) used to initiate the transaction
bytes32 operation, // Operation hash (sha3 of toAddress, value, data, expireTime, sequenceId)
address toAddress, // The address the transaction was sent to
uint value, // Amount of Wei sent to the address
bytes data // Data sent when invoking the transaction
);
event TokenTransacted(
address msgSender, // Address of the sender of the message initiating the transaction
address otherSigner, // Address of the signer (second signature) used to initiate the transaction
bytes32 operation, // Operation hash (sha3 of toAddress, value, tokenContractAddress, expireTime, sequenceId)
address toAddress, // The address the transaction was sent to
uint value, // Amount of token sent
address tokenContractAddress // The contract address of the token
);
// Public fields
address[] public signers; // The addresses that can co-sign transactions on the wallet
bool public safeMode = false; // When active, wallet may only send to signer addresses
// Internal fields
uint constant SEQUENCE_ID_WINDOW_SIZE = 10;
uint[10] recentSequenceIds;
/**
* Modifier that will execute internal code block only if the sender is an authorized signer on this wallet
*/
modifier onlysigner {
if (!isSigner(msg.sender)) {
throw;
}
_;
}
/**
* Set up a simple multi-sig wallet by specifying the signers allowed to be used on this wallet.
* 2 signers will be required to send a transaction from this wallet.
* Note: The sender is NOT automatically added to the list of signers.
* Signers CANNOT be changed once they are set
*
* @param allowedSigners An array of signers on the wallet
*/
function WalletSimple(address[] allowedSigners) {
if (allowedSigners.length != 3) {
// Invalid number of signers
throw;
}
signers = allowedSigners;
}
/**
* Gets called when a transaction is received without calling a method
*/
function() payable {
if (msg.value > 0) {
// Fire deposited event if we are receiving funds
Deposited(msg.sender, msg.value, msg.data);
}
}
/**
* Create a new contract (and also address) that forwards funds to this contract
* returns address of newly created forwarder address
*/
function createForwarder() onlysigner returns (address) {
return new Forwarder();
}
/**
* Execute a multi-signature transaction from this wallet using 2 signers: one from msg.sender and the other from ecrecover.
* The signature is a signed form (using eth.sign) of tightly packed toAddress, value, data, expireTime and sequenceId
* Sequence IDs are numbers starting from 1. They are used to prevent replay attacks and may not be repeated.
*
* @param toAddress the destination address to send an outgoing transaction
* @param value the amount in Wei to be sent
* @param data the data to send to the toAddress when invoking the transaction
* @param expireTime the number of seconds since 1970 for which this transaction is valid
* @param sequenceId the unique sequence id obtainable from getNextSequenceId
* @param signature the result of eth.sign on the operationHash sha3(toAddress, value, data, expireTime, sequenceId)
*/
function sendMultiSig(address toAddress, uint value, bytes data, uint expireTime, uint sequenceId, bytes signature) onlysigner {
// Verify the other signer
var operationHash = sha3("ETHER", toAddress, value, data, expireTime, sequenceId);
var otherSigner = verifyMultiSig(toAddress, operationHash, signature, expireTime, sequenceId);
// Success, send the transaction
if (!(toAddress.call.value(value)(data))) {
// Failed executing transaction
throw;
}
Transacted(msg.sender, otherSigner, operationHash, toAddress, value, data);
}
/**
* Execute a multi-signature token transfer from this wallet using 2 signers: one from msg.sender and the other from ecrecover.
* The signature is a signed form (using eth.sign) of tightly packed toAddress, value, tokenContractAddress, expireTime and sequenceId
* Sequence IDs are numbers starting from 1. They are used to prevent replay attacks and may not be repeated.
*
* @param toAddress the destination address to send an outgoing transaction
* @param value the amount in tokens to be sent
* @param tokenContractAddress the address of the erc20 token contract
* @param expireTime the number of seconds since 1970 for which this transaction is valid
* @param sequenceId the unique sequence id obtainable from getNextSequenceId
* @param signature the result of eth.sign on the operationHash sha3(toAddress, value, tokenContractAddress, expireTime, sequenceId)
*/
function sendMultiSigToken(address toAddress, uint value, address tokenContractAddress, uint expireTime, uint sequenceId, bytes signature) onlysigner {
// Verify the other signer
var operationHash = sha3("ERC20", toAddress, value, tokenContractAddress, expireTime, sequenceId);
var otherSigner = verifyMultiSig(toAddress, operationHash, signature, expireTime, sequenceId);
ERC20Interface instance = ERC20Interface(tokenContractAddress);
if (!instance.transfer(toAddress, value)) {
throw;
}
TokenTransacted(msg.sender, otherSigner, operationHash, toAddress, value, tokenContractAddress);
}
/**
* Execute a token flush from one of the forwarder addresses. This transfer needs only a single signature and can be done by any signer
*
* @param forwarderAddress the address of the forwarder address to flush the tokens from
* @param tokenContractAddress the address of the erc20 token contract
*/
function flushForwarderTokens(address forwarderAddress, address tokenContractAddress) onlysigner {
Forwarder forwarder = Forwarder(forwarderAddress);
forwarder.flushTokens(tokenContractAddress);
}
/**
* Do common multisig verification for both eth sends and erc20token transfers
*
* @param toAddress the destination address to send an outgoing transaction
* @param operationHash the sha3 of the toAddress, value, data/tokenContractAddress and expireTime
* @param signature the tightly packed signature of r, s, and v as an array of 65 bytes (returned by eth.sign)
* @param expireTime the number of seconds since 1970 for which this transaction is valid
* @param sequenceId the unique sequence id obtainable from getNextSequenceId
* returns address of the address to send tokens or eth to
*/
function verifyMultiSig(address toAddress, bytes32 operationHash, bytes signature, uint expireTime, uint sequenceId) private returns (address) {
var otherSigner = recoverAddressFromSignature(operationHash, signature);
// Verify if we are in safe mode. In safe mode, the wallet can only send to signers
if (safeMode && !isSigner(toAddress)) {
// We are in safe mode and the toAddress is not a signer. Disallow!
throw;
}
// Verify that the transaction has not expired
if (expireTime < block.timestamp) {
// Transaction expired
throw;
}
// Try to insert the sequence ID. Will throw if the sequence id was invalid
tryInsertSequenceId(sequenceId);
if (!isSigner(otherSigner)) {
// Other signer not on this wallet or operation does not match arguments
throw;
}
if (otherSigner == msg.sender) {
// Cannot approve own transaction
throw;
}
return otherSigner;
}
/**
* Irrevocably puts contract into safe mode. When in this mode, transactions may only be sent to signing addresses.
*/
function activateSafeMode() onlysigner {
safeMode = true;
SafeModeActivated(msg.sender);
}
/**
* Determine if an address is a signer on this wallet
* @param signer address to check
* returns boolean indicating whether address is signer or not
*/
function isSigner(address signer) returns (bool) {
// Iterate through all signers on the wallet and
for (uint i = 0; i < signers.length; i++) {
if (signers[i] == signer) {
return true;
}
}
return false;
}
/**
* Gets the second signer's address using ecrecover
* @param operationHash the sha3 of the toAddress, value, data/tokenContractAddress and expireTime
* @param signature the tightly packed signature of r, s, and v as an array of 65 bytes (returned by eth.sign)
* returns address recovered from the signature
*/
function recoverAddressFromSignature(bytes32 operationHash, bytes signature) private returns (address) {
if (signature.length != 65) {
throw;
}
// We need to unpack the signature, which is given as an array of 65 bytes (from eth.sign)
bytes32 r;
bytes32 s;
uint8 v;
assembly {
r := mload(add(signature, 32))
s := mload(add(signature, 64))
v := and(mload(add(signature, 65)), 255)
}
if (v < 27) {
v += 27; // Ethereum versions are 27 or 28 as opposed to 0 or 1 which is submitted by some signing libs
}
return ecrecover(operationHash, v, r, s);
}
/**
* Verify that the sequence id has not been used before and inserts it. Throws if the sequence ID was not accepted.
* We collect a window of up to 10 recent sequence ids, and allow any sequence id that is not in the window and
* greater than the minimum element in the window.
* @param sequenceId to insert into array of stored ids
*/
function tryInsertSequenceId(uint sequenceId) onlysigner private {
// Keep a pointer to the lowest value element in the window
uint lowestValueIndex = 0;
for (uint i = 0; i < SEQUENCE_ID_WINDOW_SIZE; i++) {
if (recentSequenceIds[i] == sequenceId) {
// This sequence ID has been used before. Disallow!
throw;
}
if (recentSequenceIds[i] < recentSequenceIds[lowestValueIndex]) {
lowestValueIndex = i;
}
}
if (sequenceId < recentSequenceIds[lowestValueIndex]) {
// The sequence ID being used is lower than the lowest value in the window
// so we cannot accept it as it may have been used before
throw;
}
if (sequenceId > (recentSequenceIds[lowestValueIndex] + 10000)) {
// Block sequence IDs which are much higher than the lowest value
// This prevents people blocking the contract by using very large sequence IDs quickly
throw;
}
recentSequenceIds[lowestValueIndex] = sequenceId;
}
/**
* Gets the next available sequence ID for signing when using executeAndConfirm
* returns the sequenceId one higher than the highest currently stored
*/
function getNextSequenceId() returns (uint) {
uint highestSequenceId = 0;
for (uint i = 0; i < SEQUENCE_ID_WINDOW_SIZE; i++) {
if (recentSequenceIds[i] > highestSequenceId) {
highestSequenceId = recentSequenceIds[i];
}
}
return highestSequenceId + 1;
}
}
|
[{"constant":true,"inputs":[],"name":"parentAddress","outputs":[{"name":"","type":"address"}],"payable":false,"type":"function"},{"constant":false,"inputs":[{"name":"tokenContractAddress","type":"address"}],"name":"flushTokens","outputs":[],"payable":false,"type":"function"},{"constant":false,"inputs":[],"name":"flush","outputs":[],"payable":false,"type":"function"},{"inputs":[],"payable":false,"type":"constructor"},{"payable":true,"type":"fallback"},{"anonymous":false,"inputs":[{"indexed":false,"name":"from","type":"address"},{"indexed":false,"name":"value","type":"uint256"},{"indexed":false,"name":"data","type":"bytes"}],"name":"ForwarderDeposited","type":"event"},{"anonymous":false,"inputs":[{"indexed":false,"name":"tokenContractAddress","type":"address"},{"indexed":false,"name":"value","type":"uint256"}],"name":"TokensFlushed","type":"event"}]
|
v0.4.16-nightly.2017.8.11+commit.c84de7fa
| true
| 200
|
Default
| false
|
bzzr://d0f8838ba17108a895d34ae8ef3bff4e0dc9d639c3c51921fee1d17eaa803721
|
||||
UserWallet
|
0x1cb2ba3242fcda0ac42aae910091cb387b4f1a84
|
Solidity
|
pragma solidity ^0.4.10;
// Copyright 2017 Bittrex
contract AbstractSweeper {
function sweep(address token, uint amount) returns (bool);
function () { throw; }
Controller controller;
function AbstractSweeper(address _controller) {
controller = Controller(_controller);
}
modifier canSweep() {
if (msg.sender != controller.authorizedCaller() && msg.sender != controller.owner()) throw;
if (controller.halted()) throw;
_;
}
}
contract Token {
function balanceOf(address a) returns (uint) {
(a);
return 0;
}
function transfer(address a, uint val) returns (bool) {
(a);
(val);
return false;
}
}
contract DefaultSweeper is AbstractSweeper {
function DefaultSweeper(address controller)
AbstractSweeper(controller) {}
function sweep(address _token, uint _amount)
canSweep
returns (bool) {
bool success = false;
address destination = controller.destination();
if (_token != address(0)) {
Token token = Token(_token);
uint amount = _amount;
if (amount > token.balanceOf(this)) {
return false;
}
success = token.transfer(destination, amount);
}
else {
uint amountInWei = _amount;
if (amountInWei > this.balance) {
return false;
}
success = destination.send(amountInWei);
}
if (success) {
controller.logSweep(this, destination, _token, _amount);
}
return success;
}
}
contract UserWallet {
AbstractSweeperList sweeperList;
function UserWallet(address _sweeperlist) {
sweeperList = AbstractSweeperList(_sweeperlist);
}
function () public payable { }
function tokenFallback(address _from, uint _value, bytes _data) {
(_from);
(_value);
(_data);
}
function sweep(address _token, uint _amount)
returns (bool) {
(_amount);
return sweeperList.sweeperOf(_token).delegatecall(msg.data);
}
}
contract AbstractSweeperList {
function sweeperOf(address _token) returns (address);
}
contract Controller is AbstractSweeperList {
address public owner;
address public authorizedCaller;
address public destination;
bool public halted;
event LogNewWallet(address receiver);
event LogSweep(address indexed from, address indexed to, address indexed token, uint amount);
modifier onlyOwner() {
if (msg.sender != owner) throw;
_;
}
modifier onlyAuthorizedCaller() {
if (msg.sender != authorizedCaller) throw;
_;
}
modifier onlyAdmins() {
if (msg.sender != authorizedCaller && msg.sender != owner) throw;
_;
}
function Controller()
{
owner = msg.sender;
destination = msg.sender;
authorizedCaller = msg.sender;
}
function changeAuthorizedCaller(address _newCaller) onlyOwner {
authorizedCaller = _newCaller;
}
function changeDestination(address _dest) onlyOwner {
destination = _dest;
}
function changeOwner(address _owner) onlyOwner {
owner = _owner;
}
function makeWallet() onlyAdmins returns (address wallet) {
wallet = address(new UserWallet(this));
LogNewWallet(wallet);
}
function halt() onlyAdmins {
halted = true;
}
function start() onlyOwner {
halted = false;
}
address public defaultSweeper = address(new DefaultSweeper(this));
mapping (address => address) sweepers;
function addSweeper(address _token, address _sweeper) onlyOwner {
sweepers[_token] = _sweeper;
}
function sweeperOf(address _token) returns (address) {
address sweeper = sweepers[_token];
if (sweeper == 0) sweeper = defaultSweeper;
return sweeper;
}
function logSweep(address from, address to, address token, uint amount) {
LogSweep(from, to, token, amount);
}
}
|
[{"constant":false,"inputs":[{"name":"_token","type":"address"},{"name":"_amount","type":"uint256"}],"name":"sweep","outputs":[{"name":"","type":"bool"}],"payable":false,"type":"function"},{"constant":false,"inputs":[{"name":"_from","type":"address"},{"name":"_value","type":"uint256"},{"name":"_data","type":"bytes"}],"name":"tokenFallback","outputs":[],"payable":false,"type":"function"},{"inputs":[{"name":"_sweeperlist","type":"address"}],"payable":false,"type":"constructor"},{"payable":true,"type":"fallback"}]
|
v0.4.11+commit.68ef5810
| true
| 200
|
000000000000000000000000a3C1E324CA1ce40db73eD6026c4A177F099B5770
|
Default
| false
|
bzzr://4cdd69fdcf3cf6cbee9677fe380fa5f044048aa9e060ec5619a21ca5a5bd4cd1
|
|||
UserWallet
|
0x4ed76281a9150cf70f0f603c9dab504d0914deda
|
Solidity
|
pragma solidity ^0.4.10;
// Copyright 2017 Bittrex
contract AbstractSweeper {
function sweep(address token, uint amount) returns (bool);
function () { throw; }
Controller controller;
function AbstractSweeper(address _controller) {
controller = Controller(_controller);
}
modifier canSweep() {
if (msg.sender != controller.authorizedCaller() && msg.sender != controller.owner()) throw;
if (controller.halted()) throw;
_;
}
}
contract Token {
function balanceOf(address a) returns (uint) {
(a);
return 0;
}
function transfer(address a, uint val) returns (bool) {
(a);
(val);
return false;
}
}
contract DefaultSweeper is AbstractSweeper {
function DefaultSweeper(address controller)
AbstractSweeper(controller) {}
function sweep(address _token, uint _amount)
canSweep
returns (bool) {
bool success = false;
address destination = controller.destination();
if (_token != address(0)) {
Token token = Token(_token);
uint amount = _amount;
if (amount > token.balanceOf(this)) {
return false;
}
success = token.transfer(destination, amount);
}
else {
uint amountInWei = _amount;
if (amountInWei > this.balance) {
return false;
}
success = destination.send(amountInWei);
}
if (success) {
controller.logSweep(this, destination, _token, _amount);
}
return success;
}
}
contract UserWallet {
AbstractSweeperList sweeperList;
function UserWallet(address _sweeperlist) {
sweeperList = AbstractSweeperList(_sweeperlist);
}
function () public payable { }
function tokenFallback(address _from, uint _value, bytes _data) {
(_from);
(_value);
(_data);
}
function sweep(address _token, uint _amount)
returns (bool) {
(_amount);
return sweeperList.sweeperOf(_token).delegatecall(msg.data);
}
}
contract AbstractSweeperList {
function sweeperOf(address _token) returns (address);
}
contract Controller is AbstractSweeperList {
address public owner;
address public authorizedCaller;
address public destination;
bool public halted;
event LogNewWallet(address receiver);
event LogSweep(address indexed from, address indexed to, address indexed token, uint amount);
modifier onlyOwner() {
if (msg.sender != owner) throw;
_;
}
modifier onlyAuthorizedCaller() {
if (msg.sender != authorizedCaller) throw;
_;
}
modifier onlyAdmins() {
if (msg.sender != authorizedCaller && msg.sender != owner) throw;
_;
}
function Controller()
{
owner = msg.sender;
destination = msg.sender;
authorizedCaller = msg.sender;
}
function changeAuthorizedCaller(address _newCaller) onlyOwner {
authorizedCaller = _newCaller;
}
function changeDestination(address _dest) onlyOwner {
destination = _dest;
}
function changeOwner(address _owner) onlyOwner {
owner = _owner;
}
function makeWallet() onlyAdmins returns (address wallet) {
wallet = address(new UserWallet(this));
LogNewWallet(wallet);
}
function halt() onlyAdmins {
halted = true;
}
function start() onlyOwner {
halted = false;
}
address public defaultSweeper = address(new DefaultSweeper(this));
mapping (address => address) sweepers;
function addSweeper(address _token, address _sweeper) onlyOwner {
sweepers[_token] = _sweeper;
}
function sweeperOf(address _token) returns (address) {
address sweeper = sweepers[_token];
if (sweeper == 0) sweeper = defaultSweeper;
return sweeper;
}
function logSweep(address from, address to, address token, uint amount) {
LogSweep(from, to, token, amount);
}
}
|
[{"constant":false,"inputs":[{"name":"_token","type":"address"},{"name":"_amount","type":"uint256"}],"name":"sweep","outputs":[{"name":"","type":"bool"}],"payable":false,"type":"function"},{"constant":false,"inputs":[{"name":"_from","type":"address"},{"name":"_value","type":"uint256"},{"name":"_data","type":"bytes"}],"name":"tokenFallback","outputs":[],"payable":false,"type":"function"},{"inputs":[{"name":"_sweeperlist","type":"address"}],"payable":false,"type":"constructor"},{"payable":true,"type":"fallback"}]
|
v0.4.11+commit.68ef5810
| true
| 200
|
000000000000000000000000a3C1E324CA1ce40db73eD6026c4A177F099B5770
|
Default
| false
|
bzzr://4cdd69fdcf3cf6cbee9677fe380fa5f044048aa9e060ec5619a21ca5a5bd4cd1
|
|||
UserWallet
|
0x3385f4adeeed59975f107ebaaf70d83cd32c6cb4
|
Solidity
|
pragma solidity ^0.4.10;
// Copyright 2017 Bittrex
contract AbstractSweeper {
function sweep(address token, uint amount) returns (bool);
function () { throw; }
Controller controller;
function AbstractSweeper(address _controller) {
controller = Controller(_controller);
}
modifier canSweep() {
if (msg.sender != controller.authorizedCaller() && msg.sender != controller.owner()) throw;
if (controller.halted()) throw;
_;
}
}
contract Token {
function balanceOf(address a) returns (uint) {
(a);
return 0;
}
function transfer(address a, uint val) returns (bool) {
(a);
(val);
return false;
}
}
contract DefaultSweeper is AbstractSweeper {
function DefaultSweeper(address controller)
AbstractSweeper(controller) {}
function sweep(address _token, uint _amount)
canSweep
returns (bool) {
bool success = false;
address destination = controller.destination();
if (_token != address(0)) {
Token token = Token(_token);
uint amount = _amount;
if (amount > token.balanceOf(this)) {
return false;
}
success = token.transfer(destination, amount);
}
else {
uint amountInWei = _amount;
if (amountInWei > this.balance) {
return false;
}
success = destination.send(amountInWei);
}
if (success) {
controller.logSweep(this, destination, _token, _amount);
}
return success;
}
}
contract UserWallet {
AbstractSweeperList sweeperList;
function UserWallet(address _sweeperlist) {
sweeperList = AbstractSweeperList(_sweeperlist);
}
function () public payable { }
function tokenFallback(address _from, uint _value, bytes _data) {
(_from);
(_value);
(_data);
}
function sweep(address _token, uint _amount)
returns (bool) {
(_amount);
return sweeperList.sweeperOf(_token).delegatecall(msg.data);
}
}
contract AbstractSweeperList {
function sweeperOf(address _token) returns (address);
}
contract Controller is AbstractSweeperList {
address public owner;
address public authorizedCaller;
address public destination;
bool public halted;
event LogNewWallet(address receiver);
event LogSweep(address indexed from, address indexed to, address indexed token, uint amount);
modifier onlyOwner() {
if (msg.sender != owner) throw;
_;
}
modifier onlyAuthorizedCaller() {
if (msg.sender != authorizedCaller) throw;
_;
}
modifier onlyAdmins() {
if (msg.sender != authorizedCaller && msg.sender != owner) throw;
_;
}
function Controller()
{
owner = msg.sender;
destination = msg.sender;
authorizedCaller = msg.sender;
}
function changeAuthorizedCaller(address _newCaller) onlyOwner {
authorizedCaller = _newCaller;
}
function changeDestination(address _dest) onlyOwner {
destination = _dest;
}
function changeOwner(address _owner) onlyOwner {
owner = _owner;
}
function makeWallet() onlyAdmins returns (address wallet) {
wallet = address(new UserWallet(this));
LogNewWallet(wallet);
}
function halt() onlyAdmins {
halted = true;
}
function start() onlyOwner {
halted = false;
}
address public defaultSweeper = address(new DefaultSweeper(this));
mapping (address => address) sweepers;
function addSweeper(address _token, address _sweeper) onlyOwner {
sweepers[_token] = _sweeper;
}
function sweeperOf(address _token) returns (address) {
address sweeper = sweepers[_token];
if (sweeper == 0) sweeper = defaultSweeper;
return sweeper;
}
function logSweep(address from, address to, address token, uint amount) {
LogSweep(from, to, token, amount);
}
}
|
[{"constant":false,"inputs":[{"name":"_token","type":"address"},{"name":"_amount","type":"uint256"}],"name":"sweep","outputs":[{"name":"","type":"bool"}],"payable":false,"type":"function"},{"constant":false,"inputs":[{"name":"_from","type":"address"},{"name":"_value","type":"uint256"},{"name":"_data","type":"bytes"}],"name":"tokenFallback","outputs":[],"payable":false,"type":"function"},{"inputs":[{"name":"_sweeperlist","type":"address"}],"payable":false,"type":"constructor"},{"payable":true,"type":"fallback"}]
|
v0.4.11+commit.68ef5810
| true
| 200
|
000000000000000000000000a3C1E324CA1ce40db73eD6026c4A177F099B5770
|
Default
| false
|
bzzr://4cdd69fdcf3cf6cbee9677fe380fa5f044048aa9e060ec5619a21ca5a5bd4cd1
|
|||
UserWallet
|
0x3fe603df9d46da0f67d41d2beac84dbdf7109380
|
Solidity
|
pragma solidity ^0.4.10;
// Copyright 2017 Bittrex
contract AbstractSweeper {
function sweep(address token, uint amount) returns (bool);
function () { throw; }
Controller controller;
function AbstractSweeper(address _controller) {
controller = Controller(_controller);
}
modifier canSweep() {
if (msg.sender != controller.authorizedCaller() && msg.sender != controller.owner()) throw;
if (controller.halted()) throw;
_;
}
}
contract Token {
function balanceOf(address a) returns (uint) {
(a);
return 0;
}
function transfer(address a, uint val) returns (bool) {
(a);
(val);
return false;
}
}
contract DefaultSweeper is AbstractSweeper {
function DefaultSweeper(address controller)
AbstractSweeper(controller) {}
function sweep(address _token, uint _amount)
canSweep
returns (bool) {
bool success = false;
address destination = controller.destination();
if (_token != address(0)) {
Token token = Token(_token);
uint amount = _amount;
if (amount > token.balanceOf(this)) {
return false;
}
success = token.transfer(destination, amount);
}
else {
uint amountInWei = _amount;
if (amountInWei > this.balance) {
return false;
}
success = destination.send(amountInWei);
}
if (success) {
controller.logSweep(this, destination, _token, _amount);
}
return success;
}
}
contract UserWallet {
AbstractSweeperList sweeperList;
function UserWallet(address _sweeperlist) {
sweeperList = AbstractSweeperList(_sweeperlist);
}
function () public payable { }
function tokenFallback(address _from, uint _value, bytes _data) {
(_from);
(_value);
(_data);
}
function sweep(address _token, uint _amount)
returns (bool) {
(_amount);
return sweeperList.sweeperOf(_token).delegatecall(msg.data);
}
}
contract AbstractSweeperList {
function sweeperOf(address _token) returns (address);
}
contract Controller is AbstractSweeperList {
address public owner;
address public authorizedCaller;
address public destination;
bool public halted;
event LogNewWallet(address receiver);
event LogSweep(address indexed from, address indexed to, address indexed token, uint amount);
modifier onlyOwner() {
if (msg.sender != owner) throw;
_;
}
modifier onlyAuthorizedCaller() {
if (msg.sender != authorizedCaller) throw;
_;
}
modifier onlyAdmins() {
if (msg.sender != authorizedCaller && msg.sender != owner) throw;
_;
}
function Controller()
{
owner = msg.sender;
destination = msg.sender;
authorizedCaller = msg.sender;
}
function changeAuthorizedCaller(address _newCaller) onlyOwner {
authorizedCaller = _newCaller;
}
function changeDestination(address _dest) onlyOwner {
destination = _dest;
}
function changeOwner(address _owner) onlyOwner {
owner = _owner;
}
function makeWallet() onlyAdmins returns (address wallet) {
wallet = address(new UserWallet(this));
LogNewWallet(wallet);
}
function halt() onlyAdmins {
halted = true;
}
function start() onlyOwner {
halted = false;
}
address public defaultSweeper = address(new DefaultSweeper(this));
mapping (address => address) sweepers;
function addSweeper(address _token, address _sweeper) onlyOwner {
sweepers[_token] = _sweeper;
}
function sweeperOf(address _token) returns (address) {
address sweeper = sweepers[_token];
if (sweeper == 0) sweeper = defaultSweeper;
return sweeper;
}
function logSweep(address from, address to, address token, uint amount) {
LogSweep(from, to, token, amount);
}
}
|
[{"constant":false,"inputs":[{"name":"_token","type":"address"},{"name":"_amount","type":"uint256"}],"name":"sweep","outputs":[{"name":"","type":"bool"}],"payable":false,"type":"function"},{"constant":false,"inputs":[{"name":"_from","type":"address"},{"name":"_value","type":"uint256"},{"name":"_data","type":"bytes"}],"name":"tokenFallback","outputs":[],"payable":false,"type":"function"},{"inputs":[{"name":"_sweeperlist","type":"address"}],"payable":false,"type":"constructor"},{"payable":true,"type":"fallback"}]
|
v0.4.11+commit.68ef5810
| true
| 200
|
000000000000000000000000a3C1E324CA1ce40db73eD6026c4A177F099B5770
|
Default
| false
|
bzzr://4cdd69fdcf3cf6cbee9677fe380fa5f044048aa9e060ec5619a21ca5a5bd4cd1
|
|||
Forwarder
|
0x4bcdc667047fb776cd3e043063678a9c0fc4b583
|
Solidity
|
pragma solidity ^0.4.14;
/**
* Contract that exposes the needed erc20 token functions
*/
contract ERC20Interface {
// Send _value amount of tokens to address _to
function transfer(address _to, uint256 _value) returns (bool success);
// Get the account balance of another account with address _owner
function balanceOf(address _owner) constant returns (uint256 balance);
}
/**
* Contract that will forward any incoming Ether to its creator
*/
contract Forwarder {
// Address to which any funds sent to this contract will be forwarded
address public parentAddress;
event ForwarderDeposited(address from, uint value, bytes data);
event TokensFlushed(
address tokenContractAddress, // The contract address of the token
uint value // Amount of token sent
);
/**
* Create the contract, and set the destination address to that of the creator
*/
function Forwarder() {
parentAddress = msg.sender;
}
/**
* Modifier that will execute internal code block only if the sender is a parent of the forwarder contract
*/
modifier onlyParent {
if (msg.sender != parentAddress) {
throw;
}
_;
}
/**
* Default function; Gets called when Ether is deposited, and forwards it to the destination address
*/
function() payable {
if (!parentAddress.call.value(msg.value)(msg.data))
throw;
// Fire off the deposited event if we can forward it
ForwarderDeposited(msg.sender, msg.value, msg.data);
}
/**
* Execute a token transfer of the full balance from the forwarder token to the main wallet contract
* @param tokenContractAddress the address of the erc20 token contract
*/
function flushTokens(address tokenContractAddress) onlyParent {
ERC20Interface instance = ERC20Interface(tokenContractAddress);
var forwarderAddress = address(this);
var forwarderBalance = instance.balanceOf(forwarderAddress);
if (forwarderBalance == 0) {
return;
}
if (!instance.transfer(parentAddress, forwarderBalance)) {
throw;
}
TokensFlushed(tokenContractAddress, forwarderBalance);
}
/**
* It is possible that funds were sent to this address before the contract was deployed.
* We can flush those funds to the destination address.
*/
function flush() {
if (!parentAddress.call.value(this.balance)())
throw;
}
}
/**
* Basic multi-signer wallet designed for use in a co-signing environment where 2 signatures are required to move funds.
* Typically used in a 2-of-3 signing configuration. Uses ecrecover to allow for 2 signatures in a single transaction.
*/
contract WalletSimple {
// Events
event Deposited(address from, uint value, bytes data);
event SafeModeActivated(address msgSender);
event Transacted(
address msgSender, // Address of the sender of the message initiating the transaction
address otherSigner, // Address of the signer (second signature) used to initiate the transaction
bytes32 operation, // Operation hash (sha3 of toAddress, value, data, expireTime, sequenceId)
address toAddress, // The address the transaction was sent to
uint value, // Amount of Wei sent to the address
bytes data // Data sent when invoking the transaction
);
event TokenTransacted(
address msgSender, // Address of the sender of the message initiating the transaction
address otherSigner, // Address of the signer (second signature) used to initiate the transaction
bytes32 operation, // Operation hash (sha3 of toAddress, value, tokenContractAddress, expireTime, sequenceId)
address toAddress, // The address the transaction was sent to
uint value, // Amount of token sent
address tokenContractAddress // The contract address of the token
);
// Public fields
address[] public signers; // The addresses that can co-sign transactions on the wallet
bool public safeMode = false; // When active, wallet may only send to signer addresses
// Internal fields
uint constant SEQUENCE_ID_WINDOW_SIZE = 10;
uint[10] recentSequenceIds;
/**
* Modifier that will execute internal code block only if the sender is an authorized signer on this wallet
*/
modifier onlysigner {
if (!isSigner(msg.sender)) {
throw;
}
_;
}
/**
* Set up a simple multi-sig wallet by specifying the signers allowed to be used on this wallet.
* 2 signers will be required to send a transaction from this wallet.
* Note: The sender is NOT automatically added to the list of signers.
* Signers CANNOT be changed once they are set
*
* @param allowedSigners An array of signers on the wallet
*/
function WalletSimple(address[] allowedSigners) {
if (allowedSigners.length != 3) {
// Invalid number of signers
throw;
}
signers = allowedSigners;
}
/**
* Gets called when a transaction is received without calling a method
*/
function() payable {
if (msg.value > 0) {
// Fire deposited event if we are receiving funds
Deposited(msg.sender, msg.value, msg.data);
}
}
/**
* Create a new contract (and also address) that forwards funds to this contract
* returns address of newly created forwarder address
*/
function createForwarder() onlysigner returns (address) {
return new Forwarder();
}
/**
* Execute a multi-signature transaction from this wallet using 2 signers: one from msg.sender and the other from ecrecover.
* The signature is a signed form (using eth.sign) of tightly packed toAddress, value, data, expireTime and sequenceId
* Sequence IDs are numbers starting from 1. They are used to prevent replay attacks and may not be repeated.
*
* @param toAddress the destination address to send an outgoing transaction
* @param value the amount in Wei to be sent
* @param data the data to send to the toAddress when invoking the transaction
* @param expireTime the number of seconds since 1970 for which this transaction is valid
* @param sequenceId the unique sequence id obtainable from getNextSequenceId
* @param signature the result of eth.sign on the operationHash sha3(toAddress, value, data, expireTime, sequenceId)
*/
function sendMultiSig(address toAddress, uint value, bytes data, uint expireTime, uint sequenceId, bytes signature) onlysigner {
// Verify the other signer
var operationHash = sha3("ETHER", toAddress, value, data, expireTime, sequenceId);
var otherSigner = verifyMultiSig(toAddress, operationHash, signature, expireTime, sequenceId);
// Success, send the transaction
if (!(toAddress.call.value(value)(data))) {
// Failed executing transaction
throw;
}
Transacted(msg.sender, otherSigner, operationHash, toAddress, value, data);
}
/**
* Execute a multi-signature token transfer from this wallet using 2 signers: one from msg.sender and the other from ecrecover.
* The signature is a signed form (using eth.sign) of tightly packed toAddress, value, tokenContractAddress, expireTime and sequenceId
* Sequence IDs are numbers starting from 1. They are used to prevent replay attacks and may not be repeated.
*
* @param toAddress the destination address to send an outgoing transaction
* @param value the amount in tokens to be sent
* @param tokenContractAddress the address of the erc20 token contract
* @param expireTime the number of seconds since 1970 for which this transaction is valid
* @param sequenceId the unique sequence id obtainable from getNextSequenceId
* @param signature the result of eth.sign on the operationHash sha3(toAddress, value, tokenContractAddress, expireTime, sequenceId)
*/
function sendMultiSigToken(address toAddress, uint value, address tokenContractAddress, uint expireTime, uint sequenceId, bytes signature) onlysigner {
// Verify the other signer
var operationHash = sha3("ERC20", toAddress, value, tokenContractAddress, expireTime, sequenceId);
var otherSigner = verifyMultiSig(toAddress, operationHash, signature, expireTime, sequenceId);
ERC20Interface instance = ERC20Interface(tokenContractAddress);
if (!instance.transfer(toAddress, value)) {
throw;
}
TokenTransacted(msg.sender, otherSigner, operationHash, toAddress, value, tokenContractAddress);
}
/**
* Execute a token flush from one of the forwarder addresses. This transfer needs only a single signature and can be done by any signer
*
* @param forwarderAddress the address of the forwarder address to flush the tokens from
* @param tokenContractAddress the address of the erc20 token contract
*/
function flushForwarderTokens(address forwarderAddress, address tokenContractAddress) onlysigner {
Forwarder forwarder = Forwarder(forwarderAddress);
forwarder.flushTokens(tokenContractAddress);
}
/**
* Do common multisig verification for both eth sends and erc20token transfers
*
* @param toAddress the destination address to send an outgoing transaction
* @param operationHash the sha3 of the toAddress, value, data/tokenContractAddress and expireTime
* @param signature the tightly packed signature of r, s, and v as an array of 65 bytes (returned by eth.sign)
* @param expireTime the number of seconds since 1970 for which this transaction is valid
* @param sequenceId the unique sequence id obtainable from getNextSequenceId
* returns address of the address to send tokens or eth to
*/
function verifyMultiSig(address toAddress, bytes32 operationHash, bytes signature, uint expireTime, uint sequenceId) private returns (address) {
var otherSigner = recoverAddressFromSignature(operationHash, signature);
// Verify if we are in safe mode. In safe mode, the wallet can only send to signers
if (safeMode && !isSigner(toAddress)) {
// We are in safe mode and the toAddress is not a signer. Disallow!
throw;
}
// Verify that the transaction has not expired
if (expireTime < block.timestamp) {
// Transaction expired
throw;
}
// Try to insert the sequence ID. Will throw if the sequence id was invalid
tryInsertSequenceId(sequenceId);
if (!isSigner(otherSigner)) {
// Other signer not on this wallet or operation does not match arguments
throw;
}
if (otherSigner == msg.sender) {
// Cannot approve own transaction
throw;
}
return otherSigner;
}
/**
* Irrevocably puts contract into safe mode. When in this mode, transactions may only be sent to signing addresses.
*/
function activateSafeMode() onlysigner {
safeMode = true;
SafeModeActivated(msg.sender);
}
/**
* Determine if an address is a signer on this wallet
* @param signer address to check
* returns boolean indicating whether address is signer or not
*/
function isSigner(address signer) returns (bool) {
// Iterate through all signers on the wallet and
for (uint i = 0; i < signers.length; i++) {
if (signers[i] == signer) {
return true;
}
}
return false;
}
/**
* Gets the second signer's address using ecrecover
* @param operationHash the sha3 of the toAddress, value, data/tokenContractAddress and expireTime
* @param signature the tightly packed signature of r, s, and v as an array of 65 bytes (returned by eth.sign)
* returns address recovered from the signature
*/
function recoverAddressFromSignature(bytes32 operationHash, bytes signature) private returns (address) {
if (signature.length != 65) {
throw;
}
// We need to unpack the signature, which is given as an array of 65 bytes (from eth.sign)
bytes32 r;
bytes32 s;
uint8 v;
assembly {
r := mload(add(signature, 32))
s := mload(add(signature, 64))
v := and(mload(add(signature, 65)), 255)
}
if (v < 27) {
v += 27; // Ethereum versions are 27 or 28 as opposed to 0 or 1 which is submitted by some signing libs
}
return ecrecover(operationHash, v, r, s);
}
/**
* Verify that the sequence id has not been used before and inserts it. Throws if the sequence ID was not accepted.
* We collect a window of up to 10 recent sequence ids, and allow any sequence id that is not in the window and
* greater than the minimum element in the window.
* @param sequenceId to insert into array of stored ids
*/
function tryInsertSequenceId(uint sequenceId) onlysigner private {
// Keep a pointer to the lowest value element in the window
uint lowestValueIndex = 0;
for (uint i = 0; i < SEQUENCE_ID_WINDOW_SIZE; i++) {
if (recentSequenceIds[i] == sequenceId) {
// This sequence ID has been used before. Disallow!
throw;
}
if (recentSequenceIds[i] < recentSequenceIds[lowestValueIndex]) {
lowestValueIndex = i;
}
}
if (sequenceId < recentSequenceIds[lowestValueIndex]) {
// The sequence ID being used is lower than the lowest value in the window
// so we cannot accept it as it may have been used before
throw;
}
if (sequenceId > (recentSequenceIds[lowestValueIndex] + 10000)) {
// Block sequence IDs which are much higher than the lowest value
// This prevents people blocking the contract by using very large sequence IDs quickly
throw;
}
recentSequenceIds[lowestValueIndex] = sequenceId;
}
/**
* Gets the next available sequence ID for signing when using executeAndConfirm
* returns the sequenceId one higher than the highest currently stored
*/
function getNextSequenceId() returns (uint) {
uint highestSequenceId = 0;
for (uint i = 0; i < SEQUENCE_ID_WINDOW_SIZE; i++) {
if (recentSequenceIds[i] > highestSequenceId) {
highestSequenceId = recentSequenceIds[i];
}
}
return highestSequenceId + 1;
}
}
|
[{"constant":true,"inputs":[],"name":"parentAddress","outputs":[{"name":"","type":"address"}],"payable":false,"type":"function"},{"constant":false,"inputs":[{"name":"tokenContractAddress","type":"address"}],"name":"flushTokens","outputs":[],"payable":false,"type":"function"},{"constant":false,"inputs":[],"name":"flush","outputs":[],"payable":false,"type":"function"},{"inputs":[],"payable":false,"type":"constructor"},{"payable":true,"type":"fallback"},{"anonymous":false,"inputs":[{"indexed":false,"name":"from","type":"address"},{"indexed":false,"name":"value","type":"uint256"},{"indexed":false,"name":"data","type":"bytes"}],"name":"ForwarderDeposited","type":"event"},{"anonymous":false,"inputs":[{"indexed":false,"name":"tokenContractAddress","type":"address"},{"indexed":false,"name":"value","type":"uint256"}],"name":"TokensFlushed","type":"event"}]
|
v0.4.16-nightly.2017.8.11+commit.c84de7fa
| true
| 200
|
Default
| false
|
bzzr://d0f8838ba17108a895d34ae8ef3bff4e0dc9d639c3c51921fee1d17eaa803721
|
||||
UserWallet
|
0xc951809fe27ea86c666ed72db657afb8667abf35
|
Solidity
|
pragma solidity ^0.4.10;
// Copyright 2017 Bittrex
contract AbstractSweeper {
function sweep(address token, uint amount) returns (bool);
function () { throw; }
Controller controller;
function AbstractSweeper(address _controller) {
controller = Controller(_controller);
}
modifier canSweep() {
if (msg.sender != controller.authorizedCaller() && msg.sender != controller.owner()) throw;
if (controller.halted()) throw;
_;
}
}
contract Token {
function balanceOf(address a) returns (uint) {
(a);
return 0;
}
function transfer(address a, uint val) returns (bool) {
(a);
(val);
return false;
}
}
contract DefaultSweeper is AbstractSweeper {
function DefaultSweeper(address controller)
AbstractSweeper(controller) {}
function sweep(address _token, uint _amount)
canSweep
returns (bool) {
bool success = false;
address destination = controller.destination();
if (_token != address(0)) {
Token token = Token(_token);
uint amount = _amount;
if (amount > token.balanceOf(this)) {
return false;
}
success = token.transfer(destination, amount);
}
else {
uint amountInWei = _amount;
if (amountInWei > this.balance) {
return false;
}
success = destination.send(amountInWei);
}
if (success) {
controller.logSweep(this, destination, _token, _amount);
}
return success;
}
}
contract UserWallet {
AbstractSweeperList sweeperList;
function UserWallet(address _sweeperlist) {
sweeperList = AbstractSweeperList(_sweeperlist);
}
function () public payable { }
function tokenFallback(address _from, uint _value, bytes _data) {
(_from);
(_value);
(_data);
}
function sweep(address _token, uint _amount)
returns (bool) {
(_amount);
return sweeperList.sweeperOf(_token).delegatecall(msg.data);
}
}
contract AbstractSweeperList {
function sweeperOf(address _token) returns (address);
}
contract Controller is AbstractSweeperList {
address public owner;
address public authorizedCaller;
address public destination;
bool public halted;
event LogNewWallet(address receiver);
event LogSweep(address indexed from, address indexed to, address indexed token, uint amount);
modifier onlyOwner() {
if (msg.sender != owner) throw;
_;
}
modifier onlyAuthorizedCaller() {
if (msg.sender != authorizedCaller) throw;
_;
}
modifier onlyAdmins() {
if (msg.sender != authorizedCaller && msg.sender != owner) throw;
_;
}
function Controller()
{
owner = msg.sender;
destination = msg.sender;
authorizedCaller = msg.sender;
}
function changeAuthorizedCaller(address _newCaller) onlyOwner {
authorizedCaller = _newCaller;
}
function changeDestination(address _dest) onlyOwner {
destination = _dest;
}
function changeOwner(address _owner) onlyOwner {
owner = _owner;
}
function makeWallet() onlyAdmins returns (address wallet) {
wallet = address(new UserWallet(this));
LogNewWallet(wallet);
}
function halt() onlyAdmins {
halted = true;
}
function start() onlyOwner {
halted = false;
}
address public defaultSweeper = address(new DefaultSweeper(this));
mapping (address => address) sweepers;
function addSweeper(address _token, address _sweeper) onlyOwner {
sweepers[_token] = _sweeper;
}
function sweeperOf(address _token) returns (address) {
address sweeper = sweepers[_token];
if (sweeper == 0) sweeper = defaultSweeper;
return sweeper;
}
function logSweep(address from, address to, address token, uint amount) {
LogSweep(from, to, token, amount);
}
}
|
[{"constant":false,"inputs":[{"name":"_token","type":"address"},{"name":"_amount","type":"uint256"}],"name":"sweep","outputs":[{"name":"","type":"bool"}],"payable":false,"type":"function"},{"constant":false,"inputs":[{"name":"_from","type":"address"},{"name":"_value","type":"uint256"},{"name":"_data","type":"bytes"}],"name":"tokenFallback","outputs":[],"payable":false,"type":"function"},{"inputs":[{"name":"_sweeperlist","type":"address"}],"payable":false,"type":"constructor"},{"payable":true,"type":"fallback"}]
|
v0.4.11+commit.68ef5810
| true
| 200
|
000000000000000000000000a3C1E324CA1ce40db73eD6026c4A177F099B5770
|
Default
| false
|
bzzr://4cdd69fdcf3cf6cbee9677fe380fa5f044048aa9e060ec5619a21ca5a5bd4cd1
|
|||
CollectionContract
|
0x97002ecbf1c4165da3a8c8e94ea778cf2a34a8e5
|
Solidity
|
// File: contracts/CollectionContract.sol
// SPDX-License-Identifier: MIT OR Apache-2.0
pragma solidity ^0.8.0;
import "@openzeppelin/contracts-upgradeable/token/ERC721/extensions/ERC721BurnableUpgradeable.sol";
import "@openzeppelin/contracts-upgradeable/utils/AddressUpgradeable.sol";
import "./interfaces/ICollectionContractInitializer.sol";
import "./interfaces/ICollectionFactory.sol";
import "./interfaces/IGetRoyalties.sol";
import "./interfaces/IProxyCall.sol";
import "./interfaces/ITokenCreator.sol";
import "./interfaces/ITokenCreatorPaymentAddress.sol";
import "./interfaces/IGetFees.sol";
import "./libraries/AccountMigrationLibrary.sol";
import "./libraries/ProxyCall.sol";
import "./libraries/BytesLibrary.sol";
import "./interfaces/IRoyaltyInfo.sol";
/**
* @title A collection of NFTs.
* @notice All NFTs from this contract are minted by the same creator.
* A 10% royalty to the creator is included which may be split with collaborators.
*/
contract CollectionContract is
ICollectionContractInitializer,
IGetRoyalties,
IGetFees,
IRoyaltyInfo,
ITokenCreator,
ITokenCreatorPaymentAddress,
ERC721BurnableUpgradeable
{
using AccountMigrationLibrary for address;
using AddressUpgradeable for address;
using BytesLibrary for bytes;
using ProxyCall for IProxyCall;
uint256 private constant ROYALTY_IN_BASIS_POINTS = 1000;
uint256 private constant ROYALTY_RATIO = 10;
/**
* @notice The baseURI to use for the tokenURI, if undefined then `ipfs://` is used.
*/
string private baseURI_;
/**
* @dev Stores hashes minted to prevent duplicates.
*/
mapping(string => bool) private cidToMinted;
/**
* @notice The factory which was used to create this collection.
* @dev This is used to read common config.
*/
ICollectionFactory public immutable collectionFactory;
/**
* @notice The tokenId of the most recently created NFT.
* @dev Minting starts at tokenId 1. Each mint will use this value + 1.
*/
uint256 public latestTokenId;
/**
* @notice The max tokenId which can be minted, or 0 if there's no limit.
* @dev This value may be set at any time, but once set it cannot be increased.
*/
uint256 public maxTokenId;
/**
* @notice The owner/creator of this NFT collection.
*/
address payable public owner;
/**
* @dev Stores an optional alternate address to receive creator revenue and royalty payments.
* The target address may be a contract which could split or escrow payments.
*/
mapping(uint256 => address payable) private tokenIdToCreatorPaymentAddress;
/**
* @dev Tracks how many tokens have been burned, used to calc the total supply efficiently.
*/
uint256 private burnCounter;
/**
* @dev Stores a CID for each NFT.
*/
mapping(uint256 => string) private _tokenCIDs;
event BaseURIUpdated(string baseURI);
event CreatorMigrated(address indexed originalAddress, address indexed newAddress);
event MaxTokenIdUpdated(uint256 indexed maxTokenId);
event Minted(address indexed creator, uint256 indexed tokenId, string indexed indexedTokenCID, string tokenCID);
event NFTOwnerMigrated(uint256 indexed tokenId, address indexed originalAddress, address indexed newAddress);
event PaymentAddressMigrated(
uint256 indexed tokenId,
address indexed originalAddress,
address indexed newAddress,
address originalPaymentAddress,
address newPaymentAddress
);
event SelfDestruct(address indexed owner);
event TokenCreatorPaymentAddressSet(
address indexed fromPaymentAddress,
address indexed toPaymentAddress,
uint256 indexed tokenId
);
modifier onlyOwner() {
require(msg.sender == owner, "CollectionContract: Caller is not owner");
_;
}
modifier onlyOperator() {
require(collectionFactory.rolesContract().isOperator(msg.sender), "CollectionContract: Caller is not an operator");
_;
}
/**
* @dev The constructor for a proxy can only be used to assign immutable variables.
*/
constructor(address _collectionFactory) {
require(_collectionFactory.isContract(), "CollectionContract: collectionFactory is not a contract");
collectionFactory = ICollectionFactory(_collectionFactory);
}
/**
* @notice Called by the factory on creation.
* @dev This may only be called once.
*/
function initialize(
address payable _creator,
string memory _name,
string memory _symbol
) external initializer {
require(msg.sender == address(collectionFactory), "CollectionContract: Collection must be created via the factory");
__ERC721_init_unchained(_name, _symbol);
owner = _creator;
}
/**
* @notice Allows the owner to mint an NFT defined by its metadata path.
*/
function mint(string memory tokenCID) public returns (uint256 tokenId) {
tokenId = _mint(tokenCID);
}
/**
* @notice Allows the owner to mint and sets approval for all for the provided operator.
* @dev This can be used by creators the first time they mint an NFT to save having to issue a separate approval
* transaction before starting an auction.
*/
function mintAndApprove(string memory tokenCID, address operator) public returns (uint256 tokenId) {
tokenId = _mint(tokenCID);
setApprovalForAll(operator, true);
}
/**
* @notice Allows the owner to mint an NFT and have creator revenue/royalties sent to an alternate address.
*/
function mintWithCreatorPaymentAddress(string memory tokenCID, address payable tokenCreatorPaymentAddress)
public
returns (uint256 tokenId)
{
require(tokenCreatorPaymentAddress != address(0), "CollectionContract: tokenCreatorPaymentAddress is required");
tokenId = mint(tokenCID);
_setTokenCreatorPaymentAddress(tokenId, tokenCreatorPaymentAddress);
}
/**
* @notice Allows the owner to mint an NFT and have creator revenue/royalties sent to an alternate address.
* Also sets approval for all for the provided operator.
* @dev This can be used by creators the first time they mint an NFT to save having to issue a separate approval
* transaction before starting an auction.
*/
function mintWithCreatorPaymentAddressAndApprove(
string memory tokenCID,
address payable tokenCreatorPaymentAddress,
address operator
) public returns (uint256 tokenId) {
tokenId = mintWithCreatorPaymentAddress(tokenCID, tokenCreatorPaymentAddress);
setApprovalForAll(operator, true);
}
/**
* @notice Allows the owner to mint an NFT and have creator revenue/royalties sent to an alternate address
* which is defined by a contract call, typically a proxy contract address representing the payment terms.
* @param paymentAddressFactory The contract to call which will return the address to use for payments.
* @param paymentAddressCallData The call details to sent to the factory provided.
*/
function mintWithCreatorPaymentFactory(
string memory tokenCID,
address paymentAddressFactory,
bytes memory paymentAddressCallData
) public returns (uint256 tokenId) {
address payable tokenCreatorPaymentAddress = collectionFactory
.proxyCallContract()
.proxyCallAndReturnContractAddress(paymentAddressFactory, paymentAddressCallData);
tokenId = mintWithCreatorPaymentAddress(tokenCID, tokenCreatorPaymentAddress);
}
/**
* @notice Allows the owner to mint an NFT and have creator revenue/royalties sent to an alternate address
* which is defined by a contract call, typically a proxy contract address representing the payment terms.
* Also sets approval for all for the provided operator.
* @param paymentAddressFactory The contract to call which will return the address to use for payments.
* @param paymentAddressCallData The call details to sent to the factory provided.
* @dev This can be used by creators the first time they mint an NFT to save having to issue a separate approval
* transaction before starting an auction.
*/
function mintWithCreatorPaymentFactoryAndApprove(
string memory tokenCID,
address paymentAddressFactory,
bytes memory paymentAddressCallData,
address operator
) public returns (uint256 tokenId) {
tokenId = mintWithCreatorPaymentFactory(tokenCID, paymentAddressFactory, paymentAddressCallData);
setApprovalForAll(operator, true);
}
/**
* @notice Allows the owner to set a max tokenID.
* This provides a guarantee to collectors about the limit of this collection contract, if applicable.
* @dev Once this value has been set, it may be decreased but can never be increased.
*/
function updateMaxTokenId(uint256 _maxTokenId) external onlyOwner {
require(_maxTokenId > 0, "CollectionContract: Max token ID may not be cleared");
require(maxTokenId == 0 || _maxTokenId < maxTokenId, "CollectionContract: Max token ID may not increase");
require(latestTokenId + 1 <= _maxTokenId, "CollectionContract: Max token ID must be greater than last mint");
maxTokenId = _maxTokenId;
emit MaxTokenIdUpdated(_maxTokenId);
}
/**
* @notice Allows the owner to assign a baseURI to use for the tokenURI instead of the default `ipfs://`.
*/
function updateBaseURI(string calldata baseURIOverride) external onlyOwner {
baseURI_ = baseURIOverride;
emit BaseURIUpdated(baseURIOverride);
}
/**
* @notice Allows the creator to burn if they currently own the NFT.
*/
function burn(uint256 tokenId) public override onlyOwner {
super.burn(tokenId);
}
/**
* @notice Allows the collection owner to destroy this contract only if
* no NFTs have been minted yet.
*/
function selfDestruct() external onlyOwner {
require(totalSupply() == 0, "CollectionContract: Any NFTs minted must be burned first");
emit SelfDestruct(msg.sender);
selfdestruct(payable(msg.sender));
}
/**
* @notice Allows an NFT owner or creator and Foundation to work together in order to update the creator
* to a new account and/or transfer NFTs to that account.
* @param signature Message `I authorize Foundation to migrate my account to ${newAccount.address.toLowerCase()}`
* signed by the original account.
* @dev This will gracefully skip any NFTs that have been burned or transferred.
*/
function adminAccountMigration(
uint256[] calldata ownedTokenIds,
address originalAddress,
address payable newAddress,
bytes calldata signature
) public onlyOperator {
originalAddress.requireAuthorizedAccountMigration(newAddress, signature);
for (uint256 i = 0; i < ownedTokenIds.length; i++) {
uint256 tokenId = ownedTokenIds[i];
// Check that the token exists and still is owned by the originalAddress
// so that frontrunning a burn or transfer will not cause the entire tx to revert
if (_exists(tokenId) && ownerOf(tokenId) == originalAddress) {
_transfer(originalAddress, newAddress, tokenId);
emit NFTOwnerMigrated(tokenId, originalAddress, newAddress);
}
}
if (owner == originalAddress) {
owner = newAddress;
emit CreatorMigrated(originalAddress, newAddress);
}
}
/**
* @notice Allows a split recipient and Foundation to work together in order to update the payment address
* to a new account.
* @param signature Message `I authorize Foundation to migrate my account to ${newAccount.address.toLowerCase()}`
* signed by the original account.
*/
function adminAccountMigrationForPaymentAddresses(
uint256[] calldata paymentAddressTokenIds,
address paymentAddressFactory,
bytes memory paymentAddressCallData,
uint256 addressLocationInCallData,
address originalAddress,
address payable newAddress,
bytes calldata signature
) public onlyOperator {
originalAddress.requireAuthorizedAccountMigration(newAddress, signature);
_adminAccountRecoveryForPaymentAddresses(
paymentAddressTokenIds,
paymentAddressFactory,
paymentAddressCallData,
addressLocationInCallData,
originalAddress,
newAddress
);
}
function baseURI() external view returns (string memory) {
return _baseURI();
}
/**
* @notice Returns an array of recipient addresses to which royalties for secondary sales should be sent.
* The expected royalty amount is communicated with `getFeeBps`.
*/
function getFeeRecipients(uint256 id) external view returns (address payable[] memory recipients) {
recipients = new address payable[](1);
recipients[0] = getTokenCreatorPaymentAddress(id);
}
/**
* @notice Returns an array of royalties to be sent for secondary sales in basis points.
* The expected recipients is communicated with `getFeeRecipients`.
*/
function getFeeBps(
uint256 /* id */
) external pure returns (uint256[] memory feesInBasisPoints) {
feesInBasisPoints = new uint256[](1);
feesInBasisPoints[0] = ROYALTY_IN_BASIS_POINTS;
}
/**
* @notice Checks if the creator has already minted a given NFT using this collection contract.
*/
function getHasMintedCID(string memory tokenCID) public view returns (bool) {
return cidToMinted[tokenCID];
}
/**
* @notice Returns an array of royalties to be sent for secondary sales.
*/
function getRoyalties(uint256 tokenId)
external
view
returns (address payable[] memory recipients, uint256[] memory feesInBasisPoints)
{
recipients = new address payable[](1);
recipients[0] = getTokenCreatorPaymentAddress(tokenId);
feesInBasisPoints = new uint256[](1);
feesInBasisPoints[0] = ROYALTY_IN_BASIS_POINTS;
}
/**
* @notice Returns the receiver and the amount to be sent for a secondary sale.
*/
function royaltyInfo(uint256 _tokenId, uint256 _salePrice)
external
view
returns (address receiver, uint256 royaltyAmount)
{
receiver = getTokenCreatorPaymentAddress(_tokenId);
unchecked {
royaltyAmount = _salePrice / ROYALTY_RATIO;
}
}
/**
* @notice Returns the creator for an NFT, which is always the collection owner.
*/
function tokenCreator(
uint256 /* tokenId */
) external view returns (address payable) {
return owner;
}
/**
* @notice Returns the desired payment address to be used for any transfers to the creator.
* @dev The payment address may be assigned for each individual NFT, if not defined the collection owner is returned.
*/
function getTokenCreatorPaymentAddress(uint256 tokenId)
public
view
returns (address payable tokenCreatorPaymentAddress)
{
tokenCreatorPaymentAddress = tokenIdToCreatorPaymentAddress[tokenId];
if (tokenCreatorPaymentAddress == address(0)) {
tokenCreatorPaymentAddress = owner;
}
}
/**
* @notice Count of NFTs tracked by this contract.
* @dev From the ERC-721 enumerable standard.
*/
function totalSupply() public view returns (uint256) {
unchecked {
return latestTokenId - burnCounter;
}
}
function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) {
if (
interfaceId == type(IGetRoyalties).interfaceId ||
interfaceId == type(ITokenCreator).interfaceId ||
interfaceId == type(ITokenCreatorPaymentAddress).interfaceId ||
interfaceId == type(IGetFees).interfaceId ||
interfaceId == type(IRoyaltyInfo).interfaceId
) {
return true;
}
return super.supportsInterface(interfaceId);
}
function tokenURI(uint256 tokenId) public view virtual override returns (string memory) {
require(_exists(tokenId), "CollectionContract: URI query for nonexistent token");
return string(abi.encodePacked(_baseURI(), _tokenCIDs[tokenId]));
}
function _mint(string memory tokenCID) private onlyOwner returns (uint256 tokenId) {
require(bytes(tokenCID).length > 0, "CollectionContract: tokenCID is required");
require(!cidToMinted[tokenCID], "CollectionContract: NFT was already minted");
unchecked {
tokenId = ++latestTokenId;
require(maxTokenId == 0 || tokenId <= maxTokenId, "CollectionContract: Max token count has already been minted");
cidToMinted[tokenCID] = true;
_tokenCIDs[tokenId] = tokenCID;
_safeMint(msg.sender, tokenId, "");
emit Minted(msg.sender, tokenId, tokenCID, tokenCID);
}
}
/**
* @dev Allow setting a different address to send payments to for both primary sale revenue
* and secondary sales royalties.
*/
function _setTokenCreatorPaymentAddress(uint256 tokenId, address payable tokenCreatorPaymentAddress) internal {
emit TokenCreatorPaymentAddressSet(tokenIdToCreatorPaymentAddress[tokenId], tokenCreatorPaymentAddress, tokenId);
tokenIdToCreatorPaymentAddress[tokenId] = tokenCreatorPaymentAddress;
}
function _burn(uint256 tokenId) internal override {
delete cidToMinted[_tokenCIDs[tokenId]];
delete tokenIdToCreatorPaymentAddress[tokenId];
delete _tokenCIDs[tokenId];
unchecked {
burnCounter++;
}
super._burn(tokenId);
}
/**
* @dev Split into a second function to avoid stack too deep errors
*/
function _adminAccountRecoveryForPaymentAddresses(
uint256[] calldata paymentAddressTokenIds,
address paymentAddressFactory,
bytes memory paymentAddressCallData,
uint256 addressLocationInCallData,
address originalAddress,
address payable newAddress
) private {
// Call the factory and get the originalPaymentAddress
address payable originalPaymentAddress = collectionFactory.proxyCallContract().proxyCallAndReturnContractAddress(
paymentAddressFactory,
paymentAddressCallData
);
// Confirm the original address and swap with the new address
paymentAddressCallData.replaceAtIf(addressLocationInCallData, originalAddress, newAddress);
// Call the factory and get the newPaymentAddress
address payable newPaymentAddress = collectionFactory.proxyCallContract().proxyCallAndReturnContractAddress(
paymentAddressFactory,
paymentAddressCallData
);
// For each token, confirm the expected payment address and then update to the new one
for (uint256 i = 0; i < paymentAddressTokenIds.length; i++) {
uint256 tokenId = paymentAddressTokenIds[i];
require(
tokenIdToCreatorPaymentAddress[tokenId] == originalPaymentAddress,
"CollectionContract: Payment address is not the expected value"
);
_setTokenCreatorPaymentAddress(tokenId, newPaymentAddress);
emit PaymentAddressMigrated(tokenId, originalAddress, newAddress, originalPaymentAddress, newPaymentAddress);
}
}
function _baseURI() internal view override returns (string memory) {
if (bytes(baseURI_).length > 0) {
return baseURI_;
}
return "ipfs://";
}
}
// File: @openzeppelin/contracts-upgradeable/token/ERC721/extensions/ERC721BurnableUpgradeable.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (token/ERC721/extensions/ERC721Burnable.sol)
pragma solidity ^0.8.0;
import "../ERC721Upgradeable.sol";
import "../../../utils/ContextUpgradeable.sol";
import "../../../proxy/utils/Initializable.sol";
/**
* @title ERC721 Burnable Token
* @dev ERC721 Token that can be irreversibly burned (destroyed).
*/
abstract contract ERC721BurnableUpgradeable is Initializable, ContextUpgradeable, ERC721Upgradeable {
function __ERC721Burnable_init() internal onlyInitializing {
__Context_init_unchained();
__ERC165_init_unchained();
__ERC721Burnable_init_unchained();
}
function __ERC721Burnable_init_unchained() internal onlyInitializing {
}
/**
* @dev Burns `tokenId`. See {ERC721-_burn}.
*
* Requirements:
*
* - The caller must own `tokenId` or be an approved operator.
*/
function burn(uint256 tokenId) public virtual {
//solhint-disable-next-line max-line-length
require(_isApprovedOrOwner(_msgSender(), tokenId), "ERC721Burnable: caller is not owner nor approved");
_burn(tokenId);
}
uint256[50] private __gap;
}
// File: @openzeppelin/contracts-upgradeable/utils/AddressUpgradeable.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (utils/Address.sol)
pragma solidity ^0.8.0;
/**
* @dev Collection of functions related to the address type
*/
library AddressUpgradeable {
/**
* @dev Returns true if `account` is a contract.
*
* [IMPORTANT]
* ====
* It is unsafe to assume that an address for which this function returns
* false is an externally-owned account (EOA) and not a contract.
*
* Among others, `isContract` will return false for the following
* types of addresses:
*
* - an externally-owned account
* - a contract in construction
* - an address where a contract will be created
* - an address where a contract lived, but was destroyed
* ====
*/
function isContract(address account) internal view returns (bool) {
// This method relies on extcodesize, which returns 0 for contracts in
// construction, since the code is only stored at the end of the
// constructor execution.
uint256 size;
assembly {
size := extcodesize(account)
}
return size > 0;
}
/**
* @dev Replacement for Solidity's `transfer`: sends `amount` wei to
* `recipient`, forwarding all available gas and reverting on errors.
*
* https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost
* of certain opcodes, possibly making contracts go over the 2300 gas limit
* imposed by `transfer`, making them unable to receive funds via
* `transfer`. {sendValue} removes this limitation.
*
* https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more].
*
* IMPORTANT: because control is transferred to `recipient`, care must be
* taken to not create reentrancy vulnerabilities. Consider using
* {ReentrancyGuard} or the
* https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern].
*/
function sendValue(address payable recipient, uint256 amount) internal {
require(address(this).balance >= amount, "Address: insufficient balance");
(bool success, ) = recipient.call{value: amount}("");
require(success, "Address: unable to send value, recipient may have reverted");
}
/**
* @dev Performs a Solidity function call using a low level `call`. A
* plain `call` is an unsafe replacement for a function call: use this
* function instead.
*
* If `target` reverts with a revert reason, it is bubbled up by this
* function (like regular Solidity function calls).
*
* Returns the raw returned data. To convert to the expected return value,
* use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`].
*
* Requirements:
*
* - `target` must be a contract.
* - calling `target` with `data` must not revert.
*
* _Available since v3.1._
*/
function functionCall(address target, bytes memory data) internal returns (bytes memory) {
return functionCall(target, data, "Address: low-level call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with
* `errorMessage` as a fallback revert reason when `target` reverts.
*
* _Available since v3.1._
*/
function functionCall(
address target,
bytes memory data,
string memory errorMessage
) internal returns (bytes memory) {
return functionCallWithValue(target, data, 0, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but also transferring `value` wei to `target`.
*
* Requirements:
*
* - the calling contract must have an ETH balance of at least `value`.
* - the called Solidity function must be `payable`.
*
* _Available since v3.1._
*/
function functionCallWithValue(
address target,
bytes memory data,
uint256 value
) internal returns (bytes memory) {
return functionCallWithValue(target, data, value, "Address: low-level call with value failed");
}
/**
* @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but
* with `errorMessage` as a fallback revert reason when `target` reverts.
*
* _Available since v3.1._
*/
function functionCallWithValue(
address target,
bytes memory data,
uint256 value,
string memory errorMessage
) internal returns (bytes memory) {
require(address(this).balance >= value, "Address: insufficient balance for call");
require(isContract(target), "Address: call to non-contract");
(bool success, bytes memory returndata) = target.call{value: value}(data);
return verifyCallResult(success, returndata, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but performing a static call.
*
* _Available since v3.3._
*/
function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) {
return functionStaticCall(target, data, "Address: low-level static call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`],
* but performing a static call.
*
* _Available since v3.3._
*/
function functionStaticCall(
address target,
bytes memory data,
string memory errorMessage
) internal view returns (bytes memory) {
require(isContract(target), "Address: static call to non-contract");
(bool success, bytes memory returndata) = target.staticcall(data);
return verifyCallResult(success, returndata, errorMessage);
}
/**
* @dev Tool to verifies that a low level call was successful, and revert if it wasn't, either by bubbling the
* revert reason using the provided one.
*
* _Available since v4.3._
*/
function verifyCallResult(
bool success,
bytes memory returndata,
string memory errorMessage
) internal pure returns (bytes memory) {
if (success) {
return returndata;
} else {
// Look for revert reason and bubble it up if present
if (returndata.length > 0) {
// The easiest way to bubble the revert reason is using memory via assembly
assembly {
let returndata_size := mload(returndata)
revert(add(32, returndata), returndata_size)
}
} else {
revert(errorMessage);
}
}
}
}
// File: contracts/interfaces/ICollectionContractInitializer.sol
// SPDX-License-Identifier: MIT OR Apache-2.0
pragma solidity ^0.8.0;
interface ICollectionContractInitializer {
function initialize(
address payable _creator,
string memory _name,
string memory _symbol
) external;
}
// File: contracts/interfaces/ICollectionFactory.sol
// SPDX-License-Identifier: MIT OR Apache-2.0
pragma solidity ^0.8.0;
import "./IRoles.sol";
import "./IProxyCall.sol";
interface ICollectionFactory {
function rolesContract() external returns (IRoles);
function proxyCallContract() external returns (IProxyCall);
}
// File: contracts/interfaces/IGetRoyalties.sol
// SPDX-License-Identifier: MIT OR Apache-2.0
pragma solidity ^0.8.0;
interface IGetRoyalties {
function getRoyalties(uint256 tokenId)
external
view
returns (address payable[] memory recipients, uint256[] memory feesInBasisPoints);
}
// File: contracts/interfaces/IProxyCall.sol
// SPDX-License-Identifier: MIT OR Apache-2.0
pragma solidity ^0.8.0;
interface IProxyCall {
function proxyCallAndReturnAddress(address externalContract, bytes calldata callData)
external
returns (address payable result);
}
// File: contracts/interfaces/ITokenCreator.sol
// SPDX-License-Identifier: MIT OR Apache-2.0
pragma solidity ^0.8.0;
interface ITokenCreator {
function tokenCreator(uint256 tokenId) external view returns (address payable);
}
// File: contracts/interfaces/ITokenCreatorPaymentAddress.sol
// SPDX-License-Identifier: MIT OR Apache-2.0
pragma solidity ^0.8.0;
interface ITokenCreatorPaymentAddress {
function getTokenCreatorPaymentAddress(uint256 tokenId)
external
view
returns (address payable tokenCreatorPaymentAddress);
}
// File: contracts/interfaces/IGetFees.sol
// SPDX-License-Identifier: MIT OR Apache-2.0
pragma solidity ^0.8.0;
/**
* @notice An interface for communicating fees to 3rd party marketplaces.
* @dev Originally implemented in mainnet contract 0x44d6e8933f8271abcf253c72f9ed7e0e4c0323b3
*/
interface IGetFees {
function getFeeRecipients(uint256 id) external view returns (address payable[] memory);
function getFeeBps(uint256 id) external view returns (uint256[] memory);
}
// File: contracts/libraries/AccountMigrationLibrary.sol
// SPDX-License-Identifier: MIT OR Apache-2.0
pragma solidity ^0.8.0;
import "@openzeppelin/contracts/utils/cryptography/ECDSA.sol";
import "@openzeppelin/contracts/utils/cryptography/SignatureChecker.sol";
import "@openzeppelin/contracts/utils/Strings.sol";
/**
* @notice Checks for a valid signature authorizing the migration of an account to a new address.
* @dev This is shared by both the NFT contracts and FNDNFTMarket, and the same signature authorizes both.
*/
library AccountMigrationLibrary {
using ECDSA for bytes;
using SignatureChecker for address;
using Strings for uint256;
// From https://ethereum.stackexchange.com/questions/8346/convert-address-to-string
function _toAsciiString(address x) private pure returns (string memory) {
bytes memory s = new bytes(42);
s[0] = "0";
s[1] = "x";
for (uint256 i = 0; i < 20; i++) {
bytes1 b = bytes1(uint8(uint256(uint160(x)) / (2**(8 * (19 - i)))));
bytes1 hi = bytes1(uint8(b) / 16);
bytes1 lo = bytes1(uint8(b) - 16 * uint8(hi));
s[2 * i + 2] = _char(hi);
s[2 * i + 3] = _char(lo);
}
return string(s);
}
function _char(bytes1 b) private pure returns (bytes1 c) {
if (uint8(b) < 10) return bytes1(uint8(b) + 0x30);
else return bytes1(uint8(b) + 0x57);
}
/**
* @dev Confirms the msg.sender is a Foundation operator and that the signature provided is valid.
* @param signature Message `I authorize Foundation to migrate my account to ${newAccount.address.toLowerCase()}`
* signed by the original account.
*/
function requireAuthorizedAccountMigration(
address originalAddress,
address newAddress,
bytes memory signature
) internal view {
require(originalAddress != newAddress, "AccountMigration: Cannot migrate to the same account");
bytes32 hash = abi
.encodePacked("I authorize Foundation to migrate my account to ", _toAsciiString(newAddress))
.toEthSignedMessageHash();
require(
originalAddress.isValidSignatureNow(hash, signature),
"AccountMigration: Signature must be from the original account"
);
}
}
// File: contracts/libraries/ProxyCall.sol
// SPDX-License-Identifier: MIT OR Apache-2.0
pragma solidity ^0.8.0;
import "@openzeppelin/contracts-upgradeable/utils/AddressUpgradeable.sol";
import "../interfaces/IProxyCall.sol";
/**
* @notice Forwards arbitrary calls to an external contract to be processed.
* @dev This is used so that the from address of the calling contract does not have
* any special permissions (e.g. ERC-20 transfer).
*/
library ProxyCall {
using AddressUpgradeable for address payable;
/**
* @dev Used by other mixins to make external calls through the proxy contract.
* This will fail if the proxyCall address is address(0).
*/
function proxyCallAndReturnContractAddress(
IProxyCall proxyCall,
address externalContract,
bytes memory callData
) internal returns (address payable result) {
result = proxyCall.proxyCallAndReturnAddress(externalContract, callData);
require(result.isContract(), "ProxyCall: address returned is not a contract");
}
}
// File: contracts/libraries/BytesLibrary.sol
// SPDX-License-Identifier: MIT OR Apache-2.0
pragma solidity ^0.8.0;
/**
* @notice A library for manipulation of byte arrays.
*/
library BytesLibrary {
/**
* @dev Replace the address at the given location in a byte array if the contents at that location
* match the expected address.
*/
function replaceAtIf(
bytes memory data,
uint256 startLocation,
address expectedAddress,
address newAddress
) internal pure {
bytes memory expectedData = abi.encodePacked(expectedAddress);
bytes memory newData = abi.encodePacked(newAddress);
// An address is 20 bytes long
for (uint256 i = 0; i < 20; i++) {
uint256 dataLocation = startLocation + i;
require(data[dataLocation] == expectedData[i], "Bytes: Data provided does not include the expectedAddress");
data[dataLocation] = newData[i];
}
}
/**
* @dev Checks if the call data starts with the given function signature.
*/
function startsWith(bytes memory callData, bytes4 functionSig) internal pure returns (bool) {
// A signature is 4 bytes long
if (callData.length < 4) {
return false;
}
for (uint256 i = 0; i < 4; i++) {
if (callData[i] != functionSig[i]) {
return false;
}
}
return true;
}
}
// File: contracts/interfaces/IRoyaltyInfo.sol
// SPDX-License-Identifier: MIT OR Apache-2.0
pragma solidity ^0.8.0;
/**
* @notice Interface for EIP-2981: NFT Royalty Standard.
* For more see: https://eips.ethereum.org/EIPS/eip-2981.
*/
interface IRoyaltyInfo {
/// @notice Called with the sale price to determine how much royalty
// is owed and to whom.
/// @param _tokenId - the NFT asset queried for royalty information
/// @param _salePrice - the sale price of the NFT asset specified by _tokenId
/// @return receiver - address of who should be sent the royalty payment
/// @return royaltyAmount - the royalty payment amount for _salePrice
function royaltyInfo(uint256 _tokenId, uint256 _salePrice)
external
view
returns (address receiver, uint256 royaltyAmount);
}
// File: @openzeppelin/contracts-upgradeable/token/ERC721/ERC721Upgradeable.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (token/ERC721/ERC721.sol)
pragma solidity ^0.8.0;
import "./IERC721Upgradeable.sol";
import "./IERC721ReceiverUpgradeable.sol";
import "./extensions/IERC721MetadataUpgradeable.sol";
import "../../utils/AddressUpgradeable.sol";
import "../../utils/ContextUpgradeable.sol";
import "../../utils/StringsUpgradeable.sol";
import "../../utils/introspection/ERC165Upgradeable.sol";
import "../../proxy/utils/Initializable.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 ERC721Upgradeable is Initializable, ContextUpgradeable, ERC165Upgradeable, IERC721Upgradeable, IERC721MetadataUpgradeable {
using AddressUpgradeable for address;
using StringsUpgradeable 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.
*/
function __ERC721_init(string memory name_, string memory symbol_) internal onlyInitializing {
__Context_init_unchained();
__ERC165_init_unchained();
__ERC721_init_unchained(name_, symbol_);
}
function __ERC721_init_unchained(string memory name_, string memory symbol_) internal onlyInitializing {
_name = name_;
_symbol = symbol_;
}
/**
* @dev See {IERC165-supportsInterface}.
*/
function supportsInterface(bytes4 interfaceId) public view virtual override(ERC165Upgradeable, IERC165Upgradeable) returns (bool) {
return
interfaceId == type(IERC721Upgradeable).interfaceId ||
interfaceId == type(IERC721MetadataUpgradeable).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 = ERC721Upgradeable.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 = ERC721Upgradeable.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 = ERC721Upgradeable.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(ERC721Upgradeable.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(ERC721Upgradeable.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 IERC721ReceiverUpgradeable(to).onERC721Received(_msgSender(), from, tokenId, _data) returns (bytes4 retval) {
return retval == IERC721ReceiverUpgradeable.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 {}
uint256[44] private __gap;
}
// File: @openzeppelin/contracts-upgradeable/utils/ContextUpgradeable.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (utils/Context.sol)
pragma solidity ^0.8.0;
import "../proxy/utils/Initializable.sol";
/**
* @dev Provides information about the current execution context, including the
* sender of the transaction and its data. While these are generally available
* via msg.sender and msg.data, they should not be accessed in such a direct
* manner, since when dealing with meta-transactions the account sending and
* paying for execution may not be the actual sender (as far as an application
* is concerned).
*
* This contract is only required for intermediate, library-like contracts.
*/
abstract contract ContextUpgradeable is Initializable {
function __Context_init() internal onlyInitializing {
__Context_init_unchained();
}
function __Context_init_unchained() internal onlyInitializing {
}
function _msgSender() internal view virtual returns (address) {
return msg.sender;
}
function _msgData() internal view virtual returns (bytes calldata) {
return msg.data;
}
uint256[50] private __gap;
}
// File: @openzeppelin/contracts-upgradeable/proxy/utils/Initializable.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (proxy/utils/Initializable.sol)
pragma solidity ^0.8.0;
import "../../utils/AddressUpgradeable.sol";
/**
* @dev This is a base contract to aid in writing upgradeable contracts, or any kind of contract that will be deployed
* behind a proxy. Since a proxied contract can't have a constructor, it's common to move constructor logic to an
* external initializer function, usually called `initialize`. It then becomes necessary to protect this initializer
* function so it can only be called once. The {initializer} modifier provided by this contract will have this effect.
*
* TIP: To avoid leaving the proxy in an uninitialized state, the initializer function should be called as early as
* possible by providing the encoded function call as the `_data` argument to {ERC1967Proxy-constructor}.
*
* CAUTION: When used with inheritance, manual care must be taken to not invoke a parent initializer twice, or to ensure
* that all initializers are idempotent. This is not verified automatically as constructors are by Solidity.
*
* [CAUTION]
* ====
* Avoid leaving a contract uninitialized.
*
* An uninitialized contract can be taken over by an attacker. This applies to both a proxy and its implementation
* contract, which may impact the proxy. To initialize the implementation contract, you can either invoke the
* initializer manually, or you can include a constructor to automatically mark it as initialized when it is deployed:
*
* [.hljs-theme-light.nopadding]
* ```
* /// @custom:oz-upgrades-unsafe-allow constructor
* constructor() initializer {}
* ```
* ====
*/
abstract contract Initializable {
/**
* @dev Indicates that the contract has been initialized.
*/
bool private _initialized;
/**
* @dev Indicates that the contract is in the process of being initialized.
*/
bool private _initializing;
/**
* @dev Modifier to protect an initializer function from being invoked twice.
*/
modifier initializer() {
// If the contract is initializing we ignore whether _initialized is set in order to support multiple
// inheritance patterns, but we only do this in the context of a constructor, because in other contexts the
// contract may have been reentered.
require(_initializing ? _isConstructor() : !_initialized, "Initializable: contract is already initialized");
bool isTopLevelCall = !_initializing;
if (isTopLevelCall) {
_initializing = true;
_initialized = true;
}
_;
if (isTopLevelCall) {
_initializing = false;
}
}
/**
* @dev Modifier to protect an initialization function so that it can only be invoked by functions with the
* {initializer} modifier, directly or indirectly.
*/
modifier onlyInitializing() {
require(_initializing, "Initializable: contract is not initializing");
_;
}
function _isConstructor() private view returns (bool) {
return !AddressUpgradeable.isContract(address(this));
}
}
// File: @openzeppelin/contracts-upgradeable/token/ERC721/IERC721Upgradeable.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (token/ERC721/IERC721.sol)
pragma solidity ^0.8.0;
import "../../utils/introspection/IERC165Upgradeable.sol";
/**
* @dev Required interface of an ERC721 compliant contract.
*/
interface IERC721Upgradeable is IERC165Upgradeable {
/**
* @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-upgradeable/token/ERC721/IERC721ReceiverUpgradeable.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (token/ERC721/IERC721Receiver.sol)
pragma solidity ^0.8.0;
/**
* @title ERC721 token receiver interface
* @dev Interface for any contract that wants to support safeTransfers
* from ERC721 asset contracts.
*/
interface IERC721ReceiverUpgradeable {
/**
* @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-upgradeable/token/ERC721/extensions/IERC721MetadataUpgradeable.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (token/ERC721/extensions/IERC721Metadata.sol)
pragma solidity ^0.8.0;
import "../IERC721Upgradeable.sol";
/**
* @title ERC-721 Non-Fungible Token Standard, optional metadata extension
* @dev See https://eips.ethereum.org/EIPS/eip-721
*/
interface IERC721MetadataUpgradeable is IERC721Upgradeable {
/**
* @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-upgradeable/utils/StringsUpgradeable.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (utils/Strings.sol)
pragma solidity ^0.8.0;
/**
* @dev String operations.
*/
library StringsUpgradeable {
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-upgradeable/utils/introspection/ERC165Upgradeable.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (utils/introspection/ERC165.sol)
pragma solidity ^0.8.0;
import "./IERC165Upgradeable.sol";
import "../../proxy/utils/Initializable.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 ERC165Upgradeable is Initializable, IERC165Upgradeable {
function __ERC165_init() internal onlyInitializing {
__ERC165_init_unchained();
}
function __ERC165_init_unchained() internal onlyInitializing {
}
/**
* @dev See {IERC165-supportsInterface}.
*/
function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) {
return interfaceId == type(IERC165Upgradeable).interfaceId;
}
uint256[50] private __gap;
}
// File: @openzeppelin/contracts-upgradeable/utils/introspection/IERC165Upgradeable.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (utils/introspection/IERC165.sol)
pragma solidity ^0.8.0;
/**
* @dev Interface of the ERC165 standard, as defined in the
* https://eips.ethereum.org/EIPS/eip-165[EIP].
*
* Implementers can declare support of contract interfaces, which can then be
* queried by others ({ERC165Checker}).
*
* For an implementation, see {ERC165}.
*/
interface IERC165Upgradeable {
/**
* @dev Returns true if this contract implements the interface defined by
* `interfaceId`. See the corresponding
* https://eips.ethereum.org/EIPS/eip-165#how-interfaces-are-identified[EIP section]
* to learn more about how these ids are created.
*
* This function call must use less than 30 000 gas.
*/
function supportsInterface(bytes4 interfaceId) external view returns (bool);
}
// File: contracts/interfaces/IRoles.sol
// SPDX-License-Identifier: MIT OR Apache-2.0
pragma solidity ^0.8.0;
/**
* @notice Interface for a contract which implements admin roles.
*/
interface IRoles {
function isAdmin(address account) external view returns (bool);
function isOperator(address account) external view returns (bool);
}
// File: @openzeppelin/contracts/utils/cryptography/ECDSA.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (utils/cryptography/ECDSA.sol)
pragma solidity ^0.8.0;
import "../Strings.sol";
/**
* @dev Elliptic Curve Digital Signature Algorithm (ECDSA) operations.
*
* These functions can be used to verify that a message was signed by the holder
* of the private keys of a given address.
*/
library ECDSA {
enum RecoverError {
NoError,
InvalidSignature,
InvalidSignatureLength,
InvalidSignatureS,
InvalidSignatureV
}
function _throwError(RecoverError error) private pure {
if (error == RecoverError.NoError) {
return; // no error: do nothing
} else if (error == RecoverError.InvalidSignature) {
revert("ECDSA: invalid signature");
} else if (error == RecoverError.InvalidSignatureLength) {
revert("ECDSA: invalid signature length");
} else if (error == RecoverError.InvalidSignatureS) {
revert("ECDSA: invalid signature 's' value");
} else if (error == RecoverError.InvalidSignatureV) {
revert("ECDSA: invalid signature 'v' value");
}
}
/**
* @dev Returns the address that signed a hashed message (`hash`) with
* `signature` or error string. This address can then be used for verification purposes.
*
* The `ecrecover` EVM opcode allows for malleable (non-unique) signatures:
* this function rejects them by requiring the `s` value to be in the lower
* half order, and the `v` value to be either 27 or 28.
*
* IMPORTANT: `hash` _must_ be the result of a hash operation for the
* verification to be secure: it is possible to craft signatures that
* recover to arbitrary addresses for non-hashed data. A safe way to ensure
* this is by receiving a hash of the original message (which may otherwise
* be too long), and then calling {toEthSignedMessageHash} on it.
*
* Documentation for signature generation:
* - with https://web3js.readthedocs.io/en/v1.3.4/web3-eth-accounts.html#sign[Web3.js]
* - with https://docs.ethers.io/v5/api/signer/#Signer-signMessage[ethers]
*
* _Available since v4.3._
*/
function tryRecover(bytes32 hash, bytes memory signature) internal pure returns (address, RecoverError) {
// Check the signature length
// - case 65: r,s,v signature (standard)
// - case 64: r,vs signature (cf https://eips.ethereum.org/EIPS/eip-2098) _Available since v4.1._
if (signature.length == 65) {
bytes32 r;
bytes32 s;
uint8 v;
// ecrecover takes the signature parameters, and the only way to get them
// currently is to use assembly.
assembly {
r := mload(add(signature, 0x20))
s := mload(add(signature, 0x40))
v := byte(0, mload(add(signature, 0x60)))
}
return tryRecover(hash, v, r, s);
} else if (signature.length == 64) {
bytes32 r;
bytes32 vs;
// ecrecover takes the signature parameters, and the only way to get them
// currently is to use assembly.
assembly {
r := mload(add(signature, 0x20))
vs := mload(add(signature, 0x40))
}
return tryRecover(hash, r, vs);
} else {
return (address(0), RecoverError.InvalidSignatureLength);
}
}
/**
* @dev Returns the address that signed a hashed message (`hash`) with
* `signature`. This address can then be used for verification purposes.
*
* The `ecrecover` EVM opcode allows for malleable (non-unique) signatures:
* this function rejects them by requiring the `s` value to be in the lower
* half order, and the `v` value to be either 27 or 28.
*
* IMPORTANT: `hash` _must_ be the result of a hash operation for the
* verification to be secure: it is possible to craft signatures that
* recover to arbitrary addresses for non-hashed data. A safe way to ensure
* this is by receiving a hash of the original message (which may otherwise
* be too long), and then calling {toEthSignedMessageHash} on it.
*/
function recover(bytes32 hash, bytes memory signature) internal pure returns (address) {
(address recovered, RecoverError error) = tryRecover(hash, signature);
_throwError(error);
return recovered;
}
/**
* @dev Overload of {ECDSA-tryRecover} that receives the `r` and `vs` short-signature fields separately.
*
* See https://eips.ethereum.org/EIPS/eip-2098[EIP-2098 short signatures]
*
* _Available since v4.3._
*/
function tryRecover(
bytes32 hash,
bytes32 r,
bytes32 vs
) internal pure returns (address, RecoverError) {
bytes32 s;
uint8 v;
assembly {
s := and(vs, 0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff)
v := add(shr(255, vs), 27)
}
return tryRecover(hash, v, r, s);
}
/**
* @dev Overload of {ECDSA-recover} that receives the `r and `vs` short-signature fields separately.
*
* _Available since v4.2._
*/
function recover(
bytes32 hash,
bytes32 r,
bytes32 vs
) internal pure returns (address) {
(address recovered, RecoverError error) = tryRecover(hash, r, vs);
_throwError(error);
return recovered;
}
/**
* @dev Overload of {ECDSA-tryRecover} that receives the `v`,
* `r` and `s` signature fields separately.
*
* _Available since v4.3._
*/
function tryRecover(
bytes32 hash,
uint8 v,
bytes32 r,
bytes32 s
) internal pure returns (address, RecoverError) {
// EIP-2 still allows signature malleability for ecrecover(). Remove this possibility and make the signature
// unique. Appendix F in the Ethereum Yellow paper (https://ethereum.github.io/yellowpaper/paper.pdf), defines
// the valid range for s in (301): 0 < s < secp256k1n ÷ 2 + 1, and for v in (302): v ∈ {27, 28}. Most
// signatures from current libraries generate a unique signature with an s-value in the lower half order.
//
// If your library generates malleable signatures, such as s-values in the upper range, calculate a new s-value
// with 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFEBAAEDCE6AF48A03BBFD25E8CD0364141 - s1 and flip v from 27 to 28 or
// vice versa. If your library also generates signatures with 0/1 for v instead 27/28, add 27 to v to accept
// these malleable signatures as well.
if (uint256(s) > 0x7FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF5D576E7357A4501DDFE92F46681B20A0) {
return (address(0), RecoverError.InvalidSignatureS);
}
if (v != 27 && v != 28) {
return (address(0), RecoverError.InvalidSignatureV);
}
// If the signature is valid (and not malleable), return the signer address
address signer = ecrecover(hash, v, r, s);
if (signer == address(0)) {
return (address(0), RecoverError.InvalidSignature);
}
return (signer, RecoverError.NoError);
}
/**
* @dev Overload of {ECDSA-recover} that receives the `v`,
* `r` and `s` signature fields separately.
*/
function recover(
bytes32 hash,
uint8 v,
bytes32 r,
bytes32 s
) internal pure returns (address) {
(address recovered, RecoverError error) = tryRecover(hash, v, r, s);
_throwError(error);
return recovered;
}
/**
* @dev Returns an Ethereum Signed Message, created from a `hash`. This
* produces hash corresponding to the one signed with the
* https://eth.wiki/json-rpc/API#eth_sign[`eth_sign`]
* JSON-RPC method as part of EIP-191.
*
* See {recover}.
*/
function toEthSignedMessageHash(bytes32 hash) internal pure returns (bytes32) {
// 32 is the length in bytes of hash,
// enforced by the type signature above
return keccak256(abi.encodePacked("\x19Ethereum Signed Message:\n32", hash));
}
/**
* @dev Returns an Ethereum Signed Message, created from `s`. This
* produces hash corresponding to the one signed with the
* https://eth.wiki/json-rpc/API#eth_sign[`eth_sign`]
* JSON-RPC method as part of EIP-191.
*
* See {recover}.
*/
function toEthSignedMessageHash(bytes memory s) internal pure returns (bytes32) {
return keccak256(abi.encodePacked("\x19Ethereum Signed Message:\n", Strings.toString(s.length), s));
}
/**
* @dev Returns an Ethereum Signed Typed Data, created from a
* `domainSeparator` and a `structHash`. This produces hash corresponding
* to the one signed with the
* https://eips.ethereum.org/EIPS/eip-712[`eth_signTypedData`]
* JSON-RPC method as part of EIP-712.
*
* See {recover}.
*/
function toTypedDataHash(bytes32 domainSeparator, bytes32 structHash) internal pure returns (bytes32) {
return keccak256(abi.encodePacked("\x19\x01", domainSeparator, structHash));
}
}
// File: @openzeppelin/contracts/utils/cryptography/SignatureChecker.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (utils/cryptography/SignatureChecker.sol)
pragma solidity ^0.8.0;
import "./ECDSA.sol";
import "../Address.sol";
import "../../interfaces/IERC1271.sol";
/**
* @dev Signature verification helper: Provide a single mechanism to verify both private-key (EOA) ECDSA signature and
* ERC1271 contract signatures. Using this instead of ECDSA.recover in your contract will make them compatible with
* smart contract wallets such as Argent and Gnosis.
*
* Note: unlike ECDSA signatures, contract signature's are revocable, and the outcome of this function can thus change
* through time. It could return true at block N and false at block N+1 (or the opposite).
*
* _Available since v4.1._
*/
library SignatureChecker {
function isValidSignatureNow(
address signer,
bytes32 hash,
bytes memory signature
) internal view returns (bool) {
(address recovered, ECDSA.RecoverError error) = ECDSA.tryRecover(hash, signature);
if (error == ECDSA.RecoverError.NoError && recovered == signer) {
return true;
}
(bool success, bytes memory result) = signer.staticcall(
abi.encodeWithSelector(IERC1271.isValidSignature.selector, hash, signature)
);
return (success && result.length == 32 && abi.decode(result, (bytes4)) == IERC1271.isValidSignature.selector);
}
}
// File: @openzeppelin/contracts/utils/Strings.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (utils/Strings.sol)
pragma solidity ^0.8.0;
/**
* @dev String operations.
*/
library Strings {
bytes16 private constant _HEX_SYMBOLS = "0123456789abcdef";
/**
* @dev Converts a `uint256` to its ASCII `string` decimal representation.
*/
function toString(uint256 value) internal pure returns (string memory) {
// Inspired by OraclizeAPI's implementation - MIT licence
// https://github.com/oraclize/ethereum-api/blob/b42146b063c7d6ee1358846c198246239e9360e8/oraclizeAPI_0.4.25.sol
if (value == 0) {
return "0";
}
uint256 temp = value;
uint256 digits;
while (temp != 0) {
digits++;
temp /= 10;
}
bytes memory buffer = new bytes(digits);
while (value != 0) {
digits -= 1;
buffer[digits] = bytes1(uint8(48 + uint256(value % 10)));
value /= 10;
}
return string(buffer);
}
/**
* @dev Converts a `uint256` to its ASCII `string` hexadecimal representation.
*/
function toHexString(uint256 value) internal pure returns (string memory) {
if (value == 0) {
return "0x00";
}
uint256 temp = value;
uint256 length = 0;
while (temp != 0) {
length++;
temp >>= 8;
}
return toHexString(value, length);
}
/**
* @dev Converts a `uint256` to its ASCII `string` hexadecimal representation with fixed length.
*/
function toHexString(uint256 value, uint256 length) internal pure returns (string memory) {
bytes memory buffer = new bytes(2 * length + 2);
buffer[0] = "0";
buffer[1] = "x";
for (uint256 i = 2 * length + 1; i > 1; --i) {
buffer[i] = _HEX_SYMBOLS[value & 0xf];
value >>= 4;
}
require(value == 0, "Strings: hex length insufficient");
return string(buffer);
}
}
// File: @openzeppelin/contracts/utils/Address.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (utils/Address.sol)
pragma solidity ^0.8.0;
/**
* @dev Collection of functions related to the address type
*/
library Address {
/**
* @dev Returns true if `account` is a contract.
*
* [IMPORTANT]
* ====
* It is unsafe to assume that an address for which this function returns
* false is an externally-owned account (EOA) and not a contract.
*
* Among others, `isContract` will return false for the following
* types of addresses:
*
* - an externally-owned account
* - a contract in construction
* - an address where a contract will be created
* - an address where a contract lived, but was destroyed
* ====
*/
function isContract(address account) internal view returns (bool) {
// This method relies on extcodesize, which returns 0 for contracts in
// construction, since the code is only stored at the end of the
// constructor execution.
uint256 size;
assembly {
size := extcodesize(account)
}
return size > 0;
}
/**
* @dev Replacement for Solidity's `transfer`: sends `amount` wei to
* `recipient`, forwarding all available gas and reverting on errors.
*
* https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost
* of certain opcodes, possibly making contracts go over the 2300 gas limit
* imposed by `transfer`, making them unable to receive funds via
* `transfer`. {sendValue} removes this limitation.
*
* https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more].
*
* IMPORTANT: because control is transferred to `recipient`, care must be
* taken to not create reentrancy vulnerabilities. Consider using
* {ReentrancyGuard} or the
* https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern].
*/
function sendValue(address payable recipient, uint256 amount) internal {
require(address(this).balance >= amount, "Address: insufficient balance");
(bool success, ) = recipient.call{value: amount}("");
require(success, "Address: unable to send value, recipient may have reverted");
}
/**
* @dev Performs a Solidity function call using a low level `call`. A
* plain `call` is an unsafe replacement for a function call: use this
* function instead.
*
* If `target` reverts with a revert reason, it is bubbled up by this
* function (like regular Solidity function calls).
*
* Returns the raw returned data. To convert to the expected return value,
* use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`].
*
* Requirements:
*
* - `target` must be a contract.
* - calling `target` with `data` must not revert.
*
* _Available since v3.1._
*/
function functionCall(address target, bytes memory data) internal returns (bytes memory) {
return functionCall(target, data, "Address: low-level call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with
* `errorMessage` as a fallback revert reason when `target` reverts.
*
* _Available since v3.1._
*/
function functionCall(
address target,
bytes memory data,
string memory errorMessage
) internal returns (bytes memory) {
return functionCallWithValue(target, data, 0, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but also transferring `value` wei to `target`.
*
* Requirements:
*
* - the calling contract must have an ETH balance of at least `value`.
* - the called Solidity function must be `payable`.
*
* _Available since v3.1._
*/
function functionCallWithValue(
address target,
bytes memory data,
uint256 value
) internal returns (bytes memory) {
return functionCallWithValue(target, data, value, "Address: low-level call with value failed");
}
/**
* @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but
* with `errorMessage` as a fallback revert reason when `target` reverts.
*
* _Available since v3.1._
*/
function functionCallWithValue(
address target,
bytes memory data,
uint256 value,
string memory errorMessage
) internal returns (bytes memory) {
require(address(this).balance >= value, "Address: insufficient balance for call");
require(isContract(target), "Address: call to non-contract");
(bool success, bytes memory returndata) = target.call{value: value}(data);
return verifyCallResult(success, returndata, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but performing a static call.
*
* _Available since v3.3._
*/
function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) {
return functionStaticCall(target, data, "Address: low-level static call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`],
* but performing a static call.
*
* _Available since v3.3._
*/
function functionStaticCall(
address target,
bytes memory data,
string memory errorMessage
) internal view returns (bytes memory) {
require(isContract(target), "Address: static call to non-contract");
(bool success, bytes memory returndata) = target.staticcall(data);
return verifyCallResult(success, returndata, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but performing a delegate call.
*
* _Available since v3.4._
*/
function functionDelegateCall(address target, bytes memory data) internal returns (bytes memory) {
return functionDelegateCall(target, data, "Address: low-level delegate call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`],
* but performing a delegate call.
*
* _Available since v3.4._
*/
function functionDelegateCall(
address target,
bytes memory data,
string memory errorMessage
) internal returns (bytes memory) {
require(isContract(target), "Address: delegate call to non-contract");
(bool success, bytes memory returndata) = target.delegatecall(data);
return verifyCallResult(success, returndata, errorMessage);
}
/**
* @dev Tool to verifies that a low level call was successful, and revert if it wasn't, either by bubbling the
* revert reason using the provided one.
*
* _Available since v4.3._
*/
function verifyCallResult(
bool success,
bytes memory returndata,
string memory errorMessage
) internal pure returns (bytes memory) {
if (success) {
return returndata;
} else {
// Look for revert reason and bubble it up if present
if (returndata.length > 0) {
// The easiest way to bubble the revert reason is using memory via assembly
assembly {
let returndata_size := mload(returndata)
revert(add(32, returndata), returndata_size)
}
} else {
revert(errorMessage);
}
}
}
}
// File: @openzeppelin/contracts/interfaces/IERC1271.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (interfaces/IERC1271.sol)
pragma solidity ^0.8.0;
/**
* @dev Interface of the ERC1271 standard signature validation method for
* contracts as defined in https://eips.ethereum.org/EIPS/eip-1271[ERC-1271].
*
* _Available since v4.1._
*/
interface IERC1271 {
/**
* @dev Should return whether the signature provided is valid for the provided data
* @param hash Hash of the data to be signed
* @param signature Signature byte array associated with _data
*/
function isValidSignature(bytes32 hash, bytes memory signature) external view returns (bytes4 magicValue);
}
|
[{"inputs":[{"internalType":"address","name":"_collectionFactory","type":"address"}],"stateMutability":"nonpayable","type":"constructor"},{"anonymous":false,"inputs":[{"indexed":true,"internalType":"address","name":"owner","type":"address"},{"indexed":true,"internalType":"address","name":"approved","type":"address"},{"indexed":true,"internalType":"uint256","name":"tokenId","type":"uint256"}],"name":"Approval","type":"event"},{"anonymous":false,"inputs":[{"indexed":true,"internalType":"address","name":"owner","type":"address"},{"indexed":true,"internalType":"address","name":"operator","type":"address"},{"indexed":false,"internalType":"bool","name":"approved","type":"bool"}],"name":"ApprovalForAll","type":"event"},{"anonymous":false,"inputs":[{"indexed":false,"internalType":"string","name":"baseURI","type":"string"}],"name":"BaseURIUpdated","type":"event"},{"anonymous":false,"inputs":[{"indexed":true,"internalType":"address","name":"originalAddress","type":"address"},{"indexed":true,"internalType":"address","name":"newAddress","type":"address"}],"name":"CreatorMigrated","type":"event"},{"anonymous":false,"inputs":[{"indexed":true,"internalType":"uint256","name":"maxTokenId","type":"uint256"}],"name":"MaxTokenIdUpdated","type":"event"},{"anonymous":false,"inputs":[{"indexed":true,"internalType":"address","name":"creator","type":"address"},{"indexed":true,"internalType":"uint256","name":"tokenId","type":"uint256"},{"indexed":true,"internalType":"string","name":"indexedTokenCID","type":"string"},{"indexed":false,"internalType":"string","name":"tokenCID","type":"string"}],"name":"Minted","type":"event"},{"anonymous":false,"inputs":[{"indexed":true,"internalType":"uint256","name":"tokenId","type":"uint256"},{"indexed":true,"internalType":"address","name":"originalAddress","type":"address"},{"indexed":true,"internalType":"address","name":"newAddress","type":"address"}],"name":"NFTOwnerMigrated","type":"event"},{"anonymous":false,"inputs":[{"indexed":true,"internalType":"uint256","name":"tokenId","type":"uint256"},{"indexed":true,"internalType":"address","name":"originalAddress","type":"address"},{"indexed":true,"internalType":"address","name":"newAddress","type":"address"},{"indexed":false,"internalType":"address","name":"originalPaymentAddress","type":"address"},{"indexed":false,"internalType":"address","name":"newPaymentAddress","type":"address"}],"name":"PaymentAddressMigrated","type":"event"},{"anonymous":false,"inputs":[{"indexed":true,"internalType":"address","name":"owner","type":"address"}],"name":"SelfDestruct","type":"event"},{"anonymous":false,"inputs":[{"indexed":true,"internalType":"address","name":"fromPaymentAddress","type":"address"},{"indexed":true,"internalType":"address","name":"toPaymentAddress","type":"address"},{"indexed":true,"internalType":"uint256","name":"tokenId","type":"uint256"}],"name":"TokenCreatorPaymentAddressSet","type":"event"},{"anonymous":false,"inputs":[{"indexed":true,"internalType":"address","name":"from","type":"address"},{"indexed":true,"internalType":"address","name":"to","type":"address"},{"indexed":true,"internalType":"uint256","name":"tokenId","type":"uint256"}],"name":"Transfer","type":"event"},{"inputs":[{"internalType":"uint256[]","name":"ownedTokenIds","type":"uint256[]"},{"internalType":"address","name":"originalAddress","type":"address"},{"internalType":"address payable","name":"newAddress","type":"address"},{"internalType":"bytes","name":"signature","type":"bytes"}],"name":"adminAccountMigration","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"uint256[]","name":"paymentAddressTokenIds","type":"uint256[]"},{"internalType":"address","name":"paymentAddressFactory","type":"address"},{"internalType":"bytes","name":"paymentAddressCallData","type":"bytes"},{"internalType":"uint256","name":"addressLocationInCallData","type":"uint256"},{"internalType":"address","name":"originalAddress","type":"address"},{"internalType":"address payable","name":"newAddress","type":"address"},{"internalType":"bytes","name":"signature","type":"bytes"}],"name":"adminAccountMigrationForPaymentAddresses","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"address","name":"to","type":"address"},{"internalType":"uint256","name":"tokenId","type":"uint256"}],"name":"approve","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"address","name":"owner","type":"address"}],"name":"balanceOf","outputs":[{"internalType":"uint256","name":"","type":"uint256"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"baseURI","outputs":[{"internalType":"string","name":"","type":"string"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"uint256","name":"tokenId","type":"uint256"}],"name":"burn","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[],"name":"collectionFactory","outputs":[{"internalType":"contract ICollectionFactory","name":"","type":"address"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"uint256","name":"tokenId","type":"uint256"}],"name":"getApproved","outputs":[{"internalType":"address","name":"","type":"address"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"uint256","name":"","type":"uint256"}],"name":"getFeeBps","outputs":[{"internalType":"uint256[]","name":"feesInBasisPoints","type":"uint256[]"}],"stateMutability":"pure","type":"function"},{"inputs":[{"internalType":"uint256","name":"id","type":"uint256"}],"name":"getFeeRecipients","outputs":[{"internalType":"address payable[]","name":"recipients","type":"address[]"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"string","name":"tokenCID","type":"string"}],"name":"getHasMintedCID","outputs":[{"internalType":"bool","name":"","type":"bool"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"uint256","name":"tokenId","type":"uint256"}],"name":"getRoyalties","outputs":[{"internalType":"address payable[]","name":"recipients","type":"address[]"},{"internalType":"uint256[]","name":"feesInBasisPoints","type":"uint256[]"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"uint256","name":"tokenId","type":"uint256"}],"name":"getTokenCreatorPaymentAddress","outputs":[{"internalType":"address payable","name":"tokenCreatorPaymentAddress","type":"address"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"address payable","name":"_creator","type":"address"},{"internalType":"string","name":"_name","type":"string"},{"internalType":"string","name":"_symbol","type":"string"}],"name":"initialize","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"address","name":"owner","type":"address"},{"internalType":"address","name":"operator","type":"address"}],"name":"isApprovedForAll","outputs":[{"internalType":"bool","name":"","type":"bool"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"latestTokenId","outputs":[{"internalType":"uint256","name":"","type":"uint256"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"maxTokenId","outputs":[{"internalType":"uint256","name":"","type":"uint256"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"string","name":"tokenCID","type":"string"}],"name":"mint","outputs":[{"internalType":"uint256","name":"tokenId","type":"uint256"}],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"string","name":"tokenCID","type":"string"},{"internalType":"address","name":"operator","type":"address"}],"name":"mintAndApprove","outputs":[{"internalType":"uint256","name":"tokenId","type":"uint256"}],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"string","name":"tokenCID","type":"string"},{"internalType":"address payable","name":"tokenCreatorPaymentAddress","type":"address"}],"name":"mintWithCreatorPaymentAddress","outputs":[{"internalType":"uint256","name":"tokenId","type":"uint256"}],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"string","name":"tokenCID","type":"string"},{"internalType":"address payable","name":"tokenCreatorPaymentAddress","type":"address"},{"internalType":"address","name":"operator","type":"address"}],"name":"mintWithCreatorPaymentAddressAndApprove","outputs":[{"internalType":"uint256","name":"tokenId","type":"uint256"}],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"string","name":"tokenCID","type":"string"},{"internalType":"address","name":"paymentAddressFactory","type":"address"},{"internalType":"bytes","name":"paymentAddressCallData","type":"bytes"}],"name":"mintWithCreatorPaymentFactory","outputs":[{"internalType":"uint256","name":"tokenId","type":"uint256"}],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"string","name":"tokenCID","type":"string"},{"internalType":"address","name":"paymentAddressFactory","type":"address"},{"internalType":"bytes","name":"paymentAddressCallData","type":"bytes"},{"internalType":"address","name":"operator","type":"address"}],"name":"mintWithCreatorPaymentFactoryAndApprove","outputs":[{"internalType":"uint256","name":"tokenId","type":"uint256"}],"stateMutability":"nonpayable","type":"function"},{"inputs":[],"name":"name","outputs":[{"internalType":"string","name":"","type":"string"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"owner","outputs":[{"internalType":"address payable","name":"","type":"address"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"uint256","name":"tokenId","type":"uint256"}],"name":"ownerOf","outputs":[{"internalType":"address","name":"","type":"address"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"uint256","name":"_tokenId","type":"uint256"},{"internalType":"uint256","name":"_salePrice","type":"uint256"}],"name":"royaltyInfo","outputs":[{"internalType":"address","name":"receiver","type":"address"},{"internalType":"uint256","name":"royaltyAmount","type":"uint256"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"address","name":"from","type":"address"},{"internalType":"address","name":"to","type":"address"},{"internalType":"uint256","name":"tokenId","type":"uint256"}],"name":"safeTransferFrom","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"address","name":"from","type":"address"},{"internalType":"address","name":"to","type":"address"},{"internalType":"uint256","name":"tokenId","type":"uint256"},{"internalType":"bytes","name":"_data","type":"bytes"}],"name":"safeTransferFrom","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[],"name":"selfDestruct","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"address","name":"operator","type":"address"},{"internalType":"bool","name":"approved","type":"bool"}],"name":"setApprovalForAll","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"bytes4","name":"interfaceId","type":"bytes4"}],"name":"supportsInterface","outputs":[{"internalType":"bool","name":"","type":"bool"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"symbol","outputs":[{"internalType":"string","name":"","type":"string"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"uint256","name":"","type":"uint256"}],"name":"tokenCreator","outputs":[{"internalType":"address payable","name":"","type":"address"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"uint256","name":"tokenId","type":"uint256"}],"name":"tokenURI","outputs":[{"internalType":"string","name":"","type":"string"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"totalSupply","outputs":[{"internalType":"uint256","name":"","type":"uint256"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"address","name":"from","type":"address"},{"internalType":"address","name":"to","type":"address"},{"internalType":"uint256","name":"tokenId","type":"uint256"}],"name":"transferFrom","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"string","name":"baseURIOverride","type":"string"}],"name":"updateBaseURI","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"uint256","name":"_maxTokenId","type":"uint256"}],"name":"updateMaxTokenId","outputs":[],"stateMutability":"nonpayable","type":"function"}]
|
v0.8.11+commit.d7f03943
| true
| 1,337
|
0000000000000000000000003b612a5b49e025a6e4ba4ee4fb1ef46d13588059
|
Default
| false
| ||||
SafeCrypt
|
0x330b88d40e85163cc2e27251e7defbde67851e6f
|
Solidity
|
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 burn(uint256 _value) public 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);
event Burn(address indexed from, uint256 value);
}
contract StandardToken is Token {
function transfer(address _to, uint256 _value) returns (bool success) {
if (balances[msg.sender] >= _value && _value > 0) {
balances[msg.sender] -= _value;
balances[_to] += _value;
Transfer(msg.sender, _to, _value);
return true;
} else { return false; }
}
function transferFrom(address _from, address _to, uint256 _value) returns (bool success) {
if (balances[_from] >= _value && allowed[_from][msg.sender] >= _value && _value > 0) {
balances[_to] += _value;
balances[_from] -= _value;
allowed[_from][msg.sender] -= _value;
Transfer(_from, _to, _value);
return true;
} else { return false; }
}
function balanceOf(address _owner) constant returns (uint256 balance) {
return balances[_owner];
}
function approve(address _spender, uint256 _value) returns (bool success) {
allowed[msg.sender][_spender] = _value;
Approval(msg.sender, _spender, _value);
return true;
}
function allowance(address _owner, address _spender) constant returns (uint256 remaining) {
return allowed[_owner][_spender];
}
function burn(uint256 _value) public returns (bool success) {
require(balances[msg.sender] >= _value);
balances[msg.sender] -= _value;
totalSupply -= _value;
Burn(msg.sender, _value);
return true;
}
mapping (address => uint256) balances;
mapping (address => mapping (address => uint256)) allowed;
uint256 public totalSupply;
}
contract HumanStandardToken is StandardToken {
function () {
//if ether is sent to this address, send it back.
throw;
}
string public name;
uint8 public decimals;
string public symbol;
string public version = 'H0.1';
function HumanStandardToken(
uint256 _initialAmount,
string _tokenName,
uint8 _decimalUnits,
string _tokenSymbol
) {
balances[msg.sender] = _initialAmount;
totalSupply = _initialAmount;
name = _tokenName;
decimals = _decimalUnits;
symbol = _tokenSymbol;
}
function approveAndCall(address _spender, uint256 _value, bytes _extraData) returns (bool success) {
allowed[msg.sender][_spender] = _value;
Approval(msg.sender, _spender, _value);
if(!_spender.call(bytes4(bytes32(sha3("receiveApproval(address,uint256,address,bytes)"))), msg.sender, _value, this, _extraData)) { throw; }
return true;
}
}
contract SafeCrypt is HumanStandardToken(1535714285000000000000000000, "SafeCrypt", 18, "SFC") {}
|
[{"constant":true,"inputs":[],"name":"name","outputs":[{"name":"","type":"string"}],"payable":false,"stateMutability":"view","type":"function"},{"constant":false,"inputs":[{"name":"_spender","type":"address"},{"name":"_value","type":"uint256"}],"name":"approve","outputs":[{"name":"success","type":"bool"}],"payable":false,"stateMutability":"nonpayable","type":"function"},{"constant":true,"inputs":[],"name":"totalSupply","outputs":[{"name":"","type":"uint256"}],"payable":false,"stateMutability":"view","type":"function"},{"constant":false,"inputs":[{"name":"_from","type":"address"},{"name":"_to","type":"address"},{"name":"_value","type":"uint256"}],"name":"transferFrom","outputs":[{"name":"success","type":"bool"}],"payable":false,"stateMutability":"nonpayable","type":"function"},{"constant":true,"inputs":[],"name":"decimals","outputs":[{"name":"","type":"uint8"}],"payable":false,"stateMutability":"view","type":"function"},{"constant":false,"inputs":[{"name":"_value","type":"uint256"}],"name":"burn","outputs":[{"name":"success","type":"bool"}],"payable":false,"stateMutability":"nonpayable","type":"function"},{"constant":true,"inputs":[],"name":"version","outputs":[{"name":"","type":"string"}],"payable":false,"stateMutability":"view","type":"function"},{"constant":true,"inputs":[{"name":"_owner","type":"address"}],"name":"balanceOf","outputs":[{"name":"balance","type":"uint256"}],"payable":false,"stateMutability":"view","type":"function"},{"constant":true,"inputs":[],"name":"symbol","outputs":[{"name":"","type":"string"}],"payable":false,"stateMutability":"view","type":"function"},{"constant":false,"inputs":[{"name":"_to","type":"address"},{"name":"_value","type":"uint256"}],"name":"transfer","outputs":[{"name":"success","type":"bool"}],"payable":false,"stateMutability":"nonpayable","type":"function"},{"constant":false,"inputs":[{"name":"_spender","type":"address"},{"name":"_value","type":"uint256"},{"name":"_extraData","type":"bytes"}],"name":"approveAndCall","outputs":[{"name":"success","type":"bool"}],"payable":false,"stateMutability":"nonpayable","type":"function"},{"constant":true,"inputs":[{"name":"_owner","type":"address"},{"name":"_spender","type":"address"}],"name":"allowance","outputs":[{"name":"remaining","type":"uint256"}],"payable":false,"stateMutability":"view","type":"function"},{"payable":false,"stateMutability":"nonpayable","type":"fallback"},{"anonymous":false,"inputs":[{"indexed":true,"name":"_from","type":"address"},{"indexed":true,"name":"_to","type":"address"},{"indexed":false,"name":"_value","type":"uint256"}],"name":"Transfer","type":"event"},{"anonymous":false,"inputs":[{"indexed":true,"name":"_owner","type":"address"},{"indexed":true,"name":"_spender","type":"address"},{"indexed":false,"name":"_value","type":"uint256"}],"name":"Approval","type":"event"},{"anonymous":false,"inputs":[{"indexed":true,"name":"from","type":"address"},{"indexed":false,"name":"value","type":"uint256"}],"name":"Burn","type":"event"}]
|
v0.4.19-nightly.2017.11.11+commit.284c3839
| true
| 200
|
Default
| false
|
bzzr://f693046e4699578fbf47397b5db34d6dce39b718b856e6b689725d3dc22f16d9
|
||||
UserWallet
|
0x94191b3faad74080d58bb31d6719988970e74b38
|
Solidity
|
pragma solidity ^0.4.10;
// Copyright 2017 Bittrex
contract AbstractSweeper {
function sweep(address token, uint amount) returns (bool);
function () { throw; }
Controller controller;
function AbstractSweeper(address _controller) {
controller = Controller(_controller);
}
modifier canSweep() {
if (msg.sender != controller.authorizedCaller() && msg.sender != controller.owner()) throw;
if (controller.halted()) throw;
_;
}
}
contract Token {
function balanceOf(address a) returns (uint) {
(a);
return 0;
}
function transfer(address a, uint val) returns (bool) {
(a);
(val);
return false;
}
}
contract DefaultSweeper is AbstractSweeper {
function DefaultSweeper(address controller)
AbstractSweeper(controller) {}
function sweep(address _token, uint _amount)
canSweep
returns (bool) {
bool success = false;
address destination = controller.destination();
if (_token != address(0)) {
Token token = Token(_token);
uint amount = _amount;
if (amount > token.balanceOf(this)) {
return false;
}
success = token.transfer(destination, amount);
}
else {
uint amountInWei = _amount;
if (amountInWei > this.balance) {
return false;
}
success = destination.send(amountInWei);
}
if (success) {
controller.logSweep(this, destination, _token, _amount);
}
return success;
}
}
contract UserWallet {
AbstractSweeperList sweeperList;
function UserWallet(address _sweeperlist) {
sweeperList = AbstractSweeperList(_sweeperlist);
}
function () public payable { }
function tokenFallback(address _from, uint _value, bytes _data) {
(_from);
(_value);
(_data);
}
function sweep(address _token, uint _amount)
returns (bool) {
(_amount);
return sweeperList.sweeperOf(_token).delegatecall(msg.data);
}
}
contract AbstractSweeperList {
function sweeperOf(address _token) returns (address);
}
contract Controller is AbstractSweeperList {
address public owner;
address public authorizedCaller;
address public destination;
bool public halted;
event LogNewWallet(address receiver);
event LogSweep(address indexed from, address indexed to, address indexed token, uint amount);
modifier onlyOwner() {
if (msg.sender != owner) throw;
_;
}
modifier onlyAuthorizedCaller() {
if (msg.sender != authorizedCaller) throw;
_;
}
modifier onlyAdmins() {
if (msg.sender != authorizedCaller && msg.sender != owner) throw;
_;
}
function Controller()
{
owner = msg.sender;
destination = msg.sender;
authorizedCaller = msg.sender;
}
function changeAuthorizedCaller(address _newCaller) onlyOwner {
authorizedCaller = _newCaller;
}
function changeDestination(address _dest) onlyOwner {
destination = _dest;
}
function changeOwner(address _owner) onlyOwner {
owner = _owner;
}
function makeWallet() onlyAdmins returns (address wallet) {
wallet = address(new UserWallet(this));
LogNewWallet(wallet);
}
function halt() onlyAdmins {
halted = true;
}
function start() onlyOwner {
halted = false;
}
address public defaultSweeper = address(new DefaultSweeper(this));
mapping (address => address) sweepers;
function addSweeper(address _token, address _sweeper) onlyOwner {
sweepers[_token] = _sweeper;
}
function sweeperOf(address _token) returns (address) {
address sweeper = sweepers[_token];
if (sweeper == 0) sweeper = defaultSweeper;
return sweeper;
}
function logSweep(address from, address to, address token, uint amount) {
LogSweep(from, to, token, amount);
}
}
|
[{"constant":false,"inputs":[{"name":"_token","type":"address"},{"name":"_amount","type":"uint256"}],"name":"sweep","outputs":[{"name":"","type":"bool"}],"payable":false,"type":"function"},{"constant":false,"inputs":[{"name":"_from","type":"address"},{"name":"_value","type":"uint256"},{"name":"_data","type":"bytes"}],"name":"tokenFallback","outputs":[],"payable":false,"type":"function"},{"inputs":[{"name":"_sweeperlist","type":"address"}],"payable":false,"type":"constructor"},{"payable":true,"type":"fallback"}]
|
v0.4.11+commit.68ef5810
| true
| 200
|
000000000000000000000000a3C1E324CA1ce40db73eD6026c4A177F099B5770
|
Default
| false
|
bzzr://4cdd69fdcf3cf6cbee9677fe380fa5f044048aa9e060ec5619a21ca5a5bd4cd1
|
|||
Forwarder
|
0xb94573db4409a7d63738d2890a92e3814cd9af11
|
Solidity
|
pragma solidity 0.7.5;
/*
The MIT License (MIT)
Copyright (c) 2018 Murray Software, LLC.
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.
*/
//solhint-disable max-line-length
//solhint-disable no-inline-assembly
contract CloneFactory {
function createClone(address target, bytes32 salt)
internal
returns (address payable result)
{
bytes20 targetBytes = bytes20(target);
assembly {
// load the next free memory slot as a place to store the clone contract data
let clone := mload(0x40)
// The bytecode block below is responsible for contract initialization
// during deployment, it is worth noting the proxied contract constructor will not be called during
// the cloning procedure and that is why an initialization function needs to be called after the
// clone is created
mstore(
clone,
0x3d602d80600a3d3981f3363d3d373d3d3d363d73000000000000000000000000
)
// This stores the address location of the implementation contract
// so that the proxy knows where to delegate call logic to
mstore(add(clone, 0x14), targetBytes)
// The bytecode block is the actual code that is deployed for each clone created.
// It forwards all calls to the already deployed implementation via a delegatecall
mstore(
add(clone, 0x28),
0x5af43d82803e903d91602b57fd5bf30000000000000000000000000000000000
)
// deploy the contract using the CREATE2 opcode
// this deploys the minimal proxy defined above, which will proxy all
// calls to use the logic defined in the implementation contract `target`
result := create2(0, clone, 0x37, salt)
}
}
function isClone(address target, address query)
internal
view
returns (bool result)
{
bytes20 targetBytes = bytes20(target);
assembly {
// load the next free memory slot as a place to store the comparison clone
let clone := mload(0x40)
// The next three lines store the expected bytecode for a miniml proxy
// that targets `target` as its implementation contract
mstore(
clone,
0x363d3d373d3d3d363d7300000000000000000000000000000000000000000000
)
mstore(add(clone, 0xa), targetBytes)
mstore(
add(clone, 0x1e),
0x5af43d82803e903d91602b57fd5bf30000000000000000000000000000000000
)
// the next two lines store the bytecode of the contract that we are checking in memory
let other := add(clone, 0x40)
extcodecopy(query, other, 0, 0x2d)
// Check if the expected bytecode equals the actual bytecode and return the result
result := and(
eq(mload(clone), mload(other)),
eq(mload(add(clone, 0xd)), mload(add(other, 0xd)))
)
}
}
}
/**
* Contract that exposes the needed erc20 token functions
*/
abstract contract ERC20Interface {
// Send _value amount of tokens to address _to
function transfer(address _to, uint256 _value)
public
virtual
returns (bool success);
// Get the account balance of another account with address _owner
function balanceOf(address _owner)
public
virtual
view
returns (uint256 balance);
}
// helper methods for interacting with ERC20 tokens and sending ETH that do not consistently return true/false
library TransferHelper {
function safeApprove(
address token,
address to,
uint256 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::safeApprove: approve failed'
);
}
function safeTransfer(
address token,
address to,
uint256 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::safeTransfer: transfer failed'
);
}
function safeTransferFrom(
address token,
address from,
address to,
uint256 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::transferFrom: transferFrom failed'
);
}
function safeTransferETH(address to, uint256 value) internal {
(bool success, ) = to.call{value: value}(new bytes(0));
require(success, 'TransferHelper::safeTransferETH: ETH transfer failed');
}
}
/**
* Contract that will forward any incoming Ether to the creator of the contract
*
*/
contract Forwarder {
// Address to which any funds sent to this contract will be forwarded
address public parentAddress;
event ForwarderDeposited(address from, uint256 value, bytes data);
/**
* Initialize the contract, and sets the destination address to that of the creator
*/
function init(address _parentAddress) external onlyUninitialized {
parentAddress = _parentAddress;
uint256 value = address(this).balance;
if (value == 0) {
return;
}
(bool success, ) = parentAddress.call{ value: value }('');
require(success, 'Flush failed');
// NOTE: since we are forwarding on initialization,
// we don't have the context of the original sender.
// We still emit an event about the forwarding but set
// the sender to the forwarder itself
emit ForwarderDeposited(address(this), value, msg.data);
}
/**
* Modifier that will execute internal code block only if the sender is the parent address
*/
modifier onlyParent {
require(msg.sender == parentAddress, 'Only Parent');
_;
}
/**
* Modifier that will execute internal code block only if the contract has not been initialized yet
*/
modifier onlyUninitialized {
require(parentAddress == address(0x0), 'Already initialized');
_;
}
/**
* Default function; Gets called when data is sent but does not match any other function
*/
fallback() external payable {
flush();
}
/**
* Default function; Gets called when Ether is deposited with no data, and forwards it to the parent address
*/
receive() external payable {
flush();
}
/**
* Execute a token transfer of the full balance from the forwarder token to the parent address
* @param tokenContractAddress the address of the erc20 token contract
*/
function flushTokens(address tokenContractAddress) external onlyParent {
ERC20Interface instance = ERC20Interface(tokenContractAddress);
address forwarderAddress = address(this);
uint256 forwarderBalance = instance.balanceOf(forwarderAddress);
if (forwarderBalance == 0) {
return;
}
TransferHelper.safeTransfer(
tokenContractAddress,
parentAddress,
forwarderBalance
);
}
/**
* Flush the entire balance of the contract to the parent address.
*/
function flush() public {
uint256 value = address(this).balance;
if (value == 0) {
return;
}
(bool success, ) = parentAddress.call{ value: value }('');
require(success, 'Flush failed');
emit ForwarderDeposited(msg.sender, value, msg.data);
}
}
contract ForwarderFactory is CloneFactory {
address public implementationAddress;
event ForwarderCreated(address newForwarderAddress, address parentAddress);
constructor(address _implementationAddress) {
implementationAddress = _implementationAddress;
}
function createForwarder(address parent, bytes32 salt) external {
// include the signers in the salt so any contract deployed to a given address must have the same signers
bytes32 finalSalt = keccak256(abi.encodePacked(parent, salt));
address payable clone = createClone(implementationAddress, finalSalt);
Forwarder(clone).init(parent);
emit ForwarderCreated(clone, parent);
}
}
|
[{"anonymous":false,"inputs":[{"indexed":false,"internalType":"address","name":"from","type":"address"},{"indexed":false,"internalType":"uint256","name":"value","type":"uint256"},{"indexed":false,"internalType":"bytes","name":"data","type":"bytes"}],"name":"ForwarderDeposited","type":"event"},{"stateMutability":"payable","type":"fallback"},{"inputs":[],"name":"flush","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"address","name":"tokenContractAddress","type":"address"}],"name":"flushTokens","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"address","name":"_parentAddress","type":"address"}],"name":"init","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[],"name":"parentAddress","outputs":[{"internalType":"address","name":"","type":"address"}],"stateMutability":"view","type":"function"},{"stateMutability":"payable","type":"receive"}]
|
v0.7.5+commit.eb77ed08
| false
| 200
|
Default
|
Apache-2.0
| false
|
ipfs://934a7b5f246917d20f5e049b9344e4f3d923110c9d150ea2a4118848dd414bc3
|
|||
Forwarder
|
0x00e25bd1492f11bca02c64b54b32d4e35ccf4a5b
|
Solidity
|
pragma solidity ^0.4.14;
/**
* Contract that exposes the needed erc20 token functions
*/
contract ERC20Interface {
// Send _value amount of tokens to address _to
function transfer(address _to, uint256 _value) returns (bool success);
// Get the account balance of another account with address _owner
function balanceOf(address _owner) constant returns (uint256 balance);
}
/**
* Contract that will forward any incoming Ether to its creator
*/
contract Forwarder {
// Address to which any funds sent to this contract will be forwarded
address public parentAddress;
event ForwarderDeposited(address from, uint value, bytes data);
event TokensFlushed(
address tokenContractAddress, // The contract address of the token
uint value // Amount of token sent
);
/**
* Create the contract, and set the destination address to that of the creator
*/
function Forwarder() {
parentAddress = msg.sender;
}
/**
* Modifier that will execute internal code block only if the sender is a parent of the forwarder contract
*/
modifier onlyParent {
if (msg.sender != parentAddress) {
throw;
}
_;
}
/**
* Default function; Gets called when Ether is deposited, and forwards it to the destination address
*/
function() payable {
if (!parentAddress.call.value(msg.value)(msg.data))
throw;
// Fire off the deposited event if we can forward it
ForwarderDeposited(msg.sender, msg.value, msg.data);
}
/**
* Execute a token transfer of the full balance from the forwarder token to the main wallet contract
* @param tokenContractAddress the address of the erc20 token contract
*/
function flushTokens(address tokenContractAddress) onlyParent {
ERC20Interface instance = ERC20Interface(tokenContractAddress);
var forwarderAddress = address(this);
var forwarderBalance = instance.balanceOf(forwarderAddress);
if (forwarderBalance == 0) {
return;
}
if (!instance.transfer(parentAddress, forwarderBalance)) {
throw;
}
TokensFlushed(tokenContractAddress, forwarderBalance);
}
/**
* It is possible that funds were sent to this address before the contract was deployed.
* We can flush those funds to the destination address.
*/
function flush() {
if (!parentAddress.call.value(this.balance)())
throw;
}
}
/**
* Basic multi-signer wallet designed for use in a co-signing environment where 2 signatures are required to move funds.
* Typically used in a 2-of-3 signing configuration. Uses ecrecover to allow for 2 signatures in a single transaction.
*/
contract WalletSimple {
// Events
event Deposited(address from, uint value, bytes data);
event SafeModeActivated(address msgSender);
event Transacted(
address msgSender, // Address of the sender of the message initiating the transaction
address otherSigner, // Address of the signer (second signature) used to initiate the transaction
bytes32 operation, // Operation hash (sha3 of toAddress, value, data, expireTime, sequenceId)
address toAddress, // The address the transaction was sent to
uint value, // Amount of Wei sent to the address
bytes data // Data sent when invoking the transaction
);
event TokenTransacted(
address msgSender, // Address of the sender of the message initiating the transaction
address otherSigner, // Address of the signer (second signature) used to initiate the transaction
bytes32 operation, // Operation hash (sha3 of toAddress, value, tokenContractAddress, expireTime, sequenceId)
address toAddress, // The address the transaction was sent to
uint value, // Amount of token sent
address tokenContractAddress // The contract address of the token
);
// Public fields
address[] public signers; // The addresses that can co-sign transactions on the wallet
bool public safeMode = false; // When active, wallet may only send to signer addresses
// Internal fields
uint constant SEQUENCE_ID_WINDOW_SIZE = 10;
uint[10] recentSequenceIds;
/**
* Modifier that will execute internal code block only if the sender is an authorized signer on this wallet
*/
modifier onlysigner {
if (!isSigner(msg.sender)) {
throw;
}
_;
}
/**
* Set up a simple multi-sig wallet by specifying the signers allowed to be used on this wallet.
* 2 signers will be required to send a transaction from this wallet.
* Note: The sender is NOT automatically added to the list of signers.
* Signers CANNOT be changed once they are set
*
* @param allowedSigners An array of signers on the wallet
*/
function WalletSimple(address[] allowedSigners) {
if (allowedSigners.length != 3) {
// Invalid number of signers
throw;
}
signers = allowedSigners;
}
/**
* Gets called when a transaction is received without calling a method
*/
function() payable {
if (msg.value > 0) {
// Fire deposited event if we are receiving funds
Deposited(msg.sender, msg.value, msg.data);
}
}
/**
* Create a new contract (and also address) that forwards funds to this contract
* returns address of newly created forwarder address
*/
function createForwarder() onlysigner returns (address) {
return new Forwarder();
}
/**
* Execute a multi-signature transaction from this wallet using 2 signers: one from msg.sender and the other from ecrecover.
* The signature is a signed form (using eth.sign) of tightly packed toAddress, value, data, expireTime and sequenceId
* Sequence IDs are numbers starting from 1. They are used to prevent replay attacks and may not be repeated.
*
* @param toAddress the destination address to send an outgoing transaction
* @param value the amount in Wei to be sent
* @param data the data to send to the toAddress when invoking the transaction
* @param expireTime the number of seconds since 1970 for which this transaction is valid
* @param sequenceId the unique sequence id obtainable from getNextSequenceId
* @param signature the result of eth.sign on the operationHash sha3(toAddress, value, data, expireTime, sequenceId)
*/
function sendMultiSig(address toAddress, uint value, bytes data, uint expireTime, uint sequenceId, bytes signature) onlysigner {
// Verify the other signer
var operationHash = sha3("ETHER", toAddress, value, data, expireTime, sequenceId);
var otherSigner = verifyMultiSig(toAddress, operationHash, signature, expireTime, sequenceId);
// Success, send the transaction
if (!(toAddress.call.value(value)(data))) {
// Failed executing transaction
throw;
}
Transacted(msg.sender, otherSigner, operationHash, toAddress, value, data);
}
/**
* Execute a multi-signature token transfer from this wallet using 2 signers: one from msg.sender and the other from ecrecover.
* The signature is a signed form (using eth.sign) of tightly packed toAddress, value, tokenContractAddress, expireTime and sequenceId
* Sequence IDs are numbers starting from 1. They are used to prevent replay attacks and may not be repeated.
*
* @param toAddress the destination address to send an outgoing transaction
* @param value the amount in tokens to be sent
* @param tokenContractAddress the address of the erc20 token contract
* @param expireTime the number of seconds since 1970 for which this transaction is valid
* @param sequenceId the unique sequence id obtainable from getNextSequenceId
* @param signature the result of eth.sign on the operationHash sha3(toAddress, value, tokenContractAddress, expireTime, sequenceId)
*/
function sendMultiSigToken(address toAddress, uint value, address tokenContractAddress, uint expireTime, uint sequenceId, bytes signature) onlysigner {
// Verify the other signer
var operationHash = sha3("ERC20", toAddress, value, tokenContractAddress, expireTime, sequenceId);
var otherSigner = verifyMultiSig(toAddress, operationHash, signature, expireTime, sequenceId);
ERC20Interface instance = ERC20Interface(tokenContractAddress);
if (!instance.transfer(toAddress, value)) {
throw;
}
TokenTransacted(msg.sender, otherSigner, operationHash, toAddress, value, tokenContractAddress);
}
/**
* Execute a token flush from one of the forwarder addresses. This transfer needs only a single signature and can be done by any signer
*
* @param forwarderAddress the address of the forwarder address to flush the tokens from
* @param tokenContractAddress the address of the erc20 token contract
*/
function flushForwarderTokens(address forwarderAddress, address tokenContractAddress) onlysigner {
Forwarder forwarder = Forwarder(forwarderAddress);
forwarder.flushTokens(tokenContractAddress);
}
/**
* Do common multisig verification for both eth sends and erc20token transfers
*
* @param toAddress the destination address to send an outgoing transaction
* @param operationHash the sha3 of the toAddress, value, data/tokenContractAddress and expireTime
* @param signature the tightly packed signature of r, s, and v as an array of 65 bytes (returned by eth.sign)
* @param expireTime the number of seconds since 1970 for which this transaction is valid
* @param sequenceId the unique sequence id obtainable from getNextSequenceId
* returns address of the address to send tokens or eth to
*/
function verifyMultiSig(address toAddress, bytes32 operationHash, bytes signature, uint expireTime, uint sequenceId) private returns (address) {
var otherSigner = recoverAddressFromSignature(operationHash, signature);
// Verify if we are in safe mode. In safe mode, the wallet can only send to signers
if (safeMode && !isSigner(toAddress)) {
// We are in safe mode and the toAddress is not a signer. Disallow!
throw;
}
// Verify that the transaction has not expired
if (expireTime < block.timestamp) {
// Transaction expired
throw;
}
// Try to insert the sequence ID. Will throw if the sequence id was invalid
tryInsertSequenceId(sequenceId);
if (!isSigner(otherSigner)) {
// Other signer not on this wallet or operation does not match arguments
throw;
}
if (otherSigner == msg.sender) {
// Cannot approve own transaction
throw;
}
return otherSigner;
}
/**
* Irrevocably puts contract into safe mode. When in this mode, transactions may only be sent to signing addresses.
*/
function activateSafeMode() onlysigner {
safeMode = true;
SafeModeActivated(msg.sender);
}
/**
* Determine if an address is a signer on this wallet
* @param signer address to check
* returns boolean indicating whether address is signer or not
*/
function isSigner(address signer) returns (bool) {
// Iterate through all signers on the wallet and
for (uint i = 0; i < signers.length; i++) {
if (signers[i] == signer) {
return true;
}
}
return false;
}
/**
* Gets the second signer's address using ecrecover
* @param operationHash the sha3 of the toAddress, value, data/tokenContractAddress and expireTime
* @param signature the tightly packed signature of r, s, and v as an array of 65 bytes (returned by eth.sign)
* returns address recovered from the signature
*/
function recoverAddressFromSignature(bytes32 operationHash, bytes signature) private returns (address) {
if (signature.length != 65) {
throw;
}
// We need to unpack the signature, which is given as an array of 65 bytes (from eth.sign)
bytes32 r;
bytes32 s;
uint8 v;
assembly {
r := mload(add(signature, 32))
s := mload(add(signature, 64))
v := and(mload(add(signature, 65)), 255)
}
if (v < 27) {
v += 27; // Ethereum versions are 27 or 28 as opposed to 0 or 1 which is submitted by some signing libs
}
return ecrecover(operationHash, v, r, s);
}
/**
* Verify that the sequence id has not been used before and inserts it. Throws if the sequence ID was not accepted.
* We collect a window of up to 10 recent sequence ids, and allow any sequence id that is not in the window and
* greater than the minimum element in the window.
* @param sequenceId to insert into array of stored ids
*/
function tryInsertSequenceId(uint sequenceId) onlysigner private {
// Keep a pointer to the lowest value element in the window
uint lowestValueIndex = 0;
for (uint i = 0; i < SEQUENCE_ID_WINDOW_SIZE; i++) {
if (recentSequenceIds[i] == sequenceId) {
// This sequence ID has been used before. Disallow!
throw;
}
if (recentSequenceIds[i] < recentSequenceIds[lowestValueIndex]) {
lowestValueIndex = i;
}
}
if (sequenceId < recentSequenceIds[lowestValueIndex]) {
// The sequence ID being used is lower than the lowest value in the window
// so we cannot accept it as it may have been used before
throw;
}
if (sequenceId > (recentSequenceIds[lowestValueIndex] + 10000)) {
// Block sequence IDs which are much higher than the lowest value
// This prevents people blocking the contract by using very large sequence IDs quickly
throw;
}
recentSequenceIds[lowestValueIndex] = sequenceId;
}
/**
* Gets the next available sequence ID for signing when using executeAndConfirm
* returns the sequenceId one higher than the highest currently stored
*/
function getNextSequenceId() returns (uint) {
uint highestSequenceId = 0;
for (uint i = 0; i < SEQUENCE_ID_WINDOW_SIZE; i++) {
if (recentSequenceIds[i] > highestSequenceId) {
highestSequenceId = recentSequenceIds[i];
}
}
return highestSequenceId + 1;
}
}
|
[{"constant":true,"inputs":[],"name":"parentAddress","outputs":[{"name":"","type":"address"}],"payable":false,"type":"function"},{"constant":false,"inputs":[{"name":"tokenContractAddress","type":"address"}],"name":"flushTokens","outputs":[],"payable":false,"type":"function"},{"constant":false,"inputs":[],"name":"flush","outputs":[],"payable":false,"type":"function"},{"inputs":[],"payable":false,"type":"constructor"},{"payable":true,"type":"fallback"},{"anonymous":false,"inputs":[{"indexed":false,"name":"from","type":"address"},{"indexed":false,"name":"value","type":"uint256"},{"indexed":false,"name":"data","type":"bytes"}],"name":"ForwarderDeposited","type":"event"},{"anonymous":false,"inputs":[{"indexed":false,"name":"tokenContractAddress","type":"address"},{"indexed":false,"name":"value","type":"uint256"}],"name":"TokensFlushed","type":"event"}]
|
v0.4.16-nightly.2017.8.11+commit.c84de7fa
| true
| 200
|
Default
| false
|
bzzr://d0f8838ba17108a895d34ae8ef3bff4e0dc9d639c3c51921fee1d17eaa803721
|
||||
InstaAccount
|
0x2c0323424e6f0730d4be5c7067a99bdf9631777a
|
Solidity
|
pragma solidity ^0.6.0;
pragma experimental ABIEncoderV2;
/**
* @title InstaAccount.
* @dev DeFi Smart Account Wallet.
*/
interface IndexInterface {
function connectors(uint version) external view returns (address);
function check(uint version) external view returns (address);
function list() external view returns (address);
}
interface ConnectorsInterface {
function isConnector(address[] calldata logicAddr) external view returns (bool);
function isStaticConnector(address[] calldata logicAddr) external view returns (bool);
}
interface CheckInterface {
function isOk() external view returns (bool);
}
interface ListInterface {
function addAuth(address user) external;
function removeAuth(address user) external;
}
contract Record {
event LogEnable(address indexed user);
event LogDisable(address indexed user);
event LogSwitchShield(bool _shield);
// InstaIndex Address.
address public constant instaIndex = 0x2971AdFa57b20E5a416aE5a708A8655A9c74f723;
// The Account Module Version.
uint public constant version = 1;
// Auth Module(Address of Auth => bool).
mapping (address => bool) private auth;
// Is shield true/false.
bool public shield;
/**
* @dev Check for Auth if enabled.
* @param user address/user/owner.
*/
function isAuth(address user) public view returns (bool) {
return auth[user];
}
/**
* @dev Change Shield State.
*/
function switchShield(bool _shield) external {
require(auth[msg.sender], "not-self");
require(shield != _shield, "shield is set");
shield = _shield;
emit LogSwitchShield(shield);
}
/**
* @dev Enable New User.
* @param user Owner of the Smart Account.
*/
function enable(address user) public {
require(msg.sender == address(this) || msg.sender == instaIndex, "not-self-index");
require(user != address(0), "not-valid");
require(!auth[user], "already-enabled");
auth[user] = true;
ListInterface(IndexInterface(instaIndex).list()).addAuth(user);
emit LogEnable(user);
}
/**
* @dev Disable User.
* @param user Owner of the Smart Account.
*/
function disable(address user) public {
require(msg.sender == address(this), "not-self");
require(user != address(0), "not-valid");
require(auth[user], "already-disabled");
delete auth[user];
ListInterface(IndexInterface(instaIndex).list()).removeAuth(user);
emit LogDisable(user);
}
}
contract InstaAccount is Record {
event LogCast(address indexed origin, address indexed sender, uint value);
receive() external payable {}
/**
* @dev Delegate the calls to Connector And this function is ran by cast().
* @param _target Target to of Connector.
* @param _data CallData of function in Connector.
*/
function spell(address _target, bytes memory _data) internal {
require(_target != address(0), "target-invalid");
assembly {
let succeeded := delegatecall(gas(), _target, add(_data, 0x20), mload(_data), 0, 0)
switch iszero(succeeded)
case 1 {
// throw if delegatecall failed
let size := returndatasize()
returndatacopy(0x00, 0x00, size)
revert(0x00, size)
}
}
}
/**
* @dev This is the main function, Where all the different functions are called
* from Smart Account.
* @param _targets Array of Target(s) to of Connector.
* @param _datas Array of Calldata(S) of function.
*/
function cast(
address[] calldata _targets,
bytes[] calldata _datas,
address _origin
)
external
payable
{
require(isAuth(msg.sender) || msg.sender == instaIndex, "permission-denied");
require(_targets.length == _datas.length , "array-length-invalid");
IndexInterface indexContract = IndexInterface(instaIndex);
bool isShield = shield;
if (!isShield) {
require(ConnectorsInterface(indexContract.connectors(version)).isConnector(_targets), "not-connector");
} else {
require(ConnectorsInterface(indexContract.connectors(version)).isStaticConnector(_targets), "not-static-connector");
}
for (uint i = 0; i < _targets.length; i++) {
spell(_targets[i], _datas[i]);
}
address _check = indexContract.check(version);
if (_check != address(0) && !isShield) require(CheckInterface(_check).isOk(), "not-ok");
emit LogCast(_origin, msg.sender, msg.value);
}
}
|
[{"anonymous":false,"inputs":[{"indexed":true,"internalType":"address","name":"origin","type":"address"},{"indexed":true,"internalType":"address","name":"sender","type":"address"},{"indexed":false,"internalType":"uint256","name":"value","type":"uint256"}],"name":"LogCast","type":"event"},{"anonymous":false,"inputs":[{"indexed":true,"internalType":"address","name":"user","type":"address"}],"name":"LogDisable","type":"event"},{"anonymous":false,"inputs":[{"indexed":true,"internalType":"address","name":"user","type":"address"}],"name":"LogEnable","type":"event"},{"anonymous":false,"inputs":[{"indexed":false,"internalType":"bool","name":"_shield","type":"bool"}],"name":"LogSwitchShield","type":"event"},{"inputs":[{"internalType":"address[]","name":"_targets","type":"address[]"},{"internalType":"bytes[]","name":"_datas","type":"bytes[]"},{"internalType":"address","name":"_origin","type":"address"}],"name":"cast","outputs":[],"stateMutability":"payable","type":"function"},{"inputs":[{"internalType":"address","name":"user","type":"address"}],"name":"disable","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"address","name":"user","type":"address"}],"name":"enable","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[],"name":"instaIndex","outputs":[{"internalType":"address","name":"","type":"address"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"address","name":"user","type":"address"}],"name":"isAuth","outputs":[{"internalType":"bool","name":"","type":"bool"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"shield","outputs":[{"internalType":"bool","name":"","type":"bool"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"bool","name":"_shield","type":"bool"}],"name":"switchShield","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[],"name":"version","outputs":[{"internalType":"uint256","name":"","type":"uint256"}],"stateMutability":"view","type":"function"},{"stateMutability":"payable","type":"receive"}]
|
v0.6.0+commit.26b70077
| false
| 200
|
Default
|
MIT
| false
|
ipfs://c7356d76ef680ea6649af388d2a518797700466c0a8ed7e5356ec7932509c8e8
|
|||
LockToken
|
0x0ea66dc5ee1e610394c741f887ae4c6f0167a098
|
Solidity
|
pragma solidity ^0.4.24;
/**
* @title SafeMath
* @dev Math operations with safety checks that throw on error
*/
library SafeMath {
function mul(uint256 a, uint256 b) internal pure returns (uint256) {
uint256 c = a * b;
assert(a == 0 || c / a == b);
return c;
}
function div(uint256 a, uint256 b) internal pure returns (uint256) {
// assert(b > 0); // Solidity automatically throws when dividing by 0
uint256 c = a / b;
// assert(a == b * c + a % b); // There is no case in which this doesn't hold
return c;
}
function sub(uint256 a, uint256 b) internal pure returns (uint256) {
assert(b <= a);
return a - b;
}
function add(uint256 a, uint256 b) internal pure returns (uint256) {
uint256 c = a + b;
assert(c >= a);
return c;
}
}
contract token {
function balanceOf(address _owner) public constant returns (uint256 balance);
function transfer(address _to, uint256 _value) public returns (bool success);
}
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.
*/
constructor() public{
owner = msg.sender;
}
/**
* @dev Throws if called by any account other than the owner.
*/
modifier onlyOwner() {
require(msg.sender == owner);
_;
}
/**
* @dev Allows the current owner to transfer control of the contract to a newOwner.
* @param newOwner The address to transfer ownership to.
*/
function transferOwnership(address newOwner) onlyOwner public {
require(newOwner != address(0));
emit OwnershipTransferred(owner, newOwner);
owner = newOwner;
}
}
contract LockToken is Ownable {
using SafeMath for uint256;
token token_reward;
address public beneficiary;
bool public isLocked = false;
bool public isReleased = false;
uint256 public start_time;
uint256 public end_time;
event TokenReleased(address beneficiary, uint256 token_amount);
constructor(address tokenContractAddress, address _beneficiary) public{
token_reward = token(tokenContractAddress);
beneficiary = _beneficiary;
}
function tokenBalance() constant public returns (uint256){
return token_reward.balanceOf(this);
}
function lock(uint256 lockTime) public onlyOwner returns (bool){
require(!isLocked);
require(tokenBalance() > 0);
start_time = now;
end_time = lockTime;
isLocked = true;
}
function lockOver() constant public returns (bool){
uint256 current_time = now;
return current_time > end_time;
}
function release() onlyOwner public{
require(isLocked);
require(!isReleased);
require(lockOver());
uint256 token_amount = tokenBalance();
token_reward.transfer( beneficiary, token_amount);
emit TokenReleased(beneficiary, token_amount);
isReleased = true;
}
}
|
[{"constant":true,"inputs":[],"name":"end_time","outputs":[{"name":"","type":"uint256"}],"payable":false,"stateMutability":"view","type":"function"},{"constant":true,"inputs":[],"name":"beneficiary","outputs":[{"name":"","type":"address"}],"payable":false,"stateMutability":"view","type":"function"},{"constant":true,"inputs":[],"name":"start_time","outputs":[{"name":"","type":"uint256"}],"payable":false,"stateMutability":"view","type":"function"},{"constant":false,"inputs":[],"name":"release","outputs":[],"payable":false,"stateMutability":"nonpayable","type":"function"},{"constant":true,"inputs":[],"name":"owner","outputs":[{"name":"","type":"address"}],"payable":false,"stateMutability":"view","type":"function"},{"constant":true,"inputs":[],"name":"lockOver","outputs":[{"name":"","type":"bool"}],"payable":false,"stateMutability":"view","type":"function"},{"constant":true,"inputs":[],"name":"tokenBalance","outputs":[{"name":"","type":"uint256"}],"payable":false,"stateMutability":"view","type":"function"},{"constant":true,"inputs":[],"name":"isLocked","outputs":[{"name":"","type":"bool"}],"payable":false,"stateMutability":"view","type":"function"},{"constant":false,"inputs":[{"name":"lockTime","type":"uint256"}],"name":"lock","outputs":[{"name":"","type":"bool"}],"payable":false,"stateMutability":"nonpayable","type":"function"},{"constant":false,"inputs":[{"name":"newOwner","type":"address"}],"name":"transferOwnership","outputs":[],"payable":false,"stateMutability":"nonpayable","type":"function"},{"constant":true,"inputs":[],"name":"isReleased","outputs":[{"name":"","type":"bool"}],"payable":false,"stateMutability":"view","type":"function"},{"inputs":[{"name":"tokenContractAddress","type":"address"},{"name":"_beneficiary","type":"address"}],"payable":false,"stateMutability":"nonpayable","type":"constructor"},{"anonymous":false,"inputs":[{"indexed":false,"name":"beneficiary","type":"address"},{"indexed":false,"name":"token_amount","type":"uint256"}],"name":"TokenReleased","type":"event"},{"anonymous":false,"inputs":[{"indexed":true,"name":"previousOwner","type":"address"},{"indexed":true,"name":"newOwner","type":"address"}],"name":"OwnershipTransferred","type":"event"}]
|
v0.4.24+commit.e67f0147
| true
| 200
|
000000000000000000000000aa1ae5e57dc05981d83ec7fca0b3c7ee2565b7d6000000000000000000000000dc2bdc0c335a5f727e5353c01453cd061d934eb7
|
Default
| false
|
bzzr://99c2ec89d57327903251481ffd6add6b411f458178a9c29747e3571d81f0e629
|
|||
InstaAccount
|
0xe8770f5b0232233a755c042319451cbe98310d4c
|
Solidity
|
pragma solidity ^0.6.0;
pragma experimental ABIEncoderV2;
/**
* @title InstaAccount.
* @dev DeFi Smart Account Wallet.
*/
interface IndexInterface {
function connectors(uint version) external view returns (address);
function check(uint version) external view returns (address);
function list() external view returns (address);
}
interface ConnectorsInterface {
function isConnector(address[] calldata logicAddr) external view returns (bool);
function isStaticConnector(address[] calldata logicAddr) external view returns (bool);
}
interface CheckInterface {
function isOk() external view returns (bool);
}
interface ListInterface {
function addAuth(address user) external;
function removeAuth(address user) external;
}
contract Record {
event LogEnable(address indexed user);
event LogDisable(address indexed user);
event LogSwitchShield(bool _shield);
// InstaIndex Address.
address public constant instaIndex = 0x2971AdFa57b20E5a416aE5a708A8655A9c74f723;
// The Account Module Version.
uint public constant version = 1;
// Auth Module(Address of Auth => bool).
mapping (address => bool) private auth;
// Is shield true/false.
bool public shield;
/**
* @dev Check for Auth if enabled.
* @param user address/user/owner.
*/
function isAuth(address user) public view returns (bool) {
return auth[user];
}
/**
* @dev Change Shield State.
*/
function switchShield(bool _shield) external {
require(auth[msg.sender], "not-self");
require(shield != _shield, "shield is set");
shield = _shield;
emit LogSwitchShield(shield);
}
/**
* @dev Enable New User.
* @param user Owner of the Smart Account.
*/
function enable(address user) public {
require(msg.sender == address(this) || msg.sender == instaIndex, "not-self-index");
require(user != address(0), "not-valid");
require(!auth[user], "already-enabled");
auth[user] = true;
ListInterface(IndexInterface(instaIndex).list()).addAuth(user);
emit LogEnable(user);
}
/**
* @dev Disable User.
* @param user Owner of the Smart Account.
*/
function disable(address user) public {
require(msg.sender == address(this), "not-self");
require(user != address(0), "not-valid");
require(auth[user], "already-disabled");
delete auth[user];
ListInterface(IndexInterface(instaIndex).list()).removeAuth(user);
emit LogDisable(user);
}
}
contract InstaAccount is Record {
event LogCast(address indexed origin, address indexed sender, uint value);
receive() external payable {}
/**
* @dev Delegate the calls to Connector And this function is ran by cast().
* @param _target Target to of Connector.
* @param _data CallData of function in Connector.
*/
function spell(address _target, bytes memory _data) internal {
require(_target != address(0), "target-invalid");
assembly {
let succeeded := delegatecall(gas(), _target, add(_data, 0x20), mload(_data), 0, 0)
switch iszero(succeeded)
case 1 {
// throw if delegatecall failed
let size := returndatasize()
returndatacopy(0x00, 0x00, size)
revert(0x00, size)
}
}
}
/**
* @dev This is the main function, Where all the different functions are called
* from Smart Account.
* @param _targets Array of Target(s) to of Connector.
* @param _datas Array of Calldata(S) of function.
*/
function cast(
address[] calldata _targets,
bytes[] calldata _datas,
address _origin
)
external
payable
{
require(isAuth(msg.sender) || msg.sender == instaIndex, "permission-denied");
require(_targets.length == _datas.length , "array-length-invalid");
IndexInterface indexContract = IndexInterface(instaIndex);
bool isShield = shield;
if (!isShield) {
require(ConnectorsInterface(indexContract.connectors(version)).isConnector(_targets), "not-connector");
} else {
require(ConnectorsInterface(indexContract.connectors(version)).isStaticConnector(_targets), "not-static-connector");
}
for (uint i = 0; i < _targets.length; i++) {
spell(_targets[i], _datas[i]);
}
address _check = indexContract.check(version);
if (_check != address(0) && !isShield) require(CheckInterface(_check).isOk(), "not-ok");
emit LogCast(_origin, msg.sender, msg.value);
}
}
|
[{"anonymous":false,"inputs":[{"indexed":true,"internalType":"address","name":"origin","type":"address"},{"indexed":true,"internalType":"address","name":"sender","type":"address"},{"indexed":false,"internalType":"uint256","name":"value","type":"uint256"}],"name":"LogCast","type":"event"},{"anonymous":false,"inputs":[{"indexed":true,"internalType":"address","name":"user","type":"address"}],"name":"LogDisable","type":"event"},{"anonymous":false,"inputs":[{"indexed":true,"internalType":"address","name":"user","type":"address"}],"name":"LogEnable","type":"event"},{"anonymous":false,"inputs":[{"indexed":false,"internalType":"bool","name":"_shield","type":"bool"}],"name":"LogSwitchShield","type":"event"},{"inputs":[{"internalType":"address[]","name":"_targets","type":"address[]"},{"internalType":"bytes[]","name":"_datas","type":"bytes[]"},{"internalType":"address","name":"_origin","type":"address"}],"name":"cast","outputs":[],"stateMutability":"payable","type":"function"},{"inputs":[{"internalType":"address","name":"user","type":"address"}],"name":"disable","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"address","name":"user","type":"address"}],"name":"enable","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[],"name":"instaIndex","outputs":[{"internalType":"address","name":"","type":"address"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"address","name":"user","type":"address"}],"name":"isAuth","outputs":[{"internalType":"bool","name":"","type":"bool"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"shield","outputs":[{"internalType":"bool","name":"","type":"bool"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"bool","name":"_shield","type":"bool"}],"name":"switchShield","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[],"name":"version","outputs":[{"internalType":"uint256","name":"","type":"uint256"}],"stateMutability":"view","type":"function"},{"stateMutability":"payable","type":"receive"}]
|
v0.6.0+commit.26b70077
| false
| 200
|
Default
|
MIT
| false
|
ipfs://c7356d76ef680ea6649af388d2a518797700466c0a8ed7e5356ec7932509c8e8
|
|||
UserWallet
|
0x1cc4bb8965abc492989986c5ea382ef13833180e
|
Solidity
|
pragma solidity ^0.4.10;
// Copyright 2017 Bittrex
contract AbstractSweeper {
function sweep(address token, uint amount) returns (bool);
function () { throw; }
Controller controller;
function AbstractSweeper(address _controller) {
controller = Controller(_controller);
}
modifier canSweep() {
if (msg.sender != controller.authorizedCaller() && msg.sender != controller.owner()) throw;
if (controller.halted()) throw;
_;
}
}
contract Token {
function balanceOf(address a) returns (uint) {
(a);
return 0;
}
function transfer(address a, uint val) returns (bool) {
(a);
(val);
return false;
}
}
contract DefaultSweeper is AbstractSweeper {
function DefaultSweeper(address controller)
AbstractSweeper(controller) {}
function sweep(address _token, uint _amount)
canSweep
returns (bool) {
bool success = false;
address destination = controller.destination();
if (_token != address(0)) {
Token token = Token(_token);
uint amount = _amount;
if (amount > token.balanceOf(this)) {
return false;
}
success = token.transfer(destination, amount);
}
else {
uint amountInWei = _amount;
if (amountInWei > this.balance) {
return false;
}
success = destination.send(amountInWei);
}
if (success) {
controller.logSweep(this, destination, _token, _amount);
}
return success;
}
}
contract UserWallet {
AbstractSweeperList sweeperList;
function UserWallet(address _sweeperlist) {
sweeperList = AbstractSweeperList(_sweeperlist);
}
function () public payable { }
function tokenFallback(address _from, uint _value, bytes _data) {
(_from);
(_value);
(_data);
}
function sweep(address _token, uint _amount)
returns (bool) {
(_amount);
return sweeperList.sweeperOf(_token).delegatecall(msg.data);
}
}
contract AbstractSweeperList {
function sweeperOf(address _token) returns (address);
}
contract Controller is AbstractSweeperList {
address public owner;
address public authorizedCaller;
address public destination;
bool public halted;
event LogNewWallet(address receiver);
event LogSweep(address indexed from, address indexed to, address indexed token, uint amount);
modifier onlyOwner() {
if (msg.sender != owner) throw;
_;
}
modifier onlyAuthorizedCaller() {
if (msg.sender != authorizedCaller) throw;
_;
}
modifier onlyAdmins() {
if (msg.sender != authorizedCaller && msg.sender != owner) throw;
_;
}
function Controller()
{
owner = msg.sender;
destination = msg.sender;
authorizedCaller = msg.sender;
}
function changeAuthorizedCaller(address _newCaller) onlyOwner {
authorizedCaller = _newCaller;
}
function changeDestination(address _dest) onlyOwner {
destination = _dest;
}
function changeOwner(address _owner) onlyOwner {
owner = _owner;
}
function makeWallet() onlyAdmins returns (address wallet) {
wallet = address(new UserWallet(this));
LogNewWallet(wallet);
}
function halt() onlyAdmins {
halted = true;
}
function start() onlyOwner {
halted = false;
}
address public defaultSweeper = address(new DefaultSweeper(this));
mapping (address => address) sweepers;
function addSweeper(address _token, address _sweeper) onlyOwner {
sweepers[_token] = _sweeper;
}
function sweeperOf(address _token) returns (address) {
address sweeper = sweepers[_token];
if (sweeper == 0) sweeper = defaultSweeper;
return sweeper;
}
function logSweep(address from, address to, address token, uint amount) {
LogSweep(from, to, token, amount);
}
}
|
[{"constant":false,"inputs":[{"name":"_token","type":"address"},{"name":"_amount","type":"uint256"}],"name":"sweep","outputs":[{"name":"","type":"bool"}],"payable":false,"type":"function"},{"constant":false,"inputs":[{"name":"_from","type":"address"},{"name":"_value","type":"uint256"},{"name":"_data","type":"bytes"}],"name":"tokenFallback","outputs":[],"payable":false,"type":"function"},{"inputs":[{"name":"_sweeperlist","type":"address"}],"payable":false,"type":"constructor"},{"payable":true,"type":"fallback"}]
|
v0.4.11+commit.68ef5810
| true
| 200
|
000000000000000000000000a3C1E324CA1ce40db73eD6026c4A177F099B5770
|
Default
| false
|
bzzr://4cdd69fdcf3cf6cbee9677fe380fa5f044048aa9e060ec5619a21ca5a5bd4cd1
|
|||
UserWallet
|
0x8ef52261c914ee70eef05e601c7078d4be399a1f
|
Solidity
|
pragma solidity ^0.4.10;
// Copyright 2017 Bittrex
contract AbstractSweeper {
function sweep(address token, uint amount) returns (bool);
function () { throw; }
Controller controller;
function AbstractSweeper(address _controller) {
controller = Controller(_controller);
}
modifier canSweep() {
if (msg.sender != controller.authorizedCaller() && msg.sender != controller.owner()) throw;
if (controller.halted()) throw;
_;
}
}
contract Token {
function balanceOf(address a) returns (uint) {
(a);
return 0;
}
function transfer(address a, uint val) returns (bool) {
(a);
(val);
return false;
}
}
contract DefaultSweeper is AbstractSweeper {
function DefaultSweeper(address controller)
AbstractSweeper(controller) {}
function sweep(address _token, uint _amount)
canSweep
returns (bool) {
bool success = false;
address destination = controller.destination();
if (_token != address(0)) {
Token token = Token(_token);
uint amount = _amount;
if (amount > token.balanceOf(this)) {
return false;
}
success = token.transfer(destination, amount);
}
else {
uint amountInWei = _amount;
if (amountInWei > this.balance) {
return false;
}
success = destination.send(amountInWei);
}
if (success) {
controller.logSweep(this, destination, _token, _amount);
}
return success;
}
}
contract UserWallet {
AbstractSweeperList sweeperList;
function UserWallet(address _sweeperlist) {
sweeperList = AbstractSweeperList(_sweeperlist);
}
function () public payable { }
function tokenFallback(address _from, uint _value, bytes _data) {
(_from);
(_value);
(_data);
}
function sweep(address _token, uint _amount)
returns (bool) {
(_amount);
return sweeperList.sweeperOf(_token).delegatecall(msg.data);
}
}
contract AbstractSweeperList {
function sweeperOf(address _token) returns (address);
}
contract Controller is AbstractSweeperList {
address public owner;
address public authorizedCaller;
address public destination;
bool public halted;
event LogNewWallet(address receiver);
event LogSweep(address indexed from, address indexed to, address indexed token, uint amount);
modifier onlyOwner() {
if (msg.sender != owner) throw;
_;
}
modifier onlyAuthorizedCaller() {
if (msg.sender != authorizedCaller) throw;
_;
}
modifier onlyAdmins() {
if (msg.sender != authorizedCaller && msg.sender != owner) throw;
_;
}
function Controller()
{
owner = msg.sender;
destination = msg.sender;
authorizedCaller = msg.sender;
}
function changeAuthorizedCaller(address _newCaller) onlyOwner {
authorizedCaller = _newCaller;
}
function changeDestination(address _dest) onlyOwner {
destination = _dest;
}
function changeOwner(address _owner) onlyOwner {
owner = _owner;
}
function makeWallet() onlyAdmins returns (address wallet) {
wallet = address(new UserWallet(this));
LogNewWallet(wallet);
}
function halt() onlyAdmins {
halted = true;
}
function start() onlyOwner {
halted = false;
}
address public defaultSweeper = address(new DefaultSweeper(this));
mapping (address => address) sweepers;
function addSweeper(address _token, address _sweeper) onlyOwner {
sweepers[_token] = _sweeper;
}
function sweeperOf(address _token) returns (address) {
address sweeper = sweepers[_token];
if (sweeper == 0) sweeper = defaultSweeper;
return sweeper;
}
function logSweep(address from, address to, address token, uint amount) {
LogSweep(from, to, token, amount);
}
}
|
[{"constant":false,"inputs":[{"name":"_token","type":"address"},{"name":"_amount","type":"uint256"}],"name":"sweep","outputs":[{"name":"","type":"bool"}],"payable":false,"type":"function"},{"constant":false,"inputs":[{"name":"_from","type":"address"},{"name":"_value","type":"uint256"},{"name":"_data","type":"bytes"}],"name":"tokenFallback","outputs":[],"payable":false,"type":"function"},{"inputs":[{"name":"_sweeperlist","type":"address"}],"payable":false,"type":"constructor"},{"payable":true,"type":"fallback"}]
|
v0.4.11+commit.68ef5810
| true
| 200
|
000000000000000000000000a3C1E324CA1ce40db73eD6026c4A177F099B5770
|
Default
| false
|
bzzr://4cdd69fdcf3cf6cbee9677fe380fa5f044048aa9e060ec5619a21ca5a5bd4cd1
|
|||
SimpleChildToken
|
0x3dda0d81b48aead148585664d4c0e369701ba9bf
|
Solidity
|
pragma solidity ^0.4.21;
// File: openzeppelin-solidity/contracts/math/SafeMath.sol
/**
* @title SafeMath
* @dev Math operations with safety checks that throw on error
*/
library SafeMath {
/**
* @dev Multiplies two numbers, throws on overflow.
*/
function mul(uint256 a, uint256 b) internal pure returns (uint256 c) {
if (a == 0) {
return 0;
}
c = a * b;
assert(c / a == b);
return c;
}
/**
* @dev Integer division of two numbers, truncating the quotient.
*/
function div(uint256 a, uint256 b) internal pure returns (uint256) {
// assert(b > 0); // Solidity automatically throws when dividing by 0
// uint256 c = a / b;
// assert(a == b * c + a % b); // There is no case in which this doesn't hold
return a / b;
}
/**
* @dev Subtracts two numbers, throws on overflow (i.e. if subtrahend is greater than minuend).
*/
function sub(uint256 a, uint256 b) internal pure returns (uint256) {
assert(b <= a);
return a - b;
}
/**
* @dev Adds two numbers, throws on overflow.
*/
function add(uint256 a, uint256 b) internal pure returns (uint256 c) {
c = a + b;
assert(c >= a);
return c;
}
}
// File: openzeppelin-solidity/contracts/token/ERC20/ERC20Basic.sol
/**
* @title ERC20Basic
* @dev Simpler version of ERC20 interface
* @dev see https://github.com/ethereum/EIPs/issues/179
*/
contract ERC20Basic {
function totalSupply() public view returns (uint256);
function balanceOf(address who) public view returns (uint256);
function transfer(address to, uint256 value) public returns (bool);
event Transfer(address indexed from, address indexed to, uint256 value);
}
// File: openzeppelin-solidity/contracts/token/ERC20/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;
uint256 totalSupply_;
/**
* @dev total number of tokens in existence
*/
function totalSupply() public view returns (uint256) {
return totalSupply_;
}
/**
* @dev transfer token for a specified address
* @param _to The address to transfer to.
* @param _value The amount to be transferred.
*/
function transfer(address _to, uint256 _value) public returns (bool) {
require(_to != address(0));
require(_value <= balances[msg.sender]);
balances[msg.sender] = balances[msg.sender].sub(_value);
balances[_to] = balances[_to].add(_value);
emit Transfer(msg.sender, _to, _value);
return true;
}
/**
* @dev Gets the balance of the specified address.
* @param _owner The address to query the the balance of.
* @return An uint256 representing the amount owned by the passed address.
*/
function balanceOf(address _owner) public view returns (uint256) {
return balances[_owner];
}
}
// File: openzeppelin-solidity/contracts/token/ERC20/ERC20.sol
/**
* @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);
}
// File: openzeppelin-solidity/contracts/token/ERC20/StandardToken.sol
/**
* @title Standard ERC20 token
*
* @dev Implementation of the basic standard token.
* @dev https://github.com/ethereum/EIPs/issues/20
* @dev Based on code by FirstBlood: https://github.com/Firstbloodio/token/blob/master/smart_contract/FirstBloodToken.sol
*/
contract StandardToken is ERC20, BasicToken {
mapping (address => mapping (address => uint256)) internal allowed;
/**
* @dev Transfer tokens from one address to another
* @param _from address The address which you want to send tokens from
* @param _to address The address which you want to transfer to
* @param _value uint256 the amount of tokens to be transferred
*/
function transferFrom(address _from, address _to, uint256 _value) public returns (bool) {
require(_to != address(0));
require(_value <= balances[_from]);
require(_value <= allowed[_from][msg.sender]);
balances[_from] = balances[_from].sub(_value);
balances[_to] = balances[_to].add(_value);
allowed[_from][msg.sender] = allowed[_from][msg.sender].sub(_value);
emit Transfer(_from, _to, _value);
return true;
}
/**
* @dev Approve the passed address to spend the specified amount of tokens on behalf of msg.sender.
*
* Beware that changing an allowance with this method brings the risk that someone may use both the old
* and the new allowance by unfortunate transaction ordering. One possible solution to mitigate this
* race condition is to first reduce the spender's allowance to 0 and set the desired value afterwards:
* https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729
* @param _spender The address which will spend the funds.
* @param _value The amount of tokens to be spent.
*/
function approve(address _spender, uint256 _value) public returns (bool) {
allowed[msg.sender][_spender] = _value;
emit Approval(msg.sender, _spender, _value);
return true;
}
/**
* @dev Function to check the amount of tokens that an owner allowed to a spender.
* @param _owner address The address which owns the funds.
* @param _spender address The address which will spend the funds.
* @return A uint256 specifying the amount of tokens still available for the spender.
*/
function allowance(address _owner, address _spender) public view returns (uint256) {
return allowed[_owner][_spender];
}
/**
* @dev Increase the amount of tokens that an owner allowed to a spender.
*
* approve should be called when allowed[_spender] == 0. To increment
* allowed value is better to use this function to avoid 2 calls (and wait until
* the first transaction is mined)
* From MonolithDAO Token.sol
* @param _spender The address which will spend the funds.
* @param _addedValue The amount of tokens to increase the allowance by.
*/
function increaseApproval(address _spender, uint _addedValue) public returns (bool) {
allowed[msg.sender][_spender] = allowed[msg.sender][_spender].add(_addedValue);
emit Approval(msg.sender, _spender, allowed[msg.sender][_spender]);
return true;
}
/**
* @dev Decrease the amount of tokens that an owner allowed to a spender.
*
* approve should be called when allowed[_spender] == 0. To decrement
* allowed value is better to use this function to avoid 2 calls (and wait until
* the first transaction is mined)
* From MonolithDAO Token.sol
* @param _spender The address which will spend the funds.
* @param _subtractedValue The amount of tokens to decrease the allowance by.
*/
function decreaseApproval(address _spender, uint _subtractedValue) public returns (bool) {
uint oldValue = allowed[msg.sender][_spender];
if (_subtractedValue > oldValue) {
allowed[msg.sender][_spender] = 0;
} else {
allowed[msg.sender][_spender] = oldValue.sub(_subtractedValue);
}
emit Approval(msg.sender, _spender, allowed[msg.sender][_spender]);
return true;
}
}
// File: contracts/ChildToken.sol
/**
* @title ChildToken
* @dev ChildToken is the base contract of child token contracts
*/
contract ChildToken is StandardToken {
}
// File: openzeppelin-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));
emit OwnershipTransferred(owner, newOwner);
owner = newOwner;
}
}
// File: contracts/Refundable.sol
/**
* @title Refundable
* @dev Base contract that can refund funds(ETH and tokens) by owner.
* @dev Reference TokenDestructible(zeppelinand) TokenDestructible(zeppelin)
*/
contract Refundable is Ownable {
event RefundETH(address indexed owner, address indexed payee, uint256 amount);
event RefundERC20(address indexed owner, address indexed payee, address indexed token, uint256 amount);
function Refundable() public payable {
}
function refundETH(address payee, uint256 amount) onlyOwner public {
require(payee != address(0));
require(this.balance >= amount);
assert(payee.send(amount));
RefundETH(owner, payee, amount);
}
function refundERC20(address tokenContract, address payee, uint256 amount) onlyOwner public {
require(payee != address(0));
bool isContract;
assembly {
isContract := gt(extcodesize(tokenContract), 0)
}
require(isContract);
ERC20 token = ERC20(tokenContract);
assert(token.transfer(payee, amount));
RefundERC20(owner, payee, tokenContract, amount);
}
}
// File: contracts/SimpleChildToken.sol
/**
* @title SimpleChildToken
* @dev Simple child token to be generated by TokenFather.
*/
contract SimpleChildToken is ChildToken, Refundable {
string public name;
string public symbol;
uint8 public decimals;
function SimpleChildToken(address _owner, string _name, string _symbol, uint256 _initSupply, uint8 _decimals) public {
require(_owner != address(0));
owner = _owner;
name = _name;
symbol = _symbol;
decimals = _decimals;
uint256 amount = _initSupply;
totalSupply_ = totalSupply_.add(amount);
balances[owner] = balances[owner].add(amount);
Transfer(address(0), owner, amount);
}
}
|
[{"constant":true,"inputs":[],"name":"name","outputs":[{"name":"","type":"string"}],"payable":false,"stateMutability":"view","type":"function"},{"constant":false,"inputs":[{"name":"_spender","type":"address"},{"name":"_value","type":"uint256"}],"name":"approve","outputs":[{"name":"","type":"bool"}],"payable":false,"stateMutability":"nonpayable","type":"function"},{"constant":true,"inputs":[],"name":"totalSupply","outputs":[{"name":"","type":"uint256"}],"payable":false,"stateMutability":"view","type":"function"},{"constant":false,"inputs":[{"name":"_from","type":"address"},{"name":"_to","type":"address"},{"name":"_value","type":"uint256"}],"name":"transferFrom","outputs":[{"name":"","type":"bool"}],"payable":false,"stateMutability":"nonpayable","type":"function"},{"constant":true,"inputs":[],"name":"decimals","outputs":[{"name":"","type":"uint8"}],"payable":false,"stateMutability":"view","type":"function"},{"constant":false,"inputs":[{"name":"tokenContract","type":"address"},{"name":"payee","type":"address"},{"name":"amount","type":"uint256"}],"name":"refundERC20","outputs":[],"payable":false,"stateMutability":"nonpayable","type":"function"},{"constant":false,"inputs":[{"name":"payee","type":"address"},{"name":"amount","type":"uint256"}],"name":"refundETH","outputs":[],"payable":false,"stateMutability":"nonpayable","type":"function"},{"constant":false,"inputs":[{"name":"_spender","type":"address"},{"name":"_subtractedValue","type":"uint256"}],"name":"decreaseApproval","outputs":[{"name":"","type":"bool"}],"payable":false,"stateMutability":"nonpayable","type":"function"},{"constant":true,"inputs":[{"name":"_owner","type":"address"}],"name":"balanceOf","outputs":[{"name":"","type":"uint256"}],"payable":false,"stateMutability":"view","type":"function"},{"constant":true,"inputs":[],"name":"owner","outputs":[{"name":"","type":"address"}],"payable":false,"stateMutability":"view","type":"function"},{"constant":true,"inputs":[],"name":"symbol","outputs":[{"name":"","type":"string"}],"payable":false,"stateMutability":"view","type":"function"},{"constant":false,"inputs":[{"name":"_to","type":"address"},{"name":"_value","type":"uint256"}],"name":"transfer","outputs":[{"name":"","type":"bool"}],"payable":false,"stateMutability":"nonpayable","type":"function"},{"constant":false,"inputs":[{"name":"_spender","type":"address"},{"name":"_addedValue","type":"uint256"}],"name":"increaseApproval","outputs":[{"name":"","type":"bool"}],"payable":false,"stateMutability":"nonpayable","type":"function"},{"constant":true,"inputs":[{"name":"_owner","type":"address"},{"name":"_spender","type":"address"}],"name":"allowance","outputs":[{"name":"","type":"uint256"}],"payable":false,"stateMutability":"view","type":"function"},{"constant":false,"inputs":[{"name":"newOwner","type":"address"}],"name":"transferOwnership","outputs":[],"payable":false,"stateMutability":"nonpayable","type":"function"},{"inputs":[{"name":"_owner","type":"address"},{"name":"_name","type":"string"},{"name":"_symbol","type":"string"},{"name":"_initSupply","type":"uint256"},{"name":"_decimals","type":"uint8"}],"payable":false,"stateMutability":"nonpayable","type":"constructor"},{"anonymous":false,"inputs":[{"indexed":true,"name":"owner","type":"address"},{"indexed":true,"name":"payee","type":"address"},{"indexed":false,"name":"amount","type":"uint256"}],"name":"RefundETH","type":"event"},{"anonymous":false,"inputs":[{"indexed":true,"name":"owner","type":"address"},{"indexed":true,"name":"payee","type":"address"},{"indexed":true,"name":"token","type":"address"},{"indexed":false,"name":"amount","type":"uint256"}],"name":"RefundERC20","type":"event"},{"anonymous":false,"inputs":[{"indexed":true,"name":"previousOwner","type":"address"},{"indexed":true,"name":"newOwner","type":"address"}],"name":"OwnershipTransferred","type":"event"},{"anonymous":false,"inputs":[{"indexed":true,"name":"owner","type":"address"},{"indexed":true,"name":"spender","type":"address"},{"indexed":false,"name":"value","type":"uint256"}],"name":"Approval","type":"event"},{"anonymous":false,"inputs":[{"indexed":true,"name":"from","type":"address"},{"indexed":true,"name":"to","type":"address"},{"indexed":false,"name":"value","type":"uint256"}],"name":"Transfer","type":"event"}]
|
v0.4.24+commit.e67f0147
| true
| 200
|
000000000000000000000000025bf0b26099c10b3f90f3a040703064faf84ac200000000000000000000000000000000000000000000000000000000000000a000000000000000000000000000000000000000000000000000000000000000e000000000000000000000000000000000000000000052b7d2dcc80cd2e4000000000000000000000000000000000000000000000000000000000000000000001200000000000000000000000000000000000000000000000000000000000000094d6f6f6b546f6b656e000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000024d54000000000000000000000000000000000000000000000000000000000000
|
Default
| false
|
bzzr://3ad6ad55aadee502c53a711f8c0f2fdc334bbcb68c344a76aee5d1ac28681c63
|
|||
CustomToken
|
0xe14039a9f3120c45b8c0b3881ade055e46694755
|
Solidity
|
pragma solidity ^0.4.25;
contract BaseToken {
string public name;
string public symbol;
uint8 public decimals;
uint256 public totalSupply;
mapping (address => uint256) public balanceOf;
mapping (address => mapping (address => uint256)) public allowance;
event Transfer(address indexed from, address indexed to, uint256 value);
event Approval(address indexed owner, address indexed spender, uint256 value);
function _transfer(address _from, address _to, uint _value) internal {
require(_to != 0x0);
require(balanceOf[_from] >= _value);
require(balanceOf[_to] + _value > balanceOf[_to]);
uint previousBalances = balanceOf[_from] + balanceOf[_to];
balanceOf[_from] -= _value;
balanceOf[_to] += _value;
assert(balanceOf[_from] + balanceOf[_to] == previousBalances);
Transfer(_from, _to, _value);
}
function transfer(address _to, uint256 _value) public returns (bool success) {
_transfer(msg.sender, _to, _value);
return true;
}
function transferFrom(address _from, address _to, uint256 _value) public returns (bool success) {
require(_value <= allowance[_from][msg.sender]);
allowance[_from][msg.sender] -= _value;
_transfer(_from, _to, _value);
return true;
}
function approve(address _spender, uint256 _value) public returns (bool success) {
allowance[msg.sender][_spender] = _value;
Approval(msg.sender, _spender, _value);
return true;
}
}
contract CustomToken is BaseToken {
function CustomToken() public {
totalSupply = 50000000000000000000000000;
name = 'changeum';
symbol = 'CNGX';
decimals = 18;
balanceOf[0x290a76806ec39e731877b8874a32761d60321bcd] = totalSupply;
Transfer(address(0), 0x290a76806ec39e731877b8874a32761d60321bcd, totalSupply);
}
}
|
[{"constant":true,"inputs":[],"name":"name","outputs":[{"name":"","type":"string"}],"payable":false,"stateMutability":"view","type":"function"},{"constant":false,"inputs":[{"name":"_spender","type":"address"},{"name":"_value","type":"uint256"}],"name":"approve","outputs":[{"name":"success","type":"bool"}],"payable":false,"stateMutability":"nonpayable","type":"function"},{"constant":true,"inputs":[],"name":"totalSupply","outputs":[{"name":"","type":"uint256"}],"payable":false,"stateMutability":"view","type":"function"},{"constant":false,"inputs":[{"name":"_from","type":"address"},{"name":"_to","type":"address"},{"name":"_value","type":"uint256"}],"name":"transferFrom","outputs":[{"name":"success","type":"bool"}],"payable":false,"stateMutability":"nonpayable","type":"function"},{"constant":true,"inputs":[],"name":"decimals","outputs":[{"name":"","type":"uint8"}],"payable":false,"stateMutability":"view","type":"function"},{"constant":true,"inputs":[{"name":"","type":"address"}],"name":"balanceOf","outputs":[{"name":"","type":"uint256"}],"payable":false,"stateMutability":"view","type":"function"},{"constant":true,"inputs":[],"name":"symbol","outputs":[{"name":"","type":"string"}],"payable":false,"stateMutability":"view","type":"function"},{"constant":false,"inputs":[{"name":"_to","type":"address"},{"name":"_value","type":"uint256"}],"name":"transfer","outputs":[{"name":"success","type":"bool"}],"payable":false,"stateMutability":"nonpayable","type":"function"},{"constant":true,"inputs":[{"name":"","type":"address"},{"name":"","type":"address"}],"name":"allowance","outputs":[{"name":"","type":"uint256"}],"payable":false,"stateMutability":"view","type":"function"},{"inputs":[],"payable":false,"stateMutability":"nonpayable","type":"constructor"},{"anonymous":false,"inputs":[{"indexed":true,"name":"from","type":"address"},{"indexed":true,"name":"to","type":"address"},{"indexed":false,"name":"value","type":"uint256"}],"name":"Transfer","type":"event"},{"anonymous":false,"inputs":[{"indexed":true,"name":"owner","type":"address"},{"indexed":true,"name":"spender","type":"address"},{"indexed":false,"name":"value","type":"uint256"}],"name":"Approval","type":"event"}]
|
v0.4.25+commit.59dbf8f1
| true
| 200
|
Default
| false
|
bzzr://d1c509f26ecdc6429499d4bc771fa69fea6b0b64fb891b6ba2a1a88114b3e5bb
|
||||
UserWallet
|
0xf60feb362c0a81574575af208aa20558e2540740
|
Solidity
|
pragma solidity ^0.4.10;
// Copyright 2017 Bittrex
contract AbstractSweeper {
function sweep(address token, uint amount) returns (bool);
function () { throw; }
Controller controller;
function AbstractSweeper(address _controller) {
controller = Controller(_controller);
}
modifier canSweep() {
if (msg.sender != controller.authorizedCaller() && msg.sender != controller.owner()) throw;
if (controller.halted()) throw;
_;
}
}
contract Token {
function balanceOf(address a) returns (uint) {
(a);
return 0;
}
function transfer(address a, uint val) returns (bool) {
(a);
(val);
return false;
}
}
contract DefaultSweeper is AbstractSweeper {
function DefaultSweeper(address controller)
AbstractSweeper(controller) {}
function sweep(address _token, uint _amount)
canSweep
returns (bool) {
bool success = false;
address destination = controller.destination();
if (_token != address(0)) {
Token token = Token(_token);
uint amount = _amount;
if (amount > token.balanceOf(this)) {
return false;
}
success = token.transfer(destination, amount);
}
else {
uint amountInWei = _amount;
if (amountInWei > this.balance) {
return false;
}
success = destination.send(amountInWei);
}
if (success) {
controller.logSweep(this, destination, _token, _amount);
}
return success;
}
}
contract UserWallet {
AbstractSweeperList sweeperList;
function UserWallet(address _sweeperlist) {
sweeperList = AbstractSweeperList(_sweeperlist);
}
function () public payable { }
function tokenFallback(address _from, uint _value, bytes _data) {
(_from);
(_value);
(_data);
}
function sweep(address _token, uint _amount)
returns (bool) {
(_amount);
return sweeperList.sweeperOf(_token).delegatecall(msg.data);
}
}
contract AbstractSweeperList {
function sweeperOf(address _token) returns (address);
}
contract Controller is AbstractSweeperList {
address public owner;
address public authorizedCaller;
address public destination;
bool public halted;
event LogNewWallet(address receiver);
event LogSweep(address indexed from, address indexed to, address indexed token, uint amount);
modifier onlyOwner() {
if (msg.sender != owner) throw;
_;
}
modifier onlyAuthorizedCaller() {
if (msg.sender != authorizedCaller) throw;
_;
}
modifier onlyAdmins() {
if (msg.sender != authorizedCaller && msg.sender != owner) throw;
_;
}
function Controller()
{
owner = msg.sender;
destination = msg.sender;
authorizedCaller = msg.sender;
}
function changeAuthorizedCaller(address _newCaller) onlyOwner {
authorizedCaller = _newCaller;
}
function changeDestination(address _dest) onlyOwner {
destination = _dest;
}
function changeOwner(address _owner) onlyOwner {
owner = _owner;
}
function makeWallet() onlyAdmins returns (address wallet) {
wallet = address(new UserWallet(this));
LogNewWallet(wallet);
}
function halt() onlyAdmins {
halted = true;
}
function start() onlyOwner {
halted = false;
}
address public defaultSweeper = address(new DefaultSweeper(this));
mapping (address => address) sweepers;
function addSweeper(address _token, address _sweeper) onlyOwner {
sweepers[_token] = _sweeper;
}
function sweeperOf(address _token) returns (address) {
address sweeper = sweepers[_token];
if (sweeper == 0) sweeper = defaultSweeper;
return sweeper;
}
function logSweep(address from, address to, address token, uint amount) {
LogSweep(from, to, token, amount);
}
}
|
[{"constant":false,"inputs":[{"name":"_token","type":"address"},{"name":"_amount","type":"uint256"}],"name":"sweep","outputs":[{"name":"","type":"bool"}],"payable":false,"type":"function"},{"constant":false,"inputs":[{"name":"_from","type":"address"},{"name":"_value","type":"uint256"},{"name":"_data","type":"bytes"}],"name":"tokenFallback","outputs":[],"payable":false,"type":"function"},{"inputs":[{"name":"_sweeperlist","type":"address"}],"payable":false,"type":"constructor"},{"payable":true,"type":"fallback"}]
|
v0.4.11+commit.68ef5810
| true
| 200
|
000000000000000000000000a3C1E324CA1ce40db73eD6026c4A177F099B5770
|
Default
| false
|
bzzr://4cdd69fdcf3cf6cbee9677fe380fa5f044048aa9e060ec5619a21ca5a5bd4cd1
|
|||
RocketMinipool
|
0x93a6f596390c1629a72217a066b4523d190d3da3
|
Solidity
|
// File: /contracts/contract/minipool/RocketMinipool.sol
/**
* .
* / \
* |.'.|
* |'.'|
* ,'| |`.
* |,-'-|-'-.|
* __|_| | _ _ _____ _
* | ___ \| | | | | | ___ \ | |
* | |_/ /|__ ___| | _____| |_ | |_/ /__ ___ | |
* | // _ \ / __| |/ / _ \ __| | __/ _ \ / _ \| |
* | |\ \ (_) | (__| < __/ |_ | | | (_) | (_) | |
* \_| \_\___/ \___|_|\_\___|\__| \_| \___/ \___/|_|
* +---------------------------------------------------+
* | DECENTRALISED STAKING PROTOCOL FOR ETHEREUM 2.0 |
* +---------------------------------------------------+
*
* Rocket Pool is a first-of-its-kind ETH2 Proof of Stake protocol, designed to be community owned,
* decentralised, trustless and compatible with staking in Ethereum 2.0.
*
* For more information about Rocket Pool, visit https://rocketpool.net
*
* Authors: David Rugendyke, Jake Pospischil, Kane Wallmann, Darren Langley, Joe Clapis, Nick Doherty
*
*/
pragma solidity 0.7.6;
// SPDX-License-Identifier: GPL-3.0-only
import "./RocketMinipoolStorageLayout.sol";
import "../../interface/RocketStorageInterface.sol";
import "../../types/MinipoolDeposit.sol";
import "../../types/MinipoolStatus.sol";
// An individual minipool in the Rocket Pool network
contract RocketMinipool is RocketMinipoolStorageLayout {
// Events
event EtherReceived(address indexed from, uint256 amount, uint256 time);
event DelegateUpgraded(address oldDelegate, address newDelegate, uint256 time);
event DelegateRolledBack(address oldDelegate, address newDelegate, uint256 time);
// Modifiers
// Only allow access from the owning node address
modifier onlyMinipoolOwner() {
// Only the node operator can upgrade
address withdrawalAddress = rocketStorage.getNodeWithdrawalAddress(nodeAddress);
require(msg.sender == nodeAddress || msg.sender == withdrawalAddress, "Only the node operator can access this method");
_;
}
// Construct
constructor(RocketStorageInterface _rocketStorageAddress, address _nodeAddress, MinipoolDeposit _depositType) {
// Initialise RocketStorage
require(address(_rocketStorageAddress) != address(0x0), "Invalid storage address");
rocketStorage = RocketStorageInterface(_rocketStorageAddress);
// Set storage state to uninitialised
storageState = StorageState.Uninitialised;
// Set the current delegate
address delegateAddress = getContractAddress("rocketMinipoolDelegate");
rocketMinipoolDelegate = delegateAddress;
// Check for contract existence
require(contractExists(delegateAddress), "Delegate contract does not exist");
// Call initialise on delegate
(bool success, bytes memory data) = delegateAddress.delegatecall(abi.encodeWithSignature('initialise(address,uint8)', _nodeAddress, uint8(_depositType)));
if (!success) { revert(getRevertMessage(data)); }
}
// Receive an ETH deposit
receive() external payable {
// Emit ether received event
emit EtherReceived(msg.sender, msg.value, block.timestamp);
}
// Upgrade this minipool to the latest network delegate contract
function delegateUpgrade() external onlyMinipoolOwner {
// Set previous address
rocketMinipoolDelegatePrev = rocketMinipoolDelegate;
// Set new delegate
rocketMinipoolDelegate = getContractAddress("rocketMinipoolDelegate");
// Verify
require(rocketMinipoolDelegate != rocketMinipoolDelegatePrev, "New delegate is the same as the existing one");
// Log event
emit DelegateUpgraded(rocketMinipoolDelegatePrev, rocketMinipoolDelegate, block.timestamp);
}
// Rollback to previous delegate contract
function delegateRollback() external onlyMinipoolOwner {
// Make sure they have upgraded before
require(rocketMinipoolDelegatePrev != address(0x0), "Previous delegate contract is not set");
// Store original
address originalDelegate = rocketMinipoolDelegate;
// Update delegate to previous and zero out previous
rocketMinipoolDelegate = rocketMinipoolDelegatePrev;
rocketMinipoolDelegatePrev = address(0x0);
// Log event
emit DelegateRolledBack(originalDelegate, rocketMinipoolDelegate, block.timestamp);
}
// If set to true, will automatically use the latest delegate contract
function setUseLatestDelegate(bool _setting) external onlyMinipoolOwner {
useLatestDelegate = _setting;
}
// Getter for useLatestDelegate setting
function getUseLatestDelegate() external view returns (bool) {
return useLatestDelegate;
}
// Returns the address of the minipool's stored delegate
function getDelegate() external view returns (address) {
return rocketMinipoolDelegate;
}
// Returns the address of the minipool's previous delegate (or address(0) if not set)
function getPreviousDelegate() external view returns (address) {
return rocketMinipoolDelegatePrev;
}
// Returns the delegate which will be used when calling this minipool taking into account useLatestDelegate setting
function getEffectiveDelegate() external view returns (address) {
return useLatestDelegate ? getContractAddress("rocketMinipoolDelegate") : rocketMinipoolDelegate;
}
// Delegate all other calls to minipool delegate contract
fallback(bytes calldata _input) external payable returns (bytes memory) {
// If useLatestDelegate is set, use the latest delegate contract
address delegateContract = useLatestDelegate ? getContractAddress("rocketMinipoolDelegate") : rocketMinipoolDelegate;
// Check for contract existence
require(contractExists(delegateContract), "Delegate contract does not exist");
// Execute delegatecall
(bool success, bytes memory data) = delegateContract.delegatecall(_input);
if (!success) { revert(getRevertMessage(data)); }
return data;
}
// Get the address of a Rocket Pool network contract
function getContractAddress(string memory _contractName) private view returns (address) {
address contractAddress = rocketStorage.getAddress(keccak256(abi.encodePacked("contract.address", _contractName)));
require(contractAddress != address(0x0), "Contract not found");
return contractAddress;
}
// Get a revert message from delegatecall return data
function getRevertMessage(bytes memory _returnData) private pure returns (string memory) {
if (_returnData.length < 68) { return "Transaction reverted silently"; }
assembly {
_returnData := add(_returnData, 0x04)
}
return abi.decode(_returnData, (string));
}
// Returns true if contract exists at _contractAddress (if called during that contract's construction it will return a false negative)
function contractExists(address _contractAddress) private returns (bool) {
uint32 codeSize;
assembly {
codeSize := extcodesize(_contractAddress)
}
return codeSize > 0;
}
}
// File: /contracts/contract/minipool/RocketMinipoolStorageLayout.sol
/**
* .
* / \
* |.'.|
* |'.'|
* ,'| |`.
* |,-'-|-'-.|
* __|_| | _ _ _____ _
* | ___ \| | | | | | ___ \ | |
* | |_/ /|__ ___| | _____| |_ | |_/ /__ ___ | |
* | // _ \ / __| |/ / _ \ __| | __/ _ \ / _ \| |
* | |\ \ (_) | (__| < __/ |_ | | | (_) | (_) | |
* \_| \_\___/ \___|_|\_\___|\__| \_| \___/ \___/|_|
* +---------------------------------------------------+
* | DECENTRALISED STAKING PROTOCOL FOR ETHEREUM 2.0 |
* +---------------------------------------------------+
*
* Rocket Pool is a first-of-its-kind ETH2 Proof of Stake protocol, designed to be community owned,
* decentralised, trustless and compatible with staking in Ethereum 2.0.
*
* For more information about Rocket Pool, visit https://rocketpool.net
*
* Authors: David Rugendyke, Jake Pospischil, Kane Wallmann, Darren Langley, Joe Clapis, Nick Doherty
*
*/
pragma solidity 0.7.6;
// SPDX-License-Identifier: GPL-3.0-only
import "../../interface/RocketStorageInterface.sol";
import "../../types/MinipoolDeposit.sol";
import "../../types/MinipoolStatus.sol";
// The RocketMinipool contract storage layout, shared by RocketMinipoolDelegate
// ******************************************************
// Note: This contract MUST NOT BE UPDATED after launch.
// All deployed minipool contracts must maintain a
// Consistent storage layout with RocketMinipoolDelegate.
// ******************************************************
abstract contract RocketMinipoolStorageLayout {
// Storage state enum
enum StorageState {
Undefined,
Uninitialised,
Initialised
}
// Main Rocket Pool storage contract
RocketStorageInterface internal rocketStorage = RocketStorageInterface(0);
// Status
MinipoolStatus internal status;
uint256 internal statusBlock;
uint256 internal statusTime;
uint256 internal withdrawalBlock;
// Deposit type
MinipoolDeposit internal depositType;
// Node details
address internal nodeAddress;
uint256 internal nodeFee;
uint256 internal nodeDepositBalance;
bool internal nodeDepositAssigned;
uint256 internal nodeRefundBalance;
uint256 internal nodeSlashBalance;
// User deposit details
uint256 internal userDepositBalance;
uint256 internal userDepositAssignedTime;
// Upgrade options
bool internal useLatestDelegate = false;
address internal rocketMinipoolDelegate;
address internal rocketMinipoolDelegatePrev;
// Local copy of RETH address
address internal rocketTokenRETH;
// Local copy of penalty contract
address internal rocketMinipoolPenalty;
// Used to prevent direct access to delegate and prevent calling initialise more than once
StorageState storageState = StorageState.Undefined;
// Whether node operator has finalised the pool
bool internal finalised;
// Trusted member scrub votes
mapping(address => bool) memberScrubVotes;
uint256 totalScrubVotes;
}
// File: /contracts/interface/RocketStorageInterface.sol
/**
* .
* / \
* |.'.|
* |'.'|
* ,'| |`.
* |,-'-|-'-.|
* __|_| | _ _ _____ _
* | ___ \| | | | | | ___ \ | |
* | |_/ /|__ ___| | _____| |_ | |_/ /__ ___ | |
* | // _ \ / __| |/ / _ \ __| | __/ _ \ / _ \| |
* | |\ \ (_) | (__| < __/ |_ | | | (_) | (_) | |
* \_| \_\___/ \___|_|\_\___|\__| \_| \___/ \___/|_|
* +---------------------------------------------------+
* | DECENTRALISED STAKING PROTOCOL FOR ETHEREUM 2.0 |
* +---------------------------------------------------+
*
* Rocket Pool is a first-of-its-kind ETH2 Proof of Stake protocol, designed to be community owned,
* decentralised, trustless and compatible with staking in Ethereum 2.0.
*
* For more information about Rocket Pool, visit https://rocketpool.net
*
* Authors: David Rugendyke, Jake Pospischil, Kane Wallmann, Darren Langley, Joe Clapis, Nick Doherty
*
*/
pragma solidity 0.7.6;
// SPDX-License-Identifier: GPL-3.0-only
interface RocketStorageInterface {
// Deploy status
function getDeployedStatus() external view returns (bool);
// Guardian
function getGuardian() external view returns(address);
function setGuardian(address _newAddress) external;
function confirmGuardian() external;
// Getters
function getAddress(bytes32 _key) external view returns (address);
function getUint(bytes32 _key) external view returns (uint);
function getString(bytes32 _key) external view returns (string memory);
function getBytes(bytes32 _key) external view returns (bytes memory);
function getBool(bytes32 _key) external view returns (bool);
function getInt(bytes32 _key) external view returns (int);
function getBytes32(bytes32 _key) external view returns (bytes32);
// Setters
function setAddress(bytes32 _key, address _value) external;
function setUint(bytes32 _key, uint _value) external;
function setString(bytes32 _key, string calldata _value) external;
function setBytes(bytes32 _key, bytes calldata _value) external;
function setBool(bytes32 _key, bool _value) external;
function setInt(bytes32 _key, int _value) external;
function setBytes32(bytes32 _key, bytes32 _value) external;
// Deleters
function deleteAddress(bytes32 _key) external;
function deleteUint(bytes32 _key) external;
function deleteString(bytes32 _key) external;
function deleteBytes(bytes32 _key) external;
function deleteBool(bytes32 _key) external;
function deleteInt(bytes32 _key) external;
function deleteBytes32(bytes32 _key) external;
// Arithmetic
function addUint(bytes32 _key, uint256 _amount) external;
function subUint(bytes32 _key, uint256 _amount) external;
// Protected storage
function getNodeWithdrawalAddress(address _nodeAddress) external view returns (address);
function getNodePendingWithdrawalAddress(address _nodeAddress) external view returns (address);
function setWithdrawalAddress(address _nodeAddress, address _newWithdrawalAddress, bool _confirm) external;
function confirmWithdrawalAddress(address _nodeAddress) external;
}
// File: /contracts/types/MinipoolDeposit.sol
/**
* .
* / \
* |.'.|
* |'.'|
* ,'| |`.
* |,-'-|-'-.|
* __|_| | _ _ _____ _
* | ___ \| | | | | | ___ \ | |
* | |_/ /|__ ___| | _____| |_ | |_/ /__ ___ | |
* | // _ \ / __| |/ / _ \ __| | __/ _ \ / _ \| |
* | |\ \ (_) | (__| < __/ |_ | | | (_) | (_) | |
* \_| \_\___/ \___|_|\_\___|\__| \_| \___/ \___/|_|
* +---------------------------------------------------+
* | DECENTRALISED STAKING PROTOCOL FOR ETHEREUM 2.0 |
* +---------------------------------------------------+
*
* Rocket Pool is a first-of-its-kind ETH2 Proof of Stake protocol, designed to be community owned,
* decentralised, trustless and compatible with staking in Ethereum 2.0.
*
* For more information about Rocket Pool, visit https://rocketpool.net
*
* Authors: David Rugendyke, Jake Pospischil, Kane Wallmann, Darren Langley, Joe Clapis, Nick Doherty
*
*/
pragma solidity 0.7.6;
// SPDX-License-Identifier: GPL-3.0-only
// Represents the type of deposits required by a minipool
enum MinipoolDeposit {
None, // Marks an invalid deposit type
Full, // The minipool requires 32 ETH from the node operator, 16 ETH of which will be refinanced from user deposits
Half, // The minipool required 16 ETH from the node operator to be matched with 16 ETH from user deposits
Empty // The minipool requires 0 ETH from the node operator to be matched with 32 ETH from user deposits (trusted nodes only)
}
// File: /contracts/types/MinipoolStatus.sol
/**
* .
* / \
* |.'.|
* |'.'|
* ,'| |`.
* |,-'-|-'-.|
* __|_| | _ _ _____ _
* | ___ \| | | | | | ___ \ | |
* | |_/ /|__ ___| | _____| |_ | |_/ /__ ___ | |
* | // _ \ / __| |/ / _ \ __| | __/ _ \ / _ \| |
* | |\ \ (_) | (__| < __/ |_ | | | (_) | (_) | |
* \_| \_\___/ \___|_|\_\___|\__| \_| \___/ \___/|_|
* +---------------------------------------------------+
* | DECENTRALISED STAKING PROTOCOL FOR ETHEREUM 2.0 |
* +---------------------------------------------------+
*
* Rocket Pool is a first-of-its-kind ETH2 Proof of Stake protocol, designed to be community owned,
* decentralised, trustless and compatible with staking in Ethereum 2.0.
*
* For more information about Rocket Pool, visit https://rocketpool.net
*
* Authors: David Rugendyke, Jake Pospischil, Kane Wallmann, Darren Langley, Joe Clapis, Nick Doherty
*
*/
pragma solidity 0.7.6;
// SPDX-License-Identifier: GPL-3.0-only
// Represents a minipool's status within the network
enum MinipoolStatus {
Initialised, // The minipool has been initialised and is awaiting a deposit of user ETH
Prelaunch, // The minipool has enough ETH to begin staking and is awaiting launch by the node operator
Staking, // The minipool is currently staking
Withdrawable, // The minipool has become withdrawable on the beacon chain and can be withdrawn from by the node operator
Dissolved // The minipool has been dissolved and its user deposited ETH has been returned to the deposit pool
}
|
[{"inputs":[{"internalType":"contract RocketStorageInterface","name":"_rocketStorageAddress","type":"address"},{"internalType":"address","name":"_nodeAddress","type":"address"},{"internalType":"enum MinipoolDeposit","name":"_depositType","type":"uint8"}],"stateMutability":"nonpayable","type":"constructor"},{"anonymous":false,"inputs":[{"indexed":false,"internalType":"address","name":"oldDelegate","type":"address"},{"indexed":false,"internalType":"address","name":"newDelegate","type":"address"},{"indexed":false,"internalType":"uint256","name":"time","type":"uint256"}],"name":"DelegateRolledBack","type":"event"},{"anonymous":false,"inputs":[{"indexed":false,"internalType":"address","name":"oldDelegate","type":"address"},{"indexed":false,"internalType":"address","name":"newDelegate","type":"address"},{"indexed":false,"internalType":"uint256","name":"time","type":"uint256"}],"name":"DelegateUpgraded","type":"event"},{"anonymous":false,"inputs":[{"indexed":true,"internalType":"address","name":"from","type":"address"},{"indexed":false,"internalType":"uint256","name":"amount","type":"uint256"},{"indexed":false,"internalType":"uint256","name":"time","type":"uint256"}],"name":"EtherReceived","type":"event"},{"stateMutability":"payable","type":"fallback"},{"inputs":[],"name":"delegateRollback","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[],"name":"delegateUpgrade","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[],"name":"getDelegate","outputs":[{"internalType":"address","name":"","type":"address"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"getEffectiveDelegate","outputs":[{"internalType":"address","name":"","type":"address"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"getPreviousDelegate","outputs":[{"internalType":"address","name":"","type":"address"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"getUseLatestDelegate","outputs":[{"internalType":"bool","name":"","type":"bool"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"bool","name":"_setting","type":"bool"}],"name":"setUseLatestDelegate","outputs":[],"stateMutability":"nonpayable","type":"function"},{"stateMutability":"payable","type":"receive"}]
|
v0.7.6+commit.7338295f
| true
| 15,000
|
0000000000000000000000001d8f8f00cfa6758d7bE78336684788Fb0ee0Fa4600000000000000000000000082ed7b4d62b6f1e297ed1cc598b42d61c89ea7910000000000000000000000000000000000000000000000000000000000000002
|
istanbul
|
GNU GPLv3
| false
|
ipfs://9a6daedd83e54e66fbfbf927322718b812db513528d0b0bf4667b671d50dbd53
|
||
UniswapV2Pair
|
0x2ccc8116095e800ccb07406308472514d79c92cc
|
Solidity
|
// File: contracts/interfaces/IUniswapV2Pair.sol
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/interfaces/IUniswapV2ERC20.sol
pragma solidity >=0.5.0;
interface IUniswapV2ERC20 {
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;
}
// File: contracts/libraries/SafeMath.sol
pragma solidity =0.5.16;
// a library for performing overflow-safe math, courtesy of DappHub (https://github.com/dapphub/ds-math)
library SafeMath {
function add(uint x, uint y) internal pure returns (uint z) {
require((z = x + y) >= x, 'ds-math-add-overflow');
}
function sub(uint x, uint y) internal pure returns (uint z) {
require((z = x - y) <= x, 'ds-math-sub-underflow');
}
function mul(uint x, uint y) internal pure returns (uint z) {
require(y == 0 || (z = x * y) / y == x, 'ds-math-mul-overflow');
}
}
// File: contracts/UniswapV2ERC20.sol
pragma solidity =0.5.16;
contract UniswapV2ERC20 is IUniswapV2ERC20 {
using SafeMath for uint;
string public constant name = 'Uniswap V2';
string public constant symbol = 'UNI-V2';
uint8 public constant decimals = 18;
uint public totalSupply;
mapping(address => uint) public balanceOf;
mapping(address => mapping(address => uint)) public allowance;
bytes32 public DOMAIN_SEPARATOR;
// keccak256("Permit(address owner,address spender,uint256 value,uint256 nonce,uint256 deadline)");
bytes32 public constant PERMIT_TYPEHASH = 0x6e71edae12b1b97f4d1f60370fef10105fa2faae0126114a169c64845d6126c9;
mapping(address => uint) public nonces;
event Approval(address indexed owner, address indexed spender, uint value);
event Transfer(address indexed from, address indexed to, uint value);
constructor() public {
uint chainId;
assembly {
chainId := chainid
}
DOMAIN_SEPARATOR = keccak256(
abi.encode(
keccak256('EIP712Domain(string name,string version,uint256 chainId,address verifyingContract)'),
keccak256(bytes(name)),
keccak256(bytes('1')),
chainId,
address(this)
)
);
}
function _mint(address to, uint value) internal {
totalSupply = totalSupply.add(value);
balanceOf[to] = balanceOf[to].add(value);
emit Transfer(address(0), to, value);
}
function _burn(address from, uint value) internal {
balanceOf[from] = balanceOf[from].sub(value);
totalSupply = totalSupply.sub(value);
emit Transfer(from, address(0), value);
}
function _approve(address owner, address spender, uint value) private {
allowance[owner][spender] = value;
emit Approval(owner, spender, value);
}
function _transfer(address from, address to, uint value) private {
balanceOf[from] = balanceOf[from].sub(value);
balanceOf[to] = balanceOf[to].add(value);
emit Transfer(from, to, value);
}
function approve(address spender, uint value) external returns (bool) {
_approve(msg.sender, spender, value);
return true;
}
function transfer(address to, uint value) external returns (bool) {
_transfer(msg.sender, to, value);
return true;
}
function transferFrom(address from, address to, uint value) external returns (bool) {
if (allowance[from][msg.sender] != uint(-1)) {
allowance[from][msg.sender] = allowance[from][msg.sender].sub(value);
}
_transfer(from, to, value);
return true;
}
function permit(address owner, address spender, uint value, uint deadline, uint8 v, bytes32 r, bytes32 s) external {
require(deadline >= block.timestamp, 'UniswapV2: EXPIRED');
bytes32 digest = keccak256(
abi.encodePacked(
'\x19\x01',
DOMAIN_SEPARATOR,
keccak256(abi.encode(PERMIT_TYPEHASH, owner, spender, value, nonces[owner]++, deadline))
)
);
address recoveredAddress = ecrecover(digest, v, r, s);
require(recoveredAddress != address(0) && recoveredAddress == owner, 'UniswapV2: INVALID_SIGNATURE');
_approve(owner, spender, value);
}
}
// File: contracts/libraries/Math.sol
pragma solidity =0.5.16;
// a library for performing various math operations
library Math {
function min(uint x, uint y) internal pure returns (uint z) {
z = x < y ? x : y;
}
// babylonian method (https://en.wikipedia.org/wiki/Methods_of_computing_square_roots#Babylonian_method)
function sqrt(uint y) internal pure returns (uint z) {
if (y > 3) {
z = y;
uint x = y / 2 + 1;
while (x < z) {
z = x;
x = (y / x + x) / 2;
}
} else if (y != 0) {
z = 1;
}
}
}
// File: contracts/libraries/UQ112x112.sol
pragma solidity =0.5.16;
// a library for handling binary fixed point numbers (https://en.wikipedia.org/wiki/Q_(number_format))
// range: [0, 2**112 - 1]
// resolution: 1 / 2**112
library UQ112x112 {
uint224 constant Q112 = 2**112;
// encode a uint112 as a UQ112x112
function encode(uint112 y) internal pure returns (uint224 z) {
z = uint224(y) * Q112; // never overflows
}
// divide a UQ112x112 by a uint112, returning a UQ112x112
function uqdiv(uint224 x, uint112 y) internal pure returns (uint224 z) {
z = x / uint224(y);
}
}
// File: contracts/interfaces/IERC20.sol
pragma solidity >=0.5.0;
interface IERC20 {
event Approval(address indexed owner, address indexed spender, uint value);
event Transfer(address indexed from, address indexed to, uint value);
function name() external view returns (string memory);
function symbol() external view returns (string memory);
function decimals() external view returns (uint8);
function totalSupply() external view returns (uint);
function balanceOf(address owner) external view returns (uint);
function allowance(address owner, address spender) external view returns (uint);
function approve(address spender, uint value) external returns (bool);
function transfer(address to, uint value) external returns (bool);
function transferFrom(address from, address to, uint value) external returns (bool);
}
// File: contracts/interfaces/IUniswapV2Factory.sol
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;
}
// File: contracts/interfaces/IUniswapV2Callee.sol
pragma solidity >=0.5.0;
interface IUniswapV2Callee {
function uniswapV2Call(address sender, uint amount0, uint amount1, bytes calldata data) external;
}
// File: contracts/UniswapV2Pair.sol
pragma solidity =0.5.16;
contract UniswapV2Pair is IUniswapV2Pair, UniswapV2ERC20 {
using SafeMath for uint;
using UQ112x112 for uint224;
uint public constant MINIMUM_LIQUIDITY = 10**3;
bytes4 private constant SELECTOR = bytes4(keccak256(bytes('transfer(address,uint256)')));
address public factory;
address public token0;
address public token1;
uint112 private reserve0; // uses single storage slot, accessible via getReserves
uint112 private reserve1; // uses single storage slot, accessible via getReserves
uint32 private blockTimestampLast; // uses single storage slot, accessible via getReserves
uint public price0CumulativeLast;
uint public price1CumulativeLast;
uint public kLast; // reserve0 * reserve1, as of immediately after the most recent liquidity event
uint private unlocked = 1;
modifier lock() {
require(unlocked == 1, 'UniswapV2: LOCKED');
unlocked = 0;
_;
unlocked = 1;
}
function getReserves() public view returns (uint112 _reserve0, uint112 _reserve1, uint32 _blockTimestampLast) {
_reserve0 = reserve0;
_reserve1 = reserve1;
_blockTimestampLast = blockTimestampLast;
}
function _safeTransfer(address token, address to, uint value) private {
(bool success, bytes memory data) = token.call(abi.encodeWithSelector(SELECTOR, to, value));
require(success && (data.length == 0 || abi.decode(data, (bool))), 'UniswapV2: TRANSFER_FAILED');
}
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);
constructor() public {
factory = msg.sender;
}
// called once by the factory at time of deployment
function initialize(address _token0, address _token1) external {
require(msg.sender == factory, 'UniswapV2: FORBIDDEN'); // sufficient check
token0 = _token0;
token1 = _token1;
}
// update reserves and, on the first call per block, price accumulators
function _update(uint balance0, uint balance1, uint112 _reserve0, uint112 _reserve1) private {
require(balance0 <= uint112(-1) && balance1 <= uint112(-1), 'UniswapV2: OVERFLOW');
uint32 blockTimestamp = uint32(block.timestamp % 2**32);
uint32 timeElapsed = blockTimestamp - blockTimestampLast; // overflow is desired
if (timeElapsed > 0 && _reserve0 != 0 && _reserve1 != 0) {
// * never overflows, and + overflow is desired
price0CumulativeLast += uint(UQ112x112.encode(_reserve1).uqdiv(_reserve0)) * timeElapsed;
price1CumulativeLast += uint(UQ112x112.encode(_reserve0).uqdiv(_reserve1)) * timeElapsed;
}
reserve0 = uint112(balance0);
reserve1 = uint112(balance1);
blockTimestampLast = blockTimestamp;
emit Sync(reserve0, reserve1);
}
// if fee is on, mint liquidity equivalent to 1/6th of the growth in sqrt(k)
function _mintFee(uint112 _reserve0, uint112 _reserve1) private returns (bool feeOn) {
address feeTo = IUniswapV2Factory(factory).feeTo();
feeOn = feeTo != address(0);
uint _kLast = kLast; // gas savings
if (feeOn) {
if (_kLast != 0) {
uint rootK = Math.sqrt(uint(_reserve0).mul(_reserve1));
uint rootKLast = Math.sqrt(_kLast);
if (rootK > rootKLast) {
uint numerator = totalSupply.mul(rootK.sub(rootKLast));
uint denominator = rootK.mul(5).add(rootKLast);
uint liquidity = numerator / denominator;
if (liquidity > 0) _mint(feeTo, liquidity);
}
}
} else if (_kLast != 0) {
kLast = 0;
}
}
// this low-level function should be called from a contract which performs important safety checks
function mint(address to) external lock returns (uint liquidity) {
(uint112 _reserve0, uint112 _reserve1,) = getReserves(); // gas savings
uint balance0 = IERC20(token0).balanceOf(address(this));
uint balance1 = IERC20(token1).balanceOf(address(this));
uint amount0 = balance0.sub(_reserve0);
uint amount1 = balance1.sub(_reserve1);
bool feeOn = _mintFee(_reserve0, _reserve1);
uint _totalSupply = totalSupply; // gas savings, must be defined here since totalSupply can update in _mintFee
if (_totalSupply == 0) {
liquidity = Math.sqrt(amount0.mul(amount1)).sub(MINIMUM_LIQUIDITY);
_mint(address(0), MINIMUM_LIQUIDITY); // permanently lock the first MINIMUM_LIQUIDITY tokens
} else {
liquidity = Math.min(amount0.mul(_totalSupply) / _reserve0, amount1.mul(_totalSupply) / _reserve1);
}
require(liquidity > 0, 'UniswapV2: INSUFFICIENT_LIQUIDITY_MINTED');
_mint(to, liquidity);
_update(balance0, balance1, _reserve0, _reserve1);
if (feeOn) kLast = uint(reserve0).mul(reserve1); // reserve0 and reserve1 are up-to-date
emit Mint(msg.sender, amount0, amount1);
}
// this low-level function should be called from a contract which performs important safety checks
function burn(address to) external lock returns (uint amount0, uint amount1) {
(uint112 _reserve0, uint112 _reserve1,) = getReserves(); // gas savings
address _token0 = token0; // gas savings
address _token1 = token1; // gas savings
uint balance0 = IERC20(_token0).balanceOf(address(this));
uint balance1 = IERC20(_token1).balanceOf(address(this));
uint liquidity = balanceOf[address(this)];
bool feeOn = _mintFee(_reserve0, _reserve1);
uint _totalSupply = totalSupply; // gas savings, must be defined here since totalSupply can update in _mintFee
amount0 = liquidity.mul(balance0) / _totalSupply; // using balances ensures pro-rata distribution
amount1 = liquidity.mul(balance1) / _totalSupply; // using balances ensures pro-rata distribution
require(amount0 > 0 && amount1 > 0, 'UniswapV2: INSUFFICIENT_LIQUIDITY_BURNED');
_burn(address(this), liquidity);
_safeTransfer(_token0, to, amount0);
_safeTransfer(_token1, to, amount1);
balance0 = IERC20(_token0).balanceOf(address(this));
balance1 = IERC20(_token1).balanceOf(address(this));
_update(balance0, balance1, _reserve0, _reserve1);
if (feeOn) kLast = uint(reserve0).mul(reserve1); // reserve0 and reserve1 are up-to-date
emit Burn(msg.sender, amount0, amount1, to);
}
// this low-level function should be called from a contract which performs important safety checks
function swap(uint amount0Out, uint amount1Out, address to, bytes calldata data) external lock {
require(amount0Out > 0 || amount1Out > 0, 'UniswapV2: INSUFFICIENT_OUTPUT_AMOUNT');
(uint112 _reserve0, uint112 _reserve1,) = getReserves(); // gas savings
require(amount0Out < _reserve0 && amount1Out < _reserve1, 'UniswapV2: INSUFFICIENT_LIQUIDITY');
uint balance0;
uint balance1;
{ // scope for _token{0,1}, avoids stack too deep errors
address _token0 = token0;
address _token1 = token1;
require(to != _token0 && to != _token1, 'UniswapV2: INVALID_TO');
if (amount0Out > 0) _safeTransfer(_token0, to, amount0Out); // optimistically transfer tokens
if (amount1Out > 0) _safeTransfer(_token1, to, amount1Out); // optimistically transfer tokens
if (data.length > 0) IUniswapV2Callee(to).uniswapV2Call(msg.sender, amount0Out, amount1Out, data);
balance0 = IERC20(_token0).balanceOf(address(this));
balance1 = IERC20(_token1).balanceOf(address(this));
}
uint amount0In = balance0 > _reserve0 - amount0Out ? balance0 - (_reserve0 - amount0Out) : 0;
uint amount1In = balance1 > _reserve1 - amount1Out ? balance1 - (_reserve1 - amount1Out) : 0;
require(amount0In > 0 || amount1In > 0, 'UniswapV2: INSUFFICIENT_INPUT_AMOUNT');
{ // scope for reserve{0,1}Adjusted, avoids stack too deep errors
uint balance0Adjusted = balance0.mul(1000).sub(amount0In.mul(3));
uint balance1Adjusted = balance1.mul(1000).sub(amount1In.mul(3));
require(balance0Adjusted.mul(balance1Adjusted) >= uint(_reserve0).mul(_reserve1).mul(1000**2), 'UniswapV2: K');
}
_update(balance0, balance1, _reserve0, _reserve1);
emit Swap(msg.sender, amount0In, amount1In, amount0Out, amount1Out, to);
}
// force balances to match reserves
function skim(address to) external lock {
address _token0 = token0; // gas savings
address _token1 = token1; // gas savings
_safeTransfer(_token0, to, IERC20(_token0).balanceOf(address(this)).sub(reserve0));
_safeTransfer(_token1, to, IERC20(_token1).balanceOf(address(this)).sub(reserve1));
}
// force reserves to match balances
function sync() external lock {
_update(IERC20(token0).balanceOf(address(this)), IERC20(token1).balanceOf(address(this)), reserve0, reserve1);
}
}
|
[{"inputs":[],"payable":false,"stateMutability":"nonpayable","type":"constructor"},{"anonymous":false,"inputs":[{"indexed":true,"internalType":"address","name":"owner","type":"address"},{"indexed":true,"internalType":"address","name":"spender","type":"address"},{"indexed":false,"internalType":"uint256","name":"value","type":"uint256"}],"name":"Approval","type":"event"},{"anonymous":false,"inputs":[{"indexed":true,"internalType":"address","name":"sender","type":"address"},{"indexed":false,"internalType":"uint256","name":"amount0","type":"uint256"},{"indexed":false,"internalType":"uint256","name":"amount1","type":"uint256"},{"indexed":true,"internalType":"address","name":"to","type":"address"}],"name":"Burn","type":"event"},{"anonymous":false,"inputs":[{"indexed":true,"internalType":"address","name":"sender","type":"address"},{"indexed":false,"internalType":"uint256","name":"amount0","type":"uint256"},{"indexed":false,"internalType":"uint256","name":"amount1","type":"uint256"}],"name":"Mint","type":"event"},{"anonymous":false,"inputs":[{"indexed":true,"internalType":"address","name":"sender","type":"address"},{"indexed":false,"internalType":"uint256","name":"amount0In","type":"uint256"},{"indexed":false,"internalType":"uint256","name":"amount1In","type":"uint256"},{"indexed":false,"internalType":"uint256","name":"amount0Out","type":"uint256"},{"indexed":false,"internalType":"uint256","name":"amount1Out","type":"uint256"},{"indexed":true,"internalType":"address","name":"to","type":"address"}],"name":"Swap","type":"event"},{"anonymous":false,"inputs":[{"indexed":false,"internalType":"uint112","name":"reserve0","type":"uint112"},{"indexed":false,"internalType":"uint112","name":"reserve1","type":"uint112"}],"name":"Sync","type":"event"},{"anonymous":false,"inputs":[{"indexed":true,"internalType":"address","name":"from","type":"address"},{"indexed":true,"internalType":"address","name":"to","type":"address"},{"indexed":false,"internalType":"uint256","name":"value","type":"uint256"}],"name":"Transfer","type":"event"},{"constant":true,"inputs":[],"name":"DOMAIN_SEPARATOR","outputs":[{"internalType":"bytes32","name":"","type":"bytes32"}],"payable":false,"stateMutability":"view","type":"function"},{"constant":true,"inputs":[],"name":"MINIMUM_LIQUIDITY","outputs":[{"internalType":"uint256","name":"","type":"uint256"}],"payable":false,"stateMutability":"view","type":"function"},{"constant":true,"inputs":[],"name":"PERMIT_TYPEHASH","outputs":[{"internalType":"bytes32","name":"","type":"bytes32"}],"payable":false,"stateMutability":"view","type":"function"},{"constant":true,"inputs":[{"internalType":"address","name":"","type":"address"},{"internalType":"address","name":"","type":"address"}],"name":"allowance","outputs":[{"internalType":"uint256","name":"","type":"uint256"}],"payable":false,"stateMutability":"view","type":"function"},{"constant":false,"inputs":[{"internalType":"address","name":"spender","type":"address"},{"internalType":"uint256","name":"value","type":"uint256"}],"name":"approve","outputs":[{"internalType":"bool","name":"","type":"bool"}],"payable":false,"stateMutability":"nonpayable","type":"function"},{"constant":true,"inputs":[{"internalType":"address","name":"","type":"address"}],"name":"balanceOf","outputs":[{"internalType":"uint256","name":"","type":"uint256"}],"payable":false,"stateMutability":"view","type":"function"},{"constant":false,"inputs":[{"internalType":"address","name":"to","type":"address"}],"name":"burn","outputs":[{"internalType":"uint256","name":"amount0","type":"uint256"},{"internalType":"uint256","name":"amount1","type":"uint256"}],"payable":false,"stateMutability":"nonpayable","type":"function"},{"constant":true,"inputs":[],"name":"decimals","outputs":[{"internalType":"uint8","name":"","type":"uint8"}],"payable":false,"stateMutability":"view","type":"function"},{"constant":true,"inputs":[],"name":"factory","outputs":[{"internalType":"address","name":"","type":"address"}],"payable":false,"stateMutability":"view","type":"function"},{"constant":true,"inputs":[],"name":"getReserves","outputs":[{"internalType":"uint112","name":"_reserve0","type":"uint112"},{"internalType":"uint112","name":"_reserve1","type":"uint112"},{"internalType":"uint32","name":"_blockTimestampLast","type":"uint32"}],"payable":false,"stateMutability":"view","type":"function"},{"constant":false,"inputs":[{"internalType":"address","name":"_token0","type":"address"},{"internalType":"address","name":"_token1","type":"address"}],"name":"initialize","outputs":[],"payable":false,"stateMutability":"nonpayable","type":"function"},{"constant":true,"inputs":[],"name":"kLast","outputs":[{"internalType":"uint256","name":"","type":"uint256"}],"payable":false,"stateMutability":"view","type":"function"},{"constant":false,"inputs":[{"internalType":"address","name":"to","type":"address"}],"name":"mint","outputs":[{"internalType":"uint256","name":"liquidity","type":"uint256"}],"payable":false,"stateMutability":"nonpayable","type":"function"},{"constant":true,"inputs":[],"name":"name","outputs":[{"internalType":"string","name":"","type":"string"}],"payable":false,"stateMutability":"view","type":"function"},{"constant":true,"inputs":[{"internalType":"address","name":"","type":"address"}],"name":"nonces","outputs":[{"internalType":"uint256","name":"","type":"uint256"}],"payable":false,"stateMutability":"view","type":"function"},{"constant":false,"inputs":[{"internalType":"address","name":"owner","type":"address"},{"internalType":"address","name":"spender","type":"address"},{"internalType":"uint256","name":"value","type":"uint256"},{"internalType":"uint256","name":"deadline","type":"uint256"},{"internalType":"uint8","name":"v","type":"uint8"},{"internalType":"bytes32","name":"r","type":"bytes32"},{"internalType":"bytes32","name":"s","type":"bytes32"}],"name":"permit","outputs":[],"payable":false,"stateMutability":"nonpayable","type":"function"},{"constant":true,"inputs":[],"name":"price0CumulativeLast","outputs":[{"internalType":"uint256","name":"","type":"uint256"}],"payable":false,"stateMutability":"view","type":"function"},{"constant":true,"inputs":[],"name":"price1CumulativeLast","outputs":[{"internalType":"uint256","name":"","type":"uint256"}],"payable":false,"stateMutability":"view","type":"function"},{"constant":false,"inputs":[{"internalType":"address","name":"to","type":"address"}],"name":"skim","outputs":[],"payable":false,"stateMutability":"nonpayable","type":"function"},{"constant":false,"inputs":[{"internalType":"uint256","name":"amount0Out","type":"uint256"},{"internalType":"uint256","name":"amount1Out","type":"uint256"},{"internalType":"address","name":"to","type":"address"},{"internalType":"bytes","name":"data","type":"bytes"}],"name":"swap","outputs":[],"payable":false,"stateMutability":"nonpayable","type":"function"},{"constant":true,"inputs":[],"name":"symbol","outputs":[{"internalType":"string","name":"","type":"string"}],"payable":false,"stateMutability":"view","type":"function"},{"constant":false,"inputs":[],"name":"sync","outputs":[],"payable":false,"stateMutability":"nonpayable","type":"function"},{"constant":true,"inputs":[],"name":"token0","outputs":[{"internalType":"address","name":"","type":"address"}],"payable":false,"stateMutability":"view","type":"function"},{"constant":true,"inputs":[],"name":"token1","outputs":[{"internalType":"address","name":"","type":"address"}],"payable":false,"stateMutability":"view","type":"function"},{"constant":true,"inputs":[],"name":"totalSupply","outputs":[{"internalType":"uint256","name":"","type":"uint256"}],"payable":false,"stateMutability":"view","type":"function"},{"constant":false,"inputs":[{"internalType":"address","name":"to","type":"address"},{"internalType":"uint256","name":"value","type":"uint256"}],"name":"transfer","outputs":[{"internalType":"bool","name":"","type":"bool"}],"payable":false,"stateMutability":"nonpayable","type":"function"},{"constant":false,"inputs":[{"internalType":"address","name":"from","type":"address"},{"internalType":"address","name":"to","type":"address"},{"internalType":"uint256","name":"value","type":"uint256"}],"name":"transferFrom","outputs":[{"internalType":"bool","name":"","type":"bool"}],"payable":false,"stateMutability":"nonpayable","type":"function"}]
|
v0.5.16+commit.9c3226ce
| true
| 999,999
|
Default
|
GNU GPLv3
| false
|
bzzr://7dca18479e58487606bf70c79e44d8dee62353c9ee6d01f9a9d70885b8765f22
|
|||
UserWallet
|
0x266efdc66a0cf35cea305a3728d164b9c10422a5
|
Solidity
|
pragma solidity ^0.4.10;
// Copyright 2017 Bittrex
contract AbstractSweeper {
function sweep(address token, uint amount) returns (bool);
function () { throw; }
Controller controller;
function AbstractSweeper(address _controller) {
controller = Controller(_controller);
}
modifier canSweep() {
if (msg.sender != controller.authorizedCaller() && msg.sender != controller.owner()) throw;
if (controller.halted()) throw;
_;
}
}
contract Token {
function balanceOf(address a) returns (uint) {
(a);
return 0;
}
function transfer(address a, uint val) returns (bool) {
(a);
(val);
return false;
}
}
contract DefaultSweeper is AbstractSweeper {
function DefaultSweeper(address controller)
AbstractSweeper(controller) {}
function sweep(address _token, uint _amount)
canSweep
returns (bool) {
bool success = false;
address destination = controller.destination();
if (_token != address(0)) {
Token token = Token(_token);
uint amount = _amount;
if (amount > token.balanceOf(this)) {
return false;
}
success = token.transfer(destination, amount);
}
else {
uint amountInWei = _amount;
if (amountInWei > this.balance) {
return false;
}
success = destination.send(amountInWei);
}
if (success) {
controller.logSweep(this, destination, _token, _amount);
}
return success;
}
}
contract UserWallet {
AbstractSweeperList sweeperList;
function UserWallet(address _sweeperlist) {
sweeperList = AbstractSweeperList(_sweeperlist);
}
function () public payable { }
function tokenFallback(address _from, uint _value, bytes _data) {
(_from);
(_value);
(_data);
}
function sweep(address _token, uint _amount)
returns (bool) {
(_amount);
return sweeperList.sweeperOf(_token).delegatecall(msg.data);
}
}
contract AbstractSweeperList {
function sweeperOf(address _token) returns (address);
}
contract Controller is AbstractSweeperList {
address public owner;
address public authorizedCaller;
address public destination;
bool public halted;
event LogNewWallet(address receiver);
event LogSweep(address indexed from, address indexed to, address indexed token, uint amount);
modifier onlyOwner() {
if (msg.sender != owner) throw;
_;
}
modifier onlyAuthorizedCaller() {
if (msg.sender != authorizedCaller) throw;
_;
}
modifier onlyAdmins() {
if (msg.sender != authorizedCaller && msg.sender != owner) throw;
_;
}
function Controller()
{
owner = msg.sender;
destination = msg.sender;
authorizedCaller = msg.sender;
}
function changeAuthorizedCaller(address _newCaller) onlyOwner {
authorizedCaller = _newCaller;
}
function changeDestination(address _dest) onlyOwner {
destination = _dest;
}
function changeOwner(address _owner) onlyOwner {
owner = _owner;
}
function makeWallet() onlyAdmins returns (address wallet) {
wallet = address(new UserWallet(this));
LogNewWallet(wallet);
}
function halt() onlyAdmins {
halted = true;
}
function start() onlyOwner {
halted = false;
}
address public defaultSweeper = address(new DefaultSweeper(this));
mapping (address => address) sweepers;
function addSweeper(address _token, address _sweeper) onlyOwner {
sweepers[_token] = _sweeper;
}
function sweeperOf(address _token) returns (address) {
address sweeper = sweepers[_token];
if (sweeper == 0) sweeper = defaultSweeper;
return sweeper;
}
function logSweep(address from, address to, address token, uint amount) {
LogSweep(from, to, token, amount);
}
}
|
[{"constant":false,"inputs":[{"name":"_token","type":"address"},{"name":"_amount","type":"uint256"}],"name":"sweep","outputs":[{"name":"","type":"bool"}],"payable":false,"type":"function"},{"constant":false,"inputs":[{"name":"_from","type":"address"},{"name":"_value","type":"uint256"},{"name":"_data","type":"bytes"}],"name":"tokenFallback","outputs":[],"payable":false,"type":"function"},{"inputs":[{"name":"_sweeperlist","type":"address"}],"payable":false,"type":"constructor"},{"payable":true,"type":"fallback"}]
|
v0.4.11+commit.68ef5810
| true
| 200
|
000000000000000000000000a3C1E324CA1ce40db73eD6026c4A177F099B5770
|
Default
| false
|
bzzr://4cdd69fdcf3cf6cbee9677fe380fa5f044048aa9e060ec5619a21ca5a5bd4cd1
|
|||
Forwarder
|
0x52386b33ed121269d2dd633e7cdf1d05f651f185
|
Solidity
|
pragma solidity 0.7.5;
/*
The MIT License (MIT)
Copyright (c) 2018 Murray Software, LLC.
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.
*/
//solhint-disable max-line-length
//solhint-disable no-inline-assembly
contract CloneFactory {
function createClone(address target, bytes32 salt)
internal
returns (address payable result)
{
bytes20 targetBytes = bytes20(target);
assembly {
// load the next free memory slot as a place to store the clone contract data
let clone := mload(0x40)
// The bytecode block below is responsible for contract initialization
// during deployment, it is worth noting the proxied contract constructor will not be called during
// the cloning procedure and that is why an initialization function needs to be called after the
// clone is created
mstore(
clone,
0x3d602d80600a3d3981f3363d3d373d3d3d363d73000000000000000000000000
)
// This stores the address location of the implementation contract
// so that the proxy knows where to delegate call logic to
mstore(add(clone, 0x14), targetBytes)
// The bytecode block is the actual code that is deployed for each clone created.
// It forwards all calls to the already deployed implementation via a delegatecall
mstore(
add(clone, 0x28),
0x5af43d82803e903d91602b57fd5bf30000000000000000000000000000000000
)
// deploy the contract using the CREATE2 opcode
// this deploys the minimal proxy defined above, which will proxy all
// calls to use the logic defined in the implementation contract `target`
result := create2(0, clone, 0x37, salt)
}
}
function isClone(address target, address query)
internal
view
returns (bool result)
{
bytes20 targetBytes = bytes20(target);
assembly {
// load the next free memory slot as a place to store the comparison clone
let clone := mload(0x40)
// The next three lines store the expected bytecode for a miniml proxy
// that targets `target` as its implementation contract
mstore(
clone,
0x363d3d373d3d3d363d7300000000000000000000000000000000000000000000
)
mstore(add(clone, 0xa), targetBytes)
mstore(
add(clone, 0x1e),
0x5af43d82803e903d91602b57fd5bf30000000000000000000000000000000000
)
// the next two lines store the bytecode of the contract that we are checking in memory
let other := add(clone, 0x40)
extcodecopy(query, other, 0, 0x2d)
// Check if the expected bytecode equals the actual bytecode and return the result
result := and(
eq(mload(clone), mload(other)),
eq(mload(add(clone, 0xd)), mload(add(other, 0xd)))
)
}
}
}
/**
* Contract that exposes the needed erc20 token functions
*/
abstract contract ERC20Interface {
// Send _value amount of tokens to address _to
function transfer(address _to, uint256 _value)
public
virtual
returns (bool success);
// Get the account balance of another account with address _owner
function balanceOf(address _owner)
public
virtual
view
returns (uint256 balance);
}
// helper methods for interacting with ERC20 tokens and sending ETH that do not consistently return true/false
library TransferHelper {
function safeApprove(
address token,
address to,
uint256 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::safeApprove: approve failed'
);
}
function safeTransfer(
address token,
address to,
uint256 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::safeTransfer: transfer failed'
);
}
function safeTransferFrom(
address token,
address from,
address to,
uint256 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::transferFrom: transferFrom failed'
);
}
function safeTransferETH(address to, uint256 value) internal {
(bool success, ) = to.call{value: value}(new bytes(0));
require(success, 'TransferHelper::safeTransferETH: ETH transfer failed');
}
}
/**
* Contract that will forward any incoming Ether to the creator of the contract
*
*/
contract Forwarder {
// Address to which any funds sent to this contract will be forwarded
address public parentAddress;
event ForwarderDeposited(address from, uint256 value, bytes data);
/**
* Initialize the contract, and sets the destination address to that of the creator
*/
function init(address _parentAddress) external onlyUninitialized {
parentAddress = _parentAddress;
uint256 value = address(this).balance;
if (value == 0) {
return;
}
(bool success, ) = parentAddress.call{ value: value }('');
require(success, 'Flush failed');
// NOTE: since we are forwarding on initialization,
// we don't have the context of the original sender.
// We still emit an event about the forwarding but set
// the sender to the forwarder itself
emit ForwarderDeposited(address(this), value, msg.data);
}
/**
* Modifier that will execute internal code block only if the sender is the parent address
*/
modifier onlyParent {
require(msg.sender == parentAddress, 'Only Parent');
_;
}
/**
* Modifier that will execute internal code block only if the contract has not been initialized yet
*/
modifier onlyUninitialized {
require(parentAddress == address(0x0), 'Already initialized');
_;
}
/**
* Default function; Gets called when data is sent but does not match any other function
*/
fallback() external payable {
flush();
}
/**
* Default function; Gets called when Ether is deposited with no data, and forwards it to the parent address
*/
receive() external payable {
flush();
}
/**
* Execute a token transfer of the full balance from the forwarder token to the parent address
* @param tokenContractAddress the address of the erc20 token contract
*/
function flushTokens(address tokenContractAddress) external onlyParent {
ERC20Interface instance = ERC20Interface(tokenContractAddress);
address forwarderAddress = address(this);
uint256 forwarderBalance = instance.balanceOf(forwarderAddress);
if (forwarderBalance == 0) {
return;
}
TransferHelper.safeTransfer(
tokenContractAddress,
parentAddress,
forwarderBalance
);
}
/**
* Flush the entire balance of the contract to the parent address.
*/
function flush() public {
uint256 value = address(this).balance;
if (value == 0) {
return;
}
(bool success, ) = parentAddress.call{ value: value }('');
require(success, 'Flush failed');
emit ForwarderDeposited(msg.sender, value, msg.data);
}
}
contract ForwarderFactory is CloneFactory {
address public implementationAddress;
event ForwarderCreated(address newForwarderAddress, address parentAddress);
constructor(address _implementationAddress) {
implementationAddress = _implementationAddress;
}
function createForwarder(address parent, bytes32 salt) external {
// include the signers in the salt so any contract deployed to a given address must have the same signers
bytes32 finalSalt = keccak256(abi.encodePacked(parent, salt));
address payable clone = createClone(implementationAddress, finalSalt);
Forwarder(clone).init(parent);
emit ForwarderCreated(clone, parent);
}
}
|
[{"anonymous":false,"inputs":[{"indexed":false,"internalType":"address","name":"from","type":"address"},{"indexed":false,"internalType":"uint256","name":"value","type":"uint256"},{"indexed":false,"internalType":"bytes","name":"data","type":"bytes"}],"name":"ForwarderDeposited","type":"event"},{"stateMutability":"payable","type":"fallback"},{"inputs":[],"name":"flush","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"address","name":"tokenContractAddress","type":"address"}],"name":"flushTokens","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"address","name":"_parentAddress","type":"address"}],"name":"init","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[],"name":"parentAddress","outputs":[{"internalType":"address","name":"","type":"address"}],"stateMutability":"view","type":"function"},{"stateMutability":"payable","type":"receive"}]
|
v0.7.5+commit.eb77ed08
| false
| 200
|
Default
|
Apache-2.0
| false
|
ipfs://934a7b5f246917d20f5e049b9344e4f3d923110c9d150ea2a4118848dd414bc3
|
|||
Forwarder
|
0x2e95c44db2f53e5ebb2370936a3d1dcb9528cf37
|
Solidity
|
pragma solidity ^0.4.14;
/**
* Contract that exposes the needed erc20 token functions
*/
contract ERC20Interface {
// Send _value amount of tokens to address _to
function transfer(address _to, uint256 _value) returns (bool success);
// Get the account balance of another account with address _owner
function balanceOf(address _owner) constant returns (uint256 balance);
}
/**
* Contract that will forward any incoming Ether to its creator
*/
contract Forwarder {
// Address to which any funds sent to this contract will be forwarded
address public parentAddress;
event ForwarderDeposited(address from, uint value, bytes data);
event TokensFlushed(
address tokenContractAddress, // The contract address of the token
uint value // Amount of token sent
);
/**
* Create the contract, and set the destination address to that of the creator
*/
function Forwarder() {
parentAddress = msg.sender;
}
/**
* Modifier that will execute internal code block only if the sender is a parent of the forwarder contract
*/
modifier onlyParent {
if (msg.sender != parentAddress) {
throw;
}
_;
}
/**
* Default function; Gets called when Ether is deposited, and forwards it to the destination address
*/
function() payable {
if (!parentAddress.call.value(msg.value)(msg.data))
throw;
// Fire off the deposited event if we can forward it
ForwarderDeposited(msg.sender, msg.value, msg.data);
}
/**
* Execute a token transfer of the full balance from the forwarder token to the main wallet contract
* @param tokenContractAddress the address of the erc20 token contract
*/
function flushTokens(address tokenContractAddress) onlyParent {
ERC20Interface instance = ERC20Interface(tokenContractAddress);
var forwarderAddress = address(this);
var forwarderBalance = instance.balanceOf(forwarderAddress);
if (forwarderBalance == 0) {
return;
}
if (!instance.transfer(parentAddress, forwarderBalance)) {
throw;
}
TokensFlushed(tokenContractAddress, forwarderBalance);
}
/**
* It is possible that funds were sent to this address before the contract was deployed.
* We can flush those funds to the destination address.
*/
function flush() {
if (!parentAddress.call.value(this.balance)())
throw;
}
}
/**
* Basic multi-signer wallet designed for use in a co-signing environment where 2 signatures are required to move funds.
* Typically used in a 2-of-3 signing configuration. Uses ecrecover to allow for 2 signatures in a single transaction.
*/
contract WalletSimple {
// Events
event Deposited(address from, uint value, bytes data);
event SafeModeActivated(address msgSender);
event Transacted(
address msgSender, // Address of the sender of the message initiating the transaction
address otherSigner, // Address of the signer (second signature) used to initiate the transaction
bytes32 operation, // Operation hash (sha3 of toAddress, value, data, expireTime, sequenceId)
address toAddress, // The address the transaction was sent to
uint value, // Amount of Wei sent to the address
bytes data // Data sent when invoking the transaction
);
event TokenTransacted(
address msgSender, // Address of the sender of the message initiating the transaction
address otherSigner, // Address of the signer (second signature) used to initiate the transaction
bytes32 operation, // Operation hash (sha3 of toAddress, value, tokenContractAddress, expireTime, sequenceId)
address toAddress, // The address the transaction was sent to
uint value, // Amount of token sent
address tokenContractAddress // The contract address of the token
);
// Public fields
address[] public signers; // The addresses that can co-sign transactions on the wallet
bool public safeMode = false; // When active, wallet may only send to signer addresses
// Internal fields
uint constant SEQUENCE_ID_WINDOW_SIZE = 10;
uint[10] recentSequenceIds;
/**
* Modifier that will execute internal code block only if the sender is an authorized signer on this wallet
*/
modifier onlysigner {
if (!isSigner(msg.sender)) {
throw;
}
_;
}
/**
* Set up a simple multi-sig wallet by specifying the signers allowed to be used on this wallet.
* 2 signers will be required to send a transaction from this wallet.
* Note: The sender is NOT automatically added to the list of signers.
* Signers CANNOT be changed once they are set
*
* @param allowedSigners An array of signers on the wallet
*/
function WalletSimple(address[] allowedSigners) {
if (allowedSigners.length != 3) {
// Invalid number of signers
throw;
}
signers = allowedSigners;
}
/**
* Gets called when a transaction is received without calling a method
*/
function() payable {
if (msg.value > 0) {
// Fire deposited event if we are receiving funds
Deposited(msg.sender, msg.value, msg.data);
}
}
/**
* Create a new contract (and also address) that forwards funds to this contract
* returns address of newly created forwarder address
*/
function createForwarder() onlysigner returns (address) {
return new Forwarder();
}
/**
* Execute a multi-signature transaction from this wallet using 2 signers: one from msg.sender and the other from ecrecover.
* The signature is a signed form (using eth.sign) of tightly packed toAddress, value, data, expireTime and sequenceId
* Sequence IDs are numbers starting from 1. They are used to prevent replay attacks and may not be repeated.
*
* @param toAddress the destination address to send an outgoing transaction
* @param value the amount in Wei to be sent
* @param data the data to send to the toAddress when invoking the transaction
* @param expireTime the number of seconds since 1970 for which this transaction is valid
* @param sequenceId the unique sequence id obtainable from getNextSequenceId
* @param signature the result of eth.sign on the operationHash sha3(toAddress, value, data, expireTime, sequenceId)
*/
function sendMultiSig(address toAddress, uint value, bytes data, uint expireTime, uint sequenceId, bytes signature) onlysigner {
// Verify the other signer
var operationHash = sha3("ETHER", toAddress, value, data, expireTime, sequenceId);
var otherSigner = verifyMultiSig(toAddress, operationHash, signature, expireTime, sequenceId);
// Success, send the transaction
if (!(toAddress.call.value(value)(data))) {
// Failed executing transaction
throw;
}
Transacted(msg.sender, otherSigner, operationHash, toAddress, value, data);
}
/**
* Execute a multi-signature token transfer from this wallet using 2 signers: one from msg.sender and the other from ecrecover.
* The signature is a signed form (using eth.sign) of tightly packed toAddress, value, tokenContractAddress, expireTime and sequenceId
* Sequence IDs are numbers starting from 1. They are used to prevent replay attacks and may not be repeated.
*
* @param toAddress the destination address to send an outgoing transaction
* @param value the amount in tokens to be sent
* @param tokenContractAddress the address of the erc20 token contract
* @param expireTime the number of seconds since 1970 for which this transaction is valid
* @param sequenceId the unique sequence id obtainable from getNextSequenceId
* @param signature the result of eth.sign on the operationHash sha3(toAddress, value, tokenContractAddress, expireTime, sequenceId)
*/
function sendMultiSigToken(address toAddress, uint value, address tokenContractAddress, uint expireTime, uint sequenceId, bytes signature) onlysigner {
// Verify the other signer
var operationHash = sha3("ERC20", toAddress, value, tokenContractAddress, expireTime, sequenceId);
var otherSigner = verifyMultiSig(toAddress, operationHash, signature, expireTime, sequenceId);
ERC20Interface instance = ERC20Interface(tokenContractAddress);
if (!instance.transfer(toAddress, value)) {
throw;
}
TokenTransacted(msg.sender, otherSigner, operationHash, toAddress, value, tokenContractAddress);
}
/**
* Execute a token flush from one of the forwarder addresses. This transfer needs only a single signature and can be done by any signer
*
* @param forwarderAddress the address of the forwarder address to flush the tokens from
* @param tokenContractAddress the address of the erc20 token contract
*/
function flushForwarderTokens(address forwarderAddress, address tokenContractAddress) onlysigner {
Forwarder forwarder = Forwarder(forwarderAddress);
forwarder.flushTokens(tokenContractAddress);
}
/**
* Do common multisig verification for both eth sends and erc20token transfers
*
* @param toAddress the destination address to send an outgoing transaction
* @param operationHash the sha3 of the toAddress, value, data/tokenContractAddress and expireTime
* @param signature the tightly packed signature of r, s, and v as an array of 65 bytes (returned by eth.sign)
* @param expireTime the number of seconds since 1970 for which this transaction is valid
* @param sequenceId the unique sequence id obtainable from getNextSequenceId
* returns address of the address to send tokens or eth to
*/
function verifyMultiSig(address toAddress, bytes32 operationHash, bytes signature, uint expireTime, uint sequenceId) private returns (address) {
var otherSigner = recoverAddressFromSignature(operationHash, signature);
// Verify if we are in safe mode. In safe mode, the wallet can only send to signers
if (safeMode && !isSigner(toAddress)) {
// We are in safe mode and the toAddress is not a signer. Disallow!
throw;
}
// Verify that the transaction has not expired
if (expireTime < block.timestamp) {
// Transaction expired
throw;
}
// Try to insert the sequence ID. Will throw if the sequence id was invalid
tryInsertSequenceId(sequenceId);
if (!isSigner(otherSigner)) {
// Other signer not on this wallet or operation does not match arguments
throw;
}
if (otherSigner == msg.sender) {
// Cannot approve own transaction
throw;
}
return otherSigner;
}
/**
* Irrevocably puts contract into safe mode. When in this mode, transactions may only be sent to signing addresses.
*/
function activateSafeMode() onlysigner {
safeMode = true;
SafeModeActivated(msg.sender);
}
/**
* Determine if an address is a signer on this wallet
* @param signer address to check
* returns boolean indicating whether address is signer or not
*/
function isSigner(address signer) returns (bool) {
// Iterate through all signers on the wallet and
for (uint i = 0; i < signers.length; i++) {
if (signers[i] == signer) {
return true;
}
}
return false;
}
/**
* Gets the second signer's address using ecrecover
* @param operationHash the sha3 of the toAddress, value, data/tokenContractAddress and expireTime
* @param signature the tightly packed signature of r, s, and v as an array of 65 bytes (returned by eth.sign)
* returns address recovered from the signature
*/
function recoverAddressFromSignature(bytes32 operationHash, bytes signature) private returns (address) {
if (signature.length != 65) {
throw;
}
// We need to unpack the signature, which is given as an array of 65 bytes (from eth.sign)
bytes32 r;
bytes32 s;
uint8 v;
assembly {
r := mload(add(signature, 32))
s := mload(add(signature, 64))
v := and(mload(add(signature, 65)), 255)
}
if (v < 27) {
v += 27; // Ethereum versions are 27 or 28 as opposed to 0 or 1 which is submitted by some signing libs
}
return ecrecover(operationHash, v, r, s);
}
/**
* Verify that the sequence id has not been used before and inserts it. Throws if the sequence ID was not accepted.
* We collect a window of up to 10 recent sequence ids, and allow any sequence id that is not in the window and
* greater than the minimum element in the window.
* @param sequenceId to insert into array of stored ids
*/
function tryInsertSequenceId(uint sequenceId) onlysigner private {
// Keep a pointer to the lowest value element in the window
uint lowestValueIndex = 0;
for (uint i = 0; i < SEQUENCE_ID_WINDOW_SIZE; i++) {
if (recentSequenceIds[i] == sequenceId) {
// This sequence ID has been used before. Disallow!
throw;
}
if (recentSequenceIds[i] < recentSequenceIds[lowestValueIndex]) {
lowestValueIndex = i;
}
}
if (sequenceId < recentSequenceIds[lowestValueIndex]) {
// The sequence ID being used is lower than the lowest value in the window
// so we cannot accept it as it may have been used before
throw;
}
if (sequenceId > (recentSequenceIds[lowestValueIndex] + 10000)) {
// Block sequence IDs which are much higher than the lowest value
// This prevents people blocking the contract by using very large sequence IDs quickly
throw;
}
recentSequenceIds[lowestValueIndex] = sequenceId;
}
/**
* Gets the next available sequence ID for signing when using executeAndConfirm
* returns the sequenceId one higher than the highest currently stored
*/
function getNextSequenceId() returns (uint) {
uint highestSequenceId = 0;
for (uint i = 0; i < SEQUENCE_ID_WINDOW_SIZE; i++) {
if (recentSequenceIds[i] > highestSequenceId) {
highestSequenceId = recentSequenceIds[i];
}
}
return highestSequenceId + 1;
}
}
|
[{"constant":true,"inputs":[],"name":"parentAddress","outputs":[{"name":"","type":"address"}],"payable":false,"type":"function"},{"constant":false,"inputs":[{"name":"tokenContractAddress","type":"address"}],"name":"flushTokens","outputs":[],"payable":false,"type":"function"},{"constant":false,"inputs":[],"name":"flush","outputs":[],"payable":false,"type":"function"},{"inputs":[],"payable":false,"type":"constructor"},{"payable":true,"type":"fallback"},{"anonymous":false,"inputs":[{"indexed":false,"name":"from","type":"address"},{"indexed":false,"name":"value","type":"uint256"},{"indexed":false,"name":"data","type":"bytes"}],"name":"ForwarderDeposited","type":"event"},{"anonymous":false,"inputs":[{"indexed":false,"name":"tokenContractAddress","type":"address"},{"indexed":false,"name":"value","type":"uint256"}],"name":"TokensFlushed","type":"event"}]
|
v0.4.16-nightly.2017.8.11+commit.c84de7fa
| true
| 200
|
Default
| false
|
bzzr://d0f8838ba17108a895d34ae8ef3bff4e0dc9d639c3c51921fee1d17eaa803721
|
Subsets and Splits
Count Solidity 0.8 Contracts
Counts the total number of Solidity smart contracts using Solidity version 0.8.x, providing insight into the adoption of a specific language version.
Distinct Solidity Contracts
Retrieves unique contract names and their source code starting with 'pragma solidity', providing a basic overview of smart contract sources.
Solidity Contracts Source Code
Retrieves unique contract names and their source code that start with 'pragma solidity', providing a basic overview of smart contract sources.
Solidity Contracts Source Code
Retrieves unique contract names and their source code that start with 'pragma solidity', providing a basic overview of smart contract sources.
Solidity Contracts Source Code
Retrieves the names and source code of contracts that use Solidity, providing a basic overview of a subset of contracts in the dataset.
Solidity Contracts Source Code
Retrieves the names and source code of smart contracts that use Solidity, providing a basic overview of a subset of the dataset.